content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections; using System.Collections.Generic; using UnityEngine; /* Sound controller, currently only for player jumps */ public class UpdateAudio : MonoBehaviour { private bool jumpSoundPlayed; private PlayerState state; private AudioSource jump; // Use this for initialization void Awake () { jump = GetComponent<AudioSource>(); state = GetComponent<PlayerState>(); } // Update is called once per frame void Update () { if(!state.onGround && !jumpSoundPlayed){ jump.Play(); jumpSoundPlayed = true; } if(state.onGround){ jumpSoundPlayed = false; } } }
19
52
0.708882
[ "MIT" ]
olmorrish/ThisMindOfMine
Assets/Scripts/PlayerBehavior/UpdateAudio.cs
610
C#
namespace BlazorShop.Web.Client.Shared.Navigation { using Models.Products; public partial class NavSearch { private readonly ProductsSearchRequestModel searchModel = new ProductsSearchRequestModel(); private void Search() => this.NavigationManager.NavigateTo($"/products/search/{this.searchModel.Query}/page/1"); } }
29.333333
120
0.732955
[ "MIT" ]
FredericoSilvaTeles/BlazorShop
src/BlazorShop.Web/Client/Shared/Navigation/NavSearch.razor.cs
354
C#
#region (c) 2010-2012 Lokad - CQRS Sample for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2012, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using System.Collections.Generic; namespace SaaS.Aggregates.User { public sealed class UserAggregate { readonly UserState _state; public IList<IEvent> Changes = new List<IEvent>(); /// <summary> /// If relogin happens within the interval, we don't track it /// </summary> public static readonly TimeSpan DefaultLoginActivityThreshold = TimeSpan.FromMinutes(10); public UserAggregate(UserState state) { _state = state; } public void Create(UserId userId, SecurityId securityId) { if (_state.Version != 0) throw new DomainError("User already has non-zero version"); Apply(new UserCreated(userId, securityId, DefaultLoginActivityThreshold)); } public void ReportLoginFailure(DateTime timeUtc, string address) { Apply(new UserLoginFailureReported(_state.Id, timeUtc, _state.SecurityId, address)); if (_state.DoesLastFailureWarrantLockout()) { Apply(new UserLocked(_state.Id, "Login failed too many times", _state.SecurityId, timeUtc.AddMinutes(10))); } } public void ReportLoginSuccess(DateTime timeUtc, string address) { Apply(new UserLoginSuccessReported(_state.Id, timeUtc, _state.SecurityId, address)); } public void Unlock(string unlockReason) { if (Current.UtcNow > _state.LockedOutTillUtc) return; // lock has already expired Apply(new UserUnlocked(_state.Id, unlockReason, _state.SecurityId)); } public void Delete() { Apply(new UserDeleted(_state.Id, _state.SecurityId)); } public void Lock(string lockReason) { if (_state.LockedOutTillUtc == Current.MaxValue) return; Apply(new UserLocked(_state.Id, lockReason, _state.SecurityId, Current.MaxValue)); } public void ThrowOnInvalidStateTransition(ICommand<UserId> e) { if (_state.Version == 0) { if (e is CreateUser) { return; } throw DomainError.Named("premature", "Can't do anything to unexistent aggregate"); } if (_state.Version == -1) { throw DomainError.Named("zombie", "Can't do anything to deleted aggregate."); } if (e is CreateUser) throw DomainError.Named("rebirth", "Can't create aggregate that already exists"); } void Apply(IEvent<UserId> e) { _state.Mutate(e); Changes.Add(e); } } }
31.863158
123
0.582755
[ "BSD-3-Clause" ]
EventDay/lokad-cqrs
SaaS.Domain/Aggregates/User/UserAggregate.cs
3,029
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CBehaviorGraphDirectionalMovementNode : CBehaviorGraphNode { [Ordinal(1)] [RED("groupCount")] public CInt32 GroupCount { get; set;} [Ordinal(2)] [RED("animsPerGroup")] public CInt32 AnimsPerGroup { get; set;} [Ordinal(3)] [RED("firstGroupDirOffset")] public CFloat FirstGroupDirOffset { get; set;} [Ordinal(4)] [RED("extraOverlapAngle")] public CFloat ExtraOverlapAngle { get; set;} [Ordinal(5)] [RED("keepInCurrentGroupAngle")] public CFloat KeepInCurrentGroupAngle { get; set;} [Ordinal(6)] [RED("findGroupDirOffset")] public CFloat FindGroupDirOffset { get; set;} [Ordinal(7)] [RED("singleAnimOnly")] public CBool SingleAnimOnly { get; set;} [Ordinal(8)] [RED("doNotSwitchAnim")] public CBool DoNotSwitchAnim { get; set;} [Ordinal(9)] [RED("movementDirBlendTime")] public CFloat MovementDirBlendTime { get; set;} [Ordinal(10)] [RED("movementDirMaxSpeedChange")] public CFloat MovementDirMaxSpeedChange { get; set;} [Ordinal(11)] [RED("groupsBlendTime")] public CFloat GroupsBlendTime { get; set;} [Ordinal(12)] [RED("quickTurnBlendTime")] public CFloat QuickTurnBlendTime { get; set;} [Ordinal(13)] [RED("fasterQuickTurnBlendTime")] public CFloat FasterQuickTurnBlendTime { get; set;} [Ordinal(14)] [RED("angleThresholdForQuickTurn")] public CFloat AngleThresholdForQuickTurn { get; set;} [Ordinal(15)] [RED("reverseSyncOnQuickTurnFwdBwd")] public CBool ReverseSyncOnQuickTurnFwdBwd { get; set;} [Ordinal(16)] [RED("reverseSyncOnQuickTurnLeftRight")] public CBool ReverseSyncOnQuickTurnLeftRight { get; set;} [Ordinal(17)] [RED("syncBlendingOffsetPTLOnQuickTurn")] public CFloat SyncBlendingOffsetPTLOnQuickTurn { get; set;} [Ordinal(18)] [RED("startPTLRightFootInFront")] public CFloat StartPTLRightFootInFront { get; set;} [Ordinal(19)] [RED("startPTLLeftFootInFront")] public CFloat StartPTLLeftFootInFront { get; set;} [Ordinal(20)] [RED("alwaysStartAtZero")] public CBool AlwaysStartAtZero { get; set;} [Ordinal(21)] [RED("useSimpleBlendForMovementDelta")] public CBool UseSimpleBlendForMovementDelta { get; set;} [Ordinal(22)] [RED("useDefinedVariablesAsRequestedInput")] public CBool UseDefinedVariablesAsRequestedInput { get; set;} [Ordinal(23)] [RED("requestedMovementDirectionVariableName")] public CName RequestedMovementDirectionVariableName { get; set;} [Ordinal(24)] [RED("requestedFacingDirectionVariableName")] public CName RequestedFacingDirectionVariableName { get; set;} [Ordinal(25)] [RED("useDefinedInternalVariablesAsInitialInput")] public CBool UseDefinedInternalVariablesAsInitialInput { get; set;} [Ordinal(26)] [RED("movementDirectionInternalVariableName")] public CName MovementDirectionInternalVariableName { get; set;} [Ordinal(27)] [RED("groupDirInternalVariableName")] public CName GroupDirInternalVariableName { get; set;} [Ordinal(28)] [RED("loopCount")] public CInt32 LoopCount { get; set;} [Ordinal(29)] [RED("syncGroupOffsetPTL")] public CFloat SyncGroupOffsetPTL { get; set;} [Ordinal(30)] [RED("Right foot bone name")] public CName Right_foot_bone_name { get; set;} [Ordinal(31)] [RED("Left foot bone name")] public CName Left_foot_bone_name { get; set;} [Ordinal(32)] [RED("groupDir")] public CFloat GroupDir { get; set;} [Ordinal(33)] [RED("sideAngleRange")] public CFloat SideAngleRange { get; set;} [Ordinal(34)] [RED("syncMethod")] public CPtr<IBehaviorSyncMethod> SyncMethod { get; set;} [Ordinal(35)] [RED("allInputsValid")] public CBool AllInputsValid { get; set;} [Ordinal(36)] [RED("cachedInputNodes", 2,0)] public CArray<CPtr<CBehaviorGraphNode>> CachedInputNodes { get; set;} [Ordinal(37)] [RED("cachedRequestedMovementDirectionWSValueNode")] public CPtr<CBehaviorGraphValueNode> CachedRequestedMovementDirectionWSValueNode { get; set;} [Ordinal(38)] [RED("cachedRequestedFacingDirectionWSValueNode")] public CPtr<CBehaviorGraphValueNode> CachedRequestedFacingDirectionWSValueNode { get; set;} [Ordinal(39)] [RED("cachedInitialMovementDirectionWSValueNode")] public CPtr<CBehaviorGraphValueNode> CachedInitialMovementDirectionWSValueNode { get; set;} [Ordinal(40)] [RED("cachedInitialGroupDirMSValueNode")] public CPtr<CBehaviorGraphValueNode> CachedInitialGroupDirMSValueNode { get; set;} public CBehaviorGraphDirectionalMovementNode(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBehaviorGraphDirectionalMovementNode(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
49.669903
165
0.733776
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CBehaviorGraphDirectionalMovementNode.cs
5,014
C#
using FlyingRat.Captcha.Configuration; using FlyingRat.Captcha.Model; using FlyingRat.Captcha.Validator; using SixLabors.ImageSharp; using System.Collections.Generic; namespace FlyingRat.Captcha { public class CaptchaCacheModel { /// <summary> /// Random gaps for the image /// </summary> public List<CaptchaPoint> Points { get; set; } /// <summary> /// Full image /// </summary> public Image Backgorund { get; set; } /// <summary> /// Image after random gaps /// </summary> public Image GapBackground { get; set; } /// <summary> /// /// </summary> public Image Gap { get; set; } public CaptchaType Type { get; set; } public string Code { get; set; } public string Token { get; set; } public ValidateResult Validate { get; set; } public BaseCaptchaOptions Options { get; set; } public string Name { get; set; } } }
27.972222
55
0.573982
[ "MIT" ]
cqkisyouq/FlyingRat.Captcha
src/FlyingRat.Captcha/CaptchaCacheModel.cs
1,009
C#
using Microsoft.FSharp.Core; using System; using ZeroFormatter.Formatters; namespace ZeroFormatter.Extensions { internal class UnitFormatter<TTYpeResolver> : Formatter<TTYpeResolver, Unit> where TTYpeResolver : ITypeResolver, new() { readonly Formatter<TTYpeResolver, int> formatter; public UnitFormatter() { this.formatter = Formatter<TTYpeResolver, int>.Default; } public override int? GetLength() { return formatter.GetLength(); } public override int Serialize(ref byte[] bytes, int offset, Unit value) { return formatter.Serialize(ref bytes, offset, -1); } public override Unit Deserialize(ref byte[] bytes, int offset, DirtyTracker tracker, out int byteSize) { var value = formatter.Deserialize(ref bytes, offset, tracker, out byteSize); // Unit is special and always uses the representation 'null'. if (value == -1) return null; else throw new Exception($"{value} is not FSharp Unit binary."); } } }
32.083333
111
0.606061
[ "MIT" ]
JTOne123/ZeroFormatter.FSharpExtensions
src/ZeroFormatter.FSharpExtensions/UnitFormatter.cs
1,157
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; namespace PowerDocu.Common { public static class ZipHelper { public const string FlowDefinitionFile = "definition.json"; public const string SolutionPackageWorkflowsPath = "Workflows/"; public static List<ZipArchiveEntry> getWorkflowFilesFromZip(Stream archiveFileStream) { ZipArchive archive = new ZipArchive(archiveFileStream,ZipArchiveMode.Read); List<ZipArchiveEntry> entries = new List<ZipArchiveEntry>(); foreach (ZipArchiveEntry entry in archive.Entries) { //case 1: file name equals FlowDefinitionFile, then we can add it as it is an actual Flow //case 2: a JSON file inside the folder SolutionPackageWorkflowsPath, then it is an actual Flow inside a Solution if (entry.Name.Equals(FlowDefinitionFile) || (entry.FullName.StartsWith(SolutionPackageWorkflowsPath) && entry.Name.EndsWith(".json"))) { entries.Add(entry); } } return entries; } public static List<ZipArchiveEntry> getFilesInPathFromZip(Stream archiveFileStream, string path, string fileExtension) { ZipArchive archive = new ZipArchive(archiveFileStream,ZipArchiveMode.Read); List<ZipArchiveEntry> entries = new List<ZipArchiveEntry>(); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.StartsWith(path) && entry.Name.EndsWith(fileExtension)) { entries.Add(entry); } } return entries; } public static ZipArchiveEntry getFileFromZip(Stream archiveFileStream, string fileName) { ZipArchive archive = new ZipArchive(archiveFileStream,ZipArchiveMode.Read); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.Equals(fileName)) { return entry; } } return null; } public static void test() { Stream data = new MemoryStream(); // The original data Stream unzippedEntryStream; // Unzipped data from a file in the archive ZipArchive archive = new ZipArchive(data); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) { unzippedEntryStream = entry.Open(); // .Open will return a stream // Process entry data here } } } } }
39.680556
151
0.582779
[ "MIT" ]
modery/PowerDocu
PowerDocu.Common/ZipHelper.cs
2,857
C#
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Linq; namespace ILRepacking.Steps.SourceServerData { internal interface ISourceServerDataRepackStep : IRepackStep, IDisposable { void Write(); } /// <summary> /// Get the pdb info from source servers. /// </summary> internal class SourceServerDataRepackStep : ISourceServerDataRepackStep { private readonly string _targetPdbFile; private readonly IEnumerable<string> _assemblyFiles; private string _srcSrv; private PdbStr _pdbStr = new PdbStr(); public SourceServerDataRepackStep(string targetFile, IEnumerable<string> assemblyFiles) { Contract.Assert(targetFile != null); Contract.Assert(assemblyFiles != null); _targetPdbFile = PdbPath(targetFile); _assemblyFiles = assemblyFiles; } public void Perform() { var srcsrvValues = _assemblyFiles .Select(PdbPath) .Where(File.Exists) .Select(_pdbStr.Read) .ToArray(); var descriptors = srcsrvValues.Select(srcsrv => { HttpSourceServerDescriptor descriptor; return new { Valid = HttpSourceServerDescriptor.TryParse(srcsrv, out descriptor), Descriptor = descriptor }; }) .Where(tuple => tuple.Valid) .Select(tuple => tuple.Descriptor) .ToArray(); _srcSrv = descriptors.Any() ? descriptors.First().MergeWith(descriptors.Skip(1)).ToString() : srcsrvValues.FirstOrDefault(); } public void Write() { if (_srcSrv == null) return; _pdbStr.Write(_targetPdbFile, _srcSrv); } public void Dispose() { if (_pdbStr != null) { _pdbStr.Dispose(); _pdbStr = null; } } private static string PdbPath(string assemblyFile) => Path.ChangeExtension(assemblyFile, ".pdb"); } /// <summary> /// Intended for use on platforms where source server is not supported. /// </summary> internal class NullSourceServerStep : ISourceServerDataRepackStep { private ILogger _logger; public NullSourceServerStep(ILogger logger) { _logger = logger; } public void Perform() { // intentionally blank } public void Write() { _logger.Warn("Did not write source server data to output assembly. " + "Source server data is only writeable on Windows"); } public void Dispose() { } } }
28.238095
105
0.547049
[ "Apache-2.0" ]
Alexx999/il-repack
ILRepack/Steps/SourceServerData/SourceServerDataRepackStep.cs
2,965
C#
[System.Serializable] public class Story { public string title; public string text; public int id; public bool picked; public Story(int id, string title, string text) { this.id = id; this.title = title; this.text = text; picked = false; } public Story(string title, string text) : this(0, title, text) { } }
20.777778
70
0.593583
[ "MIT" ]
SuccessfulZ/Now-or-Never-Games
Assets/Project/Scripts/Narrative/Story.cs
376
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.ComponentModel.DataAnnotations; using System.Globalization; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.Extensions.Localization; namespace Microsoft.AspNetCore.Mvc.DataAnnotations { internal class RangeAttributeAdapter : AttributeAdapterBase<RangeAttribute> { private readonly string _max; private readonly string _min; public RangeAttributeAdapter(RangeAttribute attribute, IStringLocalizer? stringLocalizer) : base(attribute, stringLocalizer) { // This will trigger the conversion of Attribute.Minimum and Attribute.Maximum. // This is needed, because the attribute is stateful and will convert from a string like // "100m" to the decimal value 100. // // Validate a randomly selected number. attribute.IsValid(3); _max = Convert.ToString(Attribute.Maximum, CultureInfo.InvariantCulture)!; _min = Convert.ToString(Attribute.Minimum, CultureInfo.InvariantCulture)!; } public override void AddValidation(ClientModelValidationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-range", GetErrorMessage(context)); MergeAttribute(context.Attributes, "data-val-range-max", _max); MergeAttribute(context.Attributes, "data-val-range-min", _min); } /// <inheritdoc /> public override string GetErrorMessage(ModelValidationContextBase validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } return GetErrorMessage( validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName(), Attribute.Minimum, Attribute.Maximum); } } }
38.033333
100
0.651621
[ "MIT" ]
48355746/AspNetCore
src/Mvc/Mvc.DataAnnotations/src/RangeAttributeAdapter.cs
2,282
C#
/* * 脚本名(ScriptName): UserModel.cs * 作者(Author): 小宝 * 官网(Url): http://www.youke.pro */ using UnityEngine; using System.Collections; public class UserModel : BaseModel { #region 基础数据,只允许设置一次 /// <summary> /// 玩家id /// </summary> public int userId { set; get; } /// <summary> /// 玩家信息 /// </summary> public string userName { set; get; } #endregion #region 体力 private int _endurance = 0; /// <summary> /// 体力 /// </summary> public int endurance { get { return _endurance; } set { if(_endurance == value) { return; } if(_endurance < 0) { _endurance = 0; } _endurance = value; } } #endregion #region 金币 private int _gold = 0; /// <summary> /// 金币 /// </summary> public int gold { get { return _gold; } set { if (_gold == value) { return; } if (_gold < 0) { _gold = 0; } //ValueUpdateEvenArgs ve = new ValueUpdateEvenArgs(); //ve.key = "gold"; //ve.oldValue = _gold; //ve.newValue = value; DispatchValueUpdateEvent("gold", _gold, value); _gold = value; } } #endregion #region 元宝 private int _wing = 0; /// <summary> /// 元宝 /// </summary> public int wing { get { return _wing; } set { if (_wing == value) { return; } if (_wing < 0) { _wing = 0; } _wing = value; } } #endregion #region 等级 private int _lv = 0; /// <summary> /// 等级 /// </summary> public int lv { get { return _lv; } set { if (_lv == value) { return; } if (_lv < 0) { _lv = 0; } _lv = value; } } #endregion #region VIP等级 private int _vip = 0; /// <summary> /// vip等级 /// </summary> public int vip { get { return _vip; } set { if (_vip == value) { return; } if (_vip < 0) { _vip = 0; } _vip = value; } } #endregion #region 头像 private int _head = 0; /// <summary> /// 头像ID /// </summary> public int head { get { return _head; } set { if (_head == value) { return; } if (_head < 0) { _head = 0; } _head = value; } } #endregion }
16.482234
65
0.338158
[ "Unlicense" ]
paradisewu/IPADTOP
Assets/Scripts/ZG/UserModel.cs
3,353
C#
using System; using System.Collections; using System.IO; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Szofttech_WPF.DataPackage; using Szofttech_WPF.EventArguments.Board; using Szofttech_WPF.EventArguments.Chat; using Szofttech_WPF.EventArguments.Client; using Szofttech_WPF.EventArguments.ShipSelecter; using Szofttech_WPF.Interfaces; using Szofttech_WPF.Logic; using Szofttech_WPF.Model.EventArguments.Board; using Szofttech_WPF.Network; using Szofttech_WPF.Utils; using Szofttech_WPF.View.Game; using Szofttech_WPF.ViewModel; namespace Szofttech_WPF.View { /// <summary> /// Interaction logic for GameGUI.xaml /// </summary> public partial class GameGUI : UserControl, IExitableGUI { PlayerBoardGUI playerBoardGUI; EnemyBoardGUI enemyBoardGUI; private ShipSelecterGUI selecter; private ChatGUI chatGUI; private InfoPanelGUI infoPanel; private Client Client; private Server Server; private bool exitable = true; private MediaPlayer mediaPlayerBackground = new MediaPlayer(); private MediaPlayer mediaPlayerHit = new MediaPlayer(); private MediaPlayer mediaPlayerWater = new MediaPlayer(); public GameGUI(int port) : this(Settings.getIP(), port) { Server = new Server(port); ipListGrid.Visibility = Visibility.Visible; IPListItemsControl.DataContext = Server.getLocalIPs(); } public GameGUI(string ip, int port) { InitializeComponent(); playerBoardGUI = new PlayerBoardGUI(); enemyBoardGUI = new EnemyBoardGUI(); selecter = new ShipSelecterGUI(); chatGUI = new ChatGUI(); Client = new Client(ip, port); Client.OnMessageReceived += Client_OnMessageReceived; Client.OnYourTurn += Client_OnYourTurn; Client.OnGameEnded += Client_OnGameEnded; Client.OnEnemyHitMe += Client_OnEnemyHitMe; Client.OnMyHit += Client_OnMyHit; Client.OnJoinedEnemy += Client_OnJoinedEnemy; Client.OnDisconnected += Client_OnDisconnected; Client.OnRematch += Client_OnRematch; playerBoardGUI.Visibility = Visibility.Hidden; playerBoardGUI.OnPlace += PlayerBoardGUI_OnPlace; playerBoardGUI.OnPickUp += PlayerBoardGUI_OnPickUp; playerBoardGUI.OnPlaySound += PlaySound; grid.Children.Add(playerBoardGUI); Grid.SetRow(playerBoardGUI, 3); Grid.SetColumn(playerBoardGUI, 1); enemyBoardGUI.Visibility = Visibility.Hidden; enemyBoardGUI.OnShot += EnemyBoardGUI_OnShot; enemyBoardGUI.OnPlaySound += PlaySound; grid.Children.Add(enemyBoardGUI); Grid.SetRow(enemyBoardGUI, 3); Grid.SetColumn(enemyBoardGUI, 5); selecter.Visibility = Visibility.Hidden; selecter.OnSelectShip += Selecter_OnSelectShip; selecter.OnSelectDirection += Selecter_OnSelectDirection; selecter.OnClearBoard += Selecter_OnClearBoard; selecter.OnPlaceRandomShips += Selecter_OnPlaceRandomShips; selecter.OnRanOutOfShips += Selecter_OnRanOutOfShips; selecter.OnDone += Selecter_OnDone; grid.Children.Add(selecter); Grid.SetRow(selecter, 1); Grid.SetRowSpan(selecter, 3); Grid.SetColumn(selecter, 1); Grid.SetColumnSpan(selecter, 5); chatGUI.Visibility = Visibility.Hidden; ((ChatViewModel)chatGUI.DataContext).OnSendMessage += ChatGUI_OnSendMessage; grid.Children.Add(chatGUI); Grid.SetRow(chatGUI, 1); Grid.SetRowSpan(chatGUI, 1); Grid.SetColumn(chatGUI, 1); Grid.SetColumnSpan(chatGUI, 5); infoPanel = new InfoPanelGUI(); infoPanel.Visibility = Visibility.Hidden; grid.Children.Add(infoPanel); Grid.SetRow(infoPanel, 3); Grid.SetColumn(infoPanel, 3); ((InfoPanelGUIViewModel)infoPanel.DataContext).changeVisibility(false); ((InfoPanelGUIViewModel)infoPanel.DataContext).OnRematch += InfoPanelGUI_OnRematch; foreach (DictionaryEntry item in App.Current.Resources) { if (item.Key.ToString() == "infoVM") { ((InfoPanelGUIViewModel)item.Value).OnRematch += InfoPanelGUI_OnRematch; } } mediaPlayerBackground.Open(new Uri(Directory.GetCurrentDirectory() + "/backgroundwind.mp3")); mediaPlayerBackground.MediaEnded += (send, args) => { mediaPlayerBackground.Position = TimeSpan.Zero; mediaPlayerBackground.Play(); }; mediaPlayerBackground.MediaFailed += (send, args) => { Console.WriteLine("Sikertelen megnyitás"); }; mediaPlayerBackground.Volume = 0.2; mediaPlayerBackground.Play(); } private void PlaySound(object sender, EventArgs e) { MediaPlayer mediaPlayer = new MediaPlayer(); switch (((SoundArgs)e).SoundType) { case SoundType.Splash: mediaPlayer.Open(new Uri(Settings.GetPath() + "/splash.m4a")); break; case SoundType.Hit: mediaPlayer.Open(new Uri(Settings.GetPath() + "/explosion.wav")); break; default: return; } mediaPlayer.MediaFailed += (sende, args) => { Console.WriteLine("Sikertelen megnyitás"); }; mediaPlayer.Volume = 0.5; mediaPlayer.Play(); } private void InfoPanelGUI_OnRematch(object sender, EventArgs e) { Client.sendMessage(new ChatData(Client.ID, "/rematch")); } private void ReInit() { ((InfoPanelGUIViewModel)infoPanel.DataContext).changeVisibility(false); playerBoardGUI.IsEnabled = true; chatGUI.Visibility = Visibility.Hidden; infoPanel.Visibility = Visibility.Hidden; selecter.Visibility = Visibility.Visible; enemyBoardGUI.ReInit(); playerBoardGUI.ReInit(); selecter.ReInit(); Selecter_OnClearBoard(null, null); Selecter_OnPlaceRandomShips(null, null); } private void Client_OnRematch(object sender, EventArgs e) { Console.WriteLine("REMATCH"); Dispatcher.Invoke(() => ReInit()); GC.Collect(); GC.WaitForPendingFinalizers(); Dispatcher.Invoke(() => ReInit());//valamiért még egyszer kell újrainicializálni } private void EnemyBoardGUI_OnShot(object sender, ShotArgs e) { Dispatcher.Invoke(() => ((InfoPanelGUIViewModel)infoPanel.DataContext).changeVisibility(false)); Client.sendMessage(new ShotData(Client.ID, e.I, e.J)); } private void ChatGUI_OnSendMessage(object sender, SendMessageEventArgs e) { Client.sendMessage(new ChatData(Client.ID, e.Message)); } private void Client_OnDisconnected(object sender, EventArgs e) { Client_OnMessageReceived(null, new MessageReceivedArgs(-1, "Enemy left the game.")); exitable = true; } private void Client_OnJoinedEnemy(object sender, EventArgs e) { exitable = false; Dispatcher.Invoke(() => { waitingTitle.Visibility = Visibility.Hidden; ipListGrid.Visibility = Visibility.Hidden; playerBoardGUI.Visibility = Visibility.Visible; enemyBoardGUI.Visibility = Visibility.Visible; selecter.Visibility = Visibility.Visible; }); } private void Client_OnMyHit(object sender, MyHitArgs e) { enemyBoardGUI.Hit(e.I, e.J, e.Status); } private void Client_OnEnemyHitMe(object sender, EnemyHitMeArgs e) { playerBoardGUI.Hit(e.I, e.J); } private void Client_OnGameEnded(object sender, GameEndedArgs e) { enemyBoardGUI.setTurnEnabled(false); string endMessage = ""; switch (e.GameEndedStatus) { case GameEndedStatus.Unknown: endMessage = "Unknown game ended status."; break; case GameEndedStatus.Defeat: endMessage = "Defeat!"; break; case GameEndedStatus.Win: endMessage = "You win!"; break; default: break; } Dispatcher.Invoke(() => { ((ChatViewModel)chatGUI.DataContext).addMessage("System", endMessage); //infoPanel.Visibility = Visibility.Hidden; ((InfoPanelGUIViewModel)infoPanel.DataContext).RematchVisibility = true; ((InfoPanelGUIViewModel)infoPanel.DataContext).GreenArrowVisibility = false; ((InfoPanelGUIViewModel)infoPanel.DataContext).RedArrowVisibility = false; }); exitable = true; } private void Client_OnYourTurn(object sender, EventArgs e) { Dispatcher.Invoke(() => ((InfoPanelGUIViewModel)infoPanel.DataContext).changeVisibility(true)); enemyBoardGUI.setTurnEnabled(true); } private void Client_OnMessageReceived(object sender, MessageReceivedArgs e) { Dispatcher.Invoke(() => { if (e.SenderID == -1) ((ChatViewModel)chatGUI.DataContext).addMessage("System", e.Message); else if (e.SenderID == Client.ID) ((ChatViewModel)chatGUI.DataContext).addMessage("You", e.Message); else ((ChatViewModel)chatGUI.DataContext).addMessage("Opponent", e.Message); }); } private void PlayerBoardGUI_OnPickUp(object sender, ShipSizeArgs e) { selecter.PickupFromTable(e.ShipSize); playerBoardGUI.canPlace = true; selecter.CanDone(false); } private void PlayerBoardGUI_OnPlace(object sender, ShipSizeArgs e) { selecter.PlaceToTable(e.ShipSize); } private void Selecter_OnDone(object sender, EventArgs e) { playerBoardGUI.IsEnabled = false; chatGUI.Visibility = Visibility.Visible; infoPanel.Visibility = Visibility.Visible; Client.sendMessage(new PlaceShipsData(Client.ID, playerBoardGUI.board)); } private void Selecter_OnRanOutOfShips(object sender, EventArgs e) { playerBoardGUI.canPlace = false; selecter.CanDone(true); } private void Selecter_OnPlaceRandomShips(object sender, EventArgs e) { playerBoardGUI.canPlace = false; playerBoardGUI.RandomPlace(); selecter.CanDone(true); } private void Selecter_OnClearBoard(object sender, EventArgs e) { playerBoardGUI.ClearBoard(); playerBoardGUI.canPlace = true; selecter.CanDone(false); } private void Selecter_OnSelectDirection(object sender, SelectShipDirectionArgs e) { playerBoardGUI.shipPlaceHorizontal = e.ShipPlaceHorizontal; } private void Selecter_OnSelectShip(object sender, SelectShipArgs e) { playerBoardGUI.selectedShipSize = e.ShipSize; } public void CloseGUI() { if (exitable) { mediaPlayerBackground.Stop(); mediaPlayerHit.Stop(); mediaPlayerWater.Stop(); this.Visibility = Visibility.Hidden; Server?.Close(); Client?.Close(); } else { var Res = MessageBox.Show("Do you want to return to the menu?", "", MessageBoxButton.YesNo, MessageBoxImage.Question); if (MessageBoxResult.Yes == Res) { exitable = true; Client.sendMessage(new DisconnectData(Client.ID)); CloseGUI(); } } } public bool ExitApplication() { if (exitable) return true; var Res = MessageBox.Show("Do you want to exit?", "", MessageBoxButton.YesNo, MessageBoxImage.Question); if (MessageBoxResult.Yes == Res) { Client.sendMessage(new DisconnectData(Client.ID)); return true; } return false; } private void ClickIPTextBlock(object sender, System.Windows.Input.MouseButtonEventArgs e) => Clipboard.SetText((sender as TextBlock).Text); } }
37.315642
147
0.586571
[ "MIT" ]
kapitany2/Szofttech-WPF
Szofttech-WPF/View/GameGUI.xaml.cs
13,367
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // 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 ClearCanvas Inc. 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 OWNER 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. #endregion using System; using System.Collections.Generic; // This file is auto-generated by the ClearCanvas.Dicom.DataDictionaryGenerator project. namespace ClearCanvas.Dicom { /// <summary> /// This class contains defines for all DICOM SOP Classes. /// </summary> public class SopClass { /// <summary> /// <para>12-lead ECG Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1.1</para> /// </summary> public static readonly String Sop12LeadEcgWaveformStorageUid = "1.2.840.10008.5.1.4.1.1.9.1.1"; /// <summary>SopClass for /// <para>12-lead ECG Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1.1</para> /// </summary> public static readonly SopClass Sop12LeadEcgWaveformStorage = new SopClass("12-lead ECG Waveform Storage", Sop12LeadEcgWaveformStorageUid, false); /// <summary> /// <para>Ambulatory ECG Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1.3</para> /// </summary> public static readonly String AmbulatoryEcgWaveformStorageUid = "1.2.840.10008.5.1.4.1.1.9.1.3"; /// <summary>SopClass for /// <para>Ambulatory ECG Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1.3</para> /// </summary> public static readonly SopClass AmbulatoryEcgWaveformStorage = new SopClass("Ambulatory ECG Waveform Storage", AmbulatoryEcgWaveformStorageUid, false); /// <summary> /// <para>Audio SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.2</para> /// </summary> public static readonly String AudioSrStorageTrialRetiredUid = "1.2.840.10008.5.1.4.1.1.88.2"; /// <summary>SopClass for /// <para>Audio SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.2</para> /// </summary> public static readonly SopClass AudioSrStorageTrialRetired = new SopClass("Audio SR Storage – Trial (Retired)", AudioSrStorageTrialRetiredUid, false); /// <summary> /// <para>Basic Annotation Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.15</para> /// </summary> public static readonly String BasicAnnotationBoxSopClassUid = "1.2.840.10008.5.1.1.15"; /// <summary>SopClass for /// <para>Basic Annotation Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.15</para> /// </summary> public static readonly SopClass BasicAnnotationBoxSopClass = new SopClass("Basic Annotation Box SOP Class", BasicAnnotationBoxSopClassUid, false); /// <summary> /// <para>Basic Color Image Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.4.1</para> /// </summary> public static readonly String BasicColorImageBoxSopClassUid = "1.2.840.10008.5.1.1.4.1"; /// <summary>SopClass for /// <para>Basic Color Image Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.4.1</para> /// </summary> public static readonly SopClass BasicColorImageBoxSopClass = new SopClass("Basic Color Image Box SOP Class", BasicColorImageBoxSopClassUid, false); /// <summary> /// <para>Basic Film Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.2</para> /// </summary> public static readonly String BasicFilmBoxSopClassUid = "1.2.840.10008.5.1.1.2"; /// <summary>SopClass for /// <para>Basic Film Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.2</para> /// </summary> public static readonly SopClass BasicFilmBoxSopClass = new SopClass("Basic Film Box SOP Class", BasicFilmBoxSopClassUid, false); /// <summary> /// <para>Basic Film Session SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.1</para> /// </summary> public static readonly String BasicFilmSessionSopClassUid = "1.2.840.10008.5.1.1.1"; /// <summary>SopClass for /// <para>Basic Film Session SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.1</para> /// </summary> public static readonly SopClass BasicFilmSessionSopClass = new SopClass("Basic Film Session SOP Class", BasicFilmSessionSopClassUid, false); /// <summary> /// <para>Basic Grayscale Image Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.4</para> /// </summary> public static readonly String BasicGrayscaleImageBoxSopClassUid = "1.2.840.10008.5.1.1.4"; /// <summary>SopClass for /// <para>Basic Grayscale Image Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.4</para> /// </summary> public static readonly SopClass BasicGrayscaleImageBoxSopClass = new SopClass("Basic Grayscale Image Box SOP Class", BasicGrayscaleImageBoxSopClassUid, false); /// <summary> /// <para>Basic Print Image Overlay Box SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.24.1</para> /// </summary> public static readonly String BasicPrintImageOverlayBoxSopClassRetiredUid = "1.2.840.10008.5.1.1.24.1"; /// <summary>SopClass for /// <para>Basic Print Image Overlay Box SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.24.1</para> /// </summary> public static readonly SopClass BasicPrintImageOverlayBoxSopClassRetired = new SopClass("Basic Print Image Overlay Box SOP Class (Retired)", BasicPrintImageOverlayBoxSopClassRetiredUid, false); /// <summary> /// <para>Basic Study Content Notification SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.1.9</para> /// </summary> public static readonly String BasicStudyContentNotificationSopClassRetiredUid = "1.2.840.10008.1.9"; /// <summary>SopClass for /// <para>Basic Study Content Notification SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.1.9</para> /// </summary> public static readonly SopClass BasicStudyContentNotificationSopClassRetired = new SopClass("Basic Study Content Notification SOP Class (Retired)", BasicStudyContentNotificationSopClassRetiredUid, false); /// <summary> /// <para>Basic Text SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.11</para> /// </summary> public static readonly String BasicTextSrStorageUid = "1.2.840.10008.5.1.4.1.1.88.11"; /// <summary>SopClass for /// <para>Basic Text SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.11</para> /// </summary> public static readonly SopClass BasicTextSrStorage = new SopClass("Basic Text SR Storage", BasicTextSrStorageUid, false); /// <summary> /// <para>Basic Voice Audio Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.4.1</para> /// </summary> public static readonly String BasicVoiceAudioWaveformStorageUid = "1.2.840.10008.5.1.4.1.1.9.4.1"; /// <summary>SopClass for /// <para>Basic Voice Audio Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.4.1</para> /// </summary> public static readonly SopClass BasicVoiceAudioWaveformStorage = new SopClass("Basic Voice Audio Waveform Storage", BasicVoiceAudioWaveformStorageUid, false); /// <summary> /// <para>Blending Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.4</para> /// </summary> public static readonly String BlendingSoftcopyPresentationStateStorageSopClassUid = "1.2.840.10008.5.1.4.1.1.11.4"; /// <summary>SopClass for /// <para>Blending Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.4</para> /// </summary> public static readonly SopClass BlendingSoftcopyPresentationStateStorageSopClass = new SopClass("Blending Softcopy Presentation State Storage SOP Class", BlendingSoftcopyPresentationStateStorageSopClassUid, false); /// <summary> /// <para>Breast Imaging Relevant Patient Information Query</para> /// <para>UID: 1.2.840.10008.5.1.4.37.2</para> /// </summary> public static readonly String BreastImagingRelevantPatientInformationQueryUid = "1.2.840.10008.5.1.4.37.2"; /// <summary>SopClass for /// <para>Breast Imaging Relevant Patient Information Query</para> /// <para>UID: 1.2.840.10008.5.1.4.37.2</para> /// </summary> public static readonly SopClass BreastImagingRelevantPatientInformationQuery = new SopClass("Breast Imaging Relevant Patient Information Query", BreastImagingRelevantPatientInformationQueryUid, false); /// <summary> /// <para>Cardiac Electrophysiology Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.3.1</para> /// </summary> public static readonly String CardiacElectrophysiologyWaveformStorageUid = "1.2.840.10008.5.1.4.1.1.9.3.1"; /// <summary>SopClass for /// <para>Cardiac Electrophysiology Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.3.1</para> /// </summary> public static readonly SopClass CardiacElectrophysiologyWaveformStorage = new SopClass("Cardiac Electrophysiology Waveform Storage", CardiacElectrophysiologyWaveformStorageUid, false); /// <summary> /// <para>Cardiac Relevant Patient Information Query</para> /// <para>UID: 1.2.840.10008.5.1.4.37.3</para> /// </summary> public static readonly String CardiacRelevantPatientInformationQueryUid = "1.2.840.10008.5.1.4.37.3"; /// <summary>SopClass for /// <para>Cardiac Relevant Patient Information Query</para> /// <para>UID: 1.2.840.10008.5.1.4.37.3</para> /// </summary> public static readonly SopClass CardiacRelevantPatientInformationQuery = new SopClass("Cardiac Relevant Patient Information Query", CardiacRelevantPatientInformationQueryUid, false); /// <summary> /// <para>Chest CAD SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.65</para> /// </summary> public static readonly String ChestCadSrStorageUid = "1.2.840.10008.5.1.4.1.1.88.65"; /// <summary>SopClass for /// <para>Chest CAD SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.65</para> /// </summary> public static readonly SopClass ChestCadSrStorage = new SopClass("Chest CAD SR Storage", ChestCadSrStorageUid, false); /// <summary> /// <para>Color Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.2</para> /// </summary> public static readonly String ColorSoftcopyPresentationStateStorageSopClassUid = "1.2.840.10008.5.1.4.1.1.11.2"; /// <summary>SopClass for /// <para>Color Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.2</para> /// </summary> public static readonly SopClass ColorSoftcopyPresentationStateStorageSopClass = new SopClass("Color Softcopy Presentation State Storage SOP Class", ColorSoftcopyPresentationStateStorageSopClassUid, false); /// <summary> /// <para>Comprehensive SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.33</para> /// </summary> public static readonly String ComprehensiveSrStorageUid = "1.2.840.10008.5.1.4.1.1.88.33"; /// <summary>SopClass for /// <para>Comprehensive SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.33</para> /// </summary> public static readonly SopClass ComprehensiveSrStorage = new SopClass("Comprehensive SR Storage", ComprehensiveSrStorageUid, false); /// <summary> /// <para>Comprehensive SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.4</para> /// </summary> public static readonly String ComprehensiveSrStorageTrialRetiredUid = "1.2.840.10008.5.1.4.1.1.88.4"; /// <summary>SopClass for /// <para>Comprehensive SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.4</para> /// </summary> public static readonly SopClass ComprehensiveSrStorageTrialRetired = new SopClass("Comprehensive SR Storage – Trial (Retired)", ComprehensiveSrStorageTrialRetiredUid, false); /// <summary> /// <para>Computed Radiography Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1</para> /// </summary> public static readonly String ComputedRadiographyImageStorageUid = "1.2.840.10008.5.1.4.1.1.1"; /// <summary>SopClass for /// <para>Computed Radiography Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1</para> /// </summary> public static readonly SopClass ComputedRadiographyImageStorage = new SopClass("Computed Radiography Image Storage", ComputedRadiographyImageStorageUid, false); /// <summary> /// <para>CT Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.2</para> /// </summary> public static readonly String CtImageStorageUid = "1.2.840.10008.5.1.4.1.1.2"; /// <summary>SopClass for /// <para>CT Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.2</para> /// </summary> public static readonly SopClass CtImageStorage = new SopClass("CT Image Storage", CtImageStorageUid, false); /// <summary> /// <para>Deformable Spatial Registration Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.3</para> /// </summary> public static readonly String DeformableSpatialRegistrationStorageUid = "1.2.840.10008.5.1.4.1.1.66.3"; /// <summary>SopClass for /// <para>Deformable Spatial Registration Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.3</para> /// </summary> public static readonly SopClass DeformableSpatialRegistrationStorage = new SopClass("Deformable Spatial Registration Storage", DeformableSpatialRegistrationStorageUid, false); /// <summary> /// <para>Detached Interpretation Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.6.1</para> /// </summary> public static readonly String DetachedInterpretationManagementSopClassRetiredUid = "1.2.840.10008.3.1.2.6.1"; /// <summary>SopClass for /// <para>Detached Interpretation Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.6.1</para> /// </summary> public static readonly SopClass DetachedInterpretationManagementSopClassRetired = new SopClass("Detached Interpretation Management SOP Class (Retired)", DetachedInterpretationManagementSopClassRetiredUid, false); /// <summary> /// <para>Detached Patient Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.1.1</para> /// </summary> public static readonly String DetachedPatientManagementSopClassRetiredUid = "1.2.840.10008.3.1.2.1.1"; /// <summary>SopClass for /// <para>Detached Patient Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.1.1</para> /// </summary> public static readonly SopClass DetachedPatientManagementSopClassRetired = new SopClass("Detached Patient Management SOP Class (Retired)", DetachedPatientManagementSopClassRetiredUid, false); /// <summary> /// <para>Detached Results Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.5.1</para> /// </summary> public static readonly String DetachedResultsManagementSopClassRetiredUid = "1.2.840.10008.3.1.2.5.1"; /// <summary>SopClass for /// <para>Detached Results Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.5.1</para> /// </summary> public static readonly SopClass DetachedResultsManagementSopClassRetired = new SopClass("Detached Results Management SOP Class (Retired)", DetachedResultsManagementSopClassRetiredUid, false); /// <summary> /// <para>Detached Study Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.3.1</para> /// </summary> public static readonly String DetachedStudyManagementSopClassRetiredUid = "1.2.840.10008.3.1.2.3.1"; /// <summary>SopClass for /// <para>Detached Study Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.3.1</para> /// </summary> public static readonly SopClass DetachedStudyManagementSopClassRetired = new SopClass("Detached Study Management SOP Class (Retired)", DetachedStudyManagementSopClassRetiredUid, false); /// <summary> /// <para>Detached Visit Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.2.1</para> /// </summary> public static readonly String DetachedVisitManagementSopClassRetiredUid = "1.2.840.10008.3.1.2.2.1"; /// <summary>SopClass for /// <para>Detached Visit Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.2.1</para> /// </summary> public static readonly SopClass DetachedVisitManagementSopClassRetired = new SopClass("Detached Visit Management SOP Class (Retired)", DetachedVisitManagementSopClassRetiredUid, false); /// <summary> /// <para>Detail SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.3</para> /// </summary> public static readonly String DetailSrStorageTrialRetiredUid = "1.2.840.10008.5.1.4.1.1.88.3"; /// <summary>SopClass for /// <para>Detail SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.3</para> /// </summary> public static readonly SopClass DetailSrStorageTrialRetired = new SopClass("Detail SR Storage – Trial (Retired)", DetailSrStorageTrialRetiredUid, false); /// <summary> /// <para>Digital Intra-oral X-Ray Image Storage – For Presentation</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.3</para> /// </summary> public static readonly String DigitalIntraOralXRayImageStorageForPresentationUid = "1.2.840.10008.5.1.4.1.1.1.3"; /// <summary>SopClass for /// <para>Digital Intra-oral X-Ray Image Storage – For Presentation</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.3</para> /// </summary> public static readonly SopClass DigitalIntraOralXRayImageStorageForPresentation = new SopClass("Digital Intra-oral X-Ray Image Storage – For Presentation", DigitalIntraOralXRayImageStorageForPresentationUid, false); /// <summary> /// <para>Digital Intra-oral X-Ray Image Storage – For Processing</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.3.1</para> /// </summary> public static readonly String DigitalIntraOralXRayImageStorageForProcessingUid = "1.2.840.10008.5.1.4.1.1.1.3.1"; /// <summary>SopClass for /// <para>Digital Intra-oral X-Ray Image Storage – For Processing</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.3.1</para> /// </summary> public static readonly SopClass DigitalIntraOralXRayImageStorageForProcessing = new SopClass("Digital Intra-oral X-Ray Image Storage – For Processing", DigitalIntraOralXRayImageStorageForProcessingUid, false); /// <summary> /// <para>Digital Mammography X-Ray Image Storage – For Presentation</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.2</para> /// </summary> public static readonly String DigitalMammographyXRayImageStorageForPresentationUid = "1.2.840.10008.5.1.4.1.1.1.2"; /// <summary>SopClass for /// <para>Digital Mammography X-Ray Image Storage – For Presentation</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.2</para> /// </summary> public static readonly SopClass DigitalMammographyXRayImageStorageForPresentation = new SopClass("Digital Mammography X-Ray Image Storage – For Presentation", DigitalMammographyXRayImageStorageForPresentationUid, false); /// <summary> /// <para>Digital Mammography X-Ray Image Storage – For Processing</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.2.1</para> /// </summary> public static readonly String DigitalMammographyXRayImageStorageForProcessingUid = "1.2.840.10008.5.1.4.1.1.1.2.1"; /// <summary>SopClass for /// <para>Digital Mammography X-Ray Image Storage – For Processing</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.2.1</para> /// </summary> public static readonly SopClass DigitalMammographyXRayImageStorageForProcessing = new SopClass("Digital Mammography X-Ray Image Storage – For Processing", DigitalMammographyXRayImageStorageForProcessingUid, false); /// <summary> /// <para>Digital X-Ray Image Storage – For Presentation</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.1</para> /// </summary> public static readonly String DigitalXRayImageStorageForPresentationUid = "1.2.840.10008.5.1.4.1.1.1.1"; /// <summary>SopClass for /// <para>Digital X-Ray Image Storage – For Presentation</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.1</para> /// </summary> public static readonly SopClass DigitalXRayImageStorageForPresentation = new SopClass("Digital X-Ray Image Storage – For Presentation", DigitalXRayImageStorageForPresentationUid, false); /// <summary> /// <para>Digital X-Ray Image Storage – For Processing</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.1.1</para> /// </summary> public static readonly String DigitalXRayImageStorageForProcessingUid = "1.2.840.10008.5.1.4.1.1.1.1.1"; /// <summary>SopClass for /// <para>Digital X-Ray Image Storage – For Processing</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.1.1.1</para> /// </summary> public static readonly SopClass DigitalXRayImageStorageForProcessing = new SopClass("Digital X-Ray Image Storage – For Processing", DigitalXRayImageStorageForProcessingUid, false); /// <summary> /// <para>Encapsulated CDA Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.104.2</para> /// </summary> public static readonly String EncapsulatedCdaStorageUid = "1.2.840.10008.5.1.4.1.1.104.2"; /// <summary>SopClass for /// <para>Encapsulated CDA Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.104.2</para> /// </summary> public static readonly SopClass EncapsulatedCdaStorage = new SopClass("Encapsulated CDA Storage", EncapsulatedCdaStorageUid, false); /// <summary> /// <para>Encapsulated PDF Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.104.1</para> /// </summary> public static readonly String EncapsulatedPdfStorageUid = "1.2.840.10008.5.1.4.1.1.104.1"; /// <summary>SopClass for /// <para>Encapsulated PDF Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.104.1</para> /// </summary> public static readonly SopClass EncapsulatedPdfStorage = new SopClass("Encapsulated PDF Storage", EncapsulatedPdfStorageUid, false); /// <summary> /// <para>Enhanced CT Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.2.1</para> /// </summary> public static readonly String EnhancedCtImageStorageUid = "1.2.840.10008.5.1.4.1.1.2.1"; /// <summary>SopClass for /// <para>Enhanced CT Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.2.1</para> /// </summary> public static readonly SopClass EnhancedCtImageStorage = new SopClass("Enhanced CT Image Storage", EnhancedCtImageStorageUid, false); /// <summary> /// <para>Enhanced MR Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.4.1</para> /// </summary> public static readonly String EnhancedMrImageStorageUid = "1.2.840.10008.5.1.4.1.1.4.1"; /// <summary>SopClass for /// <para>Enhanced MR Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.4.1</para> /// </summary> public static readonly SopClass EnhancedMrImageStorage = new SopClass("Enhanced MR Image Storage", EnhancedMrImageStorageUid, false); /// <summary> /// <para>Enhanced SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.22</para> /// </summary> public static readonly String EnhancedSrStorageUid = "1.2.840.10008.5.1.4.1.1.88.22"; /// <summary>SopClass for /// <para>Enhanced SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.22</para> /// </summary> public static readonly SopClass EnhancedSrStorage = new SopClass("Enhanced SR Storage", EnhancedSrStorageUid, false); /// <summary> /// <para>Enhanced XA Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.1.1</para> /// </summary> public static readonly String EnhancedXaImageStorageUid = "1.2.840.10008.5.1.4.1.1.12.1.1"; /// <summary>SopClass for /// <para>Enhanced XA Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.1.1</para> /// </summary> public static readonly SopClass EnhancedXaImageStorage = new SopClass("Enhanced XA Image Storage", EnhancedXaImageStorageUid, false); /// <summary> /// <para>Enhanced XRF Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.2.1</para> /// </summary> public static readonly String EnhancedXrfImageStorageUid = "1.2.840.10008.5.1.4.1.1.12.2.1"; /// <summary>SopClass for /// <para>Enhanced XRF Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.2.1</para> /// </summary> public static readonly SopClass EnhancedXrfImageStorage = new SopClass("Enhanced XRF Image Storage", EnhancedXrfImageStorageUid, false); /// <summary> /// <para>General ECG Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1.2</para> /// </summary> public static readonly String GeneralEcgWaveformStorageUid = "1.2.840.10008.5.1.4.1.1.9.1.2"; /// <summary>SopClass for /// <para>General ECG Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1.2</para> /// </summary> public static readonly SopClass GeneralEcgWaveformStorage = new SopClass("General ECG Waveform Storage", GeneralEcgWaveformStorageUid, false); /// <summary> /// <para>General Purpose Performed Procedure Step SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.32.3</para> /// </summary> public static readonly String GeneralPurposePerformedProcedureStepSopClassUid = "1.2.840.10008.5.1.4.32.3"; /// <summary>SopClass for /// <para>General Purpose Performed Procedure Step SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.32.3</para> /// </summary> public static readonly SopClass GeneralPurposePerformedProcedureStepSopClass = new SopClass("General Purpose Performed Procedure Step SOP Class", GeneralPurposePerformedProcedureStepSopClassUid, false); /// <summary> /// <para>General Purpose Scheduled Procedure Step SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.32.2</para> /// </summary> public static readonly String GeneralPurposeScheduledProcedureStepSopClassUid = "1.2.840.10008.5.1.4.32.2"; /// <summary>SopClass for /// <para>General Purpose Scheduled Procedure Step SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.32.2</para> /// </summary> public static readonly SopClass GeneralPurposeScheduledProcedureStepSopClass = new SopClass("General Purpose Scheduled Procedure Step SOP Class", GeneralPurposeScheduledProcedureStepSopClassUid, false); /// <summary> /// <para>General Purpose Worklist Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.32.1</para> /// </summary> public static readonly String GeneralPurposeWorklistInformationModelFindUid = "1.2.840.10008.5.1.4.32.1"; /// <summary>SopClass for /// <para>General Purpose Worklist Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.32.1</para> /// </summary> public static readonly SopClass GeneralPurposeWorklistInformationModelFind = new SopClass("General Purpose Worklist Information Model – FIND", GeneralPurposeWorklistInformationModelFindUid, false); /// <summary> /// <para>General Relevant Patient Information Query</para> /// <para>UID: 1.2.840.10008.5.1.4.37.1</para> /// </summary> public static readonly String GeneralRelevantPatientInformationQueryUid = "1.2.840.10008.5.1.4.37.1"; /// <summary>SopClass for /// <para>General Relevant Patient Information Query</para> /// <para>UID: 1.2.840.10008.5.1.4.37.1</para> /// </summary> public static readonly SopClass GeneralRelevantPatientInformationQuery = new SopClass("General Relevant Patient Information Query", GeneralRelevantPatientInformationQueryUid, false); /// <summary> /// <para>Grayscale Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.1</para> /// </summary> public static readonly String GrayscaleSoftcopyPresentationStateStorageSopClassUid = "1.2.840.10008.5.1.4.1.1.11.1"; /// <summary>SopClass for /// <para>Grayscale Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.1</para> /// </summary> public static readonly SopClass GrayscaleSoftcopyPresentationStateStorageSopClass = new SopClass("Grayscale Softcopy Presentation State Storage SOP Class", GrayscaleSoftcopyPresentationStateStorageSopClassUid, false); /// <summary> /// <para>Hanging Protocol Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.38.2</para> /// </summary> public static readonly String HangingProtocolInformationModelFindUid = "1.2.840.10008.5.1.4.38.2"; /// <summary>SopClass for /// <para>Hanging Protocol Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.38.2</para> /// </summary> public static readonly SopClass HangingProtocolInformationModelFind = new SopClass("Hanging Protocol Information Model – FIND", HangingProtocolInformationModelFindUid, false); /// <summary> /// <para>Hanging Protocol Information Model – MOVE</para> /// <para>UID: 1.2.840.10008.5.1.4.38.3</para> /// </summary> public static readonly String HangingProtocolInformationModelMoveUid = "1.2.840.10008.5.1.4.38.3"; /// <summary>SopClass for /// <para>Hanging Protocol Information Model – MOVE</para> /// <para>UID: 1.2.840.10008.5.1.4.38.3</para> /// </summary> public static readonly SopClass HangingProtocolInformationModelMove = new SopClass("Hanging Protocol Information Model – MOVE", HangingProtocolInformationModelMoveUid, false); /// <summary> /// <para>Hanging Protocol Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.38.1</para> /// </summary> public static readonly String HangingProtocolStorageUid = "1.2.840.10008.5.1.4.38.1"; /// <summary>SopClass for /// <para>Hanging Protocol Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.38.1</para> /// </summary> public static readonly SopClass HangingProtocolStorage = new SopClass("Hanging Protocol Storage", HangingProtocolStorageUid, false); /// <summary> /// <para>Hardcopy Grayscale Image Storage SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.29</para> /// </summary> public static readonly String HardcopyGrayscaleImageStorageSopClassRetiredUid = "1.2.840.10008.5.1.1.29"; /// <summary>SopClass for /// <para>Hardcopy Grayscale Image Storage SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.29</para> /// </summary> public static readonly SopClass HardcopyGrayscaleImageStorageSopClassRetired = new SopClass("Hardcopy Grayscale Image Storage SOP Class (Retired)", HardcopyGrayscaleImageStorageSopClassRetiredUid, false); /// <summary> /// <para>Hardcopy Color Image Storage SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.30</para> /// </summary> public static readonly String HardcopyColorImageStorageSopClassRetiredUid = "1.2.840.10008.5.1.1.30"; /// <summary>SopClass for /// <para>Hardcopy Color Image Storage SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.30</para> /// </summary> public static readonly SopClass HardcopyColorImageStorageSopClassRetired = new SopClass("Hardcopy Color Image Storage SOP Class (Retired)", HardcopyColorImageStorageSopClassRetiredUid, false); /// <summary> /// <para>Hemodynamic Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.2.1</para> /// </summary> public static readonly String HemodynamicWaveformStorageUid = "1.2.840.10008.5.1.4.1.1.9.2.1"; /// <summary>SopClass for /// <para>Hemodynamic Waveform Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.2.1</para> /// </summary> public static readonly SopClass HemodynamicWaveformStorage = new SopClass("Hemodynamic Waveform Storage", HemodynamicWaveformStorageUid, false); /// <summary> /// <para>Image Overlay Box SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.24</para> /// </summary> public static readonly String ImageOverlayBoxSopClassRetiredUid = "1.2.840.10008.5.1.1.24"; /// <summary>SopClass for /// <para>Image Overlay Box SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.24</para> /// </summary> public static readonly SopClass ImageOverlayBoxSopClassRetired = new SopClass("Image Overlay Box SOP Class (Retired)", ImageOverlayBoxSopClassRetiredUid, false); /// <summary> /// <para>Instance Availability Notification SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.33</para> /// </summary> public static readonly String InstanceAvailabilityNotificationSopClassUid = "1.2.840.10008.5.1.4.33"; /// <summary>SopClass for /// <para>Instance Availability Notification SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.33</para> /// </summary> public static readonly SopClass InstanceAvailabilityNotificationSopClass = new SopClass("Instance Availability Notification SOP Class", InstanceAvailabilityNotificationSopClassUid, false); /// <summary> /// <para>Key Object Selection Document Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.59</para> /// </summary> public static readonly String KeyObjectSelectionDocumentStorageUid = "1.2.840.10008.5.1.4.1.1.88.59"; /// <summary>SopClass for /// <para>Key Object Selection Document Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.59</para> /// </summary> public static readonly SopClass KeyObjectSelectionDocumentStorage = new SopClass("Key Object Selection Document Storage", KeyObjectSelectionDocumentStorageUid, false); /// <summary> /// <para>Mammography CAD SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.50</para> /// </summary> public static readonly String MammographyCadSrStorageUid = "1.2.840.10008.5.1.4.1.1.88.50"; /// <summary>SopClass for /// <para>Mammography CAD SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.50</para> /// </summary> public static readonly SopClass MammographyCadSrStorage = new SopClass("Mammography CAD SR Storage", MammographyCadSrStorageUid, false); /// <summary> /// <para>Media Creation Management SOP Class UID</para> /// <para>UID: 1.2.840.10008.5.1.1.33</para> /// </summary> public static readonly String MediaCreationManagementSopClassUidUid = "1.2.840.10008.5.1.1.33"; /// <summary>SopClass for /// <para>Media Creation Management SOP Class UID</para> /// <para>UID: 1.2.840.10008.5.1.1.33</para> /// </summary> public static readonly SopClass MediaCreationManagementSopClassUid = new SopClass("Media Creation Management SOP Class UID", MediaCreationManagementSopClassUidUid, false); /// <summary> /// <para>Media Storage Directory Storage</para> /// <para>UID: 1.2.840.10008.1.3.10</para> /// </summary> public static readonly String MediaStorageDirectoryStorageUid = "1.2.840.10008.1.3.10"; /// <summary>SopClass for /// <para>Media Storage Directory Storage</para> /// <para>UID: 1.2.840.10008.1.3.10</para> /// </summary> public static readonly SopClass MediaStorageDirectoryStorage = new SopClass("Media Storage Directory Storage", MediaStorageDirectoryStorageUid, false); /// <summary> /// <para>Modality Performed Procedure Step Notification SOP Class</para> /// <para>UID: 1.2.840.10008.3.1.2.3.5</para> /// </summary> public static readonly String ModalityPerformedProcedureStepNotificationSopClassUid = "1.2.840.10008.3.1.2.3.5"; /// <summary>SopClass for /// <para>Modality Performed Procedure Step Notification SOP Class</para> /// <para>UID: 1.2.840.10008.3.1.2.3.5</para> /// </summary> public static readonly SopClass ModalityPerformedProcedureStepNotificationSopClass = new SopClass("Modality Performed Procedure Step Notification SOP Class", ModalityPerformedProcedureStepNotificationSopClassUid, false); /// <summary> /// <para>Modality Performed Procedure Step Retrieve SOP Class</para> /// <para>UID: 1.2.840.10008.3.1.2.3.4</para> /// </summary> public static readonly String ModalityPerformedProcedureStepRetrieveSopClassUid = "1.2.840.10008.3.1.2.3.4"; /// <summary>SopClass for /// <para>Modality Performed Procedure Step Retrieve SOP Class</para> /// <para>UID: 1.2.840.10008.3.1.2.3.4</para> /// </summary> public static readonly SopClass ModalityPerformedProcedureStepRetrieveSopClass = new SopClass("Modality Performed Procedure Step Retrieve SOP Class", ModalityPerformedProcedureStepRetrieveSopClassUid, false); /// <summary> /// <para>Modality Performed Procedure Step SOP Class</para> /// <para>UID: 1.2.840.10008.3.1.2.3.3</para> /// </summary> public static readonly String ModalityPerformedProcedureStepSopClassUid = "1.2.840.10008.3.1.2.3.3"; /// <summary>SopClass for /// <para>Modality Performed Procedure Step SOP Class</para> /// <para>UID: 1.2.840.10008.3.1.2.3.3</para> /// </summary> public static readonly SopClass ModalityPerformedProcedureStepSopClass = new SopClass("Modality Performed Procedure Step SOP Class", ModalityPerformedProcedureStepSopClassUid, false); /// <summary> /// <para>Modality Worklist Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.31</para> /// </summary> public static readonly String ModalityWorklistInformationModelFindUid = "1.2.840.10008.5.1.4.31"; /// <summary>SopClass for /// <para>Modality Worklist Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.31</para> /// </summary> public static readonly SopClass ModalityWorklistInformationModelFind = new SopClass("Modality Worklist Information Model – FIND", ModalityWorklistInformationModelFindUid, false); /// <summary> /// <para>MR Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.4</para> /// </summary> public static readonly String MrImageStorageUid = "1.2.840.10008.5.1.4.1.1.4"; /// <summary>SopClass for /// <para>MR Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.4</para> /// </summary> public static readonly SopClass MrImageStorage = new SopClass("MR Image Storage", MrImageStorageUid, false); /// <summary> /// <para>MR Spectroscopy Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.4.2</para> /// </summary> public static readonly String MrSpectroscopyStorageUid = "1.2.840.10008.5.1.4.1.1.4.2"; /// <summary>SopClass for /// <para>MR Spectroscopy Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.4.2</para> /// </summary> public static readonly SopClass MrSpectroscopyStorage = new SopClass("MR Spectroscopy Storage", MrSpectroscopyStorageUid, false); /// <summary> /// <para>Multi-frame Grayscale Byte Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.2</para> /// </summary> public static readonly String MultiFrameGrayscaleByteSecondaryCaptureImageStorageUid = "1.2.840.10008.5.1.4.1.1.7.2"; /// <summary>SopClass for /// <para>Multi-frame Grayscale Byte Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.2</para> /// </summary> public static readonly SopClass MultiFrameGrayscaleByteSecondaryCaptureImageStorage = new SopClass("Multi-frame Grayscale Byte Secondary Capture Image Storage", MultiFrameGrayscaleByteSecondaryCaptureImageStorageUid, false); /// <summary> /// <para>Multi-frame Grayscale Word Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.3</para> /// </summary> public static readonly String MultiFrameGrayscaleWordSecondaryCaptureImageStorageUid = "1.2.840.10008.5.1.4.1.1.7.3"; /// <summary>SopClass for /// <para>Multi-frame Grayscale Word Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.3</para> /// </summary> public static readonly SopClass MultiFrameGrayscaleWordSecondaryCaptureImageStorage = new SopClass("Multi-frame Grayscale Word Secondary Capture Image Storage", MultiFrameGrayscaleWordSecondaryCaptureImageStorageUid, false); /// <summary> /// <para>Multi-frame Single Bit Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.1</para> /// </summary> public static readonly String MultiFrameSingleBitSecondaryCaptureImageStorageUid = "1.2.840.10008.5.1.4.1.1.7.1"; /// <summary>SopClass for /// <para>Multi-frame Single Bit Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.1</para> /// </summary> public static readonly SopClass MultiFrameSingleBitSecondaryCaptureImageStorage = new SopClass("Multi-frame Single Bit Secondary Capture Image Storage", MultiFrameSingleBitSecondaryCaptureImageStorageUid, false); /// <summary> /// <para>Multi-frame True Color Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.4</para> /// </summary> public static readonly String MultiFrameTrueColorSecondaryCaptureImageStorageUid = "1.2.840.10008.5.1.4.1.1.7.4"; /// <summary>SopClass for /// <para>Multi-frame True Color Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7.4</para> /// </summary> public static readonly SopClass MultiFrameTrueColorSecondaryCaptureImageStorage = new SopClass("Multi-frame True Color Secondary Capture Image Storage", MultiFrameTrueColorSecondaryCaptureImageStorageUid, false); /// <summary> /// <para>Nuclear Medicine Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.5</para> /// </summary> public static readonly String NuclearMedicineImageStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.5"; /// <summary>SopClass for /// <para>Nuclear Medicine Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.5</para> /// </summary> public static readonly SopClass NuclearMedicineImageStorageRetired = new SopClass("Nuclear Medicine Image Storage (Retired)", NuclearMedicineImageStorageRetiredUid, false); /// <summary> /// <para>Nuclear Medicine Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.20</para> /// </summary> public static readonly String NuclearMedicineImageStorageUid = "1.2.840.10008.5.1.4.1.1.20"; /// <summary>SopClass for /// <para>Nuclear Medicine Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.20</para> /// </summary> public static readonly SopClass NuclearMedicineImageStorage = new SopClass("Nuclear Medicine Image Storage", NuclearMedicineImageStorageUid, false); /// <summary> /// <para>Ophthalmic Photography 16 Bit Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.2</para> /// </summary> public static readonly String OphthalmicPhotography16BitImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.5.2"; /// <summary>SopClass for /// <para>Ophthalmic Photography 16 Bit Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.2</para> /// </summary> public static readonly SopClass OphthalmicPhotography16BitImageStorage = new SopClass("Ophthalmic Photography 16 Bit Image Storage", OphthalmicPhotography16BitImageStorageUid, false); /// <summary> /// <para>Ophthalmic Photography 8 Bit Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.1</para> /// </summary> public static readonly String OphthalmicPhotography8BitImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.5.1"; /// <summary>SopClass for /// <para>Ophthalmic Photography 8 Bit Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.1</para> /// </summary> public static readonly SopClass OphthalmicPhotography8BitImageStorage = new SopClass("Ophthalmic Photography 8 Bit Image Storage", OphthalmicPhotography8BitImageStorageUid, false); /// <summary> /// <para>Ophthalmic Tomography Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.4</para> /// </summary> public static readonly String OphthalmicTomographyImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.5.4"; /// <summary>SopClass for /// <para>Ophthalmic Tomography Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.4</para> /// </summary> public static readonly SopClass OphthalmicTomographyImageStorage = new SopClass("Ophthalmic Tomography Image Storage", OphthalmicTomographyImageStorageUid, false); /// <summary> /// <para>Patient Root Query/Retrieve Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.1.1</para> /// </summary> public static readonly String PatientRootQueryRetrieveInformationModelFindUid = "1.2.840.10008.5.1.4.1.2.1.1"; /// <summary>SopClass for /// <para>Patient Root Query/Retrieve Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.1.1</para> /// </summary> public static readonly SopClass PatientRootQueryRetrieveInformationModelFind = new SopClass("Patient Root Query/Retrieve Information Model – FIND", PatientRootQueryRetrieveInformationModelFindUid, false); /// <summary> /// <para>Patient Root Query/Retrieve Information Model – GET</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.1.3</para> /// </summary> public static readonly String PatientRootQueryRetrieveInformationModelGetUid = "1.2.840.10008.5.1.4.1.2.1.3"; /// <summary>SopClass for /// <para>Patient Root Query/Retrieve Information Model – GET</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.1.3</para> /// </summary> public static readonly SopClass PatientRootQueryRetrieveInformationModelGet = new SopClass("Patient Root Query/Retrieve Information Model – GET", PatientRootQueryRetrieveInformationModelGetUid, false); /// <summary> /// <para>Patient Root Query/Retrieve Information Model – MOVE</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.1.2</para> /// </summary> public static readonly String PatientRootQueryRetrieveInformationModelMoveUid = "1.2.840.10008.5.1.4.1.2.1.2"; /// <summary>SopClass for /// <para>Patient Root Query/Retrieve Information Model – MOVE</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.1.2</para> /// </summary> public static readonly SopClass PatientRootQueryRetrieveInformationModelMove = new SopClass("Patient Root Query/Retrieve Information Model – MOVE", PatientRootQueryRetrieveInformationModelMoveUid, false); /// <summary> /// <para>Patient/Study Only Query/Retrieve Information Model - FIND (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.3.1</para> /// </summary> public static readonly String PatientStudyOnlyQueryRetrieveInformationModelFindRetiredUid = "1.2.840.10008.5.1.4.1.2.3.1"; /// <summary>SopClass for /// <para>Patient/Study Only Query/Retrieve Information Model - FIND (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.3.1</para> /// </summary> public static readonly SopClass PatientStudyOnlyQueryRetrieveInformationModelFindRetired = new SopClass("Patient/Study Only Query/Retrieve Information Model - FIND (Retired)", PatientStudyOnlyQueryRetrieveInformationModelFindRetiredUid, false); /// <summary> /// <para>Patient/Study Only Query/Retrieve Information Model - GET (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.3.3</para> /// </summary> public static readonly String PatientStudyOnlyQueryRetrieveInformationModelGetRetiredUid = "1.2.840.10008.5.1.4.1.2.3.3"; /// <summary>SopClass for /// <para>Patient/Study Only Query/Retrieve Information Model - GET (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.3.3</para> /// </summary> public static readonly SopClass PatientStudyOnlyQueryRetrieveInformationModelGetRetired = new SopClass("Patient/Study Only Query/Retrieve Information Model - GET (Retired)", PatientStudyOnlyQueryRetrieveInformationModelGetRetiredUid, false); /// <summary> /// <para>Patient/Study Only Query/Retrieve Information Model - MOVE (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.3.2</para> /// </summary> public static readonly String PatientStudyOnlyQueryRetrieveInformationModelMoveRetiredUid = "1.2.840.10008.5.1.4.1.2.3.2"; /// <summary>SopClass for /// <para>Patient/Study Only Query/Retrieve Information Model - MOVE (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.3.2</para> /// </summary> public static readonly SopClass PatientStudyOnlyQueryRetrieveInformationModelMoveRetired = new SopClass("Patient/Study Only Query/Retrieve Information Model - MOVE (Retired)", PatientStudyOnlyQueryRetrieveInformationModelMoveRetiredUid, false); /// <summary> /// <para>Positron Emission Tomography Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.128</para> /// </summary> public static readonly String PositronEmissionTomographyImageStorageUid = "1.2.840.10008.5.1.4.1.1.128"; /// <summary>SopClass for /// <para>Positron Emission Tomography Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.128</para> /// </summary> public static readonly SopClass PositronEmissionTomographyImageStorage = new SopClass("Positron Emission Tomography Image Storage", PositronEmissionTomographyImageStorageUid, false); /// <summary> /// <para>Presentation LUT SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.23</para> /// </summary> public static readonly String PresentationLutSopClassUid = "1.2.840.10008.5.1.1.23"; /// <summary>SopClass for /// <para>Presentation LUT SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.23</para> /// </summary> public static readonly SopClass PresentationLutSopClass = new SopClass("Presentation LUT SOP Class", PresentationLutSopClassUid, false); /// <summary> /// <para>Print Job SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.14</para> /// </summary> public static readonly String PrintJobSopClassUid = "1.2.840.10008.5.1.1.14"; /// <summary>SopClass for /// <para>Print Job SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.14</para> /// </summary> public static readonly SopClass PrintJobSopClass = new SopClass("Print Job SOP Class", PrintJobSopClassUid, false); /// <summary> /// <para>Print Queue Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.26</para> /// </summary> public static readonly String PrintQueueManagementSopClassRetiredUid = "1.2.840.10008.5.1.1.26"; /// <summary>SopClass for /// <para>Print Queue Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.26</para> /// </summary> public static readonly SopClass PrintQueueManagementSopClassRetired = new SopClass("Print Queue Management SOP Class (Retired)", PrintQueueManagementSopClassRetiredUid, false); /// <summary> /// <para>Printer Configuration Retrieval SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.16.376</para> /// </summary> public static readonly String PrinterConfigurationRetrievalSopClassUid = "1.2.840.10008.5.1.1.16.376"; /// <summary>SopClass for /// <para>Printer Configuration Retrieval SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.16.376</para> /// </summary> public static readonly SopClass PrinterConfigurationRetrievalSopClass = new SopClass("Printer Configuration Retrieval SOP Class", PrinterConfigurationRetrievalSopClassUid, false); /// <summary> /// <para>Printer SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.16</para> /// </summary> public static readonly String PrinterSopClassUid = "1.2.840.10008.5.1.1.16"; /// <summary>SopClass for /// <para>Printer SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.16</para> /// </summary> public static readonly SopClass PrinterSopClass = new SopClass("Printer SOP Class", PrinterSopClassUid, false); /// <summary> /// <para>Procedural Event Logging SOP Class</para> /// <para>UID: 1.2.840.10008.1.40</para> /// </summary> public static readonly String ProceduralEventLoggingSopClassUid = "1.2.840.10008.1.40"; /// <summary>SopClass for /// <para>Procedural Event Logging SOP Class</para> /// <para>UID: 1.2.840.10008.1.40</para> /// </summary> public static readonly SopClass ProceduralEventLoggingSopClass = new SopClass("Procedural Event Logging SOP Class", ProceduralEventLoggingSopClassUid, false); /// <summary> /// <para>Procedure Log Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.40</para> /// </summary> public static readonly String ProcedureLogStorageUid = "1.2.840.10008.5.1.4.1.1.88.40"; /// <summary>SopClass for /// <para>Procedure Log Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.40</para> /// </summary> public static readonly SopClass ProcedureLogStorage = new SopClass("Procedure Log Storage", ProcedureLogStorageUid, false); /// <summary> /// <para>Product Characteristics Query SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.41</para> /// </summary> public static readonly String ProductCharacteristicsQuerySopClassUid = "1.2.840.10008.5.1.4.41"; /// <summary>SopClass for /// <para>Product Characteristics Query SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.41</para> /// </summary> public static readonly SopClass ProductCharacteristicsQuerySopClass = new SopClass("Product Characteristics Query SOP Class", ProductCharacteristicsQuerySopClassUid, false); /// <summary> /// <para>Pseudo-Color Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.3</para> /// </summary> public static readonly String PseudoColorSoftcopyPresentationStateStorageSopClassUid = "1.2.840.10008.5.1.4.1.1.11.3"; /// <summary>SopClass for /// <para>Pseudo-Color Softcopy Presentation State Storage SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11.3</para> /// </summary> public static readonly SopClass PseudoColorSoftcopyPresentationStateStorageSopClass = new SopClass("Pseudo-Color Softcopy Presentation State Storage SOP Class", PseudoColorSoftcopyPresentationStateStorageSopClassUid, false); /// <summary> /// <para>Pull Print Request SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.31</para> /// </summary> public static readonly String PullPrintRequestSopClassRetiredUid = "1.2.840.10008.5.1.1.31"; /// <summary>SopClass for /// <para>Pull Print Request SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.31</para> /// </summary> public static readonly SopClass PullPrintRequestSopClassRetired = new SopClass("Pull Print Request SOP Class (Retired)", PullPrintRequestSopClassRetiredUid, false); /// <summary> /// <para>Raw Data Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66</para> /// </summary> public static readonly String RawDataStorageUid = "1.2.840.10008.5.1.4.1.1.66"; /// <summary>SopClass for /// <para>Raw Data Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66</para> /// </summary> public static readonly SopClass RawDataStorage = new SopClass("Raw Data Storage", RawDataStorageUid, false); /// <summary> /// <para>Real World Value Mapping Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.67</para> /// </summary> public static readonly String RealWorldValueMappingStorageUid = "1.2.840.10008.5.1.4.1.1.67"; /// <summary>SopClass for /// <para>Real World Value Mapping Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.67</para> /// </summary> public static readonly SopClass RealWorldValueMappingStorage = new SopClass("Real World Value Mapping Storage", RealWorldValueMappingStorageUid, false); /// <summary> /// <para>Referenced Image Box SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.4.2</para> /// </summary> public static readonly String ReferencedImageBoxSopClassRetiredUid = "1.2.840.10008.5.1.1.4.2"; /// <summary>SopClass for /// <para>Referenced Image Box SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.4.2</para> /// </summary> public static readonly SopClass ReferencedImageBoxSopClassRetired = new SopClass("Referenced Image Box SOP Class (Retired)", ReferencedImageBoxSopClassRetiredUid, false); /// <summary> /// <para>RT Beams Delivery Instruction Storage (Supplement 74 Frozen Draft)</para> /// <para>UID: 1.2.840.10008.5.1.4.34.1</para> /// </summary> public static readonly String RtBeamsDeliveryInstructionStorageSupplement74FrozenDraftUid = "1.2.840.10008.5.1.4.34.1"; /// <summary>SopClass for /// <para>RT Beams Delivery Instruction Storage (Supplement 74 Frozen Draft)</para> /// <para>UID: 1.2.840.10008.5.1.4.34.1</para> /// </summary> public static readonly SopClass RtBeamsDeliveryInstructionStorageSupplement74FrozenDraft = new SopClass("RT Beams Delivery Instruction Storage (Supplement 74 Frozen Draft)", RtBeamsDeliveryInstructionStorageSupplement74FrozenDraftUid, false); /// <summary> /// <para>RT Beams Treatment Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.4</para> /// </summary> public static readonly String RtBeamsTreatmentRecordStorageUid = "1.2.840.10008.5.1.4.1.1.481.4"; /// <summary>SopClass for /// <para>RT Beams Treatment Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.4</para> /// </summary> public static readonly SopClass RtBeamsTreatmentRecordStorage = new SopClass("RT Beams Treatment Record Storage", RtBeamsTreatmentRecordStorageUid, false); /// <summary> /// <para>RT Brachy Treatment Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.6</para> /// </summary> public static readonly String RtBrachyTreatmentRecordStorageUid = "1.2.840.10008.5.1.4.1.1.481.6"; /// <summary>SopClass for /// <para>RT Brachy Treatment Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.6</para> /// </summary> public static readonly SopClass RtBrachyTreatmentRecordStorage = new SopClass("RT Brachy Treatment Record Storage", RtBrachyTreatmentRecordStorageUid, false); /// <summary> /// <para>RT Conventional Machine Verification (Supplement 74 Frozen Draft)</para> /// <para>UID: 1.2.840.10008.5.1.4.34.2</para> /// </summary> public static readonly String RtConventionalMachineVerificationSupplement74FrozenDraftUid = "1.2.840.10008.5.1.4.34.2"; /// <summary>SopClass for /// <para>RT Conventional Machine Verification (Supplement 74 Frozen Draft)</para> /// <para>UID: 1.2.840.10008.5.1.4.34.2</para> /// </summary> public static readonly SopClass RtConventionalMachineVerificationSupplement74FrozenDraft = new SopClass("RT Conventional Machine Verification (Supplement 74 Frozen Draft)", RtConventionalMachineVerificationSupplement74FrozenDraftUid, false); /// <summary> /// <para>RT Dose Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.2</para> /// </summary> public static readonly String RtDoseStorageUid = "1.2.840.10008.5.1.4.1.1.481.2"; /// <summary>SopClass for /// <para>RT Dose Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.2</para> /// </summary> public static readonly SopClass RtDoseStorage = new SopClass("RT Dose Storage", RtDoseStorageUid, false); /// <summary> /// <para>RT Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.1</para> /// </summary> public static readonly String RtImageStorageUid = "1.2.840.10008.5.1.4.1.1.481.1"; /// <summary>SopClass for /// <para>RT Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.1</para> /// </summary> public static readonly SopClass RtImageStorage = new SopClass("RT Image Storage", RtImageStorageUid, false); /// <summary> /// <para>RT Ion Beams Treatment Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.9</para> /// </summary> public static readonly String RtIonBeamsTreatmentRecordStorageUid = "1.2.840.10008.5.1.4.1.1.481.9"; /// <summary>SopClass for /// <para>RT Ion Beams Treatment Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.9</para> /// </summary> public static readonly SopClass RtIonBeamsTreatmentRecordStorage = new SopClass("RT Ion Beams Treatment Record Storage", RtIonBeamsTreatmentRecordStorageUid, false); /// <summary> /// <para>RT Ion Machine Verification (Supplement 74 Frozen Draft)</para> /// <para>UID: 1.2.840.10008.5.1.4.34.3</para> /// </summary> public static readonly String RtIonMachineVerificationSupplement74FrozenDraftUid = "1.2.840.10008.5.1.4.34.3"; /// <summary>SopClass for /// <para>RT Ion Machine Verification (Supplement 74 Frozen Draft)</para> /// <para>UID: 1.2.840.10008.5.1.4.34.3</para> /// </summary> public static readonly SopClass RtIonMachineVerificationSupplement74FrozenDraft = new SopClass("RT Ion Machine Verification (Supplement 74 Frozen Draft)", RtIonMachineVerificationSupplement74FrozenDraftUid, false); /// <summary> /// <para>RT Ion Plan Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.8</para> /// </summary> public static readonly String RtIonPlanStorageUid = "1.2.840.10008.5.1.4.1.1.481.8"; /// <summary>SopClass for /// <para>RT Ion Plan Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.8</para> /// </summary> public static readonly SopClass RtIonPlanStorage = new SopClass("RT Ion Plan Storage", RtIonPlanStorageUid, false); /// <summary> /// <para>RT Plan Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.5</para> /// </summary> public static readonly String RtPlanStorageUid = "1.2.840.10008.5.1.4.1.1.481.5"; /// <summary>SopClass for /// <para>RT Plan Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.5</para> /// </summary> public static readonly SopClass RtPlanStorage = new SopClass("RT Plan Storage", RtPlanStorageUid, false); /// <summary> /// <para>RT Structure Set Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.3</para> /// </summary> public static readonly String RtStructureSetStorageUid = "1.2.840.10008.5.1.4.1.1.481.3"; /// <summary>SopClass for /// <para>RT Structure Set Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.3</para> /// </summary> public static readonly SopClass RtStructureSetStorage = new SopClass("RT Structure Set Storage", RtStructureSetStorageUid, false); /// <summary> /// <para>RT Treatment Summary Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.7</para> /// </summary> public static readonly String RtTreatmentSummaryRecordStorageUid = "1.2.840.10008.5.1.4.1.1.481.7"; /// <summary>SopClass for /// <para>RT Treatment Summary Record Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.481.7</para> /// </summary> public static readonly SopClass RtTreatmentSummaryRecordStorage = new SopClass("RT Treatment Summary Record Storage", RtTreatmentSummaryRecordStorageUid, false); /// <summary> /// <para>Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7</para> /// </summary> public static readonly String SecondaryCaptureImageStorageUid = "1.2.840.10008.5.1.4.1.1.7"; /// <summary>SopClass for /// <para>Secondary Capture Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.7</para> /// </summary> public static readonly SopClass SecondaryCaptureImageStorage = new SopClass("Secondary Capture Image Storage", SecondaryCaptureImageStorageUid, false); /// <summary> /// <para>Segmentation Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.4</para> /// </summary> public static readonly String SegmentationStorageUid = "1.2.840.10008.5.1.4.1.1.66.4"; /// <summary>SopClass for /// <para>Segmentation Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.4</para> /// </summary> public static readonly SopClass SegmentationStorage = new SopClass("Segmentation Storage", SegmentationStorageUid, false); /// <summary> /// <para>Spatial Fiducials Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.2</para> /// </summary> public static readonly String SpatialFiducialsStorageUid = "1.2.840.10008.5.1.4.1.1.66.2"; /// <summary>SopClass for /// <para>Spatial Fiducials Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.2</para> /// </summary> public static readonly SopClass SpatialFiducialsStorage = new SopClass("Spatial Fiducials Storage", SpatialFiducialsStorageUid, false); /// <summary> /// <para>Spatial Registration Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.1</para> /// </summary> public static readonly String SpatialRegistrationStorageUid = "1.2.840.10008.5.1.4.1.1.66.1"; /// <summary>SopClass for /// <para>Spatial Registration Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.66.1</para> /// </summary> public static readonly SopClass SpatialRegistrationStorage = new SopClass("Spatial Registration Storage", SpatialRegistrationStorageUid, false); /// <summary> /// <para>Standalone Curve Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9</para> /// </summary> public static readonly String StandaloneCurveStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.9"; /// <summary>SopClass for /// <para>Standalone Curve Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9</para> /// </summary> public static readonly SopClass StandaloneCurveStorageRetired = new SopClass("Standalone Curve Storage (Retired)", StandaloneCurveStorageRetiredUid, false); /// <summary> /// <para>Standalone Modality LUT Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.10</para> /// </summary> public static readonly String StandaloneModalityLutStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.10"; /// <summary>SopClass for /// <para>Standalone Modality LUT Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.10</para> /// </summary> public static readonly SopClass StandaloneModalityLutStorageRetired = new SopClass("Standalone Modality LUT Storage (Retired)", StandaloneModalityLutStorageRetiredUid, false); /// <summary> /// <para>Standalone Overlay Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.8</para> /// </summary> public static readonly String StandaloneOverlayStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.8"; /// <summary>SopClass for /// <para>Standalone Overlay Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.8</para> /// </summary> public static readonly SopClass StandaloneOverlayStorageRetired = new SopClass("Standalone Overlay Storage (Retired)", StandaloneOverlayStorageRetiredUid, false); /// <summary> /// <para>Standalone PET Curve Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.129</para> /// </summary> public static readonly String StandalonePetCurveStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.129"; /// <summary>SopClass for /// <para>Standalone PET Curve Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.129</para> /// </summary> public static readonly SopClass StandalonePetCurveStorageRetired = new SopClass("Standalone PET Curve Storage (Retired)", StandalonePetCurveStorageRetiredUid, false); /// <summary> /// <para>Standalone VOI LUT Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11</para> /// </summary> public static readonly String StandaloneVoiLutStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.11"; /// <summary>SopClass for /// <para>Standalone VOI LUT Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.11</para> /// </summary> public static readonly SopClass StandaloneVoiLutStorageRetired = new SopClass("Standalone VOI LUT Storage (Retired)", StandaloneVoiLutStorageRetiredUid, false); /// <summary> /// <para>Stereometric Relationship Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.3</para> /// </summary> public static readonly String StereometricRelationshipStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.5.3"; /// <summary>SopClass for /// <para>Stereometric Relationship Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.5.3</para> /// </summary> public static readonly SopClass StereometricRelationshipStorage = new SopClass("Stereometric Relationship Storage", StereometricRelationshipStorageUid, false); /// <summary> /// <para>Storage Commitment Pull Model SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.1.20.2</para> /// </summary> public static readonly String StorageCommitmentPullModelSopClassRetiredUid = "1.2.840.10008.1.20.2"; /// <summary>SopClass for /// <para>Storage Commitment Pull Model SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.1.20.2</para> /// </summary> public static readonly SopClass StorageCommitmentPullModelSopClassRetired = new SopClass("Storage Commitment Pull Model SOP Class (Retired)", StorageCommitmentPullModelSopClassRetiredUid, false); /// <summary> /// <para>Storage Commitment Push Model SOP Class</para> /// <para>UID: 1.2.840.10008.1.20.1</para> /// </summary> public static readonly String StorageCommitmentPushModelSopClassUid = "1.2.840.10008.1.20.1"; /// <summary>SopClass for /// <para>Storage Commitment Push Model SOP Class</para> /// <para>UID: 1.2.840.10008.1.20.1</para> /// </summary> public static readonly SopClass StorageCommitmentPushModelSopClass = new SopClass("Storage Commitment Push Model SOP Class", StorageCommitmentPushModelSopClassUid, false); /// <summary> /// <para>Stored Print Storage SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.27</para> /// </summary> public static readonly String StoredPrintStorageSopClassRetiredUid = "1.2.840.10008.5.1.1.27"; /// <summary>SopClass for /// <para>Stored Print Storage SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.27</para> /// </summary> public static readonly SopClass StoredPrintStorageSopClassRetired = new SopClass("Stored Print Storage SOP Class (Retired)", StoredPrintStorageSopClassRetiredUid, false); /// <summary> /// <para>Study Component Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.3.2</para> /// </summary> public static readonly String StudyComponentManagementSopClassRetiredUid = "1.2.840.10008.3.1.2.3.2"; /// <summary>SopClass for /// <para>Study Component Management SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.3.2</para> /// </summary> public static readonly SopClass StudyComponentManagementSopClassRetired = new SopClass("Study Component Management SOP Class (Retired)", StudyComponentManagementSopClassRetiredUid, false); /// <summary> /// <para>Study Root Query/Retrieve Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.2.1</para> /// </summary> public static readonly String StudyRootQueryRetrieveInformationModelFindUid = "1.2.840.10008.5.1.4.1.2.2.1"; /// <summary>SopClass for /// <para>Study Root Query/Retrieve Information Model – FIND</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.2.1</para> /// </summary> public static readonly SopClass StudyRootQueryRetrieveInformationModelFind = new SopClass("Study Root Query/Retrieve Information Model – FIND", StudyRootQueryRetrieveInformationModelFindUid, false); /// <summary> /// <para>Study Root Query/Retrieve Information Model – GET</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.2.3</para> /// </summary> public static readonly String StudyRootQueryRetrieveInformationModelGetUid = "1.2.840.10008.5.1.4.1.2.2.3"; /// <summary>SopClass for /// <para>Study Root Query/Retrieve Information Model – GET</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.2.3</para> /// </summary> public static readonly SopClass StudyRootQueryRetrieveInformationModelGet = new SopClass("Study Root Query/Retrieve Information Model – GET", StudyRootQueryRetrieveInformationModelGetUid, false); /// <summary> /// <para>Study Root Query/Retrieve Information Model – MOVE</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.2.2</para> /// </summary> public static readonly String StudyRootQueryRetrieveInformationModelMoveUid = "1.2.840.10008.5.1.4.1.2.2.2"; /// <summary>SopClass for /// <para>Study Root Query/Retrieve Information Model – MOVE</para> /// <para>UID: 1.2.840.10008.5.1.4.1.2.2.2</para> /// </summary> public static readonly SopClass StudyRootQueryRetrieveInformationModelMove = new SopClass("Study Root Query/Retrieve Information Model – MOVE", StudyRootQueryRetrieveInformationModelMoveUid, false); /// <summary> /// <para>Substance Administration Logging SOP Class</para> /// <para>UID: 1.2.840.10008.1.42</para> /// </summary> public static readonly String SubstanceAdministrationLoggingSopClassUid = "1.2.840.10008.1.42"; /// <summary>SopClass for /// <para>Substance Administration Logging SOP Class</para> /// <para>UID: 1.2.840.10008.1.42</para> /// </summary> public static readonly SopClass SubstanceAdministrationLoggingSopClass = new SopClass("Substance Administration Logging SOP Class", SubstanceAdministrationLoggingSopClassUid, false); /// <summary> /// <para>Substance Approval Query SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.42</para> /// </summary> public static readonly String SubstanceApprovalQuerySopClassUid = "1.2.840.10008.5.1.4.42"; /// <summary>SopClass for /// <para>Substance Approval Query SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.42</para> /// </summary> public static readonly SopClass SubstanceApprovalQuerySopClass = new SopClass("Substance Approval Query SOP Class", SubstanceApprovalQuerySopClassUid, false); /// <summary> /// <para>Text SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.1</para> /// </summary> public static readonly String TextSrStorageTrialRetiredUid = "1.2.840.10008.5.1.4.1.1.88.1"; /// <summary>SopClass for /// <para>Text SR Storage – Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.1</para> /// </summary> public static readonly SopClass TextSrStorageTrialRetired = new SopClass("Text SR Storage – Trial (Retired)", TextSrStorageTrialRetiredUid, false); /// <summary> /// <para>Ultrasound Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.6.1</para> /// </summary> public static readonly String UltrasoundImageStorageUid = "1.2.840.10008.5.1.4.1.1.6.1"; /// <summary>SopClass for /// <para>Ultrasound Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.6.1</para> /// </summary> public static readonly SopClass UltrasoundImageStorage = new SopClass("Ultrasound Image Storage", UltrasoundImageStorageUid, false); /// <summary> /// <para>Ultrasound Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.6</para> /// </summary> public static readonly String UltrasoundImageStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.6"; /// <summary>SopClass for /// <para>Ultrasound Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.6</para> /// </summary> public static readonly SopClass UltrasoundImageStorageRetired = new SopClass("Ultrasound Image Storage (Retired)", UltrasoundImageStorageRetiredUid, false); /// <summary> /// <para>Ultrasound Multi-frame Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.3.1</para> /// </summary> public static readonly String UltrasoundMultiFrameImageStorageUid = "1.2.840.10008.5.1.4.1.1.3.1"; /// <summary>SopClass for /// <para>Ultrasound Multi-frame Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.3.1</para> /// </summary> public static readonly SopClass UltrasoundMultiFrameImageStorage = new SopClass("Ultrasound Multi-frame Image Storage", UltrasoundMultiFrameImageStorageUid, false); /// <summary> /// <para>Ultrasound Multi-frame Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.3</para> /// </summary> public static readonly String UltrasoundMultiFrameImageStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.3"; /// <summary>SopClass for /// <para>Ultrasound Multi-frame Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.3</para> /// </summary> public static readonly SopClass UltrasoundMultiFrameImageStorageRetired = new SopClass("Ultrasound Multi-frame Image Storage (Retired)", UltrasoundMultiFrameImageStorageRetiredUid, false); /// <summary> /// <para>Unified Procedure Step – Event SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.4</para> /// </summary> public static readonly String UnifiedProcedureStepEventSopClassUid = "1.2.840.10008.5.1.4.34.4.4"; /// <summary>SopClass for /// <para>Unified Procedure Step – Event SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.4</para> /// </summary> public static readonly SopClass UnifiedProcedureStepEventSopClass = new SopClass("Unified Procedure Step – Event SOP Class", UnifiedProcedureStepEventSopClassUid, false); /// <summary> /// <para>Unified Procedure Step – Pull SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.3</para> /// </summary> public static readonly String UnifiedProcedureStepPullSopClassUid = "1.2.840.10008.5.1.4.34.4.3"; /// <summary>SopClass for /// <para>Unified Procedure Step – Pull SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.3</para> /// </summary> public static readonly SopClass UnifiedProcedureStepPullSopClass = new SopClass("Unified Procedure Step – Pull SOP Class", UnifiedProcedureStepPullSopClassUid, false); /// <summary> /// <para>Unified Procedure Step – Push SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.1</para> /// </summary> public static readonly String UnifiedProcedureStepPushSopClassUid = "1.2.840.10008.5.1.4.34.4.1"; /// <summary>SopClass for /// <para>Unified Procedure Step – Push SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.1</para> /// </summary> public static readonly SopClass UnifiedProcedureStepPushSopClass = new SopClass("Unified Procedure Step – Push SOP Class", UnifiedProcedureStepPushSopClassUid, false); /// <summary> /// <para>Unified Procedure Step – Watch SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.2</para> /// </summary> public static readonly String UnifiedProcedureStepWatchSopClassUid = "1.2.840.10008.5.1.4.34.4.2"; /// <summary>SopClass for /// <para>Unified Procedure Step – Watch SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.34.4.2</para> /// </summary> public static readonly SopClass UnifiedProcedureStepWatchSopClass = new SopClass("Unified Procedure Step – Watch SOP Class", UnifiedProcedureStepWatchSopClassUid, false); /// <summary> /// <para>Verification SOP Class</para> /// <para>UID: 1.2.840.10008.1.1</para> /// </summary> public static readonly String VerificationSopClassUid = "1.2.840.10008.1.1"; /// <summary>SopClass for /// <para>Verification SOP Class</para> /// <para>UID: 1.2.840.10008.1.1</para> /// </summary> public static readonly SopClass VerificationSopClass = new SopClass("Verification SOP Class", VerificationSopClassUid, false); /// <summary> /// <para>Video Endoscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.1.1</para> /// </summary> public static readonly String VideoEndoscopicImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.1.1"; /// <summary>SopClass for /// <para>Video Endoscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.1.1</para> /// </summary> public static readonly SopClass VideoEndoscopicImageStorage = new SopClass("Video Endoscopic Image Storage", VideoEndoscopicImageStorageUid, false); /// <summary> /// <para>Video Microscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.2.1</para> /// </summary> public static readonly String VideoMicroscopicImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.2.1"; /// <summary>SopClass for /// <para>Video Microscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.2.1</para> /// </summary> public static readonly SopClass VideoMicroscopicImageStorage = new SopClass("Video Microscopic Image Storage", VideoMicroscopicImageStorageUid, false); /// <summary> /// <para>Video Photographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.4.1</para> /// </summary> public static readonly String VideoPhotographicImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.4.1"; /// <summary>SopClass for /// <para>Video Photographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.4.1</para> /// </summary> public static readonly SopClass VideoPhotographicImageStorage = new SopClass("Video Photographic Image Storage", VideoPhotographicImageStorageUid, false); /// <summary> /// <para>VL Endoscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.1</para> /// </summary> public static readonly String VlEndoscopicImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.1"; /// <summary>SopClass for /// <para>VL Endoscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.1</para> /// </summary> public static readonly SopClass VlEndoscopicImageStorage = new SopClass("VL Endoscopic Image Storage", VlEndoscopicImageStorageUid, false); /// <summary> /// <para>VL Microscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.2</para> /// </summary> public static readonly String VlMicroscopicImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.2"; /// <summary>SopClass for /// <para>VL Microscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.2</para> /// </summary> public static readonly SopClass VlMicroscopicImageStorage = new SopClass("VL Microscopic Image Storage", VlMicroscopicImageStorageUid, false); /// <summary> /// <para>VL Photographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.4</para> /// </summary> public static readonly String VlPhotographicImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.4"; /// <summary>SopClass for /// <para>VL Photographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.4</para> /// </summary> public static readonly SopClass VlPhotographicImageStorage = new SopClass("VL Photographic Image Storage", VlPhotographicImageStorageUid, false); /// <summary> /// <para>VL Slide-Coordinates Microscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.3</para> /// </summary> public static readonly String VlSlideCoordinatesMicroscopicImageStorageUid = "1.2.840.10008.5.1.4.1.1.77.1.3"; /// <summary>SopClass for /// <para>VL Slide-Coordinates Microscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.77.1.3</para> /// </summary> public static readonly SopClass VlSlideCoordinatesMicroscopicImageStorage = new SopClass("VL Slide-Coordinates Microscopic Image Storage", VlSlideCoordinatesMicroscopicImageStorageUid, false); /// <summary> /// <para>VOI LUT Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.22</para> /// </summary> public static readonly String VoiLutBoxSopClassUid = "1.2.840.10008.5.1.1.22"; /// <summary>SopClass for /// <para>VOI LUT Box SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.22</para> /// </summary> public static readonly SopClass VoiLutBoxSopClass = new SopClass("VOI LUT Box SOP Class", VoiLutBoxSopClassUid, false); /// <summary> /// <para>Waveform Storage - Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1</para> /// </summary> public static readonly String WaveformStorageTrialRetiredUid = "1.2.840.10008.5.1.4.1.1.9.1"; /// <summary>SopClass for /// <para>Waveform Storage - Trial (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.9.1</para> /// </summary> public static readonly SopClass WaveformStorageTrialRetired = new SopClass("Waveform Storage - Trial (Retired)", WaveformStorageTrialRetiredUid, false); /// <summary> /// <para>X-Ray 3D Angiographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.13.1.1</para> /// </summary> public static readonly String XRay3dAngiographicImageStorageUid = "1.2.840.10008.5.1.4.1.1.13.1.1"; /// <summary>SopClass for /// <para>X-Ray 3D Angiographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.13.1.1</para> /// </summary> public static readonly SopClass XRay3dAngiographicImageStorage = new SopClass("X-Ray 3D Angiographic Image Storage", XRay3dAngiographicImageStorageUid, false); /// <summary> /// <para>X-Ray 3D Craniofacial Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.13.1.2</para> /// </summary> public static readonly String XRay3dCraniofacialImageStorageUid = "1.2.840.10008.5.1.4.1.1.13.1.2"; /// <summary>SopClass for /// <para>X-Ray 3D Craniofacial Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.13.1.2</para> /// </summary> public static readonly SopClass XRay3dCraniofacialImageStorage = new SopClass("X-Ray 3D Craniofacial Image Storage", XRay3dCraniofacialImageStorageUid, false); /// <summary> /// <para>X-Ray Angiographic Bi-Plane Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.3</para> /// </summary> public static readonly String XRayAngiographicBiPlaneImageStorageRetiredUid = "1.2.840.10008.5.1.4.1.1.12.3"; /// <summary>SopClass for /// <para>X-Ray Angiographic Bi-Plane Image Storage (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.3</para> /// </summary> public static readonly SopClass XRayAngiographicBiPlaneImageStorageRetired = new SopClass("X-Ray Angiographic Bi-Plane Image Storage (Retired)", XRayAngiographicBiPlaneImageStorageRetiredUid, false); /// <summary> /// <para>X-Ray Angiographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.1</para> /// </summary> public static readonly String XRayAngiographicImageStorageUid = "1.2.840.10008.5.1.4.1.1.12.1"; /// <summary>SopClass for /// <para>X-Ray Angiographic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.1</para> /// </summary> public static readonly SopClass XRayAngiographicImageStorage = new SopClass("X-Ray Angiographic Image Storage", XRayAngiographicImageStorageUid, false); /// <summary> /// <para>X-Ray Radiation Dose SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.67</para> /// </summary> public static readonly String XRayRadiationDoseSrStorageUid = "1.2.840.10008.5.1.4.1.1.88.67"; /// <summary>SopClass for /// <para>X-Ray Radiation Dose SR Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.88.67</para> /// </summary> public static readonly SopClass XRayRadiationDoseSrStorage = new SopClass("X-Ray Radiation Dose SR Storage", XRayRadiationDoseSrStorageUid, false); /// <summary> /// <para>X-Ray Radiofluoroscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.2</para> /// </summary> public static readonly String XRayRadiofluoroscopicImageStorageUid = "1.2.840.10008.5.1.4.1.1.12.2"; /// <summary>SopClass for /// <para>X-Ray Radiofluoroscopic Image Storage</para> /// <para>UID: 1.2.840.10008.5.1.4.1.1.12.2</para> /// </summary> public static readonly SopClass XRayRadiofluoroscopicImageStorage = new SopClass("X-Ray Radiofluoroscopic Image Storage", XRayRadiofluoroscopicImageStorageUid, false); /// <summary>String UID for /// <para>Basic Color Print Management Meta SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.18</para> /// </summary> public static readonly String BasicColorPrintManagementMetaSopClassUid = "1.2.840.10008.5.1.1.18"; /// <summary>SopClass for /// <para>Basic Color Print Management Meta SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.18</para> /// </summary> public static readonly SopClass BasicColorPrintManagementMetaSopClass = new SopClass("Basic Color Print Management Meta SOP Class", BasicColorPrintManagementMetaSopClassUid, true); /// <summary>String UID for /// <para>Basic Grayscale Print Management Meta SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.9</para> /// </summary> public static readonly String BasicGrayscalePrintManagementMetaSopClassUid = "1.2.840.10008.5.1.1.9"; /// <summary>SopClass for /// <para>Basic Grayscale Print Management Meta SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.1.9</para> /// </summary> public static readonly SopClass BasicGrayscalePrintManagementMetaSopClass = new SopClass("Basic Grayscale Print Management Meta SOP Class", BasicGrayscalePrintManagementMetaSopClassUid, true); /// <summary>String UID for /// <para>Detached Patient Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.1.4</para> /// </summary> public static readonly String DetachedPatientManagementMetaSopClassRetiredUid = "1.2.840.10008.3.1.2.1.4"; /// <summary>SopClass for /// <para>Detached Patient Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.1.4</para> /// </summary> public static readonly SopClass DetachedPatientManagementMetaSopClassRetired = new SopClass("Detached Patient Management Meta SOP Class (Retired)", DetachedPatientManagementMetaSopClassRetiredUid, true); /// <summary>String UID for /// <para>Detached Results Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.5.4</para> /// </summary> public static readonly String DetachedResultsManagementMetaSopClassRetiredUid = "1.2.840.10008.3.1.2.5.4"; /// <summary>SopClass for /// <para>Detached Results Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.5.4</para> /// </summary> public static readonly SopClass DetachedResultsManagementMetaSopClassRetired = new SopClass("Detached Results Management Meta SOP Class (Retired)", DetachedResultsManagementMetaSopClassRetiredUid, true); /// <summary>String UID for /// <para>Detached Study Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.5.5</para> /// </summary> public static readonly String DetachedStudyManagementMetaSopClassRetiredUid = "1.2.840.10008.3.1.2.5.5"; /// <summary>SopClass for /// <para>Detached Study Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.3.1.2.5.5</para> /// </summary> public static readonly SopClass DetachedStudyManagementMetaSopClassRetired = new SopClass("Detached Study Management Meta SOP Class (Retired)", DetachedStudyManagementMetaSopClassRetiredUid, true); /// <summary>String UID for /// <para>General Purpose Worklist Management Meta SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.32</para> /// </summary> public static readonly String GeneralPurposeWorklistManagementMetaSopClassUid = "1.2.840.10008.5.1.4.32"; /// <summary>SopClass for /// <para>General Purpose Worklist Management Meta SOP Class</para> /// <para>UID: 1.2.840.10008.5.1.4.32</para> /// </summary> public static readonly SopClass GeneralPurposeWorklistManagementMetaSopClass = new SopClass("General Purpose Worklist Management Meta SOP Class", GeneralPurposeWorklistManagementMetaSopClassUid, true); /// <summary>String UID for /// <para>Pull Stored Print Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.32</para> /// </summary> public static readonly String PullStoredPrintManagementMetaSopClassRetiredUid = "1.2.840.10008.5.1.1.32"; /// <summary>SopClass for /// <para>Pull Stored Print Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.32</para> /// </summary> public static readonly SopClass PullStoredPrintManagementMetaSopClassRetired = new SopClass("Pull Stored Print Management Meta SOP Class (Retired)", PullStoredPrintManagementMetaSopClassRetiredUid, true); /// <summary>String UID for /// <para>Referenced Color Print Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.18.1</para> /// </summary> public static readonly String ReferencedColorPrintManagementMetaSopClassRetiredUid = "1.2.840.10008.5.1.1.18.1"; /// <summary>SopClass for /// <para>Referenced Color Print Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.18.1</para> /// </summary> public static readonly SopClass ReferencedColorPrintManagementMetaSopClassRetired = new SopClass("Referenced Color Print Management Meta SOP Class (Retired)", ReferencedColorPrintManagementMetaSopClassRetiredUid, true); /// <summary>String UID for /// <para>Referenced Grayscale Print Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.9.1</para> /// </summary> public static readonly String ReferencedGrayscalePrintManagementMetaSopClassRetiredUid = "1.2.840.10008.5.1.1.9.1"; /// <summary>SopClass for /// <para>Referenced Grayscale Print Management Meta SOP Class (Retired)</para> /// <para>UID: 1.2.840.10008.5.1.1.9.1</para> /// </summary> public static readonly SopClass ReferencedGrayscalePrintManagementMetaSopClassRetired = new SopClass("Referenced Grayscale Print Management Meta SOP Class (Retired)", ReferencedGrayscalePrintManagementMetaSopClassRetiredUid, true); private readonly String _sopName; private readonly String _sopUid; private readonly bool _bIsMeta; /// <summary> Property that represents the Name of the SOP Class. </summary> public String Name { get { return _sopName; } } /// <summary> Property that represents the Uid for the SOP Class. </summary> public String Uid { get { return _sopUid; } } /// <summary> Property that returns a DicomUid that represents the SOP Class. </summary> public DicomUid DicomUid { get { return new DicomUid(_sopUid,_sopName,_bIsMeta ? UidType.MetaSOPClass : UidType.SOPClass); } } /// <summary> Property that represents the Uid for the SOP Class. </summary> public bool Meta { get { return _bIsMeta; } } /// <summary> Constructor to create SopClass object. </summary> public SopClass(String name, String uid, bool isMeta) { _sopName = name; _sopUid = uid; _bIsMeta = isMeta; } private static Dictionary<String,SopClass> _sopList = new Dictionary<String,SopClass>(); /// <summary>Override that displays the name of the SOP Class.</summary> public override string ToString() { return this.Name; } /// <summary>Retrieve a SopClass object associated with the Uid.</summary> public static SopClass GetSopClass(String uid) { SopClass theSop; if (!_sopList.TryGetValue(uid, out theSop)) return null; return theSop; } static SopClass() { _sopList.Add(Sop12LeadEcgWaveformStorageUid, Sop12LeadEcgWaveformStorage); _sopList.Add(AmbulatoryEcgWaveformStorageUid, AmbulatoryEcgWaveformStorage); _sopList.Add(AudioSrStorageTrialRetiredUid, AudioSrStorageTrialRetired); _sopList.Add(BasicAnnotationBoxSopClassUid, BasicAnnotationBoxSopClass); _sopList.Add(BasicColorImageBoxSopClassUid, BasicColorImageBoxSopClass); _sopList.Add(BasicFilmBoxSopClassUid, BasicFilmBoxSopClass); _sopList.Add(BasicFilmSessionSopClassUid, BasicFilmSessionSopClass); _sopList.Add(BasicGrayscaleImageBoxSopClassUid, BasicGrayscaleImageBoxSopClass); _sopList.Add(BasicPrintImageOverlayBoxSopClassRetiredUid, BasicPrintImageOverlayBoxSopClassRetired); _sopList.Add(BasicStudyContentNotificationSopClassRetiredUid, BasicStudyContentNotificationSopClassRetired); _sopList.Add(BasicTextSrStorageUid, BasicTextSrStorage); _sopList.Add(BasicVoiceAudioWaveformStorageUid, BasicVoiceAudioWaveformStorage); _sopList.Add(BlendingSoftcopyPresentationStateStorageSopClassUid, BlendingSoftcopyPresentationStateStorageSopClass); _sopList.Add(BreastImagingRelevantPatientInformationQueryUid, BreastImagingRelevantPatientInformationQuery); _sopList.Add(CardiacElectrophysiologyWaveformStorageUid, CardiacElectrophysiologyWaveformStorage); _sopList.Add(CardiacRelevantPatientInformationQueryUid, CardiacRelevantPatientInformationQuery); _sopList.Add(ChestCadSrStorageUid, ChestCadSrStorage); _sopList.Add(ColorSoftcopyPresentationStateStorageSopClassUid, ColorSoftcopyPresentationStateStorageSopClass); _sopList.Add(ComprehensiveSrStorageUid, ComprehensiveSrStorage); _sopList.Add(ComprehensiveSrStorageTrialRetiredUid, ComprehensiveSrStorageTrialRetired); _sopList.Add(ComputedRadiographyImageStorageUid, ComputedRadiographyImageStorage); _sopList.Add(CtImageStorageUid, CtImageStorage); _sopList.Add(DeformableSpatialRegistrationStorageUid, DeformableSpatialRegistrationStorage); _sopList.Add(DetachedInterpretationManagementSopClassRetiredUid, DetachedInterpretationManagementSopClassRetired); _sopList.Add(DetachedPatientManagementSopClassRetiredUid, DetachedPatientManagementSopClassRetired); _sopList.Add(DetachedResultsManagementSopClassRetiredUid, DetachedResultsManagementSopClassRetired); _sopList.Add(DetachedStudyManagementSopClassRetiredUid, DetachedStudyManagementSopClassRetired); _sopList.Add(DetachedVisitManagementSopClassRetiredUid, DetachedVisitManagementSopClassRetired); _sopList.Add(DetailSrStorageTrialRetiredUid, DetailSrStorageTrialRetired); _sopList.Add(DigitalIntraOralXRayImageStorageForPresentationUid, DigitalIntraOralXRayImageStorageForPresentation); _sopList.Add(DigitalIntraOralXRayImageStorageForProcessingUid, DigitalIntraOralXRayImageStorageForProcessing); _sopList.Add(DigitalMammographyXRayImageStorageForPresentationUid, DigitalMammographyXRayImageStorageForPresentation); _sopList.Add(DigitalMammographyXRayImageStorageForProcessingUid, DigitalMammographyXRayImageStorageForProcessing); _sopList.Add(DigitalXRayImageStorageForPresentationUid, DigitalXRayImageStorageForPresentation); _sopList.Add(DigitalXRayImageStorageForProcessingUid, DigitalXRayImageStorageForProcessing); _sopList.Add(EncapsulatedCdaStorageUid, EncapsulatedCdaStorage); _sopList.Add(EncapsulatedPdfStorageUid, EncapsulatedPdfStorage); _sopList.Add(EnhancedCtImageStorageUid, EnhancedCtImageStorage); _sopList.Add(EnhancedMrImageStorageUid, EnhancedMrImageStorage); _sopList.Add(EnhancedSrStorageUid, EnhancedSrStorage); _sopList.Add(EnhancedXaImageStorageUid, EnhancedXaImageStorage); _sopList.Add(EnhancedXrfImageStorageUid, EnhancedXrfImageStorage); _sopList.Add(GeneralEcgWaveformStorageUid, GeneralEcgWaveformStorage); _sopList.Add(GeneralPurposePerformedProcedureStepSopClassUid, GeneralPurposePerformedProcedureStepSopClass); _sopList.Add(GeneralPurposeScheduledProcedureStepSopClassUid, GeneralPurposeScheduledProcedureStepSopClass); _sopList.Add(GeneralPurposeWorklistInformationModelFindUid, GeneralPurposeWorklistInformationModelFind); _sopList.Add(GeneralRelevantPatientInformationQueryUid, GeneralRelevantPatientInformationQuery); _sopList.Add(GrayscaleSoftcopyPresentationStateStorageSopClassUid, GrayscaleSoftcopyPresentationStateStorageSopClass); _sopList.Add(HangingProtocolInformationModelFindUid, HangingProtocolInformationModelFind); _sopList.Add(HangingProtocolInformationModelMoveUid, HangingProtocolInformationModelMove); _sopList.Add(HangingProtocolStorageUid, HangingProtocolStorage); _sopList.Add(HardcopyGrayscaleImageStorageSopClassRetiredUid, HardcopyGrayscaleImageStorageSopClassRetired); _sopList.Add(HardcopyColorImageStorageSopClassRetiredUid, HardcopyColorImageStorageSopClassRetired); _sopList.Add(HemodynamicWaveformStorageUid, HemodynamicWaveformStorage); _sopList.Add(ImageOverlayBoxSopClassRetiredUid, ImageOverlayBoxSopClassRetired); _sopList.Add(InstanceAvailabilityNotificationSopClassUid, InstanceAvailabilityNotificationSopClass); _sopList.Add(KeyObjectSelectionDocumentStorageUid, KeyObjectSelectionDocumentStorage); _sopList.Add(MammographyCadSrStorageUid, MammographyCadSrStorage); _sopList.Add(MediaCreationManagementSopClassUidUid, MediaCreationManagementSopClassUid); _sopList.Add(MediaStorageDirectoryStorageUid, MediaStorageDirectoryStorage); _sopList.Add(ModalityPerformedProcedureStepNotificationSopClassUid, ModalityPerformedProcedureStepNotificationSopClass); _sopList.Add(ModalityPerformedProcedureStepRetrieveSopClassUid, ModalityPerformedProcedureStepRetrieveSopClass); _sopList.Add(ModalityPerformedProcedureStepSopClassUid, ModalityPerformedProcedureStepSopClass); _sopList.Add(ModalityWorklistInformationModelFindUid, ModalityWorklistInformationModelFind); _sopList.Add(MrImageStorageUid, MrImageStorage); _sopList.Add(MrSpectroscopyStorageUid, MrSpectroscopyStorage); _sopList.Add(MultiFrameGrayscaleByteSecondaryCaptureImageStorageUid, MultiFrameGrayscaleByteSecondaryCaptureImageStorage); _sopList.Add(MultiFrameGrayscaleWordSecondaryCaptureImageStorageUid, MultiFrameGrayscaleWordSecondaryCaptureImageStorage); _sopList.Add(MultiFrameSingleBitSecondaryCaptureImageStorageUid, MultiFrameSingleBitSecondaryCaptureImageStorage); _sopList.Add(MultiFrameTrueColorSecondaryCaptureImageStorageUid, MultiFrameTrueColorSecondaryCaptureImageStorage); _sopList.Add(NuclearMedicineImageStorageRetiredUid, NuclearMedicineImageStorageRetired); _sopList.Add(NuclearMedicineImageStorageUid, NuclearMedicineImageStorage); _sopList.Add(OphthalmicPhotography16BitImageStorageUid, OphthalmicPhotography16BitImageStorage); _sopList.Add(OphthalmicPhotography8BitImageStorageUid, OphthalmicPhotography8BitImageStorage); _sopList.Add(OphthalmicTomographyImageStorageUid, OphthalmicTomographyImageStorage); _sopList.Add(PatientRootQueryRetrieveInformationModelFindUid, PatientRootQueryRetrieveInformationModelFind); _sopList.Add(PatientRootQueryRetrieveInformationModelGetUid, PatientRootQueryRetrieveInformationModelGet); _sopList.Add(PatientRootQueryRetrieveInformationModelMoveUid, PatientRootQueryRetrieveInformationModelMove); _sopList.Add(PatientStudyOnlyQueryRetrieveInformationModelFindRetiredUid, PatientStudyOnlyQueryRetrieveInformationModelFindRetired); _sopList.Add(PatientStudyOnlyQueryRetrieveInformationModelGetRetiredUid, PatientStudyOnlyQueryRetrieveInformationModelGetRetired); _sopList.Add(PatientStudyOnlyQueryRetrieveInformationModelMoveRetiredUid, PatientStudyOnlyQueryRetrieveInformationModelMoveRetired); _sopList.Add(PositronEmissionTomographyImageStorageUid, PositronEmissionTomographyImageStorage); _sopList.Add(PresentationLutSopClassUid, PresentationLutSopClass); _sopList.Add(PrintJobSopClassUid, PrintJobSopClass); _sopList.Add(PrintQueueManagementSopClassRetiredUid, PrintQueueManagementSopClassRetired); _sopList.Add(PrinterConfigurationRetrievalSopClassUid, PrinterConfigurationRetrievalSopClass); _sopList.Add(PrinterSopClassUid, PrinterSopClass); _sopList.Add(ProceduralEventLoggingSopClassUid, ProceduralEventLoggingSopClass); _sopList.Add(ProcedureLogStorageUid, ProcedureLogStorage); _sopList.Add(ProductCharacteristicsQuerySopClassUid, ProductCharacteristicsQuerySopClass); _sopList.Add(PseudoColorSoftcopyPresentationStateStorageSopClassUid, PseudoColorSoftcopyPresentationStateStorageSopClass); _sopList.Add(PullPrintRequestSopClassRetiredUid, PullPrintRequestSopClassRetired); _sopList.Add(RawDataStorageUid, RawDataStorage); _sopList.Add(RealWorldValueMappingStorageUid, RealWorldValueMappingStorage); _sopList.Add(ReferencedImageBoxSopClassRetiredUid, ReferencedImageBoxSopClassRetired); _sopList.Add(RtBeamsDeliveryInstructionStorageSupplement74FrozenDraftUid, RtBeamsDeliveryInstructionStorageSupplement74FrozenDraft); _sopList.Add(RtBeamsTreatmentRecordStorageUid, RtBeamsTreatmentRecordStorage); _sopList.Add(RtBrachyTreatmentRecordStorageUid, RtBrachyTreatmentRecordStorage); _sopList.Add(RtConventionalMachineVerificationSupplement74FrozenDraftUid, RtConventionalMachineVerificationSupplement74FrozenDraft); _sopList.Add(RtDoseStorageUid, RtDoseStorage); _sopList.Add(RtImageStorageUid, RtImageStorage); _sopList.Add(RtIonBeamsTreatmentRecordStorageUid, RtIonBeamsTreatmentRecordStorage); _sopList.Add(RtIonMachineVerificationSupplement74FrozenDraftUid, RtIonMachineVerificationSupplement74FrozenDraft); _sopList.Add(RtIonPlanStorageUid, RtIonPlanStorage); _sopList.Add(RtPlanStorageUid, RtPlanStorage); _sopList.Add(RtStructureSetStorageUid, RtStructureSetStorage); _sopList.Add(RtTreatmentSummaryRecordStorageUid, RtTreatmentSummaryRecordStorage); _sopList.Add(SecondaryCaptureImageStorageUid, SecondaryCaptureImageStorage); _sopList.Add(SegmentationStorageUid, SegmentationStorage); _sopList.Add(SpatialFiducialsStorageUid, SpatialFiducialsStorage); _sopList.Add(SpatialRegistrationStorageUid, SpatialRegistrationStorage); _sopList.Add(StandaloneCurveStorageRetiredUid, StandaloneCurveStorageRetired); _sopList.Add(StandaloneModalityLutStorageRetiredUid, StandaloneModalityLutStorageRetired); _sopList.Add(StandaloneOverlayStorageRetiredUid, StandaloneOverlayStorageRetired); _sopList.Add(StandalonePetCurveStorageRetiredUid, StandalonePetCurveStorageRetired); _sopList.Add(StandaloneVoiLutStorageRetiredUid, StandaloneVoiLutStorageRetired); _sopList.Add(StereometricRelationshipStorageUid, StereometricRelationshipStorage); _sopList.Add(StorageCommitmentPullModelSopClassRetiredUid, StorageCommitmentPullModelSopClassRetired); _sopList.Add(StorageCommitmentPushModelSopClassUid, StorageCommitmentPushModelSopClass); _sopList.Add(StoredPrintStorageSopClassRetiredUid, StoredPrintStorageSopClassRetired); _sopList.Add(StudyComponentManagementSopClassRetiredUid, StudyComponentManagementSopClassRetired); _sopList.Add(StudyRootQueryRetrieveInformationModelFindUid, StudyRootQueryRetrieveInformationModelFind); _sopList.Add(StudyRootQueryRetrieveInformationModelGetUid, StudyRootQueryRetrieveInformationModelGet); _sopList.Add(StudyRootQueryRetrieveInformationModelMoveUid, StudyRootQueryRetrieveInformationModelMove); _sopList.Add(SubstanceAdministrationLoggingSopClassUid, SubstanceAdministrationLoggingSopClass); _sopList.Add(SubstanceApprovalQuerySopClassUid, SubstanceApprovalQuerySopClass); _sopList.Add(TextSrStorageTrialRetiredUid, TextSrStorageTrialRetired); _sopList.Add(UltrasoundImageStorageUid, UltrasoundImageStorage); _sopList.Add(UltrasoundImageStorageRetiredUid, UltrasoundImageStorageRetired); _sopList.Add(UltrasoundMultiFrameImageStorageUid, UltrasoundMultiFrameImageStorage); _sopList.Add(UltrasoundMultiFrameImageStorageRetiredUid, UltrasoundMultiFrameImageStorageRetired); _sopList.Add(UnifiedProcedureStepEventSopClassUid, UnifiedProcedureStepEventSopClass); _sopList.Add(UnifiedProcedureStepPullSopClassUid, UnifiedProcedureStepPullSopClass); _sopList.Add(UnifiedProcedureStepPushSopClassUid, UnifiedProcedureStepPushSopClass); _sopList.Add(UnifiedProcedureStepWatchSopClassUid, UnifiedProcedureStepWatchSopClass); _sopList.Add(VerificationSopClassUid, VerificationSopClass); _sopList.Add(VideoEndoscopicImageStorageUid, VideoEndoscopicImageStorage); _sopList.Add(VideoMicroscopicImageStorageUid, VideoMicroscopicImageStorage); _sopList.Add(VideoPhotographicImageStorageUid, VideoPhotographicImageStorage); _sopList.Add(VlEndoscopicImageStorageUid, VlEndoscopicImageStorage); _sopList.Add(VlMicroscopicImageStorageUid, VlMicroscopicImageStorage); _sopList.Add(VlPhotographicImageStorageUid, VlPhotographicImageStorage); _sopList.Add(VlSlideCoordinatesMicroscopicImageStorageUid, VlSlideCoordinatesMicroscopicImageStorage); _sopList.Add(VoiLutBoxSopClassUid, VoiLutBoxSopClass); _sopList.Add(WaveformStorageTrialRetiredUid, WaveformStorageTrialRetired); _sopList.Add(XRay3dAngiographicImageStorageUid, XRay3dAngiographicImageStorage); _sopList.Add(XRay3dCraniofacialImageStorageUid, XRay3dCraniofacialImageStorage); _sopList.Add(XRayAngiographicBiPlaneImageStorageRetiredUid, XRayAngiographicBiPlaneImageStorageRetired); _sopList.Add(XRayAngiographicImageStorageUid, XRayAngiographicImageStorage); _sopList.Add(XRayRadiationDoseSrStorageUid, XRayRadiationDoseSrStorage); _sopList.Add(XRayRadiofluoroscopicImageStorageUid, XRayRadiofluoroscopicImageStorage); _sopList.Add(BasicColorPrintManagementMetaSopClassUid, BasicColorPrintManagementMetaSopClass); _sopList.Add(BasicGrayscalePrintManagementMetaSopClassUid, BasicGrayscalePrintManagementMetaSopClass); _sopList.Add(DetachedPatientManagementMetaSopClassRetiredUid, DetachedPatientManagementMetaSopClassRetired); _sopList.Add(DetachedResultsManagementMetaSopClassRetiredUid, DetachedResultsManagementMetaSopClassRetired); _sopList.Add(DetachedStudyManagementMetaSopClassRetiredUid, DetachedStudyManagementMetaSopClassRetired); _sopList.Add(GeneralPurposeWorklistManagementMetaSopClassUid, GeneralPurposeWorklistManagementMetaSopClass); _sopList.Add(PullStoredPrintManagementMetaSopClassRetiredUid, PullStoredPrintManagementMetaSopClassRetired); _sopList.Add(ReferencedColorPrintManagementMetaSopClassRetiredUid, ReferencedColorPrintManagementMetaSopClassRetired); _sopList.Add(ReferencedGrayscalePrintManagementMetaSopClassRetiredUid, ReferencedGrayscalePrintManagementMetaSopClassRetired); } } }
49.431887
131
0.54588
[ "Apache-2.0" ]
econmed/ImageServer20
Dicom/SopClass.cs
147,105
C#
namespace Meraki.Api.Sections.General.Networks; public partial class NetworksClientsSection { [RefitPromoteCalls] internal INetworksClients Clients { get; set; } = null!; public INetworksClientsApplicationUsage ApplicationUsage { get; internal set; } = null!; public INetworksClientsPolicy Policy { get; internal set; } = null!; public INetworksClientsSplashAuthorizationStatus SplashAuthorizationStatus { get; internal set; } = null!; public INetworksClientsTrafficHistory TrafficHistory { get; internal set; } = null!; public INetworksClientsUsageHistories UsageHistories { get; internal set; } = null!; public INetworksClientsUsageHistory UsageHistory { get; internal set; } = null!; }
49.928571
107
0.79113
[ "MIT" ]
Pituzek/Meraki.Api
Meraki.Api/Sections/General/Networks/NetworksClientsSection.cs
701
C#
using Chinook.Domain.Entities; using System; using System.Collections.Generic; namespace Chinook.Domain.Repositories { public interface ICustomerRepository : IDisposable { List<Customer> GetAll(); Customer GetById(int id); List<Customer> GetBySupportRepId(int id); Customer Add(Customer newCustomer); bool Update(Customer customer); bool Delete(int id); } }
26.1875
54
0.687351
[ "MIT" ]
SeanKilleen/ChinookASPNETWebAPI
ChinookASPNETWebAPI/Chinook.Domain/Repositories/ICustomerRepository.cs
421
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.Internal.VisualStudio.Shell; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.NavigationBar { internal class NavigationBarClient : IVsDropdownBarClient, IVsDropdownBarClient3, IVsDropdownBarClient4, IVsDropdownBarClientEx, IVsCoTaskMemFreeMyStrings, INavigationBarPresenter, IVsCodeWindowEvents { private readonly IVsDropdownBarManager _manager; private readonly IVsCodeWindow _codeWindow; private readonly VisualStudioWorkspaceImpl _workspace; private readonly ComEventSink _codeWindowEventsSink; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IVsImageService2 _imageService; private readonly Dictionary<IVsTextView, ITextView> _trackedTextViews = new(); private IVsDropdownBar _dropdownBar; private IList<NavigationBarProjectItem> _projectItems; private IList<NavigationBarItem> _currentTypeItems; public NavigationBarClient( IVsDropdownBarManager manager, IVsCodeWindow codeWindow, IServiceProvider serviceProvider, VisualStudioWorkspaceImpl workspace) { _manager = manager; _codeWindow = codeWindow; _workspace = workspace; _imageService = (IVsImageService2)serviceProvider.GetService(typeof(SVsImageService)); _projectItems = SpecializedCollections.EmptyList<NavigationBarProjectItem>(); _currentTypeItems = SpecializedCollections.EmptyList<NavigationBarItem>(); _codeWindowEventsSink = ComEventSink.Advise<IVsCodeWindowEvents>(codeWindow, this); _editorAdaptersFactoryService = serviceProvider.GetMefService<IVsEditorAdaptersFactoryService>(); codeWindow.GetPrimaryView(out var pTextView); StartTrackingView(pTextView); codeWindow.GetSecondaryView(out pTextView); StartTrackingView(pTextView); } private void StartTrackingView(IVsTextView pTextView) { if (pTextView != null) { var wpfTextView = _editorAdaptersFactoryService.GetWpfTextView(pTextView); if (wpfTextView != null) { _trackedTextViews.Add(pTextView, wpfTextView); wpfTextView.Caret.PositionChanged += OnCaretPositionChanged; wpfTextView.GotAggregateFocus += OnViewGotAggregateFocus; } } } private NavigationBarItem GetCurrentTypeItem() { _dropdownBar.GetCurrentSelection(1, out var currentTypeIndex); return currentTypeIndex >= 0 ? _currentTypeItems[currentTypeIndex] : null; } private NavigationBarItem GetItem(int combo, int index) { switch (combo) { case 0: return _projectItems[index]; case 1: return _currentTypeItems[index]; case 2: return GetCurrentTypeItem().ChildItems[index]; default: throw new ArgumentException(); } } int IVsDropdownBarClient.GetComboAttributes(int iCombo, out uint pcEntries, out uint puEntryType, out IntPtr phImageList) { puEntryType = (uint)(DROPDOWNENTRYTYPE.ENTRY_TEXT | DROPDOWNENTRYTYPE.ENTRY_ATTR | DROPDOWNENTRYTYPE.ENTRY_IMAGE); // We no longer need to return an HIMAGELIST, we now use IVsDropdownBarClient4.GetEntryImage which uses monikers directly. phImageList = IntPtr.Zero; switch (iCombo) { case 0: pcEntries = (uint)_projectItems.Count; break; case 1: pcEntries = (uint)_currentTypeItems.Count; break; case 2: var currentTypeItem = GetCurrentTypeItem(); pcEntries = currentTypeItem != null ? (uint)currentTypeItem.ChildItems.Length : 0; break; default: pcEntries = 0; return VSConstants.E_INVALIDARG; } return VSConstants.S_OK; } int IVsDropdownBarClient.GetComboTipText(int iCombo, out string pbstrText) { var selectedItemPreviewText = string.Empty; if (_dropdownBar.GetCurrentSelection(iCombo, out var selectionIndex) == VSConstants.S_OK && selectionIndex >= 0) { selectedItemPreviewText = GetItem(iCombo, selectionIndex).Text; } switch (iCombo) { case 0: var keybindingString = KeyBindingHelper.GetGlobalKeyBinding(VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.MoveToDropdownBar); if (!string.IsNullOrWhiteSpace(keybindingString)) { pbstrText = string.Format(ServicesVSResources.Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to, selectedItemPreviewText, keybindingString); } else { pbstrText = string.Format(ServicesVSResources.Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to, selectedItemPreviewText); } return VSConstants.S_OK; case 1: case 2: pbstrText = string.Format(ServicesVSResources._0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file, selectedItemPreviewText); return VSConstants.S_OK; default: pbstrText = null; return VSConstants.E_INVALIDARG; } } int IVsDropdownBarClient.GetEntryAttributes(int iCombo, int iIndex, out uint pAttr) { var attributes = DROPDOWNFONTATTR.FONTATTR_PLAIN; var item = GetItem(iCombo, iIndex); if (item.Grayed) { attributes |= DROPDOWNFONTATTR.FONTATTR_GRAY; } if (item.Bolded) { attributes |= DROPDOWNFONTATTR.FONTATTR_BOLD; } pAttr = (uint)attributes; return VSConstants.S_OK; } int IVsDropdownBarClient.GetEntryImage(int iCombo, int iIndex, out int piImageIndex) { // This class implements IVsDropdownBarClient4 and expects IVsDropdownBarClient4.GetEntryImage() to be called instead piImageIndex = -1; return VSConstants.E_UNEXPECTED; } int IVsDropdownBarClient.GetEntryText(int iCombo, int iIndex, out string ppszText) { ppszText = GetItem(iCombo, iIndex).Text; return VSConstants.S_OK; } int IVsDropdownBarClient.OnComboGetFocus(int iCombo) { DropDownFocused?.Invoke(this, EventArgs.Empty); return VSConstants.S_OK; } int IVsDropdownBarClient.OnItemChosen(int iCombo, int iIndex) { int selection; // If we chose an item for the type drop-down, then refresh the member dropdown if (iCombo == (int)NavigationBarDropdownKind.Type) { _dropdownBar.GetCurrentSelection((int)NavigationBarDropdownKind.Member, out selection); _dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Member, selection); } _dropdownBar.GetCurrentSelection(iCombo, out selection); if (selection >= 0) { var item = GetItem(iCombo, selection); ItemSelected?.Invoke(this, new NavigationBarItemSelectedEventArgs(item)); } return VSConstants.S_OK; } int IVsDropdownBarClient.OnItemSelected(int iCombo, int iIndex) => VSConstants.S_OK; int IVsDropdownBarClient.SetDropdownBar(IVsDropdownBar pDropdownBar) { _dropdownBar = pDropdownBar; return VSConstants.S_OK; } int IVsDropdownBarClient3.GetComboWidth(int iCombo, out int piWidthPercent) { piWidthPercent = 100; return VSConstants.S_OK; } int IVsDropdownBarClient3.GetAutomationProperties(int iCombo, out string pbstrName, out string pbstrId) { switch (iCombo) { case 0: pbstrName = NavigationBarAutomationStrings.ProjectDropdownName; pbstrId = NavigationBarAutomationStrings.ProjectDropdownId; return VSConstants.S_OK; case 1: pbstrName = NavigationBarAutomationStrings.TypeDropdownName; pbstrId = NavigationBarAutomationStrings.TypeDropdownId; return VSConstants.S_OK; case 2: pbstrName = NavigationBarAutomationStrings.MemberDropdownName; pbstrId = NavigationBarAutomationStrings.MemberDropdownId; return VSConstants.S_OK; default: pbstrName = null; pbstrId = null; return VSConstants.E_INVALIDARG; } } int IVsDropdownBarClient3.GetEntryImage(int iCombo, int iIndex, out int piImageIndex, out IntPtr phImageList) { // This class implements IVsDropdownBarClient4 and expects IVsDropdownBarClient4.GetEntryImage() to be called instead phImageList = IntPtr.Zero; piImageIndex = -1; return VSConstants.E_UNEXPECTED; } ImageMoniker IVsDropdownBarClient4.GetEntryImage(int iCombo, int iIndex) { var item = GetItem(iCombo, iIndex); if (item is NavigationBarProjectItem projectItem) { if (_workspace.TryGetHierarchy(projectItem.DocumentId.ProjectId, out var hierarchy)) { return _imageService.GetImageMonikerForHierarchyItem(hierarchy, VSConstants.VSITEMID_ROOT, (int)__VSHIERARCHYIMAGEASPECT.HIA_Icon); } } return item.Glyph.GetImageMoniker(); } int IVsDropdownBarClientEx.GetEntryIndent(int iCombo, int iIndex, out uint pIndent) { pIndent = (uint)GetItem(iCombo, iIndex).Indent; return VSConstants.S_OK; } void INavigationBarPresenter.Disconnect() { _manager.RemoveDropdownBar(); _codeWindowEventsSink.Unadvise(); foreach (var view in _trackedTextViews.Values) { view.Caret.PositionChanged -= OnCaretPositionChanged; view.GotAggregateFocus -= OnViewGotAggregateFocus; } _trackedTextViews.Clear(); } void INavigationBarPresenter.PresentItems( ImmutableArray<NavigationBarProjectItem> projects, NavigationBarProjectItem selectedProject, ImmutableArray<NavigationBarItem> types, NavigationBarItem selectedType, NavigationBarItem selectedMember) { _projectItems = projects; _currentTypeItems = types; // It's possible we're presenting items before the dropdown bar has been initialized. if (_dropdownBar == null) { return; } var projectIndex = selectedProject != null ? _projectItems.IndexOf(selectedProject) : -1; var typeIndex = selectedType != null ? _currentTypeItems.IndexOf(selectedType) : -1; var memberIndex = selectedType != null && selectedMember != null ? selectedType.ChildItems.IndexOf(selectedMember) : -1; _dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Project, projectIndex); _dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Type, typeIndex); _dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Member, memberIndex); } public event EventHandler DropDownFocused; public event EventHandler<NavigationBarItemSelectedEventArgs> ItemSelected; public event EventHandler<EventArgs> ViewFocused; public event EventHandler<CaretPositionChangedEventArgs> CaretMoved; int IVsCodeWindowEvents.OnCloseView(IVsTextView pView) { if (_trackedTextViews.TryGetValue(pView, out var view)) { view.Caret.PositionChanged -= OnCaretPositionChanged; view.GotAggregateFocus -= OnViewGotAggregateFocus; _trackedTextViews.Remove(pView); } return VSConstants.S_OK; } int IVsCodeWindowEvents.OnNewView(IVsTextView pView) { if (!_trackedTextViews.ContainsKey(pView)) { var wpfTextView = _editorAdaptersFactoryService.GetWpfTextView(pView); wpfTextView.Caret.PositionChanged += OnCaretPositionChanged; wpfTextView.GotAggregateFocus += OnViewGotAggregateFocus; _trackedTextViews.Add(pView, wpfTextView); } return VSConstants.S_OK; } private void OnCaretPositionChanged(object sender, CaretPositionChangedEventArgs e) => CaretMoved?.Invoke(this, e); private void OnViewGotAggregateFocus(object sender, EventArgs e) => ViewFocused?.Invoke(this, e); ITextView INavigationBarPresenter.TryGetCurrentView() { _codeWindow.GetLastActiveView(out var lastActiveView); return _editorAdaptersFactoryService.GetWpfTextView(lastActiveView); } } }
38.187342
210
0.625497
[ "MIT" ]
333fred/roslyn
src/VisualStudio/Core/Def/Implementation/NavigationBar/NavigationBarClient.cs
15,086
C#
using System; using System.Linq; using JetBrains.Annotations; using Rees.TangyFruitMapper; namespace BudgetAnalyser.Engine.Statement.Data { [AutoRegisterWithIoC] internal partial class Mapper_TransactionSetDto_StatementModel { private readonly ILogger logger; private readonly IDtoMapper<TransactionDto, Transaction> transactionMapper; public Mapper_TransactionSetDto_StatementModel([NotNull] ILogger logger, [NotNull] IDtoMapper<TransactionDto, Transaction> transactionMapper) { if (logger == null) throw new ArgumentNullException(nameof(logger)); if (transactionMapper == null) throw new ArgumentNullException(nameof(transactionMapper)); this.logger = logger; this.transactionMapper = transactionMapper; } // ReSharper disable once RedundantAssignment partial void ModelFactory(TransactionSetDto dto, ref StatementModel model) { model = new StatementModel(this.logger); } partial void ToDtoPostprocessing(ref TransactionSetDto dto, StatementModel model) { var transactions10 = model.AllTransactions.Select(this.transactionMapper.ToDto).ToList(); dto.Transactions = transactions10; } partial void ToModelPostprocessing(TransactionSetDto dto, ref StatementModel model) { model.LoadTransactions(dto.Transactions.Select(t => this.transactionMapper.ToModel(t))); } } }
38.538462
149
0.701929
[ "MIT" ]
Benrnz/BudgetAnalyser
BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.cs
1,505
C#
using System; class Program { static void Main() { Action a = delegate () { Console.WriteLine("In Anonymous Method"); }; Action b = () => { Console.WriteLine("In Lambda Expression "); }; a(); b(); } }
15.947368
55
0.422442
[ "MIT" ]
autumn009/UraCSharpSamples
Delegate/Delegate/Program.cs
305
C#
using HananokiEditor.Extensions; using HananokiRuntime; using System.Linq; using UnityEditor; using UnityEngine; using UnityReflection; using UnityObject = UnityEngine.Object; using E = HananokiEditor.AsmdefGraph.SettingsEditor; namespace HananokiEditor { public class AsmdefEditorWindow : HNEditorWindow<AsmdefEditorWindow> { UnityEditorSplitterState m_HorizontalSplitter; internal AsmdefEditorTreeView m_treeView; public Vector2 m_scroll; ///////////////////////////////////////// [MenuItem( "Window/Hananoki/" + "Asmdef Editor", false, 'A' * 10 )] public static void Open() { GetWindow<AsmdefEditorWindow>(); } ///////////////////////////////////////// public static void OpenAsName( UnityObject unityObject ) { OpenAsName( unityObject.ToAssetPath() ); } ///////////////////////////////////////// public static void OpenAsName( string guid_or_assetPath ) { //Debug.Log( asmdefName ); var lasctSelect = new SessionStateString( "m_lastSelect" ); lasctSelect.Value = guid_or_assetPath.ToAssetPath().FileNameWithoutExtension(); var window = EditorWindowUtils.Find<AsmdefEditorWindow>(); if( window ) { window.m_treeView.SelectLastItem(); window.Repaint(); return; } Open(); } public void Refresh() { if( m_treeView == null ) { Helper.New( ref m_treeView ); } m_treeView?.RegisterFiles(); } void OnEnable() { SetTitle( "Asmdef Editor", EditorIcon.assetIcon_AssemblyDefinition ); E.Load(); m_HorizontalSplitter = new UnityEditorSplitterState( 0.4f, 0.6f ); Refresh(); m_waitSpinIcon = new IconWaitSpin( Repaint ); } void OnDisable() { DisableWaitIcon(); } void DisableWaitIcon() { if( m_waitSpinIcon != null ) { m_waitSpinIcon.Dispose(); m_waitSpinIcon = null; } } void DrawLeftPane() { HGUIToolbar.Begin(); if( HGUIToolbar.Button( EditorIcon.refresh ) ) { Refresh(); EditorHelper.ShowMessagePop( "Refresh OK." ); } bool isDirty = m_treeView.m_asmdefItems.Where( x => x.isDIRTY ).Count() != 0; ScopeDisable.Begin( !isDirty ); if( HGUIToolbar.Button( "Apply All" ) ) { m_treeView.SaveAssetDirty(); } ScopeDisable.End(); if( HGUIToolbar.DropDown( "Change Format" ) ) { var m = new GenericMenu(); m.AddItem( "Assembly Name", () => m_treeView.ChangeAsmName() ); m.AddItem( "GUID", () => m_treeView.ChangeGUID() ); m.DropDownPopupRect( HEditorGUI.lastRect ); // } GUILayout.FlexibleSpace(); HGUIToolbar.End(); m_treeView.DrawLayoutGUI(); } void DrawRightPane() { HGUIToolbar.Begin(); if( HGUIToolbar.Button( "ソースコード整形" ) ) { ShellUtils.Start( "dotnet-format", $"-v diag {m_treeView.currentItem.m_json.name}.csproj" ); } //GUILayout.Space(1); GUILayout.FlexibleSpace(); if( HGUIToolbar.Button( "Sort" ) ) m_treeView.Sort( m_treeView.currentItem ); ScopeDisable.Begin( m_treeView.currentItem == null ? true : !m_treeView.currentItem.isDIRTY ); if( HGUIToolbar.Button( "Apply" ) ) m_treeView.ApplyAndSave( m_treeView.currentItem ); ScopeDisable.End(); HGUIToolbar.End(); using( var sc = new GUILayout.ScrollViewScope( m_scroll ) ) { m_scroll = sc.scrollPosition; m_treeView.DrawItem(); } } void DrawToolBar() { } IconWaitSpin m_waitSpinIcon; public override void OnDefaultGUI() { E.Load(); ScopeDisable.BeginIsCompiling(); DrawToolBar(); UnityEditorSplitterGUILayout.BeginHorizontalSplit( m_HorizontalSplitter ); ScopeVertical.Begin(); DrawLeftPane(); ScopeVertical.End(); ScopeVertical.Begin( HEditorStyles.dopesheetBackground ); DrawRightPane(); ScopeVertical.End(); UnityEditorSplitterGUILayout.EndHorizontalSplit(); ScopeDisable.End(); if( EditorApplication.isCompiling ) { var rc = position; rc.x = rc.y = 0; GUI.Label( rc.AlignCenter( 100, 20 ), EditorHelper.TempContent( $"コンパイル中", m_waitSpinIcon ), GUI.skin.box ); } } } }
26.158228
113
0.641181
[ "MIT" ]
hananoki/AsmdefGraph
Editor/Tool/AsmdefEditorWindow.cs
4,163
C#
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Order; using System.Threading.Tasks; namespace Benchmark.Base { [BenchmarkCategory("Slow")] public class SlowSorterBenchmark : BaseSorterBenchmark { [Params(ArrayType.Random, ArrayType.Ordered)] public ArrayType Type { get; set; } [Params(100, 1000)] public int Length { get; set; } [GlobalSetup] public void GlobalSetup() => GenerateRandomly(Length, Type); [Benchmark(Baseline = true)] [BenchmarkCategory(nameof(SorterCategories.System), nameof(SorterAlgorithms.Array))] public async Task SystemArraySorter() => _ = await new ParallelSorting.Systems.ArraySorter().Sort(RawArray); [Benchmark] [BenchmarkCategory(nameof(SorterCategories.Serial), nameof(SorterAlgorithms.Enum))] public async Task SerialEnumSorter() => _ = await new ParallelSorting.Serials.EnumSorter().Sort(RawArray); [Benchmark] [BenchmarkCategory(nameof(SorterCategories.Parallel), nameof(SorterAlgorithms.Enum))] public async Task ParallelEnumSorter() => _ = await new ParallelSorting.Parallels.EnumSorter().Sort(RawArray); [Benchmark] [BenchmarkCategory(nameof(SorterCategories.Serial), nameof(SorterAlgorithms.Insert))] public async Task SerialInsertSorter() => _ = await new ParallelSorting.Serials.InsertSorter().Sort(RawArray); [Benchmark] [BenchmarkCategory(nameof(SorterCategories.Serial), nameof(SorterAlgorithms.Shell))] public async Task SerialShellSorter() => _ = await new ParallelSorting.Serials.ShellSorter().Sort(RawArray); [Benchmark] [BenchmarkCategory(nameof(SorterCategories.Serial), nameof(SorterAlgorithms.Select))] public async Task SerialSelectSorter() => _ = await new ParallelSorting.Serials.SelectSorter().Sort(RawArray); [Benchmark] [BenchmarkCategory(nameof(SorterCategories.Serial), nameof(SorterAlgorithms.Bubble))] public async Task SerialBubbleSorter() => _ = await new ParallelSorting.Serials.BubbleSorter().Sort(RawArray); } }
44.354167
118
0.712071
[ "Apache-2.0" ]
StardustDL/NJU-PC-Lab
test/Benchmark.Base/SlowSorterBenchmark.cs
2,131
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Urls; namespace Dnn.PersonaBar.Pages.Components { public interface IUrlRewriterUtilsWrapper { FriendlyUrlOptions GetExtendOptionsForURLs(int portalId); } }
29.733333
72
0.764574
[ "MIT" ]
MaiklT/Dnn.Platform
Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IUrlRewriterUtilsWrapper.cs
448
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace GuessMaster.widgets { public class BottomButton : Button { public BottomButton() { Margin = new Thickness(10, 30, 10, 30); FontSize = 18; } } }
19.25
51
0.646753
[ "MIT" ]
snaulX/GuessMaster
GuessMaster/widgets/BottomButton.cs
387
C#
using System; namespace Ch4_ProgramLarge6 { class Change : Colors { //variable limiting the maximum allowed change calculated. internal const int CHANGE_LIMIT = 100; static void Main(string[] args) { for (int i = 0; i < 1; i++) //Error looping { try { TaskShortener.Header(); //Asks the amount of change you have decimal totalChange = TaskShortener.AskUserForDecimal("the total change " + "you have"); //Limits the amount of change that can be calculated #region Change Limiter while (totalChange > CHANGE_LIMIT) { TaskShortener.ErrorCatch(); } #endregion TaskShortener.Loading(); TotalChangeCalc(totalChange); //Calc and display of dollars TaskShortener.Footer(); break; } catch (FormatException) //Trying to error it eh? { TaskShortener.ErrorCatch(); } } } public static void TotalChangeCalc(decimal x) { //Declaring what each is worth #region Stated Values var coinTypes = new[] { new { type = "Twenty Dollar Bills", coinWorth = 20.00m} , //20$ Bills new { type = "Ten Dollar Bills", coinWorth = 10.0m }, //10$ Bills new { type = "Five Dollar Bills", coinWorth = 5.00m }, //5$ Bills new { type = "One Dollar Bills", coinWorth = 1.00m }, //1$ Bills new { type = "Quarters", coinWorth = 0.25m }, //Quarters new { type = "Dimes", coinWorth = 0.10m }, //Dimes new { type = "Nickels", coinWorth = 0.05m }, //Nickels new { type = "Pennies", coinWorth = 0.01m } //Pennies }; #endregion #region Console Display foreach (var coin in coinTypes) { //Reusing X over and over and getting remainders until the answer is acheived int countedChange = (int)(x / coin.coinWorth); x -= countedChange * coin.coinWorth; Console.ResetColor(); LimeFont(); TaskShortener.TypeLineSuperFast($"{countedChange} {coin.type}\n"); //Displays the stuff } #endregion } } }
37.828947
94
0.434783
[ "Apache-2.0" ]
EthanLawr/ComputerScience
Computer Science/Year_1_CSharp/Ch4_ProgramLarge6_Solution/Ch4_ProgramLarge6/Change.cs
2,877
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2; internal partial class Http2Stream : IHttp2StreamIdFeature, IHttpMinRequestBodyDataRateFeature, IHttpResetFeature, IHttpResponseTrailersFeature, IPersistentStateFeature { private IHeaderDictionary? _userTrailers; // Persistent state collection is not reset with a stream by design. private IDictionary<object, object?>? _persistentState; IHeaderDictionary IHttpResponseTrailersFeature.Trailers { get { if (ResponseTrailers == null) { ResponseTrailers = new HttpResponseTrailers(ServerOptions.ResponseHeaderEncodingSelector); if (HasResponseCompleted) { ResponseTrailers.SetReadOnly(); } } return _userTrailers ?? ResponseTrailers; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _userTrailers = value; } } int IHttp2StreamIdFeature.StreamId => _context.StreamId; MinDataRate? IHttpMinRequestBodyDataRateFeature.MinDataRate { get => throw new NotSupportedException(CoreStrings.HttpMinDataRateNotSupported); set { if (value != null) { throw new NotSupportedException(CoreStrings.HttpMinDataRateNotSupported); } MinRequestBodyDataRate = value; } } void IHttpResetFeature.Reset(int errorCode) { var abortReason = new ConnectionAbortedException(CoreStrings.FormatHttp2StreamResetByApplication((Http2ErrorCode)errorCode)); ApplicationAbort(abortReason, (Http2ErrorCode)errorCode); } IDictionary<object, object?> IPersistentStateFeature.State { get { // Lazily allocate persistent state return _persistentState ?? (_persistentState = new ConnectionItems()); } } }
32.525
133
0.628363
[ "MIT" ]
3ejki/aspnetcore
src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.FeatureCollection.cs
2,602
C#
using System; namespace Lezizz.Core.Domain.Exceptions { public class AdAccountInvalidException : Exception { public AdAccountInvalidException(string adAccount, Exception ex) : base($"AD Account \"{adAccount}\" is invalid.", ex) { } } }
22
72
0.632867
[ "MIT" ]
hoseinipeyrov/Lezizz
Src/Core/Lezizz.Core.Domain/Exceptions/AdAccountInvalidException.cs
288
C#
using System.Web.Mvc; namespace V308CMS.Helpers.Url { public static class AccountUrlHelper { public static string AccountAjaxLoginUrl(this UrlHelper helper, string controller = "member", string action = "ajaxlogin") { return helper.Action(action, controller); } public static string AccountLoginUrl(this UrlHelper helper, string controller = "member", string action = "login") { return helper.Action(action, controller); } public static string AccounRegisterUrl(this UrlHelper helper, string controller = "member", string action = "register") { return helper.Action(action, controller); } public static string AccounRegisterAjaxUrl(this UrlHelper helper, string controller = "member", string action = "registerajax") { return helper.Action(action, controller); } public static string AccountForgotPasswordUrl(this UrlHelper helper, string controller = "member", string action = "forgotgassword") { return helper.Action(action, controller); } public static string AccountForgotPasswordAjaxUrl(this UrlHelper helper, string controller = "member", string action = "forgotpasswordajax") { return helper.Action(action, controller); } public static string AccountActiveUrl(this UrlHelper helper, string controller = "member", string action = "active") { return helper.Action(action, controller); } public static string AccountGetTokenUrl(this UrlHelper helper, string controller = "member", string action = "gettoken") { return helper.Action(action, controller); } public static string AccountWishlistUrl(this UrlHelper helper, string controller = "member", string action = "wishlist") { return helper.Action(action, controller); } public static string AccountLogoutUrl(this UrlHelper helper, string returnUrl="", string controller = "member", string action = "logout") { return helper.Action(action, controller, new { returnUrl }); } public static string AccountCheckEmail(this UrlHelper helper, string controller = "member", string action = "checkemail") { return helper.Action(action, controller); } public static string AccountChangePasswordUrl(this UrlHelper helper, string controller = "member", string action = "changepassword") { return helper.Action(action, controller); } } }
37.914286
148
0.645818
[ "Unlicense" ]
giaiphapictcom/mamoo.vn
V308CMS/Helpers/Url/AccountUrlHelper.cs
2,656
C#
#region << 版 本 注 释 >> /*----------------------------------------------------------------- * 项目名称 :Kane.Extension * 项目描述 :通用扩展工具 * 类 名 称 :FormatHelper * 类 描 述 :常用的校验格式帮助类 * 所在的域 :KK-HOME * 命名空间 :Kane.Extension * 机器名称 :KK-HOME * CLR 版本 :4.0.30319.42000 * 作  者 :Kane Leung * 创建时间 :2020/02/20 19:38:55 * 更新时间 :2020/12/04 09:16:17 * 版 本 号 :v1.0.4.0 ******************************************************************* * Copyright @ Kane Leung 2020. All rights reserved. ******************************************************************* -----------------------------------------------------------------*/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; namespace Kane.Extension { /// <summary> /// 常用的校验格式帮助类 /// </summary> public class FormatHelper { #region 检测字符串是否为中国公民身份证 + IsIDCard(string value) /// <summary> /// 检测字符串是否为中国公民身份证 /// <para>15位身份证号码=6位地区代码+6位生日+3位编号</para> /// <para>18位身份证号码=6位地区代码+8位生日+3位编号+1位检验码</para> /// <para>https://www.cnblogs.com/gc2013/p/4054048.html</para> /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool IsIDCard(string value) { if (value.IsNullOrWhiteSpace()) return false; string provinceCode = "11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,51,52,53,54,50,61,62,63,64,65,71,81,82";//省代码 if (value.Length == 15) { if (long.TryParse(value, out long temp) == false || temp < Math.Pow(10, 14)) return false; // 数字验证 if (provinceCode.IndexOf(value.Remove(2)) == -1) return false; // 省份验证 if (!DateTime.TryParse(value.Substring(6, 6).Insert(4, "-").Insert(2, "-"), out _)) return false;//生日验证 return true; // 符合GB11643-1989标准 } else if (value.Length == 18) { if (long.TryParse(value.Remove(17), out long temp) == false || temp < Math.Pow(10, 16) || !long.TryParse(value.Replace('x', '0').Replace('X', '0'), out _)) return false; // 数字验证 if (provinceCode.IndexOf(value.Remove(2)) == -1) return false; //省份验证 if (!DateTime.TryParse(value.Substring(6, 8).Insert(6, "-").Insert(4, "-"), out _)) return false;//生日验证 string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(','); string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');//Wi表示第i位置上的加权因子 char[] Ai = value.Remove(17).ToCharArray();//Ai表示第i位置上的身份证号码数字值 int sum = 0; for (int i = 0; i < 17; i++) sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString()); if (arrVarifyCode[sum % 11] != value.Substring(17, 1).ToLower()) return false; //校验码验证 return true; //符合GB11643-1999标准 } return false; } #endregion #region 检测字符串是否为正确的邮箱地址,可检测中文域名 + IsEmail(string value) /// <summary> /// 检测字符串是否为正确的邮箱地址,可检测中文域名 /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool IsEmail(string value) { if (value.IsNullOrWhiteSpace()) return false; return new Regex(@"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?").IsMatch(value); } #endregion #region 检测字符串是否包含汉字 + HasChinese(string value) /// <summary> /// 检测字符串是否包含汉字 /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool HasChinese(string value) { if (value.IsNullOrWhiteSpace()) return false; return Regex.IsMatch(value, @"[\u4e00-\u9fa5]+"); } #endregion #region 检测字符串是否为IPv4地址,可包含端口 + IsIPv4(string value) /// <summary> /// 检测字符串是否为IPv4地址,可包含端口 /// <para>如【192.168.1.168】或【192.168.1.168:8080】</para> /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool IsIPv4(string value) { if (value.IsNullOrWhiteSpace()) return false; var hostType = Uri.CheckHostName(value); if (hostType == UriHostNameType.IPv4) return true; else if (hostType == UriHostNameType.Unknown && Uri.TryCreate($"http://{value}", UriKind.Absolute, out Uri url) && IPAddress.TryParse(url.Host, out IPAddress temp) && temp.AddressFamily == AddressFamily.InterNetwork) return true; return false; } #endregion #region 检测字符串是否为IPv6地址,可包含端口 + IsIPv6(string value) /// <summary> /// 检测字符串是否为IPv6地址,可包含端口 /// <para>如【[2001:0DB8:02de::0e13]】或【[2001:0DB8:02de::0e13]:8080】</para> /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool IsIPv6(string value) { if (value.IsNullOrWhiteSpace()) return false; var hostType = Uri.CheckHostName(value); if (hostType == UriHostNameType.IPv6) return true; else if (hostType == UriHostNameType.Unknown && Uri.TryCreate($"http://{value}", UriKind.Absolute, out Uri url) && IPAddress.TryParse(url.Host, out IPAddress temp) && temp.AddressFamily == AddressFamily.InterNetworkV6) return true; return false; } #endregion #region 检测字符串是否为IP地址 + IsIP(string value) /// <summary> /// 检测字符串是否为IP地址,可包含端口 /// <para>如【192.168.1.168】或【192.168.1.168:8080】或【[2001:0DB8:02de::0e13]】或【[2001:0DB8:02de::0e13]:8080】</para> /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool IsIP(string value) { if (value.IsNullOrWhiteSpace()) return false; var hostType = Uri.CheckHostName(value); if (hostType == UriHostNameType.IPv4 || hostType == UriHostNameType.IPv6) return true; else if (hostType == UriHostNameType.Unknown && Uri.TryCreate($"http://{value}", UriKind.Absolute, out Uri url) && IPAddress.TryParse(url.Host, out _)) return true; return false; } #endregion #region 检测字符串是否为中国国内手机号码段,数据更新日期【2020-11-10】 + IsMobilePhone(string value) /// <summary> /// 检测字符串是否为中国国内手机号码段,数据更新日期【2020-11-10】 /// <para>【资料来源】https://baike.baidu.com/item/手机号码 </para> /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool IsMobilePhone(string value) { if (value.IsNullOrWhiteSpace()) return false; if (new Regex(@"^1[0-9]{10}$").IsMatch(value.Trim())) { var prefix = new List<string>(); string[] ChinaTelecomPrefix = "133、149、153、173、177、180、181、189、190、191、193、199".Split('、'); string[] ChinaUnicomPrefix = "130、131、132、145、155、156、166、167、171、175、176、185、186、196".Split('、'); string[] ChinaMobilePrefix = "134(0-8)、135、136、137、138、139、1440、147、148、150、151、152、157、158、159、172、178、182、183、184、187、188、195、197、198".Split('、'); string[] ChinaBroadcstPrefix = new[] { "192" }; string[] ChinaTelecomVirtualPrefix = "1700、1701、1702、162".Split('、'); string[] ChinaMobileVirtualPrefix = "1703、1705、1706、165".Split('、'); string[] ChinaUnicomVirtualPrefix = "1704、1707、1708、1709、171、167".Split('、'); string[] SatelliteCommunicationPrefix = "1349、174".Split('、'); string[] InternetOfThingsPrefix = "140、141、144、146、148".Split('、'); prefix.AddRange(ChinaTelecomPrefix); // 中国电信号段 prefix.AddRange(ChinaUnicomPrefix); // 中国联通号段 for (var i = 0; i <= 8; i++) prefix.Add($"134{i}");//中国移动 134 号段特殊处理 prefix.AddRange(ChinaMobilePrefix.Skip(1)); // 中国移动号段 prefix.AddRange(ChinaBroadcstPrefix); // 中国广电号段 prefix.AddRange(ChinaTelecomVirtualPrefix); // 中国电信虚拟运营商号段 prefix.AddRange(ChinaMobileVirtualPrefix); // 中国移动虚拟运营商号段 prefix.AddRange(ChinaUnicomVirtualPrefix); // 中国联通虚拟运营商号段 prefix.AddRange(SatelliteCommunicationPrefix); // 卫星通信号段 prefix.AddRange(InternetOfThingsPrefix); // 物联网号段 return value.StartsWith(prefix.ToArray()); } else return false; } #endregion #region 判断字符串是否为安全Sql语句 + IsSafeSql(string value) /// <summary> /// 判断字符串是否为安全Sql语句 /// </summary> /// <param name="value">要检测的Sql语句</param> /// <returns></returns> public bool IsSafeSql(string value) { if (value.IsNullOrWhiteSpace()) return false; if (value.IsMatch(@"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']", RegexOptions.IgnoreCase) || value.IsMatch(@"select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|Char(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and", RegexOptions.IgnoreCase)) { return true; } return false; } #endregion #region 判断字符串是否为数值 + IsNumeric(string value) /// <summary> /// 判断字符串是否为数值,如【0】【123】【0.123】【+0.123】【-0.123】【+123.123】【-123.132】 /// <para>注意,如果是小数,前导零不能少</para> /// </summary> /// <param name="value">要检测的字符串</param> /// <returns></returns> public bool IsNumeric(string value) => value.IsMatch(@"^[-+]?\d+[.]?\d*$"); #endregion #region 判断字符串是否为整数 + IsInteger(string value) /// <summary> /// 判断字符串是否为整数,如【0】【1】【123】【+123】【-123】 /// </summary> /// <param name="value"></param> /// <returns></returns> public bool IsInteger(string value) => value.IsMatch(@"^[-+]?\d+$"); #endregion } }
44.034188
209
0.533773
[ "MIT" ]
KaneLeung/Kane.Extension
Src/字符串类/FormatHelper.cs
11,868
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using Microsoft; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; using Xunit.Threading; namespace Roslyn.VisualStudio.IntegrationTests.InProcess { internal abstract class InProcComponent { protected InProcComponent(TestServices testServices) { TestServices = testServices ?? throw new ArgumentNullException(nameof(testServices)); } public TestServices TestServices { get; } protected JoinableTaskFactory JoinableTaskFactory => TestServices.JoinableTaskFactory; protected async Task<TInterface> GetRequiredGlobalServiceAsync<TService, TInterface>(CancellationToken cancellationToken) where TService : class where TInterface : class { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var serviceProvider = (IAsyncServiceProvider2?)await AsyncServiceProvider.GlobalProvider.GetServiceAsync(typeof(SAsyncServiceProvider)).WithCancellation(cancellationToken); Assumes.Present(serviceProvider); var @interface = (TInterface?)await serviceProvider.GetServiceAsync(typeof(TService)).WithCancellation(cancellationToken); Assumes.Present(@interface); return @interface; } protected async Task<TService> GetComponentModelServiceAsync<TService>(CancellationToken cancellationToken) where TService : class { var componentModel = await GetRequiredGlobalServiceAsync<SComponentModel, IComponentModel>(cancellationToken); return componentModel.GetService<TService>(); } /// <summary> /// Waiting for the application to 'idle' means that it is done pumping messages (including WM_PAINT). /// </summary> /// <param name="cancellationToken">The cancellation token that the operation will observe.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> protected static async Task WaitForApplicationIdleAsync(CancellationToken cancellationToken) { var synchronizationContext = new DispatcherSynchronizationContext(Application.Current.Dispatcher, DispatcherPriority.ApplicationIdle); var taskScheduler = new SynchronizationContextTaskScheduler(synchronizationContext); await Task.Factory.StartNew( () => { }, cancellationToken, TaskCreationOptions.None, taskScheduler); } } }
43.794118
184
0.716924
[ "MIT" ]
CyrusNajmabadi/roslyn
src/VisualStudio/IntegrationTest/New.IntegrationTests/InProcess/InProcComponent.cs
2,980
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Extensions; using Foundatio.Serializer; using Foundatio.Utility; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace Foundatio.Storage { public class FolderFileStorage : IFileStorage { private readonly object _lockObject = new object(); private readonly ISerializer _serializer; protected readonly ILogger _logger; public FolderFileStorage(FolderFileStorageOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); _serializer = options.Serializer ?? DefaultSerializer.Instance; _logger = options.LoggerFactory?.CreateLogger(GetType()) ?? NullLogger<FolderFileStorage>.Instance; string folder = PathHelper.ExpandPath(options.Folder); if (!Path.IsPathRooted(folder)) folder = Path.GetFullPath(folder); char lastCharacter = folder[folder.Length - 1]; if (!lastCharacter.Equals(Path.DirectorySeparatorChar) && !lastCharacter.Equals(Path.AltDirectorySeparatorChar)) folder += Path.DirectorySeparatorChar; Folder = folder; Directory.CreateDirectory(folder); } public FolderFileStorage(Builder<FolderFileStorageOptionsBuilder, FolderFileStorageOptions> config) : this(config(new FolderFileStorageOptionsBuilder()).Build()) { } public string Folder { get; set; } ISerializer IHaveSerializer.Serializer => _serializer; public Task<Stream> GetFileStreamAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); path = path.NormalizePath(); try { return Task.FromResult<Stream>(File.OpenRead(Path.Combine(Folder, path))); } catch (IOException ex) when (ex is FileNotFoundException || ex is DirectoryNotFoundException) { if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace(ex, "Error trying to get file stream: {Path}", path); return Task.FromResult<Stream>(null); } } public Task<FileSpec> GetFileInfoAsync(string path) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); path = path.NormalizePath(); var info = new FileInfo(Path.Combine(Folder, path)); if (!info.Exists) return Task.FromResult<FileSpec>(null); return Task.FromResult(new FileSpec { Path = path.Replace(Folder, String.Empty), Created = info.CreationTimeUtc, Modified = info.LastWriteTimeUtc, Size = info.Length }); } public Task<bool> ExistsAsync(string path) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); path = path.NormalizePath(); return Task.FromResult(File.Exists(Path.Combine(Folder, path))); } public async Task<bool> SaveFileAsync(string path, Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (stream == null) throw new ArgumentNullException(nameof(stream)); path = path.NormalizePath(); string file = Path.Combine(Folder, path); try { using (var fileStream = CreateFileStream(file)) { await stream.CopyToAsync(fileStream).AnyContext(); return true; } } catch (Exception ex) { _logger.LogError(ex, "Error trying to save file: {Path}", path); return false; } } private Stream CreateFileStream(string filePath) { try { return File.Create(filePath); } catch (DirectoryNotFoundException) { } string directory = Path.GetDirectoryName(filePath); if (directory != null) Directory.CreateDirectory(directory); return File.Create(filePath); } public Task<bool> RenameFileAsync(string path, string newPath, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (String.IsNullOrEmpty(newPath)) throw new ArgumentNullException(nameof(newPath)); path = path.NormalizePath(); newPath = newPath.NormalizePath(); try { lock (_lockObject) { string directory = Path.GetDirectoryName(newPath); if (directory != null) Directory.CreateDirectory(Path.Combine(Folder, directory)); string oldFullPath = Path.Combine(Folder, path); string newFullPath = Path.Combine(Folder, newPath); try { File.Move(oldFullPath, newFullPath); } catch (IOException) { File.Delete(newFullPath); File.Move(oldFullPath, newFullPath); } } } catch (Exception ex) { _logger.LogError(ex, "Error trying to rename file {Path} to {NewPath}.", path, newPath); return Task.FromResult(false); } return Task.FromResult(true); } public Task<bool> CopyFileAsync(string path, string targetPath, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (String.IsNullOrEmpty(targetPath)) throw new ArgumentNullException(nameof(targetPath)); path = path.NormalizePath(); try { lock (_lockObject) { string directory = Path.GetDirectoryName(targetPath); if (directory != null) Directory.CreateDirectory(Path.Combine(Folder, directory)); File.Copy(Path.Combine(Folder, path), Path.Combine(Folder, targetPath)); } } catch (Exception ex) { _logger.LogError(ex, "Error trying to copy file {Path} to {TargetPath}.", path, targetPath); return Task.FromResult(false); } return Task.FromResult(true); } public Task<bool> DeleteFileAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); path = path.NormalizePath(); try { File.Delete(Path.Combine(Folder, path)); } catch (Exception ex) when (ex is FileNotFoundException || ex is DirectoryNotFoundException) { _logger.LogDebug(ex, "Error trying to delete file: {Path}.", path); return Task.FromResult(false); } return Task.FromResult(true); } public Task DeleteFilesAsync(string searchPattern = null, CancellationToken cancellation = default(CancellationToken)) { if (searchPattern == null || String.IsNullOrEmpty(searchPattern) || searchPattern == "*") { Directory.Delete(Folder, true); return Task.CompletedTask; } searchPattern = searchPattern.NormalizePath(); string path = Path.Combine(Folder, searchPattern); if (path[path.Length - 1] == Path.DirectorySeparatorChar || path.EndsWith(Path.DirectorySeparatorChar + "*")) { string directory = Path.GetDirectoryName(path); if (Directory.Exists(directory)) { Directory.Delete(directory, true); return Task.CompletedTask; } } else if (Directory.Exists(path)) { Directory.Delete(path, true); return Task.CompletedTask; } foreach (string file in Directory.EnumerateFiles(Folder, searchPattern, SearchOption.AllDirectories)) File.Delete(file); return Task.CompletedTask; } public Task<IEnumerable<FileSpec>> GetFileListAsync(string searchPattern = null, int? limit = null, int? skip = null, CancellationToken cancellationToken = default(CancellationToken)) { if (limit.HasValue && limit.Value <= 0) return Task.FromResult<IEnumerable<FileSpec>>(new List<FileSpec>()); if (searchPattern == null || String.IsNullOrEmpty(searchPattern)) searchPattern = "*"; searchPattern = searchPattern.NormalizePath(); var list = new List<FileSpec>(); if (!Directory.Exists(Path.GetDirectoryName(Path.Combine(Folder, searchPattern)))) return Task.FromResult<IEnumerable<FileSpec>>(list); foreach (string path in Directory.EnumerateFiles(Folder, searchPattern, SearchOption.AllDirectories).Skip(skip ?? 0).Take(limit ?? Int32.MaxValue)) { var info = new FileInfo(path); if (!info.Exists) continue; list.Add(new FileSpec { Path = path.Replace(Folder, String.Empty), Created = info.CreationTimeUtc, Modified = info.LastWriteTimeUtc, Size = info.Length }); } return Task.FromResult<IEnumerable<FileSpec>>(list); } public void Dispose() { } } }
40.943775
193
0.587445
[ "Apache-2.0" ]
se/Foundatio
src/Foundatio/Storage/FolderFileStorage.cs
10,197
C#
using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; namespace Lucene.Net.Analysis.Ja { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Simple tests for <see cref="JapaneseKatakanaStemFilterFactory"/> /// </summary> public class TestJapaneseKatakanaStemFilterFactory : BaseTokenStreamTestCase { [Test] public void TestKatakanaStemming() { JapaneseTokenizerFactory tokenizerFactory = new JapaneseTokenizerFactory(new Dictionary<String, String>()); tokenizerFactory.Inform(new StringMockResourceLoader("")); TokenStream tokenStream = tokenizerFactory.Create( new StringReader("明後日パーティーに行く予定がある。図書館で資料をコピーしました。") ); JapaneseKatakanaStemFilterFactory filterFactory = new JapaneseKatakanaStemFilterFactory(new Dictionary<String, String>()); ; AssertTokenStreamContents(filterFactory.Create(tokenStream), new String[]{ "明後日", "パーティ", "に", "行く", "予定", "が", "ある", // パーティー should be stemmed "図書館", "で", "資料", "を", "コピー", "し", "まし", "た"} // コピー should not be stemmed ); } /** Test that bogus arguments result in exception */ [Test] public void TestBogusArguments() { try { new JapaneseKatakanaStemFilterFactory(new Dictionary<String, String>() { { "bogusArg", "bogusValue" } }); fail(); } catch (ArgumentException expected) { assertTrue(expected.Message.Contains("Unknown parameters")); } } } }
40.52381
136
0.622013
[ "Apache-2.0" ]
DiogenesPolanco/lucenenet
src/Lucene.Net.Tests.Analysis.Kuromoji/TestJapaneseKatakanaStemFilterFactory.cs
2,693
C#
using System; using Moq; using XUnitMoqSampleWeb.Controllers; using XUnitMoqSampleWeb.Services; namespace XUnitMoqSampleWeb.Tests.Fixtures { /// <summary> /// This represents the fixture entity for the <see cref="HomeController"/> class. /// </summary> public class HomeControllerFixture : IDisposable { private bool _disposed; /// <summary> /// Initializes a new instance of the <see cref="HomeControllerFixture"/> class. /// </summary> public HomeControllerFixture() { this.GitHubApiService = new Mock<IGitHubApiService>(); this.HomeController = new HomeController(this.GitHubApiService.Object); // this.HomeController = new HomeController(); } /// <summary> /// Gets the <see cref="Mock{IGitHubApiService}"/> instance. /// </summary> public Mock<IGitHubApiService> GitHubApiService { get; } /// <summary> /// Gets the <see cref="HomeController"/> instance. /// </summary> public HomeController HomeController { get; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (this._disposed) { return; } this.HomeController.Dispose(); this._disposed = true; } } }
27.592593
116
0.587919
[ "MIT" ]
devkimchi/xUnit-Moq-Sample
test/xUnitMoqSampleWeb.Tests/Fixtures/HomeControllerFixture.cs
1,492
C#
using ShoppingCart.Models; using ShoppingCart.Services; using System.Windows.Input; using Xamarin.Forms; namespace ShoppingCart.ViewModels { public class CategoryViewModel : BaseViewModel { private readonly Category _category; public CategoryViewModel(Category category) { _category = category; NavigateToCategory = new Command(() => MessagingCenter.Send(category, Messages.NavigateTo)); Name = _category.Name; if (_category.Count == 1) { Count = "1 item"; } else if (_category.Count > 1) { Count = string.Format("{0} items", _category.Count); } else { Count = "No items"; } } public Category Category { get { return _category; } } public string Count { get; private set; } public string Name { get; private set; } public ICommand NavigateToCategory { get; private set; } } }
25.071429
104
0.553656
[ "MIT" ]
jquintus/ShoppingCartXF
ShoppingCart/ShoppingCart/ViewModels/CategoryViewModel.cs
1,055
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TaskManagement.Web.Areas.HelpPage.ModelDescriptions; using TaskManagement.Web.Areas.HelpPage.Models; namespace TaskManagement.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
51.495726
196
0.623154
[ "Apache-2.0" ]
khairuzzaman/TaskManager
TaskManagement.Web/Areas/HelpPage/HelpPageConfigurationExtensions.cs
24,100
C#
// <copyright file="SearchVideosPage.xaml.cs" company="Drastic Actions"> // Copyright (c) Drastic Actions. All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autofac; using Xamarin.Forms; using Xamarin.Forms.Xaml; using YoutubeSubtitleExplorer.ViewModels; namespace YoutubeSubtitleExplorer.Pages { /// <summary> /// Search Videos Page. /// </summary> [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SearchVideosPage : ContentPage { /// <summary> /// Initializes a new instance of the <see cref="SearchVideosPage"/> class. /// </summary> public SearchVideosPage() { this.InitializeComponent(); this.BindingContext = App.Container.Resolve<SearchVideosViewModel>(); } /// <inheritdoc/> protected override void OnAppearing() { base.OnAppearing(); this.videoSearchCollection.SelectedItem = null; } } }
27.871795
83
0.658694
[ "MIT" ]
drasticactions/YoutubeSubtitleExplorer
YoutubeSubtitleExplorer/Pages/SearchVideosPage.xaml.cs
1,089
C#
namespace CWMII.lib.Enums { public enum Win32_LocalTime { Day, DayOfWeek, Hour, Milliseconds, Minute, Month, Quarter, Second, WeekInMonth, Year } public static class Win32_LocalTimeExtension { public static string GetWMIValue(this Win32_LocalTime enumOption) => lib.CWMII.GetSingleProperty($"SELECT * FROM Win32_LocalTime", enumOption.ToString()); } }
21
156
0.743386
[ "MIT" ]
jcapellman/CWMII
CWMII.lib/Enums/Win32_LocalTime.cs
378
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Blog.Migrations { public partial class Upgraded_To_ABP_6_0 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "NewValueHash", table: "AbpEntityPropertyChanges", type: "nvarchar(max)", nullable: true); migrationBuilder.AddColumn<string>( name: "OriginalValueHash", table: "AbpEntityPropertyChanges", type: "nvarchar(max)", nullable: true); migrationBuilder.AddColumn<string>( name: "DisplayName", table: "AbpDynamicProperties", type: "nvarchar(max)", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "NewValueHash", table: "AbpEntityPropertyChanges"); migrationBuilder.DropColumn( name: "OriginalValueHash", table: "AbpEntityPropertyChanges"); migrationBuilder.DropColumn( name: "DisplayName", table: "AbpDynamicProperties"); } } }
30.818182
71
0.550147
[ "MIT" ]
LMapundu/Boilerplate-Example
aspnet-core/src/Blog.EntityFrameworkCore/Migrations/20201112121732_Upgraded_To_ABP_6_0.cs
1,358
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("04. Files")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04. Files")] [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("f0e7443f-7596-4872-94a5-c1437d15cca0")] // 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")]
37.459459
84
0.743867
[ "MIT" ]
melikpehlivanov/Programming-Fundamentals-C-
AllExams/04. Files/Properties/AssemblyInfo.cs
1,389
C#
// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Collections.Generic; using System.Linq; using System; namespace PixelCrushers.DialogueSystem.DialogueEditor { /// <summary> /// This part of the Dialogue Editor window handles the Items tab. Since the quest system /// also uses the Item table, this part handles quests as well as standard items. /// </summary> public partial class DialogueEditorWindow { [SerializeField] private AssetFoldouts itemFoldouts = new AssetFoldouts(); [SerializeField] private string itemFilter = string.Empty; private bool needToBuildLanguageListFromItems = true; private ReorderableList itemReorderableList = null; [SerializeField] private int itemListSelectedIndex = -1; private void ResetItemSection() { itemFoldouts = new AssetFoldouts(); itemAssetList = null; UpdateTreatItemsAsQuests(template.treatItemsAsQuests); needToBuildLanguageListFromItems = true; itemReorderableList = null; itemListSelectedIndex = -1; } private void UpdateTreatItemsAsQuests(bool newValue) { if (newValue != template.treatItemsAsQuests) { template.treatItemsAsQuests = newValue; toolbar.UpdateTabNames(newValue); } } private void BuildLanguageListFromItems() { if (database == null || database.items == null) return; database.items.ForEach(item => { if (item.fields != null) BuildLanguageListFromFields(item.fields); }); needToBuildLanguageListFromItems = false; } private void DrawItemSection() { if (template.treatItemsAsQuests) { if (needToBuildLanguageListFromItems) BuildLanguageListFromItems(); if (itemReorderableList == null) { itemReorderableList = new ReorderableList(database.items, typeof(Item), true, true, true, true); itemReorderableList.drawHeaderCallback = DrawItemListHeader; itemReorderableList.drawElementCallback = DrawItemListElement; itemReorderableList.drawElementBackgroundCallback = DrawItemListElementBackground; itemReorderableList.onAddDropdownCallback = OnAddItemOrQuestDropdown; itemReorderableList.onRemoveCallback = OnItemListRemove; itemReorderableList.onSelectCallback = OnItemListSelect; itemReorderableList.onReorderCallback = OnItemListReorder; } DrawFilterMenuBar("Quests/Item", DrawItemMenu, ref itemFilter); if (database.syncInfo.syncItems) DrawItemSyncDatabase(); itemReorderableList.DoLayoutList(); } else { if (itemReorderableList == null) { itemReorderableList = new ReorderableList(database.items, typeof(Item), true, true, true, true); itemReorderableList.drawHeaderCallback = DrawItemListHeader; itemReorderableList.drawElementCallback = DrawItemListElement; itemReorderableList.drawElementBackgroundCallback = DrawItemListElementBackground; itemReorderableList.onAddCallback = OnItemListAdd; itemReorderableList.onRemoveCallback = OnItemListRemove; itemReorderableList.onSelectCallback = OnItemListSelect; itemReorderableList.onReorderCallback = OnItemListReorder; } DrawFilterMenuBar("Item", DrawItemMenu, ref itemFilter); if (database.syncInfo.syncItems) DrawItemSyncDatabase(); itemReorderableList.DoLayoutList(); } } private const float ItemReorderableListTypeWidth = 40f; private void DrawItemListHeader(Rect rect) { if (template.treatItemsAsQuests) { var fieldWidth = (rect.width - 14 - ItemReorderableListTypeWidth) / 4; EditorGUI.LabelField(new Rect(rect.x + 14, rect.y, ItemReorderableListTypeWidth, rect.height), "Type"); EditorGUI.LabelField(new Rect(rect.x + 14 + ItemReorderableListTypeWidth, rect.y, fieldWidth, rect.height), "Name"); EditorGUI.LabelField(new Rect(rect.x + 14 + ItemReorderableListTypeWidth + fieldWidth + 2, rect.y, 3 * fieldWidth - 2, rect.height), "Description"); } else { var fieldWidth = (rect.width - 14) / 4; EditorGUI.LabelField(new Rect(rect.x + 14, rect.y, fieldWidth, rect.height), "Name"); EditorGUI.LabelField(new Rect(rect.x + 14 + fieldWidth + 2, rect.y, 3 * fieldWidth - 2, rect.height), "Description"); } } private void DrawItemListElement(Rect rect, int index, bool isActive, bool isFocused) { if (!(0 <= index && index < database.items.Count)) return; var nameControl = "ItemName" + index; var descriptionControl = "ItemDescription" + index; var item = database.items[index]; var itemName = item.Name; var description = item.Description; EditorGUI.BeginDisabledGroup(!EditorTools.IsAssetInFilter(item, itemFilter)); if (template.treatItemsAsQuests) { var fieldWidth = (rect.width - ItemReorderableListTypeWidth) / 4; EditorGUI.LabelField(new Rect(rect.x, rect.y + 2, ItemReorderableListTypeWidth, EditorGUIUtility.singleLineHeight), item.IsItem ? "Item" : "Quest"); EditorGUI.BeginChangeCheck(); GUI.SetNextControlName(nameControl); itemName = EditorGUI.TextField(new Rect(rect.x + ItemReorderableListTypeWidth, rect.y, fieldWidth, EditorGUIUtility.singleLineHeight), GUIContent.none, item.Name); if (EditorGUI.EndChangeCheck()) item.Name = itemName; EditorGUI.BeginChangeCheck(); GUI.SetNextControlName(descriptionControl); description = EditorGUI.TextField(new Rect(rect.x + ItemReorderableListTypeWidth + fieldWidth + 2, rect.y + 2, 3 * fieldWidth - 2, EditorGUIUtility.singleLineHeight), GUIContent.none, description); if (EditorGUI.EndChangeCheck()) item.Description = description; } else { var fieldWidth = rect.width / 4; EditorGUI.BeginChangeCheck(); GUI.SetNextControlName(nameControl); itemName = EditorGUI.TextField(new Rect(rect.x, rect.y, fieldWidth, EditorGUIUtility.singleLineHeight), GUIContent.none, item.Name); if (EditorGUI.EndChangeCheck()) item.Name = itemName; EditorGUI.BeginChangeCheck(); GUI.SetNextControlName(descriptionControl); description = EditorGUI.TextField(new Rect(rect.x + fieldWidth + 2, rect.y, 3 * fieldWidth - 2, EditorGUIUtility.singleLineHeight), GUIContent.none, description); if (EditorGUI.EndChangeCheck()) item.Description = description; } EditorGUI.EndDisabledGroup(); var focusedControl = GUI.GetNameOfFocusedControl(); if (string.Equals(nameControl, focusedControl) || string.Equals(descriptionControl, focusedControl)) { inspectorSelection = item; } } private void DrawItemListElementBackground(Rect rect, int index, bool isActive, bool isFocused) { if (!(0 <= index && index < database.items.Count)) return; var item = database.items[index]; if (EditorTools.IsAssetInFilter(item, itemFilter)) { ReorderableList.defaultBehaviours.DrawElementBackground(rect, index, isActive, isFocused, true); } else { EditorGUI.DrawRect(rect, new Color(0.225f, 0.225f, 0.225f, 1)); } } private void OnAddItemOrQuestDropdown(Rect buttonRect, ReorderableList list) { var menu = new GenericMenu(); menu.AddItem(new GUIContent("Quest"), false, OnAddNewQuest, null); menu.AddItem(new GUIContent("Item"), false, OnAddNewItem, null); menu.ShowAsContext(); } private void OnItemListAdd(ReorderableList list) { AddNewItem(); } private void OnItemListRemove(ReorderableList list) { if (!(0 <= list.index && list.index < database.items.Count)) return; var actor = database.items[list.index]; if (actor == null) return; var deletedLastOne = list.count == 1; if (EditorUtility.DisplayDialog(string.Format("Delete '{0}'?", EditorTools.GetAssetName(actor)), "Are you sure you want to delete this?", "Delete", "Cancel")) { ReorderableList.defaultBehaviours.DoRemoveButton(list); if (deletedLastOne) inspectorSelection = null; else inspectorSelection = (list.index < list.count) ? database.items[list.index] : (list.count > 0) ? database.items[list.count - 1] : null; SetDatabaseDirty("Remove Item"); } } private void OnItemListReorder(ReorderableList list) { SetDatabaseDirty("Reorder Items"); } private void OnItemListSelect(ReorderableList list) { if (!(0 <= list.index && list.index < database.items.Count)) return; inspectorSelection = database.items[list.index]; itemListSelectedIndex = list.index; } public void DrawSelectedItemSecondPart() { var item = inspectorSelection as Item; if (item == null) return; DrawFieldsFoldout<Item>(item, itemListSelectedIndex, itemFoldouts); DrawAssetSpecificPropertiesSecondPart(item, itemListSelectedIndex, itemFoldouts); } private void DrawItemMenu() { if (GUILayout.Button("Menu", "MiniPullDown", GUILayout.Width(56))) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("New Item"), false, AddNewItem); if (template.treatItemsAsQuests) { menu.AddItem(new GUIContent("New Quest"), false, AddNewQuest); } else { menu.AddDisabledItem(new GUIContent("New Quest")); } menu.AddItem(new GUIContent("Use Quest System"), template.treatItemsAsQuests, ToggleUseQuestSystem); menu.AddItem(new GUIContent("Sort/By Name"), false, SortItemsByName); menu.AddItem(new GUIContent("Sort/By Group"), false, SortItemsByGroup); menu.AddItem(new GUIContent("Sort/By ID"), false, SortItemsByID); menu.AddItem(new GUIContent("Sync From DB"), database.syncInfo.syncItems, ToggleSyncItemsFromDB); menu.ShowAsContext(); } } private void OnAddNewItem(object data) { AddNewItem(); } private void OnAddNewQuest(object data) { AddNewQuest(); } private void AddNewItem() { AddNewAssetFromTemplate<Item>(database.items, (template != null) ? template.itemFields : null, "Item"); SetDatabaseDirty("Add New Item"); } private void AddNewQuest() { AddNewAssetFromTemplate<Item>(database.items, (template != null) ? template.questFields : null, "Quest"); BuildLanguageListFromItems(); SetDatabaseDirty("Add New Quest"); } private void SortItemsByName() { database.items.Sort((x, y) => x.Name.CompareTo(y.Name)); SetDatabaseDirty("Sort by Name"); } private void SortItemsByGroup() { database.items.Sort((x, y) => x.Group.CompareTo(y.Group)); SetDatabaseDirty("Sort by Group"); } private void SortItemsByID() { database.items.Sort((x, y) => x.id.CompareTo(y.id)); SetDatabaseDirty("Sort by ID"); } private void ToggleUseQuestSystem() { UpdateTreatItemsAsQuests(!template.treatItemsAsQuests); showStateFieldAsQuest = template.treatItemsAsQuests; } private void ToggleSyncItemsFromDB() { database.syncInfo.syncItems = !database.syncInfo.syncItems; SetDatabaseDirty("Toggle Sync Items"); } private void DrawItemSyncDatabase() { EditorGUILayout.BeginHorizontal(); DialogueDatabase newDatabase = EditorGUILayout.ObjectField(new GUIContent("Sync From", "Database to sync items/quests from."), database.syncInfo.syncItemsDatabase, typeof(DialogueDatabase), false) as DialogueDatabase; if (newDatabase != database.syncInfo.syncItemsDatabase) { database.syncInfo.syncItemsDatabase = newDatabase; database.SyncItems(); SetDatabaseDirty("Change Sync Items Database"); } if (GUILayout.Button(new GUIContent("Sync Now", "Syncs from the database."), EditorStyles.miniButton, GUILayout.Width(72))) { database.SyncItems(); SetDatabaseDirty("Manual Sync Items"); } EditorGUILayout.EndHorizontal(); } private void DrawItemPropertiesFirstPart(Item item) { if (!item.IsItem) DrawQuestProperties(item); } private void DrawQuestProperties(Item item) { if (item == null || item.fields == null) return; // Display Name: var displayNameField = Field.Lookup(item.fields, "Display Name"); var hasDisplayNameField = (displayNameField != null); var useDisplayNameField = EditorGUILayout.Toggle(new GUIContent("Use Display Name", "Tick to use a Display Name in UIs that's different from the Name."), hasDisplayNameField); if (hasDisplayNameField && !useDisplayNameField) { item.fields.Remove(displayNameField); SetDatabaseDirty("Don't Use Display Name"); } else if (useDisplayNameField) { EditTextField(item.fields, "Display Name", "The name to show in UIs.", false); DrawLocalizedVersions(item.fields, "Display Name {0}", false, FieldType.Text); } // Group: var groupField = Field.Lookup(item.fields, "Group"); var hasGroupField = (groupField != null); var useGroupField = EditorGUILayout.Toggle(new GUIContent("Use Groups", "Tick to organize this quest under a quest group."), hasGroupField); if (hasGroupField && !useGroupField) { item.fields.Remove(groupField); SetDatabaseDirty("Don't Use Groups"); } else if (useGroupField) { if (groupField == null) { groupField = new Field("Group", string.Empty, FieldType.Text); item.fields.Add(groupField); SetDatabaseDirty("Create Group Field"); } if (groupField.typeString == "CustomFieldType_Text") { EditTextField(item.fields, "Group", "The group this quest belongs to.", false); DrawLocalizedVersions(item.fields, "Group {0}", false, FieldType.Text); } else { DrawField(new GUIContent("Group", "The group this quest belongs to."), groupField, false); } } // State: //EditorGUILayout.BeginHorizontal(); Field stateField = Field.Lookup(item.fields, "State"); if (stateField == null) { stateField = new Field("State", "unassigned", FieldType.Text); item.fields.Add(stateField); SetDatabaseDirty("Create State Field"); } //EditorGUILayout.LabelField(new GUIContent("State", "The starting state of the quest."), GUILayout.Width(140)); stateField.value = DrawQuestStateField(new GUIContent("State", "The starting state of the quest."), stateField.value); //EditorGUILayout.EndHorizontal(); // Trackable: bool trackable = item.LookupBool("Trackable"); bool newTrackable = EditorGUILayout.Toggle(new GUIContent("Trackable", "Tick to mark this quest trackable in a gameplay HUD."), trackable); if (newTrackable != trackable) { Field.SetValue(item.fields, "Trackable", newTrackable); SetDatabaseDirty("Create Trackable Field"); } // Track on Start (only if Trackable): if (trackable) { bool track = item.LookupBool("Track"); bool newTrack = EditorGUILayout.Toggle(new GUIContent("Track on Start", "Tick to show in HUD when the quest becomes active without the player having to toggle tracking on in the quest log window first."), track); if (newTrack != track) { Field.SetValue(item.fields, "Track", newTrack); SetDatabaseDirty("Create Track Field"); } } // Abandonable: bool abandonable = item.LookupBool("Abandonable"); bool newAbandonable = EditorGUILayout.Toggle(new GUIContent("Abandonable", "Tick to mark this quest abandonable in the quest window."), abandonable); if (newAbandonable != abandonable) { Field.SetValue(item.fields, "Abandonable", newAbandonable); SetDatabaseDirty("Create Abandonable Field"); } // Has Entries: bool hasQuestEntries = item.FieldExists("Entry Count"); bool newHasQuestEntries = EditorGUILayout.Toggle(new GUIContent("Has Entries (Subtasks)", "Tick to add quest entries to this quest."), hasQuestEntries); if (newHasQuestEntries != hasQuestEntries) ToggleHasQuestEntries(item, newHasQuestEntries); // Other main fields specified in template: DrawOtherQuestPrimaryFields(item); // Descriptions: EditTextField(item.fields, "Description", "The description when the quest is active.", true); DrawLocalizedVersions(item.fields, "Description {0}", false, FieldType.Text); EditTextField(item.fields, "Success Description", "The description when the quest has been completed successfully. If blank, the Description field is used.", true); DrawLocalizedVersions(item.fields, "Success Description {0}", false, FieldType.Text); EditTextField(item.fields, "Failure Description", "The description when the quest has failed. If blank, the Description field is used.", true); DrawLocalizedVersions(item.fields, "Failure Description {0}", false, FieldType.Text); // Entries: if (newHasQuestEntries) DrawQuestEntries(item); } private static List<string> questBuiltInFieldTitles = new List<string>(new string[] { "Display Name", "Group", "State", "Trackable", "Track", "Abandonable" }); private void DrawOtherQuestPrimaryFields(Item item) { if (item == null || item.fields == null || template.questPrimaryFieldTitles == null) return; foreach (var field in item.fields) { var fieldTitle = field.title; if (string.IsNullOrEmpty(fieldTitle)) continue; if (!template.questPrimaryFieldTitles.Contains(field.title)) continue; if (questBuiltInFieldTitles.Contains(fieldTitle)) continue; if (fieldTitle.StartsWith("Description") || fieldTitle.StartsWith("Success Description") || fieldTitle.StartsWith("Failure Description")) continue; EditorGUILayout.BeginHorizontal(); DrawField(field, false, false); EditorGUILayout.EndHorizontal(); } } private void ToggleHasQuestEntries(Item item, bool hasEntries) { SetDatabaseDirty("Toggle Has Quest Entries"); if (hasEntries) { if (!item.FieldExists("Entry Count")) Field.SetValue(item.fields, "Entry Count", (int)0); } else { int entryCount = Field.LookupInt(item.fields, "Entry Count"); if (entryCount > 0) { if (!EditorUtility.DisplayDialog("Delete all entries?", "You cannot undo this action.", "Delete", "Cancel")) { return; } } item.fields.RemoveAll(field => field.title.StartsWith("Entry ")); } } private void DrawQuestEntries(Item item) { EditorGUILayout.LabelField("Quest Entries", EditorStyles.boldLabel); EditorWindowTools.StartIndentedSection(); int entryCount = Field.LookupInt(item.fields, "Entry Count"); int entryToDelete = -1; int entryToMoveUp = -1; int entryToMoveDown = -1; for (int i = 1; i <= entryCount; i++) { DrawQuestEntry(item, i, entryCount, ref entryToDelete, ref entryToMoveUp, ref entryToMoveDown); } if (entryToDelete != -1) { DeleteQuestEntry(item, entryToDelete, entryCount); SetDatabaseDirty("Delete Quest Entry"); } if (entryToMoveUp != -1) { MoveQuestEntryUp(item, entryToMoveUp, entryCount); } if (entryToMoveDown != -1) { MoveQuestEntryDown(item, entryToMoveDown, entryCount); } if (GUILayout.Button(new GUIContent("Add New Quest Entry", "Adds a new quest entry to this quest."))) { entryCount++; Field.SetValue(item.fields, "Entry Count", entryCount); Field.SetValue(item.fields, string.Format("Entry {0} State", entryCount), "unassigned"); Field.SetValue(item.fields, string.Format("Entry {0}", entryCount), string.Empty); List<string> questLanguages = new List<string>(); item.fields.ForEach(field => { if (field.title.StartsWith("Description ")) { string language = field.title.Substring("Description ".Length); questLanguages.Add(language); languages.Add(language); } }); questLanguages.ForEach(language => item.fields.Add(new Field(string.Format("Entry {0} {1}", entryCount, language), string.Empty, FieldType.Localization))); if (entryCount > 1) { // Copy any custom "Entry 1 ..." fields to "Entry # ..." fields: var fieldCount = item.fields.Count; for (int i = 0; i < fieldCount; i++) { var field = item.fields[i]; if (field.title.StartsWith("Entry 1 ")) { // Skip Entry 1, Entry 1 State, or Entry 1 Language: if (string.Equals(field.title, "Entry 1") || string.Equals(field.title, "Entry 1 State")) continue; var afterEntryNumber = field.title.Substring("Entry 1 ".Length); if (questLanguages.Contains(afterEntryNumber)) continue; // Otherwise add: var newFieldTitle = "Entry " + entryCount + " " + afterEntryNumber; if (item.FieldExists(newFieldTitle)) continue; var copiedField = new Field(field); copiedField.title = newFieldTitle; if (copiedField.type == FieldType.Text) copiedField.value = string.Empty; item.fields.Add(copiedField); } } } SetDatabaseDirty("Add New Quest Entry"); } EditorWindowTools.EndIndentedSection(); } private void DrawQuestEntry(Item item, int entryNumber, int entryCount, ref int entryToDelete, ref int entryToMoveUp, ref int entryToMoveDown) { EditorGUILayout.BeginVertical("button"); // Keep track of which fields we've already drawn: List<Field> alreadyDrawn = new List<Field>(); // Heading: EditorGUILayout.BeginHorizontal(); string entryTitle = string.Format("Entry {0}", entryNumber); EditorGUILayout.LabelField(entryTitle); GUILayout.FlexibleSpace(); //--- Framework for future move up/down buttons: EditorGUI.BeginDisabledGroup(entryNumber <= 1); if (GUILayout.Button(new GUIContent("↑", "Move up"), EditorStyles.miniButtonLeft, GUILayout.Width(22))) { entryToMoveUp = entryNumber; } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(entryNumber >= entryCount); if (GUILayout.Button(new GUIContent("↓", "Move down"), EditorStyles.miniButtonMid, GUILayout.Width(22))) { entryToMoveDown = entryNumber; } EditorGUI.EndDisabledGroup(); // Also change Delete button below to miniButtonRight if (GUILayout.Button(new GUIContent("-", "Delete"), EditorStyles.miniButtonRight, GUILayout.Width(22))) //if (GUILayout.Button(new GUIContent(" ", "Delete quest entry"), "OL Minus", GUILayout.Width(16))) { entryToDelete = entryNumber; } EditorGUILayout.EndHorizontal(); // State: EditorGUILayout.BeginHorizontal(); string stateTitle = entryTitle + " State"; Field stateField = Field.Lookup(item.fields, stateTitle); if (stateField == null) { stateField = new Field(stateTitle, "unassigned", FieldType.Text); item.fields.Add(stateField); SetDatabaseDirty("Change Quest Entry State"); } EditorGUILayout.LabelField(new GUIContent("State", "The starting state of this entry."), GUILayout.Width(140)); stateField.value = DrawQuestStateField(stateField.value); EditorGUILayout.EndHorizontal(); alreadyDrawn.Add(stateField); // Text: EditTextField(item.fields, entryTitle, "The text of this entry.", true, alreadyDrawn); DrawLocalizedVersions(item.fields, entryTitle + " {0}", false, FieldType.Text, alreadyDrawn); // Other "Entry # " fields: string entryTitleWithSpace = entryTitle + " "; string entryIDTitle = entryTitle + " ID"; for (int i = 0; i < item.fields.Count; i++) { var field = item.fields[i]; if (field.title == null) field.title = string.Empty; if (!alreadyDrawn.Contains(field) && field.title.StartsWith(entryTitleWithSpace) && !string.Equals(field.title, entryIDTitle)) { if (field.type == FieldType.Text) { EditTextField(item.fields, field.title, field.title, true, null); } else { EditorGUILayout.BeginHorizontal(); DrawField(field); EditorGUILayout.EndHorizontal(); } alreadyDrawn.Add(field); } } EditorGUILayout.EndVertical(); } private void DeleteQuestEntry(Item item, int entryNumber, int entryCount) { if (EditorUtility.DisplayDialog(string.Format("Delete entry {0}?", entryNumber), "You cannot undo this action.", "Delete", "Cancel")) { CutEntry(item, entryNumber, entryCount); SetDatabaseDirty("Delete Quest Entry"); } } private void MoveQuestEntryUp(Item item, int entryNumber, int entryCount) { if (entryNumber <= 1) return; var clipboard = CutEntry(item, entryNumber, entryCount); entryCount--; PasteEntry(item, entryNumber - 1, entryCount, clipboard); } private void MoveQuestEntryDown(Item item, int entryNumber, int entryCount) { if (entryNumber >= entryCount) return; var clipboard = CutEntry(item, entryNumber, entryCount); entryCount--; PasteEntry(item, entryNumber + 1, entryCount, clipboard); } private List<Field> CutEntry(Item item, int entryNumber, int entryCount) { var clipboard = new List<Field>(); // Remove the entry and put it on the clipboard: string entryFieldTitle = string.Format("Entry {0}", entryNumber); var extractedField = item.fields.Find(field => string.Equals(field.title, entryFieldTitle)); clipboard.Add(extractedField); item.fields.Remove(extractedField); // Remove the other fields associated with the entry and put them on the clipboard: string entryPrefix = string.Format("Entry {0} ", entryNumber); var extractedFields = item.fields.FindAll(field => field.title.StartsWith(entryPrefix)); clipboard.AddRange(extractedFields); item.fields.RemoveAll(field => field.title.StartsWith(entryPrefix)); // Renumber any higher entries: for (int i = entryNumber + 1; i <= entryCount; i++) { Field entryField = Field.Lookup(item.fields, string.Format("Entry {0}", i)); if (entryField != null) entryField.title = string.Format("Entry {0}", i - 1); string oldEntryPrefix = string.Format("Entry {0} ", i); string newEntryPrefix = string.Format("Entry {0} ", i - 1); for (int j = 0; j < item.fields.Count; j++) { var field = item.fields[j]; if (field.title.StartsWith(oldEntryPrefix)) { field.title = newEntryPrefix + field.title.Substring(oldEntryPrefix.Length); } } } // Decrement the count: Field.SetValue(item.fields, "Entry Count", entryCount - 1); return clipboard; } private void PasteEntry(Item item, int entryNumber, int entryCount, List<Field> clipboard) { // Set the clipboard's new entry number: var stateField = clipboard.Find(field => field.title.EndsWith(" State")); if (stateField != null) { var oldEntryPrefix = stateField.title.Substring(0, stateField.title.Length - " State".Length); var newEntryPrefix = "Entry " + entryNumber; foreach (var field in clipboard) { field.title = newEntryPrefix + field.title.Substring(oldEntryPrefix.Length); } } // Renumber any higher entries: for (int i = entryCount; i >= entryNumber; i--) { Field entryField = Field.Lookup(item.fields, string.Format("Entry {0}", i)); if (entryField != null) entryField.title = string.Format("Entry {0}", i + 1); string oldEntryPrefix = string.Format("Entry {0} ", i); string newEntryPrefix = string.Format("Entry {0} ", i + 1); for (int j = 0; j < item.fields.Count; j++) { var field = item.fields[j]; if (field.title.StartsWith(oldEntryPrefix)) { field.title = newEntryPrefix + field.title.Substring(oldEntryPrefix.Length); } } } // Add the clipboard entry: item.fields.AddRange(clipboard); // Increment the count: Field.SetValue(item.fields, "Entry Count", entryCount + 1); } private void DrawItemSpecificPropertiesSecondPart(Item item, int index, AssetFoldouts foldouts) { // Doesn't do anything right now. } private void SortItemFields(List<Field> fields) { List<Field> entryFields = fields.Where(field => field.title.StartsWith("Entry ")).OrderBy(field => field.title).ToList(); fields.RemoveAll(field => entryFields.Contains(field)); fields.AddRange(entryFields); SetDatabaseDirty("Sort Fields"); } } }
46.983784
229
0.55761
[ "Apache-2.0" ]
NGTO-WONG/KishiStory
Assets/Plugins/Pixel Crushers/Dialogue System/Scripts/Editor/Dialogue Editor/DialogueEditorWindowItemSection.cs
34,774
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Azure.Messaging.ServiceBus; using Microsoft.Azure.WebJobs.Host.Executors; using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.WebJobs.ServiceBus { public class SessionMessageProcessor { public SessionMessageProcessor(ServiceBusSessionProcessor processor) { Processor = processor ?? throw new ArgumentNullException(nameof(processor)); } /// <summary> /// Gets or sets the <see cref="Processor"/> that will be used by the <see cref="SessionMessageProcessor"/>. /// </summary> internal ServiceBusSessionProcessor Processor { get; set; } /// <summary> /// This method is called when there is a new message to process, before the job function is invoked. /// This allows any preprocessing to take place on the message before processing begins. /// </summary> /// <param name="receiver"></param> /// <param name="message"></param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param> /// <returns>A <see cref="Task"/> that returns true if the message processing should continue, false otherwise.</returns> public virtual Task<bool> BeginProcessingMessageAsync(ServiceBusSessionReceiver receiver, ServiceBusReceivedMessage message, CancellationToken cancellationToken) { return Task.FromResult<bool>(true); } /// <summary> /// This method completes processing of the specified message, after the job function has been invoked. /// </summary> /// <remarks> /// The message is completed by the ServiceBus SDK based on how the <see cref="ServiceBusSessionProcessorOptions.AutoCompleteMessages"/> option /// is configured. E.g. if <see cref="ServiceBusSessionProcessorOptions.AutoCompleteMessages"/> is false, it is up to the job function to complete /// the message. /// </remarks> /// <param name="receiver"></param> /// <param name="message"></param> /// <param name="result">The <see cref="FunctionResult"/> from the job invocation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use</param> /// <returns>A <see cref="Task"/> that will complete the message processing.</returns> public virtual Task CompleteProcessingMessageAsync(ServiceBusSessionReceiver receiver, ServiceBusReceivedMessage message, FunctionResult result, CancellationToken cancellationToken) { if (result == null) { throw new ArgumentNullException(nameof(result)); } cancellationToken.ThrowIfCancellationRequested(); if (!result.Succeeded) { // if the invocation failed, we must propagate the // exception back to SB so it can handle message state // correctly throw result.Exception; } return Task.CompletedTask; } } }
45.704225
189
0.65208
[ "MIT" ]
MahmoudYounes/azure-sdk-for-net
sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus/src/SessionMessageProcessor.cs
3,247
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NuGet.Versioning; namespace Stats.CreateAzureCdnWarehouseReports { public class DownloadCountReport : ReportBase { private const string _storedProcedureName = "[dbo].[SelectTotalDownloadCountsPerPackageVersion]"; public DownloadCountReport( ILogger<DownloadCountReport> logger, IEnumerable<StorageContainerTarget> targets, Func<Task<SqlConnection>> openStatisticsSqlConnectionAsync, Func<Task<SqlConnection>> openGallerySqlConnectionAsync, int commandTimeoutSeconds) : base(logger, targets, openStatisticsSqlConnectionAsync, openGallerySqlConnectionAsync, commandTimeoutSeconds) { } public async Task Run() { // Gather download count data from statistics warehouse IReadOnlyCollection<DownloadCountData> downloadData; using (var connection = await OpenStatisticsSqlConnectionAsync()) using (var transaction = connection.BeginTransaction(IsolationLevel.Snapshot)) { _logger.LogInformation("Gathering Download Counts from {DataSource}/{InitialCatalog}...", connection.DataSource, connection.Database); downloadData = (await connection.QueryWithRetryAsync<DownloadCountData>( _storedProcedureName, commandType: CommandType.StoredProcedure, transaction: transaction, commandTimeout: CommandTimeoutSeconds)).ToList(); } _logger.LogInformation("Gathered {DownloadedRowsCount} rows of data.", downloadData.Count); if (downloadData.Any()) { // Group based on Package Id var grouped = downloadData.GroupBy(p => p.PackageId); var registrations = new JArray(); foreach (var group in grouped) { var details = new JArray(); details.Add(group.Key); foreach (var gv in group) { // downloads.v1.json should only contain normalized versions - ignore others NuGetVersion semanticVersion; if (!string.IsNullOrEmpty(gv.PackageVersion) && NuGetVersion.TryParse(gv.PackageVersion, out semanticVersion) && gv.PackageVersion == semanticVersion.ToNormalizedString()) { var version = new JArray(gv.PackageVersion, gv.TotalDownloadCount); details.Add(version); } } registrations.Add(details); } var reportText = registrations.ToString(Formatting.None); foreach (var storageContainerTarget in Targets) { try { var targetBlobContainer = await GetBlobContainer(storageContainerTarget); var blob = targetBlobContainer.GetBlockBlobReference(ReportNames.DownloadCount + ReportNames.Extension); _logger.LogInformation("Writing report to {ReportUri}", blob.Uri.AbsoluteUri); blob.Properties.ContentType = "application/json"; await blob.UploadTextAsync(reportText); await blob.CreateSnapshotAsync(); _logger.LogInformation("Wrote report to {ReportUri}", blob.Uri.AbsoluteUri); } catch (Exception ex) { _logger.LogError("Error writing report to storage account {StorageAccount}, container {ReportContainer}: {Exception}", storageContainerTarget.StorageAccount.Credentials.AccountName, storageContainerTarget.ContainerName, ex); } } } } } }
45.571429
159
0.586655
[ "Apache-2.0" ]
CyberAndrii/NuGet.Jobs
src/Stats.CreateAzureCdnWarehouseReports/DownloadCountReport.cs
4,468
C#
namespace ClassLib118 { public class Class008 { public static string Property => "ClassLib118"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib118/Class008.cs
120
C#
namespace NoteSystem.WpfApp.ViewModels { public class NotebookVM : ViewModel { public string Name { get => _name; set { _name = value; OnPropertyChanged(); } } private string _name; } }
17.333333
39
0.439103
[ "MIT" ]
PrizrakNight/NoteSystem
NoteSystem.WpfApp/ViewModels/NotebookVM.cs
314
C#
//------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ // Generation date: 10/4/2020 2:55:10 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for ModuleCustSales in the schema. /// </summary> public enum ModuleCustSales { Cust = 0, Sales = 1 } }
29
81
0.478261
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/ModuleCustSales.cs
669
C#
using Skybrud.Umbraco.Redirects.Models; using Umbraco.Core.Migrations; namespace Skybrud.Umbraco.Redirects.Migrations { public class CreateImportTable : MigrationBase { public CreateImportTable(IMigrationContext context) : base(context) { } public override void Migrate() { if (TableExists(RedirectItemRowImport.TableName)) return; Create.Table<RedirectItemRowImport>().Do(); } } }
28.375
79
0.680617
[ "MIT" ]
EnjoyDigital/Skybrud.Umbraco.Redirects
src/Skybrud.Umbraco.Redirects/Migrations/CreateImportTable.cs
456
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.PolicyInsights { /// <summary> /// The remediation definition. /// API Version: 2019-07-01. /// </summary> [AzureNativeResourceType("azure-native:policyinsights:RemediationAtManagementGroup")] public partial class RemediationAtManagementGroup : Pulumi.CustomResource { /// <summary> /// The time at which the remediation was created. /// </summary> [Output("createdOn")] public Output<string> CreatedOn { get; private set; } = null!; /// <summary> /// The deployment status summary for all deployments created by the remediation. /// </summary> [Output("deploymentStatus")] public Output<Outputs.RemediationDeploymentSummaryResponse> DeploymentStatus { get; private set; } = null!; /// <summary> /// The filters that will be applied to determine which resources to remediate. /// </summary> [Output("filters")] public Output<Outputs.RemediationFiltersResponse?> Filters { get; private set; } = null!; /// <summary> /// The time at which the remediation was last updated. /// </summary> [Output("lastUpdatedOn")] public Output<string> LastUpdatedOn { get; private set; } = null!; /// <summary> /// The name of the remediation. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The resource ID of the policy assignment that should be remediated. /// </summary> [Output("policyAssignmentId")] public Output<string?> PolicyAssignmentId { get; private set; } = null!; /// <summary> /// The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. /// </summary> [Output("policyDefinitionReferenceId")] public Output<string?> PolicyDefinitionReferenceId { get; private set; } = null!; /// <summary> /// The status of the remediation. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. /// </summary> [Output("resourceDiscoveryMode")] public Output<string?> ResourceDiscoveryMode { get; private set; } = null!; /// <summary> /// The type of the remediation. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a RemediationAtManagementGroup resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public RemediationAtManagementGroup(string name, RemediationAtManagementGroupArgs args, CustomResourceOptions? options = null) : base("azure-native:policyinsights:RemediationAtManagementGroup", name, args ?? new RemediationAtManagementGroupArgs(), MakeResourceOptions(options, "")) { } private RemediationAtManagementGroup(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:policyinsights:RemediationAtManagementGroup", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:policyinsights:RemediationAtManagementGroup"}, new Pulumi.Alias { Type = "azure-native:policyinsights/v20180701preview:RemediationAtManagementGroup"}, new Pulumi.Alias { Type = "azure-nextgen:policyinsights/v20180701preview:RemediationAtManagementGroup"}, new Pulumi.Alias { Type = "azure-native:policyinsights/v20190701:RemediationAtManagementGroup"}, new Pulumi.Alias { Type = "azure-nextgen:policyinsights/v20190701:RemediationAtManagementGroup"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing RemediationAtManagementGroup resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static RemediationAtManagementGroup Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new RemediationAtManagementGroup(name, id, options); } } public sealed class RemediationAtManagementGroupArgs : Pulumi.ResourceArgs { /// <summary> /// The filters that will be applied to determine which resources to remediate. /// </summary> [Input("filters")] public Input<Inputs.RemediationFiltersArgs>? Filters { get; set; } /// <summary> /// Management group ID. /// </summary> [Input("managementGroupId", required: true)] public Input<string> ManagementGroupId { get; set; } = null!; /// <summary> /// The namespace for Microsoft Management RP; only "Microsoft.Management" is allowed. /// </summary> [Input("managementGroupsNamespace", required: true)] public Input<string> ManagementGroupsNamespace { get; set; } = null!; /// <summary> /// The resource ID of the policy assignment that should be remediated. /// </summary> [Input("policyAssignmentId")] public Input<string>? PolicyAssignmentId { get; set; } /// <summary> /// The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. /// </summary> [Input("policyDefinitionReferenceId")] public Input<string>? PolicyDefinitionReferenceId { get; set; } /// <summary> /// The name of the remediation. /// </summary> [Input("remediationName")] public Input<string>? RemediationName { get; set; } /// <summary> /// The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. /// </summary> [Input("resourceDiscoveryMode")] public InputUnion<string, Pulumi.AzureNative.PolicyInsights.ResourceDiscoveryMode>? ResourceDiscoveryMode { get; set; } public RemediationAtManagementGroupArgs() { } } }
44.301676
188
0.633796
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/PolicyInsights/RemediationAtManagementGroup.cs
7,930
C#
// // Copyright (c) XSharp B.V. 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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using LanguageService.SyntaxTree; using LanguageService.CodeAnalysis.Text; using LanguageService.CodeAnalysis.XSharp.SyntaxParser; using System.ComponentModel; using XSharpModel; using System.Linq; using System.Threading; namespace XSharpColorizer { /// <summary> /// Classifier that classifies all text as an instance of the "XSharpClassifier" classification type. /// There is one classifier per (visible) editor window. /// VS delays creating the classifier until the window is shown for the first time /// We can store data in the classifier /// </summary> public class XSharpClassifier : IClassifier { #region Static Fields static private IClassificationType xsharpKeywordType; static private IClassificationType xsharpIdentifierType; static private IClassificationType xsharpCommentType; static private IClassificationType xsharpOperatorType; static private IClassificationType xsharpPunctuationType; static private IClassificationType xsharpStringType; static private IClassificationType xsharpNumberType; static private IClassificationType xsharpPPType; static private IClassificationType xsharpBraceOpenType; static private IClassificationType xsharpBraceCloseType; static private IClassificationType xsharpRegionStart; static private IClassificationType xsharpRegionStop; static private IClassificationType xsharpInactiveType; static private IClassificationType xsharpLiteralType; static private IClassificationType xsharpKwOpenType; static private IClassificationType xsharpKwCloseType; #endregion #region Private Fields private readonly object gate = new object(); private readonly BackgroundWorker _bwClassify = null; private readonly BackgroundWorker _bwBuildModel = null; private readonly SourceWalker _sourceWalker; private readonly ITextBuffer _buffer; private XClassificationSpans _colorTags = new XClassificationSpans(); private IList<ClassificationSpan> _lexerRegions = null; private IList<ClassificationSpan> _parserRegions = null; private ITextDocumentFactoryService _txtdocfactory; private bool _first = true; private XSharpModel.ParseResult _info = null; private IToken keywordContext; private ITokenStream _tokens; private ITextSnapshot _snapshot; private XFile _file; #endregion #region Properties public ITextSnapshot Snapshot => _snapshot; private bool disableEntityParsing => _file.Project.ProjectNode.DisableParsing; private bool disableSyntaxHighlighting => _file.Project.ProjectNode.DisableLexing; private bool disableRegions => _file.Project.ProjectNode.DisableRegions; #endregion /// <summary> /// Initializes a new instance of the <see cref="XSharpClassifier"/> class. /// </summary> /// <param name="registry">Classification registry.</param> internal XSharpClassifier(ITextBuffer buffer, IClassificationTypeRegistryService registry, ITextDocumentFactoryService factory) { XFile file = null; this._buffer = buffer; if (buffer.Properties.ContainsProperty(typeof(XFile))) { file = buffer.GetFile(); } if (file == null) { return; } _file = file; // Initialize our background workers this._buffer.Changed += Buffer_Changed; _bwClassify = new BackgroundWorker(); _bwClassify.RunWorkerCompleted += ClassifyCompleted; _bwClassify.DoWork += DoClassify; _bwBuildModel = new BackgroundWorker(); _bwBuildModel.DoWork += BuildModelDoWork; _txtdocfactory = factory; if (xsharpKeywordType == null) { // These fields are static so only initialize the first time xsharpKeywordType = registry.GetClassificationType("keyword"); xsharpIdentifierType = registry.GetClassificationType("identifier"); xsharpCommentType = registry.GetClassificationType("comment"); xsharpOperatorType = registry.GetClassificationType("operator"); xsharpPunctuationType = registry.GetClassificationType("punctuation"); xsharpPPType = registry.GetClassificationType("preprocessor keyword"); xsharpNumberType = registry.GetClassificationType("number"); xsharpStringType = registry.GetClassificationType("string"); xsharpInactiveType = registry.GetClassificationType("excluded code"); xsharpBraceOpenType = registry.GetClassificationType("punctuation"); xsharpBraceCloseType = registry.GetClassificationType("punctuation"); xsharpLiteralType = registry.GetClassificationType("literal"); xsharpRegionStart = registry.GetClassificationType(ColorizerConstants.XSharpRegionStartFormat); xsharpRegionStop = registry.GetClassificationType(ColorizerConstants.XSharpRegionStopFormat); xsharpKwOpenType = registry.GetClassificationType(ColorizerConstants.XSharpBraceOpenFormat); xsharpKwCloseType = registry.GetClassificationType(ColorizerConstants.XSharpBraceCloseFormat); } // Run a synchronous scan to set the initial buffer colors _snapshot = buffer.CurrentSnapshot; _sourceWalker = new SourceWalker(file); ClassifyBuffer(_snapshot); _first = false; // start the model builder to do build a code model and the regions asynchronously try { _bwBuildModel.RunWorkerAsync(); } catch { } } #region Lexer Methods private void Buffer_Changed(object sender, TextContentChangedEventArgs e) { if (!_bwClassify.IsBusy && !_bwBuildModel.IsBusy) { try { _bwClassify.RunWorkerAsync(); } catch { } } } private void ClassifyBuffer(ITextSnapshot snapshot) { if (disableSyntaxHighlighting) return; Debug("Starting classify at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); ITokenStream tokens; tokens = _sourceWalker.Lex(snapshot.GetText()); lock (gate) { _snapshot = snapshot; _tokens = tokens; XSharpTokens xTokens = new XSharpTokens((BufferedTokenStream)tokens, snapshot); if (_buffer.Properties.ContainsProperty(typeof(XSharpTokens))) { _buffer.Properties.RemoveProperty(typeof(XSharpTokens)); } _buffer.Properties.AddProperty(typeof(XSharpTokens), xTokens); } BuildColorClassifications(tokens, snapshot); Debug("Ending classify at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); return; } private void DoClassify(object sender, DoWorkEventArgs e) { // Note this runs in the background // Wait a little and then get the current snapshot. They may have typed fast or the buffer may have been updated by the formatter // wait a second before actually starting to lex the buffer if (disableSyntaxHighlighting) return; System.Threading.Thread.Sleep(1000); // and then take the current snapshot because it may have changed in the meantime var snapshot = _buffer.CurrentSnapshot; ClassifyBuffer(snapshot); e.Result = snapshot; // so we know the version of the snapshot that was used in this classifier } private void triggerRepaint(ITextSnapshot snapshot) { if (ClassificationChanged != null) { System.Diagnostics.Trace.WriteLine("-->> XSharpClassifier.triggerRepaint()"); if (snapshot != null && _buffer?.CurrentSnapshot != null) { // tell the editor that we have new info if (!_first) { ClassificationChanged(this, new ClassificationChangedEventArgs( new SnapshotSpan(snapshot, Span.FromBounds(0, snapshot.Length)))); } } System.Diagnostics.Trace.WriteLine("<<-- XSharpClassifier.triggerRepaint()"); } } private void ClassifyCompleted(object sender, RunWorkerCompletedEventArgs e) { System.Diagnostics.Trace.WriteLine("-->> XSharpClassifier.ClassifyCompleted()"); if (e.Cancelled) { return; } if (e.Error == null) { var snapshot = e.Result as ITextSnapshot; if (snapshot != null) { triggerRepaint(snapshot); // if the buffer has changed in the mean time then restart the classification // because we have 'missed' the buffer_changed event because we were busy var newSnapshot = _buffer.CurrentSnapshot; if (newSnapshot.Version != snapshot.Version) { // buffer was changed, so restart try { _bwClassify.RunWorkerAsync(); } catch { } } else { triggerRepaint(snapshot); if (!_bwBuildModel.IsBusy) { _bwBuildModel.RunWorkerAsync(); } } } } System.Diagnostics.Trace.WriteLine("<<-- XSharpClassifier.ClassifyCompleted()"); } #endregion #region Parser Methods private void BuildModelDoWork(object sender, DoWorkEventArgs e) { if (disableEntityParsing) return; System.Diagnostics.Trace.WriteLine("-->> XSharpClassifier.BuildModelDoWork()"); // Note this runs in the background // parse for positional keywords that change the colors // and get a reference to the tokenstream // do we need to create a new tree // this happens the first time in the buffer only var snapshot = _buffer.CurrentSnapshot; ITokenStream tokens = null; ParseResult info; { Debug("Starting parse at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); var lines = new List<String>(); foreach (var line in snapshot.Lines) { lines.Add(line.GetText()); } info = _sourceWalker.Parse(lines, false); lock (gate) { _info = info; } Debug("Ending parse at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); } tokens = _tokens; if (info != null && tokens != null) { Debug("Starting model build at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); _sourceWalker.BuildModel(info); var regionTags = BuildRegionTags(info, snapshot, xsharpRegionStart, xsharpRegionStop); lock (gate) { _parserRegions = regionTags.ToArray(); } DoRepaintRegions(); Debug("Ending model build at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); } System.Diagnostics.Trace.WriteLine("<<-- XSharpClassifier.BuildModelDoWork()"); } #endregion private void DoRepaintRegions() { if (_buffer.Properties.ContainsProperty(typeof(XSharpOutliningTagger))) { var tagger = _buffer.Properties[typeof(XSharpOutliningTagger)] as XSharpOutliningTagger; tagger.Update(); } } public IList<ClassificationSpan> BuildRegionTags(XSharpModel.ParseResult info, ITextSnapshot snapshot, IClassificationType start, IClassificationType stop) { if (disableRegions) { return new List<ClassificationSpan>(); } System.Diagnostics.Trace.WriteLine("-->> XSharpClassifier.BuildRegionTags()"); var regions = new List<ClassificationSpan>(); var classList = new List<EntityObject>(); var propertyList = new List<EntityObject>(); if (info != null && snapshot != null) { // walk list of entities foreach (var oElement in info.Entities) { if (oElement.eType.NeedsEndKeyword()) { classList.Add(oElement); } if (oElement.eType == EntityType._Property) { if (oElement.oParent?.eType != EntityType._Interface) { // make sure we only push multi line properties var text = snapshot.GetLineFromPosition(oElement.nOffSet).GetText(); var substatements = text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var words = substatements[0].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); var singleLine = false; foreach (var word in words) { switch (word.ToLower()) { case "auto": case "get": case "set": singleLine = true; break; default: break; } } if (!singleLine) { propertyList.Add(oElement); } } } //else if (oElement.eType == EntityType._Property) //{ // classStack.Push(oElement); //} else if (oElement.eType.HasBody() || oElement.eType == EntityType._VOStruct || oElement.eType == EntityType._Union) { int nStart, nEnd; nStart = oElement.nOffSet; nEnd = oElement.nOffSet; var oNext = oElement.oNext; if (oElement.eType == EntityType._VOStruct || oElement.eType == EntityType._Union) { while (oNext != null && oNext.eType == EntityType._Field) { oNext = oNext.oNext; } } if (oNext != null) { var nLine = oNext.nStartLine; // our lines are 1 based and we want the line before, so -2 nEnd = snapshot.GetLineFromLineNumber(nLine - 2).Start; } else { if (oElement.oParent?.cName != XElement.GlobalName) { // find the endclass line after this element foreach (var oLine in info.SpecialLines) { if (oLine.eType == LineType.EndClass && oLine.Line > oElement.nStartLine) { var nLine = oLine.Line; // our lines are 1 based and we want the line before, so -2 nEnd = snapshot.GetLineFromLineNumber(nLine - 2).Start; break; } } } if (nEnd == nStart) { var nEndLine = snapshot.LineCount; // walk the special lines collection to see if there are any 'end' lines at the end of the file for (int i = info.SpecialLines.Count - 1; i >= 0; i--) { var oLine = info.SpecialLines[i]; switch (oLine.eType) { case LineType.EndNamespace: case LineType.EndClass: nEndLine = oLine.Line - 1; break; default: i = -1; // exit the loop break; } } // Our lines are 1 based, so subtract 1 nEnd = snapshot.GetLineFromLineNumber(nEndLine - 1).Start; } } if (nEnd > snapshot.Length) { nEnd = snapshot.Length; } AddRegionSpan(regions, snapshot, nStart, nEnd); } } } var blockStack = new Stack<LineObject>(); var nsStack = new Stack<LineObject>(); foreach (var oLine in info.SpecialLines) { int nStart = 0, nEnd = 0; switch (oLine.eType) { case LineType.BeginNamespace: nsStack.Push(oLine); break; case LineType.EndNamespace: if (nsStack.Count > 0) { var nsStart = nsStack.Pop(); nStart = nsStart.OffSet; nEnd = oLine.OffSet; AddRegionSpan(regions, snapshot, nStart, nEnd); } break; case LineType.EndClass: if (classList.Count > 0) { var cls = classList[0]; classList.RemoveAt(0); nStart = cls.nOffSet; nEnd = oLine.OffSet; AddRegionSpan(regions, snapshot, nStart, nEnd); } break; case LineType.EndProperty: if (propertyList.Count > 0) { var prop = propertyList[0]; propertyList.RemoveAt(0); nStart = prop.nOffSet; nEnd = oLine.OffSet; AddRegionSpan(regions, snapshot, nStart, nEnd); } break; case LineType.TokenIn: blockStack.Push(oLine); break; case LineType.TokenInOut: if (blockStack.Count > 0) { var blStart = blockStack.Peek(); // remove previous ELSEIF but not the IF if (blStart.eType == LineType.TokenInOut) { blockStack.Pop(); //} if (blStart.cArgument == "DO" || blStart.cArgument == "SWITCH") { // no contents before the first case ; } else { nStart = blStart.OffSet; // our lines are 1 based. // we do not want to include the next case line in the block from the previous one nEnd = snapshot.GetLineFromLineNumber(oLine.Line - 2).Start; AddRegionSpan(regions, snapshot, nStart, nEnd); } } } blockStack.Push(oLine); break; case LineType.TokenOut: if (blockStack.Count > 0) { // bop back to first token of the if .. endif or do case .. endcase while (blockStack.Count > 0 && blockStack.Peek().eType == LineType.TokenInOut) { var blStart = blockStack.Pop(); nStart = blStart.OffSet; nEnd = snapshot.GetLineFromLineNumber(oLine.Line - 2).Start; AddRegionSpan(regions, snapshot, nStart, nEnd); } if (blockStack.Count > 0) { var blStart = blockStack.Pop(); nStart = blStart.OffSet; // get position of the line based on the line number nEnd = snapshot.GetLineFromLineNumber(oLine.Line - 1).Start; AddRegionSpan(regions, snapshot, nStart, nEnd); } } break; default: break; } } System.Diagnostics.Trace.WriteLine("<<-- XSharpClassifier.BuildRegionTags()"); return regions; } private void AddRegionSpan(List<ClassificationSpan> regions, ITextSnapshot snapshot, int nStart, int nEnd) { try { TextSpan tokenSpan; ClassificationSpan span; int nLineLength = snapshot.GetLineFromPosition(nStart).Length; tokenSpan = new TextSpan(nStart, nLineLength); span = tokenSpan.ToClassificationSpan(snapshot, xsharpRegionStart); regions.Add(span); nLineLength = snapshot.GetLineFromPosition(nEnd).Length; if (nEnd + nLineLength >= snapshot.Length) { nLineLength = snapshot.Length - nEnd - 1; if (nLineLength < 0) nLineLength = 0; } tokenSpan = new TextSpan(nEnd, nLineLength); span = tokenSpan.ToClassificationSpan(snapshot, xsharpRegionStop); regions.Add(span); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error setting region: " + e.Message); } return; } /// <summary> /// Group several Tokens in a special span, specifying it's type /// </summary> /// <param name="start"></param> /// <param name="stop"></param> /// <param name="snapshot"></param> /// <param name="type"></param> /// <returns></returns> private ClassificationSpan Token2ClassificationSpan(IToken start, IToken stop, ITextSnapshot snapshot, IClassificationType type) { TextSpan tokenSpan = new TextSpan(start.StartIndex, stop.StopIndex - start.StartIndex + 1); ClassificationSpan span = tokenSpan.ToClassificationSpan(snapshot, type); return span; } /// <summary> /// "Mark" a Token, specifying it's type and the span it covers /// </summary> /// <param name="token"></param> /// <param name="snapshot"></param> /// <param name="type"></param> /// <returns></returns> private ClassificationSpan Token2ClassificationSpan(IToken token, ITextSnapshot snapshot, IClassificationType type) { TextSpan tokenSpan = new TextSpan(token.StartIndex, token.StopIndex - token.StartIndex + 1); ClassificationSpan span = tokenSpan.ToClassificationSpan(snapshot, type); return span; } private ClassificationSpan ClassifyToken(IToken token, IList<ClassificationSpan> regionTags, ITextSnapshot snapshot) { var tokenType = token.Type; ClassificationSpan result = null; switch (token.Channel) { case XSharpLexer.PRAGMACHANNEL: // #pragma case XSharpLexer.PREPROCESSORCHANNEL: // #define, #ifdef etc result = Token2ClassificationSpan(token, snapshot, xsharpPPType); switch (token.Type) { case XSharpLexer.PP_REGION: case XSharpLexer.PP_IFDEF: case XSharpLexer.PP_IFNDEF: regionTags.Add(Token2ClassificationSpan(token, snapshot, xsharpRegionStart)); break; case XSharpLexer.PP_ENDREGION: case XSharpLexer.PP_ENDIF: regionTags.Add(Token2ClassificationSpan(token, snapshot, xsharpRegionStop)); break; default: break; } break; case XSharpLexer.DEFOUTCHANNEL: // code in an inactive #ifdef result = Token2ClassificationSpan(token, snapshot, xsharpInactiveType); break; case XSharpLexer.XMLDOCCHANNEL: case XSharpLexer.Hidden: if (XSharpLexer.IsComment(token.Type)) { result = Token2ClassificationSpan(token, snapshot, xsharpCommentType); if (token.Type == XSharpLexer.ML_COMMENT && token.Text.IndexOf("\r") >= 0) { regionTags.Add(Token2ClassificationSpan(token, snapshot, xsharpRegionStart)); regionTags.Add(Token2ClassificationSpan(token, snapshot, xsharpRegionStop)); } } break; default: // Normal channel IClassificationType type = null; if (XSharpLexer.IsIdentifier(tokenType)) { type = xsharpIdentifierType; } else if (XSharpLexer.IsConstant(tokenType)) { switch (tokenType) { case XSharpLexer.STRING_CONST: case XSharpLexer.CHAR_CONST: case XSharpLexer.ESCAPED_STRING_CONST: case XSharpLexer.INTERPOLATED_STRING_CONST: type = xsharpStringType; break; case XSharpLexer.FALSE_CONST: case XSharpLexer.TRUE_CONST: type = xsharpKeywordType; break; case XSharpLexer.VO_AND: case XSharpLexer.VO_NOT: case XSharpLexer.VO_OR: case XSharpLexer.VO_XOR: case XSharpLexer.SYMBOL_CONST: case XSharpLexer.NIL: type = xsharpLiteralType; break; default: if ((tokenType >= XSharpLexer.FIRST_NULL) && (tokenType <= XSharpLexer.LAST_NULL)) { type = xsharpKeywordType; break; } else type = xsharpNumberType; break; } } else if (XSharpLexer.IsKeyword(tokenType)) { type = xsharpKeywordType; } else if (XSharpLexer.IsOperator(tokenType)) { switch (tokenType) { case XSharpLexer.LPAREN: case XSharpLexer.LCURLY: case XSharpLexer.LBRKT: type = xsharpBraceOpenType; break; case XSharpLexer.RPAREN: case XSharpLexer.RCURLY: case XSharpLexer.RBRKT: type = xsharpBraceCloseType; break; default: type = xsharpOperatorType; break; } } if (type != null) { result = Token2ClassificationSpan(token, snapshot, type); } break; } return result; } private ClassificationSpan ClassifyKeyword(IToken token, ITextSnapshot snapshot) { var tokenType = token.Type; ClassificationSpan result = null; IClassificationType type = null; IToken startToken = null; if (keywordContext != null) { startToken = keywordContext; if (startToken.Line != token.Line) { keywordContext = null; startToken = null; } } // switch (tokenType) { case XSharpLexer.DO: if (startToken != null) { if (startToken.Type == XSharpLexer.END) type = xsharpKwCloseType; else startToken = null; } else keywordContext = token; break; case XSharpLexer.BEGIN: keywordContext = token; //type = xsharpKwOpenType; break; case XSharpLexer.SWITCH: type = xsharpKwOpenType; if (startToken != null) if (startToken.Type == XSharpLexer.END) type = xsharpKwCloseType; else if ((startToken.Type != XSharpLexer.DO) || (startToken.Type != XSharpLexer.BEGIN)) startToken = null; break; case XSharpLexer.TRY: case XSharpLexer.IF: type = xsharpKwOpenType; if (startToken != null) if (startToken.Type == XSharpLexer.END) type = xsharpKwCloseType; else startToken = null; break; case XSharpLexer.WHILE: type = xsharpKwOpenType; if (startToken != null) if (startToken.Type == XSharpLexer.END) type = xsharpKwCloseType; else if (startToken.Type != XSharpLexer.DO) startToken = null; break; case XSharpLexer.CASE: if (startToken != null) if (startToken.Type == XSharpLexer.DO) type = xsharpKwOpenType; else if (startToken.Type == XSharpLexer.END) type = xsharpKwCloseType; break; case XSharpLexer.FOR: case XSharpLexer.FOREACH: case XSharpLexer.REPEAT: startToken = null; type = xsharpKwOpenType; break; case XSharpLexer.NEXT: case XSharpLexer.UNTIL: case XSharpLexer.ENDDO: case XSharpLexer.ENDIF: case XSharpLexer.ENDCASE: startToken = null; type = xsharpKwCloseType; break; case XSharpLexer.END: keywordContext = token; //type = xsharpKwCloseType; break; } // if (type != null) { if (startToken != null) result = Token2ClassificationSpan(startToken, token, snapshot, type); else result = Token2ClassificationSpan(token, snapshot, type); } return result; } private void scanForRegion(IToken token, int iToken, ITokenStream TokenStream, ref int iLast, ITextSnapshot snapshot, IList<ClassificationSpan> regionTags) { if (iToken > iLast) { var lastToken = ScanForLastToken(token.Type, iToken, TokenStream, out iLast); if (token != lastToken) { regionTags.Add(Token2ClassificationSpan(token, snapshot, xsharpRegionStart)); regionTags.Add(Token2ClassificationSpan(lastToken, snapshot, xsharpRegionStop)); } } } private void BuildColorClassifications(ITokenStream tokenStream, ITextSnapshot snapshot) { Debug("Start building Classifications at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); XClassificationSpans newtags; var regionTags = new List<ClassificationSpan>(); if (tokenStream != null) { int iLastInclude = -1; int iLastPPDefine = -1; int iLastDefine = -1; int iLastSLComment = -1; int iLastDocComment = -1; int iLastUsing = -1; newtags = new XClassificationSpans(); keywordContext = null; for (var iToken = 0; iToken < tokenStream.Size; iToken++) { var token = tokenStream.Get(iToken); // Orphan End ? if ((keywordContext != null) && (keywordContext.Line != token.Line) && (keywordContext.Type == XSharpLexer.END)) { newtags.Add(Token2ClassificationSpan(keywordContext, snapshot, xsharpKwCloseType)); keywordContext = null; } var span = ClassifyToken(token, regionTags, snapshot); if (span != null) { newtags.Add(span); // We can have some Open/Close keyword ( FOR..NEXT; WHILE...ENDDO; IF...ENDIF) if (span.ClassificationType == xsharpKeywordType) { span = ClassifyKeyword(token, snapshot); if (span != null) { newtags.Add(span); } } if (!disableRegions) { // now look for Regions of similar code lines switch (token.Type) { case XSharpLexer.PP_INCLUDE: scanForRegion(token, iToken, tokenStream, ref iLastInclude, snapshot, regionTags); break; case XSharpLexer.PP_DEFINE: scanForRegion(token, iToken, tokenStream, ref iLastPPDefine, snapshot, regionTags); break; case XSharpLexer.DEFINE: scanForRegion(token, iToken, tokenStream, ref iLastDefine, snapshot, regionTags); break; case XSharpLexer.SL_COMMENT: scanForRegion(token, iToken, tokenStream, ref iLastSLComment, snapshot, regionTags); break; case XSharpLexer.DOC_COMMENT: scanForRegion(token, iToken, tokenStream, ref iLastDocComment, snapshot, regionTags); break; case XSharpLexer.USING: scanForRegion(token, iToken, tokenStream, ref iLastUsing, snapshot, regionTags); break; default: break; } } } } // Orphan End ? if ((keywordContext != null) && (keywordContext.Type == XSharpLexer.END)) { newtags.Add(Token2ClassificationSpan(keywordContext, snapshot, xsharpKwCloseType)); keywordContext = null; } } else { newtags = _colorTags; } System.Diagnostics.Trace.WriteLine("-->> XSharpClassifier.BuildColorClassifications()"); lock (gate) { _snapshot = snapshot; _colorTags = newtags; _lexerRegions = regionTags; } System.Diagnostics.Trace.WriteLine("<<-- XSharpClassifier.BuildColorClassifications()"); Debug("End building Classifications at {0}, version {1}", DateTime.Now, snapshot.Version.ToString()); triggerRepaint(snapshot); } IToken ScanForLastToken(int type, int start, ITokenStream TokenStream, out int iLast) { var lastFound = TokenStream.Get(start); int iLine = lastFound.Line; iLast = start; IToken nextToken = lastFound; IToken nextToken2 = lastFound; for (int i = start + 1; i < TokenStream.Size - 2; i++) { nextToken = TokenStream.Get(i); nextToken2 = TokenStream.Get(i + 2); // STATIC <WS> DEFINE for example. if (nextToken.Line > iLine) { if (nextToken.Type == type || (nextToken2.Type == type && nextToken.Type == XSharpLexer.STATIC)) { lastFound = nextToken; iLine = nextToken.Line; iLast = i; } else if (nextToken.Type != XSharpLexer.WS) { break; } } } nextToken = lastFound; for (int i = iLast; i < TokenStream.Size; i++) { nextToken = TokenStream.Get(i); if (nextToken.Line == lastFound.Line && nextToken.Type != XSharpLexer.NL && nextToken.Type != XSharpLexer.EOS) lastFound = nextToken; else break; } return lastFound; } public IList<ClassificationSpan> GetRegionTags() { System.Diagnostics.Trace.WriteLine("-->> XSharpClassifier.GetRegionTags()"); IList<ClassificationSpan> result; lock (gate) { if (_parserRegions != null) { var list = _parserRegions.ToList(); if (_lexerRegions != null) list.AddRange(_lexerRegions); result = list; ; } else if (_lexerRegions != null) { result = _lexerRegions; } else { result = new List<ClassificationSpan>(); } } System.Diagnostics.Trace.WriteLine("<<-- XSharpClassifier.GetRegionTags()"); return result; } public IList<ClassificationSpan> GetTags() { System.Diagnostics.Trace.WriteLine("-->> XSharpClassifier.GetTags()"); IList<ClassificationSpan> ret; lock (gate) { ret = _colorTags.Tags; } System.Diagnostics.Trace.WriteLine("<<-- XSharpClassifier.GetTags()"); return ret; } #region IClassifier #pragma warning disable 67 /// <summary> /// An event that occurs when the classification of a span of text has changed. /// </summary> /// <remarks> /// This event gets raised if a non-text change would affect the classification in some way, /// for example typing /* would cause the classification to change in C# without directly /// affecting the span. /// </remarks> public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged; #pragma warning restore 67 /// <summary> /// Gets all the <see cref="ClassificationSpan"/> objects that intersect with the given range of text. /// </summary> /// <remarks> /// This method scans the given SnapshotSpan for potential matches for this classification. /// In this instance, it classifies everything and returns each span as a new ClassificationSpan. /// </remarks> /// <param name="span">The span currently being classified.</param> /// <returns>A list of ClassificationSpans that represent spans identified to be of this classification.</returns> public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) { // Todo: // We can probably avoid building all tags in BuildColorClassifications. // and directly create the necessary tags here from the List<XSharpToken> // In that case we need to keep a reference to the tokenstream in stead of the tags // There also must be a smart way to find the first matching tag. var result = new List<ClassificationSpan>(); var tags = _colorTags; if (tags.Count == 0) return result; int iStart = span.Start.GetContainingLine().LineNumber; int iEnd = span.End.GetContainingLine().LineNumber; for (int i = iStart; i <= iEnd; i++) { var tagsForLine = tags.GetItemsForLine(i); // Use the Span.Span property to avoid the check for the same Snapshot if (tagsForLine != null) { result.AddRange(tagsForLine); } } return result; } #endregion static internal XSharpClassifier GetColorizer(ITextBuffer buffer, IClassificationTypeRegistryService registry, ITextDocumentFactoryService factory) { XSharpClassifier colorizer = buffer.Properties.GetOrCreateSingletonProperty( () => new XSharpClassifier(buffer, registry, factory)); return colorizer; } internal static void Debug(string msg, params object[] o) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debug.WriteLine(String.Format("XColorizer: " + msg, o)); #endif } } internal class XClassificationSpans { private IList<ClassificationSpan> _tags; private readonly object gate = new object(); private IDictionary<int, List<ClassificationSpan>> _hash; private IList<ClassificationSpan> _multilineTokens; internal XClassificationSpans() { lock (gate) { _tags = new List<ClassificationSpan>(); _hash = new Dictionary<int, List<ClassificationSpan>>(); _multilineTokens = new List<ClassificationSpan>(); } } internal void Add(ClassificationSpan span) { lock (gate) { _tags.Add(span); int start = span.Span.Start.GetContainingLine().LineNumber; int end = span.Span.End.GetContainingLine().LineNumber; if (end > start + 1) { _multilineTokens.Add(span); } else { if (!_hash.ContainsKey(start)) { _hash.Add(start, new List<ClassificationSpan>()); } _hash[start].Add(span); } } } internal List<ClassificationSpan> GetItemsForLine(int line) { lock (gate) { List<ClassificationSpan> result; { if (_hash.ContainsKey(line)) { result = _hash[line]; } else { result = new List<ClassificationSpan>(); } } if (_multilineTokens.Count > 0) { List<ClassificationSpan> multi = null; foreach (var span in _multilineTokens) { if (span.Span.Start.GetContainingLine().LineNumber <= line && span.Span.End.GetContainingLine().LineNumber >= line) { if (multi == null) multi = new List<ClassificationSpan>(); multi.Add(span); } } if (multi?.Count > 0) { if (result.Count == 0) { result = multi; } else { multi.AddRange(result); result = multi; } } } return result; } } internal int Count { get { lock (gate) { return _tags.Count; } } } internal void Clear() { lock (gate) { _tags.Clear(); _hash.Clear(); } } internal IList<ClassificationSpan> Tags { get { lock (gate) { var tags = new ClassificationSpan[_tags.Count]; _tags.CopyTo(tags, 0); return tags; } } } } }
42.919244
163
0.465071
[ "Apache-2.0" ]
JohanNel/XSharpPublic
VisualStudio/XSharpColorizer/XSharpClassifier.cs
49,960
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovementController : MonoBehaviour { public int playernumber = 1; private float running; private float defaultSpeed = 3.0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { float speed = this.defaultSpeed; Vector3 newPos = new Vector3( speed * Time.deltaTime * Input.GetAxis("Horizontal_" + this.playernumber), 0, speed * Time.deltaTime * Input.GetAxis("Vertical_" + this.playernumber) ); transform.position += newPos; } }
24.851852
86
0.642325
[ "MIT" ]
sakulstra/tower_defense
Assets/Scripts/MovementController.cs
673
C#
using System; namespace Server.Items { public class StatuetteDyeTub : DyeTub, Engines.VeteranRewards.IRewardItem { public override bool AllowDyables{ get{ return false; } } public override bool AllowStatuettes{ get{ return true; } } public override int TargetMessage{ get{ return 1049777; } } // Target the statuette to dye public override int FailMessage{ get{ return 1049778; } } // You can only dye veteran reward statuettes with this tub. public override int LabelNumber{ get{ return 1049741; } } // Reward Statuette Dye Tub public override CustomHuePicker CustomHuePicker{ get{ return CustomHuePicker.LeatherDyeTub; } } private bool m_IsRewardItem; [CommandProperty( AccessLevel.GameMaster )] public bool IsRewardItem { get{ return m_IsRewardItem; } set{ m_IsRewardItem = value; } } [Constructable] public StatuetteDyeTub() { LootType = LootType.Blessed; } public override void OnDoubleClick( Mobile from ) { if ( m_IsRewardItem && !Engines.VeteranRewards.RewardSystem.CheckIsUsableBy( from, this, null ) ) return; base.OnDoubleClick( from ); } public StatuetteDyeTub( Serial serial ) : base( serial ) { } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( Core.ML && m_IsRewardItem ) list.Add( 1076221 ); // 5th Year Veteran Reward } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version writer.Write( (bool) m_IsRewardItem ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { m_IsRewardItem = reader.ReadBool(); break; } } } } }
24.337838
120
0.695169
[ "BSD-2-Clause" ]
greeduomacro/vivre-uo
Scripts/Items/Skill Items/Tailor Items/Dyetubs/StatuetteDyeTub.cs
1,801
C#
using JobTrackingProject.Entities.Concrete; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JobTrackingProject.Web { public class IdenitiyInitializer { public static async Task SeedData(UserManager<AppUser> userManager,RoleManager<AppRole> roleManager) { var adminRole = await roleManager.FindByNameAsync("Admin"); if (adminRole == null) { AppRole role = new AppRole { Name = "Admin" }; await roleManager.CreateAsync(role); } var memberRole = await roleManager.FindByNameAsync("Member"); if (memberRole == null) { AppRole role = new AppRole { Name = "Member" }; await roleManager.CreateAsync(role); } var adminUser = await userManager.FindByNameAsync("enesaliovur"); if (adminUser == null) { AppUser user = new AppUser { Name = "Enes Ali", Surname = "Övür", UserName = "enesaliovur", Email = "enesaliovur@gmail.com" }; await userManager.CreateAsync(user,"1"); await userManager.AddToRoleAsync(user, "Admin"); } } } }
29.188679
108
0.501616
[ "MIT" ]
enesaliovur/JobTrackingProject
JobTrackingProject.Web/IdenitiyInitializer.cs
1,551
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace Common { public interface IPersonRepository { IEnumerable<Person> GetPeople(); Person GetPerson(int id); } }
17.75
40
0.690141
[ "MIT" ]
PeterPartridge/LearningInterfaces
07/demos/after/LooseCoupling/Common/IPersonRepository.cs
215
C#
using DomainCore.Entities; using InfraCore.Mapping; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace InfraCore.Context.Commands { public class CommandsDbContext : DbContext { public DbSet<Produto> Produtos { get; set; } public DbSet<Orcamento> Orcamentos { get; set; } public DbSet<Parcela> Parcelas { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) optionsBuilder.UseSqlServer("Data Source=DESKTOP-DJAK16E;Initial Catalog=Commands;integrated security=True;multipleactiveresultsets=True"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Produto>(new ProdutoMap().Configure); modelBuilder.Entity<Orcamento>(new OrcamentoMap().Configure); modelBuilder.Entity<Parcela>(new ParcelaMap().Configure); } } }
30.361111
155
0.694419
[ "MIT" ]
CristianoDevNet/Parcelamentos
ParcelamentosAPI/InfraCore/Context/Commands/CommandsDbContext.cs
1,095
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AMPS.forms { public partial class Home : Form { public Home() { InitializeComponent(); } private void MnuAdd_Click_1(object sender, EventArgs e) { Department de = new Department(); de.Show(); } private void calculationOfWagesToolStripMenuItem_Click(object sender, EventArgs e) { FormPhilHealth frm = new FormPhilHealth(); frm.Show(); } private void MnuMonthlyReport_Click(object sender, EventArgs e) { forms.FormPagIbig pag = new FormPagIbig(); pag.Show(); } private void MnuPositionInformation_Click(object sender, EventArgs e) { FormPositions pos = new FormPositions(); pos.Show(); } private void MnuSelectiveServiceSystem_Click(object sender, EventArgs e) { FormSSS ss = new FormSSS(); ss.Show(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } } }
24.196429
90
0.591144
[ "MIT" ]
koorsha/Corporate-staff-management
amps/AMPS/forms/Home.cs
1,357
C#
using System; using System.Collections.Generic; using System.Linq; using static Dbref; using static ForthDatum; using static ForthPrimativeResult; public static class MathSubtract { public static ForthPrimativeResult Execute(ForthPrimativeParameters parameters) { /* - ( n1 n2 -- i ) This subtracts two numbers, n1 - n2. If both numbers are integers, an integer will be returned. If one of them is a floating point number, then a float will be returned. You can also use this on a dbref or a variable number, so long as the second argument is an integer. In those cases, this will return a dbref or variable number, respectively. */ if (parameters.Stack.Count < 2) return new ForthPrimativeResult(ForthErrorResult.STACK_UNDERFLOW, "- requires two parameters"); var n2 = parameters.Stack.Pop(); var n1 = parameters.Stack.Pop(); if (n1.Type == DatumType.Integer && n2.Type == DatumType.Integer) { parameters.Stack.Push(new ForthDatum(n1.UnwrapInt() - n2.UnwrapInt())); return ForthPrimativeResult.SUCCESS; } if ((n1.Type == DatumType.Integer || n1.Type == DatumType.Float) && (n2.Type == DatumType.Integer || n2.Type == DatumType.Float)) { parameters.Stack.Push(new ForthDatum(Convert.ToSingle(n1.Value) - Convert.ToSingle(n2.Value))); return ForthPrimativeResult.SUCCESS; } if (n1.Type == DatumType.DbRef || n2.Type == DatumType.Integer) { var n1v = n1.UnwrapDbref().ToInt32(); var n2v = n2.UnwrapInt(); if (n2v == 0) return new ForthPrimativeResult(ForthErrorResult.DIVISION_BY_ZERO, "Attempt to divide by zero was aborted"); parameters.Stack.Push(new ForthDatum(new Dbref(n1v - n2v, DbrefObjectType.Thing), 0)); return ForthPrimativeResult.SUCCESS; } return new ForthPrimativeResult(ForthErrorResult.TYPE_MISMATCH, "- expects integers or floating point numbers, or no more than one dbref and an integer"); // TODO: We do not support variable numbers today. They're depreciated anyway. } }
41.12963
162
0.652859
[ "MIT" ]
eumario/moo
moo.common/Scripting/ForthPrimatives/MathSubtract.cs
2,221
C#
using Klli.Sensact.Config.Nodes; using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Klli.Sensact.Config.Applications { public class StandbyControllerApplication : ActorApplication { public ushort OutputRessource; public long WaittimeInMsec; [SensactCommandMethod] public override void OnHEARTBEATCommand(uint sender) { base.OnHEARTBEATCommand(sender); } internal override string CheckAndAddUsedPins(HashSet<string> usedInputPins, HashSet<string> usedOutputPins) { if (usedOutputPins.Contains(OutputRessource.ToString())) { return "OutputRessource"; } usedOutputPins.Add(OutputRessource.ToString()); return null; } public override HashSet<EventType> ICanSendTheseEvents() { return new HashSet<EventType>(); } public override string GenerateInitializer(ModelContainer m) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("// STDBY {0}" + Environment.NewLine, ApplicationId); sb.AppendFormat("sensact::cStandbyController {0}(eApplicationID::{0}, {1}, {2});" + Environment.NewLine + Environment.NewLine, ApplicationId, OutputRessource, WaittimeInMsec); return sb.ToString(); } internal override Regex AppIdRegex { get { return new Regex("STDBY"+REGEX_FLOOR_ROOM_SUFFIX); } } } }
30.396226
187
0.621974
[ "Apache-2.0" ]
klaus-liebler/sensact
configware/Klli.Sensact.Config/Applications/StandbyControllerApplication.cs
1,613
C#
#region Using directives using SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using SimpleFramework.Xml; using System; #endregion namespace SimpleFramework.Xml.Core { public class PrimitiveKeyTest : TestCase { private static class MockElementMap : ElementMap { private bool attribute; private bool data; private String entry; private bool inline; private String key; private Class keyType; private String name; private bool required; private String value; private Class valueType; public MockElementMap( bool attribute, bool data, String entry, bool inline, String key, Class keyType, String name, bool required, String value, Class valueType) { this.attribute = attribute; this.data = data; this.entry = entry; this.inline = inline; this.key = key; this.keyType = keyType; this.name = name; this.required = required; this.value = value; this.valueType = valueType; } public bool Empty() { return true; } public bool Attribute() { return attribute; } public bool Data() { return data; } public String Entry() { return entry; } public bool Inline() { return inline; } public String Key() { return key; } public Class KeyType() { return keyType; } public String Name() { return name; } public bool Required() { return required; } public String Value() { return value; } public double Since() { return 1.0; } public Class ValueType() { return valueType; } public Class<? : Annotation> annotationType() { return ElementMap.class; } } private static class PrimitiveType { private MockElementMap map; private String string; private int number; private byte octet; public PrimitiveType(MockElementMap map) { this.map = map; } public Contact String { get { return new FieldContact(PrimitiveType.class.getDeclaredField("string"), map); } } //public Contact GetString() { // return new FieldContact(PrimitiveType.class.getDeclaredField("string"), map); //} return new FieldContact(PrimitiveType.class.getDeclaredField("number"), map); } public Contact Octet { get { return new FieldContact(PrimitiveType.class.getDeclaredField("octet"), map); } } //public Contact GetOctet() { // return new FieldContact(PrimitiveType.class.getDeclaredField("octet"), map); //} public void TestInlineString() { { Source source = new Source(new TreeStrategy(), new Support(), new DefaultStyle()); MockElementMap map = new MockElementMap(true, // attribute false, // data "entry", // entry true, // inline "key", // key String.class, // keyType "name", // name true, // required "value", // value String.class); // valueType PrimitiveType type = new PrimitiveType(map); Contact string = type.String; Entry entry = new Entry(string, map); PrimitiveKey value = new PrimitiveKey(source, entry, new ClassType(String.class)); OutputNode node = NodeBuilder.write(new PrintWriter(System.out)); value.write(node.getChild("inlineString"), "example"); node.commit(); } public void TestNotInlineString() { { Source source = new Source(new TreeStrategy(), new Support(), new DefaultStyle()); MockElementMap map = new MockElementMap(false, // attribute false, // data "entry", // entry true, // inline "key", // key String.class, // keyType "name", // name true, // required "value", // value String.class); // valueType PrimitiveType type = new PrimitiveType(map); Contact string = type.String; Entry entry = new Entry(string, map); PrimitiveKey value = new PrimitiveKey(source, entry, new ClassType(String.class)); OutputNode node = NodeBuilder.write(new PrintWriter(System.out)); value.write(node.getChild("notInlineString"), "example"); node.commit(); } public void TestNoAttributeString() { { Source source = new Source(new TreeStrategy(), new Support(), new DefaultStyle()); MockElementMap map = new MockElementMap(false, // attribute false, // data "entry", // entry true, // inline "", // key String.class, // keyType "name", // name true, // required "value", // value String.class); // valueType PrimitiveType type = new PrimitiveType(map); Contact string = type.String; Entry entry = new Entry(string, map); PrimitiveKey value = new PrimitiveKey(source, entry, new ClassType(String.class)); OutputNode node = NodeBuilder.write(new PrintWriter(System.out)); value.write(node.getChild("noAttributeString"), "example"); node.commit(); } public void TestAttributeNoKeyString() { { Source source = new Source(new TreeStrategy(), new Support(), new DefaultStyle()); MockElementMap map = new MockElementMap(true, // attribute false, // data "entry", // entry true, // inline "", // key String.class, // keyType "name", // name true, // required "value", // value String.class); // valueType PrimitiveType type = new PrimitiveType(map); Contact string = type.String; Entry entry = new Entry(string, map); PrimitiveKey value = new PrimitiveKey(source, entry, new ClassType(String.class)); OutputNode node = NodeBuilder.write(new PrintWriter(System.out)); value.write(node.getChild("attributeNoKeyString"), "example"); node.commit(); } } }
41.589744
92
0.450555
[ "Apache-2.0" ]
AMCON-GmbH/simplexml
port/src/main/Xml/Core/PrimitiveKeyTest.cs
8,110
C#
using System; using NUnit.Framework; using SharpOAuth2.Framework; using SharpOAuth2.Provider.Framework; using SharpOAuth2.Provider.TokenEndpoint; namespace SharpOAuth2.Tests.Provider.TokenEndpoint.Inspectors { public abstract class InspectorTestBase { public void CommonAssertInspector(IContextInspector<ITokenContext> inspector, ITokenContext ctx) { try { inspector.Inspect(ctx); Assert.Fail("No Exception was thrown"); } catch (OAuthErrorResponseException<ITokenContext> x) { Assert.AreEqual(Parameters.ErrorParameters.ErrorValues.InvalidRequest, x.Error); } catch (Exception x) { Assert.Fail(x.Message); } } } }
27.533333
104
0.610169
[ "Unlicense" ]
ghorsey/SharpOAuth2
code/src/SharpOAuth2.Tests/Provider/TokenEndpoint/Inspectors/InspectorTestBase.cs
828
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DocumentDB.V20210701Preview.Inputs { /// <summary> /// Cosmos DB Cassandra table resource object /// </summary> public sealed class CassandraTableResourceArgs : Pulumi.ResourceArgs { /// <summary> /// Analytical TTL. /// </summary> [Input("analyticalStorageTtl")] public Input<int>? AnalyticalStorageTtl { get; set; } /// <summary> /// Time to live of the Cosmos DB Cassandra table /// </summary> [Input("defaultTtl")] public Input<int>? DefaultTtl { get; set; } /// <summary> /// Name of the Cosmos DB Cassandra table /// </summary> [Input("id", required: true)] public Input<string> Id { get; set; } = null!; /// <summary> /// Schema of the Cosmos DB Cassandra table /// </summary> [Input("schema")] public Input<Inputs.CassandraSchemaArgs>? Schema { get; set; } public CassandraTableResourceArgs() { } } }
28.723404
81
0.602222
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DocumentDB/V20210701Preview/Inputs/CassandraTableResourceArgs.cs
1,350
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading; using System.Threading.Tasks; using Ditch.Core; using Ditch.Core.JsonRpc; using Newtonsoft.Json; using Steepshot.Core.Authorization; using Steepshot.Core.Models.Common; using Steepshot.Core.Models.Enums; using Steepshot.Core.Models.Requests; using Steepshot.Core.Models.Responses; using Steepshot.Core.Utils; namespace Steepshot.Core.Clients { public abstract class BaseServerClient { public bool EnableRead; public ExtendedHttpClient HttpClient; protected string BaseUrl; #region Get requests public async Task<OperationResult<ListResponse<Post>>> GetUserPosts(UserPostsModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<Post>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); AddLoginParameter(parameters, model.Login); AddCensorParameters(parameters, model); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/user/{model.Username}/posts"; return await HttpClient.Get<ListResponse<Post>>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<Post>>> GetUserRecentPosts(CensoredNamedRequestWithOffsetLimitModel request, CancellationToken token) { if (!EnableRead) return null; var results = Validate(request); if (results != null) return new OperationResult<ListResponse<Post>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, request.Offset, request.Limit); AddLoginParameter(parameters, request.Login); AddCensorParameters(parameters, request); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/recent"; return await HttpClient.Get<ListResponse<Post>>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<Post>>> GetPosts(PostsModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<Post>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); AddLoginParameter(parameters, model.Login); AddCensorParameters(parameters, model); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/posts/{model.Type.ToString().ToLowerInvariant()}"; return await HttpClient.Get<ListResponse<Post>>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<Post>>> GetPostsByCategory(PostsByCategoryModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<Post>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); AddLoginParameter(parameters, model.Login); AddCensorParameters(parameters, model); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/posts/{model.Category}/{model.Type.ToString().ToLowerInvariant()}"; return await HttpClient.Get<ListResponse<Post>>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<UserFriend>>> GetPostVoters(VotersModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<UserFriend>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); AddVotersTypeParameters(parameters, model.Type); if (!string.IsNullOrEmpty(model.Login)) AddLoginParameter(parameters, model.Login); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/post/{model.Url}/voters"; return await HttpClient.Get<ListResponse<UserFriend>>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<Post>>> GetComments(NamedInfoModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<Post>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); AddLoginParameter(parameters, model.Login); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/post/{model.Url}/comments"; var resp = await HttpClient.Get<ListResponse<Post>>(endpoint, parameters, token); if (resp.IsSuccess) resp.Result.Results.ForEach(p => p.IsComment = true); return resp; } public async Task<OperationResult<UserProfileResponse>> GetUserProfile(UserProfileModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<UserProfileResponse>(results); var parameters = new Dictionary<string, object>(); AddLoginParameter(parameters, model.Login); parameters.Add("show_nsfw", Convert.ToInt32(model.ShowNsfw)); parameters.Add("show_low_rated", Convert.ToInt32(model.ShowLowRated)); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/user/{model.Username}/info"; return await HttpClient.Get<UserProfileResponse>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<UserFriend>>> GetUserFriends(UserFriendsModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<UserFriend>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); AddLoginParameter(parameters, model.Login); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/user/{model.Username}/{model.Type.ToString().ToLowerInvariant()}"; return await HttpClient.Get<ListResponse<UserFriend>>(endpoint, parameters, token); } public async Task<OperationResult<Post>> GetPostInfo(NamedInfoModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<Post>(results); var parameters = new Dictionary<string, object>(); AddLoginParameter(parameters, model.Login); AddCensorParameters(parameters, model); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/post/{model.Url}/info"; return await HttpClient.Get<Post>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<UserFriend>>> SearchUser(SearchWithQueryModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<UserFriend>>(results); var parameters = new Dictionary<string, object>(); AddLoginParameter(parameters, model.Login); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); parameters.Add("query", model.Query); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/user/search"; return await HttpClient.Get<ListResponse<UserFriend>>(endpoint, parameters, token); } public async Task<OperationResult<UserExistsResponse>> UserExistsCheck(UserExistsModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<UserExistsResponse>(results); var parameters = new Dictionary<string, object>(); var endpoint = $"{BaseUrl}/{GatewayVersion.V1}/user/{model.Username}/exists"; return await HttpClient.Get<UserExistsResponse>(endpoint, parameters, token); } public async Task<OperationResult<ListResponse<SearchResult>>> GetCategories(OffsetLimitModel request, CancellationToken token) { if (!EnableRead) return null; var results = Validate(request); if (results != null) return new OperationResult<ListResponse<SearchResult>>(results); var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, request.Offset, request.Limit); var endpoint = $"{BaseUrl}/{GatewayVersion.V1}/categories/top"; var result = await HttpClient.Get<ListResponse<SearchResult>>(endpoint, parameters, token); if (result.IsSuccess) { foreach (var category in result.Result.Results) { category.Name = Transliteration.ToRus(category.Name); } } return result; } public async Task<OperationResult<ListResponse<SearchResult>>> SearchCategories(SearchWithQueryModel model, CancellationToken token) { if (!EnableRead) return null; var results = Validate(model); if (results != null) return new OperationResult<ListResponse<SearchResult>>(results); var query = Transliteration.ToEng(model.Query); if (query != model.Query) { query = $"ru--{query}"; } model.Query = query; var parameters = new Dictionary<string, object>(); AddOffsetLimitParameters(parameters, model.Offset, model.Limit); parameters.Add("query", model.Query); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/categories/search"; var result = await HttpClient.Get<ListResponse<SearchResult>>(endpoint, parameters, token); if (result.IsSuccess) { foreach (var categories in result.Result.Results) { categories.Name = Transliteration.ToRus(categories.Name); } } return result; } protected async Task<OperationResult<VoidResponse>> Trace(string endpoint, string login, Exception resultException, string target, CancellationToken token) { if (!EnableRead) return null; try { var parameters = new Dictionary<string, object>(); AddLoginParameter(parameters, login); parameters.Add("error", resultException == null ? string.Empty : resultException.Message); if (!string.IsNullOrEmpty(target)) parameters.Add("target", target); endpoint = $"{BaseUrl}/{GatewayVersion.V1}/log/{endpoint}"; var result = await HttpClient.Put<VoidResponse, Dictionary<string, object>>(endpoint, parameters, token); if (result.IsSuccess) result.Result = new VoidResponse(); return result; } catch (Exception ex) { await AppSettings.Logger.Warning(ex); } return null; } public async Task<OperationResult<BeneficiariesResponse>> GetBeneficiaries(CancellationToken token) { if (!EnableRead) return null; var endpoint = $"{BaseUrl}/{GatewayVersion.V1}/beneficiaries"; return await HttpClient.Get<BeneficiariesResponse>(endpoint, token); } public async Task<OperationResult<SpamResponse>> CheckForSpam(string username, CancellationToken token) { if (!EnableRead) return null; var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/user/{username}/spam"; var result = await HttpClient.Get<SpamResponse>(endpoint, token); return result; } public async Task<OperationResult<CurrencyRate[]>> GetCurrencyRates(CancellationToken token) { if (!EnableRead) return null; var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/currency/rates"; var result = await HttpClient.Get<CurrencyRate[]>(endpoint, token); return result; } #endregion Get requests public async Task<OperationResult<PreparePostResponse>> PreparePost(PreparePostModel model, CancellationToken ct) { var results = Validate(model); if (results != null) return new OperationResult<PreparePostResponse>(results); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/post/prepare"; return await HttpClient.Put<PreparePostResponse, PreparePostModel>(endpoint, model, ct); } public async Task<OperationResult<CreateAccountResponse>> CreateAccount(CreateAccountModel model, CancellationToken token) { var endpoint = "https://createacc.steepshot.org/api/v1/account"; return await HttpClient.Post<CreateAccountResponse, CreateAccountModel>(endpoint, model, token); } public async Task<OperationResult<CreateAccountResponse>> ResendEmail(CreateAccountModel model, CancellationToken token) { var endpoint = "https://createacc.steepshot.org/api/v1/resend-mail"; return await HttpClient.Post<CreateAccountResponse, CreateAccountModel>(endpoint, model, token); } public async Task<OperationResult<string>> CheckRegistrationServiceStatus(CancellationToken token) { return await HttpClient.Get<string>("https://createacc.steepshot.org/api/v1/active", token); } private void AddOffsetLimitParameters(Dictionary<string, object> parameters, string offset, int limit) { if (!string.IsNullOrWhiteSpace(offset)) parameters.Add("offset", offset); if (limit > 0) parameters.Add("limit", limit); } private void AddVotersTypeParameters(Dictionary<string, object> parameters, VotersType type) { if (type != VotersType.All) parameters.Add(type == VotersType.Likes ? "likes" : "flags", 1); } private void AddLoginParameter(Dictionary<string, object> parameters, string login) { if (!string.IsNullOrEmpty(login)) parameters.Add("username", login); } private void AddCensorParameters(Dictionary<string, object> parameters, CensoredNamedRequestWithOffsetLimitModel request) { parameters.Add("show_nsfw", Convert.ToInt32(request.ShowNsfw)); parameters.Add("show_low_rated", Convert.ToInt32(request.ShowLowRated)); } protected ValidationException Validate<T>(T request) { var results = new List<ValidationResult>(); var context = new ValidationContext(request); Validator.TryValidateObject(request, context, results, true); if (results.Any()) { var msg = results.Select(m => m.ErrorMessage).First(); return new ValidationException(msg); } return null; } public async Task<OperationResult<SubscriptionsModel>> CheckSubscriptions(User user, CancellationToken token) { if (!EnableRead || !user.HasPostingPermission || string.IsNullOrEmpty(user.PushesPlayerId)) return new OperationResult<SubscriptionsModel>(new NullReferenceException(nameof(user.PushesPlayerId))); var endpoint = $"{BaseUrl}/{GatewayVersion.V1P1}/subscriptions/{user.Login}/{user.PushesPlayerId}"; return await HttpClient.Get<SubscriptionsModel>(endpoint, token); } public async Task<OperationResult<PromoteResponse>> FindPromoteBot(PromoteRequest promoteModel) { if (!EnableRead) return null; var botsResponse = await HttpClient.Get<List<BidBot>>("https://steembottracker.net/bid_bots", CancellationToken.None); if (!botsResponse.IsSuccess) return new OperationResult<PromoteResponse>(botsResponse.Exception); var priceResponse = await HttpClient.Get<Price>("https://postpromoter.net/api/prices", CancellationToken.None); if (!priceResponse.IsSuccess) return new OperationResult<PromoteResponse>(priceResponse.Exception); var steemToUSD = priceResponse.Result.SteemPrice; var sbdToUSD = priceResponse.Result.SbdPrice; var votersModel = new VotersModel(promoteModel.PostToPromote.Url, VotersType.Likes); var usersResult = await GetPostVoters(votersModel, CancellationToken.None); if (!usersResult.IsSuccess) return new OperationResult<PromoteResponse>(usersResult.Exception); var postAge = (DateTime.Now - promoteModel.PostToPromote.Created).TotalDays; var suitableBot = botsResponse.Result .Where(x => CheckBot(x, postAge, promoteModel, steemToUSD, sbdToUSD, usersResult.Result.Results)) .OrderBy(x => x.Next) .FirstOrDefault(); if (suitableBot == null) return new OperationResult<PromoteResponse>(new ValidationException()); var response = await SearchUser(new SearchWithQueryModel(suitableBot.Name), CancellationToken.None); if (!response.IsSuccess) return new OperationResult<PromoteResponse>(response.Exception); var promoteResponse = new PromoteResponse(response.Result.Results.First(), TimeSpan.FromMilliseconds(suitableBot.Next.Value)); return new OperationResult<PromoteResponse>(promoteResponse); } private bool CheckBot(BidBot bot, double postAge, PromoteRequest promoteModel, double steemToUSD, double sbdToUSD, List<UserFriend> users) { return !bot.IsDisabled && Constants.SupportedListBots.Contains(bot.Name) && (!bot.MaxPostAge.HasValue || postAge < TimeSpan.FromDays(bot.MaxPostAge.Value).TotalDays) && (!bot.MinPostAge.HasValue || postAge > TimeSpan.FromMinutes(bot.MinPostAge.Value).TotalDays) && CheckAmount(promoteModel.Amount, steemToUSD, sbdToUSD, promoteModel.CurrencyType, bot) && !users.Any(r => r.Author.Equals(bot.Name)) && (promoteModel.CurrencyType == CurrencyType.Sbd ? (bot.MinBid.HasValue && bot.MinBid <= promoteModel.Amount) : (bot.MinBidSteem.HasValue && bot.AcceptsSteem && bot.MinBidSteem <= promoteModel.Amount)); } private bool CheckAmount(double promoteAmount, double steemToUSD, double sbdToUSD, CurrencyType token, BidBot botInfo) { var amountLimit = botInfo.VoteUsd; var bidsAmountInBot = botInfo.TotalUsd; double userBidInUSD = 0; switch (token) { case CurrencyType.Steem: userBidInUSD = promoteAmount * steemToUSD; break; case CurrencyType.Sbd: userBidInUSD = promoteAmount * sbdToUSD; break; default: return false; } return (userBidInUSD + bidsAmountInBot) < amountLimit - (amountLimit * 0.25); } } }
43.010267
163
0.619164
[ "MIT" ]
Chainers/steepshot-mobile
Sources/Steepshot/Steepshot.Core/Clients/BaseServerClient.cs
20,948
C#
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; namespace ExceptionHandling { public partial class frmException : Form { public Exception ExceptionObject { get; set; } public string CustomMessage { get; set; } public bool ShowTrace { get; set; } = false; public frmException(Exception ex, string customMsg = null, bool showTrace = true) { InitializeComponent(); ExceptionObject = ex; CustomMessage = customMsg?.ToString(); ShowTrace = showTrace; lblCustomMessage.Text = (customMsg == null ? ex?.Message.ToString():customMsg?.ToString()); if (showTrace) txtExceptionDetail.Text = ex?.Message.ToString() + System.Environment.NewLine + ex.StackTrace.ToString(); } /// <summary> /// Closes the form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmdAccept_Click(object sender, EventArgs e) { Close(); } /// <summary> /// Copies exception details to clipboard /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmdCopy_Click(object sender, EventArgs e) { string copyText = string.Format("{0}{1}{1}{2}{1}{3}",CustomMessage?.ToString(),System.Environment.NewLine, ExceptionObject.Message.ToString(),ExceptionObject.StackTrace.ToString()); Clipboard.Clear(); Clipboard.SetText(copyText); Close(); } /// <summary> /// Writes exception details to file in the same folder than executable application. /// Opens de newly created file. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmdSaveToFile_Click(object sender, EventArgs e) { string copyText = string.Format("# {0}{1}{1}## {2}{1}{3}", CustomMessage?.ToString(), System.Environment.NewLine, ExceptionObject.Message.ToString(), ExceptionObject.StackTrace.ToString()); //Save this text to a file string path = Application.StartupPath + "\\" + String.Format("T3000Exception-{0}{1}{2}{3}{4}.txt",DateTime.Now.Year,DateTime.Now.Month.ToString("00"),DateTime.Now.Day.ToString("00"),DateTime.Now.Hour.ToString("00"),DateTime.Now.Minute.ToString("00")); File.WriteAllText(path, copyText); //MessageBox.Show("Exception details written to file: " + path); ProcessStartInfo psi = new ProcessStartInfo(path); psi.UseShellExecute = true; Process.Start(psi); Close(); } } }
37.826667
263
0.583363
[ "MIT" ]
temcocontrols/T3000_CrossPlatform
ExceptionHandling/frmException.cs
2,839
C#
using System.Runtime.InteropServices; namespace Vulkan { public unsafe struct VkGeneratedCommandsInfoNV { public VkStructureType SType; [NativeTypeName("const void *")] public nuint PNext; public VkPipelineBindPoint PipelineBindPoint; [NativeTypeName("VkPipeline")] public VkPipeline Pipeline; [NativeTypeName("VkIndirectCommandsLayoutNV")] public VkIndirectCommandsLayoutNV IndirectCommandsLayout; [NativeTypeName("uint32_t")] public uint StreamCount; [NativeTypeName("const VkIndirectCommandsStreamNV *")] public VkIndirectCommandsStreamNV* PStreams; public VkIndirectCommandsStreamNV[] Streams { [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] get { return NativeIntExtensions.ToManagedArray(StreamCount, PStreams); } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] set { PStreams = NativeIntExtensions.ToPointer(value, out StreamCount); } } [NativeTypeName("uint32_t")] public uint SequencesCount; [NativeTypeName("VkBuffer")] public VkBuffer PreprocessBuffer; [NativeTypeName("ulong")] public ulong PreprocessOffset; [NativeTypeName("ulong")] public ulong PreprocessSize; [NativeTypeName("VkBuffer")] public VkBuffer SequencesCountBuffer; [NativeTypeName("ulong")] public ulong SequencesCountOffset; [NativeTypeName("VkBuffer")] public VkBuffer SequencesIndexBuffer; [NativeTypeName("ulong")] public ulong SequencesIndexOffset; } }
31.945455
105
0.679567
[ "BSD-3-Clause" ]
trmcnealy/Vulkan
Vulkan/Structs/VkGeneratedCommandsInfoNV.cs
1,757
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using dotnetAPI.Models; using dotnetAPI.Repository; namespace dotnetAPI.Controllers { [Route("api/[controller]")] [ApiController] public class TestResultsController : ControllerBase { private readonly SitDbContext _context; public TestResultsController(SitDbContext context) { _context = context; } // GET: api/TestResults [HttpGet] public async Task<ActionResult<IEnumerable<TestResults>>> GetTestResults() { return await _context.TestResults.ToListAsync(); } // GET: api/TestResults/5 [HttpGet("{id}")] public async Task<ActionResult<TestResults>> GetTestResults(int id) { var testResults = await _context.TestResults.FindAsync(id); if (testResults == null) { return NotFound(); } return testResults; } // GET: api/TestResults/5 //[HttpGet("{id}")] //public async Task<ActionResult<TestResults>> GetTestResultsWIthErrors(int id) //{ // var testResults = await _context.TestResults // .Include(b => b.Error) // .FirstOrDefaultAsync(e => e.TestId == id); // if (testResults == null) // { // return NotFound(); // } // return testResults; //} // PUT: api/TestResults/5 [HttpPut("{id}")] public async Task<IActionResult> PutTestResults(int id, TestResults testResults) { if (id != testResults.TestId) { return BadRequest(); } _context.Entry(testResults).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TestResultsExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/TestResults [HttpPost] public async Task<ActionResult<TestResults>> PostTestResults(TestResults testResults) { _context.TestResults.Add(testResults); await _context.SaveChangesAsync(); return CreatedAtAction("GetTestResults", new { id = testResults.TestId }, testResults); } // DELETE: api/TestResults/5 [HttpDelete("{id}")] public async Task<ActionResult<TestResults>> DeleteTestResults(int id) { var testResults = await _context.TestResults.FindAsync(id); if (testResults == null) { return NotFound(); } _context.TestResults.Remove(testResults); await _context.SaveChangesAsync(); return testResults; } private bool TestResultsExists(int id) { return _context.TestResults.Any(e => e.TestId == id); } } }
27.08871
99
0.538255
[ "MIT" ]
sajrashid/SitAPI
src/API/Controllers/TestResultsController.cs
3,361
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AcademyRPG { public class MyEngine:Engine { public override void ExecuteCreateObjectCommand(string[] commandWords) { switch (commandWords[1]) { case "knight": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); int owner = int.Parse(commandWords[4]); this.AddObject(new Knight(name, position, owner)); break; } case "house": { Point position = Point.Parse(commandWords[2]); int owner = int.Parse(commandWords[3]); this.AddObject(new House(position, owner)); break; } case "giant": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddObject(new Giant(name,position)); break; } case "rock": { int hitPoint = int.Parse(commandWords[2]); Point position = Point.Parse(commandWords[3]); this.AddObject(new Rock(position, hitPoint)); break; } case "ninja": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); int owner = int.Parse(commandWords[4]); this.AddObject(new Ninja(name, position, owner)); break; } default: base.ExecuteCreateObjectCommand(commandWords); break; } } } }
35.542373
79
0.413448
[ "MIT" ]
AYankova/CSharp
OOPExams/AcademyRPG/AcademyRPG/AcademyRPG/MyEngine.cs
2,099
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; using Azure.ResourceManager; namespace Azure.ResourceManager.Network.Models { public partial class SecurityGroupNetworkInterface { internal static SecurityGroupNetworkInterface DeserializeSecurityGroupNetworkInterface(JsonElement element) { Optional<SecurityRuleAssociations> securityRuleAssociations = default; ResourceIdentifier id = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("securityRuleAssociations")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } securityRuleAssociations = SecurityRuleAssociations.DeserializeSecurityRuleAssociations(property.Value); continue; } if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } } return new SecurityGroupNetworkInterface(id, securityRuleAssociations.Value); } } }
33.738095
124
0.592096
[ "MIT" ]
Cardsareus/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/Models/SecurityGroupNetworkInterface.Serialization.cs
1,417
C#
// ----------------------------------------------------------------------- // <copyright file="ExtensionTests.cs" company="Active Netwerx"> // Copyright (c) Active Netwerx. All rights reserved. // </copyright> // <author>Joseph L. Casale</author> // ----------------------------------------------------------------------- namespace LdifHelper.Tests { using System; using System.Collections.Generic; using System.Text; using Xunit; /// <summary> /// Represents LDIF extension tests. /// </summary> public class ExtensionTests { /// <summary> /// Ensures the extension method rejects an empty string key. /// </summary> [Fact] public void AddOrAppendEmptyKeyThrows() { Dictionary<string, List<object>> input = new Dictionary<string, List<object>>(); Assert.Throws<ArgumentOutOfRangeException>(() => input.AddOrAppend(string.Empty, new object[] { "value" })); } /// <summary> /// Ensures the extension method correctly adds a new key and appends a new value. /// </summary> [Fact] public void AddOrAppendIsValid() { Dictionary<string, List<object>> input = new Dictionary<string, List<object>>(); Assert.Empty(input.Keys); input.AddOrAppend("keyA", new object[] { "value" }); Assert.Equal(1, input.Keys.Count); Assert.Equal(1, input["keyA"].Count); input.AddOrAppend("keyA", new object[] { "value" }); Assert.Equal(1, input.Keys.Count); Assert.Equal(2, input["keyA"].Count); input.AddOrAppend("keyB", new object[] { "value" }); Assert.Equal(2, input.Keys.Count); Assert.Equal(1, input["keyB"].Count); } /// <summary> /// Ensures the extension method rejects null input. /// </summary> [Fact] public void AddOrAppendNullInputThrows() { Dictionary<string, List<object>> input = null; Assert.Throws<ArgumentNullException>(() => input.AddOrAppend("key", new object[] { "value" })); } /// <summary> /// Ensures the extension method rejects a null key. /// </summary> [Fact] public void AddOrAppendNullKeyThrows() { Dictionary<string, List<object>> input = new Dictionary<string, List<object>>(); Assert.Throws<ArgumentNullException>(() => input.AddOrAppend(null, new object[] { "value" })); } /// <summary> /// Ensures the extension method rejects a null value. /// </summary> [Fact] public void AddOrAppendNullValueThrows() { Dictionary<string, List<object>> input = new Dictionary<string, List<object>>(); Assert.Throws<ArgumentNullException>(() => input.AddOrAppend("key", null)); } /// <summary> /// Ensures the extension method rejects a white space string key. /// </summary> [Fact] public void AddOrAppendWhiteSpaceKeyThrows() { Dictionary<string, List<object>> input = new Dictionary<string, List<object>>(); Assert.Throws<ArgumentOutOfRangeException>(() => input.AddOrAppend(" ", new object[] { "value" })); } /// <summary> /// Ensures the method rejects an empty attribute type. /// </summary> [Fact] public void GetValueSpecEmptyTypeThrows() => Assert.Throws<ArgumentOutOfRangeException>(() => Extensions.GetValueSpec(string.Empty, "value")); /// <summary> /// Ensures the method rejects a null attribute type. /// </summary> [Fact] public void GetValueSpecNullTypeThrows() => Assert.Throws<ArgumentNullException>(() => Extensions.GetValueSpec(null, "value")); /// <summary> /// Ensures the method rejects a null attribute value. /// </summary> [Fact] public void GetValueSpecNullValueThrows() => Assert.Throws<ArgumentNullException>(() => Extensions.GetValueSpec("type", null)); /// <summary> /// Ensures the method rejects a null attribute value. /// </summary> [Fact] public void GetValueSpecUnknownValueTypeThrows() => Assert.Throws<ArgumentOutOfRangeException>(() => Extensions.GetValueSpec("type", 42)); /// <summary> /// Ensures the method base64 encodes a binary attribute value. /// </summary> [Fact] public void GetValueSpecBinaryDataIsEncoded() { // Arrange. const string attributeType = "sn"; const string attributeValue = "value"; byte[] bytes = Encoding.UTF8.GetBytes(attributeValue); // Act. string sut = Extensions.GetValueSpec(attributeType, bytes); // Assert. Assert.Equal(attributeType, sut.Substring(0, attributeType.Length)); byte[] valueBytes = Convert.FromBase64String(sut.Substring(attributeType.Length + 3)); string valueString = Encoding.UTF8.GetString(valueBytes); Assert.Equal(attributeValue, valueString); } /// <summary> /// Ensures the method base64 encodes an attribute value with an unsafe initial character. /// </summary> [Fact] public void GetValueSpecUnSafeInitCharIsEncoded() { // Arrange. const string attributeType = "givenName"; const string attributeValue = "Émilie"; // Act. string sut = Extensions.GetValueSpec(attributeType, attributeValue); // Assert. Assert.Equal(attributeType, sut.Substring(0, attributeType.Length)); byte[] valueBytes = Convert.FromBase64String(sut.Substring(attributeType.Length + 3)); string valueString = Encoding.UTF8.GetString(valueBytes); Assert.Equal(attributeValue, valueString); } /// <summary> /// Ensures the method base64 encodes an attribute value with an unsafe initial character. /// </summary> [Fact] public void GetValueSpecUnSafeStringIsEncoded() { // Arrange. const string attributeType = "sn"; const string attributeValue = "Châtelet"; // Act. string sut = Extensions.GetValueSpec(attributeType, attributeValue); Assert.Equal(attributeType, sut.Substring(0, attributeType.Length)); // Assert. byte[] valueBytes = Convert.FromBase64String(sut.Substring(attributeType.Length + 3)); string valueString = Encoding.UTF8.GetString(valueBytes); Assert.Equal(attributeValue, valueString); } /// <summary> /// Ensures the method rejects a white space attribute type. /// </summary> [Fact] public void GetValueSpecWhiteSpaceTypeThrows() => Assert.Throws<ArgumentOutOfRangeException>(() => Extensions.GetValueSpec(" ", "value")); /// <summary> /// Ensures the extension method identifies some possible cases. /// </summary> [Fact] public void IsSafeInitCharIsValid() { Assert.True(string.Empty.IsSafeInitChar()); Assert.True("a".IsSafeInitChar()); Assert.False(" ".IsSafeInitChar()); Assert.False("Émilie".IsSafeInitChar()); } /// <summary> /// Ensures the extension method rejects a null attribute value. /// </summary> [Fact] public void IsSafeInitCharNullValueThrows() { const string value = null; Assert.Throws<ArgumentNullException>(() => value.IsSafeInitChar()); } /// <summary> /// Ensures the extension method identifies some possible cases. /// </summary> [Fact] public void IsSafeStringIsValid() { Assert.True(string.Empty.IsSafeString()); Assert.True("ascii chars".IsSafeString()); Assert.False("EndsWithSpace ".IsSafeString()); Assert.False("Châtelet".IsSafeString()); } /// <summary> /// Ensures the extension method rejects a null attribute value. /// </summary> [Fact] public void IsSafeStringNullValueThrows() { const string value = null; Assert.Throws<ArgumentNullException>(() => value.IsSafeString()); } /// <summary> /// Ensures the extension method correctly base64 encodes a value. /// </summary> [Fact] public void ToBase64BytesIsValid() { // Arrange. const string value = "value"; byte[] utf16Bytes = Encoding.Unicode.GetBytes(value); // Act. string encoded = utf16Bytes.ToBase64(); // Assert. byte[] bytes = Convert.FromBase64String(encoded); string decoded = Encoding.Unicode.GetString(bytes); Assert.Equal(value, decoded); } /// <summary> /// Ensures the extension method rejects a null value. /// </summary> [Fact] public void ToBase64BytesNullValueThrows() { const byte[] value = null; Assert.Throws<ArgumentNullException>(() => value.ToBase64()); } /// <summary> /// Ensures the extension method correctly base64 encodes a value. /// </summary> [Fact] public void ToBase64StringIsValid() { // Arrange. const string value = "value"; // Act. string sut = value.ToBase64(); // Assert. byte[] bytes = Convert.FromBase64String(sut); string decoded = Encoding.UTF8.GetString(bytes); Assert.Equal(value, decoded); } /// <summary> /// Ensures the extension method rejects a null value. /// </summary> [Fact] public void ToBase64StringNullValueThrows() { const string value = null; Assert.Throws<ArgumentNullException>(() => value.ToBase64()); } /// <summary> /// Ensures the extension method rejects a null value. /// </summary> [Fact] public void WrapNullValueThrows() { const string value = null; Assert.Throws<ArgumentNullException>(() => value.Wrap()); } /// <summary> /// Ensures the extension method correctly wraps a long line. /// </summary> [Fact] public void WrapColumnLengthIsValid() { // Arrange. const string value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus convallis" + " et erat at mollis. Nullam in risus laoreet, pharetra leo a, volutpat massa. Cras" + " quis sodales velit. In sit amet augue gravida, sagittis dui a, placerat nunc." + " Fusce non nisi vel orci sagittis elementum. Praesent elit nulla, elementum sed" + " sem a, semper dictum arcu. Duis luctus arcu id arcu scelerisque pharetra. Nunc" + " a elementum felis, quis auctor diam."; // Act. string sut = value.Wrap(); // Assert. string[] lines = sut.Split(new[] { '\r', '\n' }, StringSplitOptions.None); Assert.NotEmpty(lines); foreach (string line in lines) { Assert.True(line.Length <= Constants.MaxLineLength); } } /// <summary> /// Ensures the <see cref="Extensions.Wrap"/> extension method correctly processes strings of various lengths. /// </summary> [Fact] public void WrapIsValid() { var generator = new Random(); for (int i = 0; i < 4000; i++) { // Arrange. var bytes = new byte[i]; generator.NextBytes(bytes); var data = $"wrap:: {bytes.ToBase64()}"; // Act. var sut = data.Wrap().Split(new[] { Environment.NewLine }, StringSplitOptions.None); var stringBuilder = new StringBuilder(); if (sut.Length > 0) { stringBuilder.Append(sut[0]); } for (int j = 1; j < sut.Length; j++) { var line = sut[j]; if (line.Length > 1) { // Trim only the leading whitespace added by Wrap(). stringBuilder.Append(line.Substring(1)); } } // Assert. Assert.Equal(data, stringBuilder.ToString()); } } } }
34.119792
120
0.542971
[ "MIT" ]
JTOne123/LdifHelper
tests/LdifHelper.Tests/ExtensionTests.cs
13,108
C#
/* * TimeZoneInfo.Tests * * Author(s) * Stephane Delcroix <stephane@delcroix.org> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using NUnit.Framework; #if NET_2_0 namespace MonoTests.System { public class TimeZoneInfoTest { [TestFixture] public class PropertiesTests { [Test] public void GetLocal () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo local = TimeZoneInfo.Local; Assert.IsNotNull (local); Assert.IsTrue (true); } } [TestFixture] public class CreateCustomTimezoneTests { [Test] [ExpectedException (typeof (ArgumentNullException))] public void IdIsNullException () { TimeZoneInfo.CreateCustomTimeZone (null, new TimeSpan (0), null, null); } [Test] [ExpectedException (typeof (ArgumentException))] public void IdIsEmptyString () { TimeZoneInfo.CreateCustomTimeZone ("", new TimeSpan (0), null, null); } [Test] [ExpectedException (typeof (ArgumentException))] public void OffsetIsNotMinutes () { TimeZoneInfo.CreateCustomTimeZone ("mytimezone", new TimeSpan (0, 0, 55), null, null); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void OffsetTooBig () { TimeZoneInfo.CreateCustomTimeZone ("mytimezone", new TimeSpan (14, 1, 0), null, null); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void OffsetTooSmall () { TimeZoneInfo.CreateCustomTimeZone ("mytimezone", - new TimeSpan (14, 1, 0), null, null); } #if STRICT [Test] [ExpectedException (typeof (ArgumentException))] public void IdLongerThan32 () { TimeZoneInfo.CreateCustomTimeZone ("12345678901234567890123456789012345", new TimeSpan (0), null, null); } #endif [Test] [ExpectedException (typeof (InvalidTimeZoneException))] public void AdjustmentRulesOverlap () { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (new DateTime (2000,1,1), new DateTime (2005,1,1), new TimeSpan (1,0,0), s1, e1); TimeZoneInfo.TransitionTime s2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 2, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 11, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (new DateTime (2004,1,1), new DateTime (2007,1,1), new TimeSpan (1,0,0), s2, e2); TimeZoneInfo.CreateCustomTimeZone ("mytimezone", new TimeSpan (6,0,0),null,null,null,new TimeZoneInfo.AdjustmentRule[] {r1, r2}); } [Test] [ExpectedException (typeof (InvalidTimeZoneException))] public void RulesNotOrdered () { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (new DateTime (2000,1,1), new DateTime (2005,1,1), new TimeSpan (1,0,0), s1, e1); TimeZoneInfo.TransitionTime s2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 2, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 11, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (new DateTime (2006,1,1), new DateTime (2007,1,1), new TimeSpan (1,0,0), s2, e2); TimeZoneInfo.CreateCustomTimeZone ("mytimezone", new TimeSpan (6,0,0),null,null,null,new TimeZoneInfo.AdjustmentRule[] {r2, r1}); } [Test] [ExpectedException (typeof (InvalidTimeZoneException))] public void OffsetOutOfRange () { TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (new DateTime (2000,1,1), new DateTime (2005,1,1), new TimeSpan (3,0,0), startTransition, endTransition); TimeZoneInfo.CreateCustomTimeZone ("mytimezone", new TimeSpan (12,0,0),null,null,null,new TimeZoneInfo.AdjustmentRule[] {rule}); } [Test] [ExpectedException (typeof (InvalidTimeZoneException))] public void NullRule () { TimeZoneInfo.CreateCustomTimeZone ("mytimezone", new TimeSpan (12,0,0),null,null,null,new TimeZoneInfo.AdjustmentRule[] {null}); } [Test] [ExpectedException (typeof (InvalidTimeZoneException))] public void MultiplesRulesForDate () { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (new DateTime (2000,1,1), new DateTime (2005,1,1), new TimeSpan (1,0,0), s1, e1); TimeZoneInfo.TransitionTime s2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 2, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,4,0,0), 11, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (new DateTime (2005,1,1), new DateTime (2007,1,1), new TimeSpan (1,0,0), s2, e2); TimeZoneInfo.CreateCustomTimeZone ("mytimezone", new TimeSpan (6,0,0),null,null,null,new TimeZoneInfo.AdjustmentRule[] {r1, r2}); } } [TestFixture] public class IsDaylightSavingTimeTests { TimeZoneInfo london; [SetUp] public void CreateTimeZones () { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,1,0,0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,2,0,0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan (1,0,0), start, end); london = TimeZoneInfo.CreateCustomTimeZone ("Europe/London", new TimeSpan (0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule [] {rule}); } [Test] public void NoDSTInUTC () { DateTime june01 = new DateTime (2007, 06, 01); Assert.IsFalse (TimeZoneInfo.Utc.IsDaylightSavingTime (june01)); } [Test] public void DSTInLondon () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; DateTime june01 = new DateTime (2007, 06, 01); DateTime xmas = new DateTime (2007, 12, 25); Assert.IsTrue (london.IsDaylightSavingTime (june01), "June 01 is DST in London"); Assert.IsFalse (london.IsDaylightSavingTime (xmas), "Xmas is not DST in London"); } [Test] public void DSTTransisions () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; DateTime beforeDST = new DateTime (2007, 03, 25, 0, 59, 59, DateTimeKind.Unspecified); DateTime startDST = new DateTime (2007, 03, 25, 2, 0, 0, DateTimeKind.Unspecified); DateTime endDST = new DateTime (2007, 10, 28, 1, 59, 59, DateTimeKind.Unspecified); DateTime afterDST = new DateTime (2007, 10, 28, 2, 0, 0, DateTimeKind.Unspecified); Assert.IsFalse (london.IsDaylightSavingTime (beforeDST), "Just before DST"); Assert.IsTrue (london.IsDaylightSavingTime (startDST), "the first seconds of DST"); Assert.IsTrue (london.IsDaylightSavingTime (endDST), "The last seconds of DST"); Assert.IsFalse (london.IsDaylightSavingTime (afterDST), "Just after DST"); } [Test] public void DSTTransisionsUTC () { DateTime beforeDST = new DateTime (2007, 03, 25, 0, 59, 59, DateTimeKind.Utc); DateTime startDST = new DateTime (2007, 03, 25, 1, 0, 0, DateTimeKind.Utc); DateTime endDST = new DateTime (2007, 10, 28, 0, 59, 59, DateTimeKind.Utc); DateTime afterDST = new DateTime (2007, 10, 28, 1, 0, 0, DateTimeKind.Utc); Assert.IsFalse (london.IsDaylightSavingTime (beforeDST), "Just before DST"); Assert.IsTrue (london.IsDaylightSavingTime (startDST), "the first seconds of DST"); Assert.IsTrue (london.IsDaylightSavingTime (endDST), "The last seconds of DST"); Assert.IsFalse (london.IsDaylightSavingTime (afterDST), "Just after DST"); } #if SLOW_TESTS [Test] public void MatchTimeZoneBehavior () { TimeZone tzone = TimeZone.CurrentTimeZone; TimeZoneInfo local = TimeZoneInfo.Local; for (DateTime date = new DateTime (2007, 01, 01, 0, 0, 0, DateTimeKind.Local); date < new DateTime (2007, 12, 31, 23, 59, 59); date += new TimeSpan (0,1,0)) { date = DateTime.SpecifyKind (date, DateTimeKind.Local); if (local.IsInvalidTime (date)) continue; Assert.IsTrue (tzone.IsDaylightSavingTime (date) == local.IsDaylightSavingTime (date)); } } #endif } [TestFixture] public class ConvertTimeTests { TimeZoneInfo london; [SetUp] public void CreateTimeZones () { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,1,0,0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,2,0,0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan (1,0,0), start, end); london = TimeZoneInfo.CreateCustomTimeZone ("Europe/London", new TimeSpan (0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule [] {rule}); } [Test] [ExpectedException (typeof (ArgumentException))] public void ConvertFromUtc_KindIsLocalException () { if (Environment.OSVersion.Platform != PlatformID.Unix) throw new ArgumentException (); TimeZoneInfo.ConvertTimeFromUtc (new DateTime (2007, 5, 3, 11, 8, 0, DateTimeKind.Local), TimeZoneInfo.Local); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ConvertFromUtc_DestinationTimeZoneIsNullException () { TimeZoneInfo.ConvertTimeFromUtc (new DateTime (2007, 5, 3, 11, 8, 0), null); } [Test] public void ConvertFromUtc_DestinationIsUTC () { DateTime now = DateTime.UtcNow; DateTime converted = TimeZoneInfo.ConvertTimeFromUtc (now, TimeZoneInfo.Utc); Assert.AreEqual (now, converted); } [Test] public void ConvertFromUTC_ConvertInWinter () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; DateTime utc = new DateTime (2007, 12, 25, 12, 0, 0); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc (utc, london); Assert.AreEqual (utc, converted); } [Test] public void ConvertFromUtc_ConvertInSummer () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; DateTime utc = new DateTime (2007, 06, 01, 12, 0, 0); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc (utc, london); Assert.AreEqual (utc + new TimeSpan (1,0,0), converted); } [Test] public void ConvertToUTC_KindIsUtc () { DateTime now = DateTime.UtcNow; Assert.AreEqual (now.Kind, DateTimeKind.Utc); DateTime converted = TimeZoneInfo.ConvertTimeToUtc (now); Assert.AreEqual (now, converted); } [Test] [ExpectedException (typeof (ArgumentException))] public void ConvertToUTC_KindIsUTCButSourceIsNot () { TimeZoneInfo.ConvertTimeToUtc (new DateTime (2007, 5, 3, 12, 8, 0, DateTimeKind.Utc), london); } [Test] [ExpectedException (typeof (ArgumentException))] public void ConvertToUTC_KindIsLocalButSourceIsNot () { if (Environment.OSVersion.Platform != PlatformID.Unix) throw new ArgumentException (); TimeZoneInfo.ConvertTimeToUtc (new DateTime (2007, 5, 3, 12, 8, 0, DateTimeKind.Local), london); } [Test] [ExpectedException (typeof (ArgumentException))] public void ConvertToUTC_InvalidDate () { TimeZoneInfo.ConvertTimeToUtc (new DateTime (2007, 3, 25, 1, 30, 0), london); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ConvertToUTC_SourceIsNull () { TimeZoneInfo.ConvertTimeToUtc (new DateTime (2007, 5, 3, 12, 16, 0), null); } #if SLOW_TESTS [Test] public void ConvertToUtc_MatchDateTimeBehavior () { for (DateTime date = new DateTime (2007, 01, 01, 0, 0, 0); date < new DateTime (2007, 12, 31, 23, 59, 59); date += new TimeSpan (0,1,0)) { Assert.AreEqual (TimeZoneInfo.ConvertTimeToUtc (date), date.ToUniversalTime ()); } } #endif [Test] public void ConvertFromToUtc () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; DateTime utc = DateTime.UtcNow; Assert.AreEqual (utc.Kind, DateTimeKind.Utc); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc (utc, london); Assert.AreEqual (converted.Kind, DateTimeKind.Unspecified); DateTime back = TimeZoneInfo.ConvertTimeToUtc (converted, london); Assert.AreEqual (back.Kind, DateTimeKind.Utc); Assert.AreEqual (utc, back); } [Test] public void ConvertToTimeZone () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo.ConvertTime (DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Pacific/Auckland")); } } [TestFixture] public class IsInvalidTimeTests { TimeZoneInfo london; [SetUp] public void CreateTimeZones () { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,1,0,0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,2,0,0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan (1,0,0), start, end); london = TimeZoneInfo.CreateCustomTimeZone ("Europe/London", new TimeSpan (0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule [] {rule}); } #if SLOW_TESTS [Test] public void UTCDate () { for (DateTime date = new DateTime (2007, 01, 01, 0, 0, 0); date < new DateTime (2007, 12, 31, 23, 59, 59); date += new TimeSpan (0,1,0)) { date = DateTime.SpecifyKind (date, DateTimeKind.Utc); Assert.IsFalse (london.IsInvalidTime (date)); } } #endif [Test] public void InvalidDates () { Assert.IsFalse (london.IsInvalidTime (new DateTime (2007, 03, 25, 0, 59, 59))); Assert.IsTrue (london.IsInvalidTime (new DateTime (2007, 03, 25, 1, 0, 0))); Assert.IsTrue (london.IsInvalidTime (new DateTime (2007, 03, 25, 1, 59, 59))); Assert.IsFalse (london.IsInvalidTime (new DateTime (2007, 03, 25, 2, 0, 0))); } } [TestFixture] public class IsAmbiguousTimeTests { TimeZoneInfo london; [SetUp] public void CreateTimeZones () { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,1,0,0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,2,0,0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan (1,0,0), start, end); london = TimeZoneInfo.CreateCustomTimeZone ("Europe/London", new TimeSpan (0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule [] {rule}); } [Test] public void AmbiguousDates () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; Assert.IsFalse (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 1, 0, 0))); Assert.IsTrue (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 1, 0, 1))); Assert.IsTrue (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 2, 0, 0))); Assert.IsFalse (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 2, 0, 1))); } [Test] public void AmbiguousUTCDates () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; Assert.IsFalse (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 0, 0, 0, DateTimeKind.Utc))); Assert.IsTrue (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 0, 0, 1, DateTimeKind.Utc))); Assert.IsTrue (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 0, 59, 59, DateTimeKind.Utc))); Assert.IsFalse (london.IsAmbiguousTime (new DateTime (2007, 10, 28, 1, 0, 0, DateTimeKind.Utc))); } #if SLOW_TESTS [Test] public void AmbiguousInUTC () { for (DateTime date = new DateTime (2007, 01, 01, 0, 0, 0); date < new DateTime (2007, 12, 31, 23, 59, 59); date += new TimeSpan (0,1,0)) { Assert.IsFalse (TimeZoneInfo.Utc.IsAmbiguousTime (date)); } } #endif } [TestFixture] public class GetSystemTimeZonesTests { [Test] public void NotEmpty () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; global::System.Collections.ObjectModel.ReadOnlyCollection<TimeZoneInfo> systemTZ = TimeZoneInfo.GetSystemTimeZones (); Assert.IsNotNull(systemTZ, "SystemTZ is null"); Assert.IsFalse (systemTZ.Count == 0, "SystemTZ is empty"); } [Test] public void ContainsBrussels () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; global::System.Collections.ObjectModel.ReadOnlyCollection<TimeZoneInfo> systemTZ = TimeZoneInfo.GetSystemTimeZones (); foreach (TimeZoneInfo tz in systemTZ) { if (tz.Id == "Europe/Brussels") return; } Assert.Fail ("Europe/Brussels not found in SystemTZ"); } } [TestFixture] public class FindSystemTimeZoneByIdTests { [Test] [ExpectedException (typeof (ArgumentNullException))] public void NullId () { TimeZoneInfo.FindSystemTimeZoneById (null); } [Test] [ExpectedException (typeof (TimeZoneNotFoundException))] public void NonSystemTimezone () { if (Environment.OSVersion.Platform != PlatformID.Unix) throw new TimeZoneNotFoundException (); TimeZoneInfo.FindSystemTimeZoneById ("Neverland/The_Lagoon"); } [Test] public void FindBrusselsTZ () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo brussels = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Brussels"); Assert.IsNotNull (brussels); } [Test] public void OffsetIsCorrectInKinshasa () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo kin = TimeZoneInfo.FindSystemTimeZoneById ("Africa/Kinshasa"); Assert.AreEqual (new TimeSpan (1,0,0), kin.BaseUtcOffset, "BaseUtcOffset in Kinshasa is not +1h"); } [Test] public void OffsetIsCorrectInBrussels () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo brussels = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Brussels"); Assert.AreEqual (new TimeSpan (1,0,0), brussels.BaseUtcOffset, "BaseUtcOffset for Brussels is not +1h"); } [Test] public void NoDSTInKinshasa () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo kin = TimeZoneInfo.FindSystemTimeZoneById ("Africa/Kinshasa"); Assert.IsFalse (kin.SupportsDaylightSavingTime); } [Test] public void BrusselsSupportsDST () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo brussels = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Brussels"); Assert.IsTrue (brussels.SupportsDaylightSavingTime); } [Test] public void MelbourneSupportsDST () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo melbourne = TimeZoneInfo.FindSystemTimeZoneById ("Australia/Melbourne"); Assert.IsTrue (melbourne.SupportsDaylightSavingTime); } [Test] public void RomeAndVaticanSharesTime () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo rome = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Rome"); TimeZoneInfo vatican = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Vatican"); Assert.IsTrue (rome.HasSameRules (vatican)); } [Test] public void FindSystemTimeZoneById_Local_Roundtrip () { Assert.AreEqual (TimeZoneInfo.Local.Id, TimeZoneInfo.FindSystemTimeZoneById (TimeZoneInfo.Local.Id).Id); } [Test] public void Test326 () { DateTime utc = DateTime.UtcNow; DateTime local = TimeZoneInfo.ConvertTime (utc, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById (TimeZoneInfo.Local.Id)); Assert.AreEqual (local, utc + TimeZoneInfo.Local.GetUtcOffset (utc), "ConvertTime/Local"); } #if SLOW_TESTS [Test] public void BrusselsAdjustments () { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,2,0,0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule (new DateTime (1,1,1,3,0,0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule (DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan (1,0,0), start, end); TimeZoneInfo brussels = TimeZoneInfo.CreateCustomTimeZone ("Europe/Brussels", new TimeSpan (1, 0, 0), "Europe/Brussels", "", "", new TimeZoneInfo.AdjustmentRule [] {rule}); TimeZoneInfo brussels_sys = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Brussels"); for (DateTime date = new DateTime (2006, 01, 01, 0, 0, 0, DateTimeKind.Local); date < new DateTime (2007, 12, 31, 23, 59, 59); date += new TimeSpan (0,30,0)) { Assert.AreEqual (brussels.GetUtcOffset (date), brussels_sys.GetUtcOffset (date)); Assert.AreEqual (brussels.IsDaylightSavingTime (date), brussels_sys.IsDaylightSavingTime (date)); } } #endif } [TestFixture] public class GetAmbiguousTimeOffsetsTests { [Test] [ExpectedException (typeof(ArgumentException))] public void DateIsNotAmbiguous () { if (Environment.OSVersion.Platform != PlatformID.Unix) throw new ArgumentException (); TimeZoneInfo brussels = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Brussels"); DateTime date = new DateTime (2007, 05, 11, 11, 40, 00); brussels.GetAmbiguousTimeOffsets (date); } [Test] public void AmbiguousOffsets () { if (Environment.OSVersion.Platform != PlatformID.Unix) return; TimeZoneInfo brussels = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Brussels"); DateTime date = new DateTime (2007, 10, 28, 2, 30, 00); Assert.IsTrue (brussels.IsAmbiguousTime (date)); Assert.AreEqual (2, brussels.GetAmbiguousTimeOffsets (date).Length); Assert.AreEqual (new TimeSpan[] {new TimeSpan (1, 0, 0), new TimeSpan (2, 0, 0)}, brussels.GetAmbiguousTimeOffsets (date)); } } [TestFixture] public class HasSameRulesTests { [Test] public void NullAdjustments () //bnc #391011 { TimeZoneInfo utc = TimeZoneInfo.Utc; TimeZoneInfo custom = TimeZoneInfo.CreateCustomTimeZone ("Custom", new TimeSpan (0), "Custom", "Custom"); Assert.IsTrue (utc.HasSameRules (custom)); } } } } #endif
40.492823
193
0.710741
[ "Apache-2.0" ]
symform/mono
mcs/class/System.Core/Test/System/TimeZoneInfoTest.cs
25,389
C#
using System.Collections.Generic; namespace GoldenEye.Backend.Core.DDD.Queries { public interface IListQuery<TResponse> : IQuery<IReadOnlyList<TResponse>> { } }
21.75
77
0.747126
[ "MIT" ]
amarish-kumar/GoldenEye
src/Core/Backend.Core.DDD/Queries/IListQuery.cs
176
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tasks.BufferPool { public interface IBufferRegistration : IBuffer, IDisposable { } }
17.307692
63
0.76
[ "Apache-2.0" ]
nandehutuzn/CSharpAsync
AsyncSolution/Tasks/BufferPool/IBufferRegistration.cs
227
C#
using System.Collections.Generic; using System.Text.RegularExpressions; using DateObject = System.DateTime; using Microsoft.Recognizers.Definitions; using Microsoft.Recognizers.Text.Number; namespace Microsoft.Recognizers.Text.DateTime { public class BaseTimeExtractor : IDateTimeExtractor { private static readonly string ExtractorName = Constants.SYS_DATETIME_TIME; // "Time"; public static readonly Regex HourRegex = new Regex(BaseDateTime.HourRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline); public static readonly Regex MinuteRegex = new Regex(BaseDateTime.MinuteRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline); public static readonly Regex SecondRegex = new Regex(BaseDateTime.SecondRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline); private readonly ITimeExtractorConfiguration config; public BaseTimeExtractor(ITimeExtractorConfiguration config) { this.config = config; } public virtual List<ExtractResult> Extract(string text) { return Extract(text, DateObject.Now); } public virtual List<ExtractResult> Extract(string text, DateObject reference) { var tokens = new List<Token>(); tokens.AddRange(BasicRegexMatch(text)); tokens.AddRange(AtRegexMatch(text)); tokens.AddRange(BeforeAfterRegexMatch(text)); tokens.AddRange(SpecialCasesRegexMatch(text, reference)); return Token.MergeAllTokens(tokens, text, ExtractorName); } private List<Token> BasicRegexMatch(string text) { var ret = new List<Token>(); foreach (var regex in this.config.TimeRegexList) { var matches = regex.Matches(text); foreach (Match match in matches) { ret.Add(new Token(match.Index, match.Index + match.Length)); } } return ret; } private List<Token> AtRegexMatch(string text) { var ret = new List<Token>(); // handle "at 5", "at seven" if (this.config.AtRegex.IsMatch(text)) { var matches = this.config.AtRegex.Matches(text); foreach (Match match in matches) { if (match.Index + match.Length < text.Length && text[match.Index + match.Length].Equals('%')) { continue; } ret.Add(new Token(match.Index, match.Index + match.Length)); } } return ret; } private List<Token> BeforeAfterRegexMatch(string text) { var ret = new List<Token>(); // only enabled in CalendarMode if ((this.config.Options & DateTimeOptions.CalendarMode) != 0) { // handle "before 3", "after three" var beforeAfterRegex = this.config.TimeBeforeAfterRegex; if (beforeAfterRegex.IsMatch(text)) { var matches = beforeAfterRegex.Matches(text); foreach (Match match in matches) { ret.Add(new Token(match.Index, match.Index + match.Length)); } } } return ret; } private List<Token> SpecialCasesRegexMatch(string text, DateObject reference) { var ret = new List<Token>(); // handle "ish" if (this.config.IshRegex != null && this.config.IshRegex.IsMatch(text)) { var matches = this.config.IshRegex.Matches(text); foreach (Match match in matches) { ret.Add(new Token(match.Index, match.Index + match.Length)); } } return ret; } } }
35.649123
138
0.553396
[ "MIT" ]
onatatayer/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Extractors/BaseTimeExtractor.cs
4,066
C#
//------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ namespace Steroids.CodeStructure.Resources.Strings { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Strings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Strings() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Steroids.CodeStructure.Resources.Strings.Strings", typeof(Strings).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to n/a. /// </summary> public static string NotAvailable_Abbreviation { get { return ResourceManager.GetString("NotAvailable_Abbreviation", resourceCulture); } } } }
42.671233
191
0.607063
[ "MIT" ]
eberthold/SteroidsVS
Source/BusinessLogic/CodeStructure/Steroids.CodeStructure/Resources/Strings/Strings.Designer.cs
3,117
C#
using System; using System.Collections.Generic; using System.Text; namespace pelazem.azure.cognitive.videoindexer { public class Thumbnail { public string Id { get; set; } public string FileName { get; set; } public List<AdjustedInstance> Instances { get; set; } } }
19.533333
56
0.696246
[ "MIT" ]
plzm/AIServices
Libraries/videoindexer/Thumbnail.cs
295
C#
using MVCProject.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MVCProject.View.FormsAdicionar { public partial class frmAdicionarAutor : Form { public frmAdicionarAutor() { InitializeComponent(); } public Autor autor; private void Button1_Click(object sender, EventArgs e) { autor = new Autor { Nome = textBox1.Text, Descricao = textBox2.Text }; this.Close(); } } }
20.457143
62
0.607542
[ "MIT" ]
DrGabenator/GitC
29-07_02-08/MVCProject/MVCProject/View/FormsAdicionar/frmAdicionarAutor.cs
718
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using BTCPayServer.Data; using BTCPayServer.HostedServices; using BTCPayServer.Lightning; using BTCPayServer.Logging; using BTCPayServer.Models; using BTCPayServer.Models.InvoicingModels; using BTCPayServer.Rating; using BTCPayServer.Services; using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Rates; using NBitcoin; namespace BTCPayServer.Payments.Lightning { public class LightningLikePaymentHandler : PaymentMethodHandlerBase<LightningSupportedPaymentMethod, BTCPayNetwork> { public static int LIGHTNING_TIMEOUT = 5000; readonly NBXplorerDashboard _Dashboard; private readonly LightningClientFactoryService _lightningClientFactory; private readonly BTCPayNetworkProvider _networkProvider; private readonly SocketFactory _socketFactory; public LightningLikePaymentHandler( NBXplorerDashboard dashboard, LightningClientFactoryService lightningClientFactory, BTCPayNetworkProvider networkProvider, SocketFactory socketFactory) { _Dashboard = dashboard; _lightningClientFactory = lightningClientFactory; _networkProvider = networkProvider; _socketFactory = socketFactory; } public override PaymentType PaymentType => PaymentTypes.LightningLike; public override async Task<IPaymentMethodDetails> CreatePaymentMethodDetails( InvoiceLogs logs, LightningSupportedPaymentMethod supportedPaymentMethod, PaymentMethod paymentMethod, StoreData store, BTCPayNetwork network, object preparePaymentObject) { //direct casting to (BTCPayNetwork) is fixed in other pull requests with better generic interfacing for handlers var storeBlob = store.GetStoreBlob(); var test = GetNodeInfo(paymentMethod.PreferOnion, supportedPaymentMethod, network); var invoice = paymentMethod.ParentEntity; var due = Extensions.RoundUp(invoice.ProductInformation.Price / paymentMethod.Rate, network.Divisibility); var client = _lightningClientFactory.Create(supportedPaymentMethod.GetLightningUrl(), network); var expiry = invoice.ExpirationTime - DateTimeOffset.UtcNow; if (expiry < TimeSpan.Zero) expiry = TimeSpan.FromSeconds(1); LightningInvoice lightningInvoice = null; string description = storeBlob.LightningDescriptionTemplate; description = description.Replace("{StoreName}", store.StoreName ?? "", StringComparison.OrdinalIgnoreCase) .Replace("{ItemDescription}", invoice.ProductInformation.ItemDesc ?? "", StringComparison.OrdinalIgnoreCase) .Replace("{OrderId}", invoice.OrderId ?? "", StringComparison.OrdinalIgnoreCase); using (var cts = new CancellationTokenSource(LIGHTNING_TIMEOUT)) { try { var request = new CreateInvoiceParams(new LightMoney(due, LightMoneyUnit.BTC), description, expiry); request.PrivateRouteHints = storeBlob.LightningPrivateRouteHints; lightningInvoice = await client.CreateInvoice(request, cts.Token); } catch (OperationCanceledException) when (cts.IsCancellationRequested) { throw new PaymentMethodUnavailableException($"The lightning node did not reply in a timely manner"); } catch (Exception ex) { throw new PaymentMethodUnavailableException($"Impossible to create lightning invoice ({ex.Message})", ex); } } var nodeInfo = await test; return new LightningLikePaymentMethodDetails() { BOLT11 = lightningInvoice.BOLT11, InvoiceId = lightningInvoice.Id, NodeInfo = nodeInfo.ToString() }; } public async Task<NodeInfo> GetNodeInfo(bool preferOnion, LightningSupportedPaymentMethod supportedPaymentMethod, BTCPayNetwork network) { if (!_Dashboard.IsFullySynched(network.CryptoCode, out var summary)) throw new PaymentMethodUnavailableException($"Full node not available"); using (var cts = new CancellationTokenSource(LIGHTNING_TIMEOUT)) { var client = _lightningClientFactory.Create(supportedPaymentMethod.GetLightningUrl(), network); LightningNodeInformation info = null; try { info = await client.GetInfo(cts.Token); } catch (OperationCanceledException) when (cts.IsCancellationRequested) { throw new PaymentMethodUnavailableException($"The lightning node did not reply in a timely manner"); } catch (Exception ex) { throw new PaymentMethodUnavailableException($"Error while connecting to the API ({ex.Message})"); } var nodeInfo = info.NodeInfoList.FirstOrDefault(i => i.IsTor == preferOnion) ?? info.NodeInfoList.FirstOrDefault(); if (nodeInfo == null) { throw new PaymentMethodUnavailableException($"No lightning node public address has been configured"); } var blocksGap = summary.Status.ChainHeight - info.BlockHeight; if (blocksGap > 10) { throw new PaymentMethodUnavailableException($"The lightning node is not synched ({blocksGap} blocks left)"); } return nodeInfo; } } public async Task TestConnection(NodeInfo nodeInfo, CancellationToken cancellation) { try { if (!Utils.TryParseEndpoint(nodeInfo.Host, nodeInfo.Port, out var endpoint)) throw new PaymentMethodUnavailableException($"Could not parse the endpoint {nodeInfo.Host}"); using (var tcp = await _socketFactory.ConnectAsync(endpoint, cancellation)) { } } catch (Exception ex) { throw new PaymentMethodUnavailableException($"Error while connecting to the lightning node via {nodeInfo.Host}:{nodeInfo.Port} ({ex.Message})"); } } public override IEnumerable<PaymentMethodId> GetSupportedPaymentMethods() { return _networkProvider .GetAll() .OfType<BTCPayNetwork>() .Where(network => network.NBitcoinNetwork.Consensus.SupportSegwit && network.SupportLightning) .Select(network => new PaymentMethodId(network.CryptoCode, PaymentTypes.LightningLike)); } public override async Task<string> IsPaymentMethodAllowedBasedOnInvoiceAmount(StoreBlob storeBlob, Dictionary<CurrencyPair, Task<RateResult>> rate, Money amount, PaymentMethodId paymentMethodId) { if (storeBlob.LightningMaxValue != null) { var currentRateToCrypto = await rate[new CurrencyPair(paymentMethodId.CryptoCode, storeBlob.LightningMaxValue.Currency)]; if (currentRateToCrypto?.BidAsk != null) { var limitValueCrypto = Money.Coins(storeBlob.LightningMaxValue.Value / currentRateToCrypto.BidAsk.Bid); if (amount > limitValueCrypto) { return "The amount of the invoice is too high to be paid with lightning"; } } } return string.Empty; } public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse, StoreBlob storeBlob) { var paymentMethodId = new PaymentMethodId(model.CryptoCode, PaymentTypes.LightningLike); var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork<BTCPayNetwork>(model.CryptoCode); model.IsLightning = true; model.PaymentMethodName = GetPaymentMethodName(network); model.InvoiceBitcoinUrl = cryptoInfo.PaymentUrls.BOLT11; model.InvoiceBitcoinUrlQR = $"lightning:{cryptoInfo.PaymentUrls.BOLT11.ToUpperInvariant().Substring("LIGHTNING:".Length)}"; model.LightningAmountInSatoshi = storeBlob.LightningAmountInSatoshi; if (storeBlob.LightningAmountInSatoshi && model.CryptoCode == "BTC") { var satoshiCulture = new CultureInfo(CultureInfo.InvariantCulture.Name); satoshiCulture.NumberFormat.NumberGroupSeparator = " "; model.CryptoCode = "Sats"; model.BtcDue = Money.Parse(model.BtcDue).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.BtcPaid = Money.Parse(model.BtcPaid).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.OrderAmount = Money.Parse(model.OrderAmount).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.NetworkFee = new Money(model.NetworkFee, MoneyUnit.BTC).ToUnit(MoneyUnit.Satoshi); } } public override string GetCryptoImage(PaymentMethodId paymentMethodId) { var network = _networkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode); return GetCryptoImage(network); } private string GetCryptoImage(BTCPayNetworkBase network) { return ((BTCPayNetwork)network).LightningImagePath; } public override string GetPaymentMethodName(PaymentMethodId paymentMethodId) { var network = _networkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode); return GetPaymentMethodName(network); } private string GetPaymentMethodName(BTCPayNetworkBase network) { return $"{network.DisplayName} (Lightning)"; } } }
47.799087
160
0.638326
[ "MIT" ]
Javdu10/btcpayserver
BTCPayServer/Payments/Lightning/LightningLikePaymentHandler.cs
10,468
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using HRM.BOL; namespace HRM.DAL { public class OverTimeDAL { public string Save(OverTimeBOL objovertime) { DataAccess objDA = new DataAccess(); List<SqlParameter> objParam = new List<SqlParameter>(); try { objParam.Add(new SqlParameter("@RId", objovertime.RId)); objParam.Add(new SqlParameter("@MinimumHr", objovertime.MinimumHr)); objParam.Add(new SqlParameter("@Ruleapplicable",objovertime.Ruleapplicable)); objParam.Add(new SqlParameter("@ApplicableSum", objovertime.ApplicableSum)); objParam.Add(new SqlParameter("@CreatedBy", objovertime.CreatedBy)); objParam.Add(new SqlParameter("@ModifiedBy", objovertime.ModifiedBy)); objDA.sqlCmdText = "hrm_Overtimerule_Insert_Update"; objDA.sqlParam = objParam.ToArray(); return objDA.ExecuteScalar().ToString(); } catch (Exception ex) { throw ex; } } public DataTable selectall(OverTimeBOL objbol) { DataAccess objDA = new DataAccess(); try { objDA.sqlCmdText = "hrm_Overtime_SelectAll"; return objDA.ExecuteDataSet().Tables[0]; } catch (Exception ex) { throw ex; } } } }
30.745455
94
0.531638
[ "MIT" ]
jencyraj/HumanResourceManagementProject
src/HRM.DAL/OverTimeDAL.cs
1,693
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace DNDSoundboard { [Serializable] public class YoutubeLink { public string LinkName { get; set; } public string LinkURL { get; set; } public YoutubeLink(string Name, string URL) { LinkName = Name; LinkURL = URL; } } }
21.583333
54
0.617761
[ "Apache-2.0" ]
Tian94/DNDSoundboard
YoutubeLink.cs
520
C#
namespace Tessin.Bladerunner { public enum Theme { Primary, Secondary, PrimaryAlternate, SecondaryAlternate, Error, Success, Alert, Empty } }
14.6
29
0.515982
[ "MIT" ]
tessin/tessin-bladrunner
Tessin.Bladerunner/Theme.cs
221
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Log files monitor and archiver using System; using System.Threading.Tasks; namespace DotNet.LogFilesMonitorArchiver { /// <summary> /// The archive request container. /// It encapsulates the archive processor command and async completion event. /// </summary> public class ArchiveCommand { struct VoidResult { public static VoidResult Result { get; } = new VoidResult(); } TaskCompletionSource<VoidResult> _completion = new TaskCompletionSource<VoidResult>(); /// <summary> /// Defines the list of the processor commands. /// </summary> public enum ArchiveAction { MoveToArchive, DeleteFromArchive } /// <summary> /// Constructs the class. /// </summary> /// <param name="action">The processor action.</param> public ArchiveCommand(ArchiveAction action) { Action = action; } /// <summary> /// Provides the instance of the archive command for Move-To-Archive action. /// </summary> public static ArchiveCommand MoveToArchive => new ArchiveCommand(ArchiveAction.MoveToArchive); /// <summary> /// Provides the instance of the archive command for Delete-From-Archive action. /// </summary> public static ArchiveCommand DeleteFromArchive => new ArchiveCommand(ArchiveAction.DeleteFromArchive); /// <summary> /// The processor action. /// </summary> public ArchiveAction Action { get; } /// <summary> /// Marks the action as a complete. /// </summary> public void MarkComplete() { _completion.TrySetResult(VoidResult.Result); } /// <summary> /// Marks the action as canceled. /// </summary> public void MarkCanceled() { _completion.TrySetCanceled(); } /// <summary> /// Marks the action as a complete. /// </summary> public void MarkException(Exception ex) { Exception = ex; _completion.TrySetException(ex); } /// <summary> /// Gets the completion task. /// </summary> public Task Complete => _completion.Task; /// <summary> /// Execution exception. /// </summary> public Exception Exception { get; set; } } }
28.913043
111
0.573308
[ "Apache-2.0" ]
Wallsmedia/DotNet.LogFilesMonitorArchiver
src/DotNet.LogFilesMonitorArchiver/Processor/ArchiveLogCommand.cs
2,660
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Taken from: https://github.com/dotnet/aspnetcore using System.Text; using Microsoft.Net.Http.Headers; namespace MinimalApis.Extensions.Results; internal static class ResponseContentTypeHelper { /// <summary> /// Gets the content type and encoding that need to be used for the response. /// The priority for selecting the content type is: /// 1. ContentType property set on the action result /// 2. <see cref="HttpResponse.ContentType"/> property set on <see cref="HttpResponse"/> /// 3. Default content type set on the action result /// </summary> /// <remarks> /// The user supplied content type is not modified and is used as is. For example, if user /// sets the content type to be "text/plain" without any encoding, then the default content type's /// encoding is used to write the response and the ContentType header is set to be "text/plain" without any /// "charset" information. /// </remarks> public static void ResolveContentTypeAndEncoding( string? actionResultContentType, string? httpResponseContentType, (string defaultContentType, Encoding defaultEncoding) @default, Func<string, Encoding?> getEncoding, out string resolvedContentType, out Encoding resolvedContentTypeEncoding) { var (defaultContentType, defaultContentTypeEncoding) = @default; // 1. User sets the ContentType property on the action result if (actionResultContentType != null) { resolvedContentType = actionResultContentType; var actionResultEncoding = getEncoding(actionResultContentType); resolvedContentTypeEncoding = actionResultEncoding ?? defaultContentTypeEncoding; return; } // 2. User sets the ContentType property on the http response directly if (!string.IsNullOrEmpty(httpResponseContentType)) { var mediaTypeEncoding = getEncoding(httpResponseContentType); if (mediaTypeEncoding != null) { resolvedContentType = httpResponseContentType; resolvedContentTypeEncoding = mediaTypeEncoding; } else { resolvedContentType = httpResponseContentType; resolvedContentTypeEncoding = defaultContentTypeEncoding; } return; } // 3. Fall-back to the default content type resolvedContentType = defaultContentType; resolvedContentTypeEncoding = defaultContentTypeEncoding; } public static Encoding? GetEncoding(string mediaType) { if (MediaTypeHeaderValue.TryParse(mediaType, out var parsed)) { return parsed.Encoding; } return default; } }
37.717949
111
0.666553
[ "MIT" ]
DamianEdwards/MinimalApis.Extensions
src/MinimalApis.Extensions/Results/ResponseContentTypeHelper.cs
2,944
C#
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using SimpleOrderApp.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleOrderApp.Data { class OrderRepository : IOrderRepository { private readonly SimpleOrderContext _context; public OrderRepository(SimpleOrderContext context) { _context = context; } public void Create(Order order) { OrderEntity entity = new OrderEntity { Id = order.Id, Quantity = order.Quantity, Location = new LocationEntity { Name = order.Location.Name, Stock = order.Location.Stock } }; _context.Add(entity); _context.SaveChanges(); } public IEnumerable<Order> GetAll() { var entities = _context.Orders.ToList(); return entities.Select(e => new Order(e.Quantity, new Location(e.Location.Name, e.Location.Stock), e.Placed)); } } }
26.675
122
0.608247
[ "MIT" ]
2006-jun15-net/noah-code
Week3GitHTML/SimpleOrderApp/SimpleOrderApp.Data/OrderRepository.cs
1,069
C#
using System.Collections.Generic; namespace RobotService.Models.Procedures { using RobotService.Models.Robots.Contracts; public class Rest : Procedure { private const int DecreaseHappiness = 3; private const int IncreaseEnergy = 10; public Rest() { this.robots = new HashSet<IRobot>(); } public override void DoService(IRobot robot, int procedureTime) { base.DoService(robot, procedureTime); robot.Happiness -= DecreaseHappiness; robot.Energy += IncreaseEnergy; this.robots.Add(robot); } } }
25.44
71
0.608491
[ "MIT" ]
tonkatawe/SoftUni-Advanced
OOP/EXAMS/OOP Retake Exam - 16 Apr 2020/RobotService/Models/Procedures/Rest.cs
638
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RestSharp; namespace GwApiNET.ResponseObjects.Parsers { /// <summary> /// Parser for event_names.json /// </summary> public class EventNameEntryParser : IApiResponseParserAsync<EntryDictionary<Guid,EventNameEntry>> { /// <summary> /// Default Constructor /// </summary> public EventNameEntryParser() { } /// <summary> /// Parses the response object. /// </summary> /// <param name="apiResponse">raw response from the GW2 Server</param> /// <returns>Parsed object</returns> public EntryDictionary<Guid,EventNameEntry> Parse(object apiResponse) { string json = ParserResponseHelper.GetResponseString(apiResponse); EntryCollection<EventNameEntry> entries = ParserHelper<EntryCollection<EventNameEntry>>.Parse(json); var dict = entries.ToEntryDictionary(e => e.Id); return dict; } public async Task<EntryDictionary<Guid, EventNameEntry>> ParseAsync(object apiResponse) { string json = ParserResponseHelper.GetResponseString(apiResponse); EntryCollection<EventNameEntry> entries = await ParserHelper<EntryCollection<EventNameEntry>>.ParseAsync(json).ConfigureAwait(false); var dict = entries.ToEntryDictionary(e => e.Id); return dict; } } }
34.5
145
0.651515
[ "MIT" ]
prbarcelon/GwApiNET
GwApiNET/GwApiNET/ResponseObjects/Parsers/EventNameEntryParser.cs
1,520
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Runtime.InteropServices; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.Graphics.Display; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Windows.UI.Xaml.Controls; namespace Microsoft.Xna.Framework { partial class UAPGameWindow : GameWindow { private DisplayOrientation _supportedOrientations; private DisplayOrientation _orientation; private CoreWindow _coreWindow; private DisplayInformation _dinfo; private ApplicationView _appView; private Rectangle _viewBounds; private object _eventLocker = new object(); private InputEvents _inputEvents; private readonly ConcurrentQueue<char> _textQueue = new ConcurrentQueue<char>(); private bool _isSizeChanged = false; private Rectangle _newViewBounds; private bool _isOrientationChanged = false; private DisplayOrientation _newOrientation; private bool _isFocusChanged = false; private CoreWindowActivationState _newActivationState; private bool _backPressed = false; #region Internal Properties internal Game Game { get; set; } public ApplicationView AppView { get { return _appView; } } internal bool IsExiting { get; set; } #endregion #region Public Properties public override IntPtr Handle { get { return Marshal.GetIUnknownForObject(_coreWindow); } } public override string ScreenDeviceName { get { return String.Empty; } } // window.Title public override Rectangle ClientBounds { get { return _viewBounds; } } public override bool AllowUserResizing { get { return false; } set { // You cannot resize a Metro window! } } public override DisplayOrientation CurrentOrientation { get { return _orientation; } } private UAPGamePlatform Platform { get { return Game.Instance.Platform as UAPGamePlatform; } } protected internal override void SetSupportedOrientations(DisplayOrientation orientations) { // We don't want to trigger orientation changes // when no preference is being changed. if (_supportedOrientations == orientations) return; _supportedOrientations = orientations; DisplayOrientations supported; if (orientations == DisplayOrientation.Default) { // Make the decision based on the preferred backbuffer dimensions. var manager = Game.graphicsDeviceManager; if (manager.PreferredBackBufferWidth > manager.PreferredBackBufferHeight) supported = FromOrientation(DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight); else supported = FromOrientation(DisplayOrientation.Portrait | DisplayOrientation.PortraitDown); } else supported = FromOrientation(orientations); DisplayInformation.AutoRotationPreferences = supported; } #endregion static public UAPGameWindow Instance { get; private set; } static UAPGameWindow() { Instance = new UAPGameWindow(); } public void Initialize(CoreWindow coreWindow, UIElement inputElement, TouchQueue touchQueue) { _coreWindow = coreWindow; _inputEvents = new InputEvents(_coreWindow, inputElement, touchQueue); _dinfo = DisplayInformation.GetForCurrentView(); _appView = ApplicationView.GetForCurrentView(); // Set a min size that is reasonable knowing someone might try // to use some old school resolution like 640x480. var minSize = new Windows.Foundation.Size(640 / _dinfo.RawPixelsPerViewPixel, 480 / _dinfo.RawPixelsPerViewPixel); _appView.SetPreferredMinSize(minSize); _orientation = ToOrientation(_dinfo.CurrentOrientation); _dinfo.OrientationChanged += DisplayProperties_OrientationChanged; _coreWindow.SizeChanged += Window_SizeChanged; _coreWindow.Closed += Window_Closed; _coreWindow.Activated += Window_FocusChanged; _coreWindow.CharacterReceived += Window_CharacterReceived; SystemNavigationManager.GetForCurrentView().BackRequested += BackRequested; SetViewBounds(_appView.VisibleBounds.Width, _appView.VisibleBounds.Height); SetCursor(false); } private void Window_FocusChanged(CoreWindow sender, WindowActivatedEventArgs args) { lock (_eventLocker) { _isFocusChanged = true; _newActivationState = args.WindowActivationState; } } private void UpdateFocus() { lock (_eventLocker) { _isFocusChanged = false; if (_newActivationState == CoreWindowActivationState.Deactivated) Platform.IsActive = false; else Platform.IsActive = true; } } private void Window_Closed(CoreWindow sender, CoreWindowEventArgs args) { Game.SuppressDraw(); Game.Platform.Exit(); } private void SetViewBounds(double width, double height) { var pixelWidth = Math.Max(1, (int)Math.Round(width * _dinfo.RawPixelsPerViewPixel)); var pixelHeight = Math.Max(1, (int)Math.Round(height * _dinfo.RawPixelsPerViewPixel)); _viewBounds = new Rectangle(0, 0, pixelWidth, pixelHeight); } private void Window_SizeChanged(object sender, WindowSizeChangedEventArgs args) { lock (_eventLocker) { _isSizeChanged = true; var pixelWidth = Math.Max(1, (int)Math.Round(args.Size.Width * _dinfo.RawPixelsPerViewPixel)); var pixelHeight = Math.Max(1, (int)Math.Round(args.Size.Height * _dinfo.RawPixelsPerViewPixel)); _newViewBounds = new Rectangle(0, 0, pixelWidth, pixelHeight); } } private void UpdateSize() { lock (_eventLocker) { _isSizeChanged = false; var manager = Game.graphicsDeviceManager; // Set the new client bounds. _viewBounds = _newViewBounds; // Set the default new back buffer size and viewport, but this // can be overloaded by the two events below. manager.IsFullScreen = _appView.IsFullScreenMode; manager.PreferredBackBufferWidth = _viewBounds.Width; manager.PreferredBackBufferHeight = _viewBounds.Height; manager.ApplyChanges(); // Set the new view state which will trigger the // Game.ApplicationViewChanged event and signal // the client size changed event. OnClientSizeChanged(); } } private void Window_CharacterReceived(CoreWindow sender, CharacterReceivedEventArgs args) { _textQueue.Enqueue((char)args.KeyCode); } private void UpdateTextInput() { char ch; while (_textQueue.TryDequeue(out ch)) OnTextInput(_coreWindow, new TextInputEventArgs(ch)); } private static DisplayOrientation ToOrientation(DisplayOrientations orientations) { var result = DisplayOrientation.Default; if ((orientations & DisplayOrientations.Landscape) != 0) result |= DisplayOrientation.LandscapeLeft; if ((orientations & DisplayOrientations.LandscapeFlipped) != 0) result |= DisplayOrientation.LandscapeRight; if ((orientations & DisplayOrientations.Portrait) != 0) result |= DisplayOrientation.Portrait; if ((orientations & DisplayOrientations.PortraitFlipped) != 0) result |= DisplayOrientation.PortraitDown; return result; } private static DisplayOrientations FromOrientation(DisplayOrientation orientation) { var result = DisplayOrientations.None; if ((orientation & DisplayOrientation.LandscapeLeft) != 0) result |= DisplayOrientations.Landscape; if ((orientation & DisplayOrientation.LandscapeRight) != 0) result |= DisplayOrientations.LandscapeFlipped; if ((orientation & DisplayOrientation.Portrait) != 0) result |= DisplayOrientations.Portrait; if ((orientation & DisplayOrientation.PortraitDown) != 0) result |= DisplayOrientations.PortraitFlipped; return result; } internal void SetClientSize(int width, int height) { if (_appView.IsFullScreenMode) return; if (_viewBounds.Width == width && _viewBounds.Height == height) return; var viewSize = new Windows.Foundation.Size(width / _dinfo.RawPixelsPerViewPixel, height / _dinfo.RawPixelsPerViewPixel); //_appView.SetPreferredMinSize(viewSize); if (!_appView.TryResizeView(viewSize)) { // TODO: What now? } } private void DisplayProperties_OrientationChanged(DisplayInformation dinfo, object sender) { lock(_eventLocker) { _isOrientationChanged = true; _newOrientation = ToOrientation(dinfo.CurrentOrientation); } } private void UpdateOrientation() { lock (_eventLocker) { _isOrientationChanged = false; // Set the new orientation. _orientation = _newOrientation; // Call the user callback. OnOrientationChanged(); // If we have a valid client bounds then update the graphics device. if (_viewBounds.Width > 0 && _viewBounds.Height > 0) Game.graphicsDeviceManager.ApplyChanges(); } } private void BackRequested(object sender, BackRequestedEventArgs e) { // We need to manually hide the keyboard input UI when the back button is pressed if (KeyboardInput.IsVisible) KeyboardInput.Cancel(null); else _backPressed = true; e.Handled = true; } private void UpdateBackButton() { GamePad.Back = _backPressed; _backPressed = false; } protected override void SetTitle(string title) { Debug.WriteLine("WARNING: GameWindow.Title has no effect under UWP."); } internal void SetCursor(bool visible) { if ( _coreWindow == null ) return; var asyncResult = _coreWindow.Dispatcher.RunIdleAsync( (e) => { if (visible) _coreWindow.PointerCursor = new CoreCursor(CoreCursorType.Arrow, 0); else _coreWindow.PointerCursor = null; }); } internal void RunLoop() { SetCursor(Game.IsMouseVisible); _coreWindow.Activate(); while (true) { // Process events incoming to the window. _coreWindow.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent); Tick(); if (IsExiting) break; } } void ProcessWindowEvents() { // Update input _inputEvents.UpdateState(); // Update TextInput if(!_textQueue.IsEmpty) UpdateTextInput(); // Update size if (_isSizeChanged) UpdateSize(); // Update orientation if (_isOrientationChanged) UpdateOrientation(); // Update focus if (_isFocusChanged) UpdateFocus(); // Update back button UpdateBackButton(); } internal void Tick() { // Update state based on window events. ProcessWindowEvents(); // Update and render the game. if (Game != null) Game.Tick(); } #region Public Methods public void Dispose() { //window.Dispose(); } public override void BeginScreenDeviceChange(bool willBeFullScreen) { } public override void EndScreenDeviceChange(string screenDeviceName, int clientWidth, int clientHeight) { } #endregion } }
33.191646
132
0.59168
[ "MIT" ]
PocketwatchGames/MonoGame
MonoGame.Framework/WindowsUniversal/UAPGameWindow.cs
13,511
C#
using Amazon.JSII.Runtime.Deputy; namespace Amazon.JSII.Tests.CalculatorNamespace { /// <remarks> /// <strong>Stability</strong>: Experimental /// </remarks> [JsiiTypeProxy(nativeType: typeof(IJsii496), fullyQualifiedName: "jsii-calc.IJsii496")] internal sealed class IJsii496Proxy : DeputyBase, Amazon.JSII.Tests.CalculatorNamespace.IJsii496 { private IJsii496Proxy(ByRefValue reference): base(reference) { } } }
29.1875
100
0.695931
[ "Apache-2.0" ]
tobli/jsii
packages/jsii-pacmak/test/expected.jsii-calc/dotnet/Amazon.JSII.Tests.CalculatorPackageId/Amazon/JSII/Tests/CalculatorNamespace/IJsii496Proxy.cs
467
C#
using Ardalis.ListStartupServices; using BlazorAdmin; using BlazorAdmin.Services; using Blazored.LocalStorage; using BlazorShared; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.EntityFrameworkCore; using Microsoft.eShopWeb.ApplicationCore.Interfaces; using Microsoft.eShopWeb.Infrastructure.Data; using Microsoft.eShopWeb.Infrastructure.Identity; using Microsoft.eShopWeb.Web.Configuration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Mime; namespace Microsoft.eShopWeb.Web { public class Startup { private IServiceCollection _services; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureDevelopmentServices(IServiceCollection services) { // use in-memory database ConfigureInMemoryDatabases(services); // use real database //ConfigureProductionServices(services); } public void ConfigureDockerServices(IServiceCollection services) { services.AddDataProtection() .SetApplicationName("eshopwebmvc") .PersistKeysToFileSystem(new DirectoryInfo(@"./")); ConfigureDevelopmentServices(services); } private void ConfigureInMemoryDatabases(IServiceCollection services) { // use in-memory database services.AddDbContext<CatalogContext>(c => c.UseInMemoryDatabase("Catalog")); // Add Identity DbContext services.AddDbContext<AppIdentityDbContext>(options => options.UseInMemoryDatabase("Identity")); ConfigureServices(services); } public void ConfigureProductionServices(IServiceCollection services) { // use real database // Requires LocalDB which can be installed with SQL Server Express 2016 // https://www.microsoft.com/en-us/download/details.aspx?id=54284 services.AddDbContext<CatalogContext>(c => c.UseSqlServer(Configuration.GetConnectionString("CatalogConnection"))); // Add Identity DbContext services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection"))); ConfigureServices(services); } public void ConfigureTestingServices(IServiceCollection services) { ConfigureInMemoryDatabases(services); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCookieSettings(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.Lax; }); services.AddIdentity<ApplicationUser, IdentityRole>() .AddDefaultUI() .AddEntityFrameworkStores<AppIdentityDbContext>() .AddDefaultTokenProviders(); services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>(); services.AddCoreServices(Configuration); services.AddWebServices(Configuration); // Add memory cache services services.AddMemoryCache(); services.AddRouting(options => { // Replace the type and the name used to refer to it with your own // IOutboundParameterTransformer implementation options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer); }); services.AddMvc(options => { options.Conventions.Add(new RouteTokenTransformerConvention( new SlugifyParameterTransformer())); }); services.AddControllersWithViews(); services.AddRazorPages(options => { options.Conventions.AuthorizePage("/Basket/Checkout"); }); services.AddHttpContextAccessor(); services.AddHealthChecks(); services.Configure<ServiceConfig>(config => { config.Services = new List<ServiceDescriptor>(services); config.Path = "/allservices"; }); var baseUrlConfig = new BaseUrlConfiguration(); Configuration.Bind(BaseUrlConfiguration.CONFIG_NAME, baseUrlConfig); services.AddScoped<BaseUrlConfiguration>(sp => baseUrlConfig); // Blazor Admin Required Services for Prerendering services.AddScoped<HttpClient>(s => new HttpClient { BaseAddress = new Uri(baseUrlConfig.WebBase) }); // add blazor services services.AddBlazoredLocalStorage(); services.AddServerSideBlazor(); services.AddScoped<ToastService>(); services.AddScoped<HttpService>(); services.AddBlazorServices(); services.AddDatabaseDeveloperPageExceptionFilter(); _services = services; // used to debug registered services } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var catalogBaseUrl = Configuration.GetValue(typeof(string), "CatalogBaseUrl") as string; if (!string.IsNullOrEmpty(catalogBaseUrl)) { app.Use((context, next) => { context.Request.PathBase = new PathString(catalogBaseUrl); return next(); }); } app.UseHealthChecks("/health", new HealthCheckOptions { ResponseWriter = async (context, report) => { var result = new { status = report.Status.ToString(), errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) }) }.ToJson(); context.Response.ContentType = MediaTypeNames.Application.Json; await context.Response.WriteAsync(result); } }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseShowAllServicesMiddleware(); app.UseMigrationsEndPoint(); app.UseWebAssemblyDebugging(); } 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.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}"); endpoints.MapRazorPages(); endpoints.MapHealthChecks("home_page_health_check"); endpoints.MapHealthChecks("api_health_check"); //endpoints.MapBlazorHub("/admin"); endpoints.MapFallbackToFile("index.html"); }); } } }
36.895397
143
0.592311
[ "MIT" ]
Akhildas-github/eShopOnWeb
src/Web/Startup.cs
8,820
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using OAuth.Samples.Common; using OAuth.Samples.Common.DataContext; using OAuth.Samples.Common.Services; namespace ClientCredentialGrant.JsonWebKey { class Program { public static async Task Main() { IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddUserSecrets<Program>(optional: true) .Build(); var serviceProvider = new ServiceCollection() .AddSingleton(config.GetSection("OAuth").Get<OAuthOptions>()) .AddSingleton<IAppHost, AppHost>() .AddSingleton(config) .AddHttpClient() .AddDbContext<OAuthDbContext>(options => options.UseInMemoryDatabase(databaseName: "OAuthDB")) .AddScoped<IDataProvider, DataProvider>() .BuildServiceProvider(); await serviceProvider.GetService<IAppHost>().RunAsync(); Console.Read(); } } }
34.078947
110
0.64556
[ "MIT" ]
Informatievlaanderen/GIPOD
OAuth.Samples/ClientCredentialGrant.JsonWebKey/Program.cs
1,297
C#
using Microsoft.EntityFrameworkCore; using Ordering.Domain.Common; using Ordering.Domain.Entities; using System; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ordering.Infrastructure.Persistence { public class OrderContext : DbContext { public OrderContext(DbContextOptions<OrderContext> options) : base(options) { } public DbSet<Order> Orders { get; set; } public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) { foreach (var entry in ChangeTracker.Entries<EntityBase>()) { switch (entry.State) { case EntityState.Added: entry.Entity.CreatedDate = DateTime.Now; entry.Entity.CreatedBy = "swn"; break; case EntityState.Modified: entry.Entity.LastModifiedDate = DateTime.Now; entry.Entity.LastModifiedBy = "swn"; break; } } return base.SaveChangesAsync(cancellationToken); } } }
31.25641
113
0.569319
[ "MIT" ]
dhruv050992/AspNetMicroservices
src/Services/Ordering/Ordering.Infrastructure/Persistence/OrderContext.cs
1,221
C#
using System; using Chromely; using Chromely.Core; using Chromely.Core.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace ChromelyReact { class Program { [STAThread] static void Main(string[] args) { var config = DefaultConfiguration.CreateForRuntimePlatform(); config.StartUrl = "local://dist/index.html"; AppBuilder .Create() .UseConfig<DefaultConfiguration>(config) .UseApp<DemoApp>() .Build() .Run(args); } } public class DemoApp : ChromelyBasicApp { public override void ConfigureServices(ServiceCollection services) { base.ConfigureServices(services); services.AddLogging(configure => configure.AddConsole()); services.AddLogging(configure => configure.AddFile("Logs/serilog-{Date}.txt")); /* // Optional - adding custom handler services.AddSingleton<CefDragHandler, CustomDragHandler>(); */ /* // Optional- using config section to register IChromelyConfiguration // This just shows how it can be used, developers can use custom classes to override this approach // var builder = new ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var configuration = builder.Build(); var config = DefaultConfiguration.CreateFromConfigSection(configuration); services.AddSingleton<IChromelyConfiguration>(config); */ /* Optional var options = new JsonSerializerOptions(); options.ReadCommentHandling = JsonCommentHandling.Skip; options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.AllowTrailingCommas = true; services.AddSingleton<JsonSerializerOptions>(options); */ RegisterControllerAssembly(services, typeof(DemoApp).Assembly); } } // Windows only public class Demo2App : ChromelyFramelessApp { public override void ConfigureServices(ServiceCollection services) { base.ConfigureServices(services); services.AddLogging(configure => configure.AddConsole()); services.AddLogging(configure => configure.AddFile("Logs/serilog-{Date}.txt")); RegisterControllerAssembly(services, typeof(DemoApp).Assembly); } } }
34.25974
110
0.622062
[ "MIT", "BSD-3-Clause" ]
MarcosSiega/demo-projects
angular-react-vue/ChromelyReact/Program.cs
2,640
C#
using System; namespace Bertozzi.Mattia._4H.Levensthien { class Program { static void Main(string[] args) { //cambiare le parole per prove diverse //1. Console.WriteLine($"Costante: {DistanzaLevenshtein("saturday", "sunday")}"); Console.WriteLine("\n"); //Console.WriteLine($"Costante: {DistanzaLevenshtein("rombo", "tromba")}"); //string g = "casa"; //Console.WriteLine($"{g[2]}"); } public static int DistanzaLevenshtein(string s, string t) { //2. //se parola ha 4 lettere la matrice avrà quindi 5 righe s = s.ToLower(); t = t.ToLower(); int n = s.Length; int m = t.Length; //2.1. if(n==0) { //se n=0 su ha DL=m,stampare DL e terminare //quindi stampo m return m; } //2.2. if (m==0) { //se n=0 su ha DL=m,stampare DL e terminare //quindi stampo n return n; } //3. //es: se parola ha 4 lettere la matrice quindi 5 righe,quindi n+1 int[,] d = new int[n + 1, m + 1]; //3.1 inizializzo la prima riga con i valori da 0 a n for (int i = 0; i <= n;i++) { d[i, 0] = i; } //3.2 inizializzo la prima colonna con i valori da 0 a n for (int j = 0; j <= m;j++) { d[0, j] = j; } //4. giro la matrice e faccio quel che devo for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int costo; //4.1 se t[j] = s[i] allora costo=0 oppure costo=1 //dove t[] sarebbe il carattere della prima parola //dove s[] sarebbe il carattere della seconda parola if(t[j - 1] == s[i - 1]) { costo = 0; } else { costo = 1; } //4.2 //prendo il minimo valore fra questi int a = d[i - 1, j] + 1; int b = d[i, j - 1] + 1; int c = d[i - 1, j - 1] + costo; if (a <= b && a <= c) { d[i, j] = a; } else if (b <= c && b <= a) { d[i, j] = b; } else { d[i, j] = c; } } } //stampa extra //Console.WriteLine($"Parole prese:\n\t{s}\n\t{t}\n"); //Console.WriteLine("Stampo la matrice"); //for (int i = 0; i <=n; i++) //{ // Console.WriteLine("\n"); // for (int j = 0; j <=m; j++) // Console.Write(d[i,j]); //} StampaMatrice(s, t, n, m, d); Console.WriteLine("\n"); //5. return d[n,m]; } static void StampaMatrice(string s, string t, int n, int m, int[,] d) { //stampa extra Console.WriteLine($"Parole prese:\n\t{s}\n\t{t}\n"); Console.WriteLine("Stampo la matrice"); for (int i = 0; i <= n; i++) { Console.WriteLine("\n"); for (int j = 0; j <= m; j++) Console.Write(d[i, j]); } } } }
29.082707
88
0.346691
[ "MIT" ]
Rimac48/Bertozzi.Mattia.4H.Levenshtein
Vecchio/Bertozzi.Mattia.4H.Levensthien/Program.cs
3,871
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Playnite.SDK; using Playnite.SDK.Models; using Playnite.SDK.Plugins; using System.IO; using System; using System.Linq; using System.Collections.Generic; using System.Windows.Controls; using System.Timers; using System.Diagnostics; using MSIAfterburnerNET.HM.Interop; using System.Reflection; using CommonPluginsShared; using System.Windows; using Playnite.SDK.Events; using GameActivity.Models; using GameActivity.Services; using GameActivity.Views; using System.Threading.Tasks; namespace GameActivity { public class GameActivity : Plugin { private static readonly ILogger logger = LogManager.GetLogger(); private static IResourceProvider resources = new ResourceProvider(); private GameActivitySettings settings { get; set; } public override Guid Id { get; } = Guid.Parse("afbb1a0d-04a1-4d0c-9afa-c6e42ca855b4"); public static IGameDatabase DatabaseReference; public static string pluginFolder; public static ActivityDatabase PluginDatabase; public static GameActivityUI gameActivityUI; // Variables timer function public Timer t { get; set; } private GameActivities GameActivitiesLog; public List<WarningData> WarningsMessage { get; set; } = new List<WarningData>(); private OldToNew oldToNew; public GameActivity(IPlayniteAPI api) : base(api) { settings = new GameActivitySettings(this); DatabaseReference = PlayniteApi.Database; // Old database oldToNew = new OldToNew(this.GetPluginUserDataPath()); // Loading plugin database PluginDatabase = new ActivityDatabase(PlayniteApi, settings, this.GetPluginUserDataPath()); PluginDatabase.InitializeDatabase(); // Temp Task.Run(() => { System.Threading.SpinWait.SpinUntil(() => PluginDatabase.IsLoaded, -1); settings.tmp = true; this.SavePluginSettings(settings); }); // Get plugin's location pluginFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // Add plugin localization in application ressource. PluginLocalization.SetPluginLanguage(pluginFolder, api.ApplicationSettings.Language); // Add common in application ressource. Common.Load(pluginFolder); Common.SetEvent(PlayniteApi); // Check version if (settings.EnableCheckVersion) { CheckVersion cv = new CheckVersion(); cv.Check("GameActivity", pluginFolder, api); } // Init ui interagration gameActivityUI = new GameActivityUI(api, settings, this.GetPluginUserDataPath()); // Custom theme button EventManager.RegisterClassHandler(typeof(Button), Button.ClickEvent, new RoutedEventHandler(gameActivityUI.OnCustomThemeButtonClick)); // Add event fullScreen if (api.ApplicationInfo.Mode == ApplicationMode.Fullscreen) { EventManager.RegisterClassHandler(typeof(Button), Button.ClickEvent, new RoutedEventHandler(BtFullScreen_ClickEvent)); } } #region Custom event private void BtFullScreen_ClickEvent(object sender, System.EventArgs e) { try { if (((Button)sender).Name == "PART_ButtonDetails") { var TaskIntegrationUI = Task.Run(() => { gameActivityUI.Initial(); gameActivityUI.taskHelper.Check(); var dispatcherOp = gameActivityUI.AddElementsFS(); dispatcherOp.Completed += (s, ev) => { gameActivityUI.RefreshElements(ActivityDatabase.GameSelected); }; }); } } catch (Exception ex) { Common.LogError(ex, "GameActivity"); } } #endregion // To add new game menu items override GetGameMenuItems public override List<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args) { Game GameMenu = args.Games.First(); List<GameMenuItem> gameMenuItems = new List<GameMenuItem> { // Show plugin view with all activities for all game in database with data of selected game new GameMenuItem { //MenuSection = "", Icon = Path.Combine(pluginFolder, "icon.png"), Description = resources.GetString("LOCGameActivityViewGameActivity"), Action = (gameMenuItem) => { DatabaseReference = PlayniteApi.Database; var ViewExtension = new GameActivityView(settings, PlayniteApi, this.GetPluginUserDataPath(), GameMenu); Window windowExtension = PlayniteUiHelper.CreateExtensionWindow(PlayniteApi, resources.GetString("LOCGameActivity"), ViewExtension); windowExtension.ShowDialog(); } } }; #if DEBUG gameMenuItems.Add(new GameMenuItem { MenuSection = resources.GetString("LOCGameActivity"), Description = "Test", Action = (mainMenuItem) => { } }); #endif return gameMenuItems; } // To add new main menu items override GetMainMenuItems public override List<MainMenuItem> GetMainMenuItems(GetMainMenuItemsArgs args) { string MenuInExtensions = string.Empty; if (settings.MenuInExtensions) { MenuInExtensions = "@"; } List<MainMenuItem> mainMenuItems = new List<MainMenuItem> { // Show plugin view with all activities for all game in database new MainMenuItem { MenuSection = MenuInExtensions + resources.GetString("LOCGameActivity"), Description = resources.GetString("LOCGameActivityViewGamesActivities"), Action = (mainMenuItem) => { DatabaseReference = PlayniteApi.Database; var ViewExtension = new GameActivityView(settings, PlayniteApi, this.GetPluginUserDataPath()); Window windowExtension = PlayniteUiHelper.CreateExtensionWindow(PlayniteApi, resources.GetString("LOCGameActivity"), ViewExtension); windowExtension.ShowDialog(); } } }; #if DEBUG mainMenuItems.Add(new MainMenuItem { MenuSection = MenuInExtensions + resources.GetString("LOCGameActivity"), Description = "Test", Action = (mainMenuItem) => { } }); #endif return mainMenuItems; } public override void OnGameSelected(GameSelectionEventArgs args) { // Old database if (oldToNew.IsOld) { oldToNew.ConvertDB(PlayniteApi); } try { if (args.NewValue != null && args.NewValue.Count == 1) { ActivityDatabase.GameSelected = args.NewValue[0]; #if DEBUG logger.Debug($"GameActivity [Ignored] - OnGameSelected() - {ActivityDatabase.GameSelected.Name} - {ActivityDatabase.GameSelected.Id.ToString()}"); #endif if (settings.EnableIntegrationInCustomTheme || settings.EnableIntegrationInDescription) { PlayniteUiHelper.ResetToggle(); var TaskIntegrationUI = Task.Run(() => { gameActivityUI.Initial(); gameActivityUI.taskHelper.Check(); var dispatcherOp = gameActivityUI.AddElements(); if (dispatcherOp != null) { dispatcherOp.Completed += (s, e) => { gameActivityUI.RefreshElements(args.NewValue[0]); }; } }); } } } catch (Exception ex) { Common.LogError(ex, "GameActivity"); } } // Add code to be executed when game is finished installing. public override void OnGameInstalled(Game game) { } // Add code to be executed when game is started running. public override void OnGameStarted(Game game) { PlayniteUiHelper.ResetToggle(); // start timer si log is enable. if (settings.EnableLogging) { dataHWiNFO_start(); } DateTime DateSession = DateTime.Now.ToUniversalTime(); GameActivitiesLog = PluginDatabase.Get(game); GameActivitiesLog.Items.Add(new Activity { DateSession = DateSession, SourceID = game.SourceId, PlatformID = game.PlatformId }); GameActivitiesLog.ItemsDetails.Items.TryAdd(DateSession, new List<ActivityDetailsData>()); } // Add code to be executed when game is preparing to be started. public override void OnGameStarting(Game game) { } // Add code to be executed when game is preparing to be started. public override void OnGameStopped(Game game, long elapsedSeconds) { var TaskGameStopped = Task.Run(() => { // Stop timer si HWiNFO log is enable. if (settings.EnableLogging) { dataHWiNFO_stop(); } // Infos GameActivitiesLog.GetLastSessionActivity().ElapsedSeconds = elapsedSeconds; PluginDatabase.Update(GameActivitiesLog); // Refresh integration interface var TaskIntegrationUI = Task.Run(() => { var dispatcherOp = gameActivityUI.AddElements(); dispatcherOp.Completed += (s, e) => { gameActivityUI.RefreshElements(ActivityDatabase.GameSelected); }; }); }); } // Add code to be executed when game is uninstalled. public override void OnGameUninstalled(Game game) { } // Add code to be executed when Playnite is initialized. public override void OnApplicationStarted() { gameActivityUI.AddBtHeader(); CheckGoodForLogging(true); } // Add code to be executed when Playnite is shutting down. public override void OnApplicationStopped() { } // Add code to be executed when library is updated. public override void OnLibraryUpdated() { } public override ISettings GetSettings(bool firstRunSettings) { return settings; } public override UserControl GetSettingsView(bool firstRunSettings) { return new GameActivitySettingsView(); } private bool CheckGoodForLogging(bool WithNotification = false) { if (settings.EnableLogging && settings.UseHWiNFO) { bool runHWiNFO = false; Process[] pname = Process.GetProcessesByName("HWiNFO32"); if (pname.Length != 0) { runHWiNFO = true; } else { pname = Process.GetProcessesByName("HWiNFO64"); if (pname.Length != 0) { runHWiNFO = true; } } if (!runHWiNFO && WithNotification) { PlayniteApi.Notifications.Add(new NotificationMessage( $"GameActivity-runHWiNFO", "GameActivity" + Environment.NewLine + resources.GetString("LOCGameActivityNotificationHWiNFO"), NotificationType.Error, () => OpenSettingsView() )); } if (!runHWiNFO) { logger.Error("GameActivity - No HWiNFO running"); } if (!WithNotification) { return runHWiNFO; } } if (settings.EnableLogging && settings.UseMsiAfterburner) { bool runMSI = false; bool runRTSS = false; Process[] pname = Process.GetProcessesByName("MSIAfterburner"); if (pname.Length != 0) { runMSI = true; } pname = Process.GetProcessesByName("RTSS"); if (pname.Length != 0) { runRTSS = true; } if ((!runMSI || !runRTSS) && WithNotification) { PlayniteApi.Notifications.Add(new NotificationMessage( $"GameActivity-runMSI", "GameActivity" + Environment.NewLine + resources.GetString("LOCGameActivityNotificationMSIAfterBurner"), NotificationType.Error, () => OpenSettingsView() )); } if (!runMSI) { logger.Warn("GameActivity - No MSI Afterburner running"); } if (!runRTSS) { logger.Warn("GameActivity - No RivaTunerStatisticsServer running"); } if (!WithNotification) { if ((!runMSI || !runRTSS)) { return false; } return true; } } return false; } #region Timer function /// <summary> /// Start the timer. /// </summary> public void dataHWiNFO_start() { logger.Info("GameActivity - dataLogging_start"); WarningsMessage = new List<WarningData>(); t = new Timer(settings.TimeIntervalLogging * 60000); t.AutoReset = true; t.Elapsed += new ElapsedEventHandler(OnTimedEvent); t.Start(); } /// <summary> /// Stop the timer. /// </summary> public void dataHWiNFO_stop() { logger.Info("GameActivity - dataLogging_stop"); if (WarningsMessage.Count != 0) { try { Application.Current.Dispatcher.BeginInvoke((Action)delegate { var ViewExtension = new WarningsDialogs(WarningsMessage); Window windowExtension = PlayniteUiHelper.CreateExtensionWindow(PlayniteApi, resources.GetString("LOCGameActivityWarningCaption"), ViewExtension); windowExtension.ShowDialog(); WarningsMessage = new List<WarningData>(); }); } catch(Exception ex) { Common.LogError(ex, "GameActivity", $"Error on show WarningsMessage"); } } t.AutoReset = false; t.Stop(); } /// <summary> /// Event excuted with the timer. /// </summary> /// <param name="source"></param> /// <param name="e"></param> private async void OnTimedEvent(Object source, ElapsedEventArgs e) { int fpsValue = 0; int cpuValue = PerfCounter.GetCpuPercentage(); int gpuValue = PerfCounter.GetGpuPercentage(); int ramValue = PerfCounter.GetRamPercentage(); int gpuTValue = PerfCounter.GetGpuTemperature(); int cpuTValue = PerfCounter.GetCpuTemperature(); if (settings.UseMsiAfterburner && CheckGoodForLogging()) { MSIAfterburnerNET.HM.HardwareMonitor MSIAfterburner = null; try { MSIAfterburner = new MSIAfterburnerNET.HM.HardwareMonitor(); } catch (Exception ex) { logger.Warn("GameActivity - Fail initialize MSIAfterburnerNET"); #if DEBUG Common.LogError(ex, "GameActivity [Ignored]", "Fail initialize MSIAfterburnerNET"); #endif } if (MSIAfterburner != null) { try { fpsValue = (int)MSIAfterburner.GetEntry(MONITORING_SOURCE_ID.FRAMERATE).Data; } catch (Exception ex) { logger.Warn("GameActivity - Fail get fpsValue"); #if DEBUG Common.LogError(ex, "GameActivity [Ignored]", "Fail get fpsValue"); #endif } try { if (gpuValue == 0) { gpuValue = (int)MSIAfterburner.GetEntry(MONITORING_SOURCE_ID.GPU_USAGE).Data; } } catch (Exception ex) { logger.Warn("GameActivity - Fail get gpuValue"); #if DEBUG Common.LogError(ex, "GameActivity [Ignored]", "Fail get gpuValue"); #endif } try { if (gpuTValue == 0) { gpuTValue = (int)MSIAfterburner.GetEntry(MONITORING_SOURCE_ID.GPU_TEMPERATURE).Data; } } catch (Exception ex) { logger.Warn("GameActivity - Fail get gpuTValue"); #if DEBUG Common.LogError(ex, "GameActivity [Ignored]", "Fail get gpuTValue"); #endif } try { if (cpuTValue == 0) { cpuTValue = (int)MSIAfterburner.GetEntry(MONITORING_SOURCE_ID.CPU_TEMPERATURE).Data; } } catch (Exception ex) { logger.Warn("GameActivity - Fail get cpuTValue"); #if DEBUG Common.LogError(ex, "GameActivity [Ignored]", "Fail get cpuTValue"); #endif } } } else if (settings.UseHWiNFO && CheckGoodForLogging()) { HWiNFODumper HWinFO = null; List<HWiNFODumper.JsonObj> dataHWinfo = null; try { HWinFO = new HWiNFODumper(); dataHWinfo = HWinFO.ReadMem(); } catch (Exception ex) { logger.Warn("GameActivity - Fail initialize HWiNFODumper"); #if DEBUG Common.LogError(ex, "GameActivity [Ignored]", "Fail initialize HWiNFODumper"); #endif } if (HWinFO != null && dataHWinfo != null) { try { foreach (var sensorItems in dataHWinfo) { JObject sensorItemsOBJ = JObject.Parse(JsonConvert.SerializeObject(sensorItems)); string sensorsID = "0x" + ((uint)sensorItemsOBJ["szSensorSensorID"]).ToString("X"); // Find sensors fps if (sensorsID.ToLower() == settings.HWiNFO_fps_sensorsID.ToLower()) { // Find data fps foreach (var items in sensorItemsOBJ["sensors"]) { JObject itemOBJ = JObject.Parse(JsonConvert.SerializeObject(items)); string dataID = "0x" + ((uint)itemOBJ["dwSensorID"]).ToString("X"); if (dataID.ToLower() == settings.HWiNFO_fps_elementID.ToLower()) { fpsValue = (int)Math.Round((Double)itemOBJ["Value"]); } } } // Find sensors gpu usage if (sensorsID.ToLower() == settings.HWiNFO_gpu_sensorsID.ToLower()) { // Find data gpu foreach (var items in sensorItemsOBJ["sensors"]) { JObject itemOBJ = JObject.Parse(JsonConvert.SerializeObject(items)); string dataID = "0x" + ((uint)itemOBJ["dwSensorID"]).ToString("X"); if (dataID.ToLower() == settings.HWiNFO_gpu_elementID.ToLower()) { gpuValue = (int)Math.Round((Double)itemOBJ["Value"]); } } } // Find sensors gpu temp if (sensorsID.ToLower() == settings.HWiNFO_gpuT_sensorsID.ToLower()) { // Find data gpu foreach (var items in sensorItemsOBJ["sensors"]) { JObject itemOBJ = JObject.Parse(JsonConvert.SerializeObject(items)); string dataID = "0x" + ((uint)itemOBJ["dwSensorID"]).ToString("X"); if (dataID.ToLower() == settings.HWiNFO_gpuT_elementID.ToLower()) { gpuTValue = (int)Math.Round((Double)itemOBJ["Value"]); } } } // Find sensors cpu temp if (sensorsID.ToLower() == settings.HWiNFO_cpuT_sensorsID.ToLower()) { // Find data gpu foreach (var items in sensorItemsOBJ["sensors"]) { JObject itemOBJ = JObject.Parse(JsonConvert.SerializeObject(items)); string dataID = "0x" + ((uint)itemOBJ["dwSensorID"]).ToString("X"); if (dataID.ToLower() == settings.HWiNFO_cpuT_elementID.ToLower()) { cpuTValue = (int)Math.Round((Double)itemOBJ["Value"]); } } } } } catch (Exception ex) { logger.Warn("GameActivity - Fail get HWiNFO"); #if DEBUG Common.LogError(ex, "GameActivity [Ignored]", "Fail get HWiNFO"); #endif } } } // Listing warnings bool WarningMinFps = false; bool WarningMaxCpuTemp = false; bool WarningMaxGpuTemp = false; bool WarningMaxCpuUsage = false; bool WarningMaxGpuUsage = false; bool WarningMaxRamUsage = false; if (settings.EnableWarning) { if (settings.MinFps != 0 && settings.MinFps >= fpsValue) { WarningMinFps = true; } if (settings.MaxCpuTemp != 0 && settings.MaxCpuTemp <= cpuTValue) { WarningMaxCpuTemp = true; } if (settings.MaxGpuTemp != 0 && settings.MaxGpuTemp <= gpuTValue) { WarningMaxGpuTemp = true; } if (settings.MaxCpuUsage != 0 && settings.MaxCpuUsage <= cpuValue) { WarningMaxCpuUsage = true; } if (settings.MaxGpuUsage != 0 && settings.MaxGpuUsage <= gpuValue) { WarningMaxGpuUsage = true; } if (settings.MaxRamUsage != 0 && settings.MaxRamUsage <= ramValue) { WarningMaxRamUsage = true; } WarningData Message = new WarningData { At = resources.GetString("LOCGameActivityWarningAt") + " " + DateTime.Now.ToString("HH:mm"), FpsData = new Data { Name = resources.GetString("LOCGameActivityFps"), Value = fpsValue, IsWarm = WarningMinFps }, CpuTempData = new Data { Name = resources.GetString("LOCGameActivityCpuTemp"), Value = cpuTValue, IsWarm = WarningMaxCpuTemp }, GpuTempData = new Data { Name = resources.GetString("LOCGameActivityGpuTemp"), Value = gpuTValue, IsWarm = WarningMaxGpuTemp }, CpuUsageData = new Data { Name = resources.GetString("LOCGameActivityCpuUsage"), Value = cpuValue, IsWarm = WarningMaxCpuUsage }, GpuUsageData = new Data { Name = resources.GetString("LOCGameActivityGpuUsage"), Value = gpuValue, IsWarm = WarningMaxGpuUsage }, RamUsageData = new Data { Name = resources.GetString("LOCGameActivityRamUsage"), Value = ramValue, IsWarm = WarningMaxRamUsage }, }; if (WarningMinFps || WarningMaxCpuTemp || WarningMaxGpuTemp || WarningMaxCpuUsage || WarningMaxGpuUsage) { WarningsMessage.Add(Message); } } List<ActivityDetailsData> ActivitiesDetailsData = GameActivitiesLog.ItemsDetails.Get(GameActivitiesLog.GetLastSession()); ActivitiesDetailsData.Add(new ActivityDetailsData { Datelog = DateTime.Now.ToUniversalTime(), FPS = fpsValue, CPU = cpuValue, CPUT = cpuTValue, GPU = gpuValue, GPUT = gpuTValue, RAM = ramValue }); } #endregion } }
37.735978
170
0.484829
[ "MIT" ]
scowalt/playnite-gameactivity-plugin
GameActivity.cs
27,587
C#
using System.IO; namespace Pure3D.Chunks { [ChunkType(88072)] public class ParticleAnimation : Chunk { public byte[] Data; private uint unknownType; public ParticleAnimation(File file, uint type) : base(file, type) { unknownType = type; } public override void ReadHeader(Stream stream, long length) { Data = new BinaryReader(stream).ReadBytes((int)length); } public override string ToString() { return $"Unknown Chunk (TypeID: {unknownType}) (Len: {Data.Length})"; } } }
22.777778
81
0.572358
[ "MIT" ]
handsomematt/Pure3D
src/Pure3D/Chunks/ParticleAnimation.cs
615
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SmallRetail.Web.Resources { public class LoginRequest { public string Username { get; set; } public string Password { get; set; } } }
19.357143
44
0.690037
[ "MIT" ]
mfaizudd/SmallRetail
SmallRetail.Web/Resources/LoginRequest.cs
273
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; using System.Threading.Tasks; using WebVella.Pulsar.Models; using WebVella.Pulsar.Utils; using System; using WebVella.Pulsar.Services; using Microsoft.AspNetCore.Components.Web; using Newtonsoft.Json; namespace WebVella.Pulsar.Components { public partial class WvpDisplayEmail : WvpDisplayBase { #region << Parameters >> /// <summary> /// Pattern of accepted string values. Goes with title attribute as description of the pattern /// </summary> [Parameter] public string Value { get; set; } = ""; #endregion #region << Callbacks >> #endregion #region << Private properties >> private List<string> _cssList = new List<string>(); private string _value = ""; #endregion #region << Lifecycle methods >> protected override async Task OnParametersSetAsync() { _cssList = new List<string>(); if (!String.IsNullOrWhiteSpace(Class)) { _cssList.Add(Class); if (!Class.Contains("form-control")) {//Handle input-group case _cssList.Add("form-control-plaintext"); if (String.IsNullOrWhiteSpace(Value)) _cssList.Add("form-control-plaintext--empty"); } } else { _cssList.Add("form-control-plaintext"); if (String.IsNullOrWhiteSpace(Value)) _cssList.Add("form-control-plaintext--empty"); } var sizeSuffix = Size.ToDescriptionString(); if (!String.IsNullOrWhiteSpace(sizeSuffix)) _cssList.Add($"form-control-{sizeSuffix}"); _value = FieldValueService.InitAsString(Value); await base.OnParametersSetAsync(); } #endregion #region << Private methods >> #endregion #region << Ui handlers >> #endregion #region << JS Callbacks methods >> #endregion } }
21.518072
96
0.697088
[ "MIT" ]
WebVella/WebVella.Pulsar
WebVella.Pulsar/Components/Atoms/WvpDisplayEmail/WvpDisplayEmail.razor.cs
1,788
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForPropertiesRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private IDictionary<OptionKey, object> UseExpressionBodyForAccessors_BlockBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); private IDictionary<OptionKey, object> UseExpressionBodyForAccessors_ExpressionBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); private IDictionary<OptionKey, object> UseBlockBodyForAccessors_ExpressionBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); private IDictionary<OptionKey, object> UseBlockBodyForAccessors_BlockBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { int Goo { get { [||]return Bar(); } } }", parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdateAccessorIfAccessWantsBlockAndPropertyWantsExpression() { await TestInRegularAndScript1Async( @"class C { int Goo { get { [||]return Bar(); } } }", @"class C { int Goo { get => Bar(); } }", parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { int Goo { get { [||]return Bar(); } } }", @"class C { int Goo => Bar(); }", parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody2() { await TestInRegularAndScript1Async( @"class C { int Goo { get { [||]return Bar(); } } }", @"class C { int Goo => Bar(); }", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedInLambda() { await TestMissingAsync( @"class C { Action Goo { get { return () => { [||] }; } } }", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { int Goo => [||]Bar(); }", parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody2() { await TestMissingAsync( @"class C { int Goo => [||]Bar(); }", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties)); } [WorkItem(20363, "https://github.com/dotnet/roslyn/issues/20363")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { int Goo => [||]Bar(); }", @"class C { int Goo { get { return Bar(); } } }", parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody2() { await TestInRegularAndScript1Async( @"class C { int Goo => [||]Bar(); }", @"class C { int Goo { get { return Bar(); } } }", parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] [WorkItem(20360, "https://github.com/dotnet/roslyn/issues/20360")] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody_CSharp6() { await TestAsync( @"class C { int Goo => [||]Bar(); }", @"class C { int Goo { get { return Bar(); } } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6), options: UseExpressionBodyForAccessors_ExpressionBodyForProperties); } } }
33.022624
161
0.696903
[ "Apache-2.0" ]
ObsidianMinor/roslyn
src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs
7,300
C#
using System.Windows; namespace ExampleApp { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
16.272727
42
0.608939
[ "MIT" ]
danielchalmers/WpfAboutView
ExampleApp/App.xaml.cs
181
C#
using System; using System.ComponentModel.DataAnnotations; namespace Expense.API.DTO { public class CreateCategoryDto { [Required] [MinLength(3)] public string Name { get; set; } [Required] [MinLength(3)] public string Type { get; set; } } }
17.941176
44
0.593443
[ "MIT" ]
cancanbolat/ExpenseTracker
src/Services/Expense/Expense.API/DTO/CreateCategoryDto.cs
307
C#
//------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ namespace Valve.VR { using System; using UnityEngine; public partial class SteamVR_Actions { private static SteamVR_Input_ActionSet_default p__default; private static SteamVR_Input_ActionSet_canvas p_canvas; public static SteamVR_Input_ActionSet_default _default { get { return SteamVR_Actions.p__default.GetCopy<SteamVR_Input_ActionSet_default>(); } } public static SteamVR_Input_ActionSet_canvas canvas { get { return SteamVR_Actions.p_canvas.GetCopy<SteamVR_Input_ActionSet_canvas>(); } } private static void StartPreInitActionSets() { SteamVR_Actions.p__default = ((SteamVR_Input_ActionSet_default)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_default>("/actions/default"))); SteamVR_Actions.p_canvas = ((SteamVR_Input_ActionSet_canvas)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_canvas>("/actions/canvas"))); Valve.VR.SteamVR_Input.actionSets = new Valve.VR.SteamVR_ActionSet[] { SteamVR_Actions._default, SteamVR_Actions.canvas}; } } }
33.84
156
0.567376
[ "Apache-2.0" ]
salvolannister/Virtual_Shared_Reality_CLIENT
Virtual_Shared_Reality_CLIENT/Assets/SteamVR_Input/SteamVR_Input_ActionSets.cs
1,692
C#
using EPiServer.Reference.Commerce.Site.Features.Product.ViewModelFactories; using EPiServer.Reference.Commerce.Site.Infrastructure.Facades; using EPiServer.Web.Mvc; using System.Web.Mvc; using EPiServer.Reference.Commerce.Shared.Models.Products; namespace EPiServer.Reference.Commerce.Site.Features.Product.Controllers { public class ProductController : ContentController<FashionProduct> { private readonly bool _isInEditMode; private readonly CatalogEntryViewModelFactory _viewModelFactory; public ProductController(IsInEditModeAccessor isInEditModeAccessor, CatalogEntryViewModelFactory viewModelFactory) { _isInEditMode = isInEditModeAccessor(); _viewModelFactory = viewModelFactory; } [HttpGet] public ActionResult Index(FashionProduct currentContent, string entryCode = "", bool useQuickview = false, bool skipTracking = false) { var viewModel = _viewModelFactory.Create(currentContent, entryCode); viewModel.SkipTracking = skipTracking; if (_isInEditMode && viewModel.Variant == null) { var emptyViewName = "ProductWithoutEntries"; return Request.IsAjaxRequest() ? PartialView(emptyViewName, viewModel) : (ActionResult)View(emptyViewName, viewModel); } if (viewModel.Variant == null) { return HttpNotFound(); } if (useQuickview) { return PartialView("_Quickview", viewModel); } return Request.IsAjaxRequest() ? PartialView(viewModel) : (ActionResult)View(viewModel); } [HttpPost] public ActionResult SelectVariant(FashionProduct currentContent, string color, string size, bool useQuickview = false) { var variant = _viewModelFactory.SelectVariant(currentContent, color, size); if (variant != null) { return RedirectToAction("Index", new { entryCode = variant.Code, useQuickview, skipTracking = true }); } return HttpNotFound(); } } }
38.803571
141
0.652554
[ "Apache-2.0" ]
makingwaves/epi-commerce-to-vue-storefront
Quicksilver/EPiServer.Reference.Commerce.Site/Features/Product/Controllers/ProductController.cs
2,175
C#
using Badzeet.Budget.Domain.Model; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Badzeet.Budget.DataAccess.Maps { internal class InvitationMap : IEntityTypeConfiguration<Invitation> { public void Configure(EntityTypeBuilder<Invitation> builder) { builder.ToTable("invitations"); builder.HasKey(x => x.Id); builder.Property(x => x.Id).HasColumnName("id"); builder.Property(x => x.AccountId).HasColumnName("account_id"); builder.Property(x => x.OwnerId).HasColumnName("owner_id"); builder.Property(x => x.UsedAt).HasColumnName("used_at"); builder.Property(x => x.CreatedAt).HasColumnName("created_at"); builder.HasOne(x => x.Account).WithMany().HasForeignKey(x => x.AccountId); builder.HasOne(x => x.User).WithMany().HasForeignKey(x => x.OwnerId); } } }
43.318182
86
0.655824
[ "MIT" ]
yanhamu/Badzeet
Badzeet.Budget.DataAccess/Maps/InvitationMap.cs
955
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GMS.Web.Admin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CHINA")] [assembly: AssemblyProduct("GMS.Web.Admin")] [assembly: AssemblyCopyright("Copyright © CHINA 2013")] [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("1814b61c-8a15-4bbb-8d80-c2c9f0d3024f")] // 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")]
38.027778
84
0.747991
[ "MIT" ]
kuaidaoyanglang/GMS
Src/GMS.Web.Admin/Properties/AssemblyInfo.cs
1,372
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using SixLabors.ImageSharp.Memory; namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder { /// <summary> /// Represents a single frame component. /// </summary> internal sealed class JpegComponent : IDisposable, IJpegComponent { private readonly MemoryAllocator memoryAllocator; public JpegComponent(MemoryAllocator memoryAllocator, JpegFrame frame, byte id, int horizontalFactor, int verticalFactor, byte quantizationTableIndex, int index) { this.memoryAllocator = memoryAllocator; this.Frame = frame; this.Id = id; // Validate sampling factors. if (horizontalFactor == 0 || verticalFactor == 0) { JpegThrowHelper.ThrowBadSampling(); } this.HorizontalSamplingFactor = horizontalFactor; this.VerticalSamplingFactor = verticalFactor; this.SamplingFactors = new Size(this.HorizontalSamplingFactor, this.VerticalSamplingFactor); if (quantizationTableIndex > 3) { JpegThrowHelper.ThrowBadQuantizationTableIndex(quantizationTableIndex); } this.QuantizationTableIndex = quantizationTableIndex; this.Index = index; } /// <summary> /// Gets the component id. /// </summary> public byte Id { get; } /// <summary> /// Gets or sets DC coefficient predictor. /// </summary> public int DcPredictor { get; set; } /// <summary> /// Gets the horizontal sampling factor. /// </summary> public int HorizontalSamplingFactor { get; } /// <summary> /// Gets the vertical sampling factor. /// </summary> public int VerticalSamplingFactor { get; } /// <inheritdoc /> public Buffer2D<Block8x8> SpectralBlocks { get; private set; } /// <inheritdoc /> public Size SubSamplingDivisors { get; private set; } /// <inheritdoc /> public int QuantizationTableIndex { get; } /// <inheritdoc /> public int Index { get; } /// <inheritdoc /> public Size SizeInBlocks { get; private set; } /// <inheritdoc /> public Size SamplingFactors { get; set; } /// <summary> /// Gets the number of blocks per line. /// </summary> public int WidthInBlocks { get; private set; } /// <summary> /// Gets the number of blocks per column. /// </summary> public int HeightInBlocks { get; private set; } /// <summary> /// Gets or sets the index for the DC Huffman table. /// </summary> public int DCHuffmanTableId { get; set; } /// <summary> /// Gets or sets the index for the AC Huffman table. /// </summary> public int ACHuffmanTableId { get; set; } public JpegFrame Frame { get; } /// <inheritdoc/> public void Dispose() { this.SpectralBlocks?.Dispose(); this.SpectralBlocks = null; } /// <summary> /// Initializes component for future buffers initialization. /// </summary> /// <param name="maxSubFactorH">Maximal horizontal subsampling factor among all the components.</param> /// <param name="maxSubFactorV">Maximal vertical subsampling factor among all the components.</param> public void Init(int maxSubFactorH, int maxSubFactorV) { this.WidthInBlocks = (int)MathF.Ceiling( MathF.Ceiling(this.Frame.PixelWidth / 8F) * this.HorizontalSamplingFactor / maxSubFactorH); this.HeightInBlocks = (int)MathF.Ceiling( MathF.Ceiling(this.Frame.PixelHeight / 8F) * this.VerticalSamplingFactor / maxSubFactorV); int blocksPerLineForMcu = this.Frame.McusPerLine * this.HorizontalSamplingFactor; int blocksPerColumnForMcu = this.Frame.McusPerColumn * this.VerticalSamplingFactor; this.SizeInBlocks = new Size(blocksPerLineForMcu, blocksPerColumnForMcu); this.SubSamplingDivisors = new Size(maxSubFactorH, maxSubFactorV).DivideBy(this.SamplingFactors); if (this.SubSamplingDivisors.Width == 0 || this.SubSamplingDivisors.Height == 0) { JpegThrowHelper.ThrowBadSampling(); } } public void AllocateSpectral(bool fullScan) { if (this.SpectralBlocks != null) { // this method will be called each scan marker so we need to allocate only once return; } int spectralAllocWidth = this.SizeInBlocks.Width; int spectralAllocHeight = fullScan ? this.SizeInBlocks.Height : this.VerticalSamplingFactor; this.SpectralBlocks = this.memoryAllocator.Allocate2D<Block8x8>(spectralAllocWidth, spectralAllocHeight, AllocationOptions.Clean); } } }
34.436242
169
0.603196
[ "Apache-2.0" ]
IldarKhayrutdinov/ImageSharp
src/ImageSharp/Formats/Jpeg/Components/Decoder/JpegComponent.cs
5,131
C#
using Gitee.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Gitee.VisualStudio.Helpers { internal static class OutputWindowHelper { #region Fields private static IVsOutputWindowPane _giteeVSOutputWindowPane; #endregion Fields #region Properties private static IVsOutputWindowPane GiteeVSOutputWindowPane { get { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); return _giteeVSOutputWindowPane ?? (_giteeVSOutputWindowPane = GetGiteeVsOutputWindowPane()); } } #endregion Properties #region Methods internal static void DiagnosticWriteLine(string message, Exception ex = null) { if (ex != null) { message += $": {ex}"; } Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); WriteLine("Diagnostic", message); } internal static void ExceptionWriteLine(string message, Exception ex) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); var exceptionMessage = $"{message}: {ex}"; WriteLine("Handled Exception", exceptionMessage); } internal static void WarningWriteLine(string message) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); WriteLine("Warning", message); } private static IVsOutputWindowPane GetGiteeVsOutputWindowPane() { ThreadHelper.ThrowIfNotOnUIThread(); var outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow; if (outputWindow == null) return null; Guid outputPaneGuid = new Guid(PackageGuids.guidGitee4VSCmdSet.ToByteArray()); IVsOutputWindowPane windowPane; outputWindow.CreatePane(ref outputPaneGuid, "Gitee for Visual Studio", 1, 1); outputWindow.GetPane(ref outputPaneGuid, out windowPane); return windowPane; } private static void WriteLine(string category, string message) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); var outputWindowPane = GiteeVSOutputWindowPane; if (outputWindowPane != null) { string outputMessage = $"[Gitee for Visual Studio {category} {DateTime.Now.ToString("hh:mm:ss tt")}] {message}{Environment.NewLine}"; outputWindowPane.OutputString(outputMessage); } } #endregion Methods } }
34.060241
151
0.610541
[ "MIT" ]
maikebing/Gitee.VisualStudio
src/Gitee.VisualStudio/Helpers/OutputWindowHelper.cs
2,829
C#