text
stringlengths
12
867k
using System; using System.Activities; using System.Activities.Core.Presentation; using System.Activities.Presentation; using System.Activities.Presentation.Toolbox; using System.Activities.Presentation.View; using System.Activities.Statements; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace HostingApplication { /// <summary> /// Interaction logic for TestCaseDesigner.xaml /// </summary> public partial class TestCaseDesigner1 : UserControl { private WorkflowDesigner wd; public TestCaseDesigner1() { InitializeComponent(); RegisterMetadata(); // Add the WFF Designer AddDesigner(); AddToolBox(); this.AddPropertyInspector(); } private void RegisterMetadata() { DesignerMetadata dm = new DesignerMetadata(); dm.Register(); } private void AddDesigner() { //Create an instance of WorkflowDesigner class. this.wd = new WorkflowDesigner(); //Place the designer canvas in the middle column of the grid. Grid.SetColumn(this.wd.View, 1); ActivityBuilder activityBuilderType = new ActivityBuilder(); activityBuilderType.Name = "Activity Builder"; activityBuilderType.Implementation = new Sequence() { DisplayName = "Default Template", Activities = { new WriteLine() { Text = "Workflow Rehosted Designer" } } }; //Load a new Sequence as default. this.wd.Load(activityBuilderType); //Add the designer canvas to the grid. grid1.Children.Add(this.wd.View); this.wd.Context.Services.GetService<DesignerView>().WorkflowShellBarItemVisibility = ShellBarItemVisibility.All; } private ToolboxControl GetToolboxControl() { // Create the ToolBoxControl. ToolboxControl ctrl = new ToolboxControl(); // Create a category. ToolboxCategory category = new ToolboxCategory("category1"); // Create Toolbox items. ToolboxItemWrapper tool1 = new ToolboxItemWrapper("System.Activities.Statements.Assign", typeof(Assign).Assembly.FullName, null, "Assign"); ToolboxItemWrapper tool2 = new ToolboxItemWrapper("System.Activities.Statements.Sequence", typeof(Sequence).Assembly.FullName, null, "Sequence"); ToolboxItemWrapper tool3 = new ToolboxItemWrapper("System.Activities.Statements.WriteLine", typeof(Sequence).Assembly.FullName, null, "WriteLine"); //ToolboxItemWrapper tool4 = new ToolboxItemWrapper("ActivityLibrary.CodeActivity1", // typeof(ActivityLibrary.CodeActivity1).Assembly.FullName, null, "CodeActivit1"); ToolboxItemWrapper tool5 = new ToolboxItemWrapper("ActivityLibrary.Activity1", typeof(ActivityLibrary.Activity1).Assembly.FullName, null, "Activity1"); // Add the Toolbox items to the category. category.Add(tool1); category.Add(tool2); category.Add(tool3); //category.Add(tool4); category.Add(tool5); // Add the category to the ToolBox control. ctrl.Categories.Add(category); return ctrl; } private void AddToolBox() { ToolboxControl tc = GetToolboxControl(); Grid.SetColumn(tc, 0); grid1.Children.Add(tc); } private void AddPropertyInspector() { Grid.SetColumn(wd.PropertyInspectorView, 2); grid1.Children.Add(wd.PropertyInspectorView); } } }
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the source repository root for complete license information. */ using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Controls; namespace ExcelServiceExplorer.Views { public sealed partial class AddChart : Page { public AddChart() { InitializeComponent(); NavigationCacheMode = NavigationCacheMode.Disabled; } } }
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice; namespace NetOffice.VisioApi { #region Delegates #pragma warning disable #pragma warning restore #endregion ///<summary> /// CoClass Comment /// SupportByVersion Visio, 15, 16 ///</summary> [SupportByVersionAttribute("Visio", 15, 16)] [EntityTypeAttribute(EntityType.IsCoClass)] public class Comment : IVComment { #pragma warning disable #region Fields private NetRuntimeSystem.Runtime.InteropServices.ComTypes.IConnectionPoint _connectPoint; private string _activeSinkId; private NetRuntimeSystem.Type _thisType; #endregion #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Comment); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Comment(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Comment(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Comment(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Comment(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Comment(COMObject replacedObject) : base(replacedObject) { } ///<summary> /// Creates a new instance of Comment ///</summary> public Comment():base("Visio.Comment") { } ///<summary> /// Creates a new instance of Comment ///</summary> ///<param name="progId">registered ProgID</param> public Comment(string progId):base(progId) { } #endregion #region Static CoClass Methods /// <summary> /// Returns all running Visio.Comment objects from the environment/system /// </summary> /// <returns>an Visio.Comment array</returns> public static NetOffice.VisioApi.Comment[] GetActiveInstances() { IDisposableEnumeration proxyList = NetOffice.ProxyService.GetActiveInstances("Visio","Comment"); NetRuntimeSystem.Collections.Generic.List<NetOffice.VisioApi.Comment> resultList = new NetRuntimeSystem.Collections.Generic.List<NetOffice.VisioApi.Comment>(); foreach(object proxy in proxyList) resultList.Add( new NetOffice.VisioApi.Comment(null, proxy) ); return resultList.ToArray(); } /// <summary> /// Returns a running Visio.Comment object from the environment/system. /// </summary> /// <returns>an Visio.Comment object or null</returns> public static NetOffice.VisioApi.Comment GetActiveInstance() { object proxy = NetOffice.ProxyService.GetActiveInstance("Visio","Comment", false); if(null != proxy) return new NetOffice.VisioApi.Comment(null, proxy); else return null; } /// <summary> /// Returns a running Visio.Comment object from the environment/system. /// </summary> /// <param name="throwOnError">throw an exception if no object was found</param> /// <returns>an Visio.Comment object or null</returns> public static NetOffice.VisioApi.Comment GetActiveInstance(bool throwOnError) { object proxy = NetOffice.ProxyService.GetActiveInstance("Visio","Comment", throwOnError); if(null != proxy) return new NetOffice.VisioApi.Comment(null, proxy); else return null; } #endregion #region Events #endregion #region IEventBinding Member /// <summary> /// Creates active sink helper /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public void CreateEventBridge() { if(false == Factory.Settings.EnableEvents) return; if (null != _connectPoint) return; if (null == _activeSinkId) _activeSinkId = SinkHelper.GetConnectionPoint(this, ref _connectPoint, null); } /// <summary> /// The instance use currently an event listener /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool EventBridgeInitialized { get { return (null != _connectPoint); } } /// <summary> /// The instance has currently one or more event recipients /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool HasEventRecipients() { if(null == _thisType) _thisType = this.GetType(); foreach (NetRuntimeSystem.Reflection.EventInfo item in _thisType.GetEvents()) { MulticastDelegate eventDelegate = (MulticastDelegate) _thisType.GetType().GetField(item.Name, NetRuntimeSystem.Reflection.BindingFlags.NonPublic | NetRuntimeSystem.Reflection.BindingFlags.Instance).GetValue(this); if( (null != eventDelegate) && (eventDelegate.GetInvocationList().Length > 0) ) return false; } return false; } /// <summary> /// Target methods from its actual event recipients /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Delegate[] GetEventRecipients(string eventName) { if(null == _thisType) _thisType = this.GetType(); MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField( "_" + eventName + "Event", NetRuntimeSystem.Reflection.BindingFlags.Instance | NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this); if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); return delegates; } else return new Delegate[0]; } /// <summary> /// Returns the current count of event recipients /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public int GetCountOfEventRecipients(string eventName) { if(null == _thisType) _thisType = this.GetType(); MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField( "_" + eventName + "Event", NetRuntimeSystem.Reflection.BindingFlags.Instance | NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this); if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); return delegates.Length; } else return 0; } /// <summary> /// Raise an instance event /// </summary> /// <param name="eventName">name of the event without 'Event' at the end</param> /// <param name="paramsArray">custom arguments for the event</param> /// <returns>count of called event recipients</returns> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public int RaiseCustomEvent(string eventName, ref object[] paramsArray) { if(null == _thisType) _thisType = this.GetType(); MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField( "_" + eventName + "Event", NetRuntimeSystem.Reflection.BindingFlags.Instance | NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this); if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); foreach (var item in delegates) { try { item.Method.Invoke(item.Target, paramsArray); } catch (NetRuntimeSystem.Exception exception) { Factory.Console.WriteException(exception); } } return delegates.Length; } else return 0; } /// <summary> /// Stop listening events for the instance /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public void DisposeEventBridge() { _connectPoint = null; } #endregion #pragma warning restore } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Models.NorthwindIB.EDMX_2012 { using System; using System.Collections.Generic; public partial class TimeGroup { public TimeGroup() { this.TimeLimits = new HashSet<TimeLimit>(); } public int Id { get; set; } public string Comment { get; set; } public virtual ICollection<TimeLimit> TimeLimits { get; set; } } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; using UltimaOnline; using UltimaOnline.Mobiles; using UltimaOnline.Network; using UltimaOnline.Targeting; using UltimaOnline.ContextMenus; namespace UltimaOnline.Items { public class TreasureMap : MapItem { private int m_Level; private bool m_Completed; private Mobile m_CompletedBy; private Mobile m_Decoder; private Map m_Map; private Point2D m_Location; [CommandProperty(AccessLevel.GameMaster)] public int Level { get { return m_Level; } set { m_Level = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public bool Completed { get { return m_Completed; } set { m_Completed = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public Mobile CompletedBy { get { return m_CompletedBy; } set { m_CompletedBy = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public Mobile Decoder { get { return m_Decoder; } set { m_Decoder = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public Map ChestMap { get { return m_Map; } set { m_Map = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public Point2D ChestLocation { get { return m_Location; } set { m_Location = value; } } private static Point2D[] m_Locations; private static Point2D[] m_HavenLocations; private static Type[][] m_SpawnTypes = new Type[][] { new Type[]{ typeof( HeadlessOne ), typeof( Skeleton ) }, new Type[]{ typeof( Mongbat ), typeof( Ratman ), typeof( HeadlessOne ), typeof( Skeleton ), typeof( Zombie ) }, new Type[]{ typeof( OrcishMage ), typeof( Gargoyle ), typeof( Gazer ), typeof( HellHound ), typeof( EarthElemental ) }, new Type[]{ typeof( Lich ), typeof( OgreLord ), typeof( DreadSpider ), typeof( AirElemental ), typeof( FireElemental ) }, new Type[]{ typeof( DreadSpider ), typeof( LichLord ), typeof( Daemon ), typeof( ElderGazer ), typeof( OgreLord ) }, new Type[]{ typeof( LichLord ), typeof( Daemon ), typeof( ElderGazer ), typeof( PoisonElemental ), typeof( BloodElemental ) }, new Type[]{ typeof( AncientWyrm ), typeof( Balron ), typeof( BloodElemental ), typeof( PoisonElemental ), typeof( Titan ) } }; public const double LootChance = 0.01; // 1% chance to appear as loot public static Point2D GetRandomLocation() { if (m_Locations == null) LoadLocations(); if (m_Locations.Length > 0) return m_Locations[Utility.Random(m_Locations.Length)]; return Point2D.Zero; } public static Point2D GetRandomHavenLocation() { if (m_HavenLocations == null) LoadLocations(); if (m_HavenLocations.Length > 0) return m_HavenLocations[Utility.Random(m_HavenLocations.Length)]; return Point2D.Zero; } private static void LoadLocations() { string filePath = Path.Combine(Core.BaseDirectory, "Data/treasure.cfg"); List<Point2D> list = new List<Point2D>(); List<Point2D> havenList = new List<Point2D>(); if (File.Exists(filePath)) { using (StreamReader ip = new StreamReader(filePath)) { string line; while ((line = ip.ReadLine()) != null) { try { string[] split = line.Split(' '); int x = Convert.ToInt32(split[0]), y = Convert.ToInt32(split[1]); Point2D loc = new Point2D(x, y); list.Add(loc); if (IsInHavenIsland(loc)) havenList.Add(loc); } catch { } } } } m_Locations = list.ToArray(); m_HavenLocations = havenList.ToArray(); } public static bool IsInHavenIsland(IPoint2D loc) { return (loc.X >= 3314 && loc.X <= 3814 && loc.Y >= 2345 && loc.Y <= 3095); } public static BaseCreature Spawn(int level, Point3D p, bool guardian) { if (level >= 0 && level < m_SpawnTypes.Length) { BaseCreature bc; try { bc = (BaseCreature)Activator.CreateInstance(m_SpawnTypes[level][Utility.Random(m_SpawnTypes[level].Length)]); } catch { return null; } bc.Home = p; bc.RangeHome = 5; if (guardian && level == 0) { bc.Name = "a chest guardian"; bc.Hue = 0x835; } return bc; } return null; } public static BaseCreature Spawn(int level, Point3D p, Map map, Mobile target, bool guardian) { if (map == null) return null; BaseCreature c = Spawn(level, p, guardian); if (c != null) { bool spawned = false; for (int i = 0; !spawned && i < 10; ++i) { int x = p.X - 3 + Utility.Random(7); int y = p.Y - 3 + Utility.Random(7); if (map.CanSpawnMobile(x, y, p.Z)) { c.MoveToWorld(new Point3D(x, y, p.Z), map); spawned = true; } else { int z = map.GetAverageZ(x, y); if (map.CanSpawnMobile(x, y, z)) { c.MoveToWorld(new Point3D(x, y, z), map); spawned = true; } } } if (!spawned) { c.Delete(); return null; } if (target != null) c.Combatant = target; return c; } return null; } [Constructable] public TreasureMap(int level, Map map) { m_Level = level; m_Map = map; if (level == 0) m_Location = GetRandomHavenLocation(); else m_Location = GetRandomLocation(); Width = 300; Height = 300; int width = 600; int height = 600; int x1 = m_Location.X - Utility.RandomMinMax(width / 4, (width / 4) * 3); int y1 = m_Location.Y - Utility.RandomMinMax(height / 4, (height / 4) * 3); if (x1 < 0) x1 = 0; if (y1 < 0) y1 = 0; int x2 = x1 + width; int y2 = y1 + height; if (x2 >= 5120) x2 = 5119; if (y2 >= 4096) y2 = 4095; x1 = x2 - width; y1 = y2 - height; Bounds = new Rectangle2D(x1, y1, width, height); Protected = true; AddWorldPin(m_Location.X, m_Location.Y); } public TreasureMap(Serial serial) : base(serial) { } public static bool HasDiggingTool(Mobile m) { if (m.Backpack == null) return false; List<BaseHarvestTool> items = m.Backpack.FindItemsByType<BaseHarvestTool>(); foreach (BaseHarvestTool tool in items) { if (tool.HarvestSystem == Engines.Harvest.Mining.System) return true; } return false; } public void OnBeginDig(Mobile from) { if (m_Completed) { from.SendLocalizedMessage(503028); // The treasure for this map has already been found. } else if (m_Level == 0 && !CheckYoung(from)) { from.SendLocalizedMessage(1046447); // Only a young player may use this treasure map. } /* else if ( from != m_Decoder ) { from.SendLocalizedMessage( 503016 ); // Only the person who decoded this map may actually dig up the treasure. } */ else if (m_Decoder != from && !HasRequiredSkill(from)) { from.SendLocalizedMessage(503031); // You did not decode this map and have no clue where to look for the treasure. } else if (!from.CanBeginAction(typeof(TreasureMap))) { from.SendLocalizedMessage(503020); // You are already digging treasure. } else if (from.Map != this.m_Map) { from.SendLocalizedMessage(1010479); // You seem to be in the right place, but may be on the wrong facet! } else { from.SendLocalizedMessage(503033); // Where do you wish to dig? from.Target = new DigTarget(this); } } private class DigTarget : Target { private TreasureMap m_Map; public DigTarget(TreasureMap map) : base(6, true, TargetFlags.None) { m_Map = map; } protected override void OnTarget(Mobile from, object targeted) { if (m_Map.Deleted) return; Map map = m_Map.m_Map; if (m_Map.m_Completed) { from.SendLocalizedMessage(503028); // The treasure for this map has already been found. } /* else if ( from != m_Map.m_Decoder ) { from.SendLocalizedMessage( 503016 ); // Only the person who decoded this map may actually dig up the treasure. } */ else if (m_Map.m_Decoder != from && !m_Map.HasRequiredSkill(from)) { from.SendLocalizedMessage(503031); // You did not decode this map and have no clue where to look for the treasure. return; } else if (!from.CanBeginAction(typeof(TreasureMap))) { from.SendLocalizedMessage(503020); // You are already digging treasure. } else if (!HasDiggingTool(from)) { from.SendMessage("You must have a digging tool to dig for treasure."); } else if (from.Map != map) { from.SendLocalizedMessage(1010479); // You seem to be in the right place, but may be on the wrong facet! } else { IPoint3D p = targeted as IPoint3D; Point3D targ3D; if (p is Item) targ3D = ((Item)p).GetWorldLocation(); else targ3D = new Point3D(p); int maxRange; double skillValue = from.Skills[SkillName.Mining].Value; if (skillValue >= 100.0) maxRange = 4; else if (skillValue >= 81.0) maxRange = 3; else if (skillValue >= 51.0) maxRange = 2; else maxRange = 1; Point2D loc = m_Map.m_Location; int x = loc.X, y = loc.Y; Point3D chest3D0 = new Point3D(loc, 0); if (Utility.InRange(targ3D, chest3D0, maxRange)) { if (from.Location.X == x && from.Location.Y == y) { from.SendLocalizedMessage(503030); // The chest can't be dug up because you are standing on top of it. } else if (map != null) { int z = map.GetAverageZ(x, y); if (!map.CanFit(x, y, z, 16, true, true)) { from.SendLocalizedMessage(503021); // You have found the treasure chest but something is keeping it from being dug up. } else if (from.BeginAction(typeof(TreasureMap))) { new DigTimer(from, m_Map, new Point3D(x, y, z), map).Start(); } else { from.SendLocalizedMessage(503020); // You are already digging treasure. } } } else if (m_Map.Level > 0) { if (Utility.InRange(targ3D, chest3D0, 8)) // We're close, but not quite { from.SendLocalizedMessage(503032); // You dig and dig but no treasure seems to be here. } else { from.SendLocalizedMessage(503035); // You dig and dig but fail to find any treasure. } } else { if (Utility.InRange(targ3D, chest3D0, 8)) // We're close, but not quite { from.SendAsciiMessage(0x44, "The treasure chest is very close!"); } else { Direction dir = Utility.GetDirection(targ3D, chest3D0); string sDir; switch (dir) { case Direction.North: sDir = "north"; break; case Direction.Right: sDir = "northeast"; break; case Direction.East: sDir = "east"; break; case Direction.Down: sDir = "southeast"; break; case Direction.South: sDir = "south"; break; case Direction.Left: sDir = "southwest"; break; case Direction.West: sDir = "west"; break; default: sDir = "northwest"; break; } from.SendAsciiMessage(0x44, "Try looking for the treasure chest more to the {0}.", sDir); } } } } } private class DigTimer : Timer { private Mobile m_From; private TreasureMap m_TreasureMap; private Point3D m_Location; private Map m_Map; private TreasureChestDirt m_Dirt1; private TreasureChestDirt m_Dirt2; private TreasureMapChest m_Chest; private int m_Count; private long m_NextSkillTime; private long m_NextSpellTime; private long m_NextActionTime; private long m_LastMoveTime; public DigTimer(Mobile from, TreasureMap treasureMap, Point3D location, Map map) : base(TimeSpan.Zero, TimeSpan.FromSeconds(1.0)) { m_From = from; m_TreasureMap = treasureMap; m_Location = location; m_Map = map; m_NextSkillTime = from.NextSkillTime; m_NextSpellTime = from.NextSpellTime; m_NextActionTime = from.NextActionTime; m_LastMoveTime = from.LastMoveTime; Priority = TimerPriority.TenMS; } private void Terminate() { Stop(); m_From.EndAction(typeof(TreasureMap)); if (m_Chest != null) m_Chest.Delete(); if (m_Dirt1 != null) { m_Dirt1.Delete(); m_Dirt2.Delete(); } } protected override void OnTick() { if (m_NextSkillTime != m_From.NextSkillTime || m_NextSpellTime != m_From.NextSpellTime || m_NextActionTime != m_From.NextActionTime) { Terminate(); return; } if (m_LastMoveTime != m_From.LastMoveTime) { m_From.SendLocalizedMessage(503023); // You cannot move around while digging up treasure. You will need to start digging anew. Terminate(); return; } int z = (m_Chest != null) ? m_Chest.Z + m_Chest.ItemData.Height : int.MinValue; int height = 16; if (z > m_Location.Z) height -= (z - m_Location.Z); else z = m_Location.Z; if (!m_Map.CanFit(m_Location.X, m_Location.Y, z, height, true, true, false)) { m_From.SendLocalizedMessage(503024); // You stop digging because something is directly on top of the treasure chest. Terminate(); return; } m_Count++; m_From.RevealingAction(); m_From.Direction = m_From.GetDirectionTo(m_Location); if (m_Count > 1 && m_Dirt1 == null) { m_Dirt1 = new TreasureChestDirt(); m_Dirt1.MoveToWorld(m_Location, m_Map); m_Dirt2 = new TreasureChestDirt(); m_Dirt2.MoveToWorld(new Point3D(m_Location.X, m_Location.Y - 1, m_Location.Z), m_Map); } if (m_Count == 5) { m_Dirt1.Turn1(); } else if (m_Count == 10) { m_Dirt1.Turn2(); m_Dirt2.Turn2(); } else if (m_Count > 10) { if (m_Chest == null) { m_Chest = new TreasureMapChest(m_From, m_TreasureMap.Level, true); m_Chest.MoveToWorld(new Point3D(m_Location.X, m_Location.Y, m_Location.Z - 15), m_Map); } else { m_Chest.Z++; } Effects.PlaySound(m_Chest, m_Map, 0x33B); } if (m_Chest != null && m_Chest.Location.Z >= m_Location.Z) { Stop(); m_From.EndAction(typeof(TreasureMap)); m_Chest.Temporary = false; m_TreasureMap.Completed = true; m_TreasureMap.CompletedBy = m_From; int spawns; switch (m_TreasureMap.Level) { case 0: spawns = 3; break; case 1: spawns = 0; break; default: spawns = 4; break; } for (int i = 0; i < spawns; ++i) { BaseCreature bc = Spawn(m_TreasureMap.Level, m_Chest.Location, m_Chest.Map, null, true); if (bc != null) m_Chest.Guardians.Add(bc); } } else { if (m_From.Body.IsHuman && !m_From.Mounted) m_From.Animate(11, 5, 1, true, false, 0); new SoundTimer(m_From, 0x125 + (m_Count % 2)).Start(); } } private class SoundTimer : Timer { private Mobile m_From; private int m_SoundID; public SoundTimer(Mobile from, int soundID) : base(TimeSpan.FromSeconds(0.9)) { m_From = from; m_SoundID = soundID; Priority = TimerPriority.TenMS; } protected override void OnTick() { m_From.PlaySound(m_SoundID); } } } public override void OnDoubleClick(Mobile from) { if (!from.InRange(GetWorldLocation(), 2)) { from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1019045); // I can't reach that. return; } if (!m_Completed && m_Decoder == null) Decode(from); else DisplayTo(from); } private bool CheckYoung(Mobile from) { if (from.AccessLevel >= AccessLevel.GameMaster) return true; if (from is PlayerMobile && ((PlayerMobile)from).Young) return true; if (from == this.Decoder) { this.Level = 1; from.SendLocalizedMessage(1046446); // This is now a level one treasure map. return true; } return false; } private double GetMinSkillLevel() { switch (m_Level) { case 1: return -3.0; case 2: return 41.0; case 3: return 51.0; case 4: return 61.0; case 5: return 70.0; case 6: return 70.0; default: return 0.0; } } private bool HasRequiredSkill(Mobile from) { return (from.Skills[SkillName.Cartography].Value >= GetMinSkillLevel()); } public void Decode(Mobile from) { if (m_Completed || m_Decoder != null) return; if (m_Level == 0) { if (!CheckYoung(from)) { from.SendLocalizedMessage(1046447); // Only a young player may use this treasure map. return; } } else { double minSkill = GetMinSkillLevel(); if (from.Skills[SkillName.Cartography].Value < minSkill) from.SendLocalizedMessage(503013); // The map is too difficult to attempt to decode. double maxSkill = minSkill + 60.0; if (!from.CheckSkill(SkillName.Cartography, minSkill, maxSkill)) { from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 503018); // You fail to make anything of the map. return; } } from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 503019); // You successfully decode a treasure map! Decoder = from; if (Core.AOS) LootType = LootType.Blessed; DisplayTo(from); } public override void DisplayTo(Mobile from) { if (m_Completed) { SendLocalizedMessageTo(from, 503014); // This treasure hunt has already been completed. } else if (m_Level == 0 && !CheckYoung(from)) { from.SendLocalizedMessage(1046447); // Only a young player may use this treasure map. return; } else if (m_Decoder != from && !HasRequiredSkill(from)) { from.SendLocalizedMessage(503031); // You did not decode this map and have no clue where to look for the treasure. return; } else { SendLocalizedMessageTo(from, 503017); // The treasure is marked by the red pin. Grab a shovel and go dig it up! } from.PlaySound(0x249); base.DisplayTo(from); } public override void GetContextMenuEntries(Mobile from, List<ContextMenuEntry> list) { base.GetContextMenuEntries(from, list); if (!m_Completed) { if (m_Decoder == null) { list.Add(new DecodeMapEntry(this)); } else { bool digTool = HasDiggingTool(from); list.Add(new OpenMapEntry(this)); list.Add(new DigEntry(this, digTool)); } } } private class DecodeMapEntry : ContextMenuEntry { private TreasureMap m_Map; public DecodeMapEntry(TreasureMap map) : base(6147, 2) { m_Map = map; } public override void OnClick() { if (!m_Map.Deleted) m_Map.Decode(Owner.From); } } private class OpenMapEntry : ContextMenuEntry { private TreasureMap m_Map; public OpenMapEntry(TreasureMap map) : base(6150, 2) { m_Map = map; } public override void OnClick() { if (!m_Map.Deleted) m_Map.DisplayTo(Owner.From); } } private class DigEntry : ContextMenuEntry { private TreasureMap m_Map; public DigEntry(TreasureMap map, bool enabled) : base(6148, 2) { m_Map = map; if (!enabled) this.Flags |= CMEFlags.Disabled; } public override void OnClick() { if (m_Map.Deleted) return; Mobile from = Owner.From; if (HasDiggingTool(from)) m_Map.OnBeginDig(from); else from.SendMessage("You must have a digging tool to dig for treasure."); } } public override int LabelNumber { get { if (m_Decoder != null) { if (m_Level == 6) return 1063453; else return 1041516 + m_Level; } else if (m_Level == 6) return 1063452; else return 1041510 + m_Level; } } public override void GetProperties(ObjectPropertyList list) { base.GetProperties(list); list.Add(m_Map == Map.Felucca ? 1041502 : 1041503); // for somewhere in Felucca : for somewhere in Trammel if (m_Completed) { list.Add(1041507, m_CompletedBy == null ? "someone" : m_CompletedBy.Name); // completed by ~1_val~ } } public override void OnSingleClick(Mobile from) { if (m_Completed) { from.Send(new MessageLocalizedAffix(Serial, ItemID, MessageType.Label, 0x3B2, 3, 1048030, "", AffixType.Append, String.Format(" completed by {0}", m_CompletedBy == null ? "someone" : m_CompletedBy.Name), "")); } else if (m_Decoder != null) { if (m_Level == 6) LabelTo(from, 1063453); else LabelTo(from, 1041516 + m_Level); } else { if (m_Level == 6) LabelTo(from, 1041522, String.Format("#{0}\t \t#{1}", 1063452, m_Map == Map.Felucca ? 1041502 : 1041503)); else LabelTo(from, 1041522, String.Format("#{0}\t \t#{1}", 1041510 + m_Level, m_Map == Map.Felucca ? 1041502 : 1041503)); } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)1); writer.Write((Mobile)m_CompletedBy); writer.Write(m_Level); writer.Write(m_Completed); writer.Write(m_Decoder); writer.Write(m_Map); writer.Write(m_Location); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); switch (version) { case 1: { m_CompletedBy = reader.ReadMobile(); goto case 0; } case 0: { m_Level = (int)reader.ReadInt(); m_Completed = reader.ReadBool(); m_Decoder = reader.ReadMobile(); m_Map = reader.ReadMap(); m_Location = reader.ReadPoint2D(); if (version == 0 && m_Completed) m_CompletedBy = m_Decoder; break; } } if (Core.AOS && m_Decoder != null && LootType == LootType.Regular) LootType = LootType.Blessed; } } public class TreasureChestDirt : Item { public TreasureChestDirt() : base(0x912) { Movable = false; Timer.DelayCall(TimeSpan.FromMinutes(2.0), new TimerCallback(Delete)); } public TreasureChestDirt(Serial serial) : base(serial) { } public void Turn1() { this.ItemID = 0x913; } public void Turn2() { this.ItemID = 0x914; } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); Delete(); } } }
using System; using System.Threading.Tasks; using Vonage.Request; namespace Vonage.Numbers { public class NumbersClient : INumbersClient { public NumbersClient(Credentials creds = null) { Credentials = creds; } public Credentials Credentials { get; set; } public Task<NumbersSearchResponse> GetOwnedNumbersAsync(NumberSearchRequest request, Credentials creds = null) { return ApiRequest.DoGetRequestWithQueryParametersAsync<NumbersSearchResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/account/numbers"), ApiRequest.AuthType.Query, request, creds ?? Credentials ); } public Task<NumbersSearchResponse> GetAvailableNumbersAsync(NumberSearchRequest request, Credentials creds = null) { return ApiRequest.DoGetRequestWithQueryParametersAsync<NumbersSearchResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/search"), ApiRequest.AuthType.Query, request, creds ?? Credentials ); } public async Task<NumberTransactionResponse> BuyANumberAsync(NumberTransactionRequest request, Credentials creds = null) { var response = await ApiRequest.DoPostRequestUrlContentFromObjectAsync<NumberTransactionResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/buy"), request, creds ?? Credentials ); ValidateNumbersResponse(response); return response; } public async Task<NumberTransactionResponse> CancelANumberAsync(NumberTransactionRequest request, Credentials creds = null) { var response = await ApiRequest.DoPostRequestUrlContentFromObjectAsync<NumberTransactionResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/cancel"), request, creds ?? Credentials ); ValidateNumbersResponse(response); return response; } public async Task<NumberTransactionResponse> UpdateANumberAsync(UpdateNumberRequest request, Credentials creds = null) { var response = await ApiRequest.DoPostRequestUrlContentFromObjectAsync<NumberTransactionResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/update"), request, creds ?? Credentials ); ValidateNumbersResponse(response); return response; } public static void ValidateNumbersResponse(NumberTransactionResponse response) { const string SUCCESS = "200"; if (response.ErrorCode != SUCCESS) { throw new VonageNumberResponseException($"Number Transaction failed with error code:{response.ErrorCode} and label {response.ErrorCodeLabel}"){ Response = response}; } } public NumbersSearchResponse GetOwnedNumbers(NumberSearchRequest request, Credentials creds = null) { return ApiRequest.DoGetRequestWithQueryParameters<NumbersSearchResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/account/numbers"), ApiRequest.AuthType.Query, request, creds ?? Credentials ); } public NumbersSearchResponse GetAvailableNumbers(NumberSearchRequest request, Credentials creds = null) { return ApiRequest.DoGetRequestWithQueryParameters<NumbersSearchResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/search"), ApiRequest.AuthType.Query, request, creds ?? Credentials ); } public NumberTransactionResponse BuyANumber(NumberTransactionRequest request, Credentials creds = null) { var response = ApiRequest.DoPostRequestUrlContentFromObject<NumberTransactionResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/buy"), request, creds ?? Credentials ); ValidateNumbersResponse(response); return response; } public NumberTransactionResponse CancelANumber(NumberTransactionRequest request, Credentials creds = null) { var response = ApiRequest.DoPostRequestUrlContentFromObject<NumberTransactionResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/cancel"), request, creds ?? Credentials ); ValidateNumbersResponse(response); return response; } public NumberTransactionResponse UpdateANumber(UpdateNumberRequest request, Credentials creds = null) { var response = ApiRequest.DoPostRequestUrlContentFromObject<NumberTransactionResponse>( ApiRequest.GetBaseUri(ApiRequest.UriType.Rest, "/number/update"), request, creds ?? Credentials ); ValidateNumbersResponse(response); return response; } } }
using System.Xml.Serialization; namespace Taxer.Domain.VAT { [XmlRoot(ElementName = "Veta5")] public class VATAdjustments { [XmlAttribute(AttributeName = "odp_uprav_kf")] public double Coef { get; set; } = 0; } }
using Bindding.ExcuteClasses; using CefSharp; using CefSharp.WinForms; using System; using System.Windows.Forms; using CefSharp.WinForms.Internals; using System.Threading.Tasks; using System.Threading; using System.Collections.Generic; using Newtonsoft.Json; using WindowsInput; using WindowsInput.Native; using Bindding.ExcuteClasses.AboutParameter; namespace Bindding.MainForms.UserControls { /// <summary> /// 浏览器控件 /// </summary> public partial class UC_Browser : BaseUserControl { private ChromiumWebBrowser browser; ///// <summary> ///// 为保证线程安全,确保顺序执行 ///// </summary> //private readonly static object _locker = new object(); /// <summary> /// 当前执行的是第几个 /// </summary> private int _currentIndex = 0; #region 属性 /// <summary> /// 当前执行的次数 /// </summary> internal int _currentNum { get { return CommonParameter.CurrentLoopNum; } set { CommonParameter.CurrentLoopNum = value; OnChangeCurrentNum(value, null); } } internal bool _is_working { get; set; } #endregion 属性 public UC_Browser() { InitializeComponent(); } /// <summary> /// 开始点击事件 /// </summary> internal void StartClick() { _currentNum = 1; _currentIndex = 0; _is_working = true; browser.Load(ConstParameter.SEARCH_ENGINES); } /// <summary> /// 结束点击事件 /// </summary> internal void StopClick() { _currentNum = 1; _currentIndex = 0; _is_working = false; } internal void InitialBrower() { // Set the CachePath during initialization. var settings = new CefSettings() { UserAgent = CommonParameter.CurrentUserAgentValue }; Cef.Initialize(settings); CommonFunction.DeleteCefsharpDirectory(); browser = new ChromiumWebBrowser(ConstParameter.SEARCH_ENGINES) { Dock = DockStyle.Fill, BrowserSettings = { ApplicationCache = CefState.Disabled, JavascriptOpenWindows = CefState.Enabled, TabToLinks = CefState.Disabled } }; var mng = Cef.GetGlobalCookieManager(); bool flag = mng.SetStoragePath(ConstParameter.CookiePath, true); toolStripContainer1.ContentPanel.Controls.Add(browser); browser.RequestHandler = new RequestHandler(); // 重写request browser.LoadingStateChanged += OnBrowserLoadingStateChanged; browser.AddressChanged += OnBrowserAddressChanged; browser.FrameLoadEnd += BeginSearch; var _lfsh = new LifeSpanHandler(); // 弹出框 _lfsh.MyBeforPopup += MyBeforPopup; browser.LifeSpanHandler = _lfsh; } internal event EventHandler MyBeforPopup; /// <summary> /// 执行第二次的查询 /// </summary> internal event EventHandler MyNextSearch; /// <summary> /// 加载完成以后 /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnBrowserLoadingStateChanged(object sender, LoadingStateChangedEventArgs args) { SetCanGoBack(args.CanGoBack); SetCanGoForward(args.CanGoForward); this.InvokeOnUiThreadIfRequired(() => SetIsLoading(!args.CanReload)); if (_is_working && _currentNum > CommonParameter.ConfigParam.loop_count) { OnExcuteClickEnd(this, null); return; } if (!args.IsLoading && browser.Address != ConstParameter.SEARCH_ENGINES && _is_working && _currentNum <= CommonParameter.ConfigParam.loop_count) { // 点击 百度一下后,加载的页面 Task.Factory.StartNew(() => { Monitor.Enter(CommonParameter.LokerObj); // Monitor.Wait(CommonParameter.LokerObj); Thread.Sleep(CommonParameter.ConfigParam.sleep_seconds.after_search.ToRandom()); this.RunJS("var _matchKey='" + CommonParameter.ConfigParam.key_match_list[_currentIndex].Value + ConstParameter.GET_BAIDU_LIST_JS); Monitor.Exit(CommonParameter.LokerObj); }); } } /// <summary> /// 执行js返回,执行的结果 /// </summary> /// <param name="strJS"></param> private void RunJS(string strJS) { string returnValue = string.Empty; browser.EvaluateScriptAsync(strJS).ContinueWith(t => { if (!t.IsFaulted) { var response = t.Result; if (response.Success && response.Result != null) { returnValue = response.Result.ToString(); if (!string.IsNullOrEmpty(returnValue)) { this.AfterSearchSimClick(returnValue); } } else { Thread.Sleep(2000); browser.Load(ConstParameter.SEARCH_ENGINES); } } }); } /// <summary> /// 加载列表 /// </summary> /// <param name="strData"></param> private void AfterSearchSimClick(string strData) { Monitor.Enter(CommonParameter.LokerObj); var _dataList = JsonConvert.DeserializeObject<List<ListContent>>(strData); bool _is_click = false; foreach (ListContent singleContent in _dataList) { // 模拟点击 if (singleContent.is_ad == ConstParameter.CLICK_AD) { var sim = new InputSimulator(); sim.Mouse .VerticalScroll(20) .Sleep(CommonParameter.ConfigParam.simulate_speed.mouse_scroll.ToRandom()); // 先到最顶层 1 = 100px; CommonFunction.SimMoveAndLefClick(singleContent.left, singleContent.top, true); // 记录日志 var _tmpLog = new ContentLog(); _tmpLog.ch_Key = CommonParameter.ConfigParam.key_match_list[_currentIndex].Key; _tmpLog.ch_Website = singleContent.target; _tmpLog.ch_Title = singleContent.title; OnWriteLog(_tmpLog, null); _is_click = true; break; // 一次搜索,只点击一次 } } _currentIndex++; if (_is_click) { Monitor.Wait(CommonParameter.LokerObj); // 点击成功需要等待 MyNextSearch(null, null); } Thread.Sleep(CommonParameter.ConfigParam.sleep_seconds.baidu_search.ToRandom()); Cef.GetGlobalCookieManager().DeleteCookiesAsync(string.Empty, string.Empty); Monitor.Exit(CommonParameter.LokerObj); browser.Load(ConstParameter.SEARCH_ENGINES); } private void BeginSearch(object sender, FrameLoadEndEventArgs args) { if (browser.Address == ConstParameter.SEARCH_ENGINES && _is_working && _currentNum <= CommonParameter.ConfigParam.loop_count) { if (_currentIndex < CommonParameter.ConfigParam.key_match_list.Count) { // 移动到搜索框 int _x = CommonParameter.FormX + ConstParameter.SearchX + ConstParameter.RandomSeed.Next(50, 300); int _y = CommonParameter.FormY + ConstParameter.BrowerY + ConstParameter.SearchY + ConstParameter.RandomSeed.Next(15, 20); Task.Factory.StartNew(() => { Monitor.Enter(CommonParameter.LokerObj); // 开始 搜索,需要锁定 var sim = new InputSimulator(); sim.Mouse .MoveMouseTo(CommonParameter.CurrentScreenWidth * _x, CommonParameter.CurrentScreenHeight * _y) .Sleep(CommonParameter.ConfigParam.simulate_speed.mouse_move_search_input.ToRandom()) .LeftButtonClick() .Sleep(CommonParameter.ConfigParam.simulate_speed.mouse_click_search_input.ToRandom()); // 输入 搜索关键字 foreach (char _single in CommonParameter.ConfigParam.key_match_list[_currentIndex].Key) { sim.Keyboard .TextEntry(_single) .Sleep(CommonParameter.ConfigParam.simulate_speed.keyboard_keywords_speed.ToRandom()); } sim.Keyboard.KeyPress(VirtualKeyCode.RETURN); // 按下回车键 Monitor.Pulse(CommonParameter.LokerObj); Monitor.Exit(CommonParameter.LokerObj); // 输入搜索完成 }); } else { // 用于判断最后一次 if (_is_working && _currentNum >= CommonParameter.ConfigParam.loop_count) { OnExcuteClickEnd(this, null); return; } var _msg = CommonFunction.BackgroundDoWorkIpelfFast(); if (!string.IsNullOrEmpty(_msg)) { MessageBox.Show(_msg, "IP精灵异常", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _currentNum++; OnExitApplcation(null, null); } } } #region 浏览的事件 /// <summary> /// 执行点击完成后 /// </summary> internal event EventHandler OnExcuteClickEnd; internal event EventHandler OnChangeCurrentNum; internal event EventHandler OnWriteLog; /// <summary> /// 执行一次后,需要关闭软件 /// </summary> internal event EventHandler OnExitApplcation; #endregion 浏览的事件 #region 浏览器的按钮 private void OnBrowserAddressChanged(object sender, AddressChangedEventArgs args) { this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = args.Address); } private void SetCanGoBack(bool canGoBack) { this.InvokeOnUiThreadIfRequired(() => backButton.Enabled = canGoBack); } private void SetCanGoForward(bool canGoForward) { this.InvokeOnUiThreadIfRequired(() => forwardButton.Enabled = canGoForward); } private void SetIsLoading(bool isLoading) { goButton.Text = isLoading ? "Stop" : "Go"; goButton.Image = isLoading ? Bindding.Properties.Resources.nav_plain_red : Bindding.Properties.Resources.nav_plain_green; HandleToolStripLayout(); } private void HandleToolStripLayout(object sender, LayoutEventArgs e) { HandleToolStripLayout(); } private void HandleToolStripLayout() { var width = toolStrip1.Width; foreach (ToolStripItem item in toolStrip1.Items) { if (item != urlTextBox) { width -= item.Width - item.Margin.Horizontal; } } urlTextBox.Width = Math.Max(0, width - urlTextBox.Margin.Horizontal - 18); } private void UrlTextBoxKeyUp(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) { return; } LoadUrl(urlTextBox.Text); } private void LoadUrl(string url) { if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { browser.Load(url); } } private void GoButtonClick(object sender, EventArgs e) { LoadUrl(urlTextBox.Text); } private void BackButtonClick(object sender, EventArgs e) { browser.Back(); } private void ForwardButtonClick(object sender, EventArgs e) { browser.Forward(); } #endregion 浏览器的按钮 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MoreMountains.Tools { public class MMDropdownAttribute : PropertyAttribute { public readonly object[] DropdownValues; public MMDropdownAttribute(params object[] dropdownValues) { DropdownValues = dropdownValues; } } }
using System.Collections.Generic; using System.Data; using System.Globalization; namespace MigSharp.NUnit.Integration { [MigrationExport(Tag = "Renaming Column With Default Value and Adding New Column With Default Value Having the Previous Name")] internal class Migration16 : IIntegrationTestMigration { private const string FirstDefaultValue = "Test"; private const int SecondDefaultValue = 747; public void Up(IDatabase db) { // renaming columns is not supported by SqlServerCe35, SqlServerCe4 and SQLite bool renameColumnIsSupported = db.Context.ProviderMetadata.Name != ProviderNames.SqlServerCe4 && db.Context.ProviderMetadata.Name != ProviderNames.SqlServerCe35 && db.Context.ProviderMetadata.Name != ProviderNames.SQLite; db.CreateTable(Tables[0].Name) .WithPrimaryKeyColumn(Tables[0].Columns[0], DbType.Int32) .WithNotNullableColumn(renameColumnIsSupported ? Tables[0].Columns[2] : Tables[0].Columns[1], DbType.String).OfSize(10).HavingDefault(FirstDefaultValue); db.Execute(string.Format(CultureInfo.InvariantCulture, "INSERT INTO \"{0}\" (\"{1}\") VALUES ('{2}')", Tables[0].Name, Tables[0].Columns[0], Tables[0].Value(0, 0))); if (renameColumnIsSupported) { db.Tables[Tables[0].Name].Columns[Tables[0].Columns[2]].Rename(Tables[0].Columns[1]); } // add a new column with the same name like the previously renamed one to make sure that any associated db object were renamed, too db.Tables[Tables[0].Name].AddNotNullableColumn(Tables[0].Columns[2], DbType.Int32).HavingDefault(SecondDefaultValue); db.Execute(string.Format(CultureInfo.InvariantCulture, "INSERT INTO \"{0}\" (\"{1}\") VALUES ('{2}')", Tables[0].Name, Tables[0].Columns[0], Tables[0].Value(1, 0))); } public ExpectedTables Tables { get { return new ExpectedTables { new ExpectedTable("Mig16", "Id", "First Renamed", "First") { { 1, FirstDefaultValue, SecondDefaultValue }, { 2, FirstDefaultValue, SecondDefaultValue }, } }; } } } }
@model VendedorModel @{ ViewData["Title"] = "Apagar"; } <h1>Agapar Vendedor?</h1> <form asp-controller="Vendedor" asp-action="Delete"> <hr /> <div class="row"> <div class="form-group col-md-8" hidden="hidden"> <label>ID *</label> <input type="text" class="form-control" asp-for="Idvendedor" value="@ViewBag.Vendedor.Idvendedor"> <span asp-validation-for="Nome" class="text-danger"></span> </div> <div class="form-group col-md-8"> <label>Nome *</label> <input type="text" class="form-control" asp-for="Nome" value="@ViewBag.Vendedor.Nome" readonly="readonly"> <span asp-validation-for="Nome" class="text-danger"></span> </div> <div class="form-group col-md-2"> <label>Sexo *</label> @{ var sexo = ViewBag.Vendedor.Sexo; } <select asp-for="Sexo" class="form-control" readonly="readonly"> <option value="@sexo" selected>@sexo</option> <option value=""></option> <option value="Feminino">Feminino</option> <option value="Masculino">Masculino</option> </select> <span asp-validation-for="Sexo" class="text-danger"></span> </div> <div class="form-group col-md-2"> <label>Status *</label> @{ var status = ViewBag.Vendedor.Status; } <select asp-for="Status" class="form-control" readonly="readonly"> <option value="@status" selected>@status</option> <option value=""></option> <option value="Ativo">Ativo</option> <option value="Inativo">Inativo</option> </select> <span asp-validation-for="Status" class="text-danger"></span> </div> </div> <div class="row"> <div class="form-group col-md-8"> <label>E-mail *</label> <input type="text" class="form-control" asp-for="Email" value="@ViewBag.Vendedor.Email" readonly="readonly"> <span asp-validation-for="Email" class="text-danger"></span> </div> <div class="form-group col-md-4"> <label>Nível *</label> @{ var nivel = ViewBag.Vendedor.Nivel; } <select asp-for="Nivel" class="form-control" readonly="readonly"> <option value="@nivel">@nivel</option> <option value=""></option> <option value="Operador">Operador</option> <option value="Administrador">Administrador</option> </select> <span asp-validation-for="Nivel" class="text-danger"></span> </div> <div class="row" hidden="hidden"> <div class="form-group col-md-3"> <label>Senha</label> <input asp-for="Senha" type="password" class="form-control" value="@ViewBag.Vendedor.Senha"> <span asp-validation-for="Senha" class="text-danger"></span> </div> <div class="form-group col-md-3"> <label>Confirmar Senha</label> <input asp-for="ConfirmSenha" type="password" class="form-control" value="@ViewBag.Vendedor.Senha"> <span asp-validation-for="ConfirmSenha" class="text-danger"></span> </div> </div> </div> <div id="actions" class="row"> <div class="col-md-12"> <button type="submit" class="btn btn-danger btn-icon-split"> <span class="icon text-white-50"> <i class="fas fa-trash"></i> </span> <span class="text">Apagar</span> </button> <a class="btn btn-light" asp-action="Index">Voltar</a> </div> </div> </form>
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sms-2016-10-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.ServerMigrationService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ServerMigrationService.Model.Internal.MarshallTransformations { /// <summary> /// UpdateReplicationJob Request Marshaller /// </summary> public class UpdateReplicationJobRequestMarshaller : IMarshaller<IRequest, UpdateReplicationJobRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateReplicationJobRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateReplicationJobRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ServerMigrationService"); string target = "AWSServerMigrationService_V2016_10_24.UpdateReplicationJob"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-10-24"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetDescription()) { context.Writer.WritePropertyName("description"); context.Writer.Write(publicRequest.Description); } if(publicRequest.IsSetEncrypted()) { context.Writer.WritePropertyName("encrypted"); context.Writer.Write(publicRequest.Encrypted); } if(publicRequest.IsSetFrequency()) { context.Writer.WritePropertyName("frequency"); context.Writer.Write(publicRequest.Frequency); } if(publicRequest.IsSetKmsKeyId()) { context.Writer.WritePropertyName("kmsKeyId"); context.Writer.Write(publicRequest.KmsKeyId); } if(publicRequest.IsSetLicenseType()) { context.Writer.WritePropertyName("licenseType"); context.Writer.Write(publicRequest.LicenseType); } if(publicRequest.IsSetNextReplicationRunStartTime()) { context.Writer.WritePropertyName("nextReplicationRunStartTime"); context.Writer.Write(publicRequest.NextReplicationRunStartTime); } if(publicRequest.IsSetNumberOfRecentAmisToKeep()) { context.Writer.WritePropertyName("numberOfRecentAmisToKeep"); context.Writer.Write(publicRequest.NumberOfRecentAmisToKeep); } if(publicRequest.IsSetReplicationJobId()) { context.Writer.WritePropertyName("replicationJobId"); context.Writer.Write(publicRequest.ReplicationJobId); } if(publicRequest.IsSetRoleName()) { context.Writer.WritePropertyName("roleName"); context.Writer.Write(publicRequest.RoleName); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateReplicationJobRequestMarshaller _instance = new UpdateReplicationJobRequestMarshaller(); internal static UpdateReplicationJobRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateReplicationJobRequestMarshaller Instance { get { return _instance; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Engine { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Plugins; public class XrefServiceResolver { private readonly List<UriTemplate<Task<List<XRefSpec>>>> _uriTemplates; public XrefServiceResolver(ImmutableArray<string> xrefServiceUrls, int maxParallelism) : this(null, xrefServiceUrls, maxParallelism) { } public XrefServiceResolver(HttpClient client, ImmutableArray<string> xrefServiceUrls, int maxParallelism) { _uriTemplates = (from url in xrefServiceUrls select UriTemplate.Create( url, new XrefClient(client, maxParallelism).ResolveAsync, GetPipeline)).ToList(); } public async Task<List<string>> ResolveAsync(List<string> uidList, ConcurrentDictionary<string, XRefSpec> externalXRefSpec) { if (_uriTemplates.Count == 0) { return uidList; } var unresolvedUidList = new List<string>(); var xrefObjects = await Task.WhenAll( from uid in uidList select ResolveAsync(uid)); foreach (var tuple in uidList.Zip(xrefObjects, Tuple.Create)) { if (tuple.Item2 == null) { unresolvedUidList.Add(tuple.Item1); } else { externalXRefSpec.AddOrUpdate(tuple.Item1, tuple.Item2, (s, x) => x + tuple.Item2); } } if (unresolvedUidList.Count > 0 && Logger.LogLevelThreshold <= LogLevel.Verbose) { var capacity = 256 + 64 * (Math.Min(100, unresolvedUidList.Count)) + 64 * _uriTemplates.Count; var sb = new StringBuilder(capacity); sb.Append("Cannot resolve "); sb.Append(unresolvedUidList.Count); sb.Append(" uids by xref service, top 100:"); foreach (var uid in unresolvedUidList.Take(100)) { sb.AppendLine().Append(" ").Append(uid); } sb.AppendLine().Append(" ").Append("xref service:"); foreach (var t in _uriTemplates) { sb.AppendLine().Append(" ").Append(t.Template); } Logger.LogVerbose(sb.ToString()); } return unresolvedUidList; } public async Task<XRefSpec> ResolveAsync(string uid) { var d = new Dictionary<string, string> { ["uid"] = uid }; foreach (var t in _uriTemplates) { List<XRefSpec> value = null; try { value = await t.Evaluate(d); } catch (Exception ex) { Logger.LogInfo($"Unable to resolve uid ({uid}) from {t.Template}, details: {ex.Message}"); } if (value?.Count > 0) { return value[0]; } } return null; } private IUriTemplatePipeline<Task<List<XRefSpec>>> GetPipeline(string name) { // todo: pluggable. switch (name) { case "removeHost": return RemoveHostUriTemplatePipeline.Default; case "addQueryString": return AddQueryStringUriTemplatePipeline.Default; default: Logger.LogWarning($"Unknown uri template pipeline: {name}.", code: WarningCodes.Build.UnknownUriTemplatePipeline); return EmptyUriTemplatePipeline.Default; } } private sealed class RemoveHostUriTemplatePipeline : IUriTemplatePipeline<Task<List<XRefSpec>>> { public static readonly RemoveHostUriTemplatePipeline Default = new RemoveHostUriTemplatePipeline(); public async Task<List<XRefSpec>> Handle(Task<List<XRefSpec>> value, string[] parameters) { var list = await value; foreach (var item in list) { if (string.IsNullOrEmpty(item.Href)) { continue; } if (Uri.TryCreate(item.Href, UriKind.Absolute, out var uri)) { if (parameters.Length == 0 || Array.IndexOf(parameters, uri.Host) != -1) { item.Href = item.Href.Substring(uri.GetLeftPart(UriPartial.Authority).Length); } } } return list; } } private sealed class AddQueryStringUriTemplatePipeline : IUriTemplatePipeline<Task<List<XRefSpec>>> { public static readonly AddQueryStringUriTemplatePipeline Default = new AddQueryStringUriTemplatePipeline(); public Task<List<XRefSpec>> Handle(Task<List<XRefSpec>> value, string[] parameters) { if (parameters.Length == 2 && !string.IsNullOrEmpty(parameters[0]) && !string.IsNullOrEmpty(parameters[1])) { return HandleCoreAsync(value, parameters[0], parameters[1]); } return value; } private async Task<List<XRefSpec>> HandleCoreAsync(Task<List<XRefSpec>> task, string name, string value) { var list = await task; foreach (var item in list) { if (string.IsNullOrEmpty(item.Href)) { continue; } var mvc = HttpUtility.ParseQueryString(UriUtility.GetQueryString(item.Href)); mvc[name] = value; item.Href = UriUtility.GetPath(item.Href) + "?" + mvc.ToString() + UriUtility.GetFragment(item.Href); } return list; } } private sealed class EmptyUriTemplatePipeline : IUriTemplatePipeline<Task<List<XRefSpec>>> { public static readonly EmptyUriTemplatePipeline Default = new EmptyUriTemplatePipeline(); public Task<List<XRefSpec>> Handle(Task<List<XRefSpec>> value, string[] parameters) { return value; } } } }
using System.Windows.Forms; using FluentAssertions; using NUnit.Framework; using UIA.Extensions.AutomationProviders.Interfaces.Tables; namespace UIA.Extensions.AutomationProviders.Defaults.Tables { [TestFixture] class DataGridCellInformationTest { private TestCell _cell; private CellInformation _cellInformation; [SetUp] public void SetUp() { _cell = new TestCell(); _cellInformation = DataGridCellInformation.FromCell(_cell); } [Test] public void ItReturnsTheValue() { _cell.Value = "Expected value"; _cellInformation.Value.Should().BeEquivalentTo("Expected value"); } [Test] public void ItDefaultsToEmptyIfThereIsNoValue() { _cell.Value = null; _cellInformation.Value.Should().BeEmpty(); } [Test] public void NonStringsAreValuesToo() { _cell.Value = 123; _cellInformation.Value.Should().BeEquivalentTo("123"); } class TestCell : DataGridViewCell { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GO2018_MKS_MessageLibrary { public class StartCreatedSessionAnswerMessage : GenericMessage { public bool Success; public string Details; public string opponentHandle; public StartCreatedSessionAnswerMessage() { Type = MessageType.startCreatedSessionAnswer; Success = false; Details = string.Empty; opponentHandle = string.Empty; } public StartCreatedSessionAnswerMessage(bool flag, string details, string newOpponentHandle) { Type = MessageType.startCreatedSessionAnswer; Success = flag; Details = details; opponentHandle = newOpponentHandle; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace wola.ha.common.Model { public class ResponseModelStatus<T> { private List<ResponseModelMessage> _message; public HttpStatusCode HtttpStatus { set; get; } public ResponseMainModelStatusEnum ResponseStatus { set; get; } public List<ResponseModelMessage> Message { get { return _message ?? (_message = new List<ResponseModelMessage>()); } set { _message = value; } } public T Model { set; get; } //public void CompletMessageFromModalState(ModelStateDictionary modelState) //{ // var modalStateList = modelState.Where(q => q.Value.Errors.Count > 0).ToList(); // if (modalStateList.Any()) // { // ResponseStatus = ResponseMainModelStatusEnum.Error; // } // foreach (var item in modalStateList) // { // foreach (var erroritem in item.Value.Errors) // { // Message.Add(new ResponseModelMessage // { // Key = item.Key, // Message = erroritem.ErrorMessage, // ResponseStatus = ResponseModelStatusEnum.Error // }); // } // } //} } public class ResponseModelMessage { public ResponseModelStatusEnum ResponseStatus { set; get; } public string Key { set; get; } public string Message { set; get; } } public enum ResponseModelStatusEnum { Error, Warning, Info }; public enum ResponseMainModelStatusEnum { Error, Warning, Ok, Onlyhttpstatus }; }
using Abp.Authorization; using Abp.Localization; using Abp.MultiTenancy; namespace FlexCMS.Authorization { public class FlexCMSAuthorizationProvider : AuthorizationProvider { public override void SetPermissions(IPermissionDefinitionContext context) { context.CreatePermission(PermissionNames.Pages_Users, L("Users")); context.CreatePermission(PermissionNames.Pages_Roles, L("Roles")); context.CreatePermission(PermissionNames.Pages_Tenants, L("Tenants"), multiTenancySides: MultiTenancySides.Host); } private static ILocalizableString L(string name) { return new LocalizableString(name, FlexCMSConsts.LocalizationSourceName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ex01_rpMovies.Models; namespace ex01_rpMovies.Pages.Movies { public class EditModel : PageModel { private readonly ex01_rpMovies.Models.RazorPagesMovieContext _context; public EditModel(ex01_rpMovies.Models.RazorPagesMovieContext context) { _context = context; } [BindProperty] public Movie Movie { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Movie = await _context.Movies.FirstOrDefaultAsync(m => m.ID == id); if (Movie == null) { return NotFound(); } return Page(); } // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(Movie).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MovieExists(Movie.ID)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool MovieExists(int id) { return _context.Movies.Any(e => e.ID == id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HackPR___NewsBot.Entities { public class LUIS_Result { public string query { get; set; } public Intent[] intents { get; set; } public Entity[] entities { get; set; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Security.Claims; using System.Threading.Tasks; using LinqToDB; using LinqToDB.Common; using LinqToDB.Data; using LinqToDB.DataProvider; using LinqToDB.Identity; using LinqToDB.Mapping; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing.xunit; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Identity.Test { public class TestConnectionFactory : IConnectionFactory { private static readonly Dictionary<string, HashSet<string>> _tables = new Dictionary<string, HashSet<string>>(); private readonly string _configuration; private readonly string _connectionString; private readonly string _key; private readonly IDataProvider _provider; public TestConnectionFactory(IDataProvider provider, string configuration, string connectionString) { _provider = provider; Configuration.Linq.AllowMultipleQuery = true; //DataConnection.AddConfiguration(configuration, connectionString, provider); _configuration = configuration; _connectionString = connectionString; _key = _configuration + "$$" + _connectionString; } public IDataContext GetContext() { return new DataContext(_provider, _connectionString); } public DataConnection GetConnection() { return new DataConnection(_provider, _connectionString); } public void CreateTable<T>() { var dc = GetContext(); var e = dc.MappingSchema.GetEntityDescriptor(typeof(T)); HashSet<string> set; lock (_tables) { if (!_tables.TryGetValue(_key, out set)) { set = new HashSet<string>(); _tables.Add(_key, set); } if (set.Contains(e.TableName)) return; set.Add(e.TableName); dc.CreateTable<T>(); } } public void CreateTables<TUser, TRole, TKey>() where TUser : class, IIdentityUser<TKey> where TRole : class, IIdentityRole<TKey> where TKey : IEquatable<TKey> { lock (_tables) { CreateTable<TUser>(); CreateTable<TRole>(); CreateTable<IdentityUserLogin<TKey>>(); CreateTable<IdentityUserRole<TKey>>(); CreateTable<IdentityRoleClaim<TKey>>(); CreateTable<IdentityUserClaim<TKey>>(); CreateTable<IdentityUserToken<TKey>>(); } } public void DropTable<T>() { var dc = GetContext(); var e = dc.MappingSchema.GetEntityDescriptor(typeof(T)); HashSet<string> set; lock (_tables) { if (!_tables.TryGetValue(_key, out set)) return; if (!set.Contains(e.TableName)) return; set.Remove(e.TableName); dc.DropTable<T>(); } } } // Common functionality tests that all verifies user manager functionality regardless of store implementation public abstract class UserManagerTestBase<TUser, TRole> : UserManagerTestBase<TUser, TRole, string> where TUser : class, IIdentityUser<string> where TRole : class, IIdentityRole<string> { } public abstract class UserManagerTestBase<TUser, TRole, TKey> where TUser : class, IIdentityUser<TKey> where TRole : class, IIdentityRole<TKey> where TKey : IEquatable<TKey> { static UserManagerTestBase() { MappingSchema.Default .GetFluentMappingBuilder() .Entity<TRole>() .HasPrimaryKey(_ => _.Id) .Property(_ => _.Id) .HasLength(255) .IsNullable(false) .Entity<TUser>() .HasPrimaryKey(_ => _.Id) .Property(_ => _.Id) .HasLength(255) .IsNullable(false); } protected void CreateTables(TestConnectionFactory factory, string connectionString) { factory.CreateTables<TUser, TRole, TKey>(); } private const string NullValue = "(null)"; private readonly IdentityErrorDescriber _errorDescriber = new IdentityErrorDescriber(); protected virtual bool ShouldSkipDbTests() { return false; } protected virtual void SetupIdentityServices(IServiceCollection services, TestConnectionFactory context = null) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddIdentity<TUser, TRole>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.User.AllowedUserNameCharacters = null; }) .AddDefaultTokenProviders(); AddUserStore(services, context); AddRoleStore(services, context); services.AddLogging(); services.AddSingleton<ILogger<UserManager<TUser>>>(new TestLogger<UserManager<TUser>>()); services.AddSingleton<ILogger<RoleManager<TRole>>>(new TestLogger<RoleManager<TRole>>()); } protected virtual UserManager<TUser> CreateManager(TestConnectionFactory context = null, IServiceCollection services = null, Action<IServiceCollection> configureServices = null) { if (services == null) services = new ServiceCollection(); if (context == null) context = CreateTestContext(); services.AddSingleton<IConnectionFactory>(context); SetupIdentityServices(services, context); if (configureServices != null) configureServices(services); return services.BuildServiceProvider().GetService<UserManager<TUser>>(); } protected RoleManager<TRole> CreateRoleManager(TestConnectionFactory context = null, IServiceCollection services = null) { if (services == null) services = new ServiceCollection(); if (context == null) context = CreateTestContext(); SetupIdentityServices(services, context); return services.BuildServiceProvider().GetService<RoleManager<TRole>>(); } protected abstract TestConnectionFactory CreateTestContext(); protected abstract void AddUserStore(IServiceCollection services, TestConnectionFactory context = null); protected abstract void AddRoleStore(IServiceCollection services, TestConnectionFactory context = null); protected abstract void SetUserPasswordHash(TUser user, string hashedPassword); protected abstract TUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "", bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = null, bool useNamePrefixAsUserName = false); protected abstract TRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false); protected abstract Expression<Func<TUser, bool>> UserNameEqualsPredicate(string userName); protected abstract Expression<Func<TUser, bool>> UserNameStartsWithPredicate(string userName); protected abstract Expression<Func<TRole, bool>> RoleNameEqualsPredicate(string roleName); protected abstract Expression<Func<TRole, bool>> RoleNameStartsWithPredicate(string roleName); [Fact] public async Task CanDeleteUser() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var userId = await manager.GetUserIdAsync(user); IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user)); Assert.Null(await manager.FindByIdAsync(userId)); } [Fact] public async Task CanUpdateUserName() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var name = Guid.NewGuid().ToString(); var user = CreateTestUser(name); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var newName = Guid.NewGuid().ToString(); Assert.Null(await manager.FindByNameAsync(newName)); IdentityResultAssert.IsSuccess(await manager.SetUserNameAsync(user, newName)); IdentityResultAssert.IsSuccess(await manager.UpdateAsync(user)); Assert.NotNull(await manager.FindByNameAsync(newName)); Assert.Null(await manager.FindByNameAsync(name)); } [Fact] public async Task CheckSetUserNameValidatesUser() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var username = "UpdateAsync" + Guid.NewGuid(); var newUsername = "New" + Guid.NewGuid(); var user = CreateTestUser(username, useNamePrefixAsUserName: true); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.Null(await manager.FindByNameAsync(newUsername)); IdentityResultAssert.IsSuccess(await manager.SetUserNameAsync(user, newUsername)); Assert.NotNull(await manager.FindByNameAsync(newUsername)); Assert.Null(await manager.FindByNameAsync(username)); var newUser = CreateTestUser(username, useNamePrefixAsUserName: true); IdentityResultAssert.IsSuccess(await manager.CreateAsync(newUser)); var error = _errorDescriber.InvalidUserName(""); IdentityResultAssert.IsFailure(await manager.SetUserNameAsync(newUser, ""), error); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(newUser)} validation failed: {error.Code}."); error = _errorDescriber.DuplicateUserName(newUsername); IdentityResultAssert.IsFailure(await manager.SetUserNameAsync(newUser, newUsername), error); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(newUser)} validation failed: {error.Code}."); } [Fact] public async Task SetUserNameUpdatesSecurityStamp() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var username = "UpdateAsync" + Guid.NewGuid(); var newUsername = "New" + Guid.NewGuid(); var user = CreateTestUser(username, useNamePrefixAsUserName: true); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); Assert.Null(await manager.FindByNameAsync(newUsername)); IdentityResultAssert.IsSuccess(await manager.SetUserNameAsync(user, newUsername)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CreateUpdatesSecurityStamp() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var username = "Create" + Guid.NewGuid(); var user = CreateTestUser(username, useNamePrefixAsUserName: true); var stamp = await manager.GetSecurityStampAsync(user); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.NotNull(await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CheckSetEmailValidatesUser() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.Options.User.RequireUniqueEmail = true; manager.UserValidators.Add(new UserValidator<TUser>()); var random = new Random(); var email = "foo" + random.Next() + "@example.com"; var newEmail = "bar" + random.Next() + "@example.com"; var user = CreateTestUser(email: email); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, newEmail)); var newUser = CreateTestUser(email: email); IdentityResultAssert.IsSuccess(await manager.CreateAsync(newUser)); IdentityResultAssert.IsFailure(await manager.SetEmailAsync(newUser, newEmail), _errorDescriber.DuplicateEmail(newEmail)); IdentityResultAssert.IsFailure(await manager.SetEmailAsync(newUser, ""), _errorDescriber.InvalidEmail("")); } [Fact] public async Task CanUpdatePasswordUsingHasher() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser("UpdatePassword"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, "password")); Assert.True(await manager.CheckPasswordAsync(user, "password")); var userId = await manager.GetUserIdAsync(user); SetUserPasswordHash(user, manager.PasswordHasher.HashPassword(user, "New")); IdentityResultAssert.IsSuccess(await manager.UpdateAsync(user)); Assert.False(await manager.CheckPasswordAsync(user, "password")); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Invalid password for user {await manager.GetUserIdAsync(user)}."); Assert.True(await manager.CheckPasswordAsync(user, "New")); } [Fact] public async Task CanFindById() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.NotNull(await manager.FindByIdAsync(await manager.GetUserIdAsync(user))); } [Fact] public async Task UserValidatorCanBlockCreate() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); manager.UserValidators.Clear(); manager.UserValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.CreateAsync(user), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } [Fact] public async Task UserValidatorCanBlockUpdate() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); manager.UserValidators.Clear(); manager.UserValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.UpdateAsync(user), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } [Fact] public async Task CanChainUserValidators() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.UserValidators.Clear(); var user = CreateTestUser(); manager.UserValidators.Add(new AlwaysBadValidator()); manager.UserValidators.Add(new AlwaysBadValidator()); var result = await manager.CreateAsync(user); IdentityResultAssert.IsFailure(result, AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code};{AlwaysBadValidator.ErrorMessage.Code}."); Assert.Equal(2, result.Errors.Count()); } [ConditionalTheory] [InlineData("")] [InlineData(null)] public async Task UserValidatorBlocksShortEmailsWhenRequiresUniqueEmail(string email) { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); manager.Options.User.RequireUniqueEmail = true; IdentityResultAssert.IsFailure(await manager.CreateAsync(user), _errorDescriber.InvalidEmail(email)); } #if NET451 [Theory] [InlineData("@@afd")] [InlineData("bogus")] public async Task UserValidatorBlocksInvalidEmailsWhenRequiresUniqueEmail(string email) { if (ShouldSkipDbTests()) { return; } var manager = CreateManager(); var user = CreateTestUser("UpdateBlocked", email); manager.Options.User.RequireUniqueEmail = true; IdentityResultAssert.IsFailure(await manager.CreateAsync(user), _errorDescriber.InvalidEmail(email)); } #endif [Fact] public async Task PasswordValidatorCanBlockAddPassword() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); manager.PasswordValidators.Clear(); manager.PasswordValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.AddPasswordAsync(user, "password"), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user)} password validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } [Fact] public async Task CanChainPasswordValidators() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.PasswordValidators.Clear(); manager.PasswordValidators.Add(new AlwaysBadValidator()); manager.PasswordValidators.Add(new AlwaysBadValidator()); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var result = await manager.AddPasswordAsync(user, "pwd"); IdentityResultAssert.IsFailure(result, AlwaysBadValidator.ErrorMessage); Assert.Equal(2, result.Errors.Count()); } [Fact] public async Task PasswordValidatorCanBlockChangePassword() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, "password")); manager.PasswordValidators.Clear(); manager.PasswordValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.ChangePasswordAsync(user, "password", "new"), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user) ?? NullValue} password validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } [Fact] public async Task PasswordValidatorCanBlockCreateUser() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); manager.PasswordValidators.Clear(); manager.PasswordValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.CreateAsync(user, "password"), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user) ?? NullValue} password validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } [Fact] public async Task CanCreateUserNoPassword() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var username = "CreateUserTest" + Guid.NewGuid(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(CreateTestUser(username, useNamePrefixAsUserName: true))); var user = await manager.FindByNameAsync(username); Assert.NotNull(user); Assert.False(await manager.HasPasswordAsync(user)); Assert.False(await manager.CheckPasswordAsync(user, "whatever")); var logins = await manager.GetLoginsAsync(user); Assert.NotNull(logins); Assert.Empty(logins); } [Fact] public async Task CanCreateUserAddLogin() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); const string provider = "ZzAuth"; const string display = "display"; var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var providerKey = await manager.GetUserIdAsync(user); IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, new UserLoginInfo(provider, providerKey, display))); var logins = await manager.GetLoginsAsync(user); Assert.NotNull(logins); Assert.NotNull(logins.Single()); Assert.Equal(provider, logins.First().LoginProvider); Assert.Equal(providerKey, logins.First().ProviderKey); Assert.Equal(display, logins.First().ProviderDisplayName); } [Fact] public async Task CanCreateUserLoginAndAddPassword() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var userId = await manager.GetUserIdAsync(user); var login = new UserLoginInfo("Provider", userId, "display"); IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, login)); Assert.False(await manager.HasPasswordAsync(user)); IdentityResultAssert.IsSuccess(await manager.AddPasswordAsync(user, "password")); Assert.True(await manager.HasPasswordAsync(user)); var logins = await manager.GetLoginsAsync(user); Assert.NotNull(logins); Assert.NotNull(logins.Single()); Assert.Equal(user.Id, (await manager.FindByLoginAsync(login.LoginProvider, login.ProviderKey)).Id); Assert.True(await manager.CheckPasswordAsync(user, "password")); } [Fact] public async Task AddPasswordFailsIfAlreadyHave() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, "Password")); Assert.True(await manager.HasPasswordAsync(user)); IdentityResultAssert.IsFailure(await manager.AddPasswordAsync(user, "password"), "User already has a password set."); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user)} already has a password."); } [Fact] public async Task CanCreateUserAddRemoveLogin() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); var result = await manager.CreateAsync(user); Assert.NotNull(user); var userId = await manager.GetUserIdAsync(user); var login = new UserLoginInfo("Provider", userId, "display"); IdentityResultAssert.IsSuccess(result); IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, login)); Assert.Equal(user.Id, (await manager.FindByLoginAsync(login.LoginProvider, login.ProviderKey)).Id); var logins = await manager.GetLoginsAsync(user); Assert.NotNull(logins); Assert.NotNull(logins.Single()); Assert.Equal(login.LoginProvider, logins.Last().LoginProvider); Assert.Equal(login.ProviderKey, logins.Last().ProviderKey); Assert.Equal(login.ProviderDisplayName, logins.Last().ProviderDisplayName); var stamp = await manager.GetSecurityStampAsync(user); IdentityResultAssert.IsSuccess(await manager.RemoveLoginAsync(user, login.LoginProvider, login.ProviderKey)); Assert.Null(await manager.FindByLoginAsync(login.LoginProvider, login.ProviderKey)); logins = await manager.GetLoginsAsync(user); Assert.NotNull(logins); Assert.Empty(logins); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CanRemovePassword() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser("CanRemovePassword"); const string password = "password"; IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, password)); var stamp = await manager.GetSecurityStampAsync(user); var username = await manager.GetUserNameAsync(user); IdentityResultAssert.IsSuccess(await manager.RemovePasswordAsync(user)); var u = await manager.FindByNameAsync(username); Assert.NotNull(u); Assert.False(await manager.HasPasswordAsync(user)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CanChangePassword() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); const string password = "password"; const string newPassword = "newpassword"; IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, password)); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); IdentityResultAssert.IsSuccess(await manager.ChangePasswordAsync(user, password, newPassword)); Assert.False(await manager.CheckPasswordAsync(user, password)); Assert.True(await manager.CheckPasswordAsync(user, newPassword)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CanAddRemoveUserClaim() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")}; foreach (var c in claims) IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c)); var userId = await manager.GetUserIdAsync(user); var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(3, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[0])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(2, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[1])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[2])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(0, userClaims.Count); } [Fact] public async Task CanAddRemoveUserClaim2() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")}; IdentityResultAssert.IsSuccess(await manager.AddClaimsAsync(user, claims)); var userId = await manager.GetUserIdAsync(user); var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(3, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimsAsync(user, claims)); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(0, userClaims.Count); } [Fact] public async Task RemoveClaimOnlyAffectsUser() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); var user2 = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user2)); Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")}; foreach (var c in claims) { IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c)); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user2, c)); } var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(3, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[0])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(2, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[1])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(user, claims[2])); userClaims = await manager.GetClaimsAsync(user); Assert.Equal(0, userClaims.Count); var userClaims2 = await manager.GetClaimsAsync(user2); Assert.Equal(3, userClaims2.Count); } [Fact] public async Task CanReplaceUserClaim() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, new Claim("c", "a"))); var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); var claim = new Claim("c", "b"); var oldClaim = userClaims.FirstOrDefault(); IdentityResultAssert.IsSuccess(await manager.ReplaceClaimAsync(user, oldClaim, claim)); var newUserClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, newUserClaims.Count); var newClaim = newUserClaims.FirstOrDefault(); Assert.Equal(claim.Type, newClaim.Type); Assert.Equal(claim.Value, newClaim.Value); } [Fact] public async Task ReplaceUserClaimOnlyAffectsUser() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); var user2 = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user2)); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, new Claim("c", "a"))); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user2, new Claim("c", "a"))); var userClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); var userClaims2 = await manager.GetClaimsAsync(user); Assert.Equal(1, userClaims2.Count); var claim = new Claim("c", "b"); var oldClaim = userClaims.FirstOrDefault(); IdentityResultAssert.IsSuccess(await manager.ReplaceClaimAsync(user, oldClaim, claim)); var newUserClaims = await manager.GetClaimsAsync(user); Assert.Equal(1, newUserClaims.Count); var newClaim = newUserClaims.FirstOrDefault(); Assert.Equal(claim.Type, newClaim.Type); Assert.Equal(claim.Value, newClaim.Value); userClaims2 = await manager.GetClaimsAsync(user2); Assert.Equal(1, userClaims2.Count); var oldClaim2 = userClaims2.FirstOrDefault(); Assert.Equal("c", oldClaim2.Type); Assert.Equal("a", oldClaim2.Value); } [Fact] public async Task ChangePasswordFallsIfPasswordWrong() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, "password")); var result = await manager.ChangePasswordAsync(user, "bogus", "newpassword"); IdentityResultAssert.IsFailure(result, "Incorrect password."); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Change password failed for user {await manager.GetUserIdAsync(user)}."); } [Fact] public async Task AddDupeUserNameFails() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var username = "AddDupeUserNameFails" + Guid.NewGuid(); var user = CreateTestUser(username, useNamePrefixAsUserName: true); var user2 = CreateTestUser(username, useNamePrefixAsUserName: true); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsFailure(await manager.CreateAsync(user2), _errorDescriber.DuplicateUserName(username)); } [Fact] public async Task AddDupeEmailAllowedByDefault() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(email: "yup@yup.com"); var user2 = CreateTestUser(email: "yup@yup.com"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user2)); IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user2, await manager.GetEmailAsync(user))); } [Fact] public async Task AddDupeEmailFailsWhenUniqueEmailRequired() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.Options.User.RequireUniqueEmail = true; var user = CreateTestUser(email: "FooUser@yup.com"); var user2 = CreateTestUser(email: "FooUser@yup.com"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsFailure(await manager.CreateAsync(user2), _errorDescriber.DuplicateEmail("FooUser@yup.com")); } [Fact] public async Task UpdateSecurityStampActuallyChanges() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); Assert.Null(await manager.GetSecurityStampAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); IdentityResultAssert.IsSuccess(await manager.UpdateSecurityStampAsync(user)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task AddDupeLoginFails() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); var login = new UserLoginInfo("Provider", "key", "display"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, login)); var result = await manager.AddLoginAsync(user, login); IdentityResultAssert.IsFailure(result, _errorDescriber.LoginAlreadyAssociated()); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"AddLogin for user {await manager.GetUserIdAsync(user)} failed because it was already associated with another user."); } // Email tests [Fact] public async Task CanFindByEmail() { if (ShouldSkipDbTests()) return; var email = "foouser@test.com"; var manager = CreateManager(); var user = CreateTestUser(email: email); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var fetch = await manager.FindByEmailAsync(email); Assert.Equal(user.Id, fetch.Id); } [Fact] public async Task CanFindUsersViaUserQuerable() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); if (mgr.SupportsQueryableUsers) { var users = GenerateUsers("CanFindUsersViaUserQuerable", 4); foreach (var u in users) IdentityResultAssert.IsSuccess(await mgr.CreateAsync(u)); Assert.Equal(users.Count, mgr.Users.Count(UserNameStartsWithPredicate("CanFindUsersViaUserQuerable"))); Assert.Null(mgr.Users.FirstOrDefault(UserNameEqualsPredicate("bogus"))); } } [Fact] public async Task ConfirmEmailFalseByDefaultTest() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.False(await manager.IsEmailConfirmedAsync(user)); } private class StaticTokenProvider : IUserTwoFactorTokenProvider<TUser> { public async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user) { return MakeToken(purpose, await manager.GetUserIdAsync(user)); } public async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user) { return token == MakeToken(purpose, await manager.GetUserIdAsync(user)); } public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user) { return Task.FromResult(true); } private static string MakeToken(string purpose, string userId) { return string.Join(":", userId, purpose, "ImmaToken"); } } [Fact] public async Task CanResetPasswordWithStaticTokenProvider() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.RegisterTokenProvider("Static", new StaticTokenProvider()); manager.Options.Tokens.PasswordResetTokenProvider = "Static"; var user = CreateTestUser(); const string password = "password"; const string newPassword = "newpassword"; IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, password)); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); var token = await manager.GeneratePasswordResetTokenAsync(user); Assert.NotNull(token); var userId = await manager.GetUserIdAsync(user); IdentityResultAssert.IsSuccess(await manager.ResetPasswordAsync(user, token, newPassword)); Assert.False(await manager.CheckPasswordAsync(user, password)); Assert.True(await manager.CheckPasswordAsync(user, newPassword)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task PasswordValidatorCanBlockResetPasswordWithStaticTokenProvider() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.RegisterTokenProvider("Static", new StaticTokenProvider()); manager.Options.Tokens.PasswordResetTokenProvider = "Static"; var user = CreateTestUser(); const string password = "password"; const string newPassword = "newpassword"; IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, password)); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); var token = await manager.GeneratePasswordResetTokenAsync(user); Assert.NotNull(token); manager.PasswordValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.ResetPasswordAsync(user, token, newPassword), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"User {await manager.GetUserIdAsync(user)} password validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); Assert.True(await manager.CheckPasswordAsync(user, password)); Assert.Equal(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task ResetPasswordWithStaticTokenProviderFailsWithWrongToken() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.RegisterTokenProvider("Static", new StaticTokenProvider()); manager.Options.Tokens.PasswordResetTokenProvider = "Static"; var user = CreateTestUser(); const string password = "password"; const string newPassword = "newpassword"; IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, password)); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); IdentityResultAssert.IsFailure(await manager.ResetPasswordAsync(user, "bogus", newPassword), "Invalid token."); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: ResetPassword for user {await manager.GetUserIdAsync(user)}."); Assert.True(await manager.CheckPasswordAsync(user, password)); Assert.Equal(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CanGenerateAndVerifyUserTokenWithStaticTokenProvider() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.RegisterTokenProvider("Static", new StaticTokenProvider()); var user = CreateTestUser(); var user2 = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user2)); var userId = await manager.GetUserIdAsync(user); var token = await manager.GenerateUserTokenAsync(user, "Static", "test"); Assert.True(await manager.VerifyUserTokenAsync(user, "Static", "test", token)); Assert.False(await manager.VerifyUserTokenAsync(user, "Static", "test2", token)); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: test2 for user {await manager.GetUserIdAsync(user)}."); Assert.False(await manager.VerifyUserTokenAsync(user, "Static", "test", token + "a")); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: test for user {await manager.GetUserIdAsync(user)}."); Assert.False(await manager.VerifyUserTokenAsync(user2, "Static", "test", token)); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: test for user {await manager.GetUserIdAsync(user2)}."); } [Fact] public async Task CanConfirmEmailWithStaticToken() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.RegisterTokenProvider("Static", new StaticTokenProvider()); manager.Options.Tokens.EmailConfirmationTokenProvider = "Static"; var user = CreateTestUser(); Assert.False(await manager.IsEmailConfirmedAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var token = await manager.GenerateEmailConfirmationTokenAsync(user); Assert.NotNull(token); var userId = await manager.GetUserIdAsync(user); IdentityResultAssert.IsSuccess(await manager.ConfirmEmailAsync(user, token)); Assert.True(await manager.IsEmailConfirmedAsync(user)); IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, null)); Assert.False(await manager.IsEmailConfirmedAsync(user)); } [Fact] public async Task ConfirmEmailWithStaticTokenFailsWithWrongToken() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); manager.RegisterTokenProvider("Static", new StaticTokenProvider()); manager.Options.Tokens.EmailConfirmationTokenProvider = "Static"; var user = CreateTestUser(); Assert.False(await manager.IsEmailConfirmedAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsFailure(await manager.ConfirmEmailAsync(user, "bogus"), "Invalid token."); Assert.False(await manager.IsEmailConfirmedAsync(user)); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: EmailConfirmation for user {await manager.GetUserIdAsync(user)}."); } [Fact] public async Task ConfirmTokenFailsAfterPasswordChange() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser("Test"); Assert.False(await manager.IsEmailConfirmedAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, "password")); var token = await manager.GenerateEmailConfirmationTokenAsync(user); Assert.NotNull(token); IdentityResultAssert.IsSuccess(await manager.ChangePasswordAsync(user, "password", "newpassword")); IdentityResultAssert.IsFailure(await manager.ConfirmEmailAsync(user, token), "Invalid token."); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: EmailConfirmation for user {await manager.GetUserIdAsync(user)}."); Assert.False(await manager.IsEmailConfirmedAsync(user)); } // Lockout tests [Fact] public async Task SingleFailureLockout() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); mgr.Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(1); mgr.Options.Lockout.MaxFailedAccessAttempts = 0; var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); IdentityResultAssert.IsSuccess(await mgr.AccessFailedAsync(user)); Assert.True(await mgr.IsLockedOutAsync(user)); Assert.True(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); IdentityResultAssert.VerifyLogMessage(mgr.Logger, $"User {await mgr.GetUserIdAsync(user)} is locked out."); Assert.Equal(0, await mgr.GetAccessFailedCountAsync(user)); } [Fact] public async Task TwoFailureLockout() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); mgr.Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(1); mgr.Options.Lockout.MaxFailedAccessAttempts = 2; var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); IdentityResultAssert.IsSuccess(await mgr.AccessFailedAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); Assert.False(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); Assert.Equal(1, await mgr.GetAccessFailedCountAsync(user)); IdentityResultAssert.IsSuccess(await mgr.AccessFailedAsync(user)); Assert.True(await mgr.IsLockedOutAsync(user)); Assert.True(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); IdentityResultAssert.VerifyLogMessage(mgr.Logger, $"User {await mgr.GetUserIdAsync(user)} is locked out."); Assert.Equal(0, await mgr.GetAccessFailedCountAsync(user)); } [Fact] public async Task ResetAccessCountPreventsLockout() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); mgr.Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(1); mgr.Options.Lockout.MaxFailedAccessAttempts = 2; var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); IdentityResultAssert.IsSuccess(await mgr.AccessFailedAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); Assert.False(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); Assert.Equal(1, await mgr.GetAccessFailedCountAsync(user)); IdentityResultAssert.IsSuccess(await mgr.ResetAccessFailedCountAsync(user)); Assert.Equal(0, await mgr.GetAccessFailedCountAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); Assert.False(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); IdentityResultAssert.IsSuccess(await mgr.AccessFailedAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); Assert.False(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); Assert.Equal(1, await mgr.GetAccessFailedCountAsync(user)); } [Fact] public async Task CanEnableLockoutManuallyAndLockout() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); mgr.Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(1); mgr.Options.Lockout.AllowedForNewUsers = false; mgr.Options.Lockout.MaxFailedAccessAttempts = 2; var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.False(await mgr.GetLockoutEnabledAsync(user)); IdentityResultAssert.IsSuccess(await mgr.SetLockoutEnabledAsync(user, true)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); IdentityResultAssert.IsSuccess(await mgr.AccessFailedAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); Assert.False(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); Assert.Equal(1, await mgr.GetAccessFailedCountAsync(user)); IdentityResultAssert.IsSuccess(await mgr.AccessFailedAsync(user)); Assert.True(await mgr.IsLockedOutAsync(user)); Assert.True(await mgr.GetLockoutEndDateAsync(user) > DateTimeOffset.UtcNow.AddMinutes(55)); IdentityResultAssert.VerifyLogMessage(mgr.Logger, $"User {await mgr.GetUserIdAsync(user)} is locked out."); Assert.Equal(0, await mgr.GetAccessFailedCountAsync(user)); } [Fact] public async Task UserNotLockedOutWithNullDateTimeAndIsSetToNullDate() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); IdentityResultAssert.IsSuccess(await mgr.SetLockoutEndDateAsync(user, new DateTimeOffset())); Assert.False(await mgr.IsLockedOutAsync(user)); Assert.Equal(new DateTimeOffset(), await mgr.GetLockoutEndDateAsync(user)); } [Fact] public async Task LockoutFailsIfNotEnabled() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); mgr.Options.Lockout.AllowedForNewUsers = false; var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.False(await mgr.GetLockoutEnabledAsync(user)); IdentityResultAssert.IsFailure(await mgr.SetLockoutEndDateAsync(user, new DateTimeOffset()), "Lockout is not enabled for this user."); IdentityResultAssert.VerifyLogMessage(mgr.Logger, $"Lockout for user {await mgr.GetUserIdAsync(user)} failed because lockout is not enabled for this user."); Assert.False(await mgr.IsLockedOutAsync(user)); } [Fact] public async Task LockoutEndToUtcNowMinus1SecInUserShouldNotBeLockedOut() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); var user = CreateTestUser(lockoutEnd: DateTimeOffset.UtcNow.AddSeconds(-1)); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); Assert.False(await mgr.IsLockedOutAsync(user)); } [Fact] public async Task LockoutEndToUtcNowSubOneSecondWithManagerShouldNotBeLockedOut() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); IdentityResultAssert.IsSuccess(await mgr.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddSeconds(-1))); Assert.False(await mgr.IsLockedOutAsync(user)); } [Fact] public async Task LockoutEndToUtcNowPlus5ShouldBeLockedOut() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); var lockoutEnd = DateTimeOffset.UtcNow.AddMinutes(5); var user = CreateTestUser(lockoutEnd: lockoutEnd); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); Assert.True(await mgr.IsLockedOutAsync(user)); } [Fact] public async Task UserLockedOutWithDateTimeLocalKindNowPlus30() { if (ShouldSkipDbTests()) return; var mgr = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await mgr.CreateAsync(user)); Assert.True(await mgr.GetLockoutEnabledAsync(user)); var lockoutEnd = new DateTimeOffset(DateTime.Now.AddMinutes(30).ToLocalTime()); IdentityResultAssert.IsSuccess(await mgr.SetLockoutEndDateAsync(user, lockoutEnd)); Assert.True(await mgr.IsLockedOutAsync(user)); var end = await mgr.GetLockoutEndDateAsync(user); Assert.Equal(lockoutEnd, end); } // Role Tests [Fact] public async Task CanCreateRoleTest() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var roleName = "create" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); } private class AlwaysBadValidator : IUserValidator<TUser>, IRoleValidator<TRole>, IPasswordValidator<TUser> { public static readonly IdentityError ErrorMessage = new IdentityError {Description = "I'm Bad.", Code = "BadValidator"}; public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password) { return Task.FromResult(IdentityResult.Failed(ErrorMessage)); } public Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role) { return Task.FromResult(IdentityResult.Failed(ErrorMessage)); } public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user) { return Task.FromResult(IdentityResult.Failed(ErrorMessage)); } } [Fact] public async Task BadValidatorBlocksCreateRole() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); manager.RoleValidators.Clear(); manager.RoleValidators.Add(new AlwaysBadValidator()); var role = CreateTestRole("blocked"); IdentityResultAssert.IsFailure(await manager.CreateAsync(role), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } [Fact] public async Task CanChainRoleValidators() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); manager.RoleValidators.Clear(); manager.RoleValidators.Add(new AlwaysBadValidator()); manager.RoleValidators.Add(new AlwaysBadValidator()); var role = CreateTestRole("blocked"); var result = await manager.CreateAsync(role); IdentityResultAssert.IsFailure(result, AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code};{AlwaysBadValidator.ErrorMessage.Code}."); Assert.Equal(2, result.Errors.Count()); } [Fact] public async Task BadValidatorBlocksRoleUpdate() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var role = CreateTestRole("poorguy"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); var error = AlwaysBadValidator.ErrorMessage; manager.RoleValidators.Clear(); manager.RoleValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.UpdateAsync(role), error); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } [Fact] public async Task CanDeleteRole() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var roleName = "delete" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.DeleteAsync(role)); Assert.False(await manager.RoleExistsAsync(roleName)); } [Fact] public async Task CanAddRemoveRoleClaim() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var role = CreateTestRole("ClaimsAddRemove"); var roleSafe = CreateTestRole("ClaimsAdd"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(roleSafe)); Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")}; foreach (var c in claims) { IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(role, c)); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(roleSafe, c)); } var roleClaims = await manager.GetClaimsAsync(role); var safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(3, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[0])); roleClaims = await manager.GetClaimsAsync(role); safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(2, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[1])); roleClaims = await manager.GetClaimsAsync(role); safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(1, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[2])); roleClaims = await manager.GetClaimsAsync(role); safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(0, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); } [Fact] public async Task CanRoleFindById() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var role = CreateTestRole("FindByIdAsync"); Assert.Null(await manager.FindByIdAsync(await manager.GetRoleIdAsync(role))); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.Equal(role.Id, (await manager.FindByIdAsync(await manager.GetRoleIdAsync(role))).Id); } [Fact] public async Task CanRoleFindByName() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var roleName = "FindByNameAsync" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); Assert.Null(await manager.FindByNameAsync(roleName)); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.Equal(role.Id, (await manager.FindByNameAsync(roleName)).Id); } [Fact] public async Task CanUpdateRoleName() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var roleName = "update" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.SetRoleNameAsync(role, "Changed")); IdentityResultAssert.IsSuccess(await manager.UpdateAsync(role)); Assert.False(await manager.RoleExistsAsync("update")); Assert.Equal(role.Id, (await manager.FindByNameAsync("Changed")).Id); } [Fact] public async Task CanQueryableRoles() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); if (manager.SupportsQueryableRoles) { var roles = GenerateRoles("CanQuerableRolesTest", 4); foreach (var r in roles) IdentityResultAssert.IsSuccess(await manager.CreateAsync(r)); Assert.Equal(roles.Count, manager.Roles.Count(RoleNameStartsWithPredicate("CanQuerableRolesTest"))); Assert.Null(manager.Roles.FirstOrDefault(RoleNameEqualsPredicate("bogus"))); } } [Fact] public async Task CreateRoleFailsIfExists() { if (ShouldSkipDbTests()) return; var manager = CreateRoleManager(); var roleName = "dupeRole" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); var role2 = CreateTestRole(roleName, true); IdentityResultAssert.IsFailure(await manager.CreateAsync(role2)); } [Fact] public async Task CanAddUsersToRole() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var manager = CreateManager(context); var roleManager = CreateRoleManager(context); var roleName = "AddUserTest" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(role)); TUser[] users = { CreateTestUser("1"), CreateTestUser("2"), CreateTestUser("3"), CreateTestUser("4") }; foreach (var u in users) { IdentityResultAssert.IsSuccess(await manager.CreateAsync(u)); IdentityResultAssert.IsSuccess(await manager.AddToRoleAsync(u, roleName)); Assert.True(await manager.IsInRoleAsync(u, roleName)); } } [ConditionalFact] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Fails due to threading bugs in Mono")] public async Task CanGetRolesForUser() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var userManager = CreateManager(context); var roleManager = CreateRoleManager(context); var users = GenerateUsers("CanGetRolesForUser", 4); var roles = GenerateRoles("CanGetRolesForUserRole", 4); foreach (var u in users) IdentityResultAssert.IsSuccess(await userManager.CreateAsync(u)); foreach (var r in roles) { IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r)); foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(u, await roleManager.GetRoleNameAsync(r))); Assert.True(await userManager.IsInRoleAsync(u, await roleManager.GetRoleNameAsync(r))); } } foreach (var u in users) { var rs = await userManager.GetRolesAsync(u); Assert.Equal(roles.Count, rs.Count); foreach (var r in roles) { var expectedRoleName = await roleManager.GetRoleNameAsync(r); Assert.NotEmpty(rs.Where(role => role == expectedRoleName)); } } } [Fact] public async Task RemoveUserFromRoleWithMultipleRoles() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var userManager = CreateManager(context); var roleManager = CreateRoleManager(context); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user)); var roles = GenerateRoles("RemoveUserFromRoleWithMultipleRoles", 4); foreach (var r in roles) { IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r)); IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(user, await roleManager.GetRoleNameAsync(r))); Assert.True(await userManager.IsInRoleAsync(user, await roleManager.GetRoleNameAsync(r))); } IdentityResultAssert.IsSuccess( await userManager.RemoveFromRoleAsync(user, await roleManager.GetRoleNameAsync(roles[2]))); Assert.False(await userManager.IsInRoleAsync(user, await roleManager.GetRoleNameAsync(roles[2]))); } [Fact] public async Task CanRemoveUsersFromRole() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var userManager = CreateManager(context); var roleManager = CreateRoleManager(context); var users = GenerateUsers("CanRemoveUsersFromRole", 4); foreach (var u in users) IdentityResultAssert.IsSuccess(await userManager.CreateAsync(u)); var r = CreateTestRole("r1"); var roleName = await roleManager.GetRoleNameAsync(r); IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r)); foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(u, roleName)); Assert.True(await userManager.IsInRoleAsync(u, roleName)); } foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.RemoveFromRoleAsync(u, roleName)); Assert.False(await userManager.IsInRoleAsync(u, roleName)); } } [Fact] public async Task RemoveUserNotInRoleFails() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var userMgr = CreateManager(context); var roleMgr = CreateRoleManager(context); var roleName = "addUserDupeTest" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); var result = await userMgr.RemoveFromRoleAsync(user, roleName); IdentityResultAssert.IsFailure(result, _errorDescriber.UserNotInRole(roleName)); IdentityResultAssert.VerifyLogMessage(userMgr.Logger, $"User {await userMgr.GetUserIdAsync(user)} is not in role {roleName}."); } [Fact] public async Task AddUserToRoleFailsIfAlreadyInRole() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var userMgr = CreateManager(context); var roleMgr = CreateRoleManager(context); var roleName = "addUserDupeTest" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); IdentityResultAssert.IsSuccess(await userMgr.AddToRoleAsync(user, roleName)); Assert.True(await userMgr.IsInRoleAsync(user, roleName)); IdentityResultAssert.IsFailure(await userMgr.AddToRoleAsync(user, roleName), _errorDescriber.UserAlreadyInRole(roleName)); IdentityResultAssert.VerifyLogMessage(userMgr.Logger, $"User {await userMgr.GetUserIdAsync(user)} is already in role {roleName}."); } [Fact] public async Task AddUserToRolesIgnoresDuplicates() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var userMgr = CreateManager(context); var roleMgr = CreateRoleManager(context); var roleName = "addUserDupeTest" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); Assert.False(await userMgr.IsInRoleAsync(user, roleName)); IdentityResultAssert.IsSuccess(await userMgr.AddToRolesAsync(user, new[] {roleName, roleName})); Assert.True(await userMgr.IsInRoleAsync(user, roleName)); } [Fact] public async Task CanFindRoleByNameWithManager() { if (ShouldSkipDbTests()) return; var roleMgr = CreateRoleManager(); var roleName = "findRoleByNameTest" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); Assert.NotNull(await roleMgr.FindByNameAsync(roleName)); } [Fact] public async Task CanFindRoleWithManager() { if (ShouldSkipDbTests()) return; var roleMgr = CreateRoleManager(); var roleName = "findRoleTest" + Guid.NewGuid(); var role = CreateTestRole(roleName, true); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); Assert.Equal(roleName, await roleMgr.GetRoleNameAsync(await roleMgr.FindByNameAsync(roleName))); } [Fact] public async Task SetPhoneNumberTest() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(phoneNumber: "123-456-7890"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); Assert.Equal("123-456-7890", await manager.GetPhoneNumberAsync(user)); IdentityResultAssert.IsSuccess(await manager.SetPhoneNumberAsync(user, "111-111-1111")); Assert.Equal("111-111-1111", await manager.GetPhoneNumberAsync(user)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CanChangePhoneNumber() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(phoneNumber: "123-456-7890"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.False(await manager.IsPhoneNumberConfirmedAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); var token1 = await manager.GenerateChangePhoneNumberTokenAsync(user, "111-111-1111"); IdentityResultAssert.IsSuccess(await manager.ChangePhoneNumberAsync(user, "111-111-1111", token1)); Assert.True(await manager.IsPhoneNumberConfirmedAsync(user)); Assert.Equal("111-111-1111", await manager.GetPhoneNumberAsync(user)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task ChangePhoneNumberFailsWithWrongToken() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(phoneNumber: "123-456-7890"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.False(await manager.IsPhoneNumberConfirmedAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); IdentityResultAssert.IsFailure(await manager.ChangePhoneNumberAsync(user, "111-111-1111", "bogus"), "Invalid token."); #if !NETSTANDARD2_0 // has other messages IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyChangePhoneNumberTokenAsync() failed for user {await manager.GetUserIdAsync(user)}."); #endif Assert.False(await manager.IsPhoneNumberConfirmedAsync(user)); Assert.Equal("123-456-7890", await manager.GetPhoneNumberAsync(user)); Assert.Equal(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task ChangePhoneNumberFailsWithWrongPhoneNumber() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(phoneNumber: "123-456-7890"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.False(await manager.IsPhoneNumberConfirmedAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); var token1 = await manager.GenerateChangePhoneNumberTokenAsync(user, "111-111-1111"); IdentityResultAssert.IsFailure(await manager.ChangePhoneNumberAsync(user, "bogus", token1), "Invalid token."); Assert.False(await manager.IsPhoneNumberConfirmedAsync(user)); Assert.Equal("123-456-7890", await manager.GetPhoneNumberAsync(user)); Assert.Equal(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CanVerifyPhoneNumber() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); const string num1 = "111-123-4567"; const string num2 = "111-111-1111"; var userId = await manager.GetUserIdAsync(user); var token1 = await manager.GenerateChangePhoneNumberTokenAsync(user, num1); var token2 = await manager.GenerateChangePhoneNumberTokenAsync(user, num2); Assert.NotEqual(token1, token2); Assert.True(await manager.VerifyChangePhoneNumberTokenAsync(user, token1, num1)); Assert.True(await manager.VerifyChangePhoneNumberTokenAsync(user, token2, num2)); Assert.False(await manager.VerifyChangePhoneNumberTokenAsync(user, token2, num1)); Assert.False(await manager.VerifyChangePhoneNumberTokenAsync(user, token1, num2)); #if !NETSTANDARD2_0 // has other messages IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyChangePhoneNumberTokenAsync() failed for user {await manager.GetUserIdAsync(user)}."); #endif } [Fact] public async Task CanChangeEmail() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser("foouser"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var email = await manager.GetUserNameAsync(user) + "@diddly.bop"; IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, email)); Assert.False(await manager.IsEmailConfirmedAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); var newEmail = await manager.GetUserNameAsync(user) + "@en.vec"; var token1 = await manager.GenerateChangeEmailTokenAsync(user, newEmail); IdentityResultAssert.IsSuccess(await manager.ChangeEmailAsync(user, newEmail, token1)); Assert.True(await manager.IsEmailConfirmedAsync(user)); Assert.Equal(await manager.GetEmailAsync(user), newEmail); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task CanChangeEmailWithDifferentTokenProvider() { if (ShouldSkipDbTests()) return; var manager = CreateManager(null, null, s => s.Configure<IdentityOptions>( o => o.Tokens.ProviderMap["NewProvider2"] = new TokenProviderDescriptor(typeof(EmailTokenProvider<TUser>)))); manager.Options.Tokens.ChangeEmailTokenProvider = "NewProvider2"; var user = CreateTestUser("foouser"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var email = await manager.GetUserNameAsync(user) + "@diddly.bop"; IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, email)); Assert.False(await manager.IsEmailConfirmedAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); var newEmail = await manager.GetUserNameAsync(user) + "@en.vec"; var token1 = await manager.GenerateChangeEmailTokenAsync(user, newEmail); IdentityResultAssert.IsSuccess(await manager.ChangeEmailAsync(user, newEmail, token1)); Assert.True(await manager.IsEmailConfirmedAsync(user)); Assert.Equal(await manager.GetEmailAsync(user), newEmail); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task ChangeEmailFailsWithWrongToken() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser("foouser"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var email = await manager.GetUserNameAsync(user) + "@diddly.bop"; IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, email)); var oldEmail = email; Assert.False(await manager.IsEmailConfirmedAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); IdentityResultAssert.IsFailure(await manager.ChangeEmailAsync(user, "whatevah@foo.barf", "bogus"), "Invalid token."); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: ChangeEmail:whatevah@foo.barf for user {await manager.GetUserIdAsync(user)}."); Assert.False(await manager.IsEmailConfirmedAsync(user)); Assert.Equal(await manager.GetEmailAsync(user), oldEmail); Assert.Equal(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task ChangeEmailFailsWithEmail() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser("foouser"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var email = await manager.GetUserNameAsync(user) + "@diddly.bop"; IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, email)); var oldEmail = email; Assert.False(await manager.IsEmailConfirmedAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); var token1 = await manager.GenerateChangeEmailTokenAsync(user, "forgot@alrea.dy"); IdentityResultAssert.IsFailure(await manager.ChangeEmailAsync(user, "oops@foo.barf", token1), "Invalid token."); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyUserTokenAsync() failed with purpose: ChangeEmail:oops@foo.barf for user {await manager.GetUserIdAsync(user)}."); Assert.False(await manager.IsEmailConfirmedAsync(user)); Assert.Equal(await manager.GetEmailAsync(user), oldEmail); Assert.Equal(stamp, await manager.GetSecurityStampAsync(user)); } [Fact] public async Task EmailFactorFailsAfterSecurityStampChangeTest() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var factorId = "Email"; //default var user = CreateTestUser("foouser"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var email = await manager.GetUserNameAsync(user) + "@diddly.bop"; IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, email)); var token = await manager.GenerateEmailConfirmationTokenAsync(user); await manager.ConfirmEmailAsync(user, token); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); token = await manager.GenerateTwoFactorTokenAsync(user, factorId); Assert.NotNull(token); IdentityResultAssert.IsSuccess(await manager.UpdateSecurityStampAsync(user)); Assert.False(await manager.VerifyTwoFactorTokenAsync(user, factorId, token)); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyTwoFactorTokenAsync() failed for user {await manager.GetUserIdAsync(user)}."); } [Fact] public async Task EnableTwoFactorChangesSecurityStamp() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); IdentityResultAssert.IsSuccess(await manager.SetTwoFactorEnabledAsync(user, true)); Assert.NotEqual(stamp, await manager.GetSecurityStampAsync(user)); Assert.True(await manager.GetTwoFactorEnabledAsync(user)); } [Fact] public async Task GenerateTwoFactorWithUnknownFactorProviderWillThrow() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); const string error = "No IUserTwoFactorTokenProvider<TUser> named 'bogus' is registered."; await ExceptionAssert.ThrowsAsync<NotSupportedException>( () => manager.GenerateTwoFactorTokenAsync(user, "bogus"), error); await ExceptionAssert.ThrowsAsync<NotSupportedException>( () => manager.VerifyTwoFactorTokenAsync(user, "bogus", "bogus"), error); } [Fact] public async Task GetValidTwoFactorTestEmptyWithNoProviders() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var factors = await manager.GetValidTwoFactorProvidersAsync(user); Assert.NotNull(factors); Assert.True(!factors.Any()); } [Fact] public async Task CanGetSetUpdateAndRemoveUserToken() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.Null(await manager.GetAuthenticationTokenAsync(user, "provider", "name")); IdentityResultAssert.IsSuccess(await manager.SetAuthenticationTokenAsync(user, "provider", "name", "value")); Assert.Equal("value", await manager.GetAuthenticationTokenAsync(user, "provider", "name")); IdentityResultAssert.IsSuccess(await manager.SetAuthenticationTokenAsync(user, "provider", "name", "value2")); Assert.Equal("value2", await manager.GetAuthenticationTokenAsync(user, "provider", "name")); IdentityResultAssert.IsSuccess(await manager.RemoveAuthenticationTokenAsync(user, "whatevs", "name")); Assert.Equal("value2", await manager.GetAuthenticationTokenAsync(user, "provider", "name")); IdentityResultAssert.IsSuccess(await manager.RemoveAuthenticationTokenAsync(user, "provider", "name")); Assert.Null(await manager.GetAuthenticationTokenAsync(user, "provider", "name")); } [Fact] public async Task CanGetValidTwoFactor() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var userId = await manager.GetUserIdAsync(user); var factors = await manager.GetValidTwoFactorProvidersAsync(user); Assert.NotNull(factors); Assert.False(factors.Any()); IdentityResultAssert.IsSuccess(await manager.SetPhoneNumberAsync(user, "111-111-1111")); var token = await manager.GenerateChangePhoneNumberTokenAsync(user, "111-111-1111"); IdentityResultAssert.IsSuccess(await manager.ChangePhoneNumberAsync(user, "111-111-1111", token)); await manager.UpdateAsync(user); factors = await manager.GetValidTwoFactorProvidersAsync(user); Assert.NotNull(factors); Assert.Single(factors); Assert.Equal("Phone", factors[0]); IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, "test@test.com")); token = await manager.GenerateEmailConfirmationTokenAsync(user); await manager.ConfirmEmailAsync(user, token); factors = await manager.GetValidTwoFactorProvidersAsync(user); Assert.NotNull(factors); Assert.Equal(2, factors.Count()); IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, null)); factors = await manager.GetValidTwoFactorProvidersAsync(user); Assert.NotNull(factors); Assert.Single(factors); Assert.Equal("Phone", factors[0]); } [Fact] public async Task PhoneFactorFailsAfterSecurityStampChangeTest() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var factorId = "Phone"; // default var user = CreateTestUser(phoneNumber: "4251234567"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var stamp = await manager.GetSecurityStampAsync(user); Assert.NotNull(stamp); var token = await manager.GenerateTwoFactorTokenAsync(user, factorId); Assert.NotNull(token); IdentityResultAssert.IsSuccess(await manager.UpdateSecurityStampAsync(user)); Assert.False(await manager.VerifyTwoFactorTokenAsync(user, factorId, token)); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyTwoFactorTokenAsync() failed for user {await manager.GetUserIdAsync(user)}."); } [Fact] public async Task VerifyTokenFromWrongTokenProviderFails() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(phoneNumber: "4251234567"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var token = await manager.GenerateTwoFactorTokenAsync(user, "Phone"); Assert.NotNull(token); Assert.False(await manager.VerifyTwoFactorTokenAsync(user, "Email", token)); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyTwoFactorTokenAsync() failed for user {await manager.GetUserIdAsync(user)}."); } [Fact] public async Task VerifyWithWrongSmsTokenFails() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); var user = CreateTestUser(phoneNumber: "4251234567"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); Assert.False(await manager.VerifyTwoFactorTokenAsync(user, "Phone", "bogus")); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"VerifyTwoFactorTokenAsync() failed for user {await manager.GetUserIdAsync(user)}."); } [Fact] public async Task NullableDateTimeOperationTest() { if (ShouldSkipDbTests()) return; var userMgr = CreateManager(); var user = CreateTestUser(lockoutEnabled: true); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); Assert.Null(await userMgr.GetLockoutEndDateAsync(user)); // set LockoutDateEndDate to null await userMgr.SetLockoutEndDateAsync(user, null); Assert.Null(await userMgr.GetLockoutEndDateAsync(user)); // set to a valid value await userMgr.SetLockoutEndDateAsync(user, DateTimeOffset.Parse("01/01/2014")); Assert.Equal(DateTimeOffset.Parse("01/01/2014"), await userMgr.GetLockoutEndDateAsync(user)); } [ConditionalFact] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Fails due to threading bugs in Mono")] public async Task CanGetUsersWithClaims() { if (ShouldSkipDbTests()) return; var manager = CreateManager(); for (var i = 0; i < 6; i++) { var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); if (i % 2 == 0) IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, new Claim("foo", "bar"))); } Assert.Equal(3, (await manager.GetUsersForClaimAsync(new Claim("foo", "bar"))).Count); Assert.Equal(0, (await manager.GetUsersForClaimAsync(new Claim("123", "456"))).Count); } [ConditionalFact] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Fails due to threading bugs in Mono")] public async Task CanGetUsersInRole() { if (ShouldSkipDbTests()) return; var context = CreateTestContext(); var manager = CreateManager(context); var roleManager = CreateRoleManager(context); var roles = GenerateRoles("UsersInRole", 4); var roleNameList = new List<string>(); foreach (var role in roles) { IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(role)); roleNameList.Add(await roleManager.GetRoleNameAsync(role)); } for (var i = 0; i < 6; i++) { var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); if (i % 2 == 0) IdentityResultAssert.IsSuccess(await manager.AddToRolesAsync(user, roleNameList)); } foreach (var role in roles) Assert.Equal(3, (await manager.GetUsersInRoleAsync(await roleManager.GetRoleNameAsync(role))).Count); Assert.Equal(0, (await manager.GetUsersInRoleAsync("123456")).Count); } public List<TUser> GenerateUsers(string userNamePrefix, int count) { var users = new List<TUser>(count); for (var i = 0; i < count; i++) users.Add(CreateTestUser(userNamePrefix + i)); return users; } public List<TRole> GenerateRoles(string namePrefix, int count) { var roles = new List<TRole>(count); for (var i = 0; i < count; i++) roles.Add(CreateTestRole(namePrefix + i)); return roles; } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace pattern_cutter.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
// // DO NOT MODIFY! THIS IS AUTOGENERATED FILE! // namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; // Role: PROXY public sealed unsafe partial class CefResponse : IDisposable { internal static CefResponse FromNative(cef_response_t* ptr) { return new CefResponse(ptr); } internal static CefResponse FromNativeOrNull(cef_response_t* ptr) { if (ptr == null) return null; return new CefResponse(ptr); } private cef_response_t* _self; private CefResponse(cef_response_t* ptr) { if (ptr == null) throw new ArgumentNullException("ptr"); _self = ptr; } ~CefResponse() { if (_self != null) { Release(); _self = null; } } public void Dispose() { if (_self != null) { Release(); _self = null; } GC.SuppressFinalize(this); } internal int AddRef() { return cef_response_t.add_ref(_self); } internal int Release() { return cef_response_t.release(_self); } internal int RefCt { get { return cef_response_t.get_refct(_self); } } internal cef_response_t* ToNative() { AddRef(); return _self; } } }
using System; using Argotic.Common; using Argotic.Syndication.Specialized; namespace Argotic.Examples { /// <summary> /// Contains the code examples for the <see cref="RsdApplicationInterface"/> class. /// </summary> /// <remarks> /// This class contains all of the code examples that are referenced by the <see cref="RsdApplicationInterface"/> class. /// The code examples are imported using the unique #region identifier that matches the method or entity that the sample code describes. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rsd")] public static class RsdApplicationInterfaceExample { /// <summary> /// Provides example code for the RsdApplicationInterface class. /// </summary> public static void ClassExample() { RsdDocument document = new RsdDocument(); document.EngineName = "Blog Munging CMS"; document.EngineLink = new Uri("http://www.blogmunging.com/"); document.Homepage = new Uri("http://www.userdomain.com/"); // Identify supported services using well known names document.AddInterface(new RsdApplicationInterface("MetaWeblog", new Uri("http://example.com/xml/rpc/url"), true, "123abc")); document.AddInterface(new RsdApplicationInterface("Blogger", new Uri("http://example.com/xml/rpc/url"), false, "123abc")); document.AddInterface(new RsdApplicationInterface("MetaWiki", new Uri("http://example.com/some/other/url"), false, "123abc")); document.AddInterface(new RsdApplicationInterface("Antville", new Uri("http://example.com/yet/another/url"), false, "123abc")); RsdApplicationInterface conversantApi = new RsdApplicationInterface("Conversant", new Uri("http://example.com/xml/rpc/url"), false, String.Empty); conversantApi.Documentation = new Uri("http://www.conversant.com/docs/api/"); conversantApi.Notes = "Additional explanation here."; conversantApi.Settings.Add("service-specific-setting", "a value"); conversantApi.Settings.Add("another-setting", "another value"); document.AddInterface(conversantApi); } } }
using System; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using Android.App; using Firebase.Iid; using Toggl.Core.Extensions; using Toggl.Shared.Extensions; namespace Toggl.Droid.Services { [Service] [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })] public class TogglFirebaseIIDService : FirebaseInstanceIdService { private CompositeDisposable disposeBag = new CompositeDisposable(); public override void OnTokenRefresh() { AndroidDependencyContainer.EnsureInitialized(Application.Context); var dependencyContainer = AndroidDependencyContainer.Instance; registerTokenIfNecessary(dependencyContainer); } private void registerTokenIfNecessary(AndroidDependencyContainer dependencyContainer) { var userLoggedIn = dependencyContainer.UserAccessManager.CheckIfLoggedIn(); if (!userLoggedIn) return; var shouldBeSubscribedToPushNotifications = dependencyContainer .RemoteConfigService .GetPushNotificationsConfiguration() .RegisterPushNotificationsTokenWithServer; if (!shouldBeSubscribedToPushNotifications) return; dependencyContainer.InteractorFactory.SubscribeToPushNotifications() .Execute() .ObserveOn(dependencyContainer.SchedulerProvider.BackgroundScheduler) .Subscribe(_ => StopSelf()) .DisposedBy(disposeBag); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (!disposing) return; disposeBag?.Dispose(); } } }
@model HRM.Models.Employee @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm("Edit","Employees",FormMethod.Post, new { enctype = "multipart/form-data"})) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Employee</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.Id) <div class="form-group"> @Html.LabelFor(model => model.EmployeeCode, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.EmployeeCode, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.EmployeeCode, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.NickName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.NickName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.NickName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.MobileNumber, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.MobileNumber, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.MobileNumber, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.FatherName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.FatherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FatherName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.MotherName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.MotherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.MotherName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.DesignationId, "DesignationId", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("DesignationId", null, htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.DesignationId, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.BloodGroup, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.BloodGroup, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BloodGroup, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.DeptId, "DeptId", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("DeptId", null, htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.DeptId, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @*@Html.LabelFor("Employee Photo", htmlAttributes: new { @class = "control-label col-md-2" })*@ <label class="control-label col-md-2">Employee Photo</label> <div class="col-md-10"> <div style="height:200px; width:200px; overflow:auto;"> <img id="imgEmpPhoto" src="@Model.EmployeePhotoPath.TrimStart('~')" alt="Employee Image"> </div> </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmployeePhotoPath, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <input type="file" id="EmployeePhoto" name="EmployeePhoto" /> </div> </div> @Html.HiddenFor(model => model.EmployeePhotoPath) <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script type="text/javascript"> //Display any size into 200 px X 200 px $(document).ready(function () { $('#imgEmpPhoto').css({ 'height': '200px', 'width': '200px' }); }); //Read input file and display in a image tag function readFile(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#imgEmpPhoto').attr('src', ""); var img = $('#imgEmpPhoto').attr('src', e.target.result).width(200).height(200); } reader.readAsDataURL(input.files[0]); } } $('#EmployeePhoto').change(function () { readFile(this); }); </script> }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AngularAppWeb.Models { public class RtcIceServer { public string Urls { get; set; } = "stun:stun1.l.google.com:19302"; public string Username { get; set; } public string Credential { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; using Verse.AI; namespace Hobbits { public class JobDriver_SolvePuzzle : JobDriver { private const TargetIndex PuzzleBoxInd = TargetIndex.A; private const TargetIndex joySpot = TargetIndex.B; private Thing PuzzleBox => job.GetTarget(TargetIndex.A).Thing; public override bool TryMakePreToilReservations(bool yeaaa) { return pawn.Reserve(PuzzleBox, job); } protected override IEnumerable<Toil> MakeNewToils() { yield return Toils_Goto.GotoThing(PuzzleBoxInd, PathEndMode.ClosestTouch) .FailOnDespawnedNullOrForbidden(PuzzleBoxInd); yield return Toils_Ingest.PickupIngestible(PuzzleBoxInd, pawn); yield return CarryPuzzleToSpot(pawn, PuzzleBoxInd); yield return Toils_Ingest.FindAdjacentEatSurface(joySpot, PuzzleBoxInd); var puzzle = new Toil { tickAction = WaitTickAction() }; puzzle.AddFinishAction(() => { JoyUtility.TryGainRecRoomThought(pawn); RollForLuck(); }); puzzle.defaultCompleteMode = ToilCompleteMode.Delay; puzzle.defaultDuration = job.def.joyDuration; puzzle.handlingFacing = true; yield return puzzle; } protected void RollForLuck() { var extraLuckFromQuality = TargetThingA.GetStatValue(StatDefOf.JoyGainFactor); float extraLuckFromHobbitSmarts = pawn.skills.GetSkill(SkillDefOf.Intellectual).levelInt; var yourLuckyNumber = (1f + extraLuckFromHobbitSmarts) * extraLuckFromQuality / 100; Log.Message("lucky number is: " + yourLuckyNumber); if (!Rand.Chance(yourLuckyNumber) && !DebugSettings.godMode) { return; } var reward = ThingMaker.MakeThing(ThingDefOf.Gold); reward.stackCount = Rand.RangeInclusive(10, 50); GenSpawn.Spawn(reward, pawn.Position, pawn.Map); PuzzleBox.Destroy(); Letter letter = LetterMaker.MakeLetter("LotRH_PuzzleSolvedLabel".Translate(), "LotRH_PuzzleSolved".Translate(pawn.Label, reward.Label), LetterDefOf.PositiveEvent); Find.LetterStack.ReceiveLetter(letter); } protected Action WaitTickAction() { return delegate { pawn.rotationTracker.FaceCell(TargetB.Cell); pawn.GainComfortFromCellIfPossible(); var extraJoyGainFactor = TargetThingA.GetStatValue(StatDefOf.JoyGainFactor); JoyUtility.JoyTickCheckEnd(pawn, JoyTickFullJoyAction.EndJob, extraJoyGainFactor); }; } //slightly modified version of Toils_Ingest.CarryIngestibleToChewSpot public static Toil CarryPuzzleToSpot(Pawn pawn, TargetIndex puzzleInd) { var toil = new Toil(); toil.initAction = delegate { var actor = toil.actor; var intVec = IntVec3.Invalid; var thing2 = actor.CurJob.GetTarget(puzzleInd).Thing; bool baseChairValidator(Thing t) { if (t.def.building == null || !t.def.building.isSittable) { return false; } if (t.IsForbidden(pawn)) { return false; } if (!actor.CanReserve(t)) { return false; } if (!t.IsSociallyProper(actor)) { return false; } if (t.IsBurning()) { return false; } if (t.HostileTo(pawn)) { return false; } var result = false; for (var i = 0; i < 4; i++) { var c = t.Position + GenAdj.CardinalDirections[i]; var edifice = c.GetEdifice(t.Map); if (edifice == null || edifice.def.surfaceType != SurfaceType.Eat) { continue; } result = true; break; } return result; } //if you can find a table with chair, great. If not, go to your room. var thing = GenClosest.ClosestThingReachable(actor.Position, actor.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.OnCell, TraverseParms.For(actor), 30f, //"chair search radius" t => baseChairValidator(t) && t.Position.GetDangerFor(pawn, t.Map) == Danger.None); if (thing == null) { if (pawn.ownership?.OwnedRoom != null) { (from c in pawn.ownership.OwnedRoom.Cells where c.Standable(pawn.Map) && !c.IsForbidden(pawn) && pawn.CanReserveAndReach(c, PathEndMode.OnCell, Danger.None) select c).TryRandomElement(out intVec); } } if (thing != null) { intVec = thing.Position; actor.Reserve(thing, actor.CurJob); } if (intVec == IntVec3.Invalid) { intVec = RCellFinder.SpotToChewStandingNear(pawn, thing2); } actor.Map.pawnDestinationReservationManager.Reserve(actor, actor.CurJob, intVec); actor.pather.StartPath(intVec, PathEndMode.OnCell); }; toil.defaultCompleteMode = ToilCompleteMode.PatherArrival; return toil; } //public override bool ModifyCarriedThingDrawPos(ref Vector3 drawPos, ref bool behind, ref bool flip) //{ // return base.ModifyCarriedThingDrawPos(ref drawPos, ref behind, ref flip); //} } }
using System.Text.Json; namespace Amazon.Metadata.Tests; public sealed class InstanceIdentityTests { [Fact] public void Parse() { // From: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html string json = @"{ ""devpayProductCodes"" : null, ""marketplaceProductCodes"" : [ ""1abc2defghijklm3nopqrs4tu"" ], ""availabilityZone"" : ""us-west-2b"", ""privateIp"" : ""10.158.112.84"", ""version"" : ""2017-09-30"", ""instanceId"" : ""i-1234567890abcdef0"", ""billingProducts"" : null, ""instanceType"" : ""t2.micro"", ""accountId"" : ""123456789012"", ""imageId"" : ""ami-5fb8c835"", ""pendingTime"" : ""2016-11-19T16:32:11Z"", ""architecture"" : ""x86_64"", ""kernelId"" : null, ""ramdiskId"" : null, ""region"" : ""us-west-2"" }"; var result = JsonSerializer.Deserialize<InstanceIdentity>(json); Assert.Null(result.KernelId); Assert.Equal("i-1234567890abcdef0", result.InstanceId); Assert.Equal("t2.micro", result.InstanceType); Assert.Equal("123456789012", result.AccountId); Assert.Equal("ami-5fb8c835", result.ImageId); Assert.Equal("10.158.112.84", result.PrivateIp); } }
using BattleMech.DataLayer.PCL.Models.Users; using BattleMech.WebAPI.Managers; using BattleMech.WebAPI.PCL.Transports.Common; namespace BattleMech.WebAPI.Controllers { public class UsersController : BaseController { public CTI<bool> PUT(Users user) { return new UserManager().AddUser(user); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Rawr { public partial class FormItemSelection : Form { private Character _character; public Character Character { get { return _character; } set { if (_character != null) { _character.CalculationsInvalidated -= new EventHandler(_character_ItemsChanged); } _character = value; _characterSlot = CharacterSlot.None; if (_character != null) { _character.CalculationsInvalidated += new EventHandler(_character_ItemsChanged); } } } private CharacterCalculationsBase _currentCalculations; public CharacterCalculationsBase CurrentCalculations { get { return _currentCalculations; } set { _currentCalculations = value; } } private ComparisonCalculationBase[] _itemCalculations; public ComparisonCalculationBase[] ItemCalculations { get { return _itemCalculations; } set { if (value == null) { _itemCalculations = new ComparisonCalculationBase[0]; } else { List<ComparisonCalculationBase> calcs = new List<ComparisonCalculationBase>(value); calcs.Sort(new System.Comparison<ComparisonCalculationBase>(CompareItemCalculations)); _itemCalculations = calcs.ToArray(); } RebuildItemList(); } } private ComparisonGraph.ComparisonSort _sort = ComparisonGraph.ComparisonSort.Overall; public ComparisonGraph.ComparisonSort Sort { get { return _sort; } set { _sort = value; ItemCalculations = ItemCalculations; } } protected int CompareItemCalculations(ComparisonCalculationBase a, ComparisonCalculationBase b) { if (Sort == ComparisonGraph.ComparisonSort.Overall) return a.OverallPoints.CompareTo(b.OverallPoints); else if (Sort == ComparisonGraph.ComparisonSort.Alphabetical) return b.Name.CompareTo(a.Name); else return a.SubPoints[(int)Sort].CompareTo(b.SubPoints[(int)Sort]); } public FormItemSelection() { InitializeComponent(); overallToolStripMenuItem.Tag = -1; alphabeticalToolStripMenuItem.Tag = -2; Calculations_ModelChanged(null, null); this.Activated += new EventHandler(FormItemSelection_Activated); ItemCache.Instance.ItemsChanged += new EventHandler(ItemCache_ItemsChanged); Calculations.ModelChanged += new EventHandler(Calculations_ModelChanged); } void Calculations_ModelChanged(object sender, EventArgs e) { _characterSlot = CharacterSlot.None; sortToolStripMenuItem_Click(overallToolStripMenuItem, EventArgs.Empty); toolStripDropDownButtonSort.DropDownItems.Clear(); toolStripDropDownButtonSort.DropDownItems.Add(overallToolStripMenuItem); toolStripDropDownButtonSort.DropDownItems.Add(alphabeticalToolStripMenuItem); foreach (string name in Calculations.SubPointNameColors.Keys) { ToolStripMenuItem toolStripMenuItemSubPoint = new ToolStripMenuItem(name); toolStripMenuItemSubPoint.Tag = toolStripDropDownButtonSort.DropDownItems.Count - 2; toolStripMenuItemSubPoint.Click += new System.EventHandler(this.sortToolStripMenuItem_Click); toolStripDropDownButtonSort.DropDownItems.Add(toolStripMenuItemSubPoint); } } void ItemCache_ItemsChanged(object sender, EventArgs e) { CharacterSlot characterSlot = _characterSlot; _characterSlot = CharacterSlot.None; LoadItemsBySlot(characterSlot); } void _character_ItemsChanged(object sender, EventArgs e) { _characterSlot = CharacterSlot.None; } void FormItemSelection_Activated(object sender, EventArgs e) { panelItems.AutoScrollPosition = new Point(0, 0); } private void CheckToHide(object sender, EventArgs e) { if (Visible) { ItemToolTip.Instance.Hide(this); this.Hide(); } } private void timerForceActivate_Tick(object sender, System.EventArgs e) { this.timerForceActivate.Enabled = false; this.Activate(); } public void ForceShow() { this.timerForceActivate.Enabled = true; } public void Show(ItemButton button, CharacterSlot slot) { _button = button; if (_buttonEnchant != null) { _characterSlot = CharacterSlot.None; _buttonEnchant = null; } this.SetAutoLocation(button); this.LoadItemsBySlot(slot); base.Show(); } public void Show(ItemButtonWithEnchant button, CharacterSlot slot) { _buttonEnchant = button; if (_button != null) { _characterSlot = CharacterSlot.None; _button = null; } this.SetAutoLocation(button); this.LoadEnchantsBySlot(slot); base.Show(); } public void SetAutoLocation(Control ctrl) { Point ctrlScreen = ctrl.Parent.PointToScreen(ctrl.Location); Point location = new Point(ctrlScreen.X + ctrl.Width, ctrlScreen.Y); Rectangle workingArea = System.Windows.Forms.Screen.GetWorkingArea(ctrl.Parent); if (location.X < workingArea.Left) location.X = workingArea.Left; if (location.Y < workingArea.Top) location.Y = workingArea.Top; if (location.X + this.Width > workingArea.Right) location.X = ctrlScreen.X - this.Width; if (location.Y + this.Height > workingArea.Bottom) location.Y = workingArea.Bottom - this.Height; this.Location = location; } private void sortToolStripMenuItem_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; ComparisonGraph.ComparisonSort sort = ComparisonGraph.ComparisonSort.Overall; foreach (ToolStripItem item in toolStripDropDownButtonSort.DropDownItems) { if (item is ToolStripMenuItem) { (item as ToolStripMenuItem).Checked = item == sender; if ((item as ToolStripMenuItem).Checked) { toolStripDropDownButtonSort.Text = item.Text; sort = (ComparisonGraph.ComparisonSort)((int)item.Tag); } } } this.Sort = sort;//(ComparisonGraph.ComparisonSort)Enum.Parse(typeof(ComparisonGraph.ComparisonSort), toolStripDropDownButtonSort.Text); this.Cursor = Cursors.Default; } private CharacterSlot _characterSlot = CharacterSlot.None; private ItemButton _button; private ItemButtonWithEnchant _buttonEnchant; public void LoadItemsBySlot(CharacterSlot slot) { if (_characterSlot != slot) { _characterSlot = slot; List<ComparisonCalculationBase> itemCalculations = new List<ComparisonCalculationBase>(); if ((int)slot >= 0 && (int)slot <= 20) { if (this.Character != null) { bool seenEquippedItem = Character[slot] == null; foreach (ItemInstance item in Character.GetRelevantItemInstances(slot)) { if (!seenEquippedItem && Character[slot].Equals(item)) seenEquippedItem = true; if (item.Item.FitsInSlot(slot, Character)) { itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, slot)); } } if (!seenEquippedItem) { itemCalculations.Add(Calculations.GetItemCalculations(Character[slot], this.Character, slot)); } } ComparisonCalculationBase emptyCalcs = Calculations.CreateNewComparisonCalculation(); emptyCalcs.Name = "Empty"; emptyCalcs.Item = new Item(); emptyCalcs.Item.Name = "Empty"; emptyCalcs.ItemInstance = new ItemInstance(); emptyCalcs.ItemInstance.Id = -1; emptyCalcs.Equipped = this.Character[slot] == null; itemCalculations.Add(emptyCalcs); } else { if (this.Character != null) { bool seenEquippedItem = false; if (_button != null && _button.SelectedItem == null) { seenEquippedItem = true; } foreach (Item item in Character.GetRelevantItems(slot)) { if (!seenEquippedItem && _button != null && item.Equals(_button.SelectedItem)) seenEquippedItem = true; if (item.FitsInSlot(slot, Character)) { if(slot == CharacterSlot.Gems) AddGemToItemCalculations(itemCalculations, item); else itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, slot)); } } if (!seenEquippedItem && _button != null && _button.SelectedItem != null) { itemCalculations.Add(Calculations.GetItemCalculations(_button.SelectedItem, this.Character, slot)); } } ComparisonCalculationBase emptyCalcs = Calculations.CreateNewComparisonCalculation(); emptyCalcs.Name = "Empty"; emptyCalcs.Item = new Item(); emptyCalcs.Item.Name = "Empty"; emptyCalcs.ItemInstance = new ItemInstance(); emptyCalcs.ItemInstance.Id = -1; if (_button != null && _button.SelectedItem != null) { emptyCalcs.Equipped = _button.SelectedItem == null; } else { emptyCalcs.Equipped = false; } itemCalculations.Add(emptyCalcs); } itemCalculations.Sort(new System.Comparison<ComparisonCalculationBase>(CompareItemCalculations)); Dictionary<int, int> countItem = new Dictionary<int, int>(); List<ComparisonCalculationBase> filteredItemCalculations = new List<ComparisonCalculationBase>(); for (int i = itemCalculations.Count - 1; i >= 0; i--) //foreach (ComparisonCalculationBase itemCalculation in itemCalculations) { ComparisonCalculationBase itemCalculation = itemCalculations[i]; int itemId = (itemCalculation.ItemInstance == null ? itemCalculation.Item.Id : itemCalculation.ItemInstance.Id); if (!countItem.ContainsKey(itemId)) countItem.Add(itemId, 0); if (countItem[itemId]++ < Properties.GeneralSettings.Default.CountGemmingsShown || itemCalculation.Equipped || itemCalculation.ItemInstance.ForceDisplay) { filteredItemCalculations.Add(itemCalculation); } } ItemCalculations = filteredItemCalculations.ToArray(); } } private void AddGemToItemCalculations(List<ComparisonCalculationBase> itemCalculations, Item item) { if (item.IsJewelersGem) { if (!Rawr.Properties.GeneralSettings.Default.HideProfEnchants || this.Character.HasProfession(Profession.Jewelcrafting)) { if (Character.JewelersGemCount < 3) itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, CharacterSlot.Gems)); else { Item nullItem = item.Clone(); nullItem.Stats = new Stats(); itemCalculations.Add(Calculations.GetItemCalculations(nullItem, this.Character, CharacterSlot.Gems)); } } } else if (item.IsLimitedGem) { if (!Character.IsUniqueGemEquipped(item)) itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, CharacterSlot.Gems)); else { Item nullItem = item.Clone(); nullItem.Stats = new Stats(); itemCalculations.Add(Calculations.GetItemCalculations(nullItem, this.Character, CharacterSlot.Gems)); } } else itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, CharacterSlot.Gems)); } private void LoadEnchantsBySlot(CharacterSlot slot) { if (_characterSlot != slot) { _characterSlot = slot; List<ComparisonCalculationBase> itemCalculations = null; if (Character != null && CurrentCalculations != null) { itemCalculations = Calculations.GetEnchantCalculations(Item.GetItemSlotByCharacterSlot(slot), Character, CurrentCalculations, false); } itemCalculations.Sort(new System.Comparison<ComparisonCalculationBase>(CompareItemCalculations)); ItemCalculations = itemCalculations.ToArray(); } } private List<ItemSelectorItem> _itemSelectorItems = new List<ItemSelectorItem>(); private void RebuildItemList() { if (this.InvokeRequired) { Invoke((MethodInvoker)RebuildItemList); //InvokeHelper.Invoke(this, "RebuildItemList", null); return; } panelItems.SuspendLayout(); ////Replaced this... //while (panelItems.Controls.Count < this.ItemCalculations.Length) // panelItems.Controls.Add(new ItemSelectorItem()); //while (panelItems.Controls.Count > this.ItemCalculations.Length) // panelItems.Controls.RemoveAt(panelItems.Controls.Count - 1); ////...with this, so as not to constantly create and remove lots of controls int currentItemLength = panelItems.Controls.Count; int targetItemLength = this.ItemCalculations.Length; if (currentItemLength < targetItemLength) { int itemSelectorsToCreate = targetItemLength - _itemSelectorItems.Count; for (int i = 0; i < itemSelectorsToCreate; i++) { _itemSelectorItems.Add(new ItemSelectorItem()); } for (int i = currentItemLength; i < targetItemLength; i++) { panelItems.Controls.Add(_itemSelectorItems[i]); } } else if (currentItemLength > targetItemLength) { for (int i = currentItemLength; i > targetItemLength; i--) { panelItems.Controls.RemoveAt(i - 1); } } float maxRating = 0; for (int i = 0; i < this.ItemCalculations.Length; i++) { ItemSelectorItem ctrl = panelItems.Controls[i] as ItemSelectorItem; ComparisonCalculationBase calc = this.ItemCalculations[i]; if (_button != null) { calc.Equipped = (calc.ItemInstance == _button.SelectedItemInstance && calc.Item == _button.SelectedItem) || (calc.Item.Id == 0 && _button.SelectedItem == null); ctrl.IsEnchant = false; } if (_buttonEnchant != null) { calc.Equipped = Math.Abs(calc.Item.Id % 10000) == _buttonEnchant.SelectedEnchantId; ctrl.IsEnchant = true; } ctrl.ItemCalculation = calc; ctrl.Character = Character; ctrl.CharacterSlot = _characterSlot; ctrl.Sort = this.Sort; ctrl.HideToolTip(); bool visible = string.IsNullOrEmpty(this.toolStripTextBoxFilter.Text) || calc.Name.ToLower().Contains(this.toolStripTextBoxFilter.Text.ToLower()); ctrl.Visible = visible; if (visible) { float calcRating; if (Sort == ComparisonGraph.ComparisonSort.Overall || this.Sort == ComparisonGraph.ComparisonSort.Alphabetical) { calcRating = calc.OverallPoints; } else { calcRating = calc.SubPoints[(int)Sort]; } maxRating = Math.Max(maxRating, calcRating); } } panelItems.ResumeLayout(true); foreach (ItemSelectorItem ctrl in panelItems.Controls) { ctrl.MaxRating = maxRating; } } private void toolStripTextBoxFilter_TextChanged(object sender, EventArgs e) { RebuildItemList(); } public void Select(ItemInstance item) { if (_button != null) _button.SelectedItemInstance = item == null ? null : item.Clone(); //if (_buttonEnchant != null) //{ // ItemInstance copy = _buttonEnchant.SelectedItem.Clone(); // copy.EnchantId = item == null ? 0 : Math.Abs(item.Id % 10000); // _buttonEnchant.SelectedItem = copy; //} _characterSlot = CharacterSlot.None; ItemToolTip.Instance.Hide(this); this.Hide(); } public void Select(Item item) { if (_button != null) _button.SelectedItem = item; if (_buttonEnchant != null) { if(_buttonEnchant.SelectedItem != null) { ItemInstance copy = _buttonEnchant.SelectedItem.Clone(); copy.EnchantId = item == null ? 0 : Math.Abs(item.Id % 10000); _buttonEnchant.SelectedItem = copy; } } _characterSlot = CharacterSlot.None; ItemToolTip.Instance.Hide(this); this.Hide(); } } public interface IFormItemSelectionProvider { FormItemSelection FormItemSelection { get; } } }
namespace _31_boilerplate_api.Controllers { using System; using System.Threading.Tasks; using _31_boilerplate_api.Commands; using _31_boilerplate_api.Constants; using _31_boilerplate_api.ViewModels; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Net.Http.Headers; [Route("[controller]")] [ApiVersion("1.0")] public class CarsController : ControllerBase { private readonly Lazy<IDeleteCarCommand> deleteCarCommand; private readonly Lazy<IGetCarCommand> getCarCommand; private readonly Lazy<IGetCarPageCommand> getCarPageCommand; private readonly Lazy<IPatchCarCommand> patchCarCommand; private readonly Lazy<IPostCarCommand> postCarCommand; private readonly Lazy<IPutCarCommand> putCarCommand; public CarsController( Lazy<IDeleteCarCommand> deleteCarCommand, Lazy<IGetCarCommand> getCarCommand, Lazy<IGetCarPageCommand> getCarPageCommand, Lazy<IPatchCarCommand> patchCarCommand, Lazy<IPostCarCommand> postCarCommand, Lazy<IPutCarCommand> putCarCommand) { this.deleteCarCommand = deleteCarCommand; this.getCarCommand = getCarCommand; this.getCarPageCommand = getCarPageCommand; this.patchCarCommand = patchCarCommand; this.postCarCommand = postCarCommand; this.putCarCommand = putCarCommand; } /// <summary> /// Returns an Allow HTTP header with the allowed HTTP methods. /// </summary> /// <returns>A 200 OK response.</returns> /// <response code="200">The allowed HTTP methods.</response> [HttpOptions] public IActionResult Options() { this.HttpContext.Response.Headers.AppendCommaSeparatedValues( HeaderNames.Allow, HttpMethods.Get, HttpMethods.Head, HttpMethods.Options, HttpMethods.Post); return this.Ok(); } /// <summary> /// Returns an Allow HTTP header with the allowed HTTP methods for a car with the specified unique identifier. /// </summary> /// <returns>A 200 OK response.</returns> /// <response code="200">The allowed HTTP methods.</response> [HttpOptions("{carId}")] public IActionResult Options(int carId) { this.HttpContext.Response.Headers.AppendCommaSeparatedValues( HeaderNames.Allow, HttpMethods.Delete, HttpMethods.Get, HttpMethods.Head, HttpMethods.Options, HttpMethods.Patch, HttpMethods.Post, HttpMethods.Put); return this.Ok(); } /// <summary> /// Deletes the car with the specified ID. /// </summary> /// <param name="carId">The car ID.</param> /// <returns>A 204 No Content response if the car was deleted or a 404 Not Found if a car with the specified ID /// was not found.</returns> /// <response code="204">The car with the specified ID was deleted.</response> /// <response code="404">A car with the specified ID was not found.</response> [HttpDelete("{carId}", Name = CarsControllerRoute.DeleteCar)] [ProducesResponseType(typeof(void), StatusCodes.Status204NoContent)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public Task<IActionResult> Delete(int carId) => this.deleteCarCommand.Value.ExecuteAsync(carId); /// <summary> /// Gets the car with the specified ID. /// </summary> /// <param name="carId">The car ID.</param> /// <returns>A 200 OK response containing the car or a 404 Not Found if a car with the specified ID was not /// found.</returns> /// <response code="200">The car with the specified ID.</response> /// <response code="304">The car has not changed since the date given in the If-Modified-Since HTTP header.</response> /// <response code="404">A car with the specified ID could not be found.</response> [HttpGet("{carId}", Name = CarsControllerRoute.GetCar)] [HttpHead("{carId}")] [ProducesResponseType(typeof(Car), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status304NotModified)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public Task<IActionResult> Get(int carId) => this.getCarCommand.Value.ExecuteAsync(carId); /// <summary> /// Gets a collection of cars using the specified page number and number of items per page. /// </summary> /// <param name="pageOptions">The page options.</param> /// <returns>A 200 OK response containing a collection of cars, a 400 Bad Request if the page request /// parameters are invalid or a 404 Not Found if a page with the specified page number was not found. /// </returns> /// <response code="200">A collection of cars for the specified page.</response> /// <response code="400">The page request parameters are invalid.</response> /// <response code="404">A page with the specified page number was not found.</response> [HttpGet("", Name = CarsControllerRoute.GetCarPage)] [HttpHead("")] [ProducesResponseType(typeof(PageResult<Car>), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public Task<IActionResult> GetPage([FromQuery] PageOptions pageOptions) => this.getCarPageCommand.Value.ExecuteAsync(pageOptions); /// <summary> /// Patches the car with the specified ID. /// </summary> /// <param name="carId">The car ID.</param> /// <param name="patch">The patch document. See http://jsonpatch.com/.</param> /// <returns>A 200 OK if the car was patched, a 400 Bad Request if the patch was invalid or a 404 Not Found /// if a car with the specified ID was not found.</returns> /// <response code="200">The patched car with the specified ID.</response> /// <response code="400">The patch document is invalid.</response> /// <response code="404">A car with the specified ID could not be found.</response> [HttpPatch("{carId}", Name = CarsControllerRoute.PatchCar)] [ProducesResponseType(typeof(Car), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public Task<IActionResult> Patch(int carId, [FromBody] JsonPatchDocument<SaveCar> patch) => this.patchCarCommand.Value.ExecuteAsync(carId, patch); /// <summary> /// Creates a new car. /// </summary> /// <param name="car">The car to create.</param> /// <returns>A 201 Created response containing the newly created car or a 400 Bad Request if the car is /// invalid.</returns> /// <response code="201">The car was created.</response> /// <response code="400">The car is invalid.</response> [HttpPost("", Name = CarsControllerRoute.PostCar)] [ProducesResponseType(typeof(Car), StatusCodes.Status201Created)] [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status400BadRequest)] public Task<IActionResult> Post([FromBody] SaveCar car) => this.postCarCommand.Value.ExecuteAsync(car); /// <summary> /// Updates an existing car with the specified ID. /// </summary> /// <param name="carId">The car identifier.</param> /// <param name="car">The car to update.</param> /// <returns>A 200 OK response containing the newly updated car, a 400 Bad Request if the car is invalid or a /// or a 404 Not Found if a car with the specified ID was not found.</returns> /// <response code="200">The car was updated.</response> /// <response code="400">The car is invalid.</response> /// <response code="404">A car with the specified ID could not be found.</response> [HttpPut("{carId}", Name = CarsControllerRoute.PutCar)] [ProducesResponseType(typeof(Car), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public Task<IActionResult> Put(int carId, [FromBody] SaveCar car) => this.putCarCommand.Value.ExecuteAsync(carId, car); } }
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-Toolkit-Suite-NET-Core) // Version 5.500.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Diagnostics; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Provide inheritance of palette ribbon background properties from source redirector. /// </summary> public class PaletteRibbonBackInheritRedirect : PaletteRibbonBackInherit { #region Instance Fields private PaletteRedirect _redirect; #endregion #region Identity /// <summary> /// Initialize a new instance of the PaletteRibbonBackInheritRedirect class. /// </summary> /// <param name="redirect">Source for inherit requests.</param> /// <param name="styleBack">Ribbon item background style.</param> public PaletteRibbonBackInheritRedirect(PaletteRedirect redirect, PaletteRibbonBackStyle styleBack) { Debug.Assert(redirect != null); _redirect = redirect; StyleBack = styleBack; } #endregion #region SetRedirector /// <summary> /// Update the redirector with new reference. /// </summary> /// <param name="redirect">Target redirector.</param> public void SetRedirector(PaletteRedirect redirect) { _redirect = redirect; } #endregion #region StyleBack /// <summary> /// Gets and sets the ribbon background style to use when inheriting. /// </summary> public PaletteRibbonBackStyle StyleBack { get; set; } #endregion #region IPaletteRibbonBack /// <summary> /// Gets the method used to draw the background of a ribbon item. /// </summary> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>PaletteRibbonBackStyle value.</returns> public override PaletteRibbonColorStyle GetRibbonBackColorStyle(PaletteState state) { return _redirect.GetRibbonBackColorStyle(StyleBack, state); } /// <summary> /// Gets the first background color for the ribbon item. /// </summary> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color value.</returns> public override Color GetRibbonBackColor1(PaletteState state) { return _redirect.GetRibbonBackColor1(StyleBack, state); } /// <summary> /// Gets the second background color for the ribbon item. /// </summary> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color value.</returns> public override Color GetRibbonBackColor2(PaletteState state) { return _redirect.GetRibbonBackColor2(StyleBack, state); } /// <summary> /// Gets the third background color for the ribbon item. /// </summary> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color value.</returns> public override Color GetRibbonBackColor3(PaletteState state) { return _redirect.GetRibbonBackColor3(StyleBack, state); } /// <summary> /// Gets the fourth background color for the ribbon item. /// </summary> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color value.</returns> public override Color GetRibbonBackColor4(PaletteState state) { return _redirect.GetRibbonBackColor4(StyleBack, state); } /// <summary> /// Gets the fifth background color for the ribbon item. /// </summary> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color value.</returns> public override Color GetRibbonBackColor5(PaletteState state) { return _redirect.GetRibbonBackColor5(StyleBack, state); } #endregion } }
namespace Matrix { using System; using System.Collections.Generic; using System.Text; public class Matrix<T> where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>, new () { private int row; private int col; private T[,] matrix; public Matrix() { matrix = new T[6, 6]; } public Matrix(int row, int col) { if (row < 0 || col < 0) throw new ArgumentOutOfRangeException("Negative row or col value"); else { this.row = row; this.col = col; matrix = new T[row, col]; } } public Matrix(T[,] matrix) { this.matrix = matrix; row = matrix.GetLength(0); col = matrix.GetLength(1); } public T this[int row, int col] { get { if (Row < row || Col < col || row < 0 || col < 0) { throw new IndexOutOfRangeException("The index was not inside boundaries of matrix!"); } return matrix[row, col]; } set { if (Row < row || Col < col || row < 0 || col < 0) { throw new IndexOutOfRangeException("The index was not inside boundaries of matrix!"); } matrix[row, col] = value; } } public int Row { get { return this.row; } set { if (value < 0) { throw new IndexOutOfRangeException("The row cannot be less than zero!"); } this.row = value; } } public int Col { get { return this.col; } set { if (value < 0) { throw new IndexOutOfRangeException("The col cannot be less than zero!"); } this.col = value; } } public static Matrix<T> operator +(Matrix<T> first, Matrix<T> second) { if (first.row == second.row && first.col == second.col) { Matrix<T> temp = new Matrix<T>(first.row, first.col); for (int i = 0; i < first.row; i++) { for (int j = 0; j < first.col; j++) { checked { temp[i, j] = (dynamic)first[i, j] + second[i, j]; } } } return temp; } else { throw new ArgumentException("Matrixes are not with same size!"); } } public static Matrix<T> operator -(Matrix<T> first, Matrix<T> second) { if (first.row == second.row && first.col == second.col) { Matrix<T> temp = new Matrix<T>(first.row, first.col); for (int i = 0; i < first.row; i++) { for (int j = 0; j < first.col; j++) { checked { temp[i, j] = (dynamic)first[i, j] - second[i, j]; } } } return temp; } else { throw new ArgumentException("Matrixes are not with same size!"); } } public static Matrix<T> operator *(Matrix<T> first, Matrix<T> second) { if (first.Col == second.Row) { Matrix<T> result = new Matrix<T>(first.Row, second.Col); for (int i = 0; i < result.Row; i++) { for (int j = 0; j < result.Col; j++) { result[i, j] = (dynamic)0; for (int k = 0; k < first.Col; k++) { checked { result[i, j] = result[i, j] + (dynamic)first[i, k] * second[k, j]; } } } } return result; } else { throw new ArgumentException("Matrixes are not with same size!"); } } public static Boolean operator true(Matrix<T> matrix) { int checker = 0; for (int i = 0; i < matrix.Row; i++) { for (int j = 0; j < matrix.Col; j++) { if ((dynamic)matrix[i, j] == checker) { return false; } } } return true; } public static Boolean operator false(Matrix<T> matrix) { int checker = 0; for (int i = 0; i < matrix.Row; i++) { for (int j = 0; j < matrix.Col; j++) { if ((dynamic)matrix[i, j] == checker) { return false; } } } return true; } public override string ToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { builder.Append(matrix[i, j] + " "); } builder.AppendLine(); } return builder.ToString(); } } }
using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Kontur.Results.SourceGenerator.Code { internal interface ITypeParameterGenericMethodSyntaxGenerator { IEnumerable<TypeParameterConstraintClauseSyntax> CreateTypeParameterConstraints(IEnumerable<MethodGenericParameterDescription> genericParameters); CompilationUnitSyntax FixMethodTypeParameterIndentation(CompilationUnitSyntax compilationUnit); } }
// SnowballController using ClubPenguin; using Disney.Kelowna.Common; using UnityEngine; [RequireComponent(typeof(ResourceCleaner))] public class SnowballController : MonoBehaviour { private ParticleSystem trailFX; private Rigidbody rbody; private TrailRenderer tRenderer; private MeshRenderer mRenderer; private float unspawnDelay; private bool readyForUnspawn; public long OwnerId { get; private set; } private void Awake() { trailFX = GetComponent<ParticleSystem>(); rbody = GetComponent<Rigidbody>(); tRenderer = GetComponent<TrailRenderer>(); mRenderer = GetComponent<MeshRenderer>(); readyForUnspawn = false; } public void Update() { if (!readyForUnspawn) { return; } unspawnDelay -= Time.deltaTime; if (unspawnDelay < 0f) { if (tRenderer != null) { tRenderer.enabled = false; } readyForUnspawn = false; SnowballManager.Instance.UnspawnSnowball(this); } } public void OnAttached() { rbody.isKinematic = true; rbody.detectCollisions = false; mRenderer.enabled = true; readyForUnspawn = false; OwnerId = 0L; if (tRenderer != null) { tRenderer.Clear(); tRenderer.enabled = false; } } public void OnDetached(long snowballOwner, ref Vector3 velocity, float chargeTime, float trailAlpha) { if (trailFX != null) { trailFX.Play(); } unspawnDelay = -1f; if (tRenderer != null) { tRenderer.Clear(); Color color = tRenderer.material.color; color.a = trailAlpha; tRenderer.material.color = color; tRenderer.enabled = true; } rbody.isKinematic = false; rbody.detectCollisions = true; rbody.AddForce(velocity, ForceMode.VelocityChange); OwnerId = snowballOwner; } private void OnCollisionEnter(Collision collision) { SnowballManager.Instance.OnSnowballCollision(collision); rbody.isKinematic = true; rbody.detectCollisions = false; mRenderer.enabled = false; if (trailFX != null) { trailFX.Stop(); } readyForUnspawn = true; if (tRenderer != null) { unspawnDelay = tRenderer.time; } else { unspawnDelay = 0f; } } }
@model Domain.Pokemon @{ ViewBag.Title = "Details"; } <h2>Details</h2> <div> <h4>Pokemon</h4> <hr /> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.PokedexNumber) </dt> <dd> @Html.DisplayFor(model => model.PokedexNumber) </dd> <dt> @Html.DisplayNameFor(model => model.Name) </dt> <dd> @Html.DisplayFor(model => model.Name) </dd> <dt> @Html.DisplayNameFor(model => model.Sprite) </dt> <dd> @Html.DisplayFor(model => model.Sprite) </dd> <dt> @Html.DisplayNameFor(model => model.Types) </dt> <dd> @Html.DisplayFor(model => model.Types) </dd> <dt> @Html.DisplayNameFor(model => model.Moves) </dt> <dd> @Html.DisplayFor(model => model.Moves) </dd> <dt> @Html.DisplayNameFor(model => model.Abilities) </dt> <dd> @Html.DisplayFor(model => model.Abilities) </dd> <dt> @Html.DisplayNameFor(model => model.LocationLat) </dt> <dd> @Html.DisplayFor(model => model.LocationLat) </dd> <dt> @Html.DisplayNameFor(model => model.LocationLong) </dt> <dd> @Html.DisplayFor(model => model.LocationLong) </dd> </dl> </div> <p> @Html.ActionLink("Edit", "Edit", new { id = Model.PokemonId }) | @Html.ActionLink("Back to List", "Index") </p>
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.OpsWorks.Model { /// <summary> /// Represents an app's environment variable. /// </summary> public partial class EnvironmentVariable { private string _key; private bool? _secure; private string _value; /// <summary> /// Gets and sets the property Key. /// <para> /// (Required) The environment variable's name, which can consist of up to 64 characters /// and must be specified. The name can contain upper- and lowercase letters, numbers, /// and underscores (_), but it must start with a letter or underscore. /// </para> /// </summary> [AWSProperty(Required=true)] public string Key { get { return this._key; } set { this._key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this._key != null; } /// <summary> /// Gets and sets the property Secure. /// <para> /// (Optional) Whether the variable's value will be returned by the <a>DescribeApps</a> /// action. To conceal an environment variable's value, set <code>Secure</code> to <code>true</code>. /// <code>DescribeApps</code> then returns <code>*****FILTERED*****</code> instead of /// the actual value. The default value for <code>Secure</code> is <code>false</code>. /// /// </para> /// </summary> public bool Secure { get { return this._secure.GetValueOrDefault(); } set { this._secure = value; } } // Check to see if Secure property is set internal bool IsSetSecure() { return this._secure.HasValue; } /// <summary> /// Gets and sets the property Value. /// <para> /// (Optional) The environment variable's value, which can be left empty. If you specify /// a value, it can contain up to 256 characters, which must all be printable. /// </para> /// </summary> [AWSProperty(Required=true)] public string Value { get { return this._value; } set { this._value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this._value != null; } } }
using System.Threading.Tasks; namespace Ghostly.Core { public interface IActivationService { Task Activate(object args); } }
namespace HeroismDiscordBot.Service.Entities.DAL { public enum InvitationStatus { Unknown = 0, Invited = 1, Accepted = 2, Tentative = 3, Declined = 4 } }
namespace DotNetWhy.Core.Interfaces; internal interface IDependencyGraphSourceProvider { string Get(); }
using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace EventSourced.Helpers { public abstract class HostedServiceBase : IHostedService { private readonly IServiceScopeFactory _serviceScopeFactory; protected HostedServiceBase(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } public async Task StartAsync(CancellationToken cancellationToken) { using var serviceScope = _serviceScopeFactory.CreateScope(); await StartAsync(serviceScope, cancellationToken); } public async Task StopAsync(CancellationToken cancellationToken) { using var serviceScope = _serviceScopeFactory.CreateScope(); await StopAsync(serviceScope, cancellationToken); } protected virtual Task StartAsync(IServiceScope serviceScope, CancellationToken cancellationToken) => Task.CompletedTask; protected virtual Task StopAsync(IServiceScope serviceScope, CancellationToken cancellationToken) => Task.CompletedTask; } }
using ULFG.Core.Data.Item; using Xamarin.Forms; using ULFG.Forms.PrivateChat.ViewModels; using ULFG.Forms.Shared; namespace ULFG.Forms.PrivateChat.Views { /// <summary> /// <see cref="ChatView"/> que representa la vista del chat individual /// </summary> public class IndividualChatView : ChatView { public IndividualChatView(Chat chat): base() { BindingContext = new IndividualChatViewModel(Navigation, chat); this.SetBinding(ContentPage.TitleProperty, "Title"); ToolbarItem leave = new ToolbarItem() { Text = "Abandonar", Order = ToolbarItemOrder.Secondary }; leave.SetBinding(ToolbarItem.CommandProperty, "Leave"); ToolbarItem profile = new ToolbarItem() { Text = "Ver Perfil", Order = ToolbarItemOrder.Secondary }; profile.SetBinding(ToolbarItem.CommandProperty, "Profile"); ToolbarItems.Add(profile); ToolbarItems.Add(leave); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal { public partial class ServerDetails { protected System.Web.UI.WebControls.Literal litServer; } }
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Lkadoxiospecialeventschedulemodifiedby. /// </summary> public static partial class LkadoxiospecialeventschedulemodifiedbyExtensions { /// <summary> /// Get lk_adoxio_specialeventschedule_modifiedby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMadoxioSpecialeventscheduleCollection Get(this ILkadoxiospecialeventschedulemodifiedby operations, string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(ownerid, top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get lk_adoxio_specialeventschedule_modifiedby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMadoxioSpecialeventscheduleCollection> GetAsync(this ILkadoxiospecialeventschedulemodifiedby operations, string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(ownerid, top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get lk_adoxio_specialeventschedule_modifiedby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioSpecialeventscheduleCollection> GetWithHttpMessages(this ILkadoxiospecialeventschedulemodifiedby operations, string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetWithHttpMessagesAsync(ownerid, top, skip, search, filter, count, orderby, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get lk_adoxio_specialeventschedule_modifiedby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='adoxioSpecialeventscheduleid'> /// key: adoxio_specialeventscheduleid of adoxio_specialeventschedule /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMadoxioSpecialeventschedule ModifiedbyByKey(this ILkadoxiospecialeventschedulemodifiedby operations, string ownerid, string adoxioSpecialeventscheduleid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.ModifiedbyByKeyAsync(ownerid, adoxioSpecialeventscheduleid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get lk_adoxio_specialeventschedule_modifiedby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='adoxioSpecialeventscheduleid'> /// key: adoxio_specialeventscheduleid of adoxio_specialeventschedule /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMadoxioSpecialeventschedule> ModifiedbyByKeyAsync(this ILkadoxiospecialeventschedulemodifiedby operations, string ownerid, string adoxioSpecialeventscheduleid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ModifiedbyByKeyWithHttpMessagesAsync(ownerid, adoxioSpecialeventscheduleid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get lk_adoxio_specialeventschedule_modifiedby from systemusers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='ownerid'> /// key: ownerid of systemuser /// </param> /// <param name='adoxioSpecialeventscheduleid'> /// key: adoxio_specialeventscheduleid of adoxio_specialeventschedule /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioSpecialeventschedule> ModifiedbyByKeyWithHttpMessages(this ILkadoxiospecialeventschedulemodifiedby operations, string ownerid, string adoxioSpecialeventscheduleid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.ModifiedbyByKeyWithHttpMessagesAsync(ownerid, adoxioSpecialeventscheduleid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
using System; using System.Threading.Tasks; using eShopOnContainers.Core.Services.RequestProvider; using eShopOnContainers.Core.Models.Basket; using eShopOnContainers.Core.Services.FixUri; using eShopOnContainers.Core.Helpers; namespace eShopOnContainers.Core.Services.Basket { public class BasketService : IBasketService { private readonly IRequestProvider _requestProvider; private readonly IFixUriService _fixUriService; private const string ApiUrlBase = "api/v1/b/basket"; public BasketService(IRequestProvider requestProvider, IFixUriService fixUriService) { _requestProvider = requestProvider; _fixUriService = fixUriService; } public async Task<CustomerBasket> GetBasketAsync(string guidUser, string token) { var uri = UriHelper.CombineUri(GlobalSetting.Instance.GatewayShoppingEndpoint, $"{ApiUrlBase}/{guidUser}"); CustomerBasket basket; try { basket = await _requestProvider.GetAsync<CustomerBasket>(uri, token); } catch (HttpRequestExceptionEx exception) when (exception.HttpCode == System.Net.HttpStatusCode.NotFound) { basket = null; } _fixUriService.FixBasketItemPictureUri(basket?.Items); return basket; } public async Task<CustomerBasket> UpdateBasketAsync(CustomerBasket customerBasket, string token) { var uri = UriHelper.CombineUri(GlobalSetting.Instance.GatewayShoppingEndpoint, ApiUrlBase); var result = await _requestProvider.PostAsync(uri, customerBasket, token); return result; } public async Task CheckoutAsync(BasketCheckout basketCheckout, string token) { var uri = UriHelper.CombineUri(GlobalSetting.Instance.GatewayShoppingEndpoint, $"{ApiUrlBase}/checkout"); await _requestProvider.PostAsync(uri, basketCheckout, token); } public async Task ClearBasketAsync(string guidUser, string token) { var uri = UriHelper.CombineUri(GlobalSetting.Instance.GatewayShoppingEndpoint, $"{ApiUrlBase}/{guidUser}"); await _requestProvider.DeleteAsync(uri, token); } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Entitas.CodeGenerator.ComponentIndicesGenerator. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public static class CoreComponentIds { public const int GameObject = 0; public const int Moveable = 1; public const int PrefabName = 2; public const int TotalComponents = 3; public static readonly string[] componentNames = { "GameObject", "Moveable", "PrefabName" }; public static readonly System.Type[] componentTypes = { typeof(GameObjectComponent), typeof(MoveableComponent), typeof(PrefabNameComponent) }; }
// <copyright file="ITrader.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.GameLogic { using MUnique.OpenMU.GameLogic.Views; using MUnique.OpenMU.Persistence; /// <summary> /// Interface of a trader. /// </summary> public interface ITrader { /// <summary> /// Gets the character name. /// </summary> string Name { get; } /// <summary> /// Gets the traders level. /// </summary> int Level { get; } /// <summary> /// Gets or sets the current trading partner. /// </summary> ITrader TradingPartner { get; set; } /// <summary> /// Gets or sets the money which is currently in the trade. /// </summary> int TradingMoney { get; set; } /// <summary> /// Gets or sets the short guild identifier. /// </summary> ushort ShortGuildID { get; set; } /// <summary> /// Gets the inventory. /// </summary> IStorage Inventory { get; } /// <summary> /// Gets the temporary storage, which holds the items of the trade. /// </summary> IStorage TemporaryStorage { get; } /// <summary> /// Gets or sets the backup inventory. /// </summary> BackupItemStorage BackupInventory { get; set; } /// <summary> /// Gets or sets the available money. /// </summary> int Money { get; set; } /// <summary> /// Gets the state of the player. /// </summary> StateMachine PlayerState { get; } /// <summary> /// Gets the persistence context of the trader. It needs to be updated when a trade finishes. /// </summary> IContext PersistenceContext { get; } /// <summary> /// Gets the trade view. /// </summary> ITradeView TradeView { get; } } }
using System; using System.Collections.Generic; using System.Text; namespace LogExpert { internal class ConfigChangedEventArgs : EventArgs { private SettingsFlags flags; internal ConfigChangedEventArgs(SettingsFlags changeFlags) { this.flags = changeFlags; } public SettingsFlags Flags { get { return this.flags; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ListwareDesktop.Framework; namespace ListwareDesktop.Windows { public partial class SetOutputsForm : Form { private string[] outputs; private IWS inputService; CheckBox setOutputsFormCheckBox; //Set the service and get all current outputs from a sample request public SetOutputsForm(CheckBox setOutputsFormCheckBox) { InitializeComponent(); this.inputService = Activator.CreateInstance(MainForm.serviceType) as IWS; this.setOutputsFormCheckBox = setOutputsFormCheckBox; outputs = inputService.outputColumns; this.fillDGV(); this.resizeForm(); } //Auto size the form to the options private void resizeForm() { int originalHeight = this.setOutputsFormDataGridView.Height; int sum = this.setOutputsFormDataGridView.ColumnHeadersHeight; foreach (DataGridViewRow row in this.setOutputsFormDataGridView.Rows) { sum += row.Height; } int heightDiff = originalHeight - sum; if (heightDiff > 0) { this.setOutputsFormDataGridView.Height = sum + 1; this.Height = this.Height - heightDiff; this.setOutputsFormSaveButton.Location = new Point(this.setOutputsFormSaveButton.Location.X, this.setOutputsFormSaveButton.Location.Y - heightDiff); this.setOutputsFormSelectAllButton.Location = new Point(this.setOutputsFormSelectAllButton.Location.X, this.setOutputsFormSelectAllButton.Location.Y - heightDiff); this.setOutputsFormCancelButton.Location = new Point(this.setOutputsFormCancelButton.Location.X, this.setOutputsFormCancelButton.Location.Y - heightDiff); } } private void fillDGV() { foreach(string individualOutput in outputs) { setOutputsFormDataGridView.Rows.Add(individualOutput); } if (MainForm.selectedOutputs != null) { foreach (DataGridViewRow row in setOutputsFormDataGridView.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["SelectColumn"]; if (MainForm.selectedOutputs.Contains(row.Cells["FieldName"].Value)) { chk.Value = chk.TrueValue; } else { chk.Value = chk.FalseValue; } } } } private void setOutputsFormSaveButton_Click(object sender, EventArgs e) { List<string> selectedOutputs = new List<string>(); foreach (DataGridViewRow row in setOutputsFormDataGridView.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["SelectColumn"]; if (chk.Value == chk.TrueValue) { selectedOutputs.Add(row.Cells["FieldName"].Value.ToString()); } } MainForm.selectedOutputs = selectedOutputs.ToArray(); this.setOutputsFormCheckBox.Checked = true; this.Close(); this.Dispose(); } private void setOutputsFormSelectAllButton_Click(object sender, EventArgs e) { bool checkedAlready = new bool(); foreach (DataGridViewRow row in setOutputsFormDataGridView.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["SelectColumn"]; if (chk.Value == chk.FalseValue) { checkedAlready = false; break; } else { checkedAlready = true; } } foreach (DataGridViewRow row in setOutputsFormDataGridView.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["SelectColumn"]; if (!checkedAlready) { chk.Value = chk.TrueValue; } else { chk.Value = chk.FalseValue; } } } private void setOutputsFormCancelButton_Click(object sender, EventArgs e) { this.Close(); this.Dispose(); } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Threading.Tasks; /// <summary> /// Represents a service request that can have multiple responses. /// </summary> /// <typeparam name="TResponse">The type of the response.</typeparam> internal abstract class MultiResponseServiceRequest<TResponse> : SimpleServiceRequestBase where TResponse : ServiceResponse { private ServiceErrorHandling errorHandlingMode; /// <summary> /// Parses the response. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Service response collection.</returns> internal override object ParseResponse(EwsServiceXmlReader reader) { ServiceResponseCollection<TResponse> serviceResponses = new ServiceResponseCollection<TResponse>(); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages); for (int i = 0; i < this.GetExpectedResponseMessageCount(); i++) { // Read ahead to see if we've reached the end of the response messages early. reader.Read(); if (reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages)) { break; } TResponse response = this.CreateServiceResponse(reader.Service, i); response.LoadFromXml(reader, this.GetResponseMessageXmlElementName()); // Add the response to the list after it has been deserialized because the response // list updates an overall result as individual responses are added to it. serviceResponses.Add(response); } // If there's a general error in batch processing, // the server will return a single response message containing the error // (for example, if the SavedItemFolderId is bogus in a batch CreateItem // call). In this case, throw a ServiceResponseException. Otherwise this // is an unexpected server error. if (serviceResponses.Count < this.GetExpectedResponseMessageCount()) { if ((serviceResponses.Count == 1) && (serviceResponses[0].Result == ServiceResult.Error)) { throw new ServiceResponseException(serviceResponses[0]); } else { throw new ServiceXmlDeserializationException( string.Format( Strings.TooFewServiceReponsesReturned, this.GetResponseMessageXmlElementName(), this.GetExpectedResponseMessageCount(), serviceResponses.Count)); } } reader.ReadEndElementIfNecessary(XmlNamespace.Messages, XmlElementNames.ResponseMessages); return serviceResponses; } /// <summary> /// Creates the service response. /// </summary> /// <param name="service">The service.</param> /// <param name="responseIndex">Index of the response.</param> /// <returns>Service response.</returns> internal abstract TResponse CreateServiceResponse(ExchangeService service, int responseIndex); /// <summary> /// Gets the name of the response message XML element. /// </summary> /// <returns>XML element name,</returns> internal abstract string GetResponseMessageXmlElementName(); /// <summary> /// Gets the expected response message count. /// </summary> /// <returns>Number of expected response messages.</returns> internal abstract int GetExpectedResponseMessageCount(); /// <summary> /// Initializes a new instance of the <see cref="MultiResponseServiceRequest&lt;TResponse&gt;"/> class. /// </summary> /// <param name="service">The service.</param> /// <param name="errorHandlingMode"> Indicates how errors should be handled.</param> internal MultiResponseServiceRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode) : base(service) { this.errorHandlingMode = errorHandlingMode; } /// <summary> /// Executes this request. /// </summary> /// <returns>Service response collection.</returns> internal async Task<ServiceResponseCollection<TResponse>> ExecuteAsync() { ServiceResponseCollection<TResponse> serviceResponses = (ServiceResponseCollection<TResponse>)await this.InternalExecuteAsync().ConfigureAwait(false); if (this.ErrorHandlingMode == ServiceErrorHandling.ThrowOnError) { EwsUtilities.Assert( serviceResponses.Count == 1, "MultiResponseServiceRequest.Execute", "ServiceErrorHandling.ThrowOnError error handling is only valid for singleton request"); serviceResponses[0].ThrowIfNecessary(); } return serviceResponses; } /// <summary> /// Gets a value indicating how errors should be handled. /// </summary> internal ServiceErrorHandling ErrorHandlingMode { get { return this.errorHandlingMode; } } } }
using System; using System.Data; using NHibernate; using NHibernate.SqlTypes; namespace Quarks.NHibernate.UserTypes { /// <summary> /// IUserType implementation for mapping System.UInt16 to a int. /// </summary> [Serializable] public class ByteType : ImmutableUserTypeBase<byte> { public override object NullSafeGet(IDataReader rs, string[] names, object owner) { var obj = NHibernateUtil.Byte.NullSafeGet(rs, names[0]); if (obj == null) return 0; return obj; } public override void NullSafeSet(IDbCommand cmd, object value, int index) { ((IDataParameter)cmd.Parameters[index]).Value = value; } public override SqlType[] SqlTypes { get { return new[] { NHibernateUtil.Byte.SqlType }; } } } }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos valores de atributo para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("Proyecto_WorldTec")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Proyecto_WorldTec")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. [assembly: Guid("77f163c6-f111-4afd-abfd-4e72f5bf76c8")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
// Copyright 2010-2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // Minimal example to call the GLOP solver. // [START program] using System; using Google.OrTools.LinearSolver; public class SimpleLpProgram { static void Main() { // [START solver] // Create the linear solver with the GLOP backend. Solver solver = Solver.CreateSolver("SimpleLpProgram", "GLOP_LINEAR_PROGRAMMING"); // [END solver] // [START variables] // Create the variables x and y. Variable x = solver.MakeNumVar(0.0, 1.0, "x"); Variable y = solver.MakeNumVar(0.0, 2.0, "y"); Console.WriteLine("Number of variables = " + solver.NumVariables()); // [END variables] // [START constraints] // Create a linear constraint, 0 <= x + y <= 2. Constraint ct = solver.MakeConstraint(0.0, 2.0, "ct"); ct.SetCoefficient(x, 1); ct.SetCoefficient(y, 1); Console.WriteLine("Number of constraints = " + solver.NumConstraints()); // [END constraints] // [START objective] // Create the objective function, 3 * x + y. Objective objective = solver.Objective(); objective.SetCoefficient(x, 3); objective.SetCoefficient(y, 1); objective.SetMaximization(); // [END objective] // [START solve] solver.Solve(); // [END solve] // [START print_solution] Console.WriteLine("Solution:"); Console.WriteLine("Objective value = " + solver.Objective().Value()); Console.WriteLine("x = " + x.SolutionValue()); Console.WriteLine("y = " + y.SolutionValue()); // [END print_solution] } } // [END program]
using System; using System.Collections.Generic; using Elite.Insight.Annotations; using Elite.Insight.Core.Helpers; using Newtonsoft.Json; namespace Elite.Insight.Core.DomainModel { /// <summary> /// /// </summary> public class StarSystem : UpdatableEntity { private readonly StationCollection _stations; private string _name; [JsonProperty("id")] public long Id { get; set; } [JsonProperty("name")] public string Name { get { return _name; } private set { _name = value.ToCleanUpperCase(); } } [JsonProperty("x")] public double X { get; set; } [JsonProperty("y")] public double Y { get; set; } [JsonProperty("z")] public double Z { get; set; } [JsonProperty("faction")] public string Faction { get; set; } [JsonProperty("population")] public long? Population { get; set; } [JsonProperty("government")] public string Government { get; set; } [JsonProperty("allegiance")] public string Allegiance { get; set; } [JsonProperty("state")] public string State { get; set; } [JsonProperty("security")] public string Security { get; set; } [JsonProperty("primary_economy")] public string PrimaryEconomy { get; set; } [JsonProperty("needs_permit")] public bool? NeedsPermit { get; set; } [JsonProperty("updated_at")] public long UpdatedAt { get; set; } public IEnumerable<Station> Stations { get { return _stations; } } /// <summary> /// creates a new system /// </summary> protected StarSystem() { _stations = new StationCollection(); Name = String.Empty; } public StarSystem(string name) : this() { if (String.IsNullOrWhiteSpace(name)) throw new ArgumentException("invalid system name", "name"); Name = name; } /// <summary> /// creates a new system as a copy of another system /// only the id must declared extra /// </summary> /// <param name="name">The name.</param> /// <param name="sourceSystem">The source system.</param> public StarSystem(string name, StarSystem sourceSystem) : this(name) { UpdateFrom(sourceSystem, UpdateMode.Copy); } /// <summary> /// copy the values from another system exept for the ID /// </summary> /// <param name="sourceSystem">The source system.</param> /// <param name="updateMode">The update mode.</param> public void UpdateFrom(StarSystem sourceSystem, UpdateMode updateMode) { bool doCopy = updateMode == UpdateMode.Clone || updateMode == UpdateMode.Copy; bool isNewer = UpdatedAt < sourceSystem.UpdatedAt; if (updateMode == UpdateMode.Clone) { Name = sourceSystem.Name; } if (doCopy || isNewer) { X = sourceSystem.X; Y = sourceSystem.Y; Z = sourceSystem.Z; } if (doCopy || String.IsNullOrEmpty(Faction) || (isNewer && !String.IsNullOrEmpty(sourceSystem.Faction))) Faction = sourceSystem.Faction; if (doCopy || !Population.HasValue || (isNewer && sourceSystem.Population.HasValue)) Population = sourceSystem.Population; if (doCopy || String.IsNullOrEmpty(Government) || (isNewer && !String.IsNullOrEmpty(sourceSystem.Government))) Government = sourceSystem.Government; if (doCopy || String.IsNullOrEmpty(Allegiance) || (isNewer && !String.IsNullOrEmpty(sourceSystem.Allegiance))) Allegiance = sourceSystem.Allegiance; if (doCopy || String.IsNullOrEmpty(State) || (isNewer && !String.IsNullOrEmpty(sourceSystem.State))) State = sourceSystem.State; if (doCopy || String.IsNullOrEmpty(Security) || (isNewer && !String.IsNullOrEmpty(sourceSystem.Security))) Security = sourceSystem.Security; if (doCopy || String.IsNullOrEmpty(PrimaryEconomy) || (isNewer && !String.IsNullOrEmpty(sourceSystem.PrimaryEconomy))) PrimaryEconomy = sourceSystem.PrimaryEconomy; if (doCopy || !NeedsPermit.HasValue || (isNewer && sourceSystem.NeedsPermit.HasValue)) NeedsPermit = sourceSystem.NeedsPermit; if (doCopy || UpdatedAt == 0 || isNewer) UpdatedAt = sourceSystem.UpdatedAt; base.UpdateFrom(sourceSystem, updateMode); } public void UpdateStations([NotNull] Station station) { if (station == null) throw new ArgumentNullException("station"); if (!station.SystemName.Equals(Name, StringComparison.InvariantCultureIgnoreCase)) throw new ArgumentException("station system " + station.SystemName + " does not match system " + Name, "station"); _stations.UpdateFrom(station); } public override string ToString() { return Name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace _Framework.Scripts.Extensions { public static class MemberInfoExtensions { public static bool IsDefined(this MemberInfo minfo, Type type) { return minfo.IsDefined(type, false); } /// <summary> /// Returns true if the attribute whose type is specified by the generic argument is defined on this member /// </summary> public static bool IsDefined<T>(this MemberInfo member, bool inherit) where T : Attribute { return member.IsDefined(typeof(T), inherit); } /// <summary> /// Returns true if the attribute whose type is specified by the generic argument is defined on this member /// </summary> public static bool IsDefined<T>(this MemberInfo member) where T : Attribute { return IsDefined<T>(member, false); } /// <summary> /// Returns PropertyInfo.PropertyType if the info was a PropertyInfo, /// FieldInfo.FieldType if FieldInfo, otherwise MethodInfo.ReturnType /// </summary> public static Type GetDataType(this MemberInfo memberInfo, Func<MemberInfo, Type> fallbackType) { var field = memberInfo as FieldInfo; if (field != null) return field.FieldType; var property = memberInfo as PropertyInfo; if (property != null) return property.PropertyType; var method = memberInfo as MethodInfo; if (method != null) return method.ReturnType; if (fallbackType == null) throw new InvalidOperationException("Member is not a field, property, method nor does it have a fallback type"); return fallbackType(memberInfo); } public static Type GetDataType(this MemberInfo memberInfo) { return GetDataType(memberInfo, null); } /// <summary> /// Returns the first found custom attribute of type T on this member /// Returns null if none was found /// </summary> public static T GetCustomAttribute<T>(this MemberInfo member, bool inherit) where T : Attribute { var all = GetCustomAttributes<T>(member, inherit).ToArray(); return all.IsNullOrEmpty() ? null : all[0]; } /// <summary> /// Returns the first found non-inherited custom attribute of type T on this member /// Returns null if none was found /// </summary> public static T GetCustomAttribute<T>(this MemberInfo member) where T : Attribute { return GetCustomAttribute<T>(member, false); } public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo member) where T : Attribute { return GetCustomAttributes<T>(member, false); } public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo member, bool inherit) where T : Attribute { return member.GetCustomAttributes(typeof(T), inherit).Cast<T>(); } public static Attribute[] GetAttributes(this MemberInfo member) { return member.GetCustomAttributes<Attribute>().ToArray(); } public static bool IsStatic(this MemberInfo member) { var field = member as FieldInfo; if (field != null) return field.IsStatic; var property = member as PropertyInfo; if (property != null) return property.CanRead ? property.GetGetMethod(true).IsStatic : property.GetSetMethod(true).IsStatic; var method = member as MethodInfo; if (method != null) return method.IsStatic; string message = string.Format("Unable to determine IsStatic for member {0}.{1}" + "MemberType was {2} but only fields, properties and methods are supported.", member.Name, member.MemberType, Environment.NewLine); throw new NotSupportedException(message); } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("FAHChatBot")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("FAHChatBot")] [assembly: System.Reflection.AssemblyTitleAttribute("FAHChatBot")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Abp.Application.Services; using Abp.IdentityFramework; using Abp.Runtime.Session; using EbusSoft.Authorization.Users; using EbusSoft.MultiTenancy; namespace EbusSoft { /// <summary> /// Derive your application services from this class. /// </summary> public abstract class EbusSoftAppServiceBase : ApplicationService { public TenantManager TenantManager { get; set; } public UserManager UserManager { get; set; } protected EbusSoftAppServiceBase() { LocalizationSourceName = EbusSoftConsts.LocalizationSourceName; } protected virtual Task<User> GetCurrentUserAsync() { var user = UserManager.FindByIdAsync(AbpSession.GetUserId().ToString()); if (user == null) { throw new Exception("There is no current user!"); } return user; } protected virtual Task<Tenant> GetCurrentTenantAsync() { return TenantManager.GetByIdAsync(AbpSession.GetTenantId()); } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class RestartLevel : MonoBehaviour { public void RestartCurrentScene() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } }
using System; using System.Collections.Generic; namespace Lextm.SharpSnmpLib.Mib { public class ValueMap : Dictionary<Int64, string> { public ValueMap() { } /// <summary> /// Returns the values of the map as continuous range. At best as one range. /// </summary> /// <returns></returns> public ValueRanges GetContinousRanges() { ValueRanges result = new ValueRanges(); if (this.Count > 0) { List<Int64> values = new List<long>(this.Keys); values.Sort(); Int64 last = values[0]; Int64 offset = values[0]; for (int i=1; i<values.Count; i++) { if (values[i] != last + 1) { if (last == offset) { result.Add(new ValueRange(offset, null)); } else { result.Add(new ValueRange(offset, last)); } offset = values[i]; } last = values[i]; } if (last == offset) { result.Add(new ValueRange(offset, null)); } else { result.Add(new ValueRange(offset, last)); } } return result; } /// <summary> /// Gets the highest value contained in this value map. /// </summary> /// <returns></returns> public Int64 GetHighestValue() { Int64 result = 0; foreach (Int64 value in this.Keys) { if (value > result) { result = value; } } return result; } /// <summary> /// Interprets the single values as bit positions and creates a mask of it. /// </summary> /// <returns></returns> public UInt32 GetBitMask() { UInt32 result = 0; foreach (Int64 key in this.Keys) { if (key < 0) { throw new NotSupportedException("Negative numbers are not allowed for Bits!"); } if (key > 31) { throw new NotSupportedException("Bits with more than 32 bits are not supported!"); } result |= (UInt32)(1 << (int)key); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaintCoinach.Graphics { public class ImcFile { #region Fields private Dictionary<byte, ImcPart> _Parts = new Dictionary<byte, ImcPart>(); #endregion #region Properties public IO.File SourceFile { get; private set; } public IEnumerable<ImcPart> Parts { get { return _Parts.Values; } } public short PartsMask { get; private set; } public short Count { get; private set; } #endregion #region Constructor public ImcFile(IO.File sourceFile) { this.SourceFile = sourceFile; var buffer = SourceFile.GetData(); this.Count = BitConverter.ToInt16(buffer, 0); this.PartsMask = BitConverter.ToInt16(buffer, 2); var offset = 4; for (byte bit = 0; bit < 8; ++bit) { var match = 1 << bit; if ((PartsMask & match) == match) _Parts.Add(bit, new ImcPart(buffer, bit, ref offset)); } var rem = Count; while (--rem >= 0) { foreach (var part in _Parts.Values) part._Variants.Add(buffer.ToStructure<ImcVariant>(ref offset)); } } #endregion #region Get public ImcVariant GetVariant(int index) { return Parts.First().Variants[index]; } public ImcVariant GetVariant(byte partKey, int index) { return _Parts[partKey].Variants[index]; } #endregion } }
using Exico.Shopify.Web.Core.Filters; using Exico.Shopify.Web.Core.Modules; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Exico.Shopify.Web.Core.Controllers.BaseControllers { /// <summary> /// If you want to make sure your controller is available to only those are paid subscribers then extend /// this controller. /// <see cref="ABaseAuthorizedController"/> /// /// <see cref="RequireSubscription"/> /// </summary> [ServiceFilter(typeof(RequireSubscription), Order = RequireSubscription.DEFAULT_ORDER)] public abstract class ABaseSubscriberController : ABaseAuthorizedController { protected readonly IPlansReader Plans; public ABaseSubscriberController(IPlansReader plansReader, IUserCaching cachedUser, IConfiguration config, IDbSettingsReader settings, ILogger logger) : base(cachedUser, config, settings, logger) { this.Plans = plansReader; } } }
using System.Collections.Generic; using StoreModel; using System; namespace StoreData { public interface IProductRepository { List<Product> GetProducts(); Product AddProduct(Product newProduct); Product GetProductByID(int ID); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace LletraWeb.Pages { public class IndexModel : PageModel { public void OnGet() { } } }
using FlatRedBall.Glue.Plugins.ExportedImplementations; using FlatRedBall.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FlatRedBall.Glue.SaveClasses; using EditorObjects.Parsing; using FlatRedBall.Glue; using FlatRedBall.Glue.Managers; using GumPlugin.ViewModels; namespace GumPlugin.Managers { class GumxPropertiesManager { public bool IsReactingToProperyChanges { get; internal set; } = true; public bool GetShouldAutoCreateGumScreens() { var gumRfs = GumProjectManager.Self.GetRfsForGumProject(); if (gumRfs != null) { return gumRfs.Properties.GetValue<bool>(nameof(GumViewModel.AutoCreateGumScreens)); } else { return false; } } public void HandlePropertyChanged(string propertyChanged) { if(IsReactingToProperyChanges) { if (propertyChanged == nameof(GumViewModel.UseAtlases)) { UpdateUseAtlases(); } else if(propertyChanged == nameof(GumViewModel.AutoCreateGumScreens)) { // Do we need to do anything? } else if(propertyChanged == nameof(GumViewModel.ShowDottedOutlines)) { UpdateShowDottedOutlines(); } else if(propertyChanged == nameof(GumViewModel.EmbedCodeFiles) || propertyChanged == nameof(GumViewModel.IncludeNoFiles) ) { UpdateCodeOrDllAdd(); } else if (propertyChanged == nameof(GumViewModel.IncludeFormsInComponents)) { TaskManager.Self.Add( CodeGeneratorManager.Self.GenerateDerivedGueRuntimes, $"Regenerating Gum derived runtimes because of changed {propertyChanged}"); } else if(propertyChanged == nameof(GumViewModel.IncludeComponentToFormsAssociation)) { TaskManager.Self.Add( () => { CodeGeneratorManager.Self.GenerateAndSaveRuntimeAssociations(); }, $"Regenerating runtime associations because of changed {propertyChanged}"); } else if(propertyChanged == nameof(GumViewModel.ShowMouse)) { TaskManager.Self.Add( () => { GlueCommands.Self.GenerateCodeCommands.GenerateGlobalContentCode(); }, $"Regenerating global content because of changed property {nameof(GumViewModel.ShowMouse)}" ); } else if(propertyChanged == nameof(GumViewModel.MakeGumInstancesPublic)) { TaskManager.Self.Add( CodeGeneratorManager.Self.GenerateDerivedGueRuntimes, $"Regenerating Gum derived runtimes because of changed {propertyChanged}"); } else if(propertyChanged == nameof(GumViewModel.IsMatchGameResolutionInGumChecked)) { AppCommands.Self.UpdateGumToGlueResolution(); } GlueCommands.Self.GluxCommands.SaveGlux(); } } private void UpdateCodeOrDllAdd() { var gumRfs = GumProjectManager.Self.GetRfsForGumProject(); if (gumRfs != null) { var behavior = (FileAdditionBehavior)gumRfs.Properties.GetValue<FileAdditionBehavior>(nameof(FileAdditionBehavior)); EmbeddedResourceManager.Self.UpdateCodeInProjectPresence(behavior); GlueCommands.Self.ProjectCommands.SaveProjects(); } } private void UpdateShowDottedOutlines() { var gumRfs = GumProjectManager.Self.GetRfsForGumProject(); if (gumRfs != null) { // At the time of this writing the // gumx file should always be part of // global content, but who knows what will // happen in the future so I'm going to make // this code work regardless of where it's added: var container = gumRfs.GetContainer(); if (container == null) { GlueCommands.Self.GenerateCodeCommands.GenerateGlobalContentCode(); } else { GlueCommands.Self.GenerateCodeCommands.GenerateElementCode(container); } } } public void UpdateUseAtlases() { var gumRfs = GumProjectManager.Self.GetRfsForGumProject(); if (gumRfs != null) { bool useAtlases = gumRfs.Properties.GetValue<bool>(nameof(GumViewModel.UseAtlases)); FileReferenceTracker.Self.UseAtlases = useAtlases; var absoluteFileName = GlueCommands.Self.GetAbsoluteFileName(gumRfs); // clear the cache for all screens, components, and standards - because whether we use atlases or not has changed var gumFiles = GlueCommands.Self.FileCommands.GetFilesReferencedBy(absoluteFileName, TopLevelOrRecursive.TopLevel); foreach (var file in gumFiles) { GlueCommands.Self.FileCommands.ClearFileCache(file.FullPath); } if (useAtlases == false) { // If useAtlases is set to false, then that means that // a lot of new files need to be added to the project. TaskManager.Self.AddSync( () => { bool wasAnythingAdded = GlueCommands.Self.ProjectCommands.UpdateFileMembershipInProject(gumRfs); if(wasAnythingAdded) { GlueCommands.Self.ProjectCommands.SaveProjects(); } }, $"Refreshing files in content project for {gumRfs.Name}"); } } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Open.Evaluation.Arithmetic; using Open.Evaluation.Catalogs; using Open.Evaluation.Core; namespace Open.Evaluation.Tests; public static class Sum { [TestClass] public class Default : ParseTestBase { const string FORMAT = "((2 * {0} * {1}) + ({0} * {1}) + ({2} * {3}))"; const string RED = "((3 * {0} * {1}) + ({2} * {3}))"; public Default() : base(FORMAT, null, RED) { } protected override double Expected { get { var x1 = PV[0] * PV[1]; var x2 = PV[2] * PV[3]; return 2 * x1 + x2 + x1; } } } [TestClass] public class ConstantCollapse : ParseTestBase { const string FORMAT = "(({0} + {1} + 13 + 17) * ({0} + {1}) * ({2} + {3}))"; const string REP = "(({0} + {1} + 30) * ({0} + {1}) * ({2} + {3}))"; public ConstantCollapse() : base(FORMAT, REP) { } protected override double Expected { get { var x1 = PV[0] + PV[1]; var x2 = PV[2] + PV[3]; var x3 = x1 + 30; return x1 * x2 * x3; } } } [TestClass] public class SumCollapse : ParseTestBase { const string FORMAT = "(({0} * {1}) + ({0} * {1}) + {2} + {2} + {3} + 2 + 1)"; const string REP = "(({0} * {1}) + ({0} * {1}) + {2} + {2} + {3} + 3)"; const string RED = "((2 * {0} * {1}) + (2 * {2}) + {3} + 3)"; public SumCollapse() : base(FORMAT, REP, RED) { } protected override double Expected { get { var x1 = 2 * PV[0] * PV[1]; var x2 = 2 * PV[2]; var x3 = PV[3]; return x1 + x2 + x3 + 3; } } } [TestClass] public class SumCollapse2 { [TestMethod] public void TestMultipleCombine() { using var catalog = new EvaluationCatalog<double>(); var a2 = catalog.GetExponent(catalog.GetParameter(0), 2); var g1 = catalog.ProductOf(catalog.GetConstant(9), a2); var b = catalog.GetParameter(1); var g2 = catalog.ProductOf(-1, a2); var sum = catalog.SumOf(g1, b, g2); var sumString = sum.ToStringRepresentation(); Assert.AreEqual("((9 * ({0}²)) + {1} - (({0}²)))", sumString); Assert.AreEqual("((8 * ({0}²)) + {1})", catalog.GetReduced(sum).ToStringRepresentation()); } } }
using System; using System.Collections.Generic; using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using Ocelot.Configuration.Provider; namespace Ocelot.Configuration.Creator { public static class IdentityServerConfigurationCreator { public static IdentityServerConfiguration GetIdentityServerConfiguration() { var username = Environment.GetEnvironmentVariable("OCELOT_USERNAME"); var hash = Environment.GetEnvironmentVariable("OCELOT_HASH"); var salt = Environment.GetEnvironmentVariable("OCELOT_SALT"); return new IdentityServerConfiguration( "admin", false, SupportedTokens.Both, "secret", new List<string> { "admin", "openid", "offline_access" }, "Ocelot Administration", true, GrantTypes.ResourceOwnerPassword, AccessTokenType.Jwt, false, new List<User> { new User("admin", username, hash, salt) } ); } } }
// CivOne // // To the extent possible under law, the person who associated CC0 with // CivOne has waived all copyright and related or neighboring rights // to CivOne. // // You should have received a copy of the CC0 legalcode along with this // work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using CivOne.IO; namespace CivOne { internal partial class SaveDataAdapter { private void SetArray<T>(ref T structure, string fieldName, params byte[] values) where T : struct { IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<T>()); Marshal.StructureToPtr(structure, ptr, false); IntPtr offset = IntPtr.Add(ptr, (int)Marshal.OffsetOf<T>(fieldName)); Marshal.Copy(values, 0, offset, values.Length); structure = Marshal.PtrToStructure<T>(ptr); Marshal.FreeHGlobal(ptr); } private void SetArray(string fieldName, params byte[] values) => SetArray<SaveData>(ref _saveData, fieldName, values); private void SetArray<T>(string fieldName, params T[] values) where T : struct { int itemSize = Marshal.SizeOf<T>(); byte[] bytes = new byte[values.Length * itemSize]; for (int i = 0; i < values.Length; i++) { T value = values[i]; IntPtr ptr = Marshal.AllocHGlobal(itemSize); Marshal.StructureToPtr<T>(value, ptr, false); Marshal.Copy(ptr, bytes, (i * itemSize), itemSize); Marshal.FreeHGlobal(ptr); } SetArray(fieldName, bytes); } private void SetArray(string fieldName, params short[] values) { byte[] bytes = new byte[values.Length * 2]; Buffer.BlockCopy(values, 0, bytes, 0, values.Length); SetArray(fieldName, bytes); } private void SetArray(string fieldName, params ushort[] values) { byte[] bytes = new byte[values.Length * 2]; Buffer.BlockCopy(values, 0, bytes, 0, values.Length); SetArray(fieldName, bytes); } private void SetArray<T>(ref T structure, string fieldName, int itemLength, params string[] values) where T : struct { byte[] bytes = new byte[itemLength * values.Length]; for (int i = 0; i < values.Length; i++) for (int c = 0; c < itemLength; c++) bytes[(i * itemLength) + c] = (c >= values[i].Length) ? (byte)0 : (byte)values[i][c]; SetArray<T>(ref structure, fieldName, bytes); } private void SetArray(string fieldName, int itemLength, params string[] values) => SetArray<SaveData>(ref _saveData, fieldName, itemLength, values); private void SetDiscoveredAdvanceIDs(byte[][] input) { byte[] bytes = new byte[8 * 10]; for (int p = 0; p < 8; p++) { if (p >= input.Length) continue; bytes = bytes.ToBitIds(p * 10, 10, input[p]); } SetArray(nameof(SaveData.DiscoveredAdvances), bytes); } private void SetAdvancesCount(ushort[] values) => SetArray(nameof(SaveData.AdvancesCount), values); private void SetLeaderNames(string[] values) => SetArray(nameof(SaveData.LeaderNames), 14, values); private void SetCivilizationNames(string[] values) => SetArray(nameof(SaveData.CivilizationNames), 12, values); private void SetCitizenNames(string[] values) => SetArray(nameof(SaveData.CitizensName), 11, values); private void SetCityNames(string[] values) => SetArray(nameof(SaveData.CityNames), 13, values); private void SetPlayerGold(short[] values) => SetArray(nameof(SaveData.PlayerGold), values); private void SetResearchProgress(short[] values) => SetArray(nameof(SaveData.ResearchProgress), values); private void SetUnitsActive(UnitData[][] unitData) { ushort[] data = new ushort[8 * 28]; for (int p = 0; p < unitData.Length; p++) for (int i = 0; i < 28; i++) { data[(p * 28) + i] = (ushort)unitData[p].Count(u => u.TypeId == i); } SetArray(nameof(SaveData.UnitsActive), data); } private void SetTaxRate(ushort[] values) => SetArray(nameof(SaveData.TaxRate), values); private void SetScienceRate(ushort[] values) => SetArray(nameof(SaveData.ScienceRate), values); private void SetStartingPositionX(ushort[] values) => SetArray(nameof(SaveData.StartingPositionX), values); private void SetGovernment(ushort[] values) => SetArray(nameof(SaveData.Government), values); private void SetCityCount(ushort[] values) => SetArray(nameof(SaveData.CityCount), values); private void SetSettlerCount(ushort[] values) => SetArray(nameof(SaveData.SettlerCount), values); private void SetUnitCount(ushort[] values) => SetArray(nameof(SaveData.UnitCount), values); private void SetTotalCitySize(ushort[] values) => SetArray(nameof(SaveData.TotalCitySize), values); private void SetCities(CityData[] values) { SaveData.City[] cities = GetArray<SaveData.City>(nameof(SaveData.Cities), 128); for (int i = 0; i < new[] { values.Length, 128 }.Min(); i++) { CityData data = values[i]; byte[] fortifiedUnits = new byte[] { 0xFF, 0xFF }; if (data.FortifiedUnits != null) Array.Copy(data.FortifiedUnits, fortifiedUnits, new[] { data.FortifiedUnits.Length, 2 }.Min()); SetArray<SaveData.City>(ref cities[i], nameof(SaveData.City.Buildings), new byte[4].ToBitIds(0, 4, data.Buildings)); cities[i].X = data.X; cities[i].Y = data.Y; cities[i].Status = data.Status; cities[i].ActualSize = data.ActualSize; cities[i].VisibleSize = data.ActualSize; // TODO: Implement Visible Size cities[i].CurrentProduction = data.CurrentProduction; cities[i].BaseTrade = 0; // TODO: Implement trade cities[i].Owner = data.Owner; cities[i].Food = data.Food; cities[i].Shields = data.Shields; SetArray<SaveData.City>(ref cities[i], nameof(SaveData.City.ResourceTiles), data.ResourceTiles); cities[i].NameId = data.NameId; SetArray<SaveData.City>(ref cities[i], nameof(SaveData.City.TradingCities), new byte[] { 0xFF, 0xFF, 0xFF }); SetArray<SaveData.City>(ref cities[i], nameof(SaveData.City.FortifiedUnits), fortifiedUnits); } SetArray<SaveData.City>(nameof(SaveData.Cities), cities); } private void SetUnitTypes(SaveData.UnitType[] types) => SetArray<SaveData.UnitType>(nameof(SaveData.UnitTypes), types); private void SetUnits(UnitData[][] values) { SaveData.Unit[] units = GetArray<SaveData.Unit>(nameof(SaveData.Units), 8 * 128); for (int p = 0; p < new[] { values.Length, 8 }.Min(); p++) for (int u = 0; u < new[] { values[p].Length, 128 }.Min(); u++) { UnitData data = values[p][u]; int i = (p * 128) + u; units[i].Status = data.Status; units[i].X = data.X; units[i].Y = data.Y; units[i].Type = data.TypeId; units[i].RemainingMoves = data.RemainingMoves; units[i].SpecialMoves = data.SpecialMoves; units[i].GotoX = data.GotoX; units[i].GotoY = data.GotoY; units[i].Visibility = data.Visibility; units[i].NextUnitId = data.NextUnitId; units[i].HomeCityId = data.HomeCityId; } SetArray(nameof(SaveData.Units), units); } private void SetWonders(ushort[] values) => SetArray<ushort>(nameof(SaveData.Wonders), values); private void SetTileVisibility(bool[][,] values) { byte[] bytes = new byte[80 * 50]; for (int p = 0; p < values.Length; p++) { for (int y = 0; y < 50; y++) for (int x = 0; x < 80; x++) { bytes[(x * 50) + y] |= (byte)(values[p][x, y] ? (1 << p) : 0); } } SetArray(nameof(SaveData.MapVisibility), bytes); } private void SetAdvanceFirstDiscovery(ushort[] values) => SetArray(nameof(SaveData.AdvanceFirstDiscovery), values); private void SetCityX(byte[] values) => SetArray(nameof(SaveData.CityX), values); private void SetCityY(byte[] values) => SetArray(nameof(SaveData.CityY), values); private void SetReplayData(ReplayData[] values) { List<byte> output = new List<byte>(); foreach (ReplayData value in values) { byte entryId = 0; byte[] data; switch (value) { case ReplayData.CivilizationDestroyed civDestroyed: entryId = 0xD; data = new byte[] { (byte)civDestroyed.DestroyedId, (byte)civDestroyed.DestroyedById }; break; default: continue; } output.Add((byte)((entryId << 4) + (value.Turn & 0x0F00) >> 8)); output.Add((byte)(value.Turn & 0xFF)); output.AddRange(data); } _saveData.ReplayLength = (ushort)output.Count; SetArray(nameof(SaveData.ReplayData), output.ToArray()); } } }
/* Copyright 2016 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SampleAddIns")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Acme")] [assembly: AssemblyProduct("SampleAddIns")] [assembly: AssemblyCopyright("Copyright © Acme 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cc7881f4-bd27-4d9d-b32b-78b1e3f230c4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
// Generated from https://github.com/nuke-build/nuke/blob/master/build/specifications/Coverlet.json using JetBrains.Annotations; using Newtonsoft.Json; using Nuke.Common; using Nuke.Common.Execution; using Nuke.Common.Tooling; using Nuke.Common.Tools; using Nuke.Common.Tools.DotNet; using Nuke.Common.Utilities.Collections; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; namespace Nuke.Common.Tools.Coverlet { /// <summary> /// <p><c>Coverlet</c> is a cross platform code coverage library for .NET Core, with support for line, branch and method coverage.The <c>dotnet test</c> command is used to execute unit tests in a given project. Unit tests are console application projects that have dependencies on the unit test framework (for example, MSTest, NUnit, or xUnit) and the dotnet test runner for the unit testing framework. These are packaged as NuGet packages and are restored as ordinary dependencies for the project.</p> /// <p>For more details, visit the <a href="https://github.com/tonerdo/coverlet/">official website</a>.</p> /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class CoverletTasks { /// <summary> /// Path to the Coverlet executable. /// </summary> public static string CoverletPath => ToolPathResolver.TryGetEnvironmentExecutable("COVERLET_EXE") ?? ToolPathResolver.GetPackageExecutable("coverlet.console", "coverlet.console.dll"); public static Action<OutputType, string> CoverletLogger { get; set; } = ProcessTasks.DefaultLogger; /// <summary> /// <p><c>Coverlet</c> is a cross platform code coverage library for .NET Core, with support for line, branch and method coverage.The <c>dotnet test</c> command is used to execute unit tests in a given project. Unit tests are console application projects that have dependencies on the unit test framework (for example, MSTest, NUnit, or xUnit) and the dotnet test runner for the unit testing framework. These are packaged as NuGet packages and are restored as ordinary dependencies for the project.</p> /// <p>For more details, visit the <a href="https://github.com/tonerdo/coverlet/">official website</a>.</p> /// </summary> public static IReadOnlyCollection<Output> Coverlet(string arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Func<string, string> outputFilter = null) { var process = ProcessTasks.StartProcess(CoverletPath, arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, CoverletLogger, outputFilter); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p><c>Coverlet</c> is a cross platform code coverage library for .NET Core, with support for line, branch and method coverage.The <c>dotnet test</c> command is used to execute unit tests in a given project. Unit tests are console application projects that have dependencies on the unit test framework (for example, MSTest, NUnit, or xUnit) and the dotnet test runner for the unit testing framework. These are packaged as NuGet packages and are restored as ordinary dependencies for the project.</p> /// <p>For more details, visit the <a href="https://github.com/tonerdo/coverlet/">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>&lt;assembly&gt;</c> via <see cref="CoverletSettings.Assembly"/></li> /// <li><c>--exclude</c> via <see cref="CoverletSettings.Exclude"/></li> /// <li><c>--exclude-by-file</c> via <see cref="CoverletSettings.ExcludeByFile"/></li> /// <li><c>--format</c> via <see cref="CoverletSettings.Format"/></li> /// <li><c>--include</c> via <see cref="CoverletSettings.Include"/></li> /// <li><c>--merge-with</c> via <see cref="CoverletSettings.MergeWith"/></li> /// <li><c>--output</c> via <see cref="CoverletSettings.Output"/></li> /// <li><c>--target</c> via <see cref="CoverletSettings.Target"/></li> /// <li><c>--targetargs</c> via <see cref="CoverletSettings.TargetArgs"/></li> /// <li><c>--threshold</c> via <see cref="CoverletSettings.Threshold"/></li> /// <li><c>--threshold-type</c> via <see cref="CoverletSettings.ThresholdType"/></li> /// <li><c>--version</c> via <see cref="CoverletSettings.Version"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> Coverlet(CoverletSettings toolSettings = null) { toolSettings = toolSettings ?? new CoverletSettings(); var process = ProcessTasks.StartProcess(toolSettings); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p><c>Coverlet</c> is a cross platform code coverage library for .NET Core, with support for line, branch and method coverage.The <c>dotnet test</c> command is used to execute unit tests in a given project. Unit tests are console application projects that have dependencies on the unit test framework (for example, MSTest, NUnit, or xUnit) and the dotnet test runner for the unit testing framework. These are packaged as NuGet packages and are restored as ordinary dependencies for the project.</p> /// <p>For more details, visit the <a href="https://github.com/tonerdo/coverlet/">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>&lt;assembly&gt;</c> via <see cref="CoverletSettings.Assembly"/></li> /// <li><c>--exclude</c> via <see cref="CoverletSettings.Exclude"/></li> /// <li><c>--exclude-by-file</c> via <see cref="CoverletSettings.ExcludeByFile"/></li> /// <li><c>--format</c> via <see cref="CoverletSettings.Format"/></li> /// <li><c>--include</c> via <see cref="CoverletSettings.Include"/></li> /// <li><c>--merge-with</c> via <see cref="CoverletSettings.MergeWith"/></li> /// <li><c>--output</c> via <see cref="CoverletSettings.Output"/></li> /// <li><c>--target</c> via <see cref="CoverletSettings.Target"/></li> /// <li><c>--targetargs</c> via <see cref="CoverletSettings.TargetArgs"/></li> /// <li><c>--threshold</c> via <see cref="CoverletSettings.Threshold"/></li> /// <li><c>--threshold-type</c> via <see cref="CoverletSettings.ThresholdType"/></li> /// <li><c>--version</c> via <see cref="CoverletSettings.Version"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> Coverlet(Configure<CoverletSettings> configurator) { return Coverlet(configurator(new CoverletSettings())); } /// <summary> /// <p><c>Coverlet</c> is a cross platform code coverage library for .NET Core, with support for line, branch and method coverage.The <c>dotnet test</c> command is used to execute unit tests in a given project. Unit tests are console application projects that have dependencies on the unit test framework (for example, MSTest, NUnit, or xUnit) and the dotnet test runner for the unit testing framework. These are packaged as NuGet packages and are restored as ordinary dependencies for the project.</p> /// <p>For more details, visit the <a href="https://github.com/tonerdo/coverlet/">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>&lt;assembly&gt;</c> via <see cref="CoverletSettings.Assembly"/></li> /// <li><c>--exclude</c> via <see cref="CoverletSettings.Exclude"/></li> /// <li><c>--exclude-by-file</c> via <see cref="CoverletSettings.ExcludeByFile"/></li> /// <li><c>--format</c> via <see cref="CoverletSettings.Format"/></li> /// <li><c>--include</c> via <see cref="CoverletSettings.Include"/></li> /// <li><c>--merge-with</c> via <see cref="CoverletSettings.MergeWith"/></li> /// <li><c>--output</c> via <see cref="CoverletSettings.Output"/></li> /// <li><c>--target</c> via <see cref="CoverletSettings.Target"/></li> /// <li><c>--targetargs</c> via <see cref="CoverletSettings.TargetArgs"/></li> /// <li><c>--threshold</c> via <see cref="CoverletSettings.Threshold"/></li> /// <li><c>--threshold-type</c> via <see cref="CoverletSettings.ThresholdType"/></li> /// <li><c>--version</c> via <see cref="CoverletSettings.Version"/></li> /// </ul> /// </remarks> public static IEnumerable<(CoverletSettings Settings, IReadOnlyCollection<Output> Output)> Coverlet(CombinatorialConfigure<CoverletSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) { return configurator.Invoke(Coverlet, CoverletLogger, degreeOfParallelism, completeOnFailure); } } #region CoverletSettings /// <summary> /// Used within <see cref="CoverletTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] [Serializable] public partial class CoverletSettings : ToolSettings { /// <summary> /// Path to the Coverlet executable. /// </summary> public override string ToolPath => base.ToolPath ?? CoverletTasks.CoverletPath; public override Action<OutputType, string> CustomLogger => CoverletTasks.CoverletLogger; /// <summary> /// Path to the test assembly. /// </summary> public virtual string Assembly { get; internal set; } /// <summary> /// Path to the test runner application. /// </summary> public virtual string Target { get; internal set; } /// <summary> /// Arguments to be passed to the test runner. /// </summary> public virtual IReadOnlyList<string> TargetArgs => TargetArgsInternal.AsReadOnly(); internal List<string> TargetArgsInternal { get; set; } = new List<string>(); /// <summary> /// Output of the generated coverage report /// </summary> public virtual string Output { get; internal set; } /// <summary> /// Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run. /// </summary> public virtual IReadOnlyList<CoverletOutputFormat> Format => FormatInternal.AsReadOnly(); internal List<CoverletOutputFormat> FormatInternal { get; set; } = new List<CoverletOutputFormat>(); /// <summary> /// Exits with error if the coverage % is below value. /// </summary> public virtual int? Threshold { get; internal set; } /// <summary> /// Coverage type to apply the threshold to. /// </summary> public virtual CoverletThresholdType ThresholdType { get; internal set; } /// <summary> /// Filter expressions to exclude specific modules and types. /// </summary> public virtual IReadOnlyList<string> Exclude => ExcludeInternal.AsReadOnly(); internal List<string> ExcludeInternal { get; set; } = new List<string>(); /// <summary> /// Filter expressions to include specific modules and types. /// </summary> public virtual IReadOnlyList<string> Include => IncludeInternal.AsReadOnly(); internal List<string> IncludeInternal { get; set; } = new List<string>(); /// <summary> /// Glob patterns specifying source files to exclude. /// </summary> public virtual IReadOnlyList<string> ExcludeByFile => ExcludeByFileInternal.AsReadOnly(); internal List<string> ExcludeByFileInternal { get; set; } = new List<string>(); /// <summary> /// Show version information. /// </summary> public virtual bool? Version { get; internal set; } /// <summary> /// Path to existing coverage result to merge. /// </summary> public virtual string MergeWith { get; internal set; } protected override Arguments ConfigureArguments(Arguments arguments) { arguments .Add("{value}", Assembly) .Add("--target {value}", Target) .Add("--targetargs {value}", TargetArgs, separator: ' ', quoteMultiple: true) .Add("--output {value}", Output) .Add("--format {value}", Format) .Add("--threshold {value}", Threshold) .Add("--threshold-type {value}", ThresholdType) .Add("--exclude {value}", Exclude) .Add("--include {value}", Include) .Add("--exclude-by-file {value}", ExcludeByFile) .Add("--version", Version) .Add("--merge-with {value}", MergeWith); return base.ConfigureArguments(arguments); } } #endregion #region CoverletSettingsExtensions /// <summary> /// Used within <see cref="CoverletTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class CoverletSettingsExtensions { #region Assembly /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Assembly"/></em></p> /// <p>Path to the test assembly.</p> /// </summary> [Pure] public static CoverletSettings SetAssembly(this CoverletSettings toolSettings, string assembly) { toolSettings = toolSettings.NewInstance(); toolSettings.Assembly = assembly; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CoverletSettings.Assembly"/></em></p> /// <p>Path to the test assembly.</p> /// </summary> [Pure] public static CoverletSettings ResetAssembly(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Assembly = null; return toolSettings; } #endregion #region Target /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Target"/></em></p> /// <p>Path to the test runner application.</p> /// </summary> [Pure] public static CoverletSettings SetTarget(this CoverletSettings toolSettings, string target) { toolSettings = toolSettings.NewInstance(); toolSettings.Target = target; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CoverletSettings.Target"/></em></p> /// <p>Path to the test runner application.</p> /// </summary> [Pure] public static CoverletSettings ResetTarget(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Target = null; return toolSettings; } #endregion #region TargetArgs /// <summary> /// <p><em>Sets <see cref="CoverletSettings.TargetArgs"/> to a new list</em></p> /// <p>Arguments to be passed to the test runner.</p> /// </summary> [Pure] public static CoverletSettings SetTargetArgs(this CoverletSettings toolSettings, params string[] targetArgs) { toolSettings = toolSettings.NewInstance(); toolSettings.TargetArgsInternal = targetArgs.ToList(); return toolSettings; } /// <summary> /// <p><em>Sets <see cref="CoverletSettings.TargetArgs"/> to a new list</em></p> /// <p>Arguments to be passed to the test runner.</p> /// </summary> [Pure] public static CoverletSettings SetTargetArgs(this CoverletSettings toolSettings, IEnumerable<string> targetArgs) { toolSettings = toolSettings.NewInstance(); toolSettings.TargetArgsInternal = targetArgs.ToList(); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.TargetArgs"/></em></p> /// <p>Arguments to be passed to the test runner.</p> /// </summary> [Pure] public static CoverletSettings AddTargetArgs(this CoverletSettings toolSettings, params string[] targetArgs) { toolSettings = toolSettings.NewInstance(); toolSettings.TargetArgsInternal.AddRange(targetArgs); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.TargetArgs"/></em></p> /// <p>Arguments to be passed to the test runner.</p> /// </summary> [Pure] public static CoverletSettings AddTargetArgs(this CoverletSettings toolSettings, IEnumerable<string> targetArgs) { toolSettings = toolSettings.NewInstance(); toolSettings.TargetArgsInternal.AddRange(targetArgs); return toolSettings; } /// <summary> /// <p><em>Clears <see cref="CoverletSettings.TargetArgs"/></em></p> /// <p>Arguments to be passed to the test runner.</p> /// </summary> [Pure] public static CoverletSettings ClearTargetArgs(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.TargetArgsInternal.Clear(); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.TargetArgs"/></em></p> /// <p>Arguments to be passed to the test runner.</p> /// </summary> [Pure] public static CoverletSettings RemoveTargetArgs(this CoverletSettings toolSettings, params string[] targetArgs) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(targetArgs); toolSettings.TargetArgsInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.TargetArgs"/></em></p> /// <p>Arguments to be passed to the test runner.</p> /// </summary> [Pure] public static CoverletSettings RemoveTargetArgs(this CoverletSettings toolSettings, IEnumerable<string> targetArgs) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(targetArgs); toolSettings.TargetArgsInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } #endregion #region Output /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Output"/></em></p> /// <p>Output of the generated coverage report</p> /// </summary> [Pure] public static CoverletSettings SetOutput(this CoverletSettings toolSettings, string output) { toolSettings = toolSettings.NewInstance(); toolSettings.Output = output; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CoverletSettings.Output"/></em></p> /// <p>Output of the generated coverage report</p> /// </summary> [Pure] public static CoverletSettings ResetOutput(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Output = null; return toolSettings; } #endregion #region Format /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Format"/> to a new list</em></p> /// <p>Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run.</p> /// </summary> [Pure] public static CoverletSettings SetFormat(this CoverletSettings toolSettings, params CoverletOutputFormat[] format) { toolSettings = toolSettings.NewInstance(); toolSettings.FormatInternal = format.ToList(); return toolSettings; } /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Format"/> to a new list</em></p> /// <p>Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run.</p> /// </summary> [Pure] public static CoverletSettings SetFormat(this CoverletSettings toolSettings, IEnumerable<CoverletOutputFormat> format) { toolSettings = toolSettings.NewInstance(); toolSettings.FormatInternal = format.ToList(); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.Format"/></em></p> /// <p>Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run.</p> /// </summary> [Pure] public static CoverletSettings AddFormat(this CoverletSettings toolSettings, params CoverletOutputFormat[] format) { toolSettings = toolSettings.NewInstance(); toolSettings.FormatInternal.AddRange(format); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.Format"/></em></p> /// <p>Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run.</p> /// </summary> [Pure] public static CoverletSettings AddFormat(this CoverletSettings toolSettings, IEnumerable<CoverletOutputFormat> format) { toolSettings = toolSettings.NewInstance(); toolSettings.FormatInternal.AddRange(format); return toolSettings; } /// <summary> /// <p><em>Clears <see cref="CoverletSettings.Format"/></em></p> /// <p>Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run.</p> /// </summary> [Pure] public static CoverletSettings ClearFormat(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.FormatInternal.Clear(); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.Format"/></em></p> /// <p>Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run.</p> /// </summary> [Pure] public static CoverletSettings RemoveFormat(this CoverletSettings toolSettings, params CoverletOutputFormat[] format) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<CoverletOutputFormat>(format); toolSettings.FormatInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.Format"/></em></p> /// <p>Format of the generated coverage report.Can be specified multiple times to output multiple formats in a single run.</p> /// </summary> [Pure] public static CoverletSettings RemoveFormat(this CoverletSettings toolSettings, IEnumerable<CoverletOutputFormat> format) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<CoverletOutputFormat>(format); toolSettings.FormatInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } #endregion #region Threshold /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Threshold"/></em></p> /// <p>Exits with error if the coverage % is below value.</p> /// </summary> [Pure] public static CoverletSettings SetThreshold(this CoverletSettings toolSettings, int? threshold) { toolSettings = toolSettings.NewInstance(); toolSettings.Threshold = threshold; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CoverletSettings.Threshold"/></em></p> /// <p>Exits with error if the coverage % is below value.</p> /// </summary> [Pure] public static CoverletSettings ResetThreshold(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Threshold = null; return toolSettings; } #endregion #region ThresholdType /// <summary> /// <p><em>Sets <see cref="CoverletSettings.ThresholdType"/></em></p> /// <p>Coverage type to apply the threshold to.</p> /// </summary> [Pure] public static CoverletSettings SetThresholdType(this CoverletSettings toolSettings, CoverletThresholdType thresholdType) { toolSettings = toolSettings.NewInstance(); toolSettings.ThresholdType = thresholdType; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CoverletSettings.ThresholdType"/></em></p> /// <p>Coverage type to apply the threshold to.</p> /// </summary> [Pure] public static CoverletSettings ResetThresholdType(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.ThresholdType = null; return toolSettings; } #endregion #region Exclude /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Exclude"/> to a new list</em></p> /// <p>Filter expressions to exclude specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings SetExclude(this CoverletSettings toolSettings, params string[] exclude) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeInternal = exclude.ToList(); return toolSettings; } /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Exclude"/> to a new list</em></p> /// <p>Filter expressions to exclude specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings SetExclude(this CoverletSettings toolSettings, IEnumerable<string> exclude) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeInternal = exclude.ToList(); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.Exclude"/></em></p> /// <p>Filter expressions to exclude specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings AddExclude(this CoverletSettings toolSettings, params string[] exclude) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeInternal.AddRange(exclude); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.Exclude"/></em></p> /// <p>Filter expressions to exclude specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings AddExclude(this CoverletSettings toolSettings, IEnumerable<string> exclude) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeInternal.AddRange(exclude); return toolSettings; } /// <summary> /// <p><em>Clears <see cref="CoverletSettings.Exclude"/></em></p> /// <p>Filter expressions to exclude specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings ClearExclude(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeInternal.Clear(); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.Exclude"/></em></p> /// <p>Filter expressions to exclude specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings RemoveExclude(this CoverletSettings toolSettings, params string[] exclude) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(exclude); toolSettings.ExcludeInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.Exclude"/></em></p> /// <p>Filter expressions to exclude specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings RemoveExclude(this CoverletSettings toolSettings, IEnumerable<string> exclude) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(exclude); toolSettings.ExcludeInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } #endregion #region Include /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Include"/> to a new list</em></p> /// <p>Filter expressions to include specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings SetInclude(this CoverletSettings toolSettings, params string[] include) { toolSettings = toolSettings.NewInstance(); toolSettings.IncludeInternal = include.ToList(); return toolSettings; } /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Include"/> to a new list</em></p> /// <p>Filter expressions to include specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings SetInclude(this CoverletSettings toolSettings, IEnumerable<string> include) { toolSettings = toolSettings.NewInstance(); toolSettings.IncludeInternal = include.ToList(); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.Include"/></em></p> /// <p>Filter expressions to include specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings AddInclude(this CoverletSettings toolSettings, params string[] include) { toolSettings = toolSettings.NewInstance(); toolSettings.IncludeInternal.AddRange(include); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.Include"/></em></p> /// <p>Filter expressions to include specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings AddInclude(this CoverletSettings toolSettings, IEnumerable<string> include) { toolSettings = toolSettings.NewInstance(); toolSettings.IncludeInternal.AddRange(include); return toolSettings; } /// <summary> /// <p><em>Clears <see cref="CoverletSettings.Include"/></em></p> /// <p>Filter expressions to include specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings ClearInclude(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.IncludeInternal.Clear(); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.Include"/></em></p> /// <p>Filter expressions to include specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings RemoveInclude(this CoverletSettings toolSettings, params string[] include) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(include); toolSettings.IncludeInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.Include"/></em></p> /// <p>Filter expressions to include specific modules and types.</p> /// </summary> [Pure] public static CoverletSettings RemoveInclude(this CoverletSettings toolSettings, IEnumerable<string> include) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(include); toolSettings.IncludeInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } #endregion #region ExcludeByFile /// <summary> /// <p><em>Sets <see cref="CoverletSettings.ExcludeByFile"/> to a new list</em></p> /// <p>Glob patterns specifying source files to exclude.</p> /// </summary> [Pure] public static CoverletSettings SetExcludeByFile(this CoverletSettings toolSettings, params string[] excludeByFile) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeByFileInternal = excludeByFile.ToList(); return toolSettings; } /// <summary> /// <p><em>Sets <see cref="CoverletSettings.ExcludeByFile"/> to a new list</em></p> /// <p>Glob patterns specifying source files to exclude.</p> /// </summary> [Pure] public static CoverletSettings SetExcludeByFile(this CoverletSettings toolSettings, IEnumerable<string> excludeByFile) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeByFileInternal = excludeByFile.ToList(); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.ExcludeByFile"/></em></p> /// <p>Glob patterns specifying source files to exclude.</p> /// </summary> [Pure] public static CoverletSettings AddExcludeByFile(this CoverletSettings toolSettings, params string[] excludeByFile) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeByFileInternal.AddRange(excludeByFile); return toolSettings; } /// <summary> /// <p><em>Adds values to <see cref="CoverletSettings.ExcludeByFile"/></em></p> /// <p>Glob patterns specifying source files to exclude.</p> /// </summary> [Pure] public static CoverletSettings AddExcludeByFile(this CoverletSettings toolSettings, IEnumerable<string> excludeByFile) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeByFileInternal.AddRange(excludeByFile); return toolSettings; } /// <summary> /// <p><em>Clears <see cref="CoverletSettings.ExcludeByFile"/></em></p> /// <p>Glob patterns specifying source files to exclude.</p> /// </summary> [Pure] public static CoverletSettings ClearExcludeByFile(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.ExcludeByFileInternal.Clear(); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.ExcludeByFile"/></em></p> /// <p>Glob patterns specifying source files to exclude.</p> /// </summary> [Pure] public static CoverletSettings RemoveExcludeByFile(this CoverletSettings toolSettings, params string[] excludeByFile) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(excludeByFile); toolSettings.ExcludeByFileInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } /// <summary> /// <p><em>Removes values from <see cref="CoverletSettings.ExcludeByFile"/></em></p> /// <p>Glob patterns specifying source files to exclude.</p> /// </summary> [Pure] public static CoverletSettings RemoveExcludeByFile(this CoverletSettings toolSettings, IEnumerable<string> excludeByFile) { toolSettings = toolSettings.NewInstance(); var hashSet = new HashSet<string>(excludeByFile); toolSettings.ExcludeByFileInternal.RemoveAll(x => hashSet.Contains(x)); return toolSettings; } #endregion #region Version /// <summary> /// <p><em>Sets <see cref="CoverletSettings.Version"/></em></p> /// <p>Show version information.</p> /// </summary> [Pure] public static CoverletSettings SetVersion(this CoverletSettings toolSettings, bool? version) { toolSettings = toolSettings.NewInstance(); toolSettings.Version = version; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CoverletSettings.Version"/></em></p> /// <p>Show version information.</p> /// </summary> [Pure] public static CoverletSettings ResetVersion(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Version = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="CoverletSettings.Version"/></em></p> /// <p>Show version information.</p> /// </summary> [Pure] public static CoverletSettings EnableVersion(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Version = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="CoverletSettings.Version"/></em></p> /// <p>Show version information.</p> /// </summary> [Pure] public static CoverletSettings DisableVersion(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Version = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="CoverletSettings.Version"/></em></p> /// <p>Show version information.</p> /// </summary> [Pure] public static CoverletSettings ToggleVersion(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.Version = !toolSettings.Version; return toolSettings; } #endregion #region MergeWith /// <summary> /// <p><em>Sets <see cref="CoverletSettings.MergeWith"/></em></p> /// <p>Path to existing coverage result to merge.</p> /// </summary> [Pure] public static CoverletSettings SetMergeWith(this CoverletSettings toolSettings, string mergeWith) { toolSettings = toolSettings.NewInstance(); toolSettings.MergeWith = mergeWith; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="CoverletSettings.MergeWith"/></em></p> /// <p>Path to existing coverage result to merge.</p> /// </summary> [Pure] public static CoverletSettings ResetMergeWith(this CoverletSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.MergeWith = null; return toolSettings; } #endregion } #endregion #region DotNetTestSettingsExtensions /// <summary> /// Used within <see cref="CoverletTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class DotNetTestSettingsExtensions { #region Properties #region CollectCoverage /// <summary> /// <p><em>Sets <c>CollectCoverage</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings SetCollectCoverage(this DotNetTestSettings toolSettings, bool? collectCoverage) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["CollectCoverage"] = collectCoverage; return toolSettings; } /// <summary> /// <p><em>Resets <c>CollectCoverage</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings ResetCollectCoverage(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal.Remove("CollectCoverage"); return toolSettings; } /// <summary> /// <p><em>Enables <c>CollectCoverage</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings EnableCollectCoverage(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["CollectCoverage"] = true; return toolSettings; } /// <summary> /// <p><em>Disables <c>CollectCoverage</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings DisableCollectCoverage(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["CollectCoverage"] = false; return toolSettings; } /// <summary> /// <p><em>Toggles <c>CollectCoverage</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings ToggleCollectCoverage(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); ExtensionHelper.ToggleBoolean(toolSettings.PropertiesInternal, "CollectCoverage"); return toolSettings; } #endregion #region CoverletOutputFormat /// <summary> /// <p><em>Sets <c>CoverletOutputFormat</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings SetCoverletOutputFormat(this DotNetTestSettings toolSettings, CoverletOutputFormat coverletOutputFormat) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["CoverletOutputFormat"] = coverletOutputFormat; return toolSettings; } /// <summary> /// <p><em>Resets <c>CoverletOutputFormat</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings ResetCoverletOutputFormat(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal.Remove("CoverletOutputFormat"); return toolSettings; } #endregion #region ExcludeByFile /// <summary> /// <p><em>Sets <c>ExcludeByFile</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings SetExcludeByFile(this DotNetTestSettings toolSettings, string excludeByFile) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["ExcludeByFile"] = excludeByFile; return toolSettings; } /// <summary> /// <p><em>Resets <c>ExcludeByFile</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings ResetExcludeByFile(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal.Remove("ExcludeByFile"); return toolSettings; } #endregion #region CoverletOutput /// <summary> /// <p><em>Sets <c>CoverletOutput</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings SetCoverletOutput(this DotNetTestSettings toolSettings, string coverletOutput) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["CoverletOutput"] = coverletOutput; return toolSettings; } /// <summary> /// <p><em>Resets <c>CoverletOutput</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings ResetCoverletOutput(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal.Remove("CoverletOutput"); return toolSettings; } #endregion #region UseSourceLink /// <summary> /// <p><em>Sets <c>UseSourceLink</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings SetUseSourceLink(this DotNetTestSettings toolSettings, bool? useSourceLink) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["UseSourceLink"] = useSourceLink; return toolSettings; } /// <summary> /// <p><em>Resets <c>UseSourceLink</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings ResetUseSourceLink(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal.Remove("UseSourceLink"); return toolSettings; } /// <summary> /// <p><em>Enables <c>UseSourceLink</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings EnableUseSourceLink(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["UseSourceLink"] = true; return toolSettings; } /// <summary> /// <p><em>Disables <c>UseSourceLink</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings DisableUseSourceLink(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); toolSettings.PropertiesInternal["UseSourceLink"] = false; return toolSettings; } /// <summary> /// <p><em>Toggles <c>UseSourceLink</c> in <see cref="DotNetTestSettings.Properties"/></em></p> /// <p>Set or override the specified project-level properties, where name is the property name and value is the property value. Specify each property separately, or use a semicolon or comma to separate multiple properties, as the following example shows:</p><p><c>/property:WarningLevel=2;OutDir=bin\Debug</c></p> /// </summary> [Pure] public static DotNetTestSettings ToggleUseSourceLink(this DotNetTestSettings toolSettings) { toolSettings = toolSettings.NewInstance(); ExtensionHelper.ToggleBoolean(toolSettings.PropertiesInternal, "UseSourceLink"); return toolSettings; } #endregion #endregion } #endregion #region CoverletOutputFormat /// <summary> /// Used within <see cref="CoverletTasks"/>. /// </summary> [PublicAPI] [Serializable] [ExcludeFromCodeCoverage] [TypeConverter(typeof(TypeConverter<CoverletOutputFormat>))] public partial class CoverletOutputFormat : Enumeration { public static CoverletOutputFormat json = (CoverletOutputFormat) "json"; public static CoverletOutputFormat Icov = (CoverletOutputFormat) "Icov"; public static CoverletOutputFormat opencover = (CoverletOutputFormat) "opencover"; public static CoverletOutputFormat cobertura = (CoverletOutputFormat) "cobertura"; public static CoverletOutputFormat teamcity = (CoverletOutputFormat) "teamcity"; public static explicit operator CoverletOutputFormat(string value) { return new CoverletOutputFormat { Value = value }; } } #endregion #region CoverletThresholdType /// <summary> /// Used within <see cref="CoverletTasks"/>. /// </summary> [PublicAPI] [Serializable] [ExcludeFromCodeCoverage] [TypeConverter(typeof(TypeConverter<CoverletThresholdType>))] public partial class CoverletThresholdType : Enumeration { public static CoverletThresholdType line = (CoverletThresholdType) "line"; public static CoverletThresholdType branch = (CoverletThresholdType) "branch"; public static CoverletThresholdType method = (CoverletThresholdType) "method"; public static explicit operator CoverletThresholdType(string value) { return new CoverletThresholdType { Value = value }; } } #endregion }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Spear.Core; using Spear.Framework; using System; using System.Net; using System.Threading.Tasks; namespace Spear.WebApi.Filters { /// <inheritdoc /> /// <summary> 默认的异常处理 </summary> public class DExceptionFilter : IAsyncExceptionFilter { /// <summary> 业务消息过滤 </summary> public static Action<DResult> ResultFilter; /// <inheritdoc /> /// <summary> 异常处理 </summary> /// <param name="context"></param> public async Task OnExceptionAsync(ExceptionContext context) { var json = await ExceptionHandler.HandlerAsync(context.Exception); if (json == null) return; ResultFilter?.Invoke(json); const int code = (int)HttpStatusCode.OK; //var code = json.Code; context.Result = new JsonResult(json) { StatusCode = code }; context.HttpContext.Response.StatusCode = code; context.ExceptionHandled = true; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using DataManager.Common; using SqlSugar; namespace DataManager.IDAL { public interface IBaseRepository<T> : IDisposable where T : class, new() { #region 事务 /// <summary> /// 初始化事务 /// </summary> /// <param name="level"></param> void BeginTran(IsolationLevel level = IsolationLevel.ReadCommitted); /// <summary> /// 完成事务 /// </summary> void CommitTran(); /// <summary> /// 完成事务 /// </summary> void RollbackTran(); #endregion #region 新增 /// <summary> /// 新增 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entity"> 实体对象 </param> /// <param name="isLock">是否加锁</param> /// <returns>操作影响的行数</returns> int Add<T>(T entity, bool isLock = false) where T : class, new(); /// <summary> /// 新增 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entitys">泛型集合</param> /// <param name="isLock">是否加锁</param> /// <returns>操作影响的行数</returns> int Add<T>(List<T> entitys, bool isLock = false) where T : class, new(); /// <summary> /// 新增 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entity"> 实体对象 </param> /// <param name="isLock">是否加锁</param> /// <returns>返回实体</returns> T AddReturnEntity<T>(T entity, bool isLock = false) where T : class, new(); /// <summary> /// 新增 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entity"> 实体对象 </param> /// <param name="isLock">是否加锁</param> /// <returns>返回bool, 并将identity赋值到实体</returns> bool AddReturnBool<T>(T entity, bool isLock = false) where T : class, new(); /// <summary> /// 新增 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entitys">泛型集合</param> /// <param name="isLock">是否加锁</param> /// <returns>返回bool, 并将identity赋值到实体</returns> bool AddReturnBool<T>(List<T> entitys, bool isLock = false) where T : class, new(); #endregion #region 修改 /// <summary> /// 修改数据源 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <returns>数据源</returns> IUpdateable<T> Updateable<T>() where T : class, new(); /// <summary> /// 修改(主键是更新条件) /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entity"> 实体对象 </param> /// <param name="isLock"> 是否加锁 </param> /// <returns>操作影响的行数</returns> int Update<T>(T entity, bool isLock = false) where T : class, new(); /// <summary> /// 修改 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="update"> 字段集合 </param> /// <param name="where"> 条件 </param> /// <param name="isLock"> 是否加锁 </param> /// <returns>操作影响的行数</returns> int Update<T>(Expression<Func<T, T>> update, Expression<Func<T, bool>> where, bool isLock = false) where T : class, new(); /// <summary> /// 修改(主键是更新条件) /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entitys">泛型集合</param> /// <param name="isLock"> 是否加锁 </param> /// <returns>操作影响的行数</returns> int Update<T>(List<T> entitys, bool isLock = false) where T : class, new(); #endregion #region 删除 /// <summary> /// 删除(主键是条件) /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="entity"> 实体对象 </param> /// <param name="isLock"> 是否加锁 </param> /// <returns>操作影响的行数</returns> int Delete<T>(T entity, bool isLock = false) where T : class, new(); /// <summary> /// 删除(主键是条件) /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="where"> 条件 </param> /// <param name="isLock"> 是否加锁 </param> /// <returns>操作影响的行数</returns> int Delete<T>(Expression<Func<T, bool>> where, bool isLock = false) where T : class, new(); #endregion #region 查询 /// <summary> /// 查询数据源 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <returns>数据源</returns> ISugarQueryable<T> Queryable<T>() where T : class, new(); /// <summary> /// 查询 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="whereLambda">查询表达式</param> /// <returns></returns> T Query<T>(Expression<Func<T, bool>> whereLambda) where T : class, new(); /// <summary> /// 查询集合 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="whereLambda">查询表达式</param> /// <returns>实体</returns> List<T> QueryList<T>(Expression<Func<T, bool>> whereLambda) where T : class, new(); /// <summary> /// 查询集合 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="sql">sql</param> /// <returns>实体</returns> List<T> QueryList<T>(string sql) where T : class, new(); /// <summary> /// 查询集合 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="whereLambda">查询表达式</param> /// <returns>实体</returns> DataTable QueryDataTable<T>(Expression<Func<T, bool>> whereLambda) where T : class, new(); /// <summary> /// 查询集合 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="sql">sql</param> /// <returns>实体</returns> DataTable QueryDataTable<T>(string sql) where T : class, new(); /// <summary> /// 分页查询 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="query">查询条件</param> /// <param name="totalCount">总行数</param> /// <returns>实体</returns> List<T> QueryPageList<T>(QueryDescriptor query, out int totalCount) where T : class, new(); /// <summary> /// 分页查询 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="query">查询条件</param> /// <param name="totalCount">总行数</param> /// <returns>实体</returns> DataTable QueryDataTablePageList<T>(QueryDescriptor query, out int totalCount) where T : class, new(); /// <summary> /// 查询集合 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam> /// <param name="whereLambda">查询表达式</param> /// <returns>Json</returns> string QueryJson<T>(Expression<Func<T, bool>> whereLambda) where T : class, new(); /// <summary> /// 查询存储过程 /// </summary> /// <param name="procedureName">存储过程名称</param> /// <param name="parameters">参数</param> DataTable QueryProcedure(string procedureName, List<SugarParameter> parameters); /// <summary> /// 查询前多少条数据 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <param name="whereLambda">查询表达式</param> /// <param name="num">数量</param> /// <returns></returns> List<T> Take<T>(Expression<Func<T, bool>> whereLambda, int num) where T : class, new(); /// <summary> /// 查询单条数据 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <param name="whereLambda">查询表达式</param> /// <returns></returns> T First<T>(Expression<Func<T, bool>> whereLambda) where T : class, new(); /// <summary> /// 是否存在 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <param name="whereLambda">查询表达式</param> /// <returns></returns> bool IsExist<T>(Expression<Func<T, bool>> whereLambda) where T : class, new(); /// <summary> /// 合计 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <param name="field">字段</param> /// <returns></returns> int Sum<T>(string field) where T : class, new(); /// <summary> /// 最大值 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <param name="field">字段</param> /// <returns></returns> object Max<T>(string field) where T : class, new(); /// <summary> /// 最小值 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <param name="field">字段</param> /// <returns></returns> object Min<T>(string field) where T : class, new(); /// <summary> /// 平均值 /// </summary> /// <typeparam name="T">泛型参数(集合成员的类型</typeparam> /// <param name="field">字段</param> /// <returns></returns> int Avg<T>(string field) where T : class, new(); #endregion } }
// 版权所有(C) Microsoft Corporation。保留所有权利。 // 此代码的发布遵从 // Microsoft 公共许可(MS-PL,http://opensource.org/licenses/ms-pl.html)的条款。 using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.VisualStudio.Tools.Applications.Runtime; using Excel = Microsoft.Office.Interop.Excel; using Office = Microsoft.Office.Core; namespace RibbonControlsExcelWorkbook { public partial class Sheet2 { private void Sheet2_Startup(object sender, System.EventArgs e) { } private void Sheet2_Shutdown(object sender, System.EventArgs e) { } #region VSTO 设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 请勿 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(Sheet2_Startup); this.Shutdown += new System.EventHandler(Sheet2_Shutdown); } #endregion } }
// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Collections.Generic; namespace PixelCrushers.DialogueSystem.DialogueEditor { /// <summary> /// This part of the Dialogue Editor window handles the Conversations tab. If the user /// has selected the node editor (default), it uses the node editor part. Otherwise /// it uses the outline-style dialogue tree part. /// </summary> public partial class DialogueEditorWindow { private const int NoID = -1; [SerializeField] public bool showNodeEditor = true; private Conversation _currentConversation = null; [SerializeField] private int currentConversationID; private Conversation currentConversation { get { return _currentConversation; } set { _currentConversation = value; if (value != null) currentConversationID = value.id; } } private bool conversationFieldsFoldout = false; private Field actorField = null; private Field conversantField = null; private int actorID = NoID; private int conversantID = NoID; private bool areParticipantsValid = false; private DialogueEntry startEntry = null; private ReorderableList conversationReorderableList = null; private void SetCurrentConversation(Conversation conversation) { if (verboseDebug) Debug.Log("<color=magenta>Set current conversation to ID=" + ((conversation != null) ? conversation.id : -1) + "</color>"); ClearActorInfoCaches(); if (conversation != null && conversation.id != currentConversationID) ResetCurrentEntryID(); currentConversation = conversation; if (currentConversation != null) { canvasScrollPosition = currentConversation.canvasScrollPosition; _zoom = currentConversation.canvasZoom; } } private void SetCurrentConversationByID() { if (verboseDebug) Debug.Log("<color=magenta>Set conversation ID to " + currentConversationID + "</color>"); conversationTitles = null; OpenConversation(database.GetConversation(currentConversationID)); if (toolbar.Current == Toolbar.Tab.Conversations && Selection.activeObject == database) { SetCurrentEntryByID(); } else { currentEntry = null; } } public void RefreshConversation() { if (currentConversation == null) { ResetConversationSection(); } else { OpenConversation(currentConversation); } } private void SelectDialogueEntry(int conversationID, int dialogueEntryID) { if (database == null) return; toolbar.Current = Toolbar.Tab.Conversations; var conversation = database.GetConversation(conversationID); if (conversation == null) return; OpenConversation(conversation); var entry = conversation.GetDialogueEntry(dialogueEntryID); if (entry == null) return; SetCurrentEntry(entry); ResetNodeEditorConversationList(); dialogueTreeFoldout = true; InitializeDialogueTree(); } private void ResetConversationSection() { SetCurrentConversation(null); conversationFieldsFoldout = false; actorField = null; conversantField = null; areParticipantsValid = false; startEntry = null; selectedLink = null; actorNamesByID.Clear(); ResetDialogueTreeSection(); ResetConversationNodeSection(); } private void OpenConversation(Conversation conversation) { ResetConversationSection(); SetCurrentConversation(conversation); startEntry = GetOrCreateFirstDialogueEntry(); CheckNodeWidths(); if (showNodeEditor) CheckNodeArrangement(); } private void OpenPreviousConversation() { if (database == null) return; Conversation conversationToOpen = (database.conversations.Count > 0) ? database.conversations[0] : null; if (currentConversation != null) { conversationIndex = database.conversations.IndexOf(currentConversation); conversationIndex = (conversationIndex == 0) ? (database.conversations.Count - 1) : (conversationIndex - 1); conversationToOpen = database.conversations[conversationIndex]; } OpenConversation(conversationToOpen); } private void OpenNextConversation() { if (database == null) return; Conversation conversationToOpen = (database.conversations.Count > 0) ? database.conversations[0] : null; if (currentConversation != null) { conversationIndex = database.conversations.IndexOf(currentConversation); conversationIndex = (conversationIndex == database.conversations.Count - 1) ? 0 : (conversationIndex + 1); conversationToOpen = database.conversations[conversationIndex]; } OpenConversation(conversationToOpen); } private void DrawConversationSection() { if (showNodeEditor) { DrawConversationSectionNodeStyle(); } else { DrawConversationSectionOutlineStyle(); } } private void DrawConversationSectionOutlineStyle() { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Conversations", EditorStyles.boldLabel); GUILayout.FlexibleSpace(); DrawOutlineEditorMenu(); EditorGUILayout.EndHorizontal(); DrawConversations(); } private const string RIConversationReferenceBackend = "RelationsInspector.Backend.DialogueSystem.ConversationReferenceBackend"; private const string RIConversationLinkBackend = "RelationsInspector.Backend.DialogueSystem.ConversationLinkBackend"; private const string RIDialogueEntryLinkBackend = "RelationsInspector.Backend.DialogueSystem.DialogueEntryLinkBackend"; private void DrawOutlineEditorMenu() { if (GUILayout.Button("Menu", "MiniPullDown", GUILayout.Width(56))) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("New Conversation"), false, AddNewConversationToOutlineEditor); if (currentConversation != null) { menu.AddItem(new GUIContent("Copy Conversation"), false, CopyConversationCallback, null); menu.AddItem(new GUIContent("Split Pipes Into Entries"), false, SplitPipesIntoEntries, null); } else { menu.AddDisabledItem(new GUIContent("Copy Conversation")); menu.AddDisabledItem(new GUIContent("Split Pipes Into Entries")); } menu.AddItem(new GUIContent("Sort/By Title"), false, SortConversationsByTitle); menu.AddItem(new GUIContent("Sort/By ID"), false, SortConversationsByID); menu.AddItem(new GUIContent("Sort/Reorder IDs/This Conversation"), false, ConfirmReorderIDsThisConversation); menu.AddItem(new GUIContent("Sort/Reorder IDs/All Conversations"), false, ConfirmReorderIDsAllConversations); menu.AddItem(new GUIContent("Search Bar"), isSearchBarOpen, ToggleDialogueTreeSearchBar); menu.AddItem(new GUIContent("Nodes"), false, ActivateNodeEditorMode); if (currentConversation == null) { menu.AddDisabledItem(new GUIContent("Refresh")); } else { menu.AddItem(new GUIContent("Refresh"), false, RefreshConversation); } AddRelationsInspectorMenuItems(menu); menu.ShowAsContext(); } } private void AddRelationsInspectorMenuItems(GenericMenu menu) { if (RelationsInspectorLink.RIisAvailable) { if (RelationsInspectorLink.HasBackend(RIConversationReferenceBackend)) { menu.AddItem(new GUIContent("RelationsInspector/Conversation References"), false, OpenRelationsInspectorConversationReferenceBackend); } if (RelationsInspectorLink.HasBackend(RIConversationLinkBackend)) { menu.AddItem(new GUIContent("RelationsInspector/Conversation Links"), false, OpenRelationsInspectorConversationLinkBackend); } //--- Not working yet: //if (RelationsInspectorLink.HasBackend(RIDialogueEntryLinkBackend)) //{ // menu.AddItem(new GUIContent("RelationsInspector/Dialogue Entry Links"), false, OpenRelationsInspectorDialogueEntryLinkBackend); //} } } private void AddNewConversationToOutlineEditor() { AddNewConversation(); } private Conversation AddNewConversation() { Conversation newConversation = AddNewAsset<Conversation>(database.conversations); // Use same actors as previous conversation: if (currentConversation != null) { newConversation.ActorID = currentConversation.ActorID; newConversation.ConversantID = currentConversation.ConversantID; var startEntry = newConversation.GetFirstDialogueEntry(); if (startEntry != null) { startEntry.ActorID = currentConversation.ActorID; startEntry.ConversantID = currentConversation.ConversantID; } } if (newConversation != null) OpenConversation(newConversation); SetDatabaseDirty("Add New Conversation"); return newConversation; } private void SortConversationsByTitle() { database.conversations.Sort((x, y) => x.Title.CompareTo(y.Title)); ResetNodeEditorConversationList(); SetDatabaseDirty("Sort Conversations by Title"); } private void SortConversationsByID() { database.conversations.Sort((x, y) => x.id.CompareTo(y.id)); ResetNodeEditorConversationList(); SetDatabaseDirty("Sort Conversation by ID"); } private void OpenRelationsInspectorConversationLinkBackend() { RelationsInspectorLink.ResetTargets(new object[] { database }, RIConversationLinkBackend); } private void OpenRelationsInspectorConversationReferenceBackend() { RelationsInspectorLink.ResetTargets(new object[] { database }, RIConversationReferenceBackend); } private void OpenRelationsInspectorDialogueEntryLinkBackend() { RelationsInspectorLink.ResetTargets(new object[] { currentConversation }, RIDialogueEntryLinkBackend); } private void DrawConversations() { if (conversationReorderableList == null) { conversationReorderableList = new ReorderableList(database.conversations, typeof(Conversation), true, true, true, true); conversationReorderableList.drawHeaderCallback = DrawConversationListHeader; conversationReorderableList.drawElementCallback = DrawConversationListElement; //conversationReorderableList.drawElementBackgroundCallback = DrawConversationListElementBackground; conversationReorderableList.onAddCallback = OnConversationListAdd; conversationReorderableList.onRemoveCallback = OnConversationListRemove; conversationReorderableList.onSelectCallback = OnConversationListSelect; conversationReorderableList.onReorderCallback = OnConversationListReorder; } conversationReorderableList.DoLayoutList(); //--- 2021-04-10: Switched to reorderable list for easier reordering and more consistency with other pages. //EditorWindowTools.StartIndentedSection(); //showStateFieldAsQuest = false; //Conversation conversationToRemove = null; //int indexToMoveUp = -1; //int indexToMoveDown = -1; //for (int index = 0; index < database.conversations.Count; index++) //{ // Conversation conversation = database.conversations[index]; // EditorGUILayout.BeginHorizontal(); // bool isCurrentConversation = (conversation == currentConversation); // bool foldout = isCurrentConversation; // foldout = EditorGUILayout.Foldout(foldout, conversation.Title); // EditorGUI.BeginDisabledGroup(index >= (database.conversations.Count - 1)); // if (GUILayout.Button(new GUIContent("↓", "Move down"), GUILayout.Width(16))) indexToMoveDown = index; // EditorGUI.EndDisabledGroup(); // EditorGUI.BeginDisabledGroup(index == 0); // if (GUILayout.Button(new GUIContent("↑", "Move up"), GUILayout.Width(16))) indexToMoveUp = index; // EditorGUI.EndDisabledGroup(); // if (GUILayout.Button(new GUIContent(" ", string.Format("Delete {0}.", conversation.Title)), "OL Minus", GUILayout.Width(16))) conversationToRemove = conversation; // EditorGUILayout.EndHorizontal(); // if (foldout) // { // if (!isCurrentConversation) OpenConversation(conversation); // DrawConversation(); // } // else if (isCurrentConversation) // { // ResetConversationSection(); // } //} //if (indexToMoveDown >= 0) //{ // var conversation = database.conversations[indexToMoveDown]; // database.conversations.RemoveAt(indexToMoveDown); // database.conversations.Insert(indexToMoveDown + 1, conversation); // SetDatabaseDirty("Move Conversation Up"); //} //else if (indexToMoveUp >= 0) //{ // var conversation = database.conversations[indexToMoveUp]; // database.conversations.RemoveAt(indexToMoveUp); // database.conversations.Insert(indexToMoveUp - 1, conversation); // SetDatabaseDirty("Move Conversation Down"); //} //else if (conversationToRemove != null) //{ // if (EditorUtility.DisplayDialog(string.Format("Delete '{0}'?", conversationToRemove.Title), // "Are you sure you want to delete this conversation?\nYou cannot undo this operation!", "Delete", "Cancel")) // { // if (conversationToRemove == currentConversation) ResetConversationSection(); // database.conversations.Remove(conversationToRemove); // SetDatabaseDirty("Delete Conversation"); // } //} //EditorWindowTools.EndIndentedSection(); } private void DrawConversationListHeader(Rect rect) { EditorGUI.LabelField(rect, "Title"); } private void DrawConversationListElement(Rect rect, int index, bool isActive, bool isFocused) { if (!(0 <= index && index < database.conversations.Count)) return; var nameControl = "ConversationTitle" + index; var conversation = database.conversations[index]; var conversationTitle = conversation.Title; EditorGUI.BeginChangeCheck(); GUI.SetNextControlName(nameControl); conversationTitle = EditorGUI.TextField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), GUIContent.none, conversationTitle); if (EditorGUI.EndChangeCheck()) conversation.Title = conversationTitle; var focusedControl = GUI.GetNameOfFocusedControl(); if (string.Equals(nameControl, focusedControl)) { inspectorSelection = conversation; if (conversation != currentConversation) OpenConversation(conversation); } } //private void DrawConversationListElementBackground(Rect rect, int index, bool isActive, bool isFocused) //{ // if (!(0 <= index && index < database.conversations.Count)) return; // var conversation = database.conversations[index]; // ReorderableList.defaultBehaviours.DrawElementBackground(rect, index, isActive, isFocused, true); //} private void OnConversationListAdd(ReorderableList list) { AddNewConversation(); } private void OnConversationListRemove(ReorderableList list) { if (!(0 <= list.index && list.index < database.conversations.Count)) return; var conversation = database.conversations[list.index]; if (conversation == null) return; var deletedLastOne = list.count == 1; if (EditorUtility.DisplayDialog(string.Format("Delete '{0}'?", EditorTools.GetAssetName(conversation)), "Are you sure you want to delete this conversation?", "Delete", "Cancel")) { ReorderableList.defaultBehaviours.DoRemoveButton(list); if (deletedLastOne) inspectorSelection = null; else { var nextConversation = (list.index < list.count) ? database.conversations[list.index] : (list.count > 0) ? database.conversations[list.count - 1] : null; if (nextConversation != null) { OpenConversation(nextConversation); } else { currentConversation = null; inspectorSelection = null; } } SetDatabaseDirty("Remove Conversation"); } } private void OnConversationListReorder(ReorderableList list) { SetDatabaseDirty("Reorder Conversations"); } private void OnConversationListSelect(ReorderableList list) { if (!(0 <= list.index && list.index < database.conversations.Count)) return; var conversation = database.conversations[list.index]; Debug.Log("Select " + conversation.Title); if (conversation != currentConversation) OpenConversation(conversation); inspectorSelection = conversation; } public void DrawConversationOutline() { if (currentConversation == null) return; EditorWindowTools.StartIndentedSection(); EditorGUILayout.BeginVertical("HelpBox"); DrawConversationProperties(); DrawConversationFieldsFoldout(); DrawDialogueTreeFoldout(); EditorGUILayout.EndVertical(); EditorWindowTools.EndIndentedSection(); } public bool DrawConversationProperties() { if (currentConversation == null) return false; EditorGUI.BeginDisabledGroup(true); // Don't let user modify ID. Breaks things way more often than not. int newID = EditorGUILayout.IntField(new GUIContent("ID", "Internal ID. Change at your own risk."), currentConversation.id); EditorGUI.EndDisabledGroup(); if (newID != currentConversation.id) SetNewConversationID(newID); bool changed = false; string newTitle = EditorGUILayout.TextField(new GUIContent("Title", "Conversation triggers reference conversations by this."), currentConversation.Title); if (!string.Equals(newTitle, currentConversation.Title)) { currentConversation.Title = RemoveLeadingSlashes(newTitle); ; changed = true; SetDatabaseDirty("Change Conversation Title"); } EditorGUILayout.HelpBox("Tip: You can organize conversations into submenus by using forward slashes ( / ) in conversation titles.", MessageType.Info); var description = Field.Lookup(currentConversation.fields, "Description"); if (description != null) { EditorGUILayout.LabelField("Description"); description.value = EditorGUILayout.TextArea(description.value); } actorField = DrawConversationParticipant(new GUIContent("Actor", "Primary actor, usually the PC."), actorField); conversantField = DrawConversationParticipant(new GUIContent("Conversant", "Other actor, usually an NPC."), conversantField); DrawOverrideSettings(currentConversation.overrideSettings); DrawOtherConversationPrimaryFields(); return changed; } private string RemoveLeadingSlashes(string s) { int safeguard = 0; // Disallow leading forward slashes. while (s.StartsWith("/") && safeguard < 99) { safeguard++; s = s.Remove(0, 1); } return s; } private static List<string> conversationBuiltInFieldTitles = new List<string>(new string[] { "Title", "Description", "Actor", "Conversant" }); private void DrawOtherConversationPrimaryFields() { if (currentConversation == null || currentConversation.fields == null || template.conversationPrimaryFieldTitles == null) return; foreach (var field in currentConversation.fields) { var fieldTitle = field.title; if (string.IsNullOrEmpty(fieldTitle)) continue; if (!template.conversationPrimaryFieldTitles.Contains(field.title)) continue; if (conversationBuiltInFieldTitles.Contains(fieldTitle)) continue; DrawMainSectionField(field); } } private Field DrawConversationParticipant(GUIContent fieldTitle, Field participantField) { EditorGUILayout.BeginHorizontal(); if (participantField == null) participantField = LookupConversationParticipantField(fieldTitle.text); string originalValue = participantField.value; DrawField(participantField, false, false); if (!string.Equals(originalValue, participantField.value)) { int newParticipantID = Tools.StringToInt(participantField.value); UpdateConversationParticipant(Tools.StringToInt(originalValue), newParticipantID); startEntry = GetOrCreateFirstDialogueEntry(); if (string.Equals(fieldTitle.text, "Actor")) { if (startEntry != null) startEntry.ActorID = newParticipantID; actorID = newParticipantID; } else { if (startEntry != null) startEntry.ConversantID = newParticipantID; conversantID = newParticipantID; } areParticipantsValid = false; ResetDialogueEntryText(); SetDatabaseDirty("Change Participant"); Repaint(); } EditorGUILayout.EndHorizontal(); return participantField; } private DialogueEntry GetOrCreateFirstDialogueEntry() { if (currentConversation == null) return null; if (currentConversation.ActorID == 0) { currentConversation.ActorID = GetFirstPCID(); SetDatabaseDirty("Set Default Conversation Actor"); } if (currentConversation.ConversantID == 0) { currentConversation.ConversantID = GetFirstNPCID(); SetDatabaseDirty("Set Default Conversation Conversant"); } DialogueEntry entry = currentConversation.GetFirstDialogueEntry(); if (entry == null) { entry = CreateNewDialogueEntry("START"); entry.ActorID = currentConversation.ActorID; entry.ConversantID = currentConversation.ConversantID; SetDatabaseDirty("Create START dialogue entry"); } if (entry.ActorID == 0) { entry.ActorID = currentConversation.ActorID; SetDatabaseDirty("Set START Actor"); } if (entry.conversationID == 0) { entry.ConversantID = currentConversation.ConversantID; SetDatabaseDirty("Set START Conversant"); } return entry; } private int GetFirstPCID() { for (int i = 0; i < database.actors.Count; i++) { var actor = database.actors[i]; if (actor.IsPlayer) return actor.id; } int id = GetHighestActorID() + 1; database.actors.Add(template.CreateActor(id, "Player", true)); SetDatabaseDirty("Create Player Actor"); return id; } private int GetFirstNPCID() { for (int i = 0; i < database.actors.Count; i++) { var actor = database.actors[i]; if (!actor.IsPlayer) return actor.id; } int id = GetHighestActorID() + 1; database.actors.Add(template.CreateActor(id, "NPC", false)); SetDatabaseDirty("Create NPC Actor"); return id; } private int GetHighestActorID() { int highestID = 0; for (int i = 0; i < database.actors.Count; i++) { var actor = database.actors[i]; highestID = Mathf.Max(highestID, actor.id); } return highestID; } private Field LookupConversationParticipantField(string fieldTitle) { Field participantField = Field.Lookup(currentConversation.fields, fieldTitle); if (participantField == null) { participantField = new Field(fieldTitle, NoIDString, FieldType.Actor); currentConversation.fields.Add(participantField); SetDatabaseDirty("Add Participant Field " + fieldTitle); } return participantField; } private void UpdateConversationParticipant(int oldID, int newID) { if (newID != oldID) { for (int i = 0; i < currentConversation.dialogueEntries.Count; i++) { var entry = currentConversation.dialogueEntries[i]; if (entry.ActorID == oldID) entry.ActorID = newID; if (entry.ConversantID == oldID) entry.ConversantID = newID; } ResetDialogueTreeCurrentEntryParticipants(); ResetDialogueEntryText(); SetDatabaseDirty("Update Conversation Participant"); } } private void SetNewConversationID(int newID) { for (int i = 0; i < currentConversation.dialogueEntries.Count; i++) { var entry = currentConversation.dialogueEntries[i]; for (int j = 0; j < entry.outgoingLinks.Count; j++) { var link = entry.outgoingLinks[j]; if (link.originConversationID == currentConversation.id) link.originConversationID = newID; if (link.destinationConversationID == currentConversation.id) link.destinationConversationID = newID; } } currentConversation.id = newID; SetDatabaseDirty("Change Conversation ID"); } public void DrawConversationFieldsFoldout() { EditorGUILayout.BeginHorizontal(); conversationFieldsFoldout = EditorGUILayout.Foldout(conversationFieldsFoldout, "All Fields"); if (conversationFieldsFoldout) { GUILayout.FlexibleSpace(); if (GUILayout.Button(new GUIContent("Template", "Add any missing fields from the template."), EditorStyles.miniButton, GUILayout.Width(68))) { ApplyTemplate(currentConversation.fields, GetTemplateFields(currentConversation)); } if (GUILayout.Button(new GUIContent("Copy", "Copy these fields to the clipboard."), EditorStyles.miniButton, GUILayout.Width(60))) { CopyFields(currentConversation.fields); } EditorGUI.BeginDisabledGroup(clipboardFields == null); if (GUILayout.Button(new GUIContent("Paste", "Paste the clipboard into these fields."), EditorStyles.miniButton, GUILayout.Width(60))) { PasteFields(currentConversation.fields); } EditorGUI.EndDisabledGroup(); } if (GUILayout.Button(new GUIContent(" ", "Add new field."), "OL Plus", GUILayout.Width(16))) { currentConversation.fields.Add(new Field()); SetDatabaseDirty("Add Conversation Field"); } EditorGUILayout.EndHorizontal(); if (conversationFieldsFoldout) { if (actorID == NoID) actorID = currentConversation.ActorID; if (conversantID == NoID) conversantID = currentConversation.ConversantID; int oldActorID = actorID; int oldConversantID = conversantID; EditorGUI.BeginChangeCheck(); DrawFieldsSection(currentConversation.fields); if (EditorGUI.EndChangeCheck()) { actorID = currentConversation.ActorID; conversantID = currentConversation.ConversantID; UpdateConversationParticipant(oldActorID, actorID); UpdateConversationParticipant(oldConversantID, conversantID); } } } private bool AreConversationParticipantsValid() { if (!areParticipantsValid) { areParticipantsValid = (database.GetActor(currentConversation.ActorID) != null) && (database.GetActor(currentConversation.ConversantID) != null); } return areParticipantsValid; } private void DrawOverrideSettings(ConversationOverrideDisplaySettings settings) { settings.useOverrides = EditorGUILayout.ToggleLeft("Override Display Settings", settings.useOverrides); if (!settings.useOverrides) return; EditorWindowTools.StartIndentedSection(); settings.overrideSubtitleSettings = EditorGUILayout.ToggleLeft("Subtitle Settings", settings.overrideSubtitleSettings); if (settings.overrideSubtitleSettings) { EditorWindowTools.StartIndentedSection(); settings.showNPCSubtitlesDuringLine = EditorGUILayout.Toggle("Show NPC Subtitles During Line", settings.showNPCSubtitlesDuringLine); settings.showNPCSubtitlesWithResponses = EditorGUILayout.Toggle("Show NPC Subtitles With Responses", settings.showNPCSubtitlesWithResponses); settings.showPCSubtitlesDuringLine = EditorGUILayout.Toggle("Show PC Subtitles During Line", settings.showPCSubtitlesDuringLine); settings.skipPCSubtitleAfterResponseMenu = EditorGUILayout.Toggle("Skip PC Subtitle After Response Menu", settings.skipPCSubtitleAfterResponseMenu); settings.subtitleCharsPerSecond = EditorGUILayout.FloatField("Subtitle Chars Per Second", settings.subtitleCharsPerSecond); settings.minSubtitleSeconds = EditorGUILayout.FloatField("Min Subtitle Seconds", settings.minSubtitleSeconds); settings.continueButton = (DisplaySettings.SubtitleSettings.ContinueButtonMode)EditorGUILayout.EnumPopup("Continue Button", settings.continueButton); EditorWindowTools.EndIndentedSection(); } settings.overrideSequenceSettings = EditorGUILayout.ToggleLeft("Sequence Settings", settings.overrideSequenceSettings); if (settings.overrideSequenceSettings) { EditorWindowTools.StartIndentedSection(); settings.defaultSequence = EditorGUILayout.TextField("Default Sequence", settings.defaultSequence); settings.defaultPlayerSequence = EditorGUILayout.TextField("Default Player Sequence", settings.defaultPlayerSequence); settings.defaultResponseMenuSequence = EditorGUILayout.TextField("Default Response Menu Sequence", settings.defaultResponseMenuSequence); EditorWindowTools.EndIndentedSection(); } settings.overrideInputSettings = EditorGUILayout.ToggleLeft("Input Settings", settings.overrideInputSettings); if (settings.overrideInputSettings) { settings.alwaysForceResponseMenu = EditorGUILayout.Toggle("Always Force Response Menu", settings.alwaysForceResponseMenu); settings.includeInvalidEntries = EditorGUILayout.Toggle("Include Invalid Entries", settings.includeInvalidEntries); settings.responseTimeout = EditorGUILayout.FloatField("Response Timeout", settings.responseTimeout); settings.cancelSubtitle.key = (KeyCode)EditorGUILayout.EnumPopup("Cancel Subtitle Key", settings.cancelSubtitle.key); settings.cancelSubtitle.buttonName = EditorGUILayout.TextField("Cancel Subtitle Button", settings.cancelSubtitle.buttonName); settings.cancelConversation.key = (KeyCode)EditorGUILayout.EnumPopup("Cancel Conversation Key", settings.cancelConversation.key); settings.cancelConversation.buttonName = EditorGUILayout.TextField("Cancel Conversation Button", settings.cancelConversation.buttonName); } EditorWindowTools.EndIndentedSection(); } #region Reorder IDs private void ConfirmReorderIDsThisConversation() { if (EditorUtility.DisplayDialog("Reorder IDs", "Are you sure you want to reorder dialogue entry ID numbers in this conversation?", "OK", "Cancel")) { ReorderIDsThisConversationNow(); } } private void ReorderIDsThisConversationNow() { var currentConv = currentConversation; ReorderIDsInConversation(currentConversation); ResetConversationSection(); OpenConversation(currentConv); } private void ConfirmReorderIDsAllConversations() { if (!EditorUtility.DisplayDialog("Reorder IDs", "Are you sure you want to reorder dialogue entry ID numbers in ALL conversations?", "OK", "Cancel")) return; var currentConv = currentConversation; ReorderIDsAllConversations(); ResetConversationSection(); OpenConversation(currentConv); } private void ReorderIDsAllConversations() { if (database == null) return; foreach (var conversation in database.conversations) { OpenConversation(conversation); InitializeDialogueTree(); ReorderIDsThisConversationNow(); } ResetDialogueTreeSection(); } private void ReorderIDsInConversation(Conversation conversation) { if (conversation == null) return; try { EditorUtility.DisplayProgressBar("Reordering IDs", conversation.Title, 0); // Determine new order: var newIDs = new Dictionary<int, int>(); int nextID = 0; DetermineNewEntryID(conversation, dialogueTree, newIDs, ref nextID); // Include orphans: foreach (var entry in conversation.dialogueEntries) { if (newIDs.ContainsKey(entry.id)) continue; newIDs.Add(entry.id, nextID); nextID++; } if (debug) { var s = conversation.Title + " new IDs:\n"; foreach (var kvp in newIDs) { s += kvp.Key + " --> " + kvp.Value + "\n"; } Debug.Log(s); } // Change IDs: int tempOffset = 100000; foreach (var kvp in newIDs) { ChangeEntryIDEverywhere(conversation.id, kvp.Key, kvp.Value + tempOffset); } foreach (var kvp in newIDs) { ChangeEntryIDEverywhere(conversation.id, kvp.Value + tempOffset, kvp.Value); } // Sort entries: conversation.dialogueEntries.Sort((x, y) =>x.id.CompareTo(y.id)); } finally { EditorUtility.ClearProgressBar(); } } private void DetermineNewEntryID(Conversation conversation, DialogueNode node, Dictionary<int, int> newIDs, ref int nextID) { if (conversation == null || node == null || node.entry.conversationID != conversation.id) return; newIDs.Add(node.entry.id, nextID); nextID++; for (int i = 0; i < node.children.Count; i++) { var child = node.children[i]; if (child == null) continue; if (newIDs.ContainsKey(child.entry.id)) continue; DetermineNewEntryID(conversation, child, newIDs, ref nextID); } } private void ChangeEntryIDEverywhere(int conversationID, int oldID, int newID) { for (int c = 0; c < database.conversations.Count; c++) { var conversation = database.conversations[c]; for (int e = 0; e < conversation.dialogueEntries.Count; e++) { var entry = conversation.dialogueEntries[e]; if (conversation.id == conversationID && entry.id == oldID) { entry.id = newID; } for (int i = 0; i < entry.outgoingLinks.Count; i++) { var link = entry.outgoingLinks[i]; if (link.originConversationID == conversationID && link.originDialogueID == oldID) link.originDialogueID = newID; if (link.destinationConversationID == conversationID && link.destinationDialogueID == oldID) link.destinationDialogueID = newID; } } } } #endregion } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; namespace Microsoft.SqlTools.ServiceLayer.ExecutionPlan.ShowPlan { /// <summary> /// This class converts methods for converting from ShowPlanXML native classes /// such as ColumnReferenceType or DefinedValuesListTypeDefinedValue to /// ShowPlan control types used in UI such as string or ExpandableObjectWrapper. /// /// The actual Conversion is done within multiple static Convert methods which are /// invoked dynamically via reflection. There is code in the static constructor which /// discovers all Convert methods and stores them in a hash table using the type /// to convert from as a key. /// If you need to add a new conversion type, you typically just need to add a new /// Convert() method. /// </summary> internal class ObjectWrapperTypeConverter : ExpandableObjectConverter { /// <summary> /// Default instance /// </summary> public static ObjectWrapperTypeConverter Default = new ObjectWrapperTypeConverter(); /// <summary> /// Default converter to ExpandableObjectWrapper /// </summary> /// <param name="item"></param> /// <returns></returns> public static ExpandableObjectWrapper ConvertToWrapperObject(object item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); wrapper.DisplayName = MakeDisplayNameFromObjectNamesAndValues(wrapper); return wrapper; } #region Specific converters /// <summary> /// Converts ColumnReferenceType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(ColumnReferenceType item) { string displayName = MergeString(".", item.Database, item.Schema, item.Table, item.Column); return new ExpandableObjectWrapper(item, "Column", displayName); } /// <summary> /// Converts GroupingSetReferenceType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(GroupingSetReferenceType item) { string displayName = item.Value; return new ExpandableObjectWrapper(item, "GroupingSet", displayName); } /// <summary> /// Converts ObjectType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(ObjectType item) { string displayName = MergeString(".", item.Server, item.Database, item.Schema, item.Table, item.Index); displayName = MergeString(" ", displayName, item.Alias); if (item.CloneAccessScopeSpecified) { string cloneAccessScope = ObjectWrapperTypeConverter.Convert(item.CloneAccessScope); displayName = MergeString(" ", displayName, cloneAccessScope); } return new ExpandableObjectWrapper(item, "Index", displayName); } /// <summary> /// Converts ObjectType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(SingleColumnReferenceType item) { return Convert(item.ColumnReference); } /// <summary> /// Converts array of DefinedValuesListTypeDefinedValue to a wrapper array. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(DefinedValuesListTypeDefinedValue[] definedValues) { // Note that DefinedValuesListTypeDefinedValue has both Item and Items properties. // Each Item gets converted to property name, while Items converted to property value. ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(); StringBuilder stringBuilder = new StringBuilder(); foreach (DefinedValuesListTypeDefinedValue definedValue in definedValues) { if (definedValue.Item == null) { continue; } // Get property name which is a string representation of the first item string name = ObjectWrapperTypeConverter.Default.ConvertFrom(definedValue.Item).ToString(); if (name.Length == 0) { // Empty property name cannot be handled // TODO: may need to generate a random property name continue; } // If the property with such name already exists, skip it and continue to // the next defined value if (wrapper[name] != null) { continue; } if (stringBuilder.Length > 0) { stringBuilder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); stringBuilder.Append(" "); } if (definedValue.Items == null || definedValue.Items.Length == 0) { // If there is just one item, add the property now as an empty string stringBuilder.Append(name); wrapper[name] = String.Empty; continue; } // Convert remaining items to an wrapper object object wrappedValue = ConvertToObjectWrapper(definedValue.Items); // Add string representation of the wrappedValue to the string builder if (definedValue.Items.Length > 1) { // In the case of multiple items, we need parenthesis around the value string, // which should be a comma separated list in this case. stringBuilder.AppendFormat(CultureInfo.CurrentCulture, "[{0}] = ({1})", name, wrappedValue); } else { stringBuilder.AppendFormat(CultureInfo.CurrentCulture, "[{0}] = {1}", name, wrappedValue); } wrapper[name] = wrappedValue; } // Finally store the display name in the wrapper and return it. wrapper.DisplayName = stringBuilder.ToString(); return wrapper; } /// <summary> /// Converts ObjectType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(SetOptionsType item) { return ConvertToWrapperObject(item); } /// <summary> /// Converts RollupLevelType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(RollupLevelType item) { return new ExpandableObjectWrapper(item,SR.Level,item.Level.ToString()); } /// <summary> /// Converts WarningsType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(WarningsType item) { string displayName = String.Empty; ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); ProcessSpillOccurred(wrapper, ref displayName); ProcessColumnWithNoStatistics(wrapper, ref displayName); ProcessNoJoinPredicate(wrapper, ref displayName); ProcessSpillToTempDb(wrapper, ref displayName); ProcessHashSpillDetails(wrapper, ref displayName); ProcessSortSpillDetails(wrapper, ref displayName); ProcessWaits(wrapper, ref displayName); ProcessPlanAffectingConvert(wrapper, ref displayName); ProcessMemoryGrantWarning(wrapper, ref displayName); ProcessFullUpdateForOnlineIndexBuild(wrapper, ref displayName); if (wrapper["FullUpdateForOnlineIndexBuild"] != null) { displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, SR.FullUpdateForOnlineIndexBuild); } wrapper.DisplayName = displayName; return wrapper; } private static void ProcessWaits(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["Wait"] != null) { List<ExpandableObjectWrapper> propList = GetPropertyList(wrapper, "Wait"); Dictionary<string, int> waitTimePerWaitType = new Dictionary<string, int>(); foreach (ExpandableObjectWrapper eow in propList) { PropertyValue pVal = eow.Properties["WaitTime"] as PropertyValue; string waitTime = pVal.Value.ToString(); pVal = eow.Properties["WaitType"] as PropertyValue; string waitType = pVal.Value.ToString(); if (waitTimePerWaitType.ContainsKey(waitType)) { waitTimePerWaitType[waitType] += int.Parse(waitTime); } else { waitTimePerWaitType.Add(waitType, int.Parse(waitTime)); } } foreach (KeyValuePair<string, int> kvp in waitTimePerWaitType) { string displayStr = string.Format(SR.Wait, kvp.Value, kvp.Key); displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, displayStr); } } } private static void ProcessSpillToTempDb(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["SpillToTempDb"] != null) { List<ExpandableObjectWrapper> propList = GetPropertyList(wrapper, "SpillToTempDb"); foreach (ExpandableObjectWrapper eow in propList) { PropertyValue pVal = eow.Properties["SpillLevel"] as PropertyValue; string spillLevel = pVal.Value.ToString(); pVal = eow.Properties["SpilledThreadCount"] as PropertyValue; string displayStr = pVal != null ? string.Format(CultureInfo.CurrentCulture, SR.SpillToTempDb, spillLevel, pVal.Value.ToString()) : string.Format(CultureInfo.CurrentCulture, SR.SpillToTempDbOld, spillLevel); displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, displayStr); } } } private static void GetCommonSpillDetails(ExpandableObjectWrapper eow, out string grantedMemory, out string usedMemory, out string writes, out string reads) { PropertyValue pVal = eow.Properties["GrantedMemoryKb"] as PropertyValue; grantedMemory = pVal.Value.ToString(); pVal = eow.Properties["UsedMemoryKb"] as PropertyValue; usedMemory = pVal.Value.ToString(); pVal = eow.Properties["WritesToTempDb"] as PropertyValue; writes = pVal.Value.ToString(); pVal = eow.Properties["ReadsFromTempDb"] as PropertyValue; reads = pVal.Value.ToString(); } private static void ProcessHashSpillDetails(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["HashSpillDetails"] != null) { List<ExpandableObjectWrapper> propList = GetPropertyList(wrapper, "HashSpillDetails"); string grantedMemory; string usedMemory; string writes; string reads; foreach (ExpandableObjectWrapper eow in propList) { GetCommonSpillDetails(eow, out grantedMemory, out usedMemory, out writes, out reads); string displayStr = string.Format(SR.HashSpillDetails, writes, reads, grantedMemory, usedMemory); displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, displayStr); } } } private static void ProcessSortSpillDetails(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["SortSpillDetails"] != null) { List<ExpandableObjectWrapper> propList = GetPropertyList(wrapper, "SortSpillDetails"); string grantedMemory; string usedMemory; string writes; string reads; foreach (ExpandableObjectWrapper eow in propList) { GetCommonSpillDetails(eow, out grantedMemory, out usedMemory, out writes, out reads); string displayStr = string.Format(SR.SortSpillDetails, writes, reads, grantedMemory, usedMemory); displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, displayStr); } } } private static void ProcessSpillOccurred(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["SpillOccurred"] != null) { displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, SR.SpillOccurredDisplayString); } } private static void ProcessNoJoinPredicate(ExpandableObjectWrapper wrapper, ref string displayName) { if (Object.Equals(wrapper["NoJoinPredicate"], true)) { displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, SR.NoJoinPredicate); } } private static void ProcessColumnWithNoStatistics(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["ColumnsWithNoStatistics"] != null) { ExpandableObjectWrapper eow = wrapper["ColumnsWithNoStatistics"] as ExpandableObjectWrapper; PropertyValue pVal = eow.Properties["ColumnReference"] as PropertyValue; string displayStr = pVal.Value.ToString(); displayName = SR.NameValuePair(SR.ColumnsWithNoStatistics, displayStr); } } private static void ProcessFullUpdateForOnlineIndexBuild(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["FullUpdateForOnlineIndexBuild"] != null) { displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, SR.FullUpdateForOnlineIndexBuild); } } private static void ProcessPlanAffectingConvert(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["PlanAffectingConvert"] != null) { List<ExpandableObjectWrapper> propList = GetPropertyList(wrapper, "PlanAffectingConvert"); foreach (ExpandableObjectWrapper eow in propList) { PropertyValue pVal = eow.Properties["ConvertIssue"] as PropertyValue; string convertIssue = pVal.Value.ToString(); pVal = eow.Properties["Expression"] as PropertyValue; string expression = pVal.Value.ToString(); string displayStr = string.Format(SR.PlanAffectingConvert, expression, convertIssue); displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, displayStr); } } } private static void ProcessMemoryGrantWarning(ExpandableObjectWrapper wrapper, ref string displayName) { if (wrapper["MemoryGrantWarning"] != null) { List<ExpandableObjectWrapper> propList = GetPropertyList(wrapper, "MemoryGrantWarning"); foreach (ExpandableObjectWrapper eow in propList) { PropertyValue pValKind = eow.Properties["GrantWarningKind"] as PropertyValue; PropertyValue pValRequested = eow.Properties["RequestedMemory"] as PropertyValue; PropertyValue pValGranted = eow.Properties["GrantedMemory"] as PropertyValue; PropertyValue pValUsed = eow.Properties["MaxUsedMemory"] as PropertyValue; if (pValKind != null && pValGranted != null && pValRequested != null && pValUsed != null) { string displayString = string.Format(SR.MemoryGrantWarning, pValKind.Value.ToString(), pValRequested.Value.ToString(), pValGranted.Value.ToString(), pValUsed.Value.ToString()); displayName = MergeString(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", displayName, displayString); } } } } private static List<ExpandableObjectWrapper> GetPropertyList(ExpandableObjectWrapper wrapper, string propertyName) { List<ExpandableObjectWrapper> propList = new List<ExpandableObjectWrapper>(); foreach (PropertyDescriptor pd in wrapper.Properties) { if (pd.Name == propertyName) { PropertyValue pVal = pd as PropertyValue; propList.Add(pVal.Value as ExpandableObjectWrapper); } } return propList; } /// <summary> /// Converts WarningsType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(MemoryFractionsType item) { return ConvertToWrapperObject(item); } /// <summary> /// Converts ScalarType[][] to a string /// The format looks like (1,2,3), (4,5,6) /// </summary> /// <param name="values"></param> /// <returns></returns> public static ExpandableObjectWrapper Convert(ScalarType[][] items) { ExpandableObjectWrapper wrapper = new ExpandableArrayWrapper(items); string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < items.Length; i++) { if (i != 0) { stringBuilder.Append(separator); } stringBuilder.Append("("); for (int j = 0; j < items[i].Length; j++ ) { if (j != 0) { stringBuilder.Append(separator); } stringBuilder.Append(Convert(items[i][j])); } stringBuilder.Append(")"); } wrapper.DisplayName = stringBuilder.ToString(); return wrapper; } /// <summary> /// Converts ScalarType to a wrapper object /// </summary> /// <param name="item">scalar to be converted</param> /// <returns></returns> public static ExpandableObjectWrapper Convert(ScalarType item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); if (!string.IsNullOrEmpty(item.ScalarString)) // optional attribute { wrapper.DisplayName = String.Format( CultureInfo.CurrentCulture, "{0}({1})", SR.ScalarOperator, item.ScalarString); } else { wrapper.DisplayName = SR.ScalarOperator; } return wrapper; } /// <summary> /// Converts ScalarType to a string. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Scalar string.</returns> public static string Convert(ScalarExpressionType item) { return item.ScalarOperator != null ? item.ScalarOperator.ScalarString : String.Empty; } /// <summary> /// Converts CompareType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(CompareType item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); object scalarOperator = wrapper["ScalarOperator"]; if (scalarOperator != null) { wrapper.DisplayName = item.CompareOp.ToString(); } else { wrapper.DisplayName = String.Format( CultureInfo.CurrentCulture, "{0}({1})", item.CompareOp, scalarOperator); } return wrapper; } /// <summary> /// Converts OrderByTypeOrderByColumn to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(OrderByTypeOrderByColumn item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); wrapper.DisplayName = String.Format( CultureInfo.CurrentCulture, "{0} {1}", wrapper["ColumnReference"], item.Ascending ? SR.Ascending : SR.Descending); return wrapper; } /// <summary> /// Converts ScanRangeType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(ScanRangeType item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); object rangeColumn = wrapper["RangeColumns"]; object rangeExpressions = wrapper["RangeExpressions"]; if (rangeColumn != null && rangeExpressions != null) { string compareOperator = String.Empty; switch (item.ScanType) { case CompareOpType.EQ: compareOperator = "="; break; case CompareOpType.GE: compareOperator = ">="; break; case CompareOpType.GT: compareOperator = ">"; break; case CompareOpType.LE: compareOperator = "<="; break; case CompareOpType.LT: compareOperator = "<"; break; case CompareOpType.NE: compareOperator = "<>"; break; } if (compareOperator.Length > 0) { wrapper.DisplayName = String.Format( CultureInfo.CurrentCulture, "{0} {1} {2}", rangeColumn, compareOperator, rangeExpressions); } else { wrapper.DisplayName = String.Format( CultureInfo.CurrentCulture, "{0}({1})", item.ScanType, MergeString(",", rangeColumn, rangeExpressions)); } } return wrapper; } /// <summary> /// Converts SeekPredicateType to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(SeekPredicateType item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); // Make display name from names and values of the following 3 properties wrapper.DisplayName = MakeDisplayNameFromObjectNamesAndValues(wrapper, "Prefix", "StartRange", "EndRange"); return wrapper; } /// <summary> /// Converts SeekPredicatesType to a wrapper object. /// </summary> /// <param name="items">Objects to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(SeekPredicatesType item) { ExpandableObjectWrapper wrapper = null; if (item.Items.Length > 0 && item.Items[0] is SeekPredicateNewType) { // New schema. Parse it differently. wrapper = new ExpandableArrayWrapper(item.Items); string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "; PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(wrapper); if (properties.Count > 1) { // If there are more than one SeekPredicateNew, merge the tooltips StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < properties.Count; i++) { if (i != 0) { stringBuilder.Append(separator); } stringBuilder.Append(String.Format( CultureInfo.CurrentCulture, "{0} {1}", properties[i].DisplayName, properties[i].GetValue(wrapper).ToString())); } wrapper.DisplayName = stringBuilder.ToString(); } } else { wrapper = new ExpandableArrayWrapper(item.Items); } return wrapper; } /// <summary> /// Converts SeekPredicateNewType to a wrapper object. /// </summary> /// <param name="items">Objects to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(SeekPredicateNewType item) { ExpandableObjectWrapper wrapper = new ExpandableArrayWrapper(item.SeekKeys); // Add string "SeekKeys" to the tooltip string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "; StringBuilder stringBuilder = new StringBuilder(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(wrapper); for (int i = 0; i < properties.Count; i++) { if (i != 0) { stringBuilder.Append(separator); } stringBuilder.Append(String.Format( CultureInfo.CurrentCulture, "{0}[{1}]: {2}", SR.SeekKeys, i+1, properties[i].GetValue(wrapper).ToString())); } wrapper.DisplayName = stringBuilder.ToString(); return wrapper; } /// <summary> /// Converts SeekPredicatePartType to a wrapper object. /// </summary> /// <param name="items">Objects to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(SeekPredicatePartType item) { ExpandableObjectWrapper wrapper = new ExpandableArrayWrapper(item.Items); string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "; PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(wrapper); if (properties.Count > 1) { // If there are more than one SeekPredicateNew, merge the tooltips StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < properties.Count; i++) { if (i != 0) { stringBuilder.Append(separator); } stringBuilder.Append(String.Format( CultureInfo.CurrentCulture, "{0} {1}", properties[i].DisplayName, properties[i].GetValue(wrapper).ToString())); } wrapper.DisplayName = stringBuilder.ToString(); } return wrapper; } /// <summary> /// Converts MergeColumns to a wrapper object. /// </summary> /// <param name="item">Object to convert.</param> /// <returns>Wrapper object.</returns> public static ExpandableObjectWrapper Convert(MergeColumns item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(item); object innerSideJoinColumns = wrapper["InnerSideJoinColumns"]; object outerSideJoinColumns = wrapper["OuterSideJoinColumns"]; if (innerSideJoinColumns != null && outerSideJoinColumns != null) { wrapper.DisplayName = String.Format( CultureInfo.CurrentCulture, "({0}) = ({1})", innerSideJoinColumns, outerSideJoinColumns); } return wrapper; } public static string Convert(BaseStmtInfoTypeStatementOptmEarlyAbortReason item) { switch (item) { case BaseStmtInfoTypeStatementOptmEarlyAbortReason.TimeOut: return SR.TimeOut; case BaseStmtInfoTypeStatementOptmEarlyAbortReason.MemoryLimitExceeded: return SR.MemoryLimitExceeded; case BaseStmtInfoTypeStatementOptmEarlyAbortReason.GoodEnoughPlanFound: return SR.GoodEnoughPlanFound; default: return item.ToString(); } } public static string Convert(CloneAccessScopeType item) { switch (item) { case CloneAccessScopeType.Primary: return SR.PrimaryClones; case CloneAccessScopeType.Secondary: return SR.SecondaryClones; case CloneAccessScopeType.Both: return SR.BothClones; case CloneAccessScopeType.Either: return SR.EitherClones; case CloneAccessScopeType.ExactMatch: return SR.ExactMatchClones; default: return item.ToString(); } } #endregion #region Converters for types to be ignored public static object Convert(InternalInfoType item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(); StringBuilder stringBuilder = new StringBuilder(); using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(stringBuilder, CultureInfo.InvariantCulture))) { writer.WriteStartElement("InternalInfo"); if (item.AnyAttr != null) { foreach (XmlAttribute attribute in item.AnyAttr) { object value = ObjectWrapperTypeConverter.Convert(attribute); if (value != null) { wrapper[attribute.Name] = value; writer.WriteAttributeString(XmlConvert.EncodeLocalName(attribute.Name), value.ToString()); } } } if (item.Any != null) { foreach (XmlElement node in item.Any) { object value = ObjectWrapperTypeConverter.Convert(node); if (value != null) { wrapper[node.Name] = value; writer.WriteRaw(Convert(node).ToString()); } } } writer.WriteEndElement(); } wrapper.DisplayName = stringBuilder.ToString(); return wrapper; } public static object Convert(System.Xml.XmlElement item) { ExpandableObjectWrapper wrapper = new ExpandableObjectWrapper(); StringBuilder stringBuilder = new StringBuilder(); using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(stringBuilder, CultureInfo.InvariantCulture))) { writer.WriteStartElement(XmlConvert.EncodeLocalName(item.Name)); foreach (XmlAttribute attribute in item.Attributes) { object value = ObjectWrapperTypeConverter.Convert(attribute); if (value != null) { wrapper[attribute.Name] = value; writer.WriteAttributeString(XmlConvert.EncodeLocalName(attribute.Name), value.ToString()); } } foreach (XmlElement node in item.ChildNodes) { object value = ObjectWrapperTypeConverter.Convert(node); if (value != null) { wrapper[node.Name] = value; writer.WriteRaw(Convert(node).ToString()); } } writer.WriteEndElement(); } wrapper.DisplayName = stringBuilder.ToString(); return wrapper; } public static object Convert(System.Xml.XmlAttribute item) { return item.Value; } #endregion #region TypeConverter overrides /// <summary> /// Determines if this converter can convert an object from the specified type. /// </summary> /// <param name="context">Type descriptor context.</param> /// <param name="sourceType">Source object type.</param> /// <returns>True if the object can be converted; otherwise false.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return Type.GetTypeCode(sourceType) == TypeCode.Object || sourceType.IsArray || convertMethods.ContainsKey(sourceType); } /// <summary> /// Converts an object to a type supported by this converter. /// Note that the target type is determined by the converter itself. /// </summary> /// <param name="context">Type descriptor context.</param> /// <param name="culture">Culture.</param> /// <param name="value">The object or value to convert from.</param> /// <returns>The converted object.</returns> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { MethodInfo converter; if (convertMethods.TryGetValue(value.GetType(), out converter)) { return converter.Invoke( null, BindingFlags.Public | BindingFlags.Static, null, new object[]{ value }, CultureInfo.CurrentCulture); } else { // TODO: review this - may need better condition return ConvertToObjectWrapper(value); } } /// <summary> /// Converts an object to a specified type. /// </summary> /// <param name="context">Type descriptor context.</param> /// <param name="culture">Culture.</param> /// <param name="value">The object or value to convert from.</param> /// <param name="destType">Target type to convert to.</param> /// <returns>The converted object.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { MethodInfo converter; if (convertMethods.TryGetValue(value.GetType(), out converter) && converter.ReturnType == destType) { return converter.Invoke(this, new object[] { value }); } else { // TODO: review this - may need better condition return ConvertToObjectWrapper(value); } } #endregion #region Implementation details /// <summary> /// Converts an object to a wrapper object. /// </summary> /// <param name="item">An object to convert.</param> /// <returns>Array or object wrapper that implements ICustomTypeDescriptor and provides expandable properties.</returns> private static object ConvertToObjectWrapper(object item) { ICollection collection = item as ICollection; if (collection != null) { if (collection.Count == 1) { // There is only one object in the collection // so return the first item. IEnumerator enumerator = collection.GetEnumerator(); enumerator.MoveNext(); return ObjectWrapperTypeConverter.Default.ConvertFrom(enumerator.Current); } else { return new ExpandableArrayWrapper(collection); } } else { // Non-collection case. return new ExpandableObjectWrapper(item); } } /// <summary> /// Static constructor /// </summary> static ObjectWrapperTypeConverter() { // Hash all Convert methods by their argument type foreach (MethodInfo methodInfo in typeof(ObjectWrapperTypeConverter).GetMethods(BindingFlags.Public | BindingFlags.Static)) { if (methodInfo.Name == "Convert") { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 1) { convertMethods.Add(parameters[0].ParameterType, methodInfo); } } } } /// <summary> /// Constructs string from multiple items. /// </summary> /// <param name="separator">Separator placed between items.</param> /// <param name="items">Items to be merged.</param> /// <returns>Text string that contains merged items with separators between them.</returns> internal static string MergeString(string separator, params object[] items) { StringBuilder builder = new StringBuilder(); foreach (object item in items) { if (item != null) { string itemText = item.ToString(); if (itemText.Length > 0) { if (builder.Length > 0) { builder.Append(separator); } builder.Append(itemText); } } } return builder.ToString(); } /// <summary> /// Makes a comma separated list from object property names and values. /// This method overload enumerates all properties. /// </summary> /// <param name="item">Object to get display name for.</param> /// <returns>Display name string.</returns> private static string MakeDisplayNameFromObjectNamesAndValues(object item) { StringBuilder stringBuilder = new StringBuilder(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(item)) { AppendPropertyNameValuePair(stringBuilder, item, property); } return stringBuilder.ToString(); } /// <summary> /// Makes a comma separated list from object property names and values. /// This method overload uses only specified properties. /// </summary> /// <param name="item">Object to get display name for.</param> /// <returns></returns> private static string MakeDisplayNameFromObjectNamesAndValues(object item, params string[] propertyNames) { StringBuilder stringBuilder = new StringBuilder(); PropertyDescriptorCollection allProperties = TypeDescriptor.GetProperties(item); foreach (string name in propertyNames) { PropertyDescriptor property = allProperties[name]; if (property != null) { AppendPropertyNameValuePair(stringBuilder, item, property); } } return stringBuilder.ToString(); } /// <summary> /// An utility method that appends property name and value to string builder. /// </summary> /// <param name="stringBuilder">String builder.</param> /// <param name="item">Object that contains properties.</param> /// <param name="property">Property Descriptor.</param> private static void AppendPropertyNameValuePair(StringBuilder stringBuilder, object item, PropertyDescriptor property) { object propertyValue = property.GetValue(item); if (propertyValue != null) { if (stringBuilder.Length > 0) { stringBuilder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); stringBuilder.Append(" "); } stringBuilder.Append(SR.NameValuePair(property.DisplayName, propertyValue.ToString())); } } private static Dictionary<Type, MethodInfo> convertMethods = new Dictionary<Type, MethodInfo>(); #endregion } }
//using System.Runtime.Serialization; //using System.Text.Json.Serialization; //namespace Reductech.Sequence.Core.Entities; ///// <summary> ///// The value of an entity property. ///// </summary> //public abstract record EntityValue(object ObjectValue) //{ // /// <summary> // /// The Null value // /// </summary> // public record Null : ISCLObject // { // private Null() : base(SCLNull.Instance) { } // /// <summary> // /// The instance // /// </summary> // public static Null Instance { get; } = new(); // /// <inheritdoc /> // public override string Serialize() => "null"; // /// <inheritdoc /> // public override string Serialize() => Serialized; // private static readonly string Serialized = "null"; // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => "null"; // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // return Maybe<object>.None; // } // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) => NullNode.Instance; // /// <inheritdoc /> // public override string ToString() => Serialize(); // } // /// <summary> // /// A string value // /// </summary> // public record String(string Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override string Serialize() // { // return Value; // } // /// <inheritdoc /> // public override string Serialize() // { // return SerializationMethods.DoubleQuote(Value); // } // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => Value; // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // if (type == typeof(string)) // return Value; // if (type == typeof(StringStream) || type == typeof(object)) // return new StringStream(Value); // return Maybe<object>.None; // } // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // if (schemaConversionOptions is null) // return StringNode.Default; // return schemaConversionOptions.GetNode(Value, path); // } // /// <inheritdoc /> // public override string ToString() => Serialize(); // } // /// <summary> // /// An integer value // /// </summary> // public record Integer(int Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => Value.ToString(); // /// <inheritdoc /> // public override string Serialize() // { // return Value.ToString(); // } // /// <inheritdoc /> // public override string Serialize() => Value.ToString(); // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // if (type == typeof(int) || type == typeof(Double)) // return Value; // return Maybe<object>.None; // } // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // return IntegerNode.Default; // } // /// <inheritdoc /> // public override string ToString() => Serialize(); // } // /// <summary> // /// A double precision floating point value // /// </summary> // public record Double(double Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => Value.ToString(Constants.DoubleFormat); // /// <inheritdoc /> // public override string Serialize() => Value.ToString("R"); // /// <inheritdoc /> // public override string Serialize() => Value.ToString(Constants.DoubleFormat); // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // if (type == typeof(double)) // return Value; // return Maybe<object>.None; // } // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // return NumberNode.Default; // } // /// <inheritdoc /> // public override string ToString() => Serialize(); // } // /// <summary> // /// A boolean value // /// </summary> // public record Boolean(bool Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // return BooleanNode.Default; // } // /// <inheritdoc /> // public override string Serialize() => Value.ToString(); // /// <inheritdoc /> // public override string Serialize() => Value.ToString(); // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => Value.ToString(); // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // if (type == typeof(bool)) // return Value; // return Maybe<object>.None; // } // /// <inheritdoc /> // public override string ToString() => Serialize(); // } //TODO constant values // /// <summary> // /// An enumeration value // /// </summary> // public record EnumerationValue(ISCLEnum Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override string Serialize() => Value.ToString(); // /// <inheritdoc /> // public override string Serialize() => Value.ToString(); // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => Value.ToString(); // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // return Maybe<object>.None; // } // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // return StringNode.Default; // } // /// <inheritdoc /> // public override string ToString() => Serialize(); // } // /// <summary> // /// A date time value // /// </summary> // public record DateTime(System.DateTime Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // return new StringNode( // EnumeratedValuesNodeData.Empty, // DateTimeStringFormat.Instance, // StringRestrictions.NoRestrictions // ); // } // /// <inheritdoc /> // public override string Serialize() => Value.ToString(Constants.DateTimeFormat); // /// <inheritdoc /> // public override string Serialize() => Value.ToString(Constants.DateTimeFormat); // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => Value.ToString(dateTimeFormat); // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // if (type == typeof(System.DateTime)) // return Value; // return Maybe<object>.None; // } // /// <inheritdoc /> // public override string ToString() => Serialize(); // } // /// <summary> // /// A nested entity value // /// </summary> // public record NestedEntity(Entity Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override string Serialize() => Value.ToString(); // /// <inheritdoc /> // public override string Serialize() => Value.Serialize(); // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => Value.ToString(); // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // if (type == typeof(Entity)) // return Value; // return Maybe<object>.None; // } // /// <inheritdoc /> // public override string ToString() => Value.ToString(); // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // var dictionary = new Dictionary<string, (SchemaNode Node, bool Required)>(); // foreach (var (key, property) in Value.Dictionary.OrderBy(x => x.Value.Order)) // { // var node = property.Value.ToSchemaNode($"{path}/{key}", schemaConversionOptions); // dictionary[key] = (node, true); // } // return new EntityNode( // EnumeratedValuesNodeData.Empty, // new EntityAdditionalItems(FalseNode.Instance), // new EntityPropertiesData(dictionary) // ); // } // } // /// <summary> // /// A list of values // /// </summary> // public record NestedList(ImmutableList<ISCLObject> Value) : ISCLObject(Value) // { // /// <inheritdoc /> // public override string Serialize() => // SerializationMethods.SerializeList(Value.Select(y => y.Serialize())); // /// <inheritdoc /> // public override string Serialize() // { // return SerializationMethods.SerializeList(Value.Select(y => y.Serialize())); // } // /// <inheritdoc /> // public override string GetFormattedString( // char delimiter, // string dateTimeFormat) => string.Join( // delimiter, // Value.Select(ev1 => ev1.GetFormattedString(delimiter, dateTimeFormat)) // ); // /// <inheritdoc /> // public virtual bool Equals(NestedList? other) // { // return other is not null && Value.SequenceEqual(other.Value); // } // /// <inheritdoc /> // public override int GetHashCode() // { // if (Value.IsEmpty) // return 0; // return HashCode.Combine(Value.First(), Value.Last(), Value.Count); // } // /// <inheritdoc /> // public override string ToString() // { // return Value.Count + " elements"; // } // /// <inheritdoc /> // public override SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions) // { // SchemaNode additionalItems = new TrueNode(); // for (var index = 0; index < Value.Count; index++) // { // var entityValue = Value[index]; // var n = entityValue.ToSchemaNode(path + $"[{index}]", schemaConversionOptions); // additionalItems = additionalItems.Combine(n); // } // return new ArrayNode( // EnumeratedValuesNodeData.Empty, // new ItemsData(ImmutableList<SchemaNode>.Empty, additionalItems) // ); // } // /// <inheritdoc /> // protected override Maybe<object> AsType(Type type) // { // if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Array<>)) // { // var genericType = type.GenericTypeArguments[0]; // var elements = Value.Select(x => x.TryGetValue(genericType)) // .Combine(ErrorBuilderList.Combine); // if (elements.IsFailure) // return elements.ConvertFailure<object>(); // var createArrayMethod = // typeof(ArrayHelper).GetMethod(nameof(ArrayHelper.CreateArray))! // .MakeGenericMethod(genericType); // var arrayInstance = createArrayMethod.Invoke( // null, // new object?[] { elements.Value } // ); // return arrayInstance!; // } // return Maybe<object>.None; // } // } // /// <summary> // /// Create an entity from structured entity properties // /// </summary> // public static ISCLObject CreateFromProperties( // IReadOnlyList<(Maybe<EntityPropertyKey> key, object? argValue)> properties) // { // if (properties.Count == 0) // return Null.Instance; // if (properties.Count == 1 && properties.Single().key.HasNoValue) // return CreateFromObject(properties.Single().argValue); // var entityProperties = // new Dictionary<string, EntityProperty>(StringComparer.OrdinalIgnoreCase); // void SetEntityProperty(string key, ISCLObject ev) // { // EntityProperty newProperty; // if (entityProperties.TryGetValue(key, out var existingValue)) // { // if (ev is NestedEntity nestedEntity) // { // if (existingValue.Value is NestedEntity existingNestedEntity) // { // var nEntity = existingNestedEntity.Value.Combine(nestedEntity.Value); // newProperty = new EntityProperty( // key, // new NestedEntity(nEntity), // existingValue.Order // ); // } // else // { // //Ignore the old property // newProperty = new EntityProperty(key, ev, existingValue.Order); // } // } // else if (existingValue.Value is NestedEntity existingNestedEntity) // { // var nEntity = // existingNestedEntity.Value.WithProperty(Entity.PrimitiveKey, ev, null); // newProperty = new EntityProperty( // key, // new NestedEntity(nEntity), // existingValue.Order // ); // } // else //overwrite the existing property // newProperty = new EntityProperty(key, ev, existingValue.Order); // } // else //New property // newProperty = new EntityProperty(key, ev, entityProperties.Count); // entityProperties[key] = newProperty; // } // foreach (var (key, argValue) in properties) // { // if (key.HasNoValue) // { // var ev = CreateFromObject(argValue); // if (ev is NestedEntity ne) // foreach (var (nestedKey, value) in ne.Value.Dictionary) // SetEntityProperty(nestedKey, value.Value); // else // SetEntityProperty(Entity.PrimitiveKey, ev); // } // else // { // var (firstKey, remainder) = key.GetValueOrThrow().Split(); // var ev = CreateFromProperties(new[] { (remainder, argValue) }); // SetEntityProperty(firstKey, ev); // } // } // var newEntity = new Entity(entityProperties.ToImmutableDictionary()); // return new NestedEntity(newEntity); // } // /// <summary> // /// Create an entity from an object // /// </summary> // public static ISCLObject CreateFromObject(object? argValue) // { // switch (argValue) // { // case null: return Null.Instance; // case SCLNull: return Null.Instance; // case ISCLObject ev: return ev; // case StringStream ss1: return CreateFromString(ss1.GetString()); // case string s: return CreateFromString(s); // case int i: return new Integer(i); // case byte @byte: return new Integer(@byte); // case short @short: return new Integer(@short); // case bool b: return new Boolean(b); // case double d: return new Double(d); // case long ln and < int.MaxValue and > int.MinValue: // return new Integer(Convert.ToInt32(ln)); // case ISCLEnum e1: return new EnumerationValue(e1); // case System.DateTime dt: return new DateTime(dt); // case Enum e: return new EnumerationValue(e.ConvertToSCLEnum()); // case JsonElement je: return Create(je); // case Entity entity: return new NestedEntity(entity); // case IEntityConvertible ec: return new NestedEntity(ec.ConvertToEntity()); // case Version version: return new String(version.ToString()); // case IDictionary dict: // { // var builder = ImmutableDictionary<string, EntityProperty>.Empty.ToBuilder(); // builder.KeyComparer = StringComparer.OrdinalIgnoreCase; // var i = 0; // foreach (DictionaryEntry dictionaryEntry in dict) // { // var val = dictionaryEntry.Value; // var ev = CreateFromObject(val); // var ep = new EntityProperty(dictionaryEntry.Key.ToString()!, ev, i); // builder.Add(dictionaryEntry.Key.ToString()!, ep); // i++; // } // var entity = new Entity(builder.ToImmutable()); // return new NestedEntity(entity); // } // case IEnumerable e2: // { // var newEnumerable = e2.Cast<object>() // .Select(CreateFromObject) // .ToImmutableList(); // if (!newEnumerable.Any()) // return Null.Instance; // return new NestedList(newEnumerable); // } // case IResult: // throw new ArgumentException( // "Attempt to set ISCLObject to a Result - you should check the result for failure and then set it to the value of the result", // nameof(argValue) // ); // default: // { // if (argValue.GetType() // .GetCustomAttributes(true) // .OfType<SerializableAttribute>() // .Any() || // argValue.GetType() // .GetCustomAttributes(true) // .OfType<DataContractAttribute>() // .Any() // ) // { // var entity = EntityConversionHelpers.ConvertToEntity(argValue); // return new NestedEntity(entity); // } // throw new ArgumentException( // $"Attempt to set ISCLObject to {argValue.GetType().Name}" // ); // } // } // static ISCLObject CreateFromString(string s) // { // return new String(s); // } // } // /// <summary> // /// Create an ISCLObject from a JsonElement // /// </summary> // public static ISCLObject Create(JsonElement element) // { // switch (element.ValueKind) // { // case JsonValueKind.Undefined: return Null.Instance; // case JsonValueKind.Object: // { // var dict = element.EnumerateObject() // .GroupBy(x => x.Name, StringComparer.OrdinalIgnoreCase) // .Select( // (x, i) => // new EntityProperty(x.First().Name, Create(x.First().Value), i) // ) // .ToImmutableDictionary(x => x.Name, StringComparer.OrdinalIgnoreCase); // var entity = new Entity(dict); // return new NestedEntity(entity); // } // case JsonValueKind.Array: // { // var list = element.EnumerateArray().Select(Create).ToImmutableList(); // return new NestedList(list); // } // case JsonValueKind.String: return new String(element.GetString()!); // case JsonValueKind.Number: // { // if (element.TryGetInt32(out var i)) // return new Integer(i); // return new Double(element.GetDouble()); // } // case JsonValueKind.True: return new Boolean(true); // case JsonValueKind.False: return new Boolean(false); // case JsonValueKind.Null: return Null.Instance; // default: throw new ArgumentOutOfRangeException(element.ValueKind.ToString()); // } // } // /// <summary> // /// Gets a schema node which could match this entity value // /// </summary> // [Pure] // public abstract SchemaNode ToSchemaNode( // string path, // SchemaConversionOptions? schemaConversionOptions); // /// <summary> // /// Convert this Entity to a Json Element // /// </summary> // [Pure] // public JsonElement ToJsonElement() // { // var options = new JsonSerializerOptions() // { // Converters = { new JsonStringEnumConverter() } // }; // var element = ObjectValue.ToJsonDocument(options).RootElement.Clone(); // return element; // } // /// <summary> // /// If this is a primitive, get a string representation // /// </summary> // public abstract string Serialize(); // /// <summary> // /// Serialize this value as it will appear in SCL // /// </summary> // public abstract string Serialize(); // /// <summary> // /// Gets a string with the given format // /// </summary> // public abstract string GetFormattedString( // char delimiter, // string dateTimeFormat); // /// <summary> // /// Gets the default entity value for a particular type // /// </summary> // public static T GetDefaultValue<T>() // { // if (Entity.Empty is T tEntity) // return tEntity; // if (StringStream.Empty is T tStringStream) // return tStringStream; // if ("" is T tString) // return tString; // if (typeof(T).IsAssignableTo(typeof(IArray)) && typeof(T).IsGenericType) // { // var param = typeof(T).GenericTypeArguments[0]; // var array = typeof(EagerArray<>).MakeGenericType(param); // var arrayInstance = Activator.CreateInstance(array); // return (T)arrayInstance!; // } // return default!; // } // /// <summary> // /// Returns the value, if it is of a particular type // /// </summary> // protected abstract Maybe<object> AsType(Type type); // private Result<object, IErrorBuilder> TryGetValue(Type type) // { // var maybeObject = AsType(type); // if (maybeObject.HasValue) // return maybeObject.GetValueOrThrow(); // var primitive = Serialize(); // if (type == typeof(int)) // { // if (int.TryParse(primitive, out var i)) // return i; // } // else if (type == typeof(double)) // { // if (double.TryParse(primitive, out var d)) // return d; // } // else if (type == typeof(bool)) // { // if (bool.TryParse(primitive, out var b)) // return b; // } // else if (type.IsEnum) // { // if (this is EnumerationValue enumeration) // { // if (Enum.TryParse(type, enumeration.Value.EnumValue, true, out var ro)) // return ro!; // } // else if (!int.TryParse(primitive, out _) && //prevent int conversion // Enum.TryParse(type, primitive, true, out var r) // ) // return r!; // } // else if (type == typeof(System.DateTime)) // { // if (!double.TryParse(primitive, out _) && //prevent double conversion // System.DateTime.TryParse(primitive, out var d)) // return d; // } // else if (type == typeof(string)) // { // var ser = Serialize(); // return ser; // } // else if (type == typeof(StringStream)) // { // var ser = new StringStream(Serialize()); // return ser; // } // else if (type == typeof(object)) // { // return AsISCLObject(ObjectValue); // new StringStream(Serialize()); // } // else if (type.GetInterfaces().Contains(typeof(IOneOf))) // { // var i = 0; // foreach (var typeGenericTypeArgument in type.GenericTypeArguments) // { // var value = TryGetValue(typeGenericTypeArgument); // if (value.IsSuccess) // { // var methodName = $"FromT{i}"; // var method = type.GetMethod( // methodName, // BindingFlags.Static | BindingFlags.Public // )!; // var oneOfThing = method.Invoke(null, new[] { value.Value })!; // return Result.Success<object, IErrorBuilder>(oneOfThing); // } // i++; // } // } // return ErrorCode.CouldNotConvertISCLObject.ToErrorBuilder(type.Name); // } // private static object AsISCLObject(object? o) // { // if (o is null) // return SCLNull.Instance; // if (o is int i) // return i; // if (o is double d) // return d; // if (o is string s) // return new StringStream(s); // if (o is StringStream ss) // return ss; // if (o is System.DateTime dt) // return dt; // if (o is IArray) // return o; // if (o is Entity e) // return e; // if (o is IEnumerable enumerable) // return SerializationMethods.SerializeList( // enumerable.OfType<ISCLObject>().Select(x => x.Serialize()) // ); // if (o is ISCLEnum enumeration) // return enumeration; // return SCLNull.Instance; // } // /// <summary> // /// Tries to get the value if it is a particular type // /// </summary> // public Result<T, IErrorBuilder> TryGetValue<T>() // { // var r = TryGetValue(typeof(T)); // if (r.IsFailure) // return r.ConvertFailure<T>(); // return (T)r.Value!; // } //}
//<unit_header> //---------------------------------------------------------------- // // Martin Korneffel: IT Beratung/Softwareentwicklung // Stuttgart, den 02.11.2017 // // Projekt.......: mko // Name..........: LaunchTimeSingleton.cs // Aufgabe/Fkt...: Records the start time of a application. // Useful for calculating time differences. // // // // //<unit_environment> //------------------------------------------------------------------ // Zielmaschine..: PC // Betriebssystem: Windows 7 mit .NET 4.5 // Werkzeuge.....: Visual Studio 2013 // Autor.........: Martin Korneffel (mko) // Version 1.0...: // // </unit_environment> // //<unit_history> //------------------------------------------------------------------ // // Version.......: 1.1 // Autor.........: Martin Korneffel (mko) // Datum.........: // Änderungen....: // //</unit_history> //</unit_header> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ATMO.mko.Logging { /// <summary> /// mko, 2.11.2017 /// Records the start time of a application. /// </summary> public class StartTimeSingleton { public static StartTimeSingleton Instance { get { if (_instance == null) { _instance = new StartTimeSingleton(); } return _instance; } } static StartTimeSingleton _instance; public static long TimeDifferenceToStartTimeInMs(DateTime now) { var t = Math.Round(new TimeSpan(now.Ticks - StartTimeSingleton.Instance.StartTime.Ticks).TotalMilliseconds, 0); return (long)t; } public static long ElapsedTimeSinceStartInMs { get { return TimeDifferenceToStartTimeInMs(DateTime.Now); } } internal StartTimeSingleton() { StartTime = DateTime.Now; } public DateTime StartTime { get; } } }
//****************************************************************************************************** // DataCellCollection.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 11/12/2004 - J. Ritchie Carroll // Generated original version of source code. // 09/15/2009 - Stephen C. Wills // Added new header and license agreement. // 12/17/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** using System; using System.Runtime.Serialization; namespace GSF.PhasorProtocols.FNET { /// <summary> /// Represents a F-NET implementation of a collection of <see cref="IDataCell"/> objects. /// </summary> [Serializable] public class DataCellCollection : PhasorProtocols.DataCellCollection { #region [ Constructors ] /// <summary> /// Creates a new <see cref="DataCellCollection"/>. /// </summary> public DataCellCollection() : base(0, true) { // F-NET only supports a single device - so there should only be one cell - since there's only one cell, cell lengths will be constant :) } /// <summary> /// Creates a new <see cref="DataCellCollection"/> from serialization parameters. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param> /// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param> protected DataCellCollection(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion #region [ Properties ] /// <summary> /// Gets or sets <see cref="DataCell"/> at specified <paramref name="index"/>. /// </summary> /// <param name="index">Index of value to get or set.</param> public new DataCell this[int index] { get { return base[index] as DataCell; } set { base[index] = value; } } #endregion } }
using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using R5T.S0026.Library; using Instances = R5T.S0026.Library.Instances; namespace System { public static class ICompilationUnitContextProviderExtensions { public static async Task InAcquiredCompilationUnitContext(this ICompilationUnitContextProvider compilationUnitContextProvider, string codeFilePath, Func<ICompilationUnitContext, CompilationUnitSyntax, Task<CompilationUnitSyntax>> compilationUnitContextAction) { var compilationUnitContext = compilationUnitContextProvider.GetCompilationUnitContext(); await Instances.CompilationUnitOperator.ModifyAcquired( codeFilePath, async compilationUnit => { var outputCompilationUnit = await compilationUnitContextAction( compilationUnitContext, compilationUnit); return outputCompilationUnit; }, compilationUnit => Task.FromResult(compilationUnit)); } public static Task InAcquiredCompilationUnitContext(this ICompilationUnitContextProvider compilationUnitContextProvider, IFileContext fileContext, Func<ICompilationUnitContext, CompilationUnitSyntax, Task<CompilationUnitSyntax>> compilationUnitContextAction) { return compilationUnitContextProvider.InAcquiredCompilationUnitContext( fileContext.FilePath, compilationUnitContextAction); } } } namespace R5T.S0026.Library { public static class ICompilationUnitContextProviderExtensions { public static CompilationUnitContext GetCompilationUnitContext(this ICompilationUnitContextProvider compilationUnitContextProvider) { var output = new CompilationUnitContext { UsingDirectivesFormatter = compilationUnitContextProvider.UsingDirectivesFormatter, }; return output; } } }
namespace SimpleMvcApp.Controllers { using System.Web.Mvc; using Services; public class StatisticsController : Controller { private readonly ProjectsService projects; public StatisticsController() { this.projects = new ProjectsService(); } public ActionResult All() { return View(this.projects.All().Count); } } }
 using System; using System.Collections.Generic; namespace DatabaseFramework.Compare { /// <summary> /// Description of DatabaseComparer. /// </summary> public interface DatabaseComparer { Database newDatabase {get;set;} Database existingDatabase {get;set;} List<DatabaseItemComparison> comparedItems {get;set;} void setOverride(DatabaseItemComparison overrideCompare, bool overrideValue,List<DatabaseItem>updatedNewItems = null); void compare(); void save(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using DotNetBlog.Models; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; using DotNetBlog.Services; using Microsoft.Extensions.Hosting; using System.Data.Common; using MySql.Data.MySqlClient; using System.Data; using System.Text.Encodings.Web; using System.Text.Unicode; namespace DotNetBlog { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddDbContext<GuorjAccountDbContext>(options => //{ // options.UseMySQL(Configuration.GetConnectionString("GuorjAccountConnection")); //}); //services.AddDbContext<GuorjBlogDbContext>(options => //{ // options.UseMySQL(Configuration.GetConnectionString("GuorjBlogConnection")); //}); //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) // .AddCookie(options => // { // //CookieBuilder builder = new CookieBuilder(); // //builder.Name = "s"; // //builder.Build(context: null); // //https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x // }); services.AddTransient<IDbConnectionFactory, DbConnectionFactory>(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => { options.Cookie.Name = "auth"; }); services.AddRazorPages().AddRazorPagesOptions(options => { options.Conventions.AuthorizeFolder("/Account/Manage"); options.Conventions.AuthorizeFolder("/Blog/Manage"); options.Conventions.AuthorizePage("/Account/Logout"); options.Conventions.AddPageRoute("/Blog/Post", "Blog/Post/{PostURL?}"); options.Conventions.AddPageRoute("/Blog/Manage/Edit", "Blog/Manage/Post/New"); options.Conventions.AddPageRoute("/Blog/Manage/Edit", "Blog/Manage/Edit/{PostID?}"); options.Conventions.AddPageRoute("/Blog/GetComments", "Blog/Post/GetComments/{PostID?}/{ContentID?}"); options.Conventions.AddPageRoute("/Blog/AddComment", "Blog/Post/AddComment/{PostID?}/{ContentID?}"); }).AddNewtonsoftJson(); services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); }); //services.AddMemoryCache(options => //{ // options.SizeLimit = 1024 * 1024; //}); // Register no-op EmailSender used by account confirmation and password reset during development // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 services.AddSingleton<IEmailSender, EmailSender>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); //app.UseCookiePolicy(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
using CommunityToolkit.Mvvm.Input; using System; #nullable enable namespace MoneyFox.Uwp.ViewModels.Interfaces { /// <summary> /// Represents the Actions for a view. /// </summary> public interface IPaymentListViewActionViewModel { /// <summary> /// Deletes the currently selected account. /// </summary> AsyncRelayCommand DeleteAccountCommand { get; } /// <summary> /// Apply the filter and reload the list. /// </summary> RelayCommand ApplyFilterCommand { get; } /// <summary> /// Indicates wether the filter for only cleared Payments is active or not. /// </summary> bool IsClearedFilterActive { get; set; } /// <summary> /// Indicates wether the filter to only display recurring Payments is active or not. /// </summary> bool IsRecurringFilterActive { get; set; } /// <summary> /// Indicates wether the paymentlist should be grouped /// </summary> bool IsGrouped { get; set; } /// <summary> /// Start of the time range to load payments. /// </summary> DateTime TimeRangeStart { get; set; } /// <summary> /// End of the time range to load payments. /// </summary> DateTime TimeRangeEnd { get; set; } } }
using System; using System.Collections.Generic; using System.Data; //using System.DirectoryServices; using System.Net.Mail; using System.Text; using VNC; using VNCAssemblyViewer.Data; //using SQLInformation.Data; namespace VNCAssemblyViewer.Helpers { public class Email { private static int CLASS_BASE_ERRORNUMBER = VNCAssemblyViewer.ErrorNumbers.VNCAssemblyViewer; private const string LOG_APPNAME = Common.LOG_APPNAME; public static void SendEmail(string sTo, string sFrom, string sSubject, string sBody, string sCC) { using (MailMessage mailMessage = new MailMessage(sFrom, sTo, sSubject, sBody)) { // TODO(crhodes): Figure out how to do format types. //message.BodyFormat = MailFormat.Text; if (sCC != "") { mailMessage.CC.Add(sCC); } SendEmail(mailMessage); } } public static void SendEmail(string sTo, string sFrom, string sSubject, string sBody, string sCC, List<string> attachments) { using (MailMessage mailMessage = new MailMessage(sFrom, sTo, sSubject, sBody)) { //message.BodyFormat = MailFormat.Text; if (sCC != "") { mailMessage.CC.Add(sCC); } foreach (string attachment in attachments) { mailMessage.Attachments.Add(new Attachment(attachment)); } SendEmail(mailMessage); } } public static void SendEmail(MailMessage message) { if (Config.SMTP_Server != "") { SmtpClient smtp = new SmtpClient(Config.SMTP_Server); try { smtp.Send(message); } catch (Exception ex) { VNC.AppLog.Error(ex, LOG_APPNAME, CLASS_BASE_ERRORNUMBER + 8); throw new ApplicationException("Cannot Send Email"); } } else { // TODO(crhodes): Something about no SMTP throw new ApplicationException("SMTP Server not configured"); } } } }
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; namespace AliFitnessAE_SP.Authentication.JwtBearer { public static class JwtTokenMiddleware { public static IApplicationBuilder UseJwtTokenMiddleware(this IApplicationBuilder app, string schema = JwtBearerDefaults.AuthenticationScheme) { return app.Use(async (ctx, next) => { if (ctx.User.Identity?.IsAuthenticated != true) { var result = await ctx.AuthenticateAsync(schema); if (result.Succeeded && result.Principal != null) { ctx.User = result.Principal; } } await next(); }); } } }
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.Greengrass")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Greengrass. AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Greengrass. AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS Greengrass. AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS Greengrass. AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS Greengrass. AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS Greengrass. AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.101.10")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.IoTEvents")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT Events. The AWS IoT Events service allows customers to monitor their IoT devices and sensors to detect failures or changes in operation and to trigger actions when these events occur")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS IoT Events. The AWS IoT Events service allows customers to monitor their IoT devices and sensors to detect failures or changes in operation and to trigger actions when these events occur")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS IoT Events. The AWS IoT Events service allows customers to monitor their IoT devices and sensors to detect failures or changes in operation and to trigger actions when these events occur")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS IoT Events. The AWS IoT Events service allows customers to monitor their IoT devices and sensors to detect failures or changes in operation and to trigger actions when these events occur")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.1.77")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Storage.V20190601.Outputs { /// <summary> /// Management policy action for snapshot. /// </summary> [OutputType] public sealed class ManagementPolicySnapShotResponse { /// <summary> /// The function to delete the blob snapshot /// </summary> public readonly Outputs.DateAfterCreationResponse? Delete; /// <summary> /// The function to tier blob snapshot to archive storage. Support blob snapshot currently at Hot or Cool tier /// </summary> public readonly Outputs.DateAfterCreationResponse? TierToArchive; /// <summary> /// The function to tier blob snapshot to cool storage. Support blob snapshot currently at Hot tier /// </summary> public readonly Outputs.DateAfterCreationResponse? TierToCool; [OutputConstructor] private ManagementPolicySnapShotResponse( Outputs.DateAfterCreationResponse? delete, Outputs.DateAfterCreationResponse? tierToArchive, Outputs.DateAfterCreationResponse? tierToCool) { Delete = delete; TierToArchive = tierToArchive; TierToCool = tierToCool; } } }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebAppOne.Asp.net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebAppOne.Asp.net")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e273b0dc-aca6-4a01-9480-84bc2863f1c6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
// (c) Copyright ESRI. // This source is subject to the Microsoft Public License (Ms-PL). // Please see https://opensource.org/licenses/ms-pl for details. // All other rights reserved using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Messaging; using ArcGISPortalViewer.Helpers; using ArcGISPortalViewer.Model; using System; using System.Linq; using System.Threading.Tasks; using Esri.ArcGISRuntime.Portal; using Esri.ArcGISRuntime.Security; using Windows.Security.Credentials.UI; namespace ArcGISPortalViewer.ViewModel { public class SignInViewModel : ViewModelBase { /// <summary> /// The <see cref="IsSigningIn" /> property's name. /// </summary> public const string IsSigningInPropertyName = "IsSigningIn"; private bool _isSigningIn = false; /// <summary> /// Sets and gets the IsSigningIn property. /// Changes to that property's value raise the PropertyChanged event. /// </summary> public bool IsSigningIn { get { return _isSigningIn; } set { Set(IsSigningInPropertyName, ref _isSigningIn, value); } } public bool IsCredentialsPersisted { get; private set; } public SignInViewModel() { Initialize(); Messenger.Default.Register<ChangeSignInMessage>(this, msg => { var _ = SignInAsync(); }); Messenger.Default.Register<ChangeSignOutMessage>(this, msg => { var _ = SignOutAsync(); }); } private void Initialize() { // set IsCredentialsPersisted to false IsCredentialsPersisted = false; if (App.IsOrgOAuth2) return; // Initialize challenge handler to allow storage in the credential locker and restore the credentials var defaultChallengeHandler = IdentityManager.Current.ChallengeHandler as DefaultChallengeHandler; if (defaultChallengeHandler != null) { defaultChallengeHandler.AllowSaveCredentials = true; defaultChallengeHandler.CredentialSaveOption = CredentialSaveOption.Selected; // set it to CredentialSaveOption.Hidden if it's not an user choice } IsCredentialsPersisted = IdentityManager.Current.Credentials.Any(); } public async Task TrySigningInAsync() { try { var _ = await SignInAsync(); } catch (Exception ex) { var _ = App.ShowExceptionDialog(ex); } } public async Task<bool> GetAnonymousAccessStatusAsync() { bool b = false; if (PortalService.CurrentPortalService.Portal != null) b = PortalService.CurrentPortalService.Portal.ArcGISPortalInfo.Access == PortalAccess.Public; else { var challengeHandler = IdentityManager.Current.ChallengeHandler; // Deactivate the challenge handler temporarily before creating the portal (else challengehandler would be called for portal secured by native) IdentityManager.Current.ChallengeHandler = new ChallengeHandler(crd => null); ArcGISPortal p = null; try { p = await ArcGISPortal.CreateAsync(App.PortalUri.Uri); } catch { } if (p != null && p.ArcGISPortalInfo != null) { b = p.ArcGISPortalInfo.Access == PortalAccess.Public; } // Restore ChallengeHandler IdentityManager.Current.ChallengeHandler = challengeHandler; } return b; } public async Task SignInAnonymouslyAsync() { await PortalService.CurrentPortalService.AttemptAnonymousAccessAsync(); } public async Task<bool> SignInAsync() { IsSigningIn = true; try { bool result = await PortalService.CurrentPortalService.SignIn(); if (result) { // navigate to the main page (new NavigationService()).Navigate(App.MainPageName); // send a message to populate the data Messenger.Default.Send<PopulateDataMessage>(new PopulateDataMessage()); IsSigningIn = false; return true; } } catch { } IsSigningIn = false; return false; } public async Task SignOutAsync() { PortalService.CurrentPortalService.SignOut(); try { ClearAllCredentials(); // set IsCredentialsPersisted to false IsCredentialsPersisted = false; } catch (Exception ex) { var _ = App.ShowExceptionDialog(ex); } // if anonymous access is enabled go back to the main page otherwise go back to the signin page bool isAnonymousAccess = await GetAnonymousAccessStatusAsync(); if (isAnonymousAccess) { (new NavigationService()).Navigate(App.MainPageName); await SignInAnonymouslyAsync(); } else (new NavigationService()).Navigate(App.BlankPageName); } private void ClearAllCredentials() { // Remove all credentials (even those for external services, hosted services, federated services) from IM and from the CredentialLocker foreach (var crd in IdentityManager.Current.Credentials.ToArray()) IdentityManager.Current.RemoveCredential(crd); var defaultChallengeHandler = IdentityManager.Current.ChallengeHandler as DefaultChallengeHandler; if (defaultChallengeHandler != null) defaultChallengeHandler.ClearCredentialsCache(); // remove stored credentials } } }
using UnityEngine; public class PlayerControl : MonoBehaviour { public Camera cameraObj; Animator animator; Rigidbody2D rb; SpriteRenderer sprite; int baseSpeedMultipler = 400; public float speed = 1; public float aimAngle = 0; public string facing = "R"; void Start() { animator = GetComponent<Animator>(); rb = GetComponent<Rigidbody2D>(); sprite = GetComponent<SpriteRenderer>(); } void Update() { Movement(); Facing(); } void Movement() { float x = Input.GetAxisRaw("Horizontal"); float y = Input.GetAxisRaw("Vertical"); rb.velocity = new Vector2(x, y) * (speed * baseSpeedMultipler) * Time.deltaTime; animator.SetBool("isMoving", (x != 0 || y != 0)); } void Facing() { Vector2 mouse = cameraObj.ScreenToWorldPoint(Input.mousePosition) - transform.position; aimAngle = (Mathf.Atan2(mouse.y, mouse.x) * Mathf.Rad2Deg) + 180f; if (aimAngle >= 90 && aimAngle < 270) { transform.localScale = new Vector3(2, 2, 0); facing = "R"; } else { transform.localScale = new Vector3(-2, 2, 0); facing = "L"; } } float PolarAngle(Vector3 a, Vector3 b) { return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg; } }
using System; using System.Data; using System.Drawing; using System.Windows.Forms; public class Form1 : Form { protected TextBox textBox1; // <Snippet1> private void BindTextBoxProperties() { // Clear the collection before adding new Binding objects. textBox1.DataBindings.Clear(); // Create a DataTable containing Color objects. DataTable t = MakeTable(); /* Bind the Text, BackColor, and ForeColor properties to columns in the DataTable. */ textBox1.DataBindings.Add("Text", t, "Text"); textBox1.DataBindings.Add("BackColor", t, "BackColor"); textBox1.DataBindings.Add("ForeColor", t, "ForeColor"); } private DataTable MakeTable() { /* Create a DataTable with three columns. Two of the columns contain Color objects. */ DataTable t = new DataTable("Control"); t.Columns.Add("BackColor", typeof(Color)); t.Columns.Add("ForeColor", typeof(Color)); t.Columns.Add("Text"); // Add three rows to the table. DataRow r; r = t.NewRow(); r["BackColor"] = Color.Blue; r["ForeColor"] = Color.Yellow; r["Text"] = "Yellow on Blue"; t.Rows.Add(r); r = t.NewRow(); r["BackColor"] = Color.White; r["ForeColor"] = Color.Green; r["Text"] = "Green on white"; t.Rows.Add(r); r = t.NewRow(); r["BackColor"] = Color.Orange; r["ForeColor"] = Color.Black; r["Text"] = "Black on Orange"; t.Rows.Add(r); return t; } // </Snippet1> }
@{ Layout = "_Layout"; }
using System; namespace RoadBook.CsharpBasic.Chapter02.Examples { public class Ex001 { public void Run() { //정수 sbyte shortByteNumber = 127; byte byteNumber = 0; short shortNumber = 32767; int intNumber = 20000; long longNumber = 50000; //실수 float floatNumber = 3.14f; double doubleNumber = 1.5; decimal decimalNumber = 5.5m; Console.WriteLine("정수 : {0}, {1}, {2}, {3}, {4}", shortByteNumber, byteNumber, shortNumber, intNumber, longNumber ); Console.WriteLine("실수 : {0}, {1}, {2}", floatNumber, doubleNumber, decimalNumber ); } } }
 @{ ViewBag.Title = "C3charts"; } <div class="row wrapper border-bottom white-bg page-heading"> <div class="col-lg-10"> <h2>c3.js</h2> <ol class="breadcrumb"> <li> <a href="index.html">Home</a> </li> <li> <a>Graphs</a> </li> <li class="active"> <strong>c3.js</strong> </li> </ol> </div> <div class="col-lg-2"> </div> </div> <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5> Line Chart Example <small>With custom colors.</small> </h5> </div> <div class="ibox-content"> <div> <div id="lineChart"></div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Bar Chart Example</h5> </div> <div class="ibox-content"> <div> <div id="slineChart"></div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Polar Area</h5> </div> <div class="ibox-content"> <div class="text-center"> <div id="scatter"></div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Pie </h5> </div> <div class="ibox-content"> <div> <div id="stocked"></div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Radar Chart Example</h5> </div> <div class="ibox-content"> <div> <div id="gauge"></div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Radar Chart Example</h5> </div> <div class="ibox-content"> <div> <div id="pie"></div> </div> </div> </div> </div> </div> </div> @section Styles { @Styles.Render("~/plugins/c3Styles") } @section Scripts { @Scripts.Render("~/plugins/d3") @Scripts.Render("~/plugins/c3") <script type="text/javascript"> $(document).ready(function () { c3.generate({ bindto: '#lineChart', data: { columns: [ ['data1', 30, 200, 100, 400, 150, 250], ['data2', 50, 20, 10, 40, 15, 25] ], colors: { data1: '#1ab394', data2: '#BABABA' } } }); c3.generate({ bindto: '#slineChart', data: { columns: [ ['data1', 30, 200, 100, 400, 150, 250], ['data2', 130, 100, 140, 200, 150, 50] ], colors: { data1: '#1ab394', data2: '#BABABA' }, type: 'spline' } }); c3.generate({ bindto: '#scatter', data: { xs: { data1: 'data1_x', data2: 'data2_x' }, columns: [ ["data1_x", 3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2.0, 3.0, 2.2, 2.9, 2.9, 3.1, 3.0, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3.0, 2.8, 3.0, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3.0, 3.4, 3.1, 2.3, 3.0, 2.5, 2.6, 3.0, 2.6, 2.3, 2.7, 3.0, 2.9, 2.9, 2.5, 2.8], ["data2_x", 3.3, 2.7, 3.0, 2.9, 3.0, 3.0, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3.0, 2.5, 2.8, 3.2, 3.0, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3.0, 2.8, 3.0, 2.8, 3.8, 2.8, 2.8, 2.6, 3.0, 3.4, 3.1, 3.0, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3.0, 2.5, 3.0, 3.4, 3.0], ["data1", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3], ["data2", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8] ], colors: { data1: '#1ab394', data2: '#BABABA' }, type: 'scatter' } }); c3.generate({ bindto: '#stocked', data: { columns: [ ['data1', 30, 200, 100, 400, 150, 250], ['data2', 50, 20, 10, 40, 15, 25] ], colors: { data1: '#1ab394', data2: '#BABABA' }, type: 'bar', groups: [ ['data1', 'data2'] ] } }); c3.generate({ bindto: '#gauge', data: { columns: [ ['data', 91.4] ], type: 'gauge' }, color: { pattern: ['#1ab394', '#BABABA'] } }); c3.generate({ bindto: '#pie', data: { columns: [ ['data1', 30], ['data2', 120] ], colors: { data1: '#1ab394', data2: '#BABABA' }, type: 'pie' } }); }); </script> }
using Core.Utilities.IoC; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text; namespace Core.Extension { public static class ServiceCollectionExtensions { //ekleyeceğimiz bütün injectionları bir arada toplayacağımız bir yapıdır. public static IServiceCollection AddDependencyResolvers(this IServiceCollection serviceCollection,ICoreModule[] modules) { foreach (var module in modules) { module.Load(serviceCollection); } return ServiceTool.Create(serviceCollection); } } }
//--------------------------------------------- // WirePolyline.cs (c) 2007 by Charles Petzold //--------------------------------------------- using System; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; namespace Petzold.Media3D { /// <summary> /// Draws a polyline of constant perceived width in 3D space /// between two points. /// </summary> public class WirePolyline : WireBase { /// <summary> /// Identifies the Points dependency property. /// </summary> public static readonly DependencyProperty PointsProperty = DependencyProperty.Register("Points", typeof(Point3DCollection), typeof(WirePolyline), new PropertyMetadata(null, PropertyChanged)); /// <summary> /// Gets or sets a collection that contains the points of /// the polyline. /// </summary> public Point3DCollection Points { set { SetValue(PointsProperty, value); } get { return (Point3DCollection)GetValue(PointsProperty); } } /// <summary> /// Sets the coordinates of all the individual lines in the visual. /// </summary> /// <param name="args"> /// The <c>DependencyPropertyChangedEventArgs</c> object associated /// with the property-changed event that resulted in this method /// being called. /// </param> /// <param name="lines"> /// The <c>Point3DCollection</c> to be filled. /// </param> /// <remarks> /// <para> /// Classes that derive from <c>WireBase</c> override this /// method to fill the <c>lines</c> collection. /// It is custmary for implementations of this method to clear /// the <c>lines</c> collection first before filling it. /// Each pair of successive members of the <c>lines</c> /// collection indicate one straight line. /// </para> /// <para> /// The <c>WirePolyline</c> class implements this method by /// clearing the <c>lines</c> collection and then breaking /// down its <c>Points</c> collection into individual lines /// and then adding the start and end points to the collection. /// </para> /// </remarks> protected override void Generate(DependencyPropertyChangedEventArgs args, Point3DCollection lines) { Point3DCollection points = Points; lines.Clear(); for (int i = 0; i < points.Count - 1; i++) { lines.Add(points[i]); lines.Add(points[i + 1]); } } } }
using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; namespace NFSDK { public class NFUIModule: NFIModule { public enum Event : int { LoginSuccess, LoginFailure, WorldList, ServerList, SelectServerSuccess, }; public override void Awake() {} public override void AfterInit() {} public override void Execute() { } public override void BeforeShut() {} public override void Shut() { } public NFUIModule(NFIPluginManager pluginManager) { mPluginManager = pluginManager; } public override void Init() { } public void ShowUI<T>(bool bPushHistory = true, NFDataList varList = null) where T : UIDialog { if (mCurrentDialog != null) { mCurrentDialog.gameObject.SetActive(false); mCurrentDialog = null; } string name = typeof(T).ToString(); GameObject uiObject; if (!mAllUIs.TryGetValue(name, out uiObject)) { GameObject perfb = Resources.Load<GameObject>("UI/" + typeof(T).ToString()); uiObject = GameObject.Instantiate(perfb); uiObject.name = name; uiObject.transform.SetParent(NFCRoot.Instance().transform); mAllUIs.Add(name, uiObject); } else { uiObject.SetActive(true); } if (uiObject) { T panel = uiObject.GetComponent<T>(); if (varList != null) panel.mUserData = varList; mCurrentDialog = panel; uiObject.SetActive(true); if (bPushHistory) { mDialogs.Enqueue(panel); } } } public void CloseUI() { if (mCurrentDialog) { mCurrentDialog.gameObject.SetActive(false); mCurrentDialog = null; } mDialogs.Clear(); } Dictionary<string, GameObject> mAllUIs = new Dictionary<string,GameObject>(); Queue<UIDialog> mDialogs = new Queue<UIDialog>(); private UIDialog mCurrentDialog = null; } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.ML.Runtime.Api; using Microsoft.ML.Runtime.Data; namespace Paragraph.Services.MachineLearning { internal class ArticleModelPrediction { [ColumnName(DefaultColumnNames.PredictedLabel)] public string Category { get; set; } } }
namespace Testing { partial class Ticket { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Ticket)); this.label5 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.textBox5 = new System.Windows.Forms.TextBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.textBox7 = new System.Windows.Forms.TextBox(); this.textBox8 = new System.Windows.Forms.TextBox(); this.textBox9 = new System.Windows.Forms.TextBox(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 26.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(136, 1); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(312, 39); this.label5.TabIndex = 24; this.label5.Text = "Ticket Information"; // // button1 // this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(533, 12); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(81, 28); this.button1.TabIndex = 31; this.button1.Text = "Logout"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(196, 120); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(217, 31); this.label6.TabIndex = 33; this.label6.Text = "Journey Details"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.Location = new System.Drawing.Point(6, 151); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(98, 16); this.label7.TabIndex = 34; this.label7.Text = "For Journey :"; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.Location = new System.Drawing.Point(37, 171); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(39, 16); this.label9.TabIndex = 36; this.label9.Text = "BUS"; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.Location = new System.Drawing.Point(140, 171); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(71, 16); this.label10.TabIndex = 37; this.label10.Text = "Category"; this.label10.Click += new System.EventHandler(this.label10_Click); // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.Location = new System.Drawing.Point(268, 171); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(49, 16); this.label11.TabIndex = 38; this.label11.Text = "Route"; // // label12 // this.label12.AutoSize = true; this.label12.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label12.Location = new System.Drawing.Point(415, 171); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(43, 16); this.label12.TabIndex = 39; this.label12.Text = "Time"; // // label13 // this.label13.AutoSize = true; this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label13.Location = new System.Drawing.Point(531, 171); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(64, 16); this.label13.TabIndex = 40; this.label13.Text = "SeatNo."; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(9, 200); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(100, 20); this.textBox5.TabIndex = 41; // // textBox6 // this.textBox6.Location = new System.Drawing.Point(131, 200); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(80, 20); this.textBox6.TabIndex = 42; // // textBox7 // this.textBox7.Location = new System.Drawing.Point(217, 200); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(151, 20); this.textBox7.TabIndex = 43; // // textBox8 // this.textBox8.Location = new System.Drawing.Point(374, 200); this.textBox8.Name = "textBox8"; this.textBox8.Size = new System.Drawing.Size(132, 20); this.textBox8.TabIndex = 44; // // textBox9 // this.textBox9.Location = new System.Drawing.Point(525, 200); this.textBox9.Name = "textBox9"; this.textBox9.Size = new System.Drawing.Size(83, 20); this.textBox9.TabIndex = 45; // // button3 // this.button3.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button3.Location = new System.Drawing.Point(374, 318); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(150, 36); this.button3.TabIndex = 57; this.button3.Text = "Print Ticket"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button4.Location = new System.Drawing.Point(131, 318); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(147, 36); this.button4.TabIndex = 58; this.button4.Text = "BuyTicketAgain"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // Ticket // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.OrangeRed; this.ClientSize = new System.Drawing.Size(626, 364); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.textBox9); this.Controls.Add(this.textBox8); this.Controls.Add(this.textBox7); this.Controls.Add(this.textBox6); this.Controls.Add(this.textBox5); this.Controls.Add(this.label13); this.Controls.Add(this.label12); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.button1); this.Controls.Add(this.label5); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Ticket"; this.Text = "Ticket"; this.Load += new System.EventHandler(this.Ticket_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label5; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.TextBox textBox9; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; } }
using Ninject; using System; using System.Linq; namespace Botje.Core.Commands { /// <summary> /// Automatically generates a help message for the user based on the registered console commands. /// </summary> public class HelpCommand : ConsoleCommandBase { [Inject] public IConsoleCommand[] Commands { get; set; } /// <summary> /// Coimmand information. /// </summary> public override CommandInfo Info => new CommandInfo { Command = "help", Aliases = new string[] { "h", "?" }, QuickHelp = "Request help", DetailedHelp = "Usage: help [command]\nWhen no command is pecified, shows a quick overview of all commands. When a command is specified explains the usage of that command." }; /// <summary> /// See CommandInfo for help. /// </summary> /// <param name="command"></param> /// <param name="args"></param> /// <returns></returns> public override bool OnInput(string command, string[] args) { if (args.Length >= 1) { foreach (var commandObj in Commands) { if (string.Equals(commandObj.Info.Command, args[0], StringComparison.InvariantCultureIgnoreCase) || (commandObj.Info.Aliases != null && commandObj.Info.Aliases.Where(x => string.Equals(x, args[0], StringComparison.InvariantCultureIgnoreCase)).Any())) { Console.WriteLine($"Help on: {commandObj.Info.Command}"); string aliasstr = commandObj.Info.Aliases == null ? "" : string.Join(", ", commandObj.Info.Aliases); Console.WriteLine($"Aliases: {aliasstr}"); Console.WriteLine($"Description:"); Console.WriteLine(commandObj.Info.DetailedHelp); Console.WriteLine($"---"); } } } else { var maxlen = Commands.Select(x => x.Info.Command.Length).Max(); foreach (var c in Commands.OrderBy(x => x.Info.Command)) { Console.WriteLine($"{string.Format($"{{0,-{maxlen}}}", c.Info.Command)} - {c.Info.QuickHelp}"); } } return true; } } }