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.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sledge.Rendering")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sledge.Rendering")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0759ff2e-b602-4903-ac93-aa5663127a68")] // 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("2.0.7.2")] [assembly: AssemblyVersion("2.0.7.2")] [assembly: AssemblyFileVersion("2.0.7.2")]
39.028571
84
0.743045
[ "BSD-3-Clause" ]
LogicAndTrick/sledge
Sledge.Rendering/Properties/AssemblyInfo.cs
1,367
C#
using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New Photo Database", menuName = "Photo/Database")] public class PhotoDatabeseObject : ScriptableObject, ISerializationCallbackReceiver { [SerializeField] private Photo[] photos; public Dictionary<int, Photo> GetPhoto = new Dictionary<int, Photo>(); public void OnAfterDeserialize() { for (int i = 0; i < photos.Length; i++) { photos[i].Id = i; GetPhoto.Add(i, photos[i]); } } public void OnBeforeSerialize() { GetPhoto = new Dictionary<int, Photo>(); } }
26.291667
83
0.635499
[ "Apache-2.0" ]
Maitrog/Psychiatrist
Assets/Scriptable Object/Paramedic/PhotoDatabeseObject.cs
631
C#
using System.ComponentModel.DataAnnotations; using Abp.Application.Services.Dto; using Abp.AutoMapper; using Abp.MultiTenancy; namespace PersonalFinance.MultiTenancy.Dto { [AutoMapFrom(typeof(Tenant))] public class TenantDto : EntityDto { [Required] [StringLength(AbpTenantBase.MaxTenancyNameLength)] [RegularExpression(AbpTenantBase.TenancyNameRegex)] public string TenancyName { get; set; } [Required] [StringLength(AbpTenantBase.MaxNameLength)] public string Name { get; set; } public bool IsActive {get; set;} } }
26.826087
59
0.679092
[ "MIT" ]
Jfontenla/PersonalFinance
aspnet-core/src/PersonalFinance.Application/MultiTenancy/Dto/TenantDto.cs
617
C#
using System.Security.Cryptography; using System.Text; namespace Connector.CcvShop.Security { internal class Encryption { internal static string ComputeHmacSha512(string key, string data) { var keyBytes = Encoding.UTF8.GetBytes(key); using (var sha512 = new HMACSHA512(keyBytes)) { return sha512.ComputeHashForString(data).Replace("-", "").ToLower(); } } } }
24.315789
84
0.599567
[ "MIT" ]
Simply-Translate/Connector-CCVShop
Connector.CcvShop/Security/Encryption.cs
464
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using System.Xml; using Dynamo.Configuration; using Dynamo.Core; using Dynamo.Engine; using Dynamo.Extensions; using Dynamo.Graph; using Dynamo.Graph.Annotations; using Dynamo.Graph.Connectors; using Dynamo.Graph.Nodes; using Dynamo.Graph.Nodes.CustomNodes; using Dynamo.Graph.Nodes.NodeLoaders; using Dynamo.Graph.Nodes.ZeroTouch; using Dynamo.Graph.Notes; using Dynamo.Graph.Workspaces; using Dynamo.Interfaces; using Dynamo.Migration; using Dynamo.Properties; using Dynamo.Scheduler; using Dynamo.Search; using Dynamo.Search.SearchElements; using Dynamo.Selection; using Dynamo.Updates; using Dynamo.Utilities; using Dynamo.Logging; using DynamoServices; using DynamoUnits; using Greg; using ProtoCore; using ProtoCore.Runtime; using Compiler = ProtoAssociative.Compiler; // Dynamo package manager using Utils = Dynamo.Graph.Nodes.Utilities; using DefaultUpdateManager = Dynamo.Updates.UpdateManager; using FunctionGroup = Dynamo.Engine.FunctionGroup; namespace Dynamo.Models { public interface IEngineControllerManager { EngineController EngineController { get; } } /// <summary> /// The core model of Dynamo. /// </summary> public partial class DynamoModel : IDynamoModel, IDisposable, IEngineControllerManager, ITraceReconciliationProcessor // : ModelBase { #region private members private readonly string geometryFactoryPath; private readonly PathManager pathManager; private WorkspaceModel currentWorkspace; private Timer backupFilesTimer; private Dictionary<Guid, string> backupFilesDict = new Dictionary<Guid, string>(); #endregion #region events internal delegate void FunctionNamePromptRequestHandler(object sender, FunctionNamePromptEventArgs e); internal event FunctionNamePromptRequestHandler RequestsFunctionNamePrompt; internal void OnRequestsFunctionNamePrompt(Object sender, FunctionNamePromptEventArgs e) { if (RequestsFunctionNamePrompt != null) RequestsFunctionNamePrompt(this, e); } internal event Action<PresetsNamePromptEventArgs> RequestPresetsNamePrompt; internal void OnRequestPresetNamePrompt(PresetsNamePromptEventArgs e) { if (RequestPresetsNamePrompt != null) RequestPresetsNamePrompt(e); } public event WorkspaceHandler WorkspaceSaved; internal void OnWorkspaceSaved(WorkspaceModel model) { if (WorkspaceSaved != null) WorkspaceSaved(model); } /// <summary> /// Event that is fired during the opening of the workspace. /// /// Use the XmlDocument object provided to conduct additional /// workspace opening operations. /// </summary> public event Action<XmlDocument> WorkspaceOpening; internal void OnWorkspaceOpening(XmlDocument obj) { var handler = WorkspaceOpening; if (handler != null) handler(obj); } /// <summary> /// This event is raised right before the shutdown of DynamoModel started. /// When this event is raised, the shutdown is guaranteed to take place /// (i.e. user has had a chance to save the work and decided to proceed /// with shutting down Dynamo). Handlers of this event can still safely /// access the DynamoModel, the WorkspaceModel (along with its contents), /// and the DynamoScheduler. /// </summary> /// public event DynamoModelHandler ShutdownStarted; private void OnShutdownStarted() { if (ShutdownStarted != null) ShutdownStarted(this); } /// <summary> /// This event is raised after DynamoModel has been shut down. At this /// point the DynamoModel is no longer valid and access to it should be /// avoided. /// </summary> /// public event DynamoModelHandler ShutdownCompleted; private void OnShutdownCompleted() { if (ShutdownCompleted != null) ShutdownCompleted(this); } #endregion #region static properties /// <summary> /// Testing flag is used to defer calls to run in the idle thread /// with the assumption that the entire test will be wrapped in an /// idle thread call. /// </summary> public static bool IsTestMode { get { return isTestMode; } set { isTestMode = value; InstrumentationLogger.IsTestMode = value; } } private static bool isTestMode; /// <summary> /// Specifies whether or not Dynamo is in a crash-state. /// </summary> public static bool IsCrashing { get; set; } /// <summary> /// Setting this flag enables creation of an XML in following format that records /// node mapping information - which old node has been converted to which to new node(s) /// </summary> public static bool EnableMigrationLogging { get; set; } #endregion #region public properties /// <summary> /// DesignScript VM EngineController, used for this instance of Dynamo. /// </summary> public EngineController EngineController { get; set; } /// <summary> /// Manages all loaded ZeroTouch libraries. /// </summary> public readonly LibraryServices LibraryServices; /// <summary> /// Flag specifying whether a shutdown of Dynamo was requested. /// </summary> public bool ShutdownRequested { get; internal set; } /// <summary> /// This version of Dynamo. /// </summary> public string Version { get { return UpdateManager.ProductVersion.ToString(); } } /// <summary> /// UpdateManager to handle automatic upgrade to higher version. /// </summary> public IUpdateManager UpdateManager { get; private set; } /// <summary> /// The path manager that configures path information required for /// Dynamo to function properly. See IPathManager interface for more /// details. /// </summary> public IPathManager PathManager { get { return pathManager; } } /// <summary> /// The context that Dynamo is running under. /// </summary> public readonly string Context; /// <summary> /// Manages all extensions for Dynamo /// </summary> public IExtensionManager ExtensionManager { get { return extensionManager; } } private readonly ExtensionManager extensionManager; /// <summary> /// Manages all loaded NodeModel libraries. /// </summary> public readonly NodeModelAssemblyLoader Loader; /// <summary> /// Custom Node Manager instance, manages all loaded custom nodes. /// </summary> public readonly CustomNodeManager CustomNodeManager; /// <summary> /// The Dynamo Logger, receives and manages all log messages. /// </summary> public readonly DynamoLogger Logger; /// <summary> /// The Dynamo Scheduler, handles scheduling of asynchronous tasks on different /// threads. /// </summary> public DynamoScheduler Scheduler { get; private set; } /// <summary> /// The Dynamo Node Library, complete with Search. /// </summary> public readonly NodeSearchModel SearchModel; /// <summary> /// The application version string for analytics reporting APIs /// </summary> internal virtual string AppVersion { get { return Process.GetCurrentProcess().ProcessName + "-" + DefaultUpdateManager.GetProductVersion(); } } /// <summary> /// Debugging settings for this instance of Dynamo. /// </summary> public readonly DebugSettings DebugSettings; /// <summary> /// Preference settings for this instance of Dynamo. /// </summary> public readonly PreferenceSettings PreferenceSettings; /// <summary> /// Node Factory, used for creating and intantiating loaded Dynamo nodes. /// </summary> public readonly NodeFactory NodeFactory; /// <summary> /// Migration Manager, upgrades old Dynamo file formats to the current version. /// </summary> public readonly MigrationManager MigrationManager; /// <summary> /// The active workspace in Dynamo. /// </summary> public WorkspaceModel CurrentWorkspace { get { return currentWorkspace; } set { if (Equals(value, currentWorkspace)) return; var old = currentWorkspace; currentWorkspace = value; OnWorkspaceHidden(old); OnPropertyChanged("CurrentWorkspace"); } } /// <summary> /// The copy/paste clipboard. /// </summary> public ObservableCollection<ModelBase> ClipBoard { get; set; } /// <summary> /// Specifies whether connectors are displayed in Dynamo. /// </summary> public bool IsShowingConnectors { get { return PreferenceSettings.ShowConnector; } set { PreferenceSettings.ShowConnector = value; } } /// <summary> /// Specifies how connectors are displayed in Dynamo. /// </summary> public ConnectorType ConnectorType { get { return PreferenceSettings.ConnectorType; } set { PreferenceSettings.ConnectorType = value; } } /// <summary> /// The private collection of visible workspaces in Dynamo /// </summary> private readonly List<WorkspaceModel> _workspaces = new List<WorkspaceModel>(); public IEnumerable<WorkspaceModel> Workspaces { get { return _workspaces; } } /// <summary> /// An object which implements the ITraceReconciliationProcessor interface, /// and is used for handlling the results of a trace reconciliation. /// </summary> public ITraceReconciliationProcessor TraceReconciliationProcessor { get; set; } public AuthenticationManager AuthenticationManager { get; set; } #endregion #region initialization and disposal /// <summary> /// External components call this method to shutdown DynamoModel. This /// method marks 'ShutdownRequested' property to 'true'. This method is /// used rather than a public virtual method to ensure that the value of /// ShutdownRequested is set to true. /// </summary> /// <param name="shutdownHost">Set this parameter to true to shutdown /// the host application.</param> /// public void ShutDown(bool shutdownHost) { if (ShutdownRequested) { const string message = "'DynamoModel.ShutDown' called twice"; throw new InvalidOperationException(message); } ShutdownRequested = true; OnShutdownStarted(); // Notify possible event handlers. PreShutdownCore(shutdownHost); ShutDownCore(shutdownHost); PostShutdownCore(shutdownHost); OnShutdownCompleted(); // Notify possible event handlers. } protected virtual void PreShutdownCore(bool shutdownHost) { } protected virtual void ShutDownCore(bool shutdownHost) { Dispose(); PreferenceSettings.SaveInternal(pathManager.PreferenceFilePath); OnCleanup(); DynamoSelection.DestroyInstance(); InstrumentationLogger.End(); if (Scheduler != null) { Scheduler.Shutdown(); Scheduler.TaskStateChanged -= OnAsyncTaskStateChanged; Scheduler = null; } } protected virtual void PostShutdownCore(bool shutdownHost) { } public interface IStartConfiguration { string Context { get; set; } string DynamoCorePath { get; set; } IPreferences Preferences { get; set; } IPathResolver PathResolver { get; set; } bool StartInTestMode { get; set; } IUpdateManager UpdateManager { get; set; } ISchedulerThread SchedulerThread { get; set; } string GeometryFactoryPath { get; set; } IAuthProvider AuthProvider { get; set; } IEnumerable<IExtension> Extensions { get; set; } TaskProcessMode ProcessMode { get; set; } } /// <summary> /// Initialization settings for DynamoModel. /// </summary> public struct DefaultStartConfiguration : IStartConfiguration { public string Context { get; set; } public string DynamoCorePath { get; set; } public IPreferences Preferences { get; set; } public IPathResolver PathResolver { get; set; } public bool StartInTestMode { get; set; } public IUpdateManager UpdateManager { get; set; } public ISchedulerThread SchedulerThread { get; set; } public string GeometryFactoryPath { get; set; } public IAuthProvider AuthProvider { get; set; } public IEnumerable<IExtension> Extensions { get; set; } public TaskProcessMode ProcessMode { get; set; } } /// <summary> /// Start DynamoModel with all default configuration options /// </summary> /// <returns></returns> public static DynamoModel Start() { return Start(new DefaultStartConfiguration() { ProcessMode = TaskProcessMode.Asynchronous }); } /// <summary> /// Start DynamoModel with custom configuration. Defaults will be assigned not provided. /// </summary> /// <param name="configuration"></param> /// <returns></returns> public static DynamoModel Start(IStartConfiguration configuration) { // where necessary, assign defaults if (string.IsNullOrEmpty(configuration.Context)) configuration.Context = Configuration.Context.NONE; return new DynamoModel(configuration); } protected DynamoModel(IStartConfiguration config) { ClipBoard = new ObservableCollection<ModelBase>(); pathManager = new PathManager(new PathManagerParams { CorePath = config.DynamoCorePath, PathResolver = config.PathResolver }); // Ensure we have all directories in place. var exceptions = new List<Exception>(); pathManager.EnsureDirectoryExistence(exceptions); Context = config.Context; IsTestMode = config.StartInTestMode; DebugSettings = new DebugSettings(); Logger = new DynamoLogger(DebugSettings, pathManager.LogDirectory); foreach (var exception in exceptions) { Logger.Log(exception); // Log all exceptions. } MigrationManager = new MigrationManager(DisplayFutureFileMessage, DisplayObsoleteFileMessage); MigrationManager.MessageLogged += LogMessage; MigrationManager.MigrationTargets.Add(typeof(WorkspaceMigrations)); var thread = config.SchedulerThread ?? new DynamoSchedulerThread(); Scheduler = new DynamoScheduler(thread, config.ProcessMode); Scheduler.TaskStateChanged += OnAsyncTaskStateChanged; geometryFactoryPath = config.GeometryFactoryPath; IPreferences preferences = CreateOrLoadPreferences(config.Preferences); var settings = preferences as PreferenceSettings; if (settings != null) { PreferenceSettings = settings; PreferenceSettings.PropertyChanged += PreferenceSettings_PropertyChanged; } InitializePreferences(preferences); InitializeInstrumentationLogger(); if (!isTestMode && this.PreferenceSettings.IsFirstRun) { DynamoMigratorBase migrator = null; try { migrator = DynamoMigratorBase.MigrateBetweenDynamoVersions(pathManager, config.PathResolver); } catch (Exception e) { Logger.Log(e.Message); } if (migrator != null) { var isFirstRun = this.PreferenceSettings.IsFirstRun; this.PreferenceSettings = migrator.PreferenceSettings; // Preserve the preference settings for IsFirstRun as this needs to be set // only by UsageReportingManager this.PreferenceSettings.IsFirstRun = isFirstRun; } } // At this point, pathManager.PackageDirectories only has 1 element which is the directory // in AppData. If list of PackageFolders is empty, add the folder in AppData to the list since there // is no additional location specified. Otherwise, update pathManager.PackageDirectories to include // PackageFolders if (PreferenceSettings.CustomPackageFolders.Count == 0) PreferenceSettings.CustomPackageFolders = new List<string> {pathManager.UserDataDirectory}; else pathManager.LoadCustomPackageFolders(PreferenceSettings.CustomPackageFolders); SearchModel = new NodeSearchModel(); SearchModel.ItemProduced += node => ExecuteCommand(new CreateNodeCommand(node, 0, 0, true, true)); NodeFactory = new NodeFactory(); NodeFactory.MessageLogged += LogMessage; CustomNodeManager = new CustomNodeManager(NodeFactory, MigrationManager); InitializeCustomNodeManager(); extensionManager = new ExtensionManager(); extensionManager.MessageLogged += LogMessage; var extensions = config.Extensions ?? ExtensionManager.ExtensionLoader.LoadDirectory(pathManager.ExtensionsDirectory); Loader = new NodeModelAssemblyLoader(); Loader.MessageLogged += LogMessage; // Create a core which is used for parsing code and loading libraries var libraryCore = new ProtoCore.Core(new Options { RootCustomPropertyFilterPathName = string.Empty }); libraryCore.Compilers.Add(Language.Associative, new Compiler(libraryCore)); libraryCore.Compilers.Add(Language.Imperative, new ProtoImperative.Compiler(libraryCore)); libraryCore.ParsingMode = ParseMode.AllowNonAssignment; LibraryServices = new LibraryServices(libraryCore, pathManager); LibraryServices.MessageLogged += LogMessage; LibraryServices.LibraryLoaded += LibraryLoaded; ResetEngineInternal(); AddHomeWorkspace(); AuthenticationManager = new AuthenticationManager(config.AuthProvider); UpdateManager = config.UpdateManager ?? new DefaultUpdateManager(null); UpdateManager.Log += UpdateManager_Log; if (!IsTestMode) { DefaultUpdateManager.CheckForProductUpdate(UpdateManager); } Logger.Log(string.Format("Dynamo -- Build {0}", Assembly.GetExecutingAssembly().GetName().Version)); InitializeNodeLibrary(preferences); if (extensions.Any()) { var startupParams = new StartupParams(config.AuthProvider, pathManager, new ExtensionLibraryLoader(this), CustomNodeManager, GetType().Assembly.GetName().Version, preferences); foreach (var ext in extensions) { var logSource = ext as ILogSource; if (logSource != null) logSource.MessageLogged += LogMessage; try { ext.Startup(startupParams); } catch (Exception ex) { Logger.Log(ex.Message); } ExtensionManager.Add(ext); } } LogWarningMessageEvents.LogWarningMessage += LogWarningMessage; StartBackupFilesTimer(); TraceReconciliationProcessor = this; foreach (var ext in ExtensionManager.Extensions) { try { ext.Ready(new ReadyParams(this)); } catch (Exception ex) { Logger.Log(ex.Message); } } } private void RemoveExtension(IExtension ext) { ExtensionManager.Remove(ext); var logSource = ext as ILogSource; if (logSource != null) logSource.MessageLogged -= LogMessage; } private void EngineController_TraceReconcliationComplete(TraceReconciliationEventArgs obj) { Debug.WriteLine("TRACE RECONCILIATION: {0} total serializables were orphaned.", obj.CallsiteToOrphanMap.SelectMany(kvp=>kvp.Value).Count()); // The orphans will come back here as a dictionary of lists of ISerializables jeyed by their callsite id. // This dictionary gets redistributed into a dictionary keyed by the workspace id. var workspaceOrphanMap = new Dictionary<Guid, List<ISerializable>>(); foreach (var ws in Workspaces.OfType<HomeWorkspaceModel>()) { // Get the orphaned serializables to this workspace var wsOrphans = ws.GetOrphanedSerializablesAndClearHistoricalTraceData().ToList(); if (!wsOrphans.Any()) continue; if (!workspaceOrphanMap.ContainsKey(ws.Guid)) { workspaceOrphanMap.Add(ws.Guid, wsOrphans); } else { workspaceOrphanMap[ws.Guid].AddRange(wsOrphans); } } foreach (var kvp in obj.CallsiteToOrphanMap) { if (!kvp.Value.Any()) continue; var nodeGuid = EngineController.LiveRunnerRuntimeCore.RuntimeData.CallSiteToNodeMap[kvp.Key]; // TODO: MAGN-7314 // Find the owning workspace for a node. var nodeSpace = Workspaces.FirstOrDefault( ws => ws.Nodes.FirstOrDefault(n => n.GUID == nodeGuid) != null); if (nodeSpace == null) continue; // Add the node's orphaned serializables to the workspace // orphan map. if (workspaceOrphanMap.ContainsKey(nodeSpace.Guid)) { workspaceOrphanMap[nodeSpace.Guid].AddRange(kvp.Value); } else { workspaceOrphanMap.Add(nodeSpace.Guid, kvp.Value); } } TraceReconciliationProcessor.PostTraceReconciliation(workspaceOrphanMap); } public virtual void PostTraceReconciliation(Dictionary<Guid, List<ISerializable>> orphanedSerializables) { // Override in derived classes to deal with orphaned serializables. } void UpdateManager_Log(LogEventArgs args) { Logger.Log(args.Message, args.Level); } /// <summary> /// LibraryLoaded event handler. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LibraryLoaded(object sender, LibraryServices.LibraryLoadedEventArgs e) { string newLibrary = e.LibraryPath; // Load all functions defined in that library. AddZeroTouchNodesToSearch(LibraryServices.GetFunctionGroups(newLibrary)); } /// <summary> /// This event handler is invoked when DynamoScheduler changes the state /// of an AsyncTask object. See TaskStateChangedEventArgs.State for more /// details of these state changes. /// </summary> /// <param name="sender">The scheduler which raised the event.</param> /// <param name="e">Task state changed event argument.</param> /// private void OnAsyncTaskStateChanged(DynamoScheduler sender, TaskStateChangedEventArgs e) { switch (e.CurrentState) { case TaskStateChangedEventArgs.State.ExecutionStarting: if (e.Task is UpdateGraphAsyncTask) ExecutionEvents.OnGraphPreExecution(); break; case TaskStateChangedEventArgs.State.ExecutionCompleted: if (e.Task is UpdateGraphAsyncTask) { // Record execution time for update graph task. long start = e.Task.ExecutionStartTime.TickCount; long end = e.Task.ExecutionEndTime.TickCount; var executionTimeSpan = new TimeSpan(end - start); InstrumentationLogger.LogAnonymousTimedEvent( "Perf", e.Task.GetType().Name, executionTimeSpan); Debug.WriteLine(String.Format(Resources.EvaluationCompleted, executionTimeSpan)); ExecutionEvents.OnGraphPostExecution(); } break; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { EngineController.TraceReconcliationComplete -= EngineController_TraceReconcliationComplete; ExtensionManager.Dispose(); extensionManager.MessageLogged -= LogMessage; LibraryServices.Dispose(); LibraryServices.LibraryManagementCore.Cleanup(); UpdateManager.Log -= UpdateManager_Log; Logger.Dispose(); EngineController.Dispose(); EngineController = null; if (backupFilesTimer != null) { backupFilesTimer.Dispose(); backupFilesTimer = null; Logger.Log("Backup files timer is disposed"); } if (PreferenceSettings != null) { PreferenceSettings.PropertyChanged -= PreferenceSettings_PropertyChanged; } LogWarningMessageEvents.LogWarningMessage -= LogWarningMessage; foreach (var ws in _workspaces) { ws.Dispose(); } } private void InitializeCustomNodeManager() { CustomNodeManager.MessageLogged += LogMessage; var customNodeSearchRegistry = new HashSet<Guid>(); CustomNodeManager.InfoUpdated += info => { if (customNodeSearchRegistry.Contains(info.FunctionId) || !info.IsVisibleInDynamoLibrary) return; var elements = SearchModel.SearchEntries.OfType<CustomNodeSearchElement>(). Where(x => { // Search for common paths and get rid of empty paths. // It can be empty just in case it's just created node. return String.Compare(x.Path, info.Path, StringComparison.OrdinalIgnoreCase) == 0 && !String.IsNullOrEmpty(x.Path); }).ToList(); if (elements.Any()) { foreach (var element in elements) { element.SyncWithCustomNodeInfo(info); SearchModel.Update(element); } return; } customNodeSearchRegistry.Add(info.FunctionId); var searchElement = new CustomNodeSearchElement(CustomNodeManager, info); SearchModel.Add(searchElement); Action<CustomNodeInfo> infoUpdatedHandler = null; infoUpdatedHandler = newInfo => { if (info.FunctionId == newInfo.FunctionId) { bool isCategoryChanged = searchElement.FullCategoryName != newInfo.Category; searchElement.SyncWithCustomNodeInfo(newInfo); SearchModel.Update(searchElement, isCategoryChanged); } }; CustomNodeManager.InfoUpdated += infoUpdatedHandler; CustomNodeManager.CustomNodeRemoved += id => { CustomNodeManager.InfoUpdated -= infoUpdatedHandler; if (info.FunctionId == id) { customNodeSearchRegistry.Remove(info.FunctionId); SearchModel.Remove(searchElement); var workspacesToRemove = _workspaces.FindAll(w => w is CustomNodeWorkspaceModel && (w as CustomNodeWorkspaceModel).CustomNodeId == id); workspacesToRemove.ForEach(w => RemoveWorkspace(w)); } }; }; CustomNodeManager.DefinitionUpdated += UpdateCustomNodeDefinition; } private void InitializeIncludedNodes() { var customNodeData = new TypeLoadData(typeof(Function)); NodeFactory.AddLoader(new CustomNodeLoader(CustomNodeManager, IsTestMode)); NodeFactory.AddAlsoKnownAs(customNodeData.Type, customNodeData.AlsoKnownAs); var dsFuncData = new TypeLoadData(typeof(DSFunction)); var dsVarArgFuncData = new TypeLoadData(typeof(DSVarArgFunction)); var cbnData = new TypeLoadData(typeof(CodeBlockNodeModel)); var dummyData = new TypeLoadData(typeof(DummyNode)); var symbolData = new TypeLoadData(typeof(Symbol)); var outputData = new TypeLoadData(typeof(Output)); var ztLoader = new ZeroTouchNodeLoader(LibraryServices); NodeFactory.AddLoader(dsFuncData.Type, ztLoader); NodeFactory.AddAlsoKnownAs(dsFuncData.Type, dsFuncData.AlsoKnownAs); NodeFactory.AddLoader(dsVarArgFuncData.Type, ztLoader); NodeFactory.AddAlsoKnownAs(dsVarArgFuncData.Type, dsVarArgFuncData.AlsoKnownAs); var cbnLoader = new CodeBlockNodeLoader(LibraryServices); NodeFactory.AddLoader(cbnData.Type, cbnLoader); NodeFactory.AddFactory(cbnData.Type, cbnLoader); NodeFactory.AddAlsoKnownAs(cbnData.Type, cbnData.AlsoKnownAs); NodeFactory.AddTypeFactoryAndLoader(dummyData.Type); NodeFactory.AddAlsoKnownAs(dummyData.Type, dummyData.AlsoKnownAs); var inputLoader = new InputNodeLoader(); NodeFactory.AddLoader(symbolData.Type, inputLoader); NodeFactory.AddFactory(symbolData.Type, inputLoader); NodeFactory.AddAlsoKnownAs(symbolData.Type, symbolData.AlsoKnownAs); NodeFactory.AddTypeFactoryAndLoader(outputData.Type); NodeFactory.AddAlsoKnownAs(outputData.Type, outputData.AlsoKnownAs); SearchModel.Add(new CodeBlockNodeSearchElement(cbnData, LibraryServices)); var symbolSearchElement = new NodeModelSearchElement(symbolData) { IsVisibleInSearch = CurrentWorkspace is CustomNodeWorkspaceModel }; var outputSearchElement = new NodeModelSearchElement(outputData) { IsVisibleInSearch = CurrentWorkspace is CustomNodeWorkspaceModel }; WorkspaceHidden += _ => { var isVisible = CurrentWorkspace is CustomNodeWorkspaceModel; symbolSearchElement.IsVisibleInSearch = isVisible; outputSearchElement.IsVisibleInSearch = isVisible; }; SearchModel.Add(symbolSearchElement); SearchModel.Add(outputSearchElement); } private void InitializeNodeLibrary(IPreferences preferences) { // Initialize all nodes inside of this assembly. InitializeIncludedNodes(); List<TypeLoadData> modelTypes; List<TypeLoadData> migrationTypes; Loader.LoadNodeModelsAndMigrations(pathManager.NodeDirectories, Context, out modelTypes, out migrationTypes); // Load NodeModels foreach (var type in modelTypes) { // Protect ourselves from exceptions thrown by malformed third party nodes. try { NodeFactory.AddTypeFactoryAndLoader(type.Type); NodeFactory.AddAlsoKnownAs(type.Type, type.AlsoKnownAs); AddNodeTypeToSearch(type); } catch (Exception e) { Logger.Log(e); } } // Load migrations foreach (var type in migrationTypes) MigrationManager.AddMigrationType(type); // Import Zero Touch libs var functionGroups = LibraryServices.GetAllFunctionGroups(); if (!IsTestMode) AddZeroTouchNodesToSearch(functionGroups); #if DEBUG_LIBRARY DumpLibrarySnapshot(functionGroups); #endif // Load local custom nodes foreach (var directory in pathManager.DefinitionDirectories) CustomNodeManager.AddUninitializedCustomNodesInPath(directory, IsTestMode); CustomNodeManager.AddUninitializedCustomNodesInPath(pathManager.CommonDefinitions, IsTestMode); } internal void LoadNodeLibrary(Assembly assem) { if (!NodeModelAssemblyLoader.ContainsNodeModelSubType(assem)) { LibraryServices.ImportLibrary(assem.Location); return; } var nodes = new List<TypeLoadData>(); Loader.LoadNodesFromAssembly(assem, Context, nodes, new List<TypeLoadData>()); foreach (var type in nodes) { // Protect ourselves from exceptions thrown by malformed third party nodes. try { NodeFactory.AddTypeFactoryAndLoader(type.Type); NodeFactory.AddAlsoKnownAs(type.Type, type.AlsoKnownAs); type.IsPackageMember = true; AddNodeTypeToSearch(type); } catch (Exception e) { Logger.Log(e); } } } private void InitializeInstrumentationLogger() { if (IsTestMode == false) InstrumentationLogger.Start(this); } private IPreferences CreateOrLoadPreferences(IPreferences preferences) { if (preferences != null) // If there is preference settings provided... return preferences; // Is order for test cases not to interfere with the regular preference // settings xml file, a test case usually specify a temporary xml file // path from where preference settings are to be loaded. If that value // is not set, then fall back to the file path specified in PathManager. // var xmlFilePath = PreferenceSettings.DynamoTestPath; if (string.IsNullOrEmpty(xmlFilePath)) xmlFilePath = pathManager.PreferenceFilePath; if (File.Exists(xmlFilePath)) { // If the specified xml file path exists, load it. return PreferenceSettings.Load(xmlFilePath); } // Otherwise make a default preference settings object. return new PreferenceSettings(); } private static void InitializePreferences(IPreferences preferences) { BaseUnit.NumberFormat = preferences.NumberFormat; } /// <summary> /// Responds to property update notifications on the preferences, /// and synchronizes with the Units Manager. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> //TODO(Steve): See if we can't just do this in PreferenceSettings by making the properties directly access BaseUnit private void PreferenceSettings_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "NumberFormat": BaseUnit.NumberFormat = PreferenceSettings.NumberFormat; break; } } /// <summary> /// This warning message is displayed on the node associated with the FFI dll /// </summary> /// <param name="args"></param> private void LogWarningMessage(LogWarningMessageEventArgs args) { Validity.Assert(EngineController.LiveRunnerRuntimeCore != null); EngineController.LiveRunnerRuntimeCore.RuntimeStatus.LogWarning(WarningID.kDefault, args.message); } #endregion #region engine management /// <summary> /// Register custom node defintion and execute all custom node /// instances. /// </summary> /// <param name="?"></param> private void UpdateCustomNodeDefinition(CustomNodeDefinition definition) { RegisterCustomNodeDefinitionWithEngine(definition); MarkAllDependenciesAsModified(definition); } /// <summary> /// Registers (or re-registers) a Custom Node definition with the DesignScript VM, /// so that instances of the custom node can be evaluated. /// </summary> /// <param name="definition"></param> private void RegisterCustomNodeDefinitionWithEngine(CustomNodeDefinition definition) { EngineController.GenerateGraphSyncDataForCustomNode( Workspaces.OfType<HomeWorkspaceModel>().SelectMany(ws => ws.Nodes), definition, DebugSettings.VerboseLogging); } /// <summary> /// Get all function instances or directly or indrectly dependo on the /// specified function definition and mark them as modified so that /// their values will be re-queryed. /// </summary> /// <param name="functionId"></param> /// <returns></returns> private void MarkAllDependenciesAsModified(CustomNodeDefinition def) { var homeWorkspace = Workspaces.OfType<HomeWorkspaceModel>().FirstOrDefault(); if (homeWorkspace == null) return; var dependencies = CustomNodeManager.GetAllDependenciesGuids(def); var funcNodes = homeWorkspace.Nodes.OfType<Function>(); var dirtyNodes = funcNodes.Where(n => dependencies.Contains(n.Definition.FunctionId)); homeWorkspace.MarkNodesAsModifiedAndRequestRun(dirtyNodes); } /// <summary> /// Call this method to reset the virtual machine, avoiding a race /// condition by using a thread join inside the vm executive. /// TODO(Luke): Push this into a resync call with the engine controller /// /// Tracked in MAGN-5167. /// As some async tasks use engine controller, for example /// CompileCustomNodeAsyncTask and UpdateGraphAsyncTask, it is possible /// that engine controller is reset *before* tasks get executed. For /// example, opening custom node will schedule a CompileCustomNodeAsyncTask /// firstly and then reset engine controller. /// /// We should make sure engine controller is reset after all tasks that /// depend on it get executed, or those tasks are thrown away if safe to /// do that. /// </summary> /// <param name="markNodesAsDirty">Set this parameter to true to force /// reset of the execution substrait. Note that setting this parameter /// to true will have a negative performance impact.</param> public virtual void ResetEngine(bool markNodesAsDirty = false) { ResetEngineInternal(); foreach (var workspaceModel in Workspaces.OfType<HomeWorkspaceModel>()) { workspaceModel.ResetEngine(EngineController, markNodesAsDirty); } } protected void ResetEngineInternal() { if (EngineController != null) { EngineController.TraceReconcliationComplete -= EngineController_TraceReconcliationComplete; EngineController.MessageLogged -= LogMessage; EngineController.Dispose(); EngineController = null; } EngineController = new EngineController( LibraryServices, geometryFactoryPath, DebugSettings.VerboseLogging); EngineController.MessageLogged += LogMessage; EngineController.TraceReconcliationComplete += EngineController_TraceReconcliationComplete; foreach (var def in CustomNodeManager.LoadedDefinitions) RegisterCustomNodeDefinitionWithEngine(def); } /// <summary> /// Forces an evaluation of the current workspace by resetting the DesignScript VM. /// </summary> public void ForceRun() { Logger.Log("Beginning engine reset"); ResetEngine(true); Logger.Log("Reset complete"); ((HomeWorkspaceModel)CurrentWorkspace).Run(); } #endregion #region save/load /// <summary> /// Opens a Dynamo workspace from a path to an Xml file on disk. /// </summary> /// <param name="xmlPath"></param> public void OpenFileFromPath(string xmlPath, bool forceManualExecutionMode = false) { var xmlDoc = new XmlDocument(); xmlDoc.Load(xmlPath); WorkspaceInfo workspaceInfo; if (WorkspaceInfo.FromXmlDocument(xmlDoc, xmlPath, IsTestMode, forceManualExecutionMode, Logger, out workspaceInfo)) { if (MigrationManager.ProcessWorkspace(workspaceInfo, xmlDoc, IsTestMode, NodeFactory)) { WorkspaceModel ws; if (OpenFile(workspaceInfo, xmlDoc, out ws)) { // TODO: #4258 // The logic to remove all other home workspaces from the model // was moved from the ViewModel. When #4258 is implemented, we will need to // remove this step. var currentHomeSpaces = Workspaces.OfType<HomeWorkspaceModel>().ToList(); if (currentHomeSpaces.Any()) { // If the workspace we're opening is a home workspace, // then remove all the other home workspaces. Otherwise, // Remove all but the first home workspace. var end = ws is HomeWorkspaceModel ? 0 : 1; for (var i = currentHomeSpaces.Count - 1; i >= end; i--) { RemoveWorkspace(currentHomeSpaces[i]); } } AddWorkspace(ws); OnWorkspaceOpening(xmlDoc); // TODO: #4258 // The following logic to start periodic evaluation will need to be moved // inside of the HomeWorkspaceModel's constructor. It cannot be there today // as it causes an immediate crash due to the above ResetEngine call. var hws = ws as HomeWorkspaceModel; if (hws != null) { // TODO: #4258 // Remove this ResetEngine call when multiple home workspaces is supported. // This call formerly lived in DynamoViewModel ResetEngine(); if (hws.RunSettings.RunType == RunType.Periodic) { hws.StartPeriodicEvaluation(); } } CurrentWorkspace = ws; return; } } } Logger.LogError("Could not open workspace at: " + xmlPath); } private bool OpenFile(WorkspaceInfo workspaceInfo, XmlDocument xmlDoc, out WorkspaceModel workspace) { CustomNodeManager.AddUninitializedCustomNodesInPath( Path.GetDirectoryName(workspaceInfo.FileName), IsTestMode); var result = workspaceInfo.IsCustomNodeWorkspace ? CustomNodeManager.OpenCustomNodeWorkspace(xmlDoc, workspaceInfo, IsTestMode, out workspace) : OpenHomeWorkspace(xmlDoc, workspaceInfo, out workspace); workspace.OnCurrentOffsetChanged( this, new PointEventArgs(new Point2D(workspaceInfo.X, workspaceInfo.Y))); return result; } private bool OpenHomeWorkspace( XmlDocument xmlDoc, WorkspaceInfo workspaceInfo, out WorkspaceModel workspace) { var nodeGraph = NodeGraph.LoadGraphFromXml(xmlDoc, NodeFactory); var newWorkspace = new HomeWorkspaceModel( EngineController, Scheduler, NodeFactory, Utils.LoadTraceDataFromXmlDocument(xmlDoc), nodeGraph.Nodes, nodeGraph.Notes, nodeGraph.Annotations, nodeGraph.Presets, nodeGraph.ElementResolver, workspaceInfo, DebugSettings.VerboseLogging, IsTestMode ); RegisterHomeWorkspace(newWorkspace); workspace = newWorkspace; return true; } private void RegisterHomeWorkspace(HomeWorkspaceModel newWorkspace) { newWorkspace.EvaluationCompleted += OnEvaluationCompleted; newWorkspace.RefreshCompleted += OnRefreshCompleted; newWorkspace.Disposed += () => { newWorkspace.EvaluationCompleted -= OnEvaluationCompleted; newWorkspace.RefreshCompleted -= OnRefreshCompleted; }; } #endregion #region backup/timer /// <summary> /// Backup all the files /// </summary> protected void SaveBackupFiles(object state) { OnRequestDispatcherBeginInvoke(() => { // tempDict stores the list of backup files and their corresponding workspaces IDs // when the last auto-save operation happens. Now the IDs will be used to know // whether some workspaces have already been backed up. If so, those workspaces won't be // backed up again. var tempDict = new Dictionary<Guid,string>(backupFilesDict); backupFilesDict.Clear(); PreferenceSettings.BackupFiles.Clear(); foreach (var workspace in Workspaces) { if (!workspace.HasUnsavedChanges) { if (workspace.Nodes.Any() && !workspace.Notes.Any()) continue; if (tempDict.ContainsKey(workspace.Guid)) { backupFilesDict.Add(workspace.Guid, tempDict[workspace.Guid]); continue; } } var savePath = pathManager.GetBackupFilePath(workspace); var oldFileName = workspace.FileName; var oldName = workspace.Name; workspace.SaveAs(savePath, null, true); workspace.FileName = oldFileName; workspace.Name = oldName; backupFilesDict.Add(workspace.Guid, savePath); Logger.Log("Backup file is saved: " + savePath); } PreferenceSettings.BackupFiles.AddRange(backupFilesDict.Values); }); } /// <summary> /// Start the timer to backup files periodically /// </summary> private void StartBackupFilesTimer() { // When running test cases, the dispatcher may be null which will cause the timer to // introduce a lot of threads. So the timer will not be started if test cases are running. if (IsTestMode) return; if (backupFilesTimer != null) { throw new Exception("The timer to backup files has already been started!"); } backupFilesTimer = new Timer(SaveBackupFiles); backupFilesTimer.Change(PreferenceSettings.BackupInterval, PreferenceSettings.BackupInterval); Logger.Log(String.Format("Backup files timer is started with an interval of {0} milliseconds", PreferenceSettings.BackupInterval)); } #endregion #region internal methods internal void PostUIActivation(object parameter) { Logger.Log(Resources.WelcomeMessage); } internal void DeleteModelInternal(List<ModelBase> modelsToDelete) { if (null == CurrentWorkspace) return; //Check for empty group var annotations = Workspaces.SelectMany(ws => ws.Annotations); foreach (var annotation in annotations) { //record the annotation before the models in it are deleted. foreach (var model in modelsToDelete) { //If there is only one model, then deleting that model should delete the group. In that case, do not record //the group for modification. Until we have one model in a group, group should be recorded for modification //otherwise, undo operation cannot get the group back. if (annotation.SelectedModels.Count() > 1 && annotation.SelectedModels.Where(x => x.GUID == model.GUID).Any()) { CurrentWorkspace.RecordGroupModelBeforeUngroup(annotation); } } if (annotation.SelectedModels.Any() && !annotation.SelectedModels.Except(modelsToDelete).Any()) { //Annotation Model has to be serialized first - before the nodes. //so, store the Annotation model as first object. This will serialize the //annotation before the nodes are deleted. So, when Undo is pressed, //annotation model is deserialized correctly. modelsToDelete.Insert(0, annotation); } } OnDeletionStarted(); CurrentWorkspace.RecordAndDeleteModels(modelsToDelete); var selection = DynamoSelection.Instance.Selection; foreach (ModelBase model in modelsToDelete) { selection.Remove(model); // Remove from selection set. model.Dispose(); } OnDeletionComplete(this, EventArgs.Empty); } internal void UngroupModel(List<ModelBase> modelsToUngroup) { var emptyGroup = new List<ModelBase>(); var annotations = Workspaces.SelectMany(ws => ws.Annotations); foreach (var model in modelsToUngroup) { foreach (var annotation in annotations) { if (annotation.SelectedModels.Any(x => x.GUID == model.GUID)) { var list = annotation.SelectedModels.ToList(); if(list.Count > 1) { CurrentWorkspace.RecordGroupModelBeforeUngroup(annotation); if (list.Remove(model)) { annotation.SelectedModels = list; annotation.UpdateBoundaryFromSelection(); } } else { emptyGroup.Add(annotation); } } } } if(emptyGroup.Any()) { DeleteModelInternal(emptyGroup); } } internal void AddToGroup(List<ModelBase> modelsToAdd) { var workspaceAnnotations = Workspaces.SelectMany(ws => ws.Annotations); var selectedGroup = workspaceAnnotations.FirstOrDefault(x => x.IsSelected); if (selectedGroup != null) { foreach (var model in modelsToAdd) { CurrentWorkspace.RecordGroupModelBeforeUngroup(selectedGroup); selectedGroup.AddToSelectedModels(model); } } } internal void DumpLibraryToXml(object parameter) { string fileName = String.Format("LibrarySnapshot_{0}.xml", DateTime.Now.ToString("yyyyMMddHmmss")); string fullFileName = Path.Combine(pathManager.LogDirectory, fileName); SearchModel.DumpLibraryToXml(fullFileName); Logger.Log(string.Format(Resources.LibraryIsDumped, fullFileName)); } internal bool CanDumpLibraryToXml(object obj) { return true; } #endregion #region public methods /// <summary> /// Add a new HomeWorkspace and set as current /// </summary> /// <api_stability>1</api_stability> public void AddHomeWorkspace() { var defaultWorkspace = new HomeWorkspaceModel( EngineController, Scheduler, NodeFactory, DebugSettings.VerboseLogging, IsTestMode,string.Empty); RegisterHomeWorkspace(defaultWorkspace); AddWorkspace(defaultWorkspace); CurrentWorkspace = defaultWorkspace; } /// <summary> /// Add a new, visible Custom Node workspace to Dynamo /// </summary> /// <param name="workspace"></param> public void AddCustomNodeWorkspace(CustomNodeWorkspaceModel workspace) { AddWorkspace(workspace); } /// <summary> /// Remove a workspace from the dynamo model. /// </summary> /// <param name="workspace"></param> public void RemoveWorkspace(WorkspaceModel workspace) { OnWorkspaceRemoveStarted(workspace); if (_workspaces.Remove(workspace)) { if (workspace is HomeWorkspaceModel) { workspace.Dispose(); } OnWorkspaceRemoved(workspace); } } /// <summary> /// Opens an existing custom node workspace. /// </summary> /// <param name="guid"></param> /// <returns></returns> public bool OpenCustomNodeWorkspace(Guid guid) { CustomNodeWorkspaceModel customNodeWorkspace; if (CustomNodeManager.TryGetFunctionWorkspace(guid, IsTestMode, out customNodeWorkspace)) { if (!Workspaces.OfType<CustomNodeWorkspaceModel>().Contains(customNodeWorkspace)) AddWorkspace(customNodeWorkspace); CurrentWorkspace = customNodeWorkspace; return true; } return false; } /// <summary> /// Adds a node to the current workspace. /// </summary> /// <param name="node"></param> /// <param name="centered"></param> public void AddNodeToCurrentWorkspace(NodeModel node, bool centered, bool addToSelection = true) { CurrentWorkspace.AddAndRegisterNode(node, centered); //TODO(Steve): This should be moved to WorkspaceModel.AddNode when all workspaces have their own selection -- MAGN-5707 if (addToSelection) { DynamoSelection.Instance.ClearSelection(); DynamoSelection.Instance.Selection.Add(node); } //TODO(Steve): Make sure we're not missing something with TransformCoordinates. -- MAGN-5708 } /// <summary> /// Copy selected ISelectable objects to the clipboard. /// </summary> public void Copy() { ClipBoard.Clear(); foreach ( var el in DynamoSelection.Instance.Selection.OfType<ModelBase>() .Where(el => !ClipBoard.Contains(el))) { ClipBoard.Add(el); if (!(el is NodeModel)) continue; var node = el as NodeModel; var connectors = node.InPorts.Concat(node.OutPorts).SelectMany(port => port.Connectors) .Where( connector => connector.End != null && connector.End.Owner.IsSelected && !ClipBoard.Contains(connector)); ClipBoard.AddRange(connectors); } } /// <summary> /// Paste ISelectable objects from the clipboard to the workspace /// so that the nodes appear in their original location with a slight offset /// </summary> public void Paste() { var locatableModels = ClipBoard.Where(model => model is NoteModel || model is NodeModel); var x = locatableModels.Min(m => m.X); var y = locatableModels.Min(m => m.Y); var targetPoint = new Point2D(x, y); Paste(targetPoint); } /// <summary> /// Paste ISelectable objects from the clipboard to the workspace at specified point. /// </summary> /// <param name="targetPoint">Location where data will be pasted</param> /// <param name="useOffset">Indicates whether we will use current workspace offset or paste nodes /// directly in this point. </param> public void Paste(Point2D targetPoint, bool useOffset = true) { if (useOffset) { // Provide a small offset when pasting so duplicate pastes aren't directly on top of each other CurrentWorkspace.IncrementPasteOffset(); } //clear the selection so we can put the //paste contents in DynamoSelection.Instance.ClearSelection(); //make a lookup table to store the guids of the //old models and the guids of their pasted versions var modelLookup = new Dictionary<Guid, ModelBase>(); //make a list of all newly created models so that their //creations can be recorded in the undo recorder. var createdModels = new List<ModelBase>(); var nodes = ClipBoard.OfType<NodeModel>(); var connectors = ClipBoard.OfType<ConnectorModel>(); var notes = ClipBoard.OfType<NoteModel>(); var annotations = ClipBoard.OfType<AnnotationModel>(); // Create the new NoteModel's var newNoteModels = new List<NoteModel>(); foreach (var note in notes) { var noteModel = new NoteModel(note.X, note.Y, note.Text, Guid.NewGuid()); //Store the old note as Key and newnote as value. modelLookup.Add(note.GUID,noteModel); newNoteModels.Add(noteModel); } var xmlDoc = new XmlDocument(); // Create the new NodeModel's var newNodeModels = new List<NodeModel>(); foreach (var node in nodes) { NodeModel newNode; if (CurrentWorkspace is HomeWorkspaceModel && (node is Symbol || node is Output)) { var symbol = (node is Symbol ? (node as Symbol).InputSymbol : (node as Output).Symbol); var code = (string.IsNullOrEmpty(symbol) ? "x" : symbol) + ";"; newNode = new CodeBlockNodeModel(code, node.X, node.Y, LibraryServices, CurrentWorkspace.ElementResolver); } else { var dynEl = node.Serialize(xmlDoc, SaveContext.Copy); newNode = NodeFactory.CreateNodeFromXml(dynEl, SaveContext.Copy, CurrentWorkspace.ElementResolver); } var lacing = node.ArgumentLacing.ToString(); newNode.UpdateValue(new UpdateValueParams("ArgumentLacing", lacing)); if (!string.IsNullOrEmpty(node.NickName)) newNode.NickName = node.NickName; newNode.Width = node.Width; newNode.Height = node.Height; modelLookup.Add(node.GUID, newNode); newNodeModels.Add(newNode); } var newItems = newNodeModels.Concat<ModelBase>(newNoteModels); var shiftX = targetPoint.X - newItems.Min(item => item.X); var shiftY = targetPoint.Y - newItems.Min(item => item.Y); var offset = useOffset ? CurrentWorkspace.CurrentPasteOffset : 0; foreach (var model in newItems) { model.X = model.X + shiftX + offset; model.Y = model.Y + shiftY + offset; } // Add the new NodeModel's to the Workspace foreach (var newNode in newNodeModels) { CurrentWorkspace.AddAndRegisterNode(newNode, false); createdModels.Add(newNode); } // TODO: is this required? OnRequestLayoutUpdate(this, EventArgs.Empty); // Add the new NoteModel's to the Workspace foreach (var newNote in newNoteModels) { CurrentWorkspace.AddNote(newNote, false); createdModels.Add(newNote); } ModelBase start; ModelBase end; var newConnectors = from c in connectors // If the guid is in nodeLookup, then we connect to the new pasted node. Otherwise we // re-connect to the original. let startNode = modelLookup.TryGetValue(c.Start.Owner.GUID, out start) ? start as NodeModel : CurrentWorkspace.Nodes.FirstOrDefault(x => x.GUID == c.Start.Owner.GUID) let endNode = modelLookup.TryGetValue(c.End.Owner.GUID, out end) ? end as NodeModel : CurrentWorkspace.Nodes.FirstOrDefault(x => x.GUID == c.End.Owner.GUID) // Don't make a connector if either end is null. where startNode != null && endNode != null select ConnectorModel.Make(startNode, endNode, c.Start.Index, c.End.Index); createdModels.AddRange(newConnectors); //Grouping depends on the selected node models. //so adding the group after nodes / notes are added to workspace. //select only those nodes that are part of a group. var newAnnotations = new List<AnnotationModel>(); foreach (var annotation in annotations) { var annotationNodeModel = new List<NodeModel>(); var annotationNoteModel = new List<NoteModel>(); // some models can be deleted after copying them, // so they need to be in pasted annotation as well var modelsToRestore = annotation.DeletedModelBases.Intersect(ClipBoard); var modelsToAdd = annotation.SelectedModels.Concat(modelsToRestore); // checked condition here that supports pasting of multiple groups foreach (var models in modelsToAdd) { ModelBase mbase; modelLookup.TryGetValue(models.GUID, out mbase); if (mbase is NodeModel) { annotationNodeModel.Add(mbase as NodeModel); } if (mbase is NoteModel) { annotationNoteModel.Add(mbase as NoteModel); } } var annotationModel = new AnnotationModel(annotationNodeModel, annotationNoteModel) { GUID = Guid.NewGuid(), AnnotationText = annotation.AnnotationText, Background = annotation.Background, FontSize = annotation.FontSize }; newAnnotations.Add(annotationModel); } // Add the new Annotation's to the Workspace foreach (var newAnnotation in newAnnotations) { CurrentWorkspace.AddAnnotation(newAnnotation); createdModels.Add(newAnnotation); AddToSelection(newAnnotation); } // adding an annotation overrides selection, so add nodes and notes after foreach (var item in newItems) { AddToSelection(item); } // Record models that are created as part of the command. CurrentWorkspace.RecordCreatedModels(createdModels); } /// <summary> /// Add an ISelectable object to the selection. /// </summary> /// <param name="parameters">The object to add to the selection.</param> public void AddToSelection(object parameters) { var selectable = parameters as ISelectable; if (selectable != null) { DynamoSelection.Instance.Selection.AddUnique(selectable); } } /// <summary> /// Clear the workspace. Removes all nodes, notes, and connectors from the current workspace. /// </summary> public void ClearCurrentWorkspace() { OnWorkspaceClearing(); CurrentWorkspace.Clear(); //don't save the file path CurrentWorkspace.FileName = ""; CurrentWorkspace.HasUnsavedChanges = false; CurrentWorkspace.WorkspaceVersion = AssemblyHelper.GetDynamoVersion(); OnWorkspaceCleared(CurrentWorkspace); } #endregion #region private methods private void LogMessage(ILogMessage obj) { Logger.Log(obj); } #if DEBUG_LIBRARY private void DumpLibrarySnapshot(IEnumerable<Engine.FunctionGroup> functionGroups) { if (null == functionGroups) return; var descriptions = functionGroups.Select(functionGroup => functionGroup.Functions.ToList()) .Where(functions => functions.Any()) .SelectMany( functions => (from function in functions where function.IsVisibleInLibrary let displayString = function.UserFriendlyName where !displayString.Contains("GetType") select string.IsNullOrEmpty(function.Namespace) ? "" : function.Namespace + "." + function.Signature + "\n")); var sb = string.Join("\n", descriptions); Logger.Log(sb, LogLevel.File); } #endif private void AddNodeTypeToSearch(TypeLoadData typeLoadData) { if (!typeLoadData.IsDSCompatible || typeLoadData.IsDeprecated || typeLoadData.IsHidden || typeLoadData.IsMetaNode) { return; } SearchModel.Add(new NodeModelSearchElement(typeLoadData)); } private void AddZeroTouchNodesToSearch(IEnumerable<FunctionGroup> functionGroups) { foreach (var funcGroup in functionGroups) AddZeroTouchNodeToSearch(funcGroup); } private void AddZeroTouchNodeToSearch(FunctionGroup funcGroup) { foreach (var functionDescriptor in funcGroup.Functions) { AddZeroTouchNodeToSearch(functionDescriptor); } } private void AddZeroTouchNodeToSearch(FunctionDescriptor functionDescriptor) { if (functionDescriptor.IsVisibleInLibrary) { SearchModel.Add(new ZeroTouchSearchElement(functionDescriptor)); } } /// <summary> /// Adds a workspace to the dynamo model. /// </summary> /// <param name="workspace"></param> private void AddWorkspace(WorkspaceModel workspace) { if (workspace == null) return; Action savedHandler = () => OnWorkspaceSaved(workspace); workspace.WorkspaceSaved += savedHandler; workspace.MessageLogged += LogMessage; workspace.PropertyChanged += OnWorkspacePropertyChanged; workspace.Disposed += () => { workspace.WorkspaceSaved -= savedHandler; workspace.MessageLogged -= LogMessage; workspace.PropertyChanged -= OnWorkspacePropertyChanged; }; _workspaces.Add(workspace); OnWorkspaceAdded(workspace); } enum ButtonId { Ok = 43420, Cancel, DownloadLatest, Proceed, Submit } /// <summary> /// Call this method to display a message box when a file of an older /// version cannot be opened by the current version of Dynamo. /// </summary> /// <param name="fullFilePath"></param> /// <param name="fileVersion">Version of the input file.</param> /// <param name="currVersion">Current version of the Dynamo.</param> private void DisplayObsoleteFileMessage(string fullFilePath, Version fileVersion, Version currVersion) { var fileVer = ((fileVersion != null) ? fileVersion.ToString() : "Unknown"); var currVer = ((currVersion != null) ? currVersion.ToString() : "Unknown"); InstrumentationLogger.LogPiiInfo( "ObsoleteFileMessage", fullFilePath + " :: fileVersion:" + fileVer + " :: currVersion:" + currVer); string summary = Resources.FileCannotBeOpened; var description = string.Format( Resources.ObsoleteFileDescription, fullFilePath, fileVersion, currVersion); const string imageUri = "/DynamoCoreWpf;component/UI/Images/task_dialog_obsolete_file.png"; var args = new TaskDialogEventArgs( new Uri(imageUri, UriKind.Relative), Resources.ObsoleteFileTitle, summary, description); args.AddRightAlignedButton((int)ButtonId.Ok, Resources.OKButton); OnRequestTaskDialog(null, args); } /// <summary> /// Call this method to display an error message in an event when live /// runner throws an exception that is not handled anywhere else. This /// message instructs user to save their work and restart Dynamo. /// </summary> /// <param name="exception">The exception to display.</param> private TaskDialogEventArgs DisplayEngineFailureMessage(Exception exception) { StabilityTracking.GetInstance().NotifyCrash(); InstrumentationLogger.LogAnonymousEvent("EngineFailure", "Stability"); if (exception != null) { InstrumentationLogger.LogException(exception); } string summary = Resources.UnhandledExceptionSummary; string description = Resources.DisplayEngineFailureMessageDescription; const string imageUri = "/DynamoCoreWpf;component/UI/Images/task_dialog_crash.png"; var args = new TaskDialogEventArgs( new Uri(imageUri, UriKind.Relative), Resources.UnhandledExceptionTitle, summary, description); args.AddRightAlignedButton((int)ButtonId.Submit, Resources.SubmitBugButton); args.AddRightAlignedButton((int)ButtonId.Ok, Resources.ArggOKButton); args.Exception = exception; OnRequestTaskDialog(null, args); if (args.ClickedButtonId == (int)ButtonId.Submit) OnRequestBugReport(); return args; } /// <summary> /// Displays file open error dialog if the file is of a future version than the currently installed version /// </summary> /// <param name="fullFilePath"></param> /// <param name="fileVersion"></param> /// <param name="currVersion"></param> /// <returns> true if the file must be opened and false otherwise </returns> private bool DisplayFutureFileMessage(string fullFilePath, Version fileVersion, Version currVersion) { var fileVer = ((fileVersion != null) ? fileVersion.ToString() : Resources.UnknownVersion); var currVer = ((currVersion != null) ? currVersion.ToString() : Resources.UnknownVersion); InstrumentationLogger.LogPiiInfo("FutureFileMessage", fullFilePath + " :: fileVersion:" + fileVer + " :: currVersion:" + currVer); string summary = Resources.FutureFileSummary; var description = string.Format(Resources.FutureFileDescription, fullFilePath, fileVersion, currVersion); const string imageUri = "/DynamoCoreWpf;component/UI/Images/task_dialog_future_file.png"; var args = new TaskDialogEventArgs( new Uri(imageUri, UriKind.Relative), Resources.FutureFileTitle, summary, description) { ClickedButtonId = (int)ButtonId.Cancel }; args.AddRightAlignedButton((int)ButtonId.Cancel, Resources.CancelButton); args.AddRightAlignedButton((int)ButtonId.DownloadLatest, Resources.DownloadLatestButton); args.AddRightAlignedButton((int)ButtonId.Proceed, Resources.ProceedButton); OnRequestTaskDialog(null, args); if (args.ClickedButtonId == (int)ButtonId.DownloadLatest) { // this should be an event on DynamoModel OnRequestDownloadDynamo(); return false; } return args.ClickedButtonId == (int)ButtonId.Proceed; } private void OnWorkspacePropertyChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName == "RunEnabled") OnPropertyChanged("RunEnabled"); if (args.PropertyName == "EnablePresetOptions") OnPropertyChanged("EnablePresetOptions"); } #endregion } }
38.864532
152
0.565106
[ "Apache-2.0", "MIT" ]
luxliber/Dynamo
src/DynamoCore/Models/DynamoModel.cs
78,895
C#
using Kubera.App.Infrastructure; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using Kubera.Application.Common.Models; using MediatR; using Kubera.Application.Features.Queries.GetAllAssets.V1; using Kubera.App.Infrastructure.Extensions; using Kubera.Application.Features.Queries.GetAsset.V1; using Kubera.Application.Features.Queries.GetAssetsTotal.V1; using Kubera.Application.Features.Commands.CreateAsset.V1; using Kubera.Application.Features.Commands.UpdateAsset.V1; using Kubera.Application.Features.Commands.DeleteAsset.V1; using Kubera.App.Models; namespace Kubera.App.Controllers.V1 { [ApiVersion("1.0")] public class AssetController : BaseController { public AssetController(IMediator mediator) : base(mediator) { } /// <summary> /// Get all assets suported by the platform /// </summary> /// <returns>Collection of assets</returns> [HttpGet] [ProducesResponseType(typeof(IEnumerable<AssetModel>), StatusCodes.Status200OK)] public async Task<ActionResult<IEnumerable<AssetModel>>> GetAssets() { var query = new GetAllAssetsQuery(); return await ExecuteRequest(query).ConfigureAwait(false); } /// <summary> /// Get all assets with their total of a user /// </summary> /// <returns>Collection of assets with their respective assets</returns> [HttpGet("totals")] [ProducesResponseType(typeof(IEnumerable<AssetTotalModel>), StatusCodes.Status200OK)] public async Task<ActionResult<IEnumerable<AssetTotalModel>>> GetAssetsTotals([FromQuery] Guid currencyId, [FromQuery] Filter filter) { var query = new GetAssetsTotalQuery { CurrencyId = currencyId, Filter = filter }; return await ExecuteRequest(query).ConfigureAwait(false); } /// <summary> /// Get an asset for the current user /// </summary> /// <param name="id">Group id</param> /// <returns>Requested group</returns> [HttpGet("{id}")] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(AssetModel), StatusCodes.Status200OK)] public async Task<ActionResult<AssetModel>> GetAsset(Guid id) { var query = new GetAssetQuery { Id = id }; return await ExecuteRequest(query).ConfigureAwait(false); } /// <summary> /// Create a new asset for logged user /// </summary> /// <param name="model">Input model for the new asset</param> /// <returns>The new asset</returns> [HttpPost] [ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(typeof(AssetModel), StatusCodes.Status201Created)] public async Task<ActionResult<AssetModel>> PostAsset(AssetInputModel model) { if (!ModelState.IsValid) return BadRequest(ModelState); var command = new CreateAssetCommand { Input = model }; var result = await Mediator.Send(command, HttpContext.RequestAborted) .ConfigureAwait(false); if(result.IsFailure) return result.AsActionResult(); return CreatedAtAction(nameof(GetAsset), new { id = result.Value.Id }, result.Value); } /// <summary> /// Update an asset /// </summary> /// <param name="id">Id of the asset</param> /// <param name="model">Asset update model</param> /// <returns>No content</returns> [HttpPut("{id}")] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task<IActionResult> PutAsset(Guid id, AssetUpdateModel model) { if (!ModelState.IsValid) return BadRequest(ModelState); var command = new UpdateAssetCommand { Id = id, Input = model }; return await ExecuteRequest(command).ConfigureAwait(false); } /// <summary> /// Delete an asset /// </summary> /// <param name="id">Id of the asset</param> /// <returns>No content</returns> [HttpDelete("{id}")] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task<IActionResult> DeleteAsset(Guid id) { if (!ModelState.IsValid) return BadRequest(ModelState); var command = new DeleteAssetCommand { Id = id }; return await ExecuteRequest(command).ConfigureAwait(false); } } }
34.907895
141
0.616849
[ "MIT" ]
anndreiAbabei/Kubera
src/Kubera.App/Controllers/V1/AssetController.cs
5,308
C#
using FluentValidation; using Pygma.Blog.ViewModels.Requests.BlogPosts; namespace Pygma.Blog.Validations.BlogPosts { public class CreateBlogPostValidator : AbstractValidator<CreateBlogPostVm> { public CreateBlogPostValidator() { RuleFor(x => x) .SetValidator(new UpsertBlogPostValidator()); } } }
25.785714
78
0.67313
[ "MIT" ]
CodeExcavator/project-pygma
backend/.net core-be/Pygma/src/Pygma.Blog/Validations/BlogPosts/CreateBlogPostValidator.cs
361
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CarDealer.Models { public class Car { public Car() { this.Sales = new List<Sale>(); this.PartCars = new List<PartCar>(); } public int Id { get; set; } [Required] public string Make { get; set; } [Required] public string Model { get; set; } [Required] public long TravelledDistance { get; set; } public ICollection<Sale> Sales { get; set; } public ICollection<PartCar> PartCars { get; set; } } }
21.517241
59
0.5625
[ "MIT" ]
MiroslavaPetrova/SoftUni-Solutions
CSharp DB Advanced/10.JSON Processing/02.Car Dealer/CarDealer/Models/Car.cs
626
C#
namespace Restaurant { partial class LoginForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LoginForm)); this.Username_TextBox = new System.Windows.Forms.TextBox(); this.Login_Button = new System.Windows.Forms.Button(); this.Username_Label = new System.Windows.Forms.Label(); this.Header_Label = new System.Windows.Forms.Label(); this.Password_Label = new System.Windows.Forms.Label(); this.Password_TextBox = new System.Windows.Forms.TextBox(); this.Failed_Label = new System.Windows.Forms.Label(); this.SuspendLayout(); // // Username_TextBox // this.Username_TextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Username_TextBox.Location = new System.Drawing.Point(12, 118); this.Username_TextBox.Name = "Username_TextBox"; this.Username_TextBox.Size = new System.Drawing.Size(360, 26); this.Username_TextBox.TabIndex = 0; // // Login_Button // this.Login_Button.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Login_Button.Location = new System.Drawing.Point(272, 269); this.Login_Button.Name = "Login_Button"; this.Login_Button.Size = new System.Drawing.Size(100, 30); this.Login_Button.TabIndex = 2; this.Login_Button.Text = "Login"; this.Login_Button.UseVisualStyleBackColor = true; this.Login_Button.Click += new System.EventHandler(this.loginClick); // // Username_Label // this.Username_Label.AutoSize = true; this.Username_Label.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Username_Label.Location = new System.Drawing.Point(12, 95); this.Username_Label.Name = "Username_Label"; this.Username_Label.Size = new System.Drawing.Size(83, 20); this.Username_Label.TabIndex = 2; this.Username_Label.Text = "Username"; // // Header_Label // this.Header_Label.AutoSize = true; this.Header_Label.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Header_Label.Location = new System.Drawing.Point(60, 30); this.Header_Label.Name = "Header_Label"; this.Header_Label.Size = new System.Drawing.Size(261, 37); this.Header_Label.TabIndex = 3; this.Header_Label.Text = "Restaurant Login"; // // Password_Label // this.Password_Label.AutoSize = true; this.Password_Label.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Password_Label.Location = new System.Drawing.Point(13, 170); this.Password_Label.Name = "Password_Label"; this.Password_Label.Size = new System.Drawing.Size(78, 20); this.Password_Label.TabIndex = 4; this.Password_Label.Text = "Password"; // // Password_TextBox // this.Password_TextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Password_TextBox.Location = new System.Drawing.Point(12, 193); this.Password_TextBox.Name = "Password_TextBox"; this.Password_TextBox.PasswordChar = '*'; this.Password_TextBox.Size = new System.Drawing.Size(360, 26); this.Password_TextBox.TabIndex = 1; this.Password_TextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.enterKeyPress); // // Failed_Label // this.Failed_Label.AutoSize = true; this.Failed_Label.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Failed_Label.ForeColor = System.Drawing.Color.Red; this.Failed_Label.Location = new System.Drawing.Point(13, 274); this.Failed_Label.Name = "Failed_Label"; this.Failed_Label.Size = new System.Drawing.Size(95, 20); this.Failed_Label.TabIndex = 6; this.Failed_Label.Text = "Login Failed"; this.Failed_Label.Visible = false; // // Login_Form // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(384, 311); this.Controls.Add(this.Failed_Label); this.Controls.Add(this.Password_TextBox); this.Controls.Add(this.Password_Label); this.Controls.Add(this.Header_Label); this.Controls.Add(this.Username_Label); this.Controls.Add(this.Login_Button); this.Controls.Add(this.Username_TextBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MaximumSize = new System.Drawing.Size(400, 350); this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(400, 350); this.Name = "Login_Form"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox Username_TextBox; private System.Windows.Forms.Button Login_Button; private System.Windows.Forms.Label Header_Label; private System.Windows.Forms.Label Username_Label; private System.Windows.Forms.TextBox Password_TextBox; private System.Windows.Forms.Label Password_Label; private System.Windows.Forms.Label Failed_Label; } }
52.055556
176
0.622732
[ "MIT" ]
BlakeBerry26/SWE-Project-2019
Restaurant/Forms/LoginForm.Designer.cs
7,498
C#
//using HealthChecks.UI.Client; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using MyWebAPITemplate.Source.Web.Middlewares; namespace MyWebAPITemplate.Extensions { /// <summary> /// Contains all the application builder extension methods for configuring the system /// This is the class for all kind of registerations for IApplicationBuilder /// </summary> public static class ApplicationBuilderExtensions { /// <summary> /// Configs for local development /// Contains development tool and other development related settings /// Should be run first /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <returns></returns> public static IApplicationBuilder ConfigureDevelopmentSettings(this IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app .UseDeveloperExceptionPage() .UseMigrationsEndPoint() .UseCors(); //.UseShowAllServicesMiddleware() //.UseDatabaseErrorPage(); } return app; } /// <summary> /// Swagger configurations /// Should be run before routing configurations /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder ConfigureSwagger(this IApplicationBuilder app) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Template API V1"); }); return app; } /// <summary> /// Middleware usings /// All the middlewares should be registered here /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <returns></returns> public static IApplicationBuilder UseCustomMiddlewares(this IApplicationBuilder app, IWebHostEnvironment env) { // Global error handling app.UseMiddleware<GlobalErrorHandlingMiddleware>(); return app; } /// <summary> /// Used for applying different cors settings /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseCors(this IApplicationBuilder app) { app.UseCors("AnyOrigin"); // TODO: Remember to change this when more specific cors settings are configured return app; } /// <summary> /// Routing related configurations /// This should be run last in Startup.cs configure /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder ConfigureRouting(this IApplicationBuilder app) { app.UseHttpsRedirection(); app.UseRouting(); app.UseEndpoints(routeBuilder => { //routeBuilder.MapAllHealthChecks(); routeBuilder.MapControllers(); }); return app; } //private static void MapAllHealthChecks(this IEndpointRouteBuilder routeBuilder) //{ // routeBuilder.MapHealthChecks("/health", new HealthCheckOptions // { // Predicate = _ => true, // ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse // }); // routeBuilder.MapHealthChecksUI(); //} } }
33.033613
125
0.570593
[ "MIT" ]
attuo/MyWebAPITemplate
app/src/Web/Extensions/ApplicationBuilderExtensions.cs
3,933
C#
using System.Collections.Generic; using System.Linq; using Elsa.Metadata; using Elsa.Models; using Elsa.WorkflowDesigner.Models; namespace Elsa.Dashboard.Areas.Elsa.ViewModels { public class WorkflowInstanceDetailsModel { public WorkflowInstanceDetailsModel( WorkflowInstance workflowInstance, WorkflowDefinitionVersion workflowDefinition, WorkflowModel workflowModel, IEnumerable<ActivityDescriptor> activityDefinitions, string returnUrl) { WorkflowInstance = workflowInstance; WorkflowDefinition = workflowDefinition; WorkflowModel = workflowModel; ActivityDefinitions = activityDefinitions.ToArray(); ReturnUrl = returnUrl; } public WorkflowInstance WorkflowInstance { get; } public WorkflowDefinitionVersion WorkflowDefinition { get; } public WorkflowModel WorkflowModel { get; } public ActivityDescriptor[] ActivityDefinitions { get; } public string ReturnUrl { get; } } }
34.677419
68
0.688372
[ "BSD-3-Clause" ]
1000sprites/elsa-core
src/dashboard/Elsa.Dashboard/Areas/Elsa/ViewModels/WorkflowInstanceDetailsModel.cs
1,075
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace h3t3 { class Program { static void Main(string[] args) { television television = new television(); television.IsOn = true; television.Volume = 0; television.Channel = 0; Console.WriteLine(television.ToString()); Console.ReadLine(); television.AdjustVolumeUp(); television.AdjustVolumeUp(); television.AdjustVolumeUp(); Console.WriteLine(television.ToString()); Console.ReadLine(); television.AdjustVolumeDown(); television.AdjustVolumeDown(); television.AdjustVolumeDown(); Console.WriteLine(television.ToString()); Console.ReadLine(); television.ChangeChannelUp(); television.ChangeChannelUp(); television.ChangeChannelDown(); television.IsOn = false; Console.WriteLine(television.ToString()); Console.ReadLine(); } } }
24.638298
53
0.580311
[ "Apache-2.0" ]
AskoVaananen/Csharp-ohjelmointi
h3t1/h3t1/h3t3/Program.cs
1,160
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using AM; using AM.Runtime; using AM.Xml; using ManagedIrbis; using Newtonsoft.Json.Linq; namespace UnitTests.ManagedIrbis { [TestClass] public class SubFieldTest { [TestMethod] public void SubField_Constructor_1() { SubField subField = new SubField(); Assert.AreEqual(SubField.NoCode, subField.Code); Assert.AreEqual(SubField.NoCodeString, subField.CodeString); Assert.AreEqual(null, subField.Value); Assert.AreEqual("^\0", subField.ToString()); subField = new SubField('A', "The value"); Assert.AreEqual('A', subField.Code); Assert.AreEqual("A", subField.CodeString); Assert.AreEqual("The value", subField.Value); Assert.AreEqual("^aThe value", subField.ToString()); SubField clone = subField.Clone(); Assert.AreEqual(subField.Code, clone.Code); Assert.AreEqual(subField.CodeString, clone.CodeString); Assert.AreEqual(subField.Value, clone.Value); Assert.AreEqual("^aThe value", clone.ToString()); Assert.AreEqual(0, SubField.Compare(subField, clone)); subField.SetValue("New value"); Assert.AreEqual("New value", subField.Value); subField.SetValue(null); Assert.AreEqual(null, subField.Value); } private void _TestSerialization ( params SubField[] subFields ) { SubField[] array1 = subFields; byte[] bytes = array1.SaveToMemory(); SubField[] array2 = bytes .RestoreArrayFromMemory<SubField>(); Assert.AreEqual(array1.Length, array2.Length); for (int i = 0; i < array1.Length; i++) { Assert.AreEqual ( 0, SubField.Compare(array1[i], array2[i]) ); } } [TestMethod] public void SubField_Serialization_1() { _TestSerialization(new SubField[0]); _TestSerialization(new SubField()); _TestSerialization(new SubField(), new SubField()); _TestSerialization(new SubField('a'), new SubField('b')); _TestSerialization(new SubField('a', "Hello"), new SubField('b', "World")); } [TestMethod] public void SubField_SetValue_1() { SubField subField = new SubField('a') { Value = "Right Value" }; Assert.AreEqual("Right Value", subField.Value); } [TestMethod] public void SubField_SetValue_2() { bool saveFlag = SubField.TrimValue; SubField.TrimValue = false; SubField subField = new SubField('a') { Value = " Right Value " }; Assert.AreEqual(" Right Value ", subField.Value); SubField.TrimValue = saveFlag; } [TestMethod] public void SubField_SetValue_3() { bool saveFlag = SubField.TrimValue; SubField.TrimValue = true; SubField subField = new SubField('a') { Value = " Right Value " }; Assert.AreEqual("Right Value", subField.Value); SubField.TrimValue = saveFlag; } [TestMethod] public void SubField_SetValue_4() { SubField subField = new SubField('a') { Value = "Right\nValue" }; Assert.AreEqual("Right Value", subField.Value); } [TestMethod] [ExpectedException(typeof(VerificationException))] public void SubField_SetValue_Exception_1() { bool save = SubFieldValue.ThrowOnVerify; SubFieldValue.ThrowOnVerify = true; try { SubField subField = new SubField('a') { Value = "Wrong^Value" }; Assert.IsNull(subField.Value); } finally { SubFieldValue.ThrowOnVerify = save; } } [TestMethod] [ExpectedException(typeof(ReadOnlyException))] public void SubField_ReadOnly_1() { SubField subField = new SubField('a', "Value", true, null); Assert.AreEqual("Value", subField.Value); subField.Value = "New value"; Assert.AreEqual("Value", subField.Value); } [TestMethod] [ExpectedException(typeof(ReadOnlyException))] public void SubField_AsReadOnly_1() { SubField subField = new SubField('a', "Value") .AsReadOnly(); Assert.AreEqual("Value", subField.Value); subField.Value = "New value"; Assert.AreEqual("Value", subField.Value); } [TestMethod] public void SubField_ToJObject_1() { SubField subField = new SubField('a', "Value"); JObject jObject = subField.ToJObject(); Assert.AreEqual("a", jObject["code"].ToString()); Assert.AreEqual("Value", jObject["value"].ToString()); } [TestMethod] public void SubField_ToJson_1() { SubField subField = new SubField('a', "Value"); string actual = subField.ToJson(); const string expected = @"{'code':'a','value':'Value'}"; Assert.AreEqual(expected, actual); } [TestMethod] public void SubField_FromJObject_1() { JObject jObject = new JObject ( new JProperty("code", "a"), new JProperty("value", "Value") ); SubField subField = SubFieldUtility.FromJObject(jObject); Assert.AreEqual('a', subField.Code); Assert.AreEqual("Value", subField.Value); } [TestMethod] public void SubField_FromJson_1() { const string text = @"{" +@" ""code"": ""a""," +@" ""value"": ""Value""" +@"}"; SubField subField = SubFieldUtility.FromJson(text); Assert.AreEqual('a', subField.Code); Assert.AreEqual("Value", subField.Value); } [TestMethod] public void SubField_ToXml_1() { SubField subField = new SubField('a', "Value"); string actual = XmlUtility.SerializeShort(subField); const string expected = "<subfield code=\"a\" value=\"Value\" />"; Assert.AreEqual(expected, actual); } [TestMethod] public void SubField_Field_1() { SubField subField = new SubField('a', "Title"); Assert.IsNull(subField.Field); RecordField field = new RecordField("200"); field.SubFields.Add(subField); Assert.AreEqual(field, subField.Field); } [TestMethod] public void SubField_Path_1() { SubField subField = new SubField(); Assert.AreEqual(string.Empty, subField.Path); subField = new SubField('a', "Title"); Assert.AreEqual("^a", subField.Path); RecordField field = new RecordField("200"); field.SubFields.Add(subField); Assert.AreEqual("200/0^a", subField.Path); } [TestMethod] public void SubField_Path_2() { RecordField field = new RecordField(100); SubField subField = new SubField(); field.SubFields.Add(subField); Assert.AreEqual("100/0", subField.Path); } [TestMethod] public void SubField_Verify_1() { SubField subField = new SubField(); Assert.IsFalse(subField.Verify(false)); subField = new SubField('a'); Assert.IsTrue(subField.Verify(false)); subField = new SubField('a', "Title"); Assert.IsTrue(subField.Verify(false)); } [TestMethod] public void SubField_Compare_1() { SubField subField1 = new SubField('a'); SubField subField2 = new SubField('b'); Assert.IsTrue ( SubField.Compare(subField1, subField2) < 0 ); subField1 = new SubField('a', "Title1"); subField2 = new SubField('a', "Title2"); Assert.IsTrue ( SubField.Compare(subField1, subField2) < 0 ); subField1 = new SubField('a', "Title"); subField2 = new SubField('a', "Title"); Assert.IsTrue ( SubField.Compare(subField1, subField2) == 0 ); } [TestMethod] public void SubField_SetModified_1() { SubField subField = new SubField('a', "Title1"); Assert.IsFalse(subField.Modified); subField.Value = "Title2"; Assert.IsTrue(subField.Modified); subField.NotModified(); Assert.IsFalse(subField.Modified); } [TestMethod] public void SubField_SetModified_2() { RecordField field = new RecordField("200"); Assert.IsFalse(field.Modified); SubField subField = new SubField('a', "Title1"); Assert.IsFalse(subField.Modified); field.SubFields.Add(subField); field.NotModified(); subField.Value = "Title2"; Assert.IsTrue(subField.Modified); Assert.IsTrue(field.Modified); subField.NotModified(); Assert.IsFalse(subField.Modified); } [TestMethod] public void SubField_UserData_1() { SubField subField = new SubField(); Assert.IsNull(subField.UserData); subField.UserData = "User data"; Assert.AreEqual("User data", subField.UserData); } [TestMethod] public void SubField_ToString_1() { SubField subField = new SubField(); Assert.AreEqual("^\0", subField.ToString()); subField = new SubField('a'); Assert.AreEqual("^a", subField.ToString()); subField = new SubField('A'); Assert.AreEqual("^a", subField.ToString()); subField = new SubField('a', "Title"); Assert.AreEqual("^aTitle", subField.ToString()); } } }
31.146552
78
0.521912
[ "MIT" ]
amironov73/ManagedClient.45
Source/UnitTests/ManagedIrbis/SubFieldTest.cs
10,841
C#
//----------------------------------------------------------------------- // ETP DevKit, 1.2 // // Copyright 2021 Energistics // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //----------------------------------------------------------------------- using System.Collections.Generic; namespace Energistics.Avro.Schemas.Navigation { public interface ISchemaVisitor<TSchema, TResult> { TResult VisitTypeName(string typeDescriptor, NavigationContext context); TResult VisitLogical(TSchema logical, string typeDescriptor, string baseTypeDescriptor, TResult baseTypeResult, string logicalType, NavigationContext context); TResult VisitPrimitive(string primitiveName, NavigationContext context); TResult VisitRecord(TSchema record, string recordName, NavigationContext context); TResult VisitRecordFields(TSchema record, string recordName, TResult recordResult, IReadOnlyList<string> fieldNames, IReadOnlyList<string> fieldValueDescriptors, IReadOnlyList<TResult> fieldValueResults, NavigationContext context); TResult VisitEnum(TSchema @enum, string enumName, IReadOnlyList<string> symbols, NavigationContext context); TResult VisitFixed(TSchema @fixed, string fixedName, long size, NavigationContext context); TResult VisitArray(TSchema array, string typeDescriptor, string itemsDescriptor, TResult itemsResult, NavigationContext context); TResult VisitMap(TSchema map, string typeDescriptor, string valuesDescriptor, TResult valuesResult, NavigationContext context); TResult VisitNullable(TSchema nullable, string typeDescriptor, bool nullFirst, string valueDescriptor, TResult valueResult, NavigationContext context); TResult VisitChoice(TSchema choice, string typeDescriptor, IReadOnlyList<string> valueDescriptors, IReadOnlyList<TResult> valueResults, NavigationContext context); } }
50.229167
239
0.732476
[ "Apache-2.0" ]
pds-technology/etp.net
src/Energistics.Avro.Schemas/Navigation/ISchemaVisitor.cs
2,413
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.Collections; using System.ComponentModel; using System.IO; using System.Threading.Tasks; using System.Threading; namespace System.Data.Common { public abstract partial class DbDataReader : MarshalByRefObject, IDataReader, IEnumerable { protected DbDataReader() : base() { } public abstract int Depth { get; } public abstract int FieldCount { get; } public abstract bool HasRows { get; } public abstract bool IsClosed { get; } public abstract int RecordsAffected { get; } public virtual int VisibleFieldCount => FieldCount; public abstract object this[int ordinal] { get; } public abstract object this[string name] { get; } public virtual void Close() { } [EditorBrowsable(EditorBrowsableState.Never)] public void Dispose() => Dispose(true); protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } public abstract string GetDataTypeName(int ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public abstract IEnumerator GetEnumerator(); public abstract Type GetFieldType(int ordinal); public abstract string GetName(int ordinal); public abstract int GetOrdinal(string name); public virtual DataTable GetSchemaTable() { throw new NotSupportedException(); } public abstract bool GetBoolean(int ordinal); public abstract byte GetByte(int ordinal); public abstract long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length); public abstract char GetChar(int ordinal); public abstract long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length); [EditorBrowsable(EditorBrowsableState.Never)] public DbDataReader GetData(int ordinal) => GetDbDataReader(ordinal); IDataReader IDataRecord.GetData(int ordinal) => GetDbDataReader(ordinal); protected virtual DbDataReader GetDbDataReader(int ordinal) { throw ADP.NotSupported(); } public abstract DateTime GetDateTime(int ordinal); public abstract decimal GetDecimal(int ordinal); public abstract double GetDouble(int ordinal); public abstract float GetFloat(int ordinal); public abstract Guid GetGuid(int ordinal); public abstract short GetInt16(int ordinal); public abstract int GetInt32(int ordinal); public abstract long GetInt64(int ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Type GetProviderSpecificFieldType(int ordinal) { // NOTE: This is virtual because not all providers may choose to support // this method, since it was added in Whidbey. return GetFieldType(ordinal); } [ EditorBrowsable(EditorBrowsableState.Never) ] public virtual object GetProviderSpecificValue(int ordinal) { // NOTE: This is virtual because not all providers may choose to support // this method, since it was added in Whidbey return GetValue(ordinal); } [ EditorBrowsable(EditorBrowsableState.Never) ] public virtual int GetProviderSpecificValues(object[] values) => GetValues(values); public abstract string GetString(int ordinal); public virtual Stream GetStream(int ordinal) { using (MemoryStream bufferStream = new MemoryStream()) { long bytesRead = 0; long bytesReadTotal = 0; byte[] buffer = new byte[4096]; do { bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length); bufferStream.Write(buffer, 0, (int)bytesRead); bytesReadTotal += bytesRead; } while (bytesRead > 0); return new MemoryStream(bufferStream.ToArray(), false); } } public virtual TextReader GetTextReader(int ordinal) { if (IsDBNull(ordinal)) { return new StringReader(string.Empty); } else { return new StringReader(GetString(ordinal)); } } public abstract object GetValue(int ordinal); public virtual T GetFieldValue<T>(int ordinal) => (T)GetValue(ordinal); public Task<T> GetFieldValueAsync<T>(int ordinal) => GetFieldValueAsync<T>(ordinal, CancellationToken.None); public virtual Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<T>(); } else { try { return Task.FromResult<T>(GetFieldValue<T>(ordinal)); } catch (Exception e) { return Task.FromException<T>(e); } } } public abstract int GetValues(object[] values); public abstract bool IsDBNull(int ordinal); public Task<bool> IsDBNullAsync(int ordinal) => IsDBNullAsync(ordinal, CancellationToken.None); public virtual Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<bool>(); } else { try { return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return Task.FromException<bool>(e); } } } public abstract bool NextResult(); public abstract bool Read(); public Task<bool> ReadAsync() => ReadAsync(CancellationToken.None); public virtual Task<bool> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<bool>(); } else { try { return Read() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return Task.FromException<bool>(e); } } } public Task<bool> NextResultAsync() => NextResultAsync(CancellationToken.None); public virtual Task<bool> NextResultAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<bool>(); } else { try { return NextResult() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return Task.FromException<bool>(e); } } } } }
30.666667
113
0.568841
[ "MIT" ]
Drawaes/corefx
src/System.Data.Common/src/System/Data/Common/DbDataReader.cs
7,728
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using VisioAutomation.Extensions; using VACONT = VisioAutomation.Models.Layouts.Container; using IVisio = Microsoft.Office.Interop.Visio; namespace VisioAutomation_Tests.Models.Layouts { [TestClass] public class CointainerLayout_Tests : VisioAutomationTest { [TestMethod] public void Container_PerformLayoutBeforeRender() { // Purpose: Verify that if PerformLayout is NOT called before Render() // is called then an exception will be thrown bool caught = false; var layout = new VACONT.ContainerLayout(); var doc = this.GetNewDoc(); try { var c1 = layout.AddContainer("A"); var i1 = c1.Add("A1"); // layout.PerformLayout(); IVisio.Page page = layout.Render(doc); page.Delete(0); } catch (System.ArgumentException) { caught = true; } doc.Close(true); if (caught == false) { Assert.Fail("Did not catch expected exception"); } } [TestMethod] public void Container_Diagram1() { // Purpose: Simple test to make sure that both Containers and Non-Container // rendering are supported. The diagram is a single container having a single // container item var doc = this.GetNewDoc(); var layout1 = new VACONT.ContainerLayout(); var l1_c1 = layout1.AddContainer("L1/C1"); var l1_c1_i1 = l1_c1.Add("L1/C1/I1"); layout1.PerformLayout(); var page1 = layout1.Render(doc); page1.Delete(0); doc.Close(true); } [TestMethod] public void Container_Diagram2() { // Make sure that empty containers can be drawn var doc = this.GetNewDoc(); var layout1 = new VACONT.ContainerLayout(); var l1_c1 = layout1.AddContainer("L1/C1"); var l1_c1_i1 = l1_c1.Add("L1/C1/I1"); var l1_c2 = layout1.AddContainer("L1/C2"); // this is the empty container layout1.PerformLayout(); var page1 = layout1.Render(doc); page1.Delete(0); doc.Close(true); } } }
30.878049
90
0.526461
[ "MIT" ]
jhliptak/VisioAutomation
VisioAutomation_2010/VisioAutomation.Tests.Models/Layouts/CointainerLayout_Tests.cs
2,532
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.CloudWatchEvents")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon CloudWatch Events. Amazon CloudWatch Events helps you to respond to state changes in your AWS resources. When your resources change state they automatically send events into an event stream. You can create rules that match selected events in the stream and route them to targets to take action. You can also use rules to take action on a pre-determined schedule.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.4.20")]
53.71875
449
0.760326
[ "Apache-2.0" ]
rczwojdrak/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/CloudWatchEvents/Properties/AssemblyInfo.cs
1,719
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler { private Image bgImg; private Image joystickImg; private Vector3 inputVector; private void Start(){ bgImg = GetComponent<Image> (); joystickImg = transform.GetChild (0).GetComponent<Image> (); } public virtual void OnDrag(PointerEventData ped){ Vector2 pos; if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos)) { pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x); pos.y = (pos.y / bgImg.rectTransform.sizeDelta.y); inputVector = new Vector3 (pos.x * 2 + 1, 0, pos.y * 2 - 1); inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector; joystickImg.rectTransform.anchoredPosition = new Vector3 (inputVector.x * (bgImg.rectTransform.sizeDelta.x / 2.5f), inputVector.z * (bgImg.rectTransform.sizeDelta.y / 2.5f), 0); } } public virtual void OnPointerDown(PointerEventData ped){ OnDrag (ped); } public virtual void OnPointerUp(PointerEventData ped){ inputVector = Vector3.zero; joystickImg.rectTransform.anchoredPosition = Vector3.zero; } public float Horizontal(){ return inputVector.x; } public float Vertical(){ return inputVector.z; } }
28.018868
180
0.723232
[ "Apache-2.0" ]
losersEngine/Breath
Assets/Assets/FPSControllerKevin/Scripts/VirtualJoystick.cs
1,487
C#
namespace WebAppRazor.Entities { public class CartItem { public int Id { get; set; } public int Quantity { get; set; } public string Color { get; set; } public decimal Price { get; set; } public int ProductId { get; set; } public Product Product { get; set; } } }
25
44
0.566154
[ "MIT" ]
hoale240803/E-commerce-Microservice
src/WebApps/WebAppRazor/Entities/CartItem.cs
327
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Assign a list of group DNs to the IMRN pool. It is possible to assign either: a single DN, /// or a list of DNs, or a range of DNs, or any combination thereof. /// The response is either SuccessResponse or ErrorResponse. /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""f3a93cf15de4abd7903673e44ee3e07b:6340""}]")] public class GroupIMRNAssignListRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.C.SuccessResponse> { private string _serviceProviderId; [XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")] [Group(@"f3a93cf15de4abd7903673e44ee3e07b:6340")] [MinLength(1)] [MaxLength(30)] public string ServiceProviderId { get => _serviceProviderId; set { ServiceProviderIdSpecified = true; _serviceProviderId = value; } } [XmlIgnore] protected bool ServiceProviderIdSpecified { get; set; } private string _groupId; [XmlElement(ElementName = "groupId", IsNullable = false, Namespace = "")] [Group(@"f3a93cf15de4abd7903673e44ee3e07b:6340")] [MinLength(1)] [MaxLength(30)] public string GroupId { get => _groupId; set { GroupIdSpecified = true; _groupId = value; } } [XmlIgnore] protected bool GroupIdSpecified { get; set; } private List<string> _imrn = new List<string>(); [XmlElement(ElementName = "imrn", IsNullable = false, Namespace = "")] [Optional] [Group(@"f3a93cf15de4abd7903673e44ee3e07b:6340")] [MinLength(1)] [MaxLength(23)] public List<string> Imrn { get => _imrn; set { ImrnSpecified = true; _imrn = value; } } [XmlIgnore] protected bool ImrnSpecified { get; set; } private List<BroadWorksConnector.Ocip.Models.DNRange> _imrnRange = new List<BroadWorksConnector.Ocip.Models.DNRange>(); [XmlElement(ElementName = "imrnRange", IsNullable = false, Namespace = "")] [Optional] [Group(@"f3a93cf15de4abd7903673e44ee3e07b:6340")] public List<BroadWorksConnector.Ocip.Models.DNRange> ImrnRange { get => _imrnRange; set { ImrnRangeSpecified = true; _imrnRange = value; } } [XmlIgnore] protected bool ImrnRangeSpecified { get; set; } } }
30.673267
141
0.586185
[ "MIT" ]
cwmiller/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupIMRNAssignListRequest.cs
3,098
C#
public interface IEncryption { string Encrypt(string str, string password); string Encrypt(string str); // Sadly constants aren't allowed in interfaces, therefore we overload. string Decrypt(string encryptedStr, string password); string Decrypt(string encryptedStr); // Sadly constants aren't allowed in interfaces, therefore we overload. }
39.888889
112
0.763231
[ "MIT" ]
SquirtingElephant/Intergalactic-Phone-Book
Assets/Scripts/Encryption/IEncryption.cs
361
C#
using SV.Builder.Mobile.Views.Enums; namespace SV.Builder.Mobile.Views.Labels.IconLabels { public class EllipsisHLabel : FASolidIcons { public EllipsisHLabel() { Text = FA5SolidEnum.EllipsisH; } } }
19.153846
51
0.630522
[ "MIT" ]
peterfournier/SoftwareVets.WorkoutBuilder
SV.Builder.Mobile.Pages/Labels/IconLabels/EllipsisHLabel.cs
251
C#
using NRealbit.Crypto; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace NRealbit.Tests { class AssertEx { [DebuggerHidden] internal static void Error(string msg) { Assert.False(true, msg); } [DebuggerHidden] internal static void Equal<T>(T actual, T expected) { Assert.Equal(expected, actual); } [DebuggerHidden] internal static void CollectionEquals<T>(T[] actual, T[] expected) { if (actual.Length != expected.Length) Assert.False(true, "Actual.Length(" + actual.Length + ") != Expected.Length(" + expected.Length + ")"); for (int i = 0; i < actual.Length; i++) { if (!Object.Equals(actual[i], expected[i])) Assert.False(true, "Actual[" + i + "](" + actual[i] + ") != Expected[" + i + "](" + expected[i] + ")"); } } [DebuggerHidden] internal static void StackEquals(ContextStack<byte[]> stack1, ContextStack<byte[]> stack2) { var hash1 = stack1.Select(o => Hashes.DoubleSHA256(o)).ToArray(); var hash2 = stack2.Select(o => Hashes.DoubleSHA256(o)).ToArray(); AssertEx.CollectionEquals(hash1, hash2); } internal static void CollectionEquals(System.Collections.BitArray bitArray, int p) { throw new NotImplementedException(); } } }
26.196078
108
0.673653
[ "MIT" ]
maren7/NRealbit
NRealbit.Tests/AssertEx.cs
1,338
C#
// Generated class v2.19.0.0, don't modify using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace NHtmlUnit.Javascript.Host.Svg { public partial class SVGPathSegCurvetoQuadraticAbs : NHtmlUnit.Javascript.Host.Svg.SVGPathSeg { static SVGPathSegCurvetoQuadraticAbs() { ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.svg.SVGPathSegCurvetoQuadraticAbs o) => new SVGPathSegCurvetoQuadraticAbs(o)); } public SVGPathSegCurvetoQuadraticAbs(com.gargoylesoftware.htmlunit.javascript.host.svg.SVGPathSegCurvetoQuadraticAbs wrappedObject) : base(wrappedObject) {} public new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGPathSegCurvetoQuadraticAbs WObj { get { return (com.gargoylesoftware.htmlunit.javascript.host.svg.SVGPathSegCurvetoQuadraticAbs)WrappedObject; } } public SVGPathSegCurvetoQuadraticAbs() : this(new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGPathSegCurvetoQuadraticAbs()) {} } }
34.030303
162
0.767587
[ "Apache-2.0" ]
JonAnders/NHtmlUnit
app/NHtmlUnit/Generated/Javascript/Host/Svg/SVGPathSegCurvetoQuadraticAbs.cs
1,123
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Sho.BankIntegration.Monobank.Models; using Sho.BankIntegration.Monobank.Models.Internal; using Sho.BankIntegration.Monobank.Utils; namespace Sho.BankIntegration.Monobank.Services { public class MonobankAccountService { private readonly MonobankHttpClient _monobankClient; public MonobankAccountService(MonobankHttpClient monobankClient) { _monobankClient = monobankClient; } /// <summary> /// Gets information about client and client accounts. /// Monobank API reference: <https://api.monobank.ua/docs/#tag---------------------------->. /// </summary> /// <param name="token">Client auth token.</param> /// <returns></returns> public async Task<MonobankClientInfo> GetClientInfoAsync(string token) { HttpResponseMessage response = await _monobankClient.GetPersonalDataAsync("personal/client-info", token); string json = await response.Content.ReadAsStringAsync(); ClientInfo info = JsonConvert.DeserializeObject<ClientInfo>(json); var accounts = info.Accounts .Select(a => new MonobankAccount(a.Id, a.Balance, a.CreditLimit, a.CurrencyCode, a.CashbackType)) .ToList(); return new MonobankClientInfo(info.Name, info.WebHookUrl, accounts); } /// <summary> /// Gets client account transactions for the specified period. /// Maximum statement interval is 31 days + 1 hour (2682000 seconds). /// Maximum request interval is 1 time in 60 seconds. /// Monobank API reference: <https://api.monobank.ua/docs/#operation--personal-statement--account---from---to--get>. /// </summary> /// <param name="token">Client auth token.</param> /// <param name="account">Account identifier from statement list or 0 for default account.</param> /// <param name="from">Start time of the statement.</param> /// <param name="to">End time of the statement.</param> /// <returns></returns> public async Task<IReadOnlyCollection<MonobankAccountTransaction>> GetAccountTransactionsAsync(string token, string account, DateTime from, DateTime to) { string fromTime = from.ToUnixTime().ToString(); string toTime = to.ToUnixTime().ToString(); HttpResponseMessage response = await _monobankClient.GetPersonalDataAsync($"personal/statement/{account}/{fromTime}/{toTime}", token); string json = await response.Content.ReadAsStringAsync(); var items = JsonConvert.DeserializeObject<IEnumerable<StatementItem>>(json); var transactions = items .Select(t => new MonobankAccountTransaction( t.Id, t.Time.FromUnixTime(), t.Description, t.CurrencyCode, t.Amount, t.Balance, t.Mcc, t.Hold, t.CommissionRate, t.CashbackAmount)) .ToList(); return transactions; } /// <summary> /// Sets service URL to receive POST responses about client new transactions. /// If the service URL will not respond in 5 seconds, the request will be retried in 60 and 600 seconds. /// After retries without a success webhook functionality will be disabled. /// Monobank API reference: <https://api.monobank.ua/docs/#operation--personal-webhook-post>. /// </summary> /// <param name="token"></param> /// <param name="webHookUrl"></param> /// <returns></returns> public async Task<bool> SetWebHookAsync(string token, string webHookUrl) { string body = JsonConvert.SerializeObject(new { webHookUrl = webHookUrl }); HttpResponseMessage response = await _monobankClient.PostAsync("personal/webhook", body, token); return response.IsSuccessStatusCode; } } }
47.034884
160
0.650185
[ "MIT" ]
AQdf/Shchack.BankIntegration.Monobank
Shchack.BankIntegration.Monobank/Services/MonobankAccountService.cs
4,047
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace Microsoft.DotNet.Interactive { internal class StreamKernelCommand { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("commandType")] public string CommandType { get; set; } [JsonProperty("command")] public object Command { get; set; } } }
26.25
101
0.664762
[ "MIT" ]
0xblack/try
Microsoft.DotNet.Interactive/StreamKernelCommand.cs
527
C#
using System.Collections.Immutable; using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Analyzers.ClassicModelAssertUsage; using NUnit.Analyzers.Constants; using NUnit.Framework; namespace NUnit.Analyzers.Tests.ClassicModelAssertUsage { [TestFixture] public sealed class IsNotInstanceOfClassicModelAssertUsageCodeFixTests { private static readonly DiagnosticAnalyzer analyzer = new ClassicModelAssertUsageAnalyzer(); private static readonly CodeFixProvider fix = new IsNotInstanceOfClassicModelAssertUsageCodeFix(); private static readonly ExpectedDiagnostic expectedDiagnostic = ExpectedDiagnostic.Create(AnalyzerIdentifiers.IsNotInstanceOfUsage); [Test] public void VerifyGetFixableDiagnosticIds() { var fix = new IsNotInstanceOfClassicModelAssertUsageCodeFix(); var ids = fix.FixableDiagnosticIds; Assert.That(ids, Is.EquivalentTo(new[] { AnalyzerIdentifiers.IsNotInstanceOfUsage })); } [Test] public void VerifyIsNotInstanceOfFix() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings($@" public void TestMethod() {{ var expected = typeof(int); var actual = 42; ↓Assert.IsNotInstanceOf(expected, actual); }}"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var expected = typeof(int); var actual = 42; Assert.That(actual, Is.Not.InstanceOf(expected)); }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } [Test] public void VerifyIsNotInstanceOfFixWithMessage() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings($@" public void TestMethod() {{ var expected = typeof(int); var actual = 42; ↓Assert.IsNotInstanceOf(expected, actual, ""message""); }}"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var expected = typeof(int); var actual = 42; Assert.That(actual, Is.Not.InstanceOf(expected), ""message""); }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } [Test] public void VerifyIsNotInstanceOfFixWithMessageAndParams() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings($@" public void TestMethod() {{ var expected = typeof(int); var actual = 42; ↓Assert.IsNotInstanceOf(expected, actual, ""message"", Guid.NewGuid()); }}"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var expected = typeof(int); var actual = 42; Assert.That(actual, Is.Not.InstanceOf(expected), ""message"", Guid.NewGuid()); }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } [Test] public void VerifyIsNotInstanceOfGenericFix() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings($@" public void TestMethod() {{ var actual = 42; ↓Assert.IsNotInstanceOf<int>(actual); }}"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var actual = 42; Assert.That(actual, Is.Not.InstanceOf<int>()); }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } [Test] public void VerifyIsNotInstanceOfSingleNestedGenericFix() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var wrapped = Create(42); ↓Assert.IsNotInstanceOf<Wrapped<int>>(wrapped); } private Wrapped<T> Create<T>(T value) => new Wrapped<T>(value); private class Wrapped<T> { public Wrapped(T value) { Value = value; } public T Value { get; } }"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var wrapped = Create(42); Assert.That(wrapped, Is.Not.InstanceOf<Wrapped<int>>()); } private Wrapped<T> Create<T>(T value) => new Wrapped<T>(value); private class Wrapped<T> { public Wrapped(T value) { Value = value; } public T Value { get; } }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } [Test] public void VerifyIsNotInstanceOfDoubleNestedGenericFix() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var wrapped = Create(42); var nested = Create(wrapped); ↓Assert.IsNotInstanceOf<Wrapped<Wrapped<int>>>(wrapped); } private Wrapped<T> Create<T>(T value) => new Wrapped<T>(value); private class Wrapped<T> { public Wrapped(T value) { Value = value; } public T Value { get; } }"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var wrapped = Create(42); var nested = Create(wrapped); Assert.That(wrapped, Is.Not.InstanceOf<Wrapped<Wrapped<int>>>()); } private Wrapped<T> Create<T>(T value) => new Wrapped<T>(value); private class Wrapped<T> { public Wrapped(T value) { Value = value; } public T Value { get; } }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } [Test] public void VerifyIsNotInstanceOfGenericFixWithMessage() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings($@" public void TestMethod() {{ var actual = 42; ↓Assert.IsNotInstanceOf<int>(actual, ""message""); }}"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var actual = 42; Assert.That(actual, Is.Not.InstanceOf<int>(), ""message""); }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } [Test] public void VerifyIsNotInstanceOfGenericFixWithMessageAndParams() { var code = TestUtility.WrapMethodInClassNamespaceAndAddUsings($@" public void TestMethod() {{ var actual = 42; ↓Assert.IsNotInstanceOf<int>(actual, ""message"", Guid.NewGuid()); }}"); var fixedCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" public void TestMethod() { var actual = 42; Assert.That(actual, Is.Not.InstanceOf<int>(), ""message"", Guid.NewGuid()); }"); RoslynAssert.CodeFix(analyzer, fix, expectedDiagnostic, code, fixedCode, fixTitle: ClassicModelAssertUsageCodeFix.TransformToConstraintModelDescription); } } }
36.219917
165
0.582083
[ "MIT" ]
Antash/nunit.analyzers
src/nunit.analyzers.tests/ClassicModelAssertUsage/IsNotInstanceOfClassicModelAssertUsageCodeFixTests.cs
8,745
C#
using System; using HotChocolate.Execution; using HotChocolate.Language; using HotChocolate.Resolvers; using HotChocolate.Types; using static HotChocolate.Stitching.Properties.StitchingResources; namespace HotChocolate.Stitching.Processing.ScopedVariables; internal class ScopedContextDataScopedVariableResolver : IScopedVariableResolver { public ScopedVariableValue Resolve( IResolverContext context, ScopedVariableNode variable, IInputType targetType) { if (context is null) { throw new ArgumentNullException(nameof(context)); } if (variable is null) { throw new ArgumentNullException(nameof(variable)); } if (targetType is null) { throw new ArgumentNullException(nameof(targetType)); } if (!ScopeNames.ScopedContextData.Equals(variable.Scope.Value)) { throw new ArgumentException( ScopedCtxDataScopedVariableResolver_CannotHandleVariable, nameof(variable)); } context.ScopedContextData.TryGetValue(variable.Name.Value, out var data); InputFormatter formatter = context.Service<InputFormatter>(); IValueNode literal = data switch { IValueNode l => l, null => NullValueNode.Default, _ => formatter.FormatValue(data, targetType, PathFactory.Instance.New(variable.Name.Value)) }; return new ScopedVariableValue ( variable.ToVariableName(), targetType.ToTypeNode(), literal, null ); } }
28.084746
103
0.639107
[ "MIT" ]
ChilliCream/prometheus
src/HotChocolate/Stitching/src/Stitching/Processing/ScopedVariables/ScopedContextDataScopedVariableResolver.cs
1,657
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SimpleSchedulerBusiness; using SimpleSchedulerData; using SimpleSchedulerEmail; using SimpleSchedulerModels; namespace SimpleSchedulerService { public sealed class JobExecutor { private readonly IConfiguration _config; private readonly IServiceScopeFactory _scopeFactory; private readonly IEmailer _emailer; private static int _runningTasks; public JobExecutor(IConfiguration config, IServiceScopeFactory scopeFactory, IEmailer emailer) => (_config, _scopeFactory, _emailer) = (config, scopeFactory, emailer); public async Task RestartStuckAppsAsync(CancellationToken cancellationToken) { // https://github.com/dotnet/runtime/issues/43970 IServiceScope scope = default!; try { scope = _scopeFactory.CreateScope(); var jobManager = scope.ServiceProvider.GetRequiredService<IJobManager>(); Trace.TraceInformation("Restarting stuck apps"); await jobManager.RestartStuckJobsAsync(cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.ServiceProvider.GetRequiredService<DatabaseFactory>().MarkForRollback(); if (!string.IsNullOrWhiteSpace(_config["AdminEmail"])) { await SendEmailAsync("ERROR: Error calling applicationStarted", ex.ToString(), _config["AdminEmail"].Split(';'), cancellationToken); } throw; } finally { await ((IAsyncDisposable)scope).DisposeAsync().ConfigureAwait(false); } } public async Task GoAsync(CancellationToken cancellationToken) { // https://github.com/dotnet/runtime/issues/43970 IServiceScope scope = default!; try { scope = _scopeFactory.CreateScope(); var scheduleManager = scope.ServiceProvider.GetRequiredService<IScheduleManager>(); var jobManager = scope.ServiceProvider.GetRequiredService<IJobManager>(); var schedulesToInsert = await scheduleManager.GetSchedulesToInsertAsync(cancellationToken).ConfigureAwait(false); foreach (var schedule in schedulesToInsert) { Trace.TraceInformation($"Inserting job for schedule {schedule.Schedule.ScheduleID} (Worker {schedule.Schedule.WorkerID})"); var lastQueuedJob = await jobManager.GetLastQueuedJobAsync(schedule.Schedule.ScheduleID, cancellationToken).ConfigureAwait(false); DateTime? lastQueueDate = lastQueuedJob?.QueueDateUTC; var daysOfTheWeek = new List<DayOfWeek>(); if (schedule.Schedule.Sunday) daysOfTheWeek.Add(DayOfWeek.Sunday); if (schedule.Schedule.Monday) daysOfTheWeek.Add(DayOfWeek.Monday); if (schedule.Schedule.Tuesday) daysOfTheWeek.Add(DayOfWeek.Tuesday); if (schedule.Schedule.Wednesday) daysOfTheWeek.Add(DayOfWeek.Wednesday); if (schedule.Schedule.Thursday) daysOfTheWeek.Add(DayOfWeek.Thursday); if (schedule.Schedule.Friday) daysOfTheWeek.Add(DayOfWeek.Friday); if (schedule.Schedule.Saturday) daysOfTheWeek.Add(DayOfWeek.Saturday); var newQueueDate = ScheduleFinder.GetNextDate(lastQueueDate, daysOfTheWeek.ToImmutableArray(), schedule.Schedule.TimeOfDayUTC?.AsTimeSpan(), schedule.Schedule.RecurTime?.AsTimeSpan(), schedule.Schedule.RecurBetweenStartUTC?.AsTimeSpan(), schedule.Schedule.RecurBetweenEndUTC?.AsTimeSpan()); await jobManager.AddJobAsync(schedule.Schedule.ScheduleID, newQueueDate, cancellationToken).ConfigureAwait(false); } if (_runningTasks >= 10) { return; } var items = await jobManager.DequeueScheduledJobsAsync(cancellationToken).ConfigureAwait(false); foreach (var jobDetail in items) { try { Trace.TraceInformation($"Processing job {jobDetail.Job.JobID}"); Interlocked.Increment(ref _runningTasks); var worker = new RunnerWorker(_config, jobDetail.Worker); // TODO: Auto-map this foreach (var prop in typeof(RunnerWorker).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var jobDetailProp = jobDetail.GetType().GetProperty(prop.Name)!; try { prop.SetValue(worker, jobDetailProp.GetValue(jobDetail, null), null); } catch { Debug.WriteLine($"Exception setting {prop.Name}"); throw; } } Trace.TraceInformation($"Executing job {jobDetail.Job.JobID}"); Trace.TraceInformation($"Worker={worker}"); worker.RunAsync(cancellationToken).ContinueWith(async t => { if (t.IsFaulted) { Trace.TraceInformation("IsFaulted"); await CompleteWorker(jobDetail, new WorkerResult(Success: false, t.Exception!.ToString()), cancellationToken).ConfigureAwait(false); } else if (t.IsCanceled) { Trace.TraceInformation("IsCanceled"); await CompleteWorker(jobDetail, new WorkerResult(Success: false, "Cancelled for an unknown reason"), cancellationToken).ConfigureAwait(false); } else if (t.IsCompleted) { Trace.TraceInformation("IsCompleted"); await CompleteWorker(jobDetail, t.Result, cancellationToken).ConfigureAwait(false); } else { Trace.TraceInformation("ELSE"); } }, TaskScheduler.Default).DoNotAwait(); } catch (Exception ex) { Trace.TraceError(ex.ToString()); await CompleteWorker(jobDetail, new WorkerResult(Success: false, ex.ToString()), cancellationToken).ConfigureAwait(false); } } } catch (Exception ex) { Trace.TraceError(ex.ToString()); scope.ServiceProvider.GetRequiredService<DatabaseFactory>().MarkForRollback(); } finally { await ((IAsyncDisposable)scope).DisposeAsync().ConfigureAwait(false); } } private async Task CompleteWorker(JobDetail jobDetail, WorkerResult workerResult, CancellationToken cancellationToken) { // https://github.com/dotnet/runtime/issues/43970 IServiceScope scope = default!; try { scope = _scopeFactory.CreateScope(); var jobManager = scope.ServiceProvider.GetRequiredService<IJobManager>(); Debug.WriteLine($"Completing JobID={jobDetail.Job.JobID} with success flag={workerResult.Success}"); try { await jobManager.CompleteJobAsync(jobDetail.Job.JobID, workerResult.Success, workerResult.DetailedMessage, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { Debug.WriteLine(ex); throw; } try { await SendEmailAsync(jobDetail, workerResult, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } Interlocked.Decrement(ref _runningTasks); } catch { scope.ServiceProvider.GetRequiredService<DatabaseFactory>().MarkForRollback(); } finally { await ((IAsyncDisposable)scope).DisposeAsync().ConfigureAwait(false); } } private async Task SendEmailAsync(JobDetail jobDetail, WorkerResult workerResult, CancellationToken cancellationToken) { try { HashSet<string> toAddresses = new(); if (!string.IsNullOrWhiteSpace(jobDetail.Worker.EmailOnSuccess)) { // Always send to the EmailOnSuccess group, for successes and failures foreach (string addr in (jobDetail.Worker.EmailOnSuccess ?? "").Split(';').Where(x => !string.IsNullOrWhiteSpace(x))) { toAddresses.Add(addr); } } if (!workerResult.Success) { // For failures, send to the admin foreach (string addr in _config["MailSettings:AdminEmail"].Split(';').Where(x => !string.IsNullOrWhiteSpace(x))) { toAddresses.Add(addr); } } if (!toAddresses.Any()) { return; } string subject = $"[{_config["EnvironmentName"]}] {(workerResult.Success ? "SUCCESS" : "ERROR")} - Worker: [{jobDetail.Worker.WorkerName}]"; string detailedMessage = (workerResult.DetailedMessage ?? "").Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>"); string body = $"Job ID: {jobDetail.Job.JobID}<br><br>{detailedMessage}"; string url = _config["ApplicationURL"]; while (!url.EndsWith("/")) { url = $"{url}/"; } url += $"ExecuteAction?ActionID={jobDetail.Job.AcknowledgementID:N}"; if (!workerResult.Success) { body = $"<a href='{url}' target=_blank>Acknowledge error</a><br><br>{body}"; } await SendEmailAsync(subject, body, toAddresses, cancellationToken); } catch (Exception ex) { Trace.TraceError($"Error sending email: {ex}"); } } private async Task SendEmailAsync(string subject, string htmlBody, IEnumerable<string> toAddresses, CancellationToken cancellationToken) { if (!toAddresses.Any()) { return; } Trace.TraceInformation($"Sending email to {string.Join(";", toAddresses)}"); await _emailer.SendEmailAsync(toAddresses, subject, htmlBody, cancellationToken).ConfigureAwait(false); Trace.TraceInformation("Email sent"); } } }
45.025926
156
0.528091
[ "CC0-1.0" ]
jtenos/SimpleScheduler
SimpleSchedulerService/JobExecutor.cs
12,159
C#
using System; using System.Net.Http; using Fitbit.Api.Portable; namespace Fitbit.OAuth1Migration { public static class FitbitClientOA1Factory { /// <summary> /// Private base constructor which takes it all and constructs or throws exceptions as appropriately /// </summary> /// <param name="consumerKey"></param> /// <param name="consumerSecret"></param> /// <param name="accessToken"></param> /// <param name="accessSecret"></param> /// <param name="httpClient"></param> public static FitbitClient Create(string consumerKey, string consumerSecret, string accessToken, string accessSecret, IFitbitInterceptor interceptor = null) { #region Parameter checking if (string.IsNullOrWhiteSpace(consumerKey)) { throw new ArgumentNullException(nameof(consumerKey), "ConsumerKey must not be empty or null"); } if (string.IsNullOrWhiteSpace(consumerSecret)) { throw new ArgumentNullException(nameof(consumerSecret), "ConsumerSecret must not be empty or null"); } if (string.IsNullOrWhiteSpace(accessToken)) { throw new ArgumentNullException(nameof(accessToken), "AccessToken must not be empty or null"); } if (string.IsNullOrWhiteSpace(accessSecret)) { throw new ArgumentNullException(nameof(accessSecret), "AccessSecret must not be empty or null"); } #endregion if (interceptor != null) { return new FitbitClient(mh => { //Injecting the Message Handler provided by FitbitClient library (mh) allows us to invoke any IFitbitInterceptor that has been registered return AsyncOAuth.OAuthUtility.CreateOAuthClient(mh, consumerKey, consumerSecret, new AsyncOAuth.AccessToken(accessToken, accessSecret)); }, interceptor); } else { return new FitbitClient(mh => { return AsyncOAuth.OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, new AsyncOAuth.AccessToken(accessToken, accessSecret)); }); } } } }
39.983871
164
0.568374
[ "MIT" ]
NagendraSUVCE/Fitbit.NET
OAuth1Migration/Fitbit.OAuth1Migration/FitbitClientOA1Factory.cs
2,481
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ORA.API; using ORA.API.Http; using ORA.API.Managers; using ORA.API.Network; using ORA.API.Network.Packets; using File = ORA.API.File; namespace ORA.Core.Managers { public class FileManager : IFileManager { private HashAlgorithm _hashAlgorithm; private Dictionary<string, Dictionary<string, File>> _files; public FileManager(string path) { this._hashAlgorithm = HashAlgorithm.Create("SHA1"); this._files = new Dictionary<string, Dictionary<string, File>>(); path = Path.Combine(path, "files"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); this.Discover(path, file => { if (!this._files.ContainsKey(file.Cluster)) this._files.Add(file.Cluster, new Dictionary<string, File>()); this._files[file.Cluster].Add(file.Hash, file); }); } public File[] GetOwnedFiles() => this._files.Values.SelectMany(files => files.Values).ToArray(); public File CreateFile(Cluster cluster, string realPath, string clusterPath) { if (!System.IO.File.Exists(realPath)) throw new ArgumentException("File doesn't exists"); byte[] data = System.IO.File.ReadAllBytes(realPath); string hash = this.HashToString(this._hashAlgorithm.ComputeHash(data)); if (this.GetFile(cluster, hash, false) != null) throw new ArgumentException("File already exists"); File file = new File(cluster.Identifier, clusterPath, hash, data.Length); HttpResponse response = Ora.GetHttpClient() .Post($"/clusters/{cluster.Identifier}/files", new HttpRequest(file.ToString()).Set("Authorization", "Bearer " + Ora.GetAuthManager().GetToken())); if (response.Code != 200) { Exception exception = new Exception($"Couldn't create file {clusterPath} in cluster {cluster.Identifier}"); Ora.GetLogger().Error(exception); throw exception; } this.WriteFile(file, data); Ora.GetLogger().Info($"Created file {file.Path} with hash {file.Hash} in cluster {cluster.Identifier}"); return file; } public bool RemoveFile(Cluster cluster, string hash) { HttpResponse response = Ora.GetHttpClient().Delete($"/clusters/{cluster.Identifier}/files?hash={hash}", new HttpRequest().Set("Authorization", "Bearer " + Ora.GetAuthManager().GetToken())); if (response.Code != 200) { Exception exception = new Exception($"Couldn't remove file {hash} from cluster {cluster.Identifier}"); Ora.GetLogger().Error(exception); return false; } if (this._files.ContainsKey(cluster.Identifier)) { string clusterPath = Ora.GetDirectory("files", cluster.Identifier); string filePath = Path.Combine(clusterPath, hash); this._files[cluster.Identifier].Remove(hash); System.IO.File.Delete(filePath); System.IO.File.Delete(filePath + ".info"); if (this._files[cluster.Identifier].Count == 0) { this._files.Remove(cluster.Identifier); Directory.Delete(clusterPath); } } Ora.GetLogger().Info($"Removed file {hash} from cluster {cluster.Identifier}"); return true; } public string[] GetFiles(Cluster cluster) { HttpResponse response = Ora.GetHttpClient().Get($"/clusters/{cluster.Identifier}", new HttpRequest().Set("Authorization", "Bearer " + Ora.GetAuthManager().GetToken())); int code = response.Code; if (code == 200) return JObject.Parse(response.Body)["files"].Children().Select(token => token.Value<string>()) .ToArray(); Exception exception = new Exception($"Couldn't get all files"); Ora.GetLogger().Error(exception); throw exception; } public File GetFile(Cluster cluster, string hash) => this.GetFile(cluster, hash, true); public File GetFile(Cluster cluster, string hash, bool shouldError) { if (!this._files.ContainsKey(cluster.Identifier)) this._files.Add(cluster.Identifier, new Dictionary<string, File>()); if (this._files[cluster.Identifier].ContainsKey(hash)) return this._files[cluster.Identifier][hash]; if (!shouldError) return null; HttpResponse response = Ora.GetHttpClient().Get($"/clusters/{cluster.Identifier}/files?hash={hash}", new HttpRequest().Set("Authorization", "Bearer " + Ora.GetAuthManager().GetToken())); if (response.Code != 200) { Exception exception = new Exception($"Couldn't get file {hash} in cluster {cluster.Identifier}"); Ora.GetLogger().Error(exception); throw exception; } JObject json = JObject.Parse(response.Body); string owner = null; foreach (JToken jToken in json["owners"].Children()) { if (!jToken["id"].Value<string>().Equals(Ora.GetIdentityManager().GetIdentity().GetIdentifier())) { owner = jToken["ip"].Value<string>(); break; } } if (String.IsNullOrEmpty(owner)) { Exception exception = new Exception($"Couldn't get file {hash} in cluster {cluster.Identifier}"); Ora.GetLogger().Error(exception); throw exception; } FilePacket filePacket = (FilePacket) Ora.GetNetworkManager() .SendPacket(owner, 5000, new RequestFilePacket(cluster.Identifier, hash)); File file = new File(cluster.Identifier, json["path"].Value<string>(), hash, json["size"].Value<long>()); this.WriteFile(file, filePacket.Content); Ora.GetHttpClient().Post($"/clusters/{cluster}/files/owned", new HttpRequest($"[\"{file.Hash}\"]").Set("Authorization", "Bearer " + Ora.GetAuthManager().GetToken())); return file; } public byte[] GetFileContent(Cluster cluster, File file) => System.IO.File.ReadAllBytes(Ora.GetDirectory("files", cluster.Identifier, file.Hash)); public byte[] GetFileContent(Cluster cluster, string hash) => System.IO.File.ReadAllBytes(Ora.GetDirectory("files", cluster.Identifier, hash)); private string HashToString(byte[] hash) => String.Concat(hash.Select(b => b.ToString("x2"))); private void WriteFile(File file, byte[] content) { string oraPath = Ora.GetDirectory("files", file.Cluster); if (!Directory.Exists(oraPath)) Directory.CreateDirectory(oraPath); oraPath = Path.Combine(oraPath, file.Hash); System.IO.File.Create(oraPath).Close(); System.IO.File.WriteAllBytes(oraPath, content); System.IO.File.Create(oraPath + ".info").Close(); System.IO.File.WriteAllText(oraPath + ".info", file.Path + Environment.NewLine + file.Size); if (!this._files.ContainsKey(file.Cluster)) this._files.Add(file.Cluster, new Dictionary<string, File>()); this._files[file.Cluster].Add(file.Hash, file); } private void Discover(string path, Action<File> action) { foreach (string file in Directory.EnumerateFiles(path, "*.info")) { string fileName = Path.GetFileName(file); string[] content = System.IO.File.ReadAllText(file).Split(Environment.NewLine); string hash = fileName.Substring(0, fileName.Length - 5); string oraPath = content[0]; long length = Int64.Parse(content[1]); action(new File(Path.GetFileName(path), oraPath, hash, length)); } foreach (string directory in Directory.EnumerateDirectories(path)) this.Discover(directory, action); } } }
42.665072
121
0.564652
[ "MIT" ]
Crab-Wave/ora
ORA.Core/Managers/FileManager.cs
8,711
C#
using System; using System.Collections.ObjectModel; using Prism.Mvvm; using Reactive.Bindings; using Reactive.Bindings.Extensions; using MVVM_Refregator.Model; using LiveCharts; using LiveCharts.Wpf; using System.Collections.Generic; using System.Linq; namespace MVVM_Refregator.ViewModel { /// <summary> /// AnalysisページのViewModel /// </summary> public class AnalysisPageViewModel : BindableBase { /// <summary> /// 解析用オブジェクト /// </summary> private AnalysisPageModel _analysisPageModel = AnalysisPageModel.GetInstance(); /// <summary> /// 全食材コレクション /// </summary> public ReadOnlyReactiveCollection<FoodModel> Foods { get; } /// <summary> /// 計算後の成分表 /// </summary> public ReactiveProperty<FoodComposition> CalculateFoodComposition { get; } /// <summary> /// 食品成分表のコレクション /// </summary> public ObservableCollection<FoodComposition> FoodCompositions { get; } //public SeriesCollection SeriesCollection { get; private set; } = new SeriesCollection(); private SeriesCollection _seriesCollection = new SeriesCollection(); public SeriesCollection SeriesCollection { get { return this._seriesCollection; } private set { this.SetProperty(ref this._seriesCollection, value); } } public ObservableCollection<string> Labels { get; private set; } public Dictionary<string, ObservableCollection<Nutrient>> NutrientGroup { get; private set; } public Dictionary<string, ObservableCollection<string>> LabelGroup { get; } public ObservableCollection<string> ComboBoxGroup { get; } public ReactiveProperty<string> SelectedText { get; } = new ReactiveProperty<string>("エネルギー"); public Func<double, string> Formatter { get; } = val => val.ToString("0.###"); public ReactiveProperty<string> UnitText { get; private set; } = new ReactiveProperty<string>("kcal"); private List<string> _keyList = new List<string>(); /// <summary> /// 解析用コレクションに追加 /// </summary> public ReactiveCommand Send_AddAnalysisFood { get; } = new ReactiveCommand(); /// <summary> /// ctor /// </summary> public AnalysisPageViewModel() { // Modelのコレクションの初期化 this._analysisPageModel.InitFoodCollection(); this.Foods = this._analysisPageModel.AllFoods .ToReadOnlyReactiveCollection(_analysisPageModel.AllFoods.ToCollectionChanged(), System.Reactive.Concurrency.Scheduler.CurrentThread); this.CalculateFoodComposition = this._analysisPageModel.ToReactivePropertyAsSynchronized(x => x.CalculatedResultFoodComposition, convert => convert, convertBack => convertBack, ReactivePropertyMode.DistinctUntilChanged | ReactivePropertyMode.RaiseLatestValueOnSubscribe, false); this.SeriesCollection = new SeriesCollection { new ColumnSeries { Title = "栄養素", Values = new ChartValues<double> { this.CalculateFoodComposition.Value.FattyAcid_Saturated.Value, this.CalculateFoodComposition.Value.FattyAcid_PolyUnsaturated.Value, this.CalculateFoodComposition.Value.FattyAcid_MonoUnsaturated.Value, this.CalculateFoodComposition.Value.Energy_kcal.Value }, }, }; this.Labels = new ObservableCollection<string>() { "飽和脂肪酸", "多価不飽和脂肪酸", "一価不和飽和脂肪酸", "エネルギー(kcal)" }; this._keyList = new List<string> { "エネルギー", "水分", "タンパク質", "脂質", "脂肪酸", "コレステロール", "炭水化物", "食物繊維", "灰分", "無機質その1", "無機質その2", "無機質その3", "無機質その4", "ビタミンその1", "ビタミンその2", "ビタミンその3", "ビタミンその4", "ビタミンその5", "ビタミンその6", "廃棄率", }; this.ComboBoxGroup = new ObservableCollection<string>() { this._keyList[0], this._keyList[1], this._keyList[2], this._keyList[3], this._keyList[4], this._keyList[5], this._keyList[6], this._keyList[7], this._keyList[8], this._keyList[9], this._keyList[10], this._keyList[11], this._keyList[12], this._keyList[13], this._keyList[14], this._keyList[15], this._keyList[16], this._keyList[17], this._keyList[18],this._keyList[19] }; this.NutrientGroup = new Dictionary<string, ObservableCollection<Nutrient>> { //{this._keyList[0], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Energy_kcal, this.CalculateFoodComposition.Value.Energy_kj } }, {this._keyList[0], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Energy_kcal, } }, {this._keyList[1], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Water, } }, {this._keyList[2], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Protein, this.CalculateFoodComposition.Value.Protein_AminoAcidResidues } }, {this._keyList[3], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Lipid, this.CalculateFoodComposition.Value.FattyAcid_TriacylGlycerol } }, {this._keyList[4], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.FattyAcid_Saturated, this.CalculateFoodComposition.Value.FattyAcid_MonoUnsaturated, this.CalculateFoodComposition.Value.FattyAcid_PolyUnsaturated } }, {this._keyList[5], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Cholesterol} }, {this._keyList[6], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Carbohydrate, this.CalculateFoodComposition.Value.Carbohydrate_Available } }, {this._keyList[7], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.DietaryFiber_Soluble, this.CalculateFoodComposition.Value.DietaryFiber_Insoluble, this.CalculateFoodComposition.Value.DietaryFiber_Total } }, {this._keyList[8], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Ash } }, {this._keyList[9], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Sodium, this.CalculateFoodComposition.Value.Potassium, this.CalculateFoodComposition.Value.Calcium, this.CalculateFoodComposition.Value.Magnesium, } }, {this._keyList[10], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Phosphorus, this.CalculateFoodComposition.Value.Iron, this.CalculateFoodComposition.Value.Zinc, this.CalculateFoodComposition.Value.Copper, } }, {this._keyList[11], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Manganese, this.CalculateFoodComposition.Value.Iodine, this.CalculateFoodComposition.Value.Selenium, this.CalculateFoodComposition.Value.Chromium, } }, {this._keyList[12], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Molybdenum} }, {this._keyList[13], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Retinol, this.CalculateFoodComposition.Value.Alpha_Carotene, this.CalculateFoodComposition.Value.Beta_Carotene, this.CalculateFoodComposition.Value.Beta_Cryptoxanthin, } }, {this._keyList[14], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Beta_CaroteneEquivalents, this.CalculateFoodComposition.Value.Retinon_ActivityEquivalents, this.CalculateFoodComposition.Value.Vitamin_D, this.CalculateFoodComposition.Value.Alpha_Tocopherol, } }, {this._keyList[15], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Beta_Tocopherol, this.CalculateFoodComposition.Value.Gamma_Tocopherol, this.CalculateFoodComposition.Value.Delta_Tocopherol, this.CalculateFoodComposition.Value.Vitamin_K, } }, {this._keyList[16], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Thiamin, this.CalculateFoodComposition.Value.Riboflavin, this.CalculateFoodComposition.Value.Niacin, this.CalculateFoodComposition.Value.Vitamin_B6, } }, {this._keyList[17], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Vitamin_B12, this.CalculateFoodComposition.Value.Folate, this.CalculateFoodComposition.Value.Pantothenic_Acid, this.CalculateFoodComposition.Value.Biotin, } }, {this._keyList[18], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Ascorbic_Acid } }, {this._keyList[19], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Refuse } }, }; this.LabelGroup = new Dictionary<string, ObservableCollection<string>> { //{this._keyList[0], new ObservableCollection<string>(){"エネルギー(kcal)", "エネルギー(kJ)"} }, {this._keyList[0], new ObservableCollection<string>(){"エネルギー(kcal)", } }, {this._keyList[1], new ObservableCollection<string>(){"水分"} }, {this._keyList[2], new ObservableCollection<string>(){"タンパク質", "アミノ酸組成によるタンパク質"} }, {this._keyList[3], new ObservableCollection<string>(){"脂質", "トリアシルグリセロール当量" } }, {this._keyList[4], new ObservableCollection<string>(){"脂肪酸(飽和)", "脂肪酸(一価不飽和)", "脂肪酸(多価不飽和)",} }, {this._keyList[5], new ObservableCollection<string>(){ "コレステロール", } }, {this._keyList[6], new ObservableCollection<string>(){ "炭水化物", "利用可能炭水化物"} }, {this._keyList[7], new ObservableCollection<string>(){ "食物繊維(水溶性)", "食物繊維(不溶性)","食物繊維(総量)"} }, {this._keyList[8], new ObservableCollection<string>(){ "灰分", } }, {this._keyList[9], new ObservableCollection<string>(){ "ナトリウム", "カリウム", "カルシウム", "マグネシウム", } }, {this._keyList[10], new ObservableCollection<string>(){ "リン", "鉄", "亜鉛", "銅", } }, {this._keyList[11], new ObservableCollection<string>(){ "マンガン", "ヨウ素", "セレン", "クロム",} }, {this._keyList[12], new ObservableCollection<string>(){ "モリブデン"} }, {this._keyList[13], new ObservableCollection<string>(){ "レチノール", "α-カロテン", "β-カロテン", "β-クリプトサチン", } }, {this._keyList[14], new ObservableCollection<string>(){ "β-カロテン当量", "レチノール活性当量","ビタミンD", "α-トコフェロール", } }, {this._keyList[15], new ObservableCollection<string>(){ "β-トコフェロール", "γ-トコフェロール", "δ-トコフェロール","ビタミンK", } }, {this._keyList[16], new ObservableCollection<string>(){ "ビタミンB1", "ビタミンB2", "ナイアシン", "ビタミンB6",} }, {this._keyList[17], new ObservableCollection<string>(){ "ビタミンB12", "葉酸", "パントテン酸", "ビオチン", } }, {this._keyList[18], new ObservableCollection<string>(){ "ビタミンC"} }, {this._keyList[19], new ObservableCollection<string>(){"廃棄率"} }, }; this.SelectedText.Subscribe((string x) => { //var seriesGroup = this.NutrientGroup[x].Select(y => y.Value).ToList(); var seriesGroup = this.NutrientGroup[x].Select(y => { if (y.UnitKind == UnitKind.mg || y.UnitKind == UnitKind.micro_g) return y.ConvertValue(UnitKind.g); else if (y.UnitKind == UnitKind.kj) return y.ConvertValue(UnitKind.kcal); else return y.Value; }).ToList(); switch (this.NutrientGroup[x].First().UnitKind) { case UnitKind.kcal: case UnitKind.kj: this.UnitText.Value = "kcal"; break; case UnitKind.g: case UnitKind.mg: case UnitKind.micro_g: this.UnitText.Value = "g"; break; case UnitKind.percent: this.UnitText.Value = "%"; break; case UnitKind.Undefine: default: this.UnitText.Value = "-"; break; } var labels = this.LabelGroup[x]; this.Labels = labels; this.RaisePropertyChanged(nameof(this.Labels)); if (this.SeriesCollection?.Chart != null) { this.SeriesCollection?.Clear(); this.SeriesCollection?.Add(new ColumnSeries() { Title = labels[0] == "廃棄率" ? "廃棄率" : "栄養価", Values = new ChartValues<double>(seriesGroup) }); var foo = SeriesCollection.First(); } else { this.SeriesCollection = new SeriesCollection { new ColumnSeries { Title = labels[0] == "廃棄率" ? "廃棄率" : "栄養価", Values = new ChartValues<double>(seriesGroup), } }; } this.RaisePropertyChanged(nameof(SeriesCollection)); }); } public void CalcComposition(DateTime date) { this._analysisPageModel.CalculateComposition(date); this.RaisePropertyChanged(nameof(this.CalculateFoodComposition)); this.UpdateNutrientGroup(); var keyText = this.SelectedText.Value; var seriesGroup = this.NutrientGroup[keyText].Select(y => y.Value).ToList(); if (this.SeriesCollection?.Chart != null) { this.SeriesCollection?.Clear(); this.SeriesCollection?.Add(new ColumnSeries { Title = keyText == "廃棄率" ? "廃棄率" : "栄養価" }); this.SeriesCollection[0].Values = new ChartValues<double>(seriesGroup); this.RaisePropertyChanged(nameof(this.SeriesCollection)); } } private void UpdateNutrientGroup() { this.NutrientGroup = new Dictionary<string, ObservableCollection<Nutrient>> { //{this._keyList[0], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Energy_kcal, this.CalculateFoodComposition.Value.Energy_kj } }, {this._keyList[0], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Energy_kcal, } }, {this._keyList[1], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Water, } }, {this._keyList[2], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Protein, this.CalculateFoodComposition.Value.Protein_AminoAcidResidues } }, {this._keyList[3], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Lipid, this.CalculateFoodComposition.Value.FattyAcid_TriacylGlycerol } }, {this._keyList[4], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.FattyAcid_Saturated, this.CalculateFoodComposition.Value.FattyAcid_MonoUnsaturated, this.CalculateFoodComposition.Value.FattyAcid_PolyUnsaturated } }, {this._keyList[5], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Cholesterol} }, {this._keyList[6], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Carbohydrate, this.CalculateFoodComposition.Value.Carbohydrate_Available } }, {this._keyList[7], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.DietaryFiber_Soluble, this.CalculateFoodComposition.Value.DietaryFiber_Insoluble, this.CalculateFoodComposition.Value.DietaryFiber_Total } }, {this._keyList[8], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Ash } }, {this._keyList[9], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Sodium, this.CalculateFoodComposition.Value.Potassium, this.CalculateFoodComposition.Value.Calcium, this.CalculateFoodComposition.Value.Magnesium, } }, {this._keyList[10], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Phosphorus, this.CalculateFoodComposition.Value.Iron, this.CalculateFoodComposition.Value.Zinc, this.CalculateFoodComposition.Value.Copper, } }, {this._keyList[11], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Manganese, this.CalculateFoodComposition.Value.Iodine, this.CalculateFoodComposition.Value.Selenium, this.CalculateFoodComposition.Value.Chromium, } }, {this._keyList[12], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Molybdenum} }, {this._keyList[13], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Retinol, this.CalculateFoodComposition.Value.Alpha_Carotene, this.CalculateFoodComposition.Value.Beta_Carotene, this.CalculateFoodComposition.Value.Beta_Cryptoxanthin, } }, {this._keyList[14], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Beta_CaroteneEquivalents, this.CalculateFoodComposition.Value.Retinon_ActivityEquivalents, this.CalculateFoodComposition.Value.Vitamin_D, this.CalculateFoodComposition.Value.Alpha_Tocopherol, } }, {this._keyList[15], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Beta_Tocopherol, this.CalculateFoodComposition.Value.Gamma_Tocopherol, this.CalculateFoodComposition.Value.Delta_Tocopherol, this.CalculateFoodComposition.Value.Vitamin_K, } }, {this._keyList[16], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Thiamin, this.CalculateFoodComposition.Value.Riboflavin, this.CalculateFoodComposition.Value.Niacin, this.CalculateFoodComposition.Value.Vitamin_B6, } }, {this._keyList[17], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Vitamin_B12, this.CalculateFoodComposition.Value.Folate, this.CalculateFoodComposition.Value.Pantothenic_Acid, this.CalculateFoodComposition.Value.Biotin, } }, {this._keyList[18], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Ascorbic_Acid } }, {this._keyList[19], new ObservableCollection<Nutrient>(){ this.CalculateFoodComposition.Value.Refuse } }, }; System.Diagnostics.Debug.WriteLine($"変更後のコレステロール:{this.CalculateFoodComposition.Value.Cholesterol}"); } } }
69.985401
307
0.645703
[ "MIT" ]
Pregum/Refregator
ViewModel/AnalysisPageViewModel.cs
20,184
C#
//------------------------------------------------------------------------------ // <copyright file="IErrorHelper.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">antonl</owner> //------------------------------------------------------------------------------ namespace System.Xml.Xsl { internal interface IErrorHelper { void ReportError(string res, params string[] args); void ReportWarning(string res, params string[] args); } }
32.705882
80
0.483813
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/XmlUtils/System/Xml/Xsl/Xslt/IErrorHelper.cs
556
C#
#region Usings using System; using System.Linq; using FpML.V5r10.Reporting.Helpers; using Orion.CalendarEngine.Helpers; using Orion.Constants; using FpML.V5r10.Reporting; //using FpML.V5r3.Reporting.Extensions; using FpML.V5r10.Reporting.Models.Rates; using FpML.V5r10.Reporting.Models.Rates.Coupons; using FpML.V5r10.Reporting.ModelFramework; using FpML.V5r10.Reporting.ModelFramework.Instruments; using FpML.V5r10.Reporting.ModelFramework.MarketEnvironments; using FpML.V5r10.Reporting.ModelFramework.PricingStructures; using Orion.CurveEngine.Helpers; #endregion namespace Orion.ValuationEngine.Instruments { [Serializable] public class PriceableCapFloorCoupon : PriceableFloatingRateCoupon { #region Member Fields #endregion #region Public Fields public string VolatilitySurfaceName { get; set; } public decimal TimeToExpiry { get; set; } public bool IsCall { get; set; } public Decimal? CapStrike {get; set;} public Decimal? FloorStrike { get; set; } #endregion #region Constructors /// <summary> /// The defualt type is a cap. /// </summary> public PriceableCapFloorCoupon() { PriceableCouponType = CouponType.Cap; ModelIdentifier = "DualCurveOptionModel"; IsCall = true; } /// <summary> /// Initializes a new instance of the <see cref="PriceableCapFloorCoupon"/> class. /// </summary> /// <param name="cashlfowId">The stream id.</param> /// <param name="buyerIsBase">The buyer is base flag.</param> /// <param name="capStrike">The Cap strike.</param> /// <param name="floorStrike">The floor strike.</param> /// <param name="accrualStartDate">The accrual start date. If adjusted, the adjustCalculationDatesIndicator should be false.</param> /// <param name="accrualEndDate">The accrual end date. If adjusted, the adjustCalculationDatesIndicator should be false.</param> /// <param name="margin">The margin.</param> /// <param name="observedRate">The observed Rate. If this is not null, then it is used.</param> /// <param name="notionalAmount">The notional amount.</param> /// <param name="adjustedFixingDate">The adjusted fixing date.</param> /// <param name="dayCountfraction">Type of day Countfraction.</param> /// <param name="paymentDate">The payment date.</param> /// <param name="forecastRateIndex">The forecastrate index.</param> /// <param name="discountingType">The swap discounting type.</param> /// <param name="discountRate">The discount rate.</param> /// <param name="fraDiscounting">Determines whether the coupon is discounted or not. If this parameter is null, /// then it is assumed that there is no fradiscounting</param> /// <param name="fixingCalendar"> The fixingCalendar. </param> /// <param name="paymentCalendar"> The paymentCalendar. </param> public PriceableCapFloorCoupon ( string cashlfowId , bool buyerIsBase , decimal? capStrike , decimal? floorStrike , DateTime accrualStartDate , DateTime accrualEndDate , DateTime adjustedFixingDate , DayCountFraction dayCountfraction , Decimal margin , Decimal? observedRate , Money notionalAmount , DateTime paymentDate , ForecastRateIndex forecastRateIndex , DiscountingTypeEnum? discountingType , Decimal? discountRate , FraDiscountingEnum? fraDiscounting , IBusinessCalendar fixingCalendar , IBusinessCalendar paymentCalendar) : base( cashlfowId , buyerIsBase , accrualStartDate , accrualEndDate , adjustedFixingDate , dayCountfraction , margin , observedRate , notionalAmount , paymentDate , forecastRateIndex , discountingType , discountRate , fraDiscounting , fixingCalendar , paymentCalendar) { CapStrike = capStrike; FloorStrike = floorStrike; VolatilitySurfaceName = CurveNameHelpers.GetRateVolatilityMatrixName(forecastRateIndex); if (capStrike != null && floorStrike == null) { PriceableCouponType = CouponType.Cap; ModelIdentifier = "DualCurveCapModel"; IsCall = true; } if (floorStrike != null && capStrike == null) { PriceableCouponType = CouponType.Floor; ModelIdentifier = "DualCurveFloorModel"; } if (floorStrike != null && capStrike != null) { PriceableCouponType = CouponType.Collar; ModelIdentifier = "DualCurveCollarModel"; } } /// <summary> /// Initializes a new instance of the <see cref="PriceableCapFloorCoupon"/> class. /// </summary> /// <param name="cashlfowId">The stream id.</param> /// <param name="buyerIsBase">The buyer is base flag.</param> /// <param name="capStrike">The Cap strike.</param> /// <param name="floorStrike">The floor strike.</param> /// <param name="accrualStartDate">The accrual start date. If adjusted, the adjustCalculationDatesIndicator should be false.</param> /// <param name="accrualEndDate">The accrual end date. If adjusted, the adjustCalculationDatesIndicator should be false.</param> /// <param name="adjustAccrualDatesIndicator">if set to <c>true</c> [adjust calculation dates indicator].</param> /// <param name="accrualBusinessCenters">The accrual business centers.</param> /// <param name="margin">The margin.</param> /// <param name="observedRate">The observed Rate.</param> /// <param name="notionalAmount">The notional amount.</param> /// <param name="dayCountfraction">Type of day Countfraction.</param> /// <param name="paymentDate">The payment date.</param> /// <param name="accrualRollConvention">The accrual roll convention.</param> /// <param name="resetRelativeTo">reset relative to?</param> /// <param name="fixingDateRelativeOffset">The fixing date offset.</param> /// <param name="forecastRateIndex">The forecastrateindex.</param> /// <param name="discountingType">The swap discounting type.</param> /// <param name="discountRate">The discount rate.</param> /// <param name="fraDiscounting">Determines whether the coupon is discounted or not. If this parameter is null, /// then it is assumed that there is no fradiscounting</param> /// <param name="fixingCalendar">The fixingCalendar.</param> /// <param name="paymentCalendar">The paymentCalendar.</param> public PriceableCapFloorCoupon ( string cashlfowId , bool buyerIsBase , decimal? capStrike , decimal? floorStrike , DateTime accrualStartDate , DateTime accrualEndDate , Boolean adjustAccrualDatesIndicator , BusinessCenters accrualBusinessCenters , BusinessDayConventionEnum accrualRollConvention , DayCountFraction dayCountfraction , ResetRelativeToEnum resetRelativeTo , RelativeDateOffset fixingDateRelativeOffset , Decimal margin , Decimal? observedRate , Money notionalAmount , AdjustableOrAdjustedDate paymentDate , ForecastRateIndex forecastRateIndex , DiscountingTypeEnum? discountingType , Decimal? discountRate , FraDiscountingEnum? fraDiscounting , IBusinessCalendar fixingCalendar , IBusinessCalendar paymentCalendar) : base( cashlfowId , buyerIsBase , accrualStartDate , accrualEndDate , adjustAccrualDatesIndicator , accrualBusinessCenters , accrualRollConvention , dayCountfraction , resetRelativeTo , fixingDateRelativeOffset , margin , observedRate , notionalAmount , paymentDate , forecastRateIndex , discountingType , discountRate , fraDiscounting , fixingCalendar , paymentCalendar) { CapStrike = capStrike; FloorStrike = floorStrike; VolatilitySurfaceName = CurveNameHelpers.GetRateVolatilityMatrixName(forecastRateIndex); if (capStrike != null && floorStrike == null) { PriceableCouponType = CouponType.Cap; ModelIdentifier = "DualCurveCapModel"; IsCall = true; } if (floorStrike != null && capStrike == null) { PriceableCouponType = CouponType.Floor; ModelIdentifier = "DualCurveFloorModel"; } if (floorStrike != null && capStrike != null) { PriceableCouponType = CouponType.Collar; ModelIdentifier = "DualCurveCollarModel"; } } /// <summary> /// Initializes a new instance of the <see cref="PriceableCapFloorCoupon"/> class. /// </summary> /// <param name="uniqueId"></param> /// <param name="buyerIsBase">The buyer is base flag.</param> /// <param name="capStrike">The Cap strike.</param> /// <param name="floorStrike">The floor strike.</param> /// <param name="accrualStartDate"></param> /// <param name="accrualEndDate"></param> /// <param name="adjustCalculationDatesIndicator"></param> /// <param name="paymentDate"></param> /// <param name="notionalAmount"></param> /// <param name="resetRelativeTo"></param> /// <param name="fixingDateRelativeOffset"></param> /// <param name="margin"></param> /// <param name="calculation"></param> /// <param name="forecastRateIndex"></param> /// <param name="fixingCalendar"></param> /// <param name="paymentCalendar"></param> public PriceableCapFloorCoupon (string uniqueId , bool buyerIsBase , decimal? capStrike , decimal? floorStrike , DateTime accrualStartDate , DateTime accrualEndDate , Boolean adjustCalculationDatesIndicator , AdjustableOrAdjustedDate paymentDate , Money notionalAmount , ResetRelativeToEnum resetRelativeTo , RelativeDateOffset fixingDateRelativeOffset , Decimal margin , Calculation calculation , ForecastRateIndex forecastRateIndex , IBusinessCalendar fixingCalendar , IBusinessCalendar paymentCalendar) : base (uniqueId , buyerIsBase , accrualStartDate , accrualEndDate , adjustCalculationDatesIndicator , paymentDate , notionalAmount , resetRelativeTo , fixingDateRelativeOffset , margin , calculation , forecastRateIndex , fixingCalendar , paymentCalendar) { CapStrike = capStrike; FloorStrike = floorStrike; VolatilitySurfaceName = CurveNameHelpers.GetRateVolatilityMatrixName(forecastRateIndex); if (capStrike != null && floorStrike == null) { PriceableCouponType = CouponType.Cap; ModelIdentifier = "DualCurveCapModel"; IsCall = true; } if (floorStrike != null && capStrike == null) { PriceableCouponType = CouponType.Floor; ModelIdentifier = "DualCurveFloorModel"; } if (floorStrike != null && capStrike != null) { PriceableCouponType = CouponType.Collar; ModelIdentifier = "DualCurveCollarModel"; } } #endregion #region Metrics for Valuation /// <summary> /// Calculates the specified model data. /// </summary> /// <param name="modelData">The model data.</param> /// <returns></returns> public override AssetValuation Calculate(IInstrumentControllerData modelData) { ModelData = modelData; AnalyticModelParameters = null; AnalyticsModel = new RateOptionCouponAnalytic(); RequiresReset = modelData.ValuationDate > ResetDate; IsRealised = HasBeenRealised(ModelData.ValuationDate); TimeToExpiry = GetPaymentYearFraction(ModelData.ValuationDate, AdjustedFixingDate); var volatilityCurveNodeTime = GetPaymentYearFraction(ModelData.ValuationDate, AccrualStartDate); IFxCurve fxCurve = null; IRateCurve discountCurve = null; IRateCurve forecastCurve = null; IVolatilitySurface indexVolSurface = null; //Add the extra metrics required var quotes = ModelData.AssetValuation.quote.ToList(); if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.BreakEvenRate.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.BreakEvenRate.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.AccrualFactor.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.AccrualFactor.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.FloatingNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.FloatingNPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.NPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyNPV.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyNPV.ToString(), "DecimalValue"); quotes.Add(quote); } if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyExpectedValue.ToString()) == null) { var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue"); quotes.Add(quote); } //Check if risk calc are required. bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null; //Check if risk calc are required. bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null || AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null; ModelData.AssetValuation.quote = quotes.ToArray(); var metrics = ResolveModelMetrics(AnalyticsModel.Metrics); //// Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored //if (metrics.Contains(InstrumentMetrics.DiscountFactorAtMaturity)) //{ // metrics.RemoveAll(metricItem => metricItem != InstrumentMetrics.DiscountFactorAtMaturity); //} //Set the forrecast rate dates. The ForecastRateInterpolation shhould have been set. ForwardStartDate = AccrualStartDate; ForwardEndDate = ForecastRateInterpolation ? AccrualEndDate : AdjustedDateHelper.ToAdjustedDate(FixingCalendar, ForecastRateIndex.indexTenor.Add(ForwardStartDate), AccrualBusinessDayAdjustments); //Set the strike var strike1 = 0.0m; var strike2 = 0.0m; var isCollar = false; if(PriceableCouponType == CouponType.Cap) { if (CapStrike != null) strike1 = (decimal)CapStrike; } if (PriceableCouponType == CouponType.Floor) { if (FloorStrike != null) strike1 = (decimal)FloorStrike; } if (PriceableCouponType == CouponType.Collar)//TODO Need to add the Floor calculation which will require a new model or extension of the current model. { if (CapStrike != null) strike1 = (decimal)CapStrike; if (FloorStrike != null) strike2 = (decimal)FloorStrike; isCollar = true; } //var metricsToEvaluate = metrics.ToArray(); if (metrics.Count > 0) { YearFractionToCashFlowPayment = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate); var reportingCurrency = ModelData.ReportingCurrency == null ? PaymentCurrency.Value : ModelData.ReportingCurrency.Value; IRateCouponParameters analyticModelParameters = new RateCouponParameters { Multiplier = Multiplier, ValuationDate = modelData.ValuationDate, PaymentDate = PaymentDate, Currency = PaymentCurrency.Value, ReportingCurrency = reportingCurrency, DiscountType = DiscountType, IsRealised = IsRealised, HasReset = RequiresReset, NotionalAmount = NotionalAmount.amount, Spread = Margin, YearFraction = CouponYearFraction, CurveYearFraction = YearFractionToCashFlowPayment, ExpiryYearFraction = TimeToExpiry, IsCall = IsCall }; // Curve Related var environment = modelData.MarketEnvironment as ISwapLegEnvironment; if (environment != null) { var streamMarket = environment; discountCurve = streamMarket.GetDiscountRateCurve(); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; forecastCurve = streamMarket.GetForecastRateCurve(); forecastCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; indexVolSurface = streamMarket.GetVolatilitySurface(); indexVolSurface.PricingStructureEvolutionType = PricingStructureEvolutionType; DiscountCurveName = discountCurve.GetPricingStructureId().UniqueIdentifier; ForecastCurveName = forecastCurve.GetPricingStructureId().UniqueIdentifier; VolatilitySurfaceName = indexVolSurface.GetPricingStructureId().UniqueIdentifier; // Bucketed Delta if (BucketedDates.Length > 1) { analyticModelParameters.PeriodAsTimesPerYear = GetPaymentYearFraction(BucketedDates[0], BucketedDates[1]); analyticModelParameters.BucketedDiscountFactors = GetBucketedDiscountFactors(discountCurve, ModelData. ValuationDate, BucketedDates); } //Check for currency. if (ModelData.ReportingCurrency != null) { if (ModelData.ReportingCurrency.Value != PaymentCurrency.Value) { fxCurve = streamMarket.GetReportingCurrencyFxCurve(); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; } } } else if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment)) { var market = (MarketEnvironment)modelData.MarketEnvironment; discountCurve = (IRateCurve)market.SearchForPricingStructureType(DiscountCurveName); discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; forecastCurve = (IRateCurve)market.SearchForPricingStructureType(ForecastCurveName); forecastCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; indexVolSurface = (IVolatilitySurface)market.SearchForPricingStructureType(VolatilitySurfaceName); indexVolSurface.PricingStructureEvolutionType = PricingStructureEvolutionType; if (!UseObservedRate) { Rate = GetRate(ForwardStartDate, ForwardEndDate, forecastCurve, ModelData.ValuationDate); } //the rate params analyticModelParameters.Rate = GetRate(ForwardStartDate, ForwardEndDate, forecastCurve, ModelData.ValuationDate); // Bucketed Delta if (BucketedDates.Length > 1) { analyticModelParameters.PeriodAsTimesPerYear = GetPaymentYearFraction(BucketedDates[0], BucketedDates[1]); analyticModelParameters.BucketedDiscountFactors = GetBucketedDiscountFactors(discountCurve, ModelData. ValuationDate, BucketedDates); } if (delta1PDH) { var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta1PDH"); analyticModelParameters.Delta1PDHCurves = riskMarket; analyticModelParameters.Delta1PDHPerturbation = 10; } if (delta0PDH) { var riskMarket = market.SearchForPerturbedPricingStructures(ForecastCurveName, "delta0PDH"); analyticModelParameters.Delta0PDHCurves = riskMarket; analyticModelParameters.Delta0PDHPerturbation = 10; } //Check for currency. if (ModelData.ReportingCurrency != null) { if (ModelData.ReportingCurrency.Value != PaymentCurrency.Value) { string curveName = MarketEnvironmentHelper.ResolveFxCurveNames(PaymentCurrency.Value, modelData.ReportingCurrency.Value); fxCurve = (IFxCurve)market.SearchForPricingStructureType(curveName); fxCurve.PricingStructureEvolutionType = PricingStructureEvolutionType; } } } analyticModelParameters.DiscountCurve = discountCurve; analyticModelParameters.ForecastCurve = forecastCurve; analyticModelParameters.VolatilitySurface = indexVolSurface; analyticModelParameters.ReportingCurrencyFxCurve = fxCurve; AnalyticModelParameters = analyticModelParameters; //Set the base rate. Default is zero if (AnalyticModelParameters != null) AnalyticModelParameters.BaseRate = BaseRate; if (UseObservedRate) { AnalyticsModel = new FixedRateCouponAnalytic(ModelData.ValuationDate, AccrualStartDate, AccrualEndDate, PaymentDate, Rate, analyticModelParameters.YearFraction, DiscountType, fxCurve, discountCurve, forecastCurve); if (Rate != null) analyticModelParameters.Rate = (decimal)Rate; } if (!isCollar) { AnalyticsModel = new RateOptionCouponAnalytic(ModelData.ValuationDate, AccrualStartDate, AccrualEndDate, PaymentDate, volatilityCurveNodeTime, strike1, fxCurve, discountCurve, forecastCurve, indexVolSurface); } else { AnalyticsModel = new RateOptionCouponAnalytic(ModelData.ValuationDate, AccrualStartDate, AccrualEndDate, PaymentDate, volatilityCurveNodeTime, strike1, strike2, fxCurve, discountCurve, forecastCurve, indexVolSurface); } CalculationResults = AnalyticsModel.Calculate<IRateInstrumentResults, RateInstrumentResults>(AnalyticModelParameters, metrics.ToArray()); CalculationPerfomedIndicator = true; PaymentDiscountFactor = ((FixedRateCouponAnalytic)AnalyticsModel).PaymentDiscountFactor; if (!UseObservedRate) { Rate = CalculationResults.BreakEvenRate; } ForecastAmount = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyExpectedValue, PaymentAmount.currency); NPV = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyNPV, PaymentAmount.currency); } AssetValuation valuation = GetValue(CalculationResults, modelData.ValuationDate); valuation.id = Id; return valuation; } /// <summary> /// Builds the product with the calculated data. /// </summary> /// <returns></returns> public override Product BuildTheProduct() { return null; } #endregion #region FpML Representation /// <summary> /// Builds the calculation period. /// </summary> /// <returns></returns> protected override CalculationPeriod BuildCalculationPeriod() { CalculationPeriod cp = base.BuildCalculationPeriod(); //Set the floating rate definition if (FloorStrike != null) { FloatingRateDefinition floatingRateDefinition = CapStrike != null ? FloatingRateDefinitionHelper.CreateCapFloor(ForecastRateIndex.floatingRateIndex, ForecastRateIndex.indexTenor, AdjustedFixingDate, GetRate(), Margin, (decimal)CapStrike, true) : FloatingRateDefinitionHelper.CreateCapFloor(ForecastRateIndex.floatingRateIndex, ForecastRateIndex.indexTenor, AdjustedFixingDate, GetRate(), Margin, (decimal)FloorStrike, false); cp.Item1 = floatingRateDefinition; if (floatingRateDefinition.calculatedRateSpecified) { cp.forecastRate = floatingRateDefinition.calculatedRate; cp.forecastRateSpecified = true; } } if (CalculationPerfomedIndicator) { cp.forecastAmount = ForecastAmount; } return cp; } #endregion } }
52.558261
209
0.561795
[ "BSD-3-Clause" ]
mmrath/Highlander.Net
FpML.V5r10.Components/ValuationEngine/Instruments/PriceableCapFloorCoupon.cs
30,223
C#
namespace autoCardboard.Common { public interface IGameTurn { } }
11.285714
31
0.658228
[ "MIT" ]
ChrisBrooksbank/autoCardboard
autoCardboard.Common/Interfaces/IGameTurn.cs
81
C#
using System; using System.Linq; using NUnit.Framework; namespace Essentions.Tests { [TestFixture] public class FunctionExtensionsTests { [Test] public void MemoizeUnaryTest() { int callCount = 0; Func<int, int> square = i => { callCount++; return i * i; }; Func<int, int> memoizedSquare = square.Memoize(); Enumerable.Range(0, 3).ForEach(i => memoizedSquare(i)).ToList(); Assert.That(callCount, Is.EqualTo(3)); memoizedSquare(1); Assert.That(callCount, Is.EqualTo(3)); memoizedSquare(4); Assert.That(callCount, Is.EqualTo(4)); } [Test] public void MemoizeBinaryTest() { int callCount = 0; Func<int, int, int> sum = (a, b) => { callCount++; return a + b; }; Func<int, int, int> memoizedSum = sum.Memoize(); Enumerable.Range(0, 3).ForEach(i => memoizedSum(i, i)).ToList(); Assert.That(callCount, Is.EqualTo(3)); memoizedSum(2, 2); Assert.That(callCount, Is.EqualTo(3)); memoizedSum(1, 2); Assert.That(callCount, Is.EqualTo(4)); } [Test] public void CurryTest() { Func<int, int, int> sum = (a, b) => a + b; Func<int, Func<int, int>> curriedSum = sum.Curry(); Assert.That(curriedSum(2)(4), Is.EqualTo(6)); } [Test] public void TestPartial() { Func<int, int, int> sum = (a, b) => a + b; Func<int, int> plusFive = sum.Partial(5); Assert.That(plusFive(5), Is.EqualTo(10)); } [Test] public void TestTuplify() { Func<int, int, int> sum = (a, b) => a + b; Func<Tuple<int, int>, int> tuplifiedSum = sum.Tuplify(); Func<int, int, int, int> ternarySum = (a, b, c) => a + b + c; Func<Tuple<int, int, int>, int> tuplifiedTernarySum = ternarySum.Tuplify(); Assert.That(tuplifiedSum(Tuple.Create(3, 5)), Is.EqualTo(8)); Assert.That(tuplifiedTernarySum(Tuple.Create(3, 5, 10)), Is.EqualTo(18)); } [Test] public void TestUntuplify() { Func<Tuple<int, int>, int> sum = tuple => tuple.Item1 + tuple.Item2; Func<Tuple<int, int, int>, int> ternarySum = tuple => tuple.Item1 + tuple.Item2 + tuple.Item3; Func<int, int, int> untuplifiedSum = sum.Untuplify(); Func<int, int, int, int> untuplifiedTernarySum = ternarySum.Untuplify(); Assert.That(untuplifiedSum(3, 5), Is.EqualTo(8)); Assert.That(untuplifiedTernarySum(3, 5, 10), Is.EqualTo(18)); } } }
32.213483
106
0.510987
[ "MIT" ]
EnoughTea/essentions
Src/Tests/FunctionExtensionsTests.cs
2,869
C#
using System; using System.Collections.Generic; using System.Text; namespace MineCase.Block { public class AirBlock : Block { public AirBlock(BlockProperties properties) :base(properties) { } } }
16.4
51
0.626016
[ "MIT" ]
bangush/MineCase
src/MineCase.Core/Block/AirBlock.cs
248
C#
using Clunker.Geometry; using ImGuiNET; using System; using System.Collections.Generic; using System.Numerics; using System.Text; using Veldrid; namespace Clunker.Editor.Utilities.PropertyEditor { public class StringEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var str = value as string ?? ""; var changed = ImGui.InputText(label, ref str, 255); return (changed, str); } } public class IntEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var num = (int)value; var changed = ImGui.DragInt(label, ref num); return (changed, num); } } public class FloatEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var num = (float)value; var changed = ImGui.DragFloat(label, ref num); return (changed, num); } } public class BooleanEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var boolean = (bool)value; var changed = ImGui.Checkbox(label, ref boolean); return (changed, boolean); } } public class Vector2Editor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var vector = (Vector2)value; var changed = ImGui.DragFloat2(label, ref vector); return (changed, vector); } } public class Vector3Editor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var vector = (Vector3)value; var changed = ImGui.DragFloat3(label, ref vector); return (changed, vector); } } public class QuaternionEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var quaternion = (Quaternion)value; var asVec4 = new Vector4(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W); var changed = ImGui.DragFloat4(label, ref asVec4, 0.01f); quaternion = changed ? Quaternion.Normalize(new Quaternion(asVec4.X, asVec4.Y, asVec4.Z, asVec4.W)) : quaternion; return (changed, quaternion); } } public class Vector2iEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var vector = (Vector2i)value; var asVec = (Vector2)vector; var changed = ImGui.DragFloat2(label, ref asVec, 1); return (changed, new Vector2i((int)asVec.X, (int)asVec.Y)); } } public class Vector3iEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var vector = (Vector3i)value; var asVec = (Vector3)vector; var changed = ImGui.DragFloat3(label, ref asVec); return (changed, new Vector3i((int)asVec.X, (int)asVec.Y, (int)asVec.Z)); } } public class RgbaFloatEditor : IPropertyEditor { public (bool, object) DrawEditor(string label, object value) { var rgbaFloat = (RgbaFloat)value; var asVector = new Vector4(rgbaFloat.R, rgbaFloat.G, rgbaFloat.B, rgbaFloat.A); var changed = ImGui.ColorEdit4(label, ref asVector); return (changed, new RgbaFloat(asVector.X, asVector.Y, asVector.Z, asVector.W)); } } }
31.826087
125
0.590437
[ "MIT" ]
my0n/Wrecker
Clunker/Editor/Utilities/PropertyEditor/PrimitiveEditors.cs
3,662
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Pakdel.GymManagement.Presentation.WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // 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.UseMvc(); } } }
31.693878
143
0.666452
[ "MIT" ]
KhaterePakdel/Pakdel.GymManagemet.WebApi
src/Presentation/Pakdel.GymManagement.Presentation.WebApi/Startup.cs
1,555
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; /// <summary> /// 64 个同类对象集成为 1 个 Block,每个 Pool 都由许多 Block 组成。 /// 每个对象拥有一个固定 ID,其 ID 前 6 位 bit 是其在 Block 中的偏差,前 26(32 - 6) 位是 Block 的序号。 /// </summary> /// <typeparam name="T"></typeparam> public class ObjectPool<T> : IEnumerable<T> { public const int BLK_LENGTH = 0x1 << 6; public const int BLK_MASK = ~0x3f; public const int OFFSET_MASK = 0x3f; private readonly ulong[] OFFSET = new ulong[] { 1 << 0x0, 1 << 0x1, 1 << 0x2, 1 << 0x3, 1 << 0x4, 1 << 0x5, 1 << 0x6, 1 << 0x7, 1 << 0x8, 1 << 0x9, 1 << 0xa, 1 << 0xb, 1 << 0xc, 1 << 0xd, 1 << 0xe, 1 << 0xf, 1 << 0x10, 1 << 0x11, 1 << 0x12, 1 << 0x13, 1 << 0x14, 1 << 0x15, 1 << 0x16, 1 << 0x17, 1 << 0x18, 1 << 0x19, 1 << 0x1a, 1 << 0x1b, 1 << 0x1c, 1 << 0x1d, 1 << 0x1e, (ulong)1 << 0x1f, (ulong)1 << 0x20, (ulong)1 << 0x21, (ulong)1 << 0x22, (ulong)1 << 0x23, (ulong)1 << 0x24, (ulong)1 << 0x25, (ulong)1 << 0x26, (ulong)1 << 0x27, (ulong)1 << 0x28, (ulong)1 << 0x29, (ulong)1 << 0x2a, (ulong)1 << 0x2b, (ulong)1 << 0x2c, (ulong)1 << 0x2d, (ulong)1 << 0x2e, (ulong)1 << 0x2f, (ulong)1 << 0x30, (ulong)1 << 0x31, (ulong)1 << 0x32, (ulong)1 << 0x33, (ulong)1 << 0x34, (ulong)1 << 0x35, (ulong)1 << 0x36, (ulong)1 << 0x37, (ulong)1 << 0x38, (ulong)1 << 0x39, (ulong)1 << 0x3a, (ulong)1 << 0x3b, (ulong)1 << 0x3c, (ulong)1 << 0x3d, (ulong)1 << 0x3e, (ulong)1 << 0x3f, }; private class Block { // Block 的锁 public readonly object mutex = new object(); // 一个格子是否被访问的快速修饰符 public ulong validates = 0x0; public Cell[] cells = new Cell[BLK_LENGTH]; public Block() { for (int i = 0; i < BLK_LENGTH; i++) { cells[i] = new Cell(); } } } private class Cell { public T content; public bool isValid = false; public readonly object mutex = new object(); } // 修改blkList和MaxLength需要使用该锁。 private readonly object listMutex = new object(); private List<Block> blks = new List<Block>(); //private readonly object blkMutex = new object(); //List<Cell[]> blkList = new List<Cell[]>(); // 最大可能的ID(实际上,最大ID应当小于MaxLength) public int MaxLength { get; private set; } = 0; // 增减idQueue需要使用该锁。 private readonly object idQueueMutex = new object(); //存储已经不被占用的id(即对象被清除) Queue<int> idQueue = new Queue<int>(); /// <summary> /// 给对象分配ID /// </summary> /// <param name="obj">目标对象</param> /// <returns>对象ID</returns> public int IDAlloc(T obj) { int res = -1; lock (idQueueMutex) { if (idQueue.Count > 0) res = idQueue.Dequeue(); } if (res == -1) { lock (listMutex) { res = MaxLength++; //如果超负荷,则申请一个新的数组 if ((res & BLK_MASK) >= blks.Count) { ExtendPool(); } } } int ofs = res & OFFSET_MASK; Block blk = blks[res & BLK_MASK]; lock (blk.mutex) { blk.validates = blk.validates | OFFSET[ofs]; } Cell c = blk.cells[ofs]; lock (c.mutex) { c.isValid = true; c.content = obj; } return res; } /// <summary> /// 给对象分配ID /// </summary> /// <param name="obj">目标对象</param> /// <param name="id">想申请的ID</param> /// <returns>对象ID。如果申请失败,则返回-1</returns> public int IDAlloc(T obj, int id) { // if (id < MaxLength) { if (CheckID(id)) return -1; } else { int prevLen; lock (listMutex) { prevLen = MaxLength; MaxLength = id + 1; while ((id & BLK_MASK) >= blks.Count) { ExtendPool(); } } lock (idQueueMutex) { for (int i = prevLen; i < MaxLength - 1; i++) { idQueue.Enqueue(i); } } } int ofs = id & OFFSET_MASK; Block blk = blks[id & BLK_MASK]; lock (blk.mutex) { blk.validates = blk.validates | OFFSET[ofs]; } Cell c = blk.cells[ofs]; lock (c.mutex) { c.isValid = true; c.content = obj; } return id; } /// <summary> /// 获取ID对应对象 /// </summary> /// <param name="id">对象ID</param> /// <returns>对象</returns> public T GetObject(int id) { return id == -1 ? default : blks[id & BLK_MASK].cells[id & OFFSET_MASK].content; } /// <summary> /// 检查ID是否被占用 /// </summary> /// <param name="id">对象ID</param> /// <returns>是否被占用。True,表示被占用;false,表示不被占用</returns> public bool CheckID(int id) { //return blks[id & BLK_MASK].cells[id & OFFSET_MASK].isValid; return (blks[id & BLK_MASK].validates & OFFSET[id & OFFSET_MASK]) != 0; } /// <summary> /// 移除对象 /// </summary> /// <param name="id">对象ID</param> public void RemoveObject(int id) { int ofs = id & OFFSET_MASK; Block blk = blks[id & BLK_MASK]; lock (blk.mutex) { blk.validates = blk.validates ^ OFFSET[ofs]; } Cell c = blk.cells[ofs]; lock (c.mutex) { c.isValid = false; } lock (idQueueMutex) idQueue.Enqueue(id); } public ObjectPool() { ExtendPool(); } private void ExtendPool() { blks.Add(new Block()); } public delegate void TraversalHandler(T obj); /// <summary> /// 遍历所有池中对象 /// </summary> /// <param name="handler"></param> public void Traversal(TraversalHandler handler) { foreach (Block blk in blks) { for (int i = 0; i < BLK_LENGTH; i++) { if (blk.cells[i].isValid) { handler(blk.cells[i].content); } } } } public IEnumerator<T> GetEnumerator() { return new ObjectPoolEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new ObjectPoolEnumerator(this); } /// <summary> /// Object Pool的迭代器 /// </summary> public class ObjectPoolEnumerator : IEnumerator<T> { public T Current => currentID == -1 ? default : pool.GetObject(currentID); ObjectPool<T> pool; // 当前的物体在池中的ID。-1,表示当前物体为空。 int currentID = -1; object IEnumerator.Current => currentID; public ObjectPoolEnumerator(ObjectPool<T> pool) { this.pool = pool; Reset(); } public void Dispose() { pool = null; } public bool MoveNext() { int minID = currentID + 1; int maxBlkIndex = pool.blks.Count; Block blk; ulong v; int ofs; // try to find in the same blk blk = pool.blks[minID & BLK_MASK]; v = blk.validates; ofs = minID & OFFSET_MASK; // if not empty if ((v >> ofs) != 0) { currentID = minID + RetrieveZeros(v >> ofs); return true; } // find from next blk for (int i = (minID & BLK_MASK) + 1; i < maxBlkIndex; i++) { blk = pool.blks[i]; v = blk.validates; // 该 blk 非空的。 if (v != 0) { currentID = (i << 6) | RetrieveZeros(v); return true; } } // no next item currentID = -1; return false; } int RetrieveZeros(ulong tp) { int cnt = 0; if ((tp & 0xffffffff) == 0) { cnt |= 32; tp >>= 32; } if ((tp & 0xffff) == 0) { cnt |= 16; tp >>= 16; } if ((tp & 0xff) == 0) { cnt |= 8; tp >>= 8; } if ((tp & 0xf) == 0) { cnt |= 4; tp >>= 4; } if ((tp & 0x3) == 0) { cnt |= 2; tp >>= 2; } if ((tp & 0x1) == 0) { cnt |= 1; } return cnt; } public void Reset() { currentID = -1; MoveNext(); } } }
27.713376
295
0.461733
[ "Apache-2.0" ]
1170300305/IEC-Project
Assets/Scripts/Game Bases/ObjectPool.cs
9,208
C#
using Pims.Api.Areas.Keycloak.Controllers; using Pims.Core.Extensions; using Pims.Core.Test; using Pims.Dal.Security; using System; using System.Diagnostics.CodeAnalysis; using Xunit; namespace Pims.Api.Test.Routes.Keycloak { /// <summary> /// RoleControllerTest class, provides a way to test endpoint routes. /// </summary> [Trait("category", "unit")] [Trait("category", "api")] [Trait("area", "keycloak")] [Trait("group", "role")] [Trait("group", "route")] [ExcludeFromCodeCoverage] public class RoleControllerTest { #region Variables #endregion #region Constructors public RoleControllerTest() { } #endregion #region Tests [Fact] public void Role_Route() { // Arrange // Act // Assert var type = typeof(RoleController); type.HasPermissions(Permissions.AdminRoles); type.HasArea("keycloak"); type.HasRoute("[area]/roles"); type.HasRoute("v{version:apiVersion}/[area]/roles"); type.HasApiVersion("1.0"); } [Fact] public void SyncRolesAsync_Route() { // Arrange var endpoint = typeof(RoleController).FindMethod(nameof(RoleController.SyncRolesAsync)); // Act // Assert Assert.NotNull(endpoint); endpoint.HasPost("sync"); endpoint.HasPermissions(Permissions.AdminRoles); } [Fact] public void GetRolesAsync_Route() { // Arrange var endpoint = typeof(RoleController).FindMethod(nameof(RoleController.GetRolesAsync), typeof(int), typeof(int), typeof(string)); // Act // Assert Assert.NotNull(endpoint); endpoint.HasGet(); endpoint.HasPermissions(Permissions.AdminRoles); } [Fact] public void GetRoleAsync_Route() { // Arrange var endpoint = typeof(RoleController).FindMethod(nameof(RoleController.GetRoleAsync), typeof(Guid)); // Act // Assert Assert.NotNull(endpoint); endpoint.HasGet("{key}"); endpoint.HasPermissions(Permissions.AdminRoles); } [Fact] public void UpdateRoleAsync_Route() { // Arrange var endpoint = typeof(RoleController).FindMethod(nameof(RoleController.UpdateRoleAsync), typeof(Guid), typeof(Areas.Keycloak.Models.Role.Update.RoleModel)); // Act // Assert Assert.NotNull(endpoint); endpoint.HasPut("{key}"); endpoint.HasPermissions(Permissions.AdminRoles); } #endregion } }
28.25
168
0.56531
[ "Apache-2.0" ]
FuriousLlama/PSP
backend/tests/unit/api/Routes/Keycloak/RoleControllerTest.cs
2,825
C#
using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace DemoApp { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); await builder.Build().RunAsync(); } } }
25.807692
115
0.779434
[ "MIT" ]
keg247/BlazorScheduler
DemoApp/Program.cs
671
C#
namespace MySkillsServer.Web.Tests { using System; using System.Linq; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using Xunit; public class SeleniumTests : IClassFixture<SeleniumServerFactory<Startup>>, IDisposable { private readonly SeleniumServerFactory<Startup> server; private readonly IWebDriver browser; public SeleniumTests(SeleniumServerFactory<Startup> server) { this.server = server; server.CreateClient(); var opts = new ChromeOptions(); opts.AddArguments("--headless"); opts.AcceptInsecureCertificates = true; this.browser = new ChromeDriver(opts); } [Fact(Skip = "Example test. Disabled for CI.")] public void FooterOfThePageContainsPrivacyLink() { this.browser.Navigate().GoToUrl(this.server.RootUri); Assert.EndsWith( "/Home/Privacy", this.browser.FindElements(By.CssSelector("footer a")).First().GetAttribute("href")); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.server?.Dispose(); this.browser?.Dispose(); } } } }
27.882353
100
0.572433
[ "MIT" ]
Paulina-Dyulgerska/MySkillsServer
Tests/MySkillsServer.Web.Tests/SeleniumTests.cs
1,424
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; using Windows.Foundation.Collections; namespace CommunicateService { public sealed class Service : IBackgroundTask { private BackgroundTaskDeferral Deferral; private static readonly ConcurrentDictionary<AppServiceConnection, AppServiceConnection> PairedConnections = new ConcurrentDictionary<AppServiceConnection, AppServiceConnection>(); private static readonly Queue<AppServiceConnection> ClientWaitingQueue = new Queue<AppServiceConnection>(); private static readonly Queue<AppServiceConnection> ServerWaitingrQueue = new Queue<AppServiceConnection>(); private static readonly object Locker = new object(); public async void Run(IBackgroundTaskInstance taskInstance) { Deferral = taskInstance.GetDeferral(); taskInstance.Canceled += TaskInstance_Canceled; if (taskInstance.TriggerDetails is AppServiceTriggerDetails Trigger) { AppServiceConnection IncomeConnection = Trigger.AppServiceConnection; IncomeConnection.RequestReceived += Connection_RequestReceived; AppServiceResponse Response = await IncomeConnection.SendMessageAsync(new ValueSet { { "ExecuteType", "Identity" } }); if (Response.Status == AppServiceResponseStatus.Success) { if (Response.Message.TryGetValue("Identity", out object Identity)) { lock (Locker) { switch (Convert.ToString(Identity)) { case "FullTrustProcess": { if (ClientWaitingQueue.TryDequeue(out AppServiceConnection ClientConnection)) { PairedConnections.TryAdd(ClientConnection, IncomeConnection); } else { ServerWaitingrQueue.Enqueue(IncomeConnection); } break; } case "UWP": { if (ServerWaitingrQueue.TryDequeue(out AppServiceConnection ServerConnection)) { PairedConnections.TryAdd(IncomeConnection, ServerConnection); } else { ClientWaitingQueue.Enqueue(IncomeConnection); } break; } } } } } } } private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { AppServiceDeferral Deferral = args.GetDeferral(); try { AppServiceConnection ServerConnection; SpinWait Spin = new SpinWait(); Stopwatch Watch = new Stopwatch(); Watch.Start(); while (!PairedConnections.TryGetValue(sender, out ServerConnection) && Watch.ElapsedMilliseconds < 5000) { if (Spin.NextSpinWillYield) { await Task.Delay(500); } else { Spin.SpinOnce(); } } Watch.Stop(); if (ServerConnection != null) { AppServiceResponse ServerRespose = await ServerConnection.SendMessageAsync(args.Request.Message); if (ServerRespose.Status == AppServiceResponseStatus.Success) { await args.Request.SendResponseAsync(ServerRespose.Message); } else { await args.Request.SendResponseAsync(new ValueSet { { "Error", "Can't not send message to server" } }); } } else { ValueSet Value = new ValueSet { { "Error", "Failed to wait a server connection within the specified time" } }; await args.Request.SendResponseAsync(Value); } } catch { ValueSet Value = new ValueSet { { "Error", "Some exceptions were threw while transmitting the message" } }; await args.Request.SendResponseAsync(Value); } finally { Deferral.Complete(); } } private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { try { if ((sender.TriggerDetails as AppServiceTriggerDetails)?.AppServiceConnection is AppServiceConnection DisConnection) { try { DisConnection.RequestReceived -= Connection_RequestReceived; lock (Locker) { if (PairedConnections.TryRemove(DisConnection, out AppServiceConnection ServerConnection)) { Task.WaitAny(ServerConnection.SendMessageAsync(new ValueSet { { "ExecuteType", "Execute_Exit" } }).AsTask(), Task.Delay(2000)); } else if (PairedConnections.FirstOrDefault((Con) => Con.Value == DisConnection).Key is AppServiceConnection ClientConnection) { if (PairedConnections.TryRemove(ClientConnection, out _)) { Task.WaitAny(ClientConnection.SendMessageAsync(new ValueSet { { "ExecuteType", "FullTrustProcessExited" } }).AsTask(), Task.Delay(2000)); ClientConnection.Dispose(); } } } } finally { DisConnection.Dispose(); } } } catch (Exception ex) { Debug.WriteLine($"Error was threw in CommunicateService: {ex.Message}"); } finally { Deferral.Complete(); } } } }
40.454054
188
0.464057
[ "Apache-2.0" ]
Nun-z/RX-Explorer
CommunicateService/Service.cs
7,486
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net { internal static class CookieFields { internal const string CommentAttributeName = "Comment"; internal const string CommentUrlAttributeName = "CommentURL"; internal const string DiscardAttributeName = "Discard"; internal const string DomainAttributeName = "Domain"; internal const string ExpiresAttributeName = "Expires"; internal const string MaxAgeAttributeName = "Max-Age"; internal const string PathAttributeName = "Path"; internal const string PortAttributeName = "Port"; internal const string SecureAttributeName = "Secure"; internal const string VersionAttributeName = "Version"; internal const string HttpOnlyAttributeName = "HttpOnly"; } }
43.285714
71
0.715072
[ "MIT" ]
2m0nd/runtime
src/libraries/Common/src/System/Net/CookieFields.cs
909
C#
using Galytix.Domain; using Galytix.Infra; using Galytix.Repositories; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Galytix { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton<CountryGwpRepository>(); services.AddSingleton<CountryGwpService>(); services.AddMemoryCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseMiddleware<GlobalExceptionHandler>(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
29.098039
106
0.633423
[ "Unlicense" ]
Gaurav-Puri101187/Galytix
Startup.cs
1,484
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SimpleSystemsManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for InventoryDeletionSummary Object /// </summary> public class InventoryDeletionSummaryUnmarshaller : IUnmarshaller<InventoryDeletionSummary, XmlUnmarshallerContext>, IUnmarshaller<InventoryDeletionSummary, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> InventoryDeletionSummary IUnmarshaller<InventoryDeletionSummary, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public InventoryDeletionSummary Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; InventoryDeletionSummary unmarshalledObject = new InventoryDeletionSummary(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("RemainingCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.RemainingCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SummaryItems", targetDepth)) { var unmarshaller = new ListUnmarshaller<InventoryDeletionSummaryItem, InventoryDeletionSummaryItemUnmarshaller>(InventoryDeletionSummaryItemUnmarshaller.Instance); unmarshalledObject.SummaryItems = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TotalCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.TotalCount = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static InventoryDeletionSummaryUnmarshaller _instance = new InventoryDeletionSummaryUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static InventoryDeletionSummaryUnmarshaller Instance { get { return _instance; } } } }
38.730769
186
0.627855
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/InventoryDeletionSummaryUnmarshaller.cs
4,028
C#
version https://git-lfs.github.com/spec/v1 oid sha256:82e05165a3fa05b30ef2533a41b621ccc17ff5884cd41dfcd3fae489bd1d8d47 size 1146
32.25
75
0.883721
[ "MIT" ]
Vakuzar/Multithreaded-Blood-Sim
Blood/Library/PackageCache/com.unity.test-framework@1.1.14/UnityEngine.TestRunner/Utils/Vector4EqualityComparer.cs
129
C#
using System.ComponentModel; namespace LearnMore.Domain.Enums { public enum Gender { Unknown = 0, [Description("Female")] Female, [Description("Male")] Male } }
13.5625
32
0.552995
[ "MIT" ]
MKnoski/LearnMore
LearnMore.Domain/Enums/Gender.cs
219
C#
using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Localization; namespace OCore.Deployment { public class DeploymentTarget { public DeploymentTarget(LocalizedString name, LocalizedString description, RouteValueDictionary route) { Name = name; Description = description; Route = route; } public LocalizedString Name { get; } public LocalizedString Description { get; } public RouteValueDictionary Route { get; } } }
26.35
110
0.658444
[ "BSD-3-Clause" ]
china-live/OCore
src/OCore/OCore.Deployment.Abstractions/DeploymentTarget.cs
529
C#
using Archigen; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Loremaker.Maps { public class PopulationCenterGenerator : IGenerator<List<PopulationCenter>> { private List<Landmass> Landmasses; private IGenerator<string> NameGenerator; public PopulationCenterGenerator(List<Landmass> landmasses, IGenerator<string> nameGenerator) { this.Landmasses = new List<Landmass>(); this.Landmasses.AddRange(landmasses); this.NameGenerator = nameGenerator; } private List<PopulationCenter> NextPopulation(Func<Landmass,bool> landmassCondition, Func<Landmass,int> maxSize, Func<MapCell,bool> mapCellCondition) { var result = new List<PopulationCenter>(); var offlimits = new List<uint>(); var maxTries = 100; foreach (var landmass in this.Landmasses.Where(x => landmassCondition(x))) { var coasts = landmass.MapCells.Where(x => mapCellCondition(x)).ToList(); var pops = maxSize(landmass); for (int i = 0; i < pops; i++) { var homecell = coasts.GetRandom(); var tries = 1; while (offlimits.Contains(homecell.Id) && tries < maxTries) { homecell = coasts.GetRandom(); tries++; } if (tries >= maxTries) continue; // ID of PopulationCenters are done inside Next() var pc = new PopulationCenter() { MapCell = homecell, MapCellId = homecell.Id, Name = this.NameGenerator.Next(), Type = PopulationCenterType.Town, Landmass = landmass, // backreference }; offlimits.Add(homecell.Id); offlimits.AddRange(homecell.AdjacentMapCellIds); offlimits.AddRange(homecell.AdjacentMapCells.SelectMany(x => x.AdjacentMapCellIds)); result.Add(pc); } } return result; } // TODO: Simplify public List<PopulationCenter> Next() { var result = new List<PopulationCenter>(); var coastalPopulations = this.NextPopulation( landmass => landmass.Size > 2, landmass => (int)Math.Max(1, landmass.Size/200 + Math.Log(landmass.Size)/2), mapcell => mapcell.IsCoast); var landlockedPopulations = this.NextPopulation( landmass => landmass.Size > 10, landmass => (int)Math.Max(0, landmass.Size/150), mapcell => mapcell.IsLand && !mapcell.IsCoast); uint id = 0; foreach(var p in coastalPopulations) { p.Id = id++; } foreach(var p in landlockedPopulations) { p.Id = id++; } result.AddRange(coastalPopulations); result.AddRange(landlockedPopulations); return result; } } }
33.168317
157
0.514328
[ "MIT" ]
kesac/Loremaker
Loremaker/Loremaker/Maps/PopulationCenterGenerator.cs
3,352
C#
namespace SETUNA.Main { using SETUNA.Main.Other; using SETUNA.Main.Style; using SETUNA.Main.StyleItems; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using Timer = System.Windows.Forms.Timer; public sealed class ScrapBase : Form { private int _activeMargin; private double _activeOpacity; private bool _blTargetSet; private string _datetime; private bool _dragmode; private Point _dragpoint; private bool _err_opac; private int _inactiveMargin; private double _inactiveOpacity; private System.Drawing.Drawing2D.InterpolationMode _interpolationmode; private bool _isMouseEnter; private string _name; private double _opacity; public ScrapBook _parent; private Point _ptTarget; private int _rolloverMargin; private double _rolloverOpacity; private double _saveopacity; private int _scale; private bool _solidframe; private bool closePrepare; private IContainer components; private const int GWL_EXSTYLE = -20; private System.Drawing.Image imgView; public bool Initialized; private bool IsStyleApply; private int StyleAppliIndex; private Timer StyleApplyTimer; private Point StyleClickPoint = Point.Empty; private CStyleItem[] StyleItems; private Timer timOpacity; private const int WS_EX_LAYERED = 0x80000; public event ScrapEventHandler ScrapActiveEvent; public event ScrapEventHandler ScrapCloseEvent; public event ScrapEventHandler ScrapCreateEvent; public event ScrapEventHandler ScrapInactiveEnterEvent; public event ScrapEventHandler ScrapInactiveEvent; public event ScrapEventHandler ScrapInactiveOutEvent; public event ScrapSubMenuHandler ScrapSubMenuOpening; public CStyleItem[] styleItems => StyleItems; public ScrapBase() { this.InitializeComponent(); base.KeyPreview = true; this.closePrepare = false; this._dragmode = false; this._scale = 100; this._opacity = base.Opacity; this._blTargetSet = false; this._ptTarget = new Point(); this._solidframe = true; this._inactiveOpacity = this.Opacity; this._activeOpacity = this.Opacity; this._rolloverOpacity = this.Opacity; this.DateTime = System.DateTime.Now.ToString(); this.Name = this.DateTime.Replace("/", "").Replace(":", "").Replace("浏览", "").Replace(" ", "-"); this._interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; } public void addScrapMenuEvent(IScrapMenuListener listener) { this.ScrapSubMenuOpening = (ScrapSubMenuHandler)Delegate.Combine(this.ScrapSubMenuOpening, new ScrapSubMenuHandler(listener.ScrapMenuOpening)); } public void addScrapStyleEvent(IScrapStyleListener listener) { this.ScrapCreateEvent = (ScrapEventHandler)Delegate.Combine(this.ScrapCreateEvent, new ScrapEventHandler(listener.ScrapCreated)); this.ScrapActiveEvent = (ScrapEventHandler)Delegate.Combine(this.ScrapActiveEvent, new ScrapEventHandler(listener.ScrapActivated)); this.ScrapInactiveEvent = (ScrapEventHandler)Delegate.Combine(this.ScrapInactiveEvent, new ScrapEventHandler(listener.ScrapInactived)); this.ScrapInactiveEnterEvent = (ScrapEventHandler)Delegate.Combine(this.ScrapInactiveEnterEvent, new ScrapEventHandler(listener.ScrapInactiveMouseOver)); this.ScrapInactiveOutEvent = (ScrapEventHandler)Delegate.Combine(this.ScrapInactiveOutEvent, new ScrapEventHandler(listener.ScrapInactiveMouseOut)); } public void ApplyStyleItem(object sender, EventArgs e) { this.StyleApplyTimer.Enabled = false; if (this.StyleItems != null && this.StyleAppliIndex < this.StyleItems.Length) { int waitinterval = 1; ScrapBase scrap = this; try { CStyleItem item = this.StyleItems[this.StyleAppliIndex]; if (this.Initialized || (!this.Initialized && item.IsInitApply)) { item.Apply(ref scrap, out waitinterval, this.StyleClickPoint); } this.StyleAppliIndex++; if (waitinterval <= 0) { waitinterval = 1; } this.StyleApplyTimer.Interval = waitinterval; this.StyleApplyTimer.Enabled = true; } catch (Exception exception) { Console.WriteLine("ScrapBase ApplyStyleItem Exception:" + exception.ToString()); this.IsStyleApply = false; } } else { this.IsStyleApply = false; } if (!this.IsStyleApply && !this.Initialized) { this.Initialized = true; } } public void ApplyStyles(CStyle style, Point clickpoint) { if (!this.IsStyleApply) { if ((style != null && cacheInfo.styleID != style.StyleID) || cacheInfo.stylePoint != clickpoint) { cacheInfo.styleID = style == null ? 0 : style.StyleID; cacheInfo.stylePoint = clickpoint; ApplyCache(); } this.StyleClickPoint = clickpoint; this.IsStyleApply = true; this.StyleAppliIndex = 0; this.StyleItems = style == null ? null : style.Items; if (this.StyleApplyTimer == null) { this.StyleApplyTimer = new Timer(); this.StyleApplyTimer.Enabled = false; this.StyleApplyTimer.Tick += new EventHandler(this.ApplyStyleItem); } this.StyleApplyTimer.Interval = 1; this.StyleApplyTimer.Start(); } } private void DragEnd() { this._dragmode = false; base.SuspendLayout(); this.Opacity = this._saveopacity; base.ResumeLayout(); if (this.cacheInfo.posX != base.Left || this.cacheInfo.posY != base.Top) { this.cacheInfo.posX = base.Left; this.cacheInfo.posY = base.Top; ApplyCache(); } } private void DragMove(Point pt) { if (this._dragmode) { base.Left += pt.X - this._dragpoint.X; base.Top += pt.Y - this._dragpoint.Y; } } private void DragStart(Point pt) { this._dragmode = true; this._dragpoint = pt; this._saveopacity = this.Opacity; base.SuspendLayout(); this.Opacity = 0.5; base.ResumeLayout(); } ~ScrapBase() { this.ImageAllDispose(); } public System.Drawing.Image GetThumbnail() { Bitmap image = new Bitmap(230, 150, PixelFormat.Format24bppRgb); Graphics graphics = Graphics.FromImage(image); graphics.FillRectangle(Brushes.DarkGray, 0, 0, image.Width, image.Height); if ((this.imgView.Width <= (image.Width - 1)) || (this.imgView.Height <= (image.Height - 1))) { graphics.DrawImageUnscaled(this.imgView, 1, 1); } else { double num; Size size = new Size(this.imgView.Width - 1, this.imgView.Height - 1); if (((size.Width - image.Width) - 1) <= ((size.Height - image.Height) - 1)) { num = ((double)(image.Width - 1)) / ((double)(size.Width - 1)); } else { num = ((double)(image.Height - 1)) / ((double)(size.Height - 1)); } size.Width = (int)(size.Width * num); size.Height = (int)(size.Height * num); graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(this.imgView, 1, 1, size.Width, size.Height); } graphics.DrawRectangle(Pens.Black, 0, 0, image.Width - 1, image.Height - 1); return image; } public System.Drawing.Image GetViewImage() { Bitmap bitmap = new Bitmap(base.Width, base.Height, PixelFormat.Format24bppRgb); base.DrawToBitmap(bitmap, new Rectangle(0, 0, base.Width, base.Height)); return bitmap; } [DllImport("user32.dll")] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); private void ImageAllDispose() { this.ImageDispose(ref this.imgView); } private void ImageDispose(ref System.Drawing.Image img) { if (img != null) { img.Dispose(); img = null; } } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScrapBase)); this.timOpacity = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // timOpacity // this.timOpacity.Interval = 15; this.timOpacity.Tick += new System.EventHandler(this.timOpacity_Tick); // // ScrapBase // this.AllowDrop = true; this.AutoSize = true; this.BackColor = System.Drawing.Color.Gray; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.ClientSize = new System.Drawing.Size(292, 266); this.DoubleBuffered = true; this.ForeColor = System.Drawing.SystemColors.ControlText; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimumSize = new System.Drawing.Size(1, 1); this.Name = "ScrapBase"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.TopMost = true; this.Activated += new System.EventHandler(this.ScrapBase_Activated); this.Deactivate += new System.EventHandler(this.ScrapBase_Deactivate); this.DragDrop += new System.Windows.Forms.DragEventHandler(this.ScrapBase_DragDrop); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.ScrapBase_DragEnter); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ScrapBase_KeyPress); this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.ScrapBase_MouseClick); this.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.ScrapBase_MouseDoubleClick); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlImg_MouseDown); this.MouseEnter += new System.EventHandler(this.ScrapBase_MouseEnter); this.MouseLeave += new System.EventHandler(this.ScrapBase_MouseLeave); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnlImg_MouseMove); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlImg_MouseUp); this.ResumeLayout(false); } public LayerInfo layerInfo { private set; get; } protected override void OnLoad(EventArgs e) { layerInfo = new LayerInfo(this); } protected override void OnClosed(EventArgs e) { layerInfo.Dispose(); this.ImageAllDispose(); base.OnClosed(e); } protected override void OnFormClosing(FormClosingEventArgs e) { if (((e.CloseReason == CloseReason.ApplicationExitCall) || (e.CloseReason == CloseReason.TaskManagerClosing)) || (e.CloseReason == CloseReason.WindowsShutDown)) { Console.WriteLine("由系统结束"); } else if (!this.closePrepare) { e.Cancel = true; this.OnScrapClose(new ScrapEventArgs()); } base.OnFormClosing(e); } protected override void OnPaint(PaintEventArgs e) { int width = (int)(this.imgView.Width * (((float)this._scale) / 100f)); int height = (int)(this.imgView.Height * (((float)this._scale) / 100f)); int all = this.Padding.All; e.Graphics.InterpolationMode = this._interpolationmode; e.Graphics.DrawImage(this.imgView, all, all, width, height); if (!this._solidframe) { Pen pen = new Pen(Color.FromArgb(0xf3, 0xf3, 0xf3)); e.Graphics.DrawLine(pen, 0, 0, base.Width, 0); e.Graphics.DrawLine(pen, 0, 0, 0, base.Height); pen.Dispose(); pen = null; } } public void OnScrapClose(ScrapEventArgs e) { if (this.ScrapCloseEvent != null) { this.ScrapCloseEvent(this, e); } CacheManager.DeleteCacheInfo(cacheInfo); cacheInfo = null; } public void OnScrapCreated() { if (this.ScrapCreateEvent != null) { this.ScrapCreateEvent(this, new ScrapEventArgs(this)); } } private void pnlImg_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.DragStart(e.Location); } } private void pnlImg_MouseMove(object sender, MouseEventArgs e) { this.DragMove(e.Location); } private void pnlImg_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.DragEnd(); } } private void ScrapBase_Activated(object sender, EventArgs e) { if (this.ScrapActiveEvent != null) { this.ScrapActiveEvent(sender, new ScrapEventArgs(this)); } this.Opacity = this.ActiveOpacity; } private void ScrapBase_Deactivate(object sender, EventArgs e) { if (this.ScrapInactiveEvent != null) { this.ScrapInactiveEvent(sender, new ScrapEventArgs(this)); } if (!this._isMouseEnter) { this.Opacity = this.InactiveOpacity; } } private void ScrapBase_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { foreach (string str in (string[])e.Data.GetData(DataFormats.FileDrop)) { this.Manager.AddDragImageFileName(str); } } } private void ScrapBase_DragEnter(object sender, DragEventArgs e) { if (this.Manager.IsImageDrag) { e.Effect = DragDropEffects.Move | DragDropEffects.Copy | DragDropEffects.Scroll; } } private void ScrapBase_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == Convert.ToChar(Keys.Escape)) { base.Close(); } } private void ScrapBase_MouseClick(object sender, MouseEventArgs e) { layerInfo.Update(); if ((e.Button == MouseButtons.Right) && (this.ScrapSubMenuOpening != null)) { this.ScrapSubMenuOpening(sender, new ScrapMenuArgs(this, null)); } } private void ScrapBase_MouseDoubleClick(object sender, MouseEventArgs e) { this.Manager.WClickStyle(this, e.Location); } private void ScrapBase_MouseEnter(object sender, EventArgs e) { this._isMouseEnter = true; if (!this.Focused && (this.ScrapInactiveEnterEvent != null)) { this.ScrapInactiveEnterEvent(sender, new ScrapEventArgs(this)); } if (Form.ActiveForm != this) { this.Opacity = this.RollOverOpacity; } } private void ScrapBase_MouseLeave(object sender, EventArgs e) { this._isMouseEnter = false; if (!this.Focused && (this.ScrapInactiveOutEvent != null)) { this.ScrapInactiveOutEvent(sender, new ScrapEventArgs(this)); } if (Form.ActiveForm != this) { this.Opacity = this.InactiveOpacity; } } public void ScrapClose() { this.closePrepare = true; base.Close(); GC.Collect(); } public void ScrapResize() { base.Width = this.imgView.Width + (this.Padding.Left + this.Padding.Right); base.Height = this.imgView.Height + (this.Padding.Top + this.Padding.Bottom); } public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) { this.SetBoundsCore(x, y, width, height, specified); } [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); private void timOpacity_Tick(object sender, EventArgs e) { try { if (base.Opacity != this._opacity) { if (this._err_opac) { try { this._opacity = 1.0; base.Opacity = 1.0; } catch { Console.WriteLine("ScrapBase timOpacity_Tick Exception2:---"); } } else { double num = base.Opacity - this._opacity; if (Math.Abs(num) < 0.10000000149011612) { try { if (base.Opacity != this._opacity) { base.Opacity = this._opacity; } } catch (Win32Exception exception) { this.timOpacity.Stop(); this._err_opac = true; this.Opacity = 1.0; Console.WriteLine("ScrapBase timOpacity_Tick Exception: " + exception.Message + ", Opaque True"); } catch (Exception exception2) { Console.WriteLine("ScrapBase timOpacity_Tick Exception: " + exception2.Message + ", " + base.Opacity.ToString() + ", " + this._opacity.ToString()); } } else if (num < 0.0) { base.Opacity += 0.10000000149011612; } else { base.Opacity -= 0.10000000149011612; } } } if (this._blTargetSet) { int num3; int num5; int num2 = base.Top - this._ptTarget.Y; if (num2 > 0) { num3 = -(Math.Abs(num2) / 3); } else { num3 = Math.Abs(num2) / 3; } if (num3 == 0) { base.Top = this._ptTarget.Y; } else { base.Top += num3; } int num4 = base.Left - this._ptTarget.X; if (num4 > 0) { num5 = -(Math.Abs(num4) / 2); } else { num5 = Math.Abs(num4) / 2; } if (num5 == 0) { base.Left = this._ptTarget.X; } else { base.Left += num5; } if ((base.Top == this._ptTarget.Y) && (base.Left == this._ptTarget.X)) { this._blTargetSet = false; } else { this.Refresh(); } } if ((base.Opacity == this._opacity) && !this._blTargetSet) { this.timOpacity.Enabled = false; } } catch (Exception exception3) { Console.WriteLine("ScrapBase timOpacity_Tick Exception:" + exception3.Message); } } public int ActiveMargin { get { return this._activeMargin; } set { this._activeMargin = value; this.Padding = new System.Windows.Forms.Padding(this._activeMargin); } } public double ActiveOpacity { get { return this._activeOpacity; } set { this._activeOpacity = value; if (Form.ActiveForm == this) { this.Opacity = this._activeOpacity; } } } public string DateTime { get { return this._datetime; } set { this._datetime = value; } } public ScrapBaseInfo cacheInfo { set { mInfo = value; } get { return mInfo; } } ScrapBaseInfo mInfo; public bool isFirstInitCompactScrap { set; get; } = false; public System.Drawing.Image Image { get { return this.imgView; } set { this.ImageAllDispose(); var bitmap = new Bitmap(value); this.imgView = (System.Drawing.Image)bitmap; //this.imgView = (System.Drawing.Image)value.Clone(); if (this.imgView == null) { Console.WriteLine("ScrapBase Image : unll"); } this.Scale = this.Scale; this.Refresh(); } } public int InactiveMargin { get { return this._inactiveMargin; } set { this._inactiveMargin = value; if ((Form.ActiveForm != this) && !this._isMouseEnter) { this.Padding = new System.Windows.Forms.Padding(this._inactiveMargin); } } } public double InactiveOpacity { get { return this._inactiveOpacity; } set { this._inactiveOpacity = value; if ((Form.ActiveForm != this) && !this._isMouseEnter) { this.Opacity = this._inactiveOpacity; } } } public System.Drawing.Drawing2D.InterpolationMode InterpolationMode { get { return this._interpolationmode; } set { this._interpolationmode = value; } } public ScrapBook Manager { get { return this._parent; } set { this._parent = value; if (this.ScrapCloseEvent == null) { this.ScrapCloseEvent = (ScrapEventHandler)Delegate.Combine(this.ScrapCloseEvent, new ScrapEventHandler(this._parent.ScrapClose)); base.KeyDown += new KeyEventHandler(this._parent.OnKeyUp); } } } public string Name { get { return this._name; } set { this._name = value; this.Text = this._name; } } public double Opacity { get { return this._opacity; } set { this._opacity = value; if (this._opacity != base.Opacity) { this.timOpacity.Enabled = true; } } } public System.Windows.Forms.Padding Padding { get { return base.Padding; } set { base.Padding = value; BoundsSpecified none = BoundsSpecified.None; int x = 0; int y = 0; int width = ((int)(this.imgView.Width * (((float)this._scale) / 100f))) + (value.All * 2); int height = ((int)(this.imgView.Height * (((float)this._scale) / 100f))) + (value.All * 2); if (base.Width != width) { none |= BoundsSpecified.Width | BoundsSpecified.X; x = base.Left + ((base.Width - width) / 2); } if (base.Height != height) { none |= BoundsSpecified.Height | BoundsSpecified.Y; y = base.Top + ((base.Height - height) / 2); } if (none != BoundsSpecified.None) { this.SetBoundsCore(x, y, width, height, BoundsSpecified.Location); base.ClientSize = new Size(width, height); } } } public int RollOverMargin { get { return this._rolloverMargin; } set { this._rolloverMargin = value; if ((Form.ActiveForm != this) && this._isMouseEnter) { this.Padding = new System.Windows.Forms.Padding(this._rolloverMargin); } } } public double RollOverOpacity { get { return this._rolloverOpacity; } set { this._rolloverOpacity = value; if ((Form.ActiveForm != this) && this._isMouseEnter) { this.Opacity = this._rolloverOpacity; } } } public int Scale { get { return this._scale; } set { this._scale = value; if (this._scale < -200) { this._scale = -200; } if (this._scale > 200) { this._scale = 200; } base.Width = ((int)(this.imgView.Width * (((float)this._scale) / 100f))) + (this.Padding.All * 2); base.Height = ((int)(this.imgView.Height * (((float)this._scale) / 100f))) + (this.Padding.All * 2); this.Refresh(); } } public bool SolidFrame { get { return this._solidframe; } set { this._solidframe = value; } } public Point TargetLocation { get { if (this._blTargetSet) { return this._ptTarget; } return base.Location; } set { this._ptTarget = value; if (this._ptTarget != base.Location) { this._blTargetSet = true; this.timOpacity.Enabled = true; } } } public bool Visible { get { return base.Visible; } set { if (!value && (base.FormBorderStyle != FormBorderStyle.None)) { base.ShowInTaskbar = false; } else if (value && (base.FormBorderStyle != FormBorderStyle.None)) { base.ShowInTaskbar = true; } base.Visible = value; } } public delegate void ScrapEventHandler(object sender, ScrapEventArgs e); public delegate void ScrapSubMenuHandler(object sender, ScrapMenuArgs e); public void ApplyCache() { CacheManager.SaveCacheInfo(cacheInfo); } } }
33.235919
179
0.47466
[ "MIT" ]
BUGchongXD/SETUNA2
SETUNA/Main/ScrapBase.cs
31,291
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using BlackFox.VsWhere; using System.Text.RegularExpressions; using QIQI.CMakeCaller.Utilities; namespace QIQI.CMakeCaller { public class CMakeEnv { public string CMakeBin { get; } public static CMakeEnv DefaultInstance = null; public CMakeEnv(string bin) { if (!File.Exists(bin)) { throw new ArgumentException(nameof(bin)); } CMakeBin = bin; } static CMakeEnv() { var bin = FindCMake(); if (!string.IsNullOrEmpty(bin)) { DefaultInstance = new CMakeEnv(bin); } } private static string FindCMake() { var methods = new Func<string>[] { () => PathUtils.Which("cmake"), () => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PathUtils.GuessPath(new string[] { "%ProgramW6432%\\CMake\\bin\\cmake.exe", "%ProgramFiles%\\CMake\\bin\\cmake.exe", "%ProgramFiles(x86)%\\CMake\\bin\\cmake.exe" }) : null, () => PathUtils.GuessPath(VsInstances.GetAll().Select(x => Path.Combine(x.InstallationPath,"Common7","IDE","CommonExtensions","Microsoft","CMake","CMake","bin","cmake.exe"))) }; var result = methods.Select(x => { try { return x(); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception) { return null; } #pragma warning restore CA1031 // Do not catch general exception types }).FirstOrDefault(x => x != null); if (result != null) { try { result = Path.GetFullPath(result); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception) { result = null; } #pragma warning restore CA1031 // Do not catch general exception types } return result; } } }
31.328947
190
0.50273
[ "MIT" ]
1354092549/CMakeCaller
CMakeCaller/CMakeEnv.cs
2,383
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QuickFix; using QuickFix.Transport; namespace SimpleAcceptor3 { class Program { [STAThread] static void Main(string[] args) { Console.WriteLine("============================================"); Console.WriteLine("===== Hello proof of concept world. ========"); Console.WriteLine("===== Simple acceptor (3) ========"); Console.WriteLine("============================================"); Console.WriteLine("This is only an example program."); Console.WriteLine("It's a simple server (e.g. Acceptor) app that will let clients (e.g. Initiators)"); Console.WriteLine("connect to it. It will accept and display any application-level messages that it receives."); Console.WriteLine("Connecting clients should set TargetCompID to 'SIMPLE' and SenderCompID to 'CLIENT1' or 'CLIENT2'."); Console.WriteLine("Port is 5001."); Console.WriteLine("(see simpleacc.cfg for configuration details)"); Console.WriteLine("see also, revised and updated from the boilerplate doc..."); Console.WriteLine("usage: SimpleAcceptor3 cfg/simpleAcceptorThree.cfg"); Console.WriteLine("============="); if (args.Length != 1) { Console.WriteLine("usage: SimpleAcceptor3 CONFIG_FILENAME"); Console.WriteLine("usage: SimpleAcceptor3 cfg/simpleAcceptorThree.cfg"); System.Environment.Exit(2); } try { // debug cwd var currentDirectory_one = System.Environment.CurrentDirectory; var currentDirectory_BaseDirectory = System.AppDomain.CurrentDomain.BaseDirectory; Console.WriteLine($"Current directory from system env: {currentDirectory_one}"); Console.WriteLine($"Current directory from app domain base dir: {currentDirectory_BaseDirectory}"); /* * Current directory from system env: C:\Users\marc\source\repos\SimpleAcceptor3\SimpleAcceptor3 * So, quickfix is using the system.env.currentdirectory as its base folder when it navigates * to the DataDictionary file from the relative file path defined in the .cfg config file. * */ SessionSettings settings = new SessionSettings(args[0]); IApplication app = new SimpleAcceptorThreeApp(); IMessageStoreFactory storeFactory = new FileStoreFactory(settings); ILogFactory logFactory = new FileLogFactory(settings); // dbg filepath to fix spec files Console.WriteLine("Spilling all session ids"); var sessionsFromSettings = settings.GetSessions(); foreach(var sess in sessionsFromSettings) { Console.WriteLine($"(dbg) session: {sess.ToString()}"); } var sessionId = "FIX.4.2:SIMPLE->CLIENT1"; var sessionSettingsStringified = settings.ToString(); Console.WriteLine($"Session settings spill: {sessionSettingsStringified}"); // problems... // if filepath errors from settings to data dictionary file, this will fault. IAcceptor acceptor = new ThreadedSocketAcceptor(app, storeFactory, settings, logFactory); // possibly look at lower-level ways to construct gthe socker acceptor (or socker initiator) relying less on files, more programmatic. acceptor.Start(); Console.WriteLine("press <enter> to quit"); Console.Read(); acceptor.Stop(); } catch (System.Exception e) { Console.WriteLine("==FATAL ERROR=="); Console.WriteLine(e.ToString()); } } } }
46.850575
150
0.578018
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
marcdata/jsonfix
SimpleAcceptor3/SimpleAcceptor3/Program.cs
4,078
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 DMEmu.Properties { 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()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DMEmu.Properties.Resources", typeof(Resources).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)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap Keyboard { get { object obj = ResourceManager.GetObject("Keyboard", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
42.459459
171
0.601209
[ "MIT" ]
Estrol/DMEmu
DMEmu/Properties/Resources.Designer.cs
3,144
C#
// Copyright (c) SimpleIdServer. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using NETCore.Ldap.DER.Universals; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace NETCore.Ldap.DER { [DebuggerDisplay("LDAP packet {MessageId.Value}")] public class LdapPacket : DERStructure { public LdapPacket() { Tag = new DERTag { LdapCommand = null, TagClass = ClassTags.Universal, UniversalClassType = UniversalClassTypes.Sequence, TagNumber = (int)UniversalClassTypes.Sequence, PcType = PcTypes.Constructed }; } public DERInteger MessageId { get; set; } public DERProtocolOperation ProtocolOperation { get; set; } public DERSequence<DERControl> Controls { get; set; } public static LdapPacket Extract(ICollection<byte> buffer) { var ldapPacket = new LdapPacket(); ldapPacket.ExtractTagAndLength(buffer); ldapPacket.MessageId = DERInteger.Extract(buffer); ldapPacket.ProtocolOperation = DERProtocolOperation.Extract(buffer); if (buffer.Count > 0) { ldapPacket.Controls = DERSequence<DERControl>.Extract(buffer); } return ldapPacket; } public override ICollection<byte> Serialize() { var content = new List<byte>(); content.AddRange(MessageId.Serialize()); content.AddRange(ProtocolOperation.Serialize()); if (Controls != null && Controls.Values.Any()) { content.AddRange(Controls.Serialize(0xa0)); } Length = content.Count(); var result = new List<byte>(); result.AddRange(SerializeDerStructure(true)); result.AddRange(content); return result; } } }
34.216667
107
0.593765
[ "Apache-2.0" ]
simpleidserver/NETCore.Ldap
src/NETCore.Ldap/DER/LdapPacket.cs
2,055
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.StepFunctions")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Step Functions. AWS Step Functions is a web service that enables you to coordinate a network of computing resources across distributed components using state machines.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Step Functions. AWS Step Functions is a web service that enables you to coordinate a network of computing resources across distributed components using state machines.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Step Functions. AWS Step Functions is a web service that enables you to coordinate a network of computing resources across distributed components using state machines.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Step Functions. AWS Step Functions is a web service that enables you to coordinate a network of computing resources across distributed components using state machines.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.0.114")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
51.27451
263
0.775908
[ "Apache-2.0" ]
pcameron-/aws-sdk-net
sdk/src/Services/StepFunctions/Properties/AssemblyInfo.cs
2,615
C#
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.DirectConnect.Model { /// <summary> /// <para>A structure containing information about a new public virtual interface.</para> /// </summary> public class NewPublicVirtualInterface { private string virtualInterfaceName; private int? vlan; private int? asn; private string authKey; private string amazonAddress; private string customerAddress; private List<RouteFilterPrefix> routeFilterPrefixes = new List<RouteFilterPrefix>(); /// <summary> /// The name of the virtual interface assigned by the customer Example: "My VPC" /// /// </summary> public string VirtualInterfaceName { get { return this.virtualInterfaceName; } set { this.virtualInterfaceName = value; } } /// <summary> /// Sets the VirtualInterfaceName property /// </summary> /// <param name="virtualInterfaceName">The value to set for the VirtualInterfaceName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithVirtualInterfaceName(string virtualInterfaceName) { this.virtualInterfaceName = virtualInterfaceName; return this; } // Check to see if VirtualInterfaceName property is set internal bool IsSetVirtualInterfaceName() { return this.virtualInterfaceName != null; } /// <summary> /// VLAN ID Example: 101 /// /// </summary> public int Vlan { get { return this.vlan ?? default(int); } set { this.vlan = value; } } /// <summary> /// Sets the Vlan property /// </summary> /// <param name="vlan">The value to set for the Vlan property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithVlan(int vlan) { this.vlan = vlan; return this; } // Check to see if Vlan property is set internal bool IsSetVlan() { return this.vlan.HasValue; } /// <summary> /// Autonomous system (AS) number for Border Gateway Protocol (BGP) configuration Example: 65000 /// /// </summary> public int Asn { get { return this.asn ?? default(int); } set { this.asn = value; } } /// <summary> /// Sets the Asn property /// </summary> /// <param name="asn">The value to set for the Asn property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithAsn(int asn) { this.asn = asn; return this; } // Check to see if Asn property is set internal bool IsSetAsn() { return this.asn.HasValue; } /// <summary> /// Authentication key for BGP configuration Example: asdf34example /// /// </summary> public string AuthKey { get { return this.authKey; } set { this.authKey = value; } } /// <summary> /// Sets the AuthKey property /// </summary> /// <param name="authKey">The value to set for the AuthKey property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithAuthKey(string authKey) { this.authKey = authKey; return this; } // Check to see if AuthKey property is set internal bool IsSetAuthKey() { return this.authKey != null; } /// <summary> /// IP address assigned to the Amazon interface. Example: 192.168.1.1/30 /// /// </summary> public string AmazonAddress { get { return this.amazonAddress; } set { this.amazonAddress = value; } } /// <summary> /// Sets the AmazonAddress property /// </summary> /// <param name="amazonAddress">The value to set for the AmazonAddress property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithAmazonAddress(string amazonAddress) { this.amazonAddress = amazonAddress; return this; } // Check to see if AmazonAddress property is set internal bool IsSetAmazonAddress() { return this.amazonAddress != null; } /// <summary> /// IP address assigned to the customer interface. Example: 192.168.1.2/30 /// /// </summary> public string CustomerAddress { get { return this.customerAddress; } set { this.customerAddress = value; } } /// <summary> /// Sets the CustomerAddress property /// </summary> /// <param name="customerAddress">The value to set for the CustomerAddress property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithCustomerAddress(string customerAddress) { this.customerAddress = customerAddress; return this; } // Check to see if CustomerAddress property is set internal bool IsSetCustomerAddress() { return this.customerAddress != null; } /// <summary> /// A list of routes to be advertised to the AWS network in this region (public virtual interface) or your VPC (private virtual interface). /// /// </summary> public List<RouteFilterPrefix> RouteFilterPrefixes { get { return this.routeFilterPrefixes; } set { this.routeFilterPrefixes = value; } } /// <summary> /// Adds elements to the RouteFilterPrefixes collection /// </summary> /// <param name="routeFilterPrefixes">The values to add to the RouteFilterPrefixes collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithRouteFilterPrefixes(params RouteFilterPrefix[] routeFilterPrefixes) { foreach (RouteFilterPrefix element in routeFilterPrefixes) { this.routeFilterPrefixes.Add(element); } return this; } /// <summary> /// Adds elements to the RouteFilterPrefixes collection /// </summary> /// <param name="routeFilterPrefixes">The values to add to the RouteFilterPrefixes collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public NewPublicVirtualInterface WithRouteFilterPrefixes(IEnumerable<RouteFilterPrefix> routeFilterPrefixes) { foreach (RouteFilterPrefix element in routeFilterPrefixes) { this.routeFilterPrefixes.Add(element); } return this; } // Check to see if RouteFilterPrefixes property is set internal bool IsSetRouteFilterPrefixes() { return this.routeFilterPrefixes.Count > 0; } } }
36.594595
177
0.599072
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.DirectConnect/Model/NewPublicVirtualInterface.cs
9,478
C#
#if NET5_0_OR_GREATER using System.Net.Http.Formatting; using System.Net.Http.Json.Formatting; using Xunit; namespace System.Net.Http.Json { public class ModuleTests { [Fact] public void Init_Test() { // assert var writer = MediaTypeFormatterCollection.Default.FindWriter(typeof(string), JsonDefaults.MediaTypeHeader); Assert.NotNull(writer); Assert.IsType<JsonMediaTypeFormatter>(writer); var reader = MediaTypeFormatterCollection.Default.FindReader(typeof(string), JsonDefaults.MediaTypeHeader); Assert.NotNull(reader); Assert.IsType<JsonMediaTypeFormatter>(reader); } } } #endif
28.48
119
0.667135
[ "MIT" ]
Byndyusoft/Byndyusoft.Net.Http.Json
tests/ModuleTests.cs
712
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MOEWcfServiceLibrary")] [assembly: AssemblyDescription("This assembly contains severices that work with the performance metrics system")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Utah Department of Transportation")] [assembly: AssemblyProduct("MOEWcfServiceLibrary")] [assembly: AssemblyCopyright("Copyright © 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("1110819b-58db-469f-8ae9-ae4b9ab306b2")] // 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.15.0.0")] [assembly: AssemblyFileVersion("1.15.0.0")]
41.305556
113
0.755212
[ "Apache-2.0" ]
AndreRSanchez/ATSPM
MOEWcfServiceLibrary/Properties/AssemblyInfo.cs
1,490
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("Help")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Help")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("d652df44-6354-4781-8f35-e5e84921a249")] // 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.324324
84
0.742216
[ "MIT" ]
StoyanTakov/Telerik
Spring Season/C#/C#Part1/Exams/Exam 2016/Help/Properties/AssemblyInfo.cs
1,384
C#
using System.Text; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Collections.Generic; using Xunit; using Bemol.Test.Fixtures; using Bemol.Http; using Bemol.Http.Exceptions; using Bemol.Http.Util; namespace Bemol.Test { [CollectionDefinition("Context")] public class ContextServer : ICollectionFixture<BemolServerFixture> { } [Collection("Context")] public class ContextTest { private readonly BemolServerFixture Server; private class User { public string Name { set; get; } public int Age { set; get; } public User(string name = "John", int age = 25) { Name = name; Age = age; } } public ContextTest(BemolServerFixture server) { Server = server; } // ******************************************************************************************** // REQUEST // ******************************************************************************************** [Fact] public void Body_String_Equal() { var content = new StringContent("Hello world!"); var ctx = Server.GetContext(client => client.PostAsync("/", content)); Assert.Equal("Hello world!", ctx.Body()); } [Fact] public void Body_Json_Equal() { var content = JsonContent.Create(new { Name = "John", Age = 25 }); var ctx = Server.GetContext(client => client.PostAsync("/", content)); Assert.Equal("{\"name\":\"John\",\"age\":25}", ctx.Body()); } [Fact] public void Body_AsClass_Equal() { var user = new User(); HttpContent content = JsonContent.Create(user); // type has to be HttpContent, else it'll hang indefinitely var ctx = Server.GetContext(client => client.PostAsJsonAsync("/", content)); var returned = ctx.Body<User>(); Assert.Equal(user.Age, returned.Age); Assert.Equal(user.Name, returned.Name); } [Fact] public void BodyAsClass_NotValid() { var ctx = Server.GetContext(client => client.PostAsync("/", null)); Assert.Throws<BadRequestException>(() => ctx.Body<User>()); } [Fact] public void Body_FormData_Equal() { var form = new List<KeyValuePair<string, string>>(); form.Add(KeyValuePair.Create("foo", "bar")); form.Add(KeyValuePair.Create("baz", "foobar")); var formData = new FormUrlEncodedContent(form); var ctx = Server.GetContext(client => client.PostAsync("/", formData)); Assert.Equal("foo=bar&baz=foobar", ctx.Body()); } [Fact] public void BodyAsBytes_Equal() { var content = new StringContent("Hello world!"); var ctx = Server.GetContext(client => client.PostAsync("/", content)); Assert.Equal(Encoding.UTF8.GetBytes("Hello world!"), ctx.BodyAsBytes()); } [Fact] public void FormParam_Equal() { var form = new List<KeyValuePair<string, string>>(); form.Add(KeyValuePair.Create("foo", "bar")); form.Add(KeyValuePair.Create("baz", "foobarzé")); var formData = new FormUrlEncodedContent(form); var ctx = Server.GetContext(client => client.PostAsync("/", formData)); Assert.Equal("bar", ctx.FormParam("foo")); Assert.Equal("foobarzé", ctx.FormParam("baz")); } [Fact] public void FormParam_AsInt_Equal() { var form = new List<KeyValuePair<string, string>>(); form.Add(KeyValuePair.Create("foo", "5")); var formData = new FormUrlEncodedContent(form); var ctx = Server.GetContext(client => client.PostAsync("/", formData)); Assert.Equal(5, ctx.FormParam<int>("foo")); } [Fact] public void FormParam_AsInt_Null() { var form = new List<KeyValuePair<string, string>>(); var formData = new FormUrlEncodedContent(form); var ctx = Server.GetContext(client => client.PostAsync("/", formData)); Assert.Throws<BadRequestException>(() => ctx.FormParam<int>("foo")); } [Fact] public void FormParam_FormIsNull_IsNull() { var ctx = Server.GetContext(client => client.PostAsync("/", null)); Assert.Null(ctx.FormParam("foo")); } [Fact] public void FormParam_MultipleValuesForSameKey_Equal() { var form = new List<KeyValuePair<string, string>>(); form.Add(KeyValuePair.Create("foo", "bar")); form.Add(KeyValuePair.Create("foo", "baz")); var formData = new FormUrlEncodedContent(form); var ctx = Server.GetContext(client => client.PostAsync("/", formData)); Assert.Equal("bar,baz", ctx.FormParam("foo")); } [Theory] [InlineData("/:name", "name", "/foo", "foo")] [InlineData("/:name/settings", "name", "/foo/settings", "foo")] public void PathParam_AsString_Equal(string path, string paramName, string requestPath, string result) { var entry = new HandlerEntry("GET", path, true, null); var ctx = Server.GetContext(client => client.GetAsync(requestPath)); ctx = ContextUtil.Update(ctx, entry); Assert.Equal(result, ctx.PathParam(paramName)); } [Fact] public void PathParam_AsString_Throw() { var ctx = Server.GetContext(client => client.GetAsync("/")); Assert.Throws<InternalServerErrorException>(() => ctx.PathParam("foo")); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void PathParam_AsInt_Equal(int id) { var entry = new HandlerEntry("GET", "/:id", true, null); var ctx = Server.GetContext(client => client.GetAsync($"/{id}")); ctx = ContextUtil.Update(ctx, entry); Assert.Equal(id, ctx.PathParam<int>("id")); } [Theory] [InlineData(0.0)] [InlineData(21.5)] [InlineData(100)] public void PathParam_AsFloat_Equal(int temperature) { var entry = new HandlerEntry("GET", "/:temperature", true, null); var ctx = Server.GetContext(client => client.GetAsync($"/{temperature}")); ctx = ContextUtil.Update(ctx, entry); Assert.Equal(temperature, ctx.PathParam<float>("temperature")); } [Fact] public void PathParam_AsInt_Throws() { var entry = new HandlerEntry("GET", "/:id", true, null); var ctx = Server.GetContext(client => client.GetAsync($"/foo")); ctx = ContextUtil.Update(ctx, entry); Assert.Throws<BadRequestException>(() => ctx.PathParam<int>("id")); } [Fact] public void ContentType_TextPlain_Equal() { var content = new StringContent("Hello world!"); var ctx = Server.GetContext(client => client.PostAsync("/", content)); Assert.Matches("text/plain", ctx.ContentType()); } [Fact] public void ContentType_ApplicationJson_Equal() { var content = JsonContent.Create(new User()); var ctx = Server.GetContext(client => client.PostAsync("/", content)); Assert.Matches("application/json", ctx.ContentType()); } [Theory] [InlineData("foo", "bar")] public void Cookie_GetCookie_Equal(string name, string value) { var ctx = Server.GetContext(client => { client.DefaultRequestHeaders.Add("Cookie", $"{name}={value}"); client.GetAsync("/"); client.DefaultRequestHeaders.Remove("Cookie"); }); Assert.Equal(value, ctx.Cookie(name)); } [Fact] public void Cookie_GetCookie_IsNull() { var ctx = Server.GetContext(client => client.GetAsync("/")); Assert.Null(ctx.Cookie("bar")); } [Theory] [InlineData("foo", "bar")] public void Header_Equal(string name, string value) { var ctx = Server.GetContext(client => { client.DefaultRequestHeaders.Add(name, value); client.GetAsync("/"); client.DefaultRequestHeaders.Remove(name); }); Assert.Equal(value, ctx.Header(name)); } [Fact] public void Header_NameDoesntExist_IsNull() { var ctx = Server.GetContext(client => client.GetAsync("/")); Assert.Null(ctx.Header("foo")); } [Fact] public void Method_Get_Equal() { var ctx = Server.GetContext(client => client.GetAsync("/")); Assert.Equal("GET", ctx.Method()); } [Fact] public void Method_Post_Equal() { var ctx = Server.GetContext(client => client.PostAsync("/", null)); Assert.Equal("POST", ctx.Method()); } [Theory] [InlineData("/")] [InlineData("/user")] [InlineData("/user/")] public void Path_Equal(string path) { var ctx = Server.GetContext(client => client.GetAsync(path)); Assert.Equal(path, ctx.Path()); } [Theory] [InlineData("/?foo=bar", "foo", "bar")] [InlineData("/?foo=bar&foo=baz", "foo", "bar,baz")] public void QueryParam_Equal(string url, string key, string value) { var ctx = Server.GetContext(client => client.GetAsync(url)); Assert.Equal(value, ctx.QueryParam(key)); } [Fact] public void QueryParam_Null() { var ctx = Server.GetContext(client => client.GetAsync("/")); Assert.Null(ctx.QueryParam("foo")); } [Theory] [InlineData("/?foo=16", "foo", 16)] public void QueryParam_AsInt_Equal(string url, string key, int value) { var ctx = Server.GetContext(client => client.GetAsync(url)); Assert.Equal(value, ctx.QueryParam<int>(key)); } [Theory] [InlineData("/?foo=16", "bar")] public void QueryParam_AsInt_Null(string url, string key) { var ctx = Server.GetContext(client => client.GetAsync(url)); Assert.Throws<BadRequestException>(() => ctx.QueryParam<int>(key)); } [Theory] [InlineData("/?foo=bar", "foo", "bar")] [InlineData("/?foo=bar&foo=baz", "foo", "bar,baz")] public void QueryMap_Equal(string url, string key, string value) { var ctx = Server.GetContext(client => client.GetAsync(url)); Assert.Equal(value, ctx.QueryMap()[key]); } [Theory] [InlineData("/hello?foo=bar", "?foo=bar")] public void QueryString_Equal(string url, string expected) { var ctx = Server.GetContext(client => client.GetAsync(url)); Assert.Equal(expected, ctx.QueryString()); } [Fact] public void UserAgent_Normal_Equal() { var ctx = Server.GetContext(client => { client.DefaultRequestHeaders.Add("User-Agent", "Foo"); client.GetAsync("/"); client.DefaultRequestHeaders.Remove("User-Agent"); }); Assert.Equal("Foo", ctx.UserAgent()); } [Fact] public void UserAgent_IsNull_Equal() { var ctx = Server.GetContext(client => { client.DefaultRequestHeaders.Remove("User-Agent"); client.GetAsync("/"); }); Assert.Null(ctx.UserAgent()); } // ******************************************************************************************** // RESPONSE // ******************************************************************************************** [Theory] [InlineData("Hello world!")] [InlineData("Tommy Josépovic")] [InlineData("На берегу пустынных волн")] [InlineData("ვეპხის ტყაოსანი შოთა რუსთაველი")] [InlineData("⠊⠀⠉⠁⠝⠀⠑⠁⠞⠀⠛⠇⠁⠎⠎⠀⠁⠝⠙⠀⠊⠞⠀⠙⠕⠑⠎⠝⠞⠀⠓⠥⠗⠞⠀⠍⠑")] public void ResultString_SetUsingString_Equal(string result) { var ctx = Server.GetContext(client => client.GetAsync("/")); ctx.Result(result); Assert.Equal(result, ctx.ResultString()); } [Theory] [InlineData("Hello world!")] [InlineData("Tommy Josépovic")] [InlineData("На берегу пустынных волн")] [InlineData("ვეპხის ტყაოსანი შოთა რუსთაველი")] [InlineData("⠊⠀⠉⠁⠝⠀⠑⠁⠞⠀⠛⠇⠁⠎⠎⠀⠁⠝⠙⠀⠊⠞⠀⠙⠕⠑⠎⠝⠞⠀⠓⠥⠗⠞⠀⠍⠑")] public void ResultString_SetUsingBytes_Equal(string result) { var ctx = Server.GetContext(client => client.GetAsync("/")); byte[] byteArray = Encoding.UTF8.GetBytes(result); ctx.Result(byteArray); Assert.Equal(result, ctx.ResultString()); } [Theory] [InlineData(404)] [InlineData(500)] public void Status_SetUsingStatus_Equal(int status) { var ctx = Server.GetContext(async client => { var response = await client.GetAsync("/"); Assert.Equal(status, (int)response.StatusCode); }); ctx.Status(status); Server.SendResponse(ctx); } [Theory] [InlineData("baz", "for")] public void Cookie_SetNameValue_Equal(string name, string value) { var ctx = Server.GetContext(async client => { var response = await client.GetAsync("/"); var cookies = response.Headers.GetValues("Set-Cookie"); foreach (var cookie in cookies) { Assert.Equal($"{name}={value}", cookie); } }); ctx.Cookie(name, value); Server.SendResponse(ctx); } [Theory] [InlineData("for", "baz")] public void Cookie_SetCookie_Equal(string name, string value) { var ctx = Server.GetContext(async client => { var response = await client.GetAsync("/"); var cookies = response.Headers.GetValues("Set-Cookie"); foreach (var cookie in cookies) { Assert.Equal($"{name}={value}", cookie); } }); ctx.Cookie(new Cookie(name, value)); Server.SendResponse(ctx); } [Theory] [InlineData("baz", "buzz")] public void RemoveCookie_Expired(string name, string value) { var ctx = Server.GetContext(async client => { client.DefaultRequestHeaders.Add("Cookie", $"{name}={value}"); var response = await client.GetAsync("/"); var cookies = response.Headers.GetValues("Set-Cookie"); foreach (var cookie in cookies) { Assert.Equal($"{name}=; Max-Age=0", cookie); } }); ctx.RemoveCookie(name); Server.SendResponse(ctx); } [Fact] public void Json_SimpleObject_Equal() { var ctx = Server.GetContext(client => client.GetAsync("/")); ctx.Json(new { Name = "John", Age = 10 }); Assert.Equal("{\"Name\":\"John\",\"Age\":10}", ctx.ResultString()); } } }
38.8475
119
0.536071
[ "MIT" ]
tommy-josepovic/bemol
test/Context.Test.cs
15,841
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.Serialization; namespace DocumentFormat.OpenXml.Validation.Schema.Restrictions { /// <summary> /// Single (xsd:float) based value restriction. /// </summary> [DataContract] internal class SingleValueRestriction : SimpleValueRestriction<Single, SingleValue> { protected override Single MinValue => Single.MinValue; protected override Single MaxValue => Single.MaxValue; /// <inheritdoc /> public override XsdType XsdType => XsdType.Float; /// <inheritdoc /> public override bool ValidateValueType(OpenXmlSimpleType attributeValue) { if (attributeValue.HasValue) { return true; // TODO: is NaN valid? //Single value = ((SingleValue)attributeValue).Value; //return !Single.IsNaN(value); } return false; } } }
29.810811
101
0.625567
[ "MIT" ]
coderIML/Open-XML-SDK.net
src/DocumentFormat.OpenXml/Validation/Schema/Restrictions/SingleValueRestriction.cs
1,105
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System.Data; using System.Diagnostics.CodeAnalysis; using EdFi.Ods.Common; using EdFi.Ods.Common.Conventions; using EdFi.Ods.Common.Models.Definitions; using EdFi.Ods.Common.Models.Domain; using EdFi.TestFixture; using NUnit.Framework; using Test.Common; namespace EdFi.Ods.Tests.EdFi.Ods.Common { [TestFixture] [SuppressMessage("ReSharper", "InconsistentNaming")] public class When_getting_a_namespace_for_an_extension_entity : TestFixtureBase { [Assert] public void Should_return_the_correct_namespace_for_an_entity_and_an_extension_of_that_entity() { var domainModelBuilder = new DomainModelBuilder(); var fullName = new FullName("edfi", "TestEntity1"); var fullName1 = new FullName("schema2", "TestEntity1Extension"); var associationProperty = new EntityPropertyDefinition("KeyProperty1", new PropertyType(DbType.Int32), null, true); domainModelBuilder.AddEntity( new EntityDefinition( fullName.Schema, fullName.Name, new[] { associationProperty, new EntityPropertyDefinition("StringProperty1", new PropertyType(DbType.String)), new EntityPropertyDefinition("DateProperty1", new PropertyType(DbType.Date)) }, new[] { new EntityIdentifierDefinition( "PK", new[] { "KeyProperty1" }, isPrimary: true) })); domainModelBuilder.AddAggregate(new AggregateDefinition(fullName, new FullName[0])); domainModelBuilder.AddEntity( new EntityDefinition( fullName1.Schema, fullName1.Name, new[] { associationProperty, new EntityPropertyDefinition("StringProperty1", new PropertyType(DbType.String)), new EntityPropertyDefinition("DateProperty1", new PropertyType(DbType.Date)) }, new[] { new EntityIdentifierDefinition( "PK", new[] { "KeyProperty1" }, isPrimary: true) })); domainModelBuilder.AddAssociation( new AssociationDefinition( new FullName("schema2", "FromCore"), Cardinality.OneToOneExtension, fullName, new[] { associationProperty }, fullName1, new[] { associationProperty }, true, true)); domainModelBuilder.AddSchema(new SchemaDefinition("EdFi", fullName.Schema)); domainModelBuilder.AddSchema(new SchemaDefinition("schema2", "schema2")); var domainModel = domainModelBuilder.Build(); string entityNamespace = domainModel.EntityByFullName[fullName] .AggregateNamespace(EdFiConventions.ProperCaseName); string entityName = domainModel.EntityByFullName[fullName] .Name; string entityExtensionNamespace = domainModel.EntityByFullName[fullName1] .AggregateNamespace("TestEntity1ExtensionProperCaseName"); string entityExtensionName = domainModel.EntityByFullName[fullName1] .Name; Assert.That( entityNamespace.Equals($"{Namespaces.Entities.NHibernate.BaseNamespace}.{entityName}Aggregate.{EdFiConventions.ProperCaseName}")); Assert.That( entityExtensionNamespace.Equals( $"{Namespaces.Entities.NHibernate.BaseNamespace}.{entityName}Aggregate.TestEntity1ExtensionProperCaseName")); } } }
40.474576
146
0.521776
[ "Apache-2.0" ]
gmcelhanon/Ed-Fi-ODS-1
Application/EdFi.Ods.Tests/EdFi.Ods.Common/NamespacesTests.cs
4,776
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Commands.Compute.Models; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using System.Collections.Generic; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute { /// <summary> /// Add a Vault Secret Group object to VM /// </summary> [Cmdlet("Add", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMSecret"),OutputType(typeof(PSVirtualMachine))] public class NewAzureVaultSecretGroupCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Alias("VMProfile")] [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = HelpMessages.VMProfile)] [ValidateNotNullOrEmpty] public PSVirtualMachine VM { get; set; } [Alias("Id")] [Parameter( Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "The ID for Source Vault")] [ValidateNotNullOrEmpty] public string SourceVaultId { get; set; } [Parameter( Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "Certificate store in LocalMachine")] [ValidateNotNullOrEmpty] public string CertificateStore { get; set; } [Parameter( Position = 3, ValueFromPipelineByPropertyName = true, HelpMessage = "URL referencing a secret in a Key Vault.")] [ValidateNotNullOrEmpty] public string CertificateUrl { get; set; } public override void ExecuteCmdlet() { if (this.VM.OSProfile == null) { this.VM.OSProfile = new OSProfile(); } if (this.VM.OSProfile.Secrets == null) { this.VM.OSProfile.Secrets = new List<VaultSecretGroup>(); } int i = 0; for (; i <= this.VM.OSProfile.Secrets.Count; i++) { if (i == this.VM.OSProfile.Secrets.Count) { var sourceVault = new SubResource { Id = this.SourceVaultId }; var vaultCertificates = new List<VaultCertificate>{ new VaultCertificate() { CertificateStore = this.CertificateStore, CertificateUrl = this.CertificateUrl, } }; this.VM.OSProfile.Secrets.Add( new VaultSecretGroup() { SourceVault = sourceVault, VaultCertificates = vaultCertificates, }); break; } if (this.VM.OSProfile.Secrets[i].SourceVault != null && this.VM.OSProfile.Secrets[i].SourceVault.Id.Equals(this.SourceVaultId)) { if (this.VM.OSProfile.Secrets[i].VaultCertificates == null) { this.VM.OSProfile.Secrets[i].VaultCertificates = new List<VaultCertificate>(); } this.VM.OSProfile.Secrets[i].VaultCertificates.Add( new VaultCertificate() { CertificateStore = this.CertificateStore, CertificateUrl = this.CertificateUrl, }); break; } } WriteObject(this.VM); } } }
37.936
144
0.516871
[ "MIT" ]
Acidburn0zzz/azure-powershell
src/ResourceManager/Compute/Commands.Compute/VirtualMachine/Config/AddAzureVMSecretCommand.cs
4,620
C#
namespace <%= domainName %>.Builders.Interfaces { using <%= domainName %>.Entities.Abstract; public interface IBuilder<TEntity, TParameters> : IBuilder where TEntity : BaseEntity where TParameters : IBuilderParameters<TEntity> { TEntity Build(TParameters command); } public interface IBuilder { } }
22.142857
134
0.751613
[ "MIT" ]
Worble/generator-dotnet-api
generators/dotnet/templates/Template.Domain/Builders/Interfaces/IBuilder.cs
310
C#
using UnityEngine; using System.Collections; public class collisionFight : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame IEnumerator OnCollisionEnter(Collision col){ if (col.gameObject.tag=="Player") { yield return new WaitForSeconds (0.2f); Destroy(col.gameObject); Destroy (gameObject); } } }
18.75
45
0.709333
[ "MIT" ]
McGameJam/McGameJam
Assets/collisionFight.cs
377
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("NavigationFlow.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NavigationFlow.iOS")] [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("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.745919
[ "Apache-2.0" ]
Aleksey7151/FlexiMvvm
Tutorials/Navigation/NavigationFlow/NavigationFlow.iOS/Properties/AssemblyInfo.cs
1,412
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace FootballBetting.Data.Models { public class Round { public int Id { get; set; } [Required] public string Name { get; set; } public List<Game> Games { get; set; } = new List<Game>(); } }
20.125
65
0.627329
[ "MIT" ]
l3kov9/CSharpWebDevelopmentBasics
.Net Core and EF Core Exercises/FootballBetting/FootballBetting.Data/Models/Round.cs
324
C#
namespace OtterUI { /// <summary> /// Used to define what type of button the GuiButton will be. Defaults to NORMAL /// </summary> public enum ButtonType { /// <summary> /// A NORMAL GuiButton is a button that has to be clicked each time you want it to fire /// </summary> NORMAL, /// <summary> /// A TOGGLE button is a button that can be switched on of off. Uses the isSelected flag and OnSelectedEvent/OnDeselected event /// </summary> TOGGLE, /// <summary> /// A RADIO button is added to a group of other RADIO buttons. Like the TOGGLE button, it uses the OnSelectedEvent and OnDeselected event. Unlike the /// TOGGLE button, a single RADIO button cannot be switched on and off, and is only deselected when another RADIO button in the same group is /// selected /// </summary> RADIO, /// <summary> /// A DOWNABLE button is like the NORMAL button except that it will fire the OnClickEvent each frame while the mouse button is held down. /// </summary> DOWNABLE } }
36.806452
159
0.619632
[ "MIT" ]
NFPN/palavrando-otter
OtterUI/ButtonType.cs
1,143
C#
using Newtonsoft.Json; using System; namespace Codelyzer.Analysis.Model { public class Annotation : UstNode { [JsonProperty("semantic-class-type", Order = 14)] public string SemanticClassType { get; set; } [JsonProperty("references", Order = 99)] public Reference Reference { get; set; } public Annotation() : base(IdConstants.AnnotationIdName) { Reference = new Reference(); } public override bool Equals(object obj) { if(obj is Annotation) { return Equals(obj as Annotation); } return false; } public bool Equals(Annotation compareNode) { return compareNode != null && Reference?.Equals(compareNode.Reference) != false && SemanticClassType?.Equals(compareNode.SemanticClassType) != false && base.Equals(compareNode); } public override int GetHashCode() { return HashCode.Combine(SemanticClassType, base.GetHashCode()); } } }
27.95122
84
0.550611
[ "Apache-2.0" ]
Eruanion/codelyzer
src/Analysis/Codelyzer.Analysis.Model/Annotation.cs
1,146
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Extensions.Logging; using WET.lib.Containers; using WET.lib.Enums; using WET.lib.Extensions; using WET.lib.Interfaces; using WET.lib.Monitors.Base; using WET.lib.OutputFormatters.Base; namespace WET.lib { public class ETWMonitor : IDisposable { public const string DefaultSessionName = nameof(ETWMonitor); private readonly CancellationTokenSource _ctSource = new(); private TraceEventSession _session; public event EventHandler<ETWEventContainerItem> OnEvent; private readonly List<BaseMonitor> _monitors; private readonly List<BaseOutputFormatter> _outputFormatters; private BaseOutputFormatter _selectedOutputFormatter; private IEventFilter _eventFilter; private ILogger _logger; private IEventStorage _eventStorage; private DateTime _lastPush = DateTime.Now; private TimeSpan? _interval; private int? _threshold; private long? _hostID; private ConcurrentBag<ETWEventContainerItem> _throttledItems = new(); private static bool IsRunningAsAdmin() { #pragma warning disable CA1416 // Validate platform compatibility var wm = new WindowsPrincipal(WindowsIdentity.GetCurrent()); #pragma warning restore CA1416 // Validate platform compatibility #pragma warning disable CA1416 // Validate platform compatibility return wm.IsInRole(WindowsBuiltInRole.Administrator); #pragma warning restore CA1416 // Validate platform compatibility } public ETWMonitor() { _monitors = GetType().Assembly.GetTypes().Where(a => a.BaseType == typeof(BaseMonitor)) .Select(a => (BaseMonitor) Activator.CreateInstance(a)).ToList(); _outputFormatters = GetType().Assembly.GetTypes().Where(a => a.BaseType == typeof(BaseOutputFormatter)) .Select(a => (BaseOutputFormatter) Activator.CreateInstance(a)).ToList(); if (!IsRunningAsAdmin()) { throw new UnauthorizedAccessException("Host process is not running as administrator"); } } private void InitializeMonitor(string sessionName, MonitorTypes monitorTypes, OutputFormat outputFormat, IEventFilter eventFilter, IEventStorage eventStorage, TimeSpan? interval = null, int? threshold = null, long? hostId = null, ILogger logger = null) { _logger = logger; _hostID = hostId; _interval = interval; _threshold = threshold; _eventFilter = eventFilter; _eventStorage = eventStorage; _selectedOutputFormatter = _outputFormatters.FirstOrDefault(a => a.Formatter == outputFormat); if (string.IsNullOrEmpty(sessionName)) { throw new ArgumentNullException(nameof(sessionName)); } _session = new TraceEventSession(sessionName); LogDebug($"Starting ETW Session ({sessionName})"); var enabledMonitors = monitorTypes == MonitorTypes.All ? _monitors : _monitors.Where(a => monitorTypes.HasFlag(a.MonitorType)).ToList(); _session.EnableKernelProvider(enabledMonitors.Where(a => a.KernelEventTracing).Select(a => a.KeyWordMap).ToKeywords()); foreach (var monitor in enabledMonitors) { switch (monitor.MonitorType) { case MonitorTypes.FileRead: _session.Source.Kernel.DiskIORead += Kernel_DiskIORead; break; case MonitorTypes.FileWrite: _session.Source.Kernel.DiskIOWrite += Kernel_DiskIOWrite; break; case MonitorTypes.FileDelete: _session.Source.Kernel.FileIOFileDelete += Kernel_FileIOFileDelete; break; case MonitorTypes.ImageLoad: _session.Source.Kernel.ImageLoad += Kernel_ImageLoad; break; case MonitorTypes.ImageUnload: _session.Source.Kernel.ImageUnload += Kernel_ImageUnload; break; case MonitorTypes.ProcessStart: _session.Source.Kernel.ProcessStart += Kernel_ProcessStart; break; case MonitorTypes.ProcessStop: _session.Source.Kernel.ProcessStop += Kernel_ProcessStop; break; case MonitorTypes.RegistryCreate: _session.Source.Kernel.RegistryCreate += Kernel_RegistryCreate; break; case MonitorTypes.RegistryOpen: _session.Source.Kernel.RegistryOpen += Kernel_RegistryOpen; break; case MonitorTypes.RegistryDelete: _session.Source.Kernel.RegistryDelete += Kernel_RegistryDelete; break; case MonitorTypes.RegistryUpdate: _session.Source.Kernel.RegistrySetValue += Kernel_RegistrySetValue; break; case MonitorTypes.TcpConnect: _session.Source.Kernel.TcpIpConnect += Kernel_TcpIpConnect; break; case MonitorTypes.TcpDisconnect: _session.Source.Kernel.TcpIpDisconnect += Kernel_TcpIpDisconnect; break; case MonitorTypes.TcpReceive: _session.Source.Kernel.TcpIpRecv += Kernel_TcpIpRecv; break; case MonitorTypes.TcpSend: _session.Source.Kernel.TcpIpSend += Kernel_TcpIpSend; break; case MonitorTypes.UdpSend: _session.Source.Kernel.UdpIpSend += Kernel_UdpIpSend; break; case MonitorTypes.UdpReceive: _session.Source.Kernel.UdpIpRecv += Kernel_UdpIpRecv; break; case MonitorTypes.EventLogs: #pragma warning disable CA1416 // Validate platform compatibility var eventLog = new EventLog("Application", "."); eventLog.EntryWritten += EventLog_EntryWritten; eventLog.EnableRaisingEvents = true; #pragma warning restore CA1416 // Validate platform compatibility break; } } _session.Source.Process(); } public void Start(string sessionName = DefaultSessionName, MonitorTypes monitorTypes = MonitorTypes.All, OutputFormat outputFormat = OutputFormat.JSON, IEventFilter eventFilter = null, IEventStorage eventStorage = null, TimeSpan? interval = null, int? threshold = null, long? hostId = null, ILogger logger = null) { Task.Run(() => { InitializeMonitor(sessionName, monitorTypes, outputFormat, eventFilter, eventStorage, interval, threshold, hostId, logger); }, _ctSource.Token); } private void LogDebug(string message) { LogMessage(LogLevel.Debug, message); } private void LogError(string message) { LogMessage(LogLevel.Error, message); } private void LogMessage(LogLevel level, string message) { _logger?.Log(level, message); } private void ParseKernelEvent(MonitorTypes monitorType, TraceEvent item) { var monitor = _monitors.FirstOrDefault(a => a.MonitorType == monitorType); if (monitor == null) { throw new Exception($"{monitorType} could not be mapped"); } var data = monitor.ParseKernel(item); if (data == null) { LogDebug($"{monitorType} event data null was null - ignoring"); return; } Parse(monitorType, data); } private async void Parse(MonitorTypes monitorType, object data) { if (_eventFilter != null && _eventFilter.IsFilteredOut(monitorType, data)) { // Filtered out based on the implementation - do not fire the event return; } var containerItem = new ETWEventContainerItem { id = Guid.NewGuid(), hostid = _hostID ?? 0, MonitorType = monitorType, Format = _selectedOutputFormatter.Formatter, Payload = _selectedOutputFormatter.ConvertData(data), Timestamp = DateTimeOffset.Now, hostname = Environment.MachineName }; // If either is set assume batching if (_interval.HasValue || _threshold.HasValue) { if ((_interval.HasValue && DateTime.Now.Subtract(_lastPush) > _interval.Value) || (_threshold.HasValue && _throttledItems.Count > _threshold.Value)) { var result = await _eventStorage.WriteBatchEventAsync(_throttledItems.ToList()); if (!result) { LogError($"Could not write batch of throttled items"); return; } _throttledItems.Clear(); _lastPush = DateTime.Now; return; } _throttledItems.Add(containerItem); return; } if (_eventStorage != null) { var result = await _eventStorage.WriteEventAsync(containerItem); if (!result) { LogError($"Could not write {containerItem} to Storage"); } return; } OnEvent?.Invoke(this, containerItem); } private void ParseEvent(MonitorTypes monitorType, object item) { var data = _monitors.FirstOrDefault(a => a.MonitorType == monitorType)?.Parse(item); if (data == null) { throw new Exception($"{monitorType} could not be mapped"); } Parse(monitorType, data); } #pragma warning disable CA1416 // Validate platform compatibility private void EventLog_EntryWritten(object sender, EntryWrittenEventArgs obj) => ParseEvent(MonitorTypes.EventLogs, obj.Entry); #pragma warning restore CA1416 // Validate platform compatibility private void Kernel_UdpIpRecv(Microsoft.Diagnostics.Tracing.Parsers.Kernel.UdpIpTraceData obj) => ParseKernelEvent(MonitorTypes.UdpReceive, obj); private void Kernel_UdpIpSend(Microsoft.Diagnostics.Tracing.Parsers.Kernel.UdpIpTraceData obj) => ParseKernelEvent(MonitorTypes.UdpSend, obj); private void Kernel_DiskIOWrite(Microsoft.Diagnostics.Tracing.Parsers.Kernel.DiskIOTraceData obj) => ParseKernelEvent(MonitorTypes.FileWrite, obj); private void Kernel_FileIOFileDelete(Microsoft.Diagnostics.Tracing.Parsers.Kernel.FileIONameTraceData obj) => ParseKernelEvent(MonitorTypes.FileDelete, obj); private void Kernel_TcpIpConnect(Microsoft.Diagnostics.Tracing.Parsers.Kernel.TcpIpConnectTraceData obj) => ParseKernelEvent(MonitorTypes.TcpConnect, obj); private void Kernel_TcpIpDisconnect(Microsoft.Diagnostics.Tracing.Parsers.Kernel.TcpIpTraceData obj) => ParseKernelEvent(MonitorTypes.TcpDisconnect, obj); private void Kernel_TcpIpRecv(Microsoft.Diagnostics.Tracing.Parsers.Kernel.TcpIpTraceData obj) => ParseKernelEvent(MonitorTypes.TcpReceive, obj); private void Kernel_TcpIpSend(Microsoft.Diagnostics.Tracing.Parsers.Kernel.TcpIpSendTraceData obj) => ParseKernelEvent(MonitorTypes.TcpSend, obj); private void Kernel_RegistryCreate(Microsoft.Diagnostics.Tracing.Parsers.Kernel.RegistryTraceData obj) => ParseKernelEvent(MonitorTypes.RegistryCreate, obj); private void Kernel_RegistryDelete(Microsoft.Diagnostics.Tracing.Parsers.Kernel.RegistryTraceData obj) => ParseKernelEvent(MonitorTypes.RegistryDelete, obj); private void Kernel_RegistryOpen(Microsoft.Diagnostics.Tracing.Parsers.Kernel.RegistryTraceData obj) => ParseKernelEvent(MonitorTypes.RegistryOpen, obj); private void Kernel_RegistrySetValue(Microsoft.Diagnostics.Tracing.Parsers.Kernel.RegistryTraceData obj) => ParseKernelEvent(MonitorTypes.RegistryUpdate, obj); private void Kernel_DiskIORead(Microsoft.Diagnostics.Tracing.Parsers.Kernel.DiskIOTraceData obj) => ParseKernelEvent(MonitorTypes.FileRead, obj); private void Kernel_ProcessStop(Microsoft.Diagnostics.Tracing.Parsers.Kernel.ProcessTraceData obj) => ParseKernelEvent(MonitorTypes.ProcessStop, obj); private void Kernel_ProcessStart(Microsoft.Diagnostics.Tracing.Parsers.Kernel.ProcessTraceData obj) => ParseKernelEvent(MonitorTypes.ProcessStart, obj); private void Kernel_ImageLoad(Microsoft.Diagnostics.Tracing.Parsers.Kernel.ImageLoadTraceData obj) => ParseKernelEvent(MonitorTypes.ImageLoad, obj); private void Kernel_ImageUnload(Microsoft.Diagnostics.Tracing.Parsers.Kernel.ImageLoadTraceData obj) => ParseKernelEvent(MonitorTypes.ImageUnload, obj); public void Stop() { _ctSource?.Cancel(); _session?.Stop(true); _eventStorage?.Shutdown(); } public void Dispose() { _ctSource.Cancel(); _session.Stop(true); _eventStorage?.Shutdown(); GC.SuppressFinalize(this); } } }
38.874667
159
0.603855
[ "MIT" ]
drew-greenwald/WET
WET.lib/ETWMonitor.cs
14,580
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the storagegateway-2013-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.StorageGateway.Model { /// <summary> /// Container for the parameters to the ListFileShares operation. /// Gets a list of the file shares for a specific file gateway, or the list of file shares /// that belong to the calling user account. This operation is only supported in the file /// gateway type. /// </summary> public partial class ListFileSharesRequest : AmazonStorageGatewayRequest { private string _gatewayARN; private int? _limit; private string _marker; /// <summary> /// Gets and sets the property GatewayARN. /// <para> /// The Amazon resource Name (ARN) of the gateway whose file shares you want to list. /// If this field is not present, all file shares under your account are listed. /// </para> /// </summary> public string GatewayARN { get { return this._gatewayARN; } set { this._gatewayARN = value; } } // Check to see if GatewayARN property is set internal bool IsSetGatewayARN() { return this._gatewayARN != null; } /// <summary> /// Gets and sets the property Limit. /// <para> /// The maximum number of file shares to return in the response. The value must be an /// integer with a value greater than zero. Optional. /// </para> /// </summary> public int Limit { get { return this._limit.GetValueOrDefault(); } set { this._limit = value; } } // Check to see if Limit property is set internal bool IsSetLimit() { return this._limit.HasValue; } /// <summary> /// Gets and sets the property Marker. /// <para> /// Opaque pagination token returned from a previous ListFileShares operation. If present, /// <code>Marker</code> specifies where to continue the list from after a previous call /// to ListFileShares. Optional. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } } }
32.475248
112
0.61372
[ "Apache-2.0" ]
HaiNguyenMediaStep/aws-sdk-net
sdk/src/Services/StorageGateway/Generated/Model/ListFileSharesRequest.cs
3,280
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Mediapipe.Unity.FaceDetection { public class FaceDetectionSolution : Solution { [SerializeField] RawImage screen; [SerializeField] DetectionListAnnotationController faceDetectionsAnnotationController; [SerializeField] FaceDetectionGraph graphRunner; [SerializeField] TextureFramePool textureFramePool; Coroutine coroutine; public RunningMode runningMode; public FaceDetectionGraph.ModelType modelType { get { return graphRunner.modelType; } set { graphRunner.modelType = value; } } public long timeoutMillisec { get { return graphRunner.timeoutMillisec; } set { graphRunner.SetTimeoutMillisec(value); } } public override void Play() { if (coroutine != null) { Stop(); } base.Play(); coroutine = StartCoroutine(Run()); } public override void Pause() { base.Pause(); ImageSourceProvider.imageSource.Pause(); } public override void Resume() { base.Resume(); StartCoroutine(ImageSourceProvider.imageSource.Resume()); } public override void Stop() { base.Stop(); StopCoroutine(coroutine); ImageSourceProvider.imageSource.Stop(); graphRunner.Stop(); } IEnumerator Run() { var graphInitRequest = graphRunner.WaitForInit(); var imageSource = ImageSourceProvider.imageSource; yield return imageSource.Play(); if (!imageSource.isPrepared) { Logger.LogError(TAG, "Failed to start ImageSource, exiting..."); yield break; } // NOTE: The screen will be resized later, keeping the aspect ratio. SetupScreen(screen, imageSource); screen.texture = imageSource.GetCurrentTexture(); Logger.LogInfo(TAG, $"Model Selection = {modelType}"); Logger.LogInfo(TAG, $"Running Mode = {runningMode}"); yield return graphInitRequest; if (graphInitRequest.isError) { Logger.LogError(TAG, graphInitRequest.error); yield break; } if (runningMode == RunningMode.Async) { graphRunner.OnFaceDetectionsOutput.AddListener(OnFaceDetectionsOutput); graphRunner.StartRunAsync(imageSource).AssertOk(); } else { graphRunner.StartRun(imageSource).AssertOk(); } // Use RGBA32 as the input format. // TODO: When using GpuBuffer, MediaPipe assumes that the input format is BGRA, so the following code must be fixed. textureFramePool.ResizeTexture(imageSource.textureWidth, imageSource.textureHeight, TextureFormat.RGBA32); SetupAnnotationController(faceDetectionsAnnotationController, imageSource); while (true) { yield return new WaitWhile(() => isPaused); var textureFrameRequest = textureFramePool.WaitForNextTextureFrame(); yield return textureFrameRequest; var textureFrame = textureFrameRequest.result; // Copy current image to TextureFrame ReadFromImageSource(textureFrame, runningMode, graphRunner.configType); graphRunner.AddTextureFrameToInputStream(textureFrame).AssertOk(); if (runningMode == RunningMode.Sync) { // When running synchronously, wait for the outputs here (blocks the main thread). var detections = graphRunner.FetchNextValue(); faceDetectionsAnnotationController.DrawNow(detections); } yield return new WaitForEndOfFrame(); } } void OnFaceDetectionsOutput(List<Detection> detections) { faceDetectionsAnnotationController.DrawLater(detections); } } }
31.869565
122
0.690314
[ "MIT" ]
DoksaVPC/MediaPipeUnityPlugin
Assets/Mediapipe/Samples/Scenes/Face Detection/FaceDetectionSolution.cs
3,665
C#
namespace BehaviourTree.FluentBuilder.Nodes { public sealed class UntilFailedNode : DecoratorNode { } }
14.75
55
0.720339
[ "MIT" ]
AnotherEnd15/BehaviourTree
src/BehaviourTree.FluentBuilder/Nodes/UntilFailedNode.cs
120
C#
namespace Fubu.Templating { public interface ITemplateStep { string Describe(TemplatePlanContext context); void Execute(TemplatePlanContext context); } }
23.5
54
0.680851
[ "Apache-2.0" ]
ketiko/fubumvc
src/Fubu/Templating/ITemplateStep.cs
188
C#
using Newtonsoft.Json; using SelectelSharp.Common; using SelectelSharp.Headers; using System; namespace SelectelSharp.Models.File { public class FileInfo { /// <summary> /// Имя файла /// </summary> public string Name { get; set; } /// <summary> /// Размер файла /// </summary> [Header(HeaderKeys.ContentLenght)] public long Bytes { get; set; } /// <summary> /// Тип файла /// </summary> [JsonProperty("content_type")] [Header(HeaderKeys.ContentType)] public string ContentType { get; set; } /// <summary> /// MD5 Hash /// </summary> [Header(HeaderKeys.ETag)] public string Hash { get; set; } /// <summary> /// Время изменения файла /// </summary> [JsonProperty("last_modified")] [Header(HeaderKeys.LastModified)] public DateTime LastModified { get; set; } /// <summary> /// Время создания файла /// </summary> [Header(HeaderKeys.Date)] public DateTime Date { get; set; } } }
23.979167
50
0.528236
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
redistributable/SelectelSharp/Models/File/FileInfo.cs
1,217
C#
using Fusion.Resources.Database; using Fusion.Resources.Database.Entities; using Fusion.Resources.Logic.Requests; using Fusion.Resources.Logic.Workflows; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Fusion.Resources.Logic.Commands { public partial class ResourceAllocationRequest { public class CanApproveStepHandler : CanApproveStepHandlerBase, INotificationHandler<CanApproveStep> { private static readonly Dictionary<WorkflowAccessKey, WorkflowAccess> AccessTable = new Dictionary<WorkflowAccessKey, WorkflowAccess> { [(AllocationNormalWorkflowV1.SUBTYPE, AllocationNormalWorkflowV1.CREATED)] = WorkflowAccess.Default with { IsResourceOwnerAllowed = true, IsAllResourceOwnersAllowed = true, }, [(AllocationNormalWorkflowV1.SUBTYPE, AllocationNormalWorkflowV1.APPROVAL)] = WorkflowAccess.Default with { IsDirectTaskOwnerAllowed = true, IsOrgAdminAllowed = true, IsOrgChartWriteAllowed = true, IsCreatorAllowed = true }, [(AllocationDirectWorkflowV1.SUBTYPE, WorkflowDefinition.PROVISIONING)] = WorkflowAccess.Default, [(AllocationDirectWorkflowV1.SUBTYPE, AllocationNormalWorkflowV1.CREATED)] = WorkflowAccess.Default with { IsResourceOwnerAllowed = true, IsAllResourceOwnersAllowed = true, }, [(AllocationDirectWorkflowV1.SUBTYPE, AllocationNormalWorkflowV1.APPROVAL)] = WorkflowAccess.Default with { IsDirectTaskOwnerAllowed = true, IsOrgAdminAllowed = true, IsOrgChartWriteAllowed = true, IsCreatorAllowed = true }, [(AllocationNormalWorkflowV1.SUBTYPE, WorkflowDefinition.PROVISIONING)] = WorkflowAccess.Default, [(AllocationJointVentureWorkflowV1.SUBTYPE, AllocationJointVentureWorkflowV1.CREATED)] = WorkflowAccess.Default with { IsResourceOwnerAllowed = true, IsParentResourceOwnerAllowed = true, IsSiblingResourceOwnerAllowed = true, IsCreatorAllowed = true, }, [(AllocationJointVentureWorkflowV1.SUBTYPE, WorkflowDefinition.PROVISIONING)] = WorkflowAccess.Default, [(AllocationEnterpriseWorkflowV1.SUBTYPE, WorkflowDefinition.PROVISIONING)] = WorkflowAccess.Default, [(AllocationDirectWorkflowV1.SUBTYPE, WorkflowDefinition.PROVISIONING)] = WorkflowAccess.Default, }; private readonly ResourcesDbContext dbContext; public CanApproveStepHandler( ResourcesDbContext dbContext, IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor) { this.dbContext = dbContext; } public async Task Handle(CanApproveStep notification, CancellationToken cancellationToken) { if (notification.Type != DbInternalRequestType.Allocation) return; var request = await dbContext.ResourceAllocationRequests .Include(p => p.Project) .FirstAsync(r => r.Id == notification.RequestId, cancellationToken: cancellationToken); var row = AccessTable[(request.SubType!.ToLower(), notification.CurrentStepId!)]; await CheckAccess(request, row); } } } }
44.269663
145
0.623096
[ "MIT" ]
equinor/fusion-app-resources
src/backend/api/Fusion.Resources.Logic/Requests/Commands/ResourceAllocationRequest/Allocation/CanApproveStepHandler.cs
3,942
C#
using System; using System.Linq; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using UIKit; [assembly: ResolutionGroupName("XamarinDocs")] [assembly: ExportEffect(typeof(TouchTracking.iOS.TouchEffect), "TouchEffect")] namespace TouchTracking.iOS { public class TouchEffect : PlatformEffect { UIView view; TouchRecognizer touchRecognizer; protected override void OnAttached() { // Get the iOS UIView corresponding to the Element that the effect is attached to view = Control == null ? Container : Control; // Get access to the TouchEffect class in the PCL TouchTracking.TouchEffect effect = (TouchTracking.TouchEffect)Element.Effects.FirstOrDefault(e => e is TouchTracking.TouchEffect); if (effect != null && view != null) { // Create a TouchRecognizer for this UIView touchRecognizer = new TouchRecognizer(Element, view, effect); view.AddGestureRecognizer(touchRecognizer); } } protected override void OnDetached() { if (touchRecognizer != null) { // Clean up the TouchRecognizer object touchRecognizer.Detach(); // Remove the TouchRecognizer from the UIView view.RemoveGestureRecognizer(touchRecognizer); } } } }
30.638298
142
0.615278
[ "Apache-2.0" ]
Alshaikh-Abdalrahman/jedoo
Effects/TouchTrackingEffectDemos/TouchTrackingEffectDemos/TouchTrackingEffectDemos.iOS/TouchEffect.cs
1,440
C#
using System; using System.Diagnostics.CodeAnalysis; namespace Auditing { [SuppressMessage("ReSharper", "UnusedMember.Global")] [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class AuditLog { public Guid Id { get; set; } public string RootEntityName { get; set; } public string EntityName { get; set; } public string EntityId { get; set; } public string OldValue { get; set; } public string NewValue { get; set; } public DateTimeOffset ChangedAt { get; set; } public string State { get; set; } public string ChangedBy { get; set; } public string RootEntityId { get; set; } } }
32.090909
71
0.637394
[ "MIT" ]
yousefataya/HRMS
source/Database/Auditing/AuditLog.cs
706
C#
// Copyright (c) Microsoft Open Technologies, Inc. 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.IO; using System.Linq; using System.Xml; namespace CSharpSyntaxGenerator { class SourceWriter : AbstractFileWriter { private SourceWriter(TextWriter writer, Tree tree) : base(writer, tree) { } public static void Write(TextWriter writer, Tree tree) { new SourceWriter(writer, tree).WriteFile(); } private void WriteFile() { WriteLine("// <auto-generated />"); WriteLine(); WriteLine("using System;"); WriteLine("using System.Collections;"); WriteLine("using System.Collections.Generic;"); WriteLine("using System.Linq;"); WriteLine("using System.Threading;"); WriteLine("using Roslyn.Utilities;"); WriteLine(); WriteLine("namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax"); WriteLine("{"); WriteLine(); this.WriteGreenTypes(); this.WriteGreenVisitors(); this.WriteGreenRewriter(); this.WriteContextualGreenFactories(); this.WriteStaticGreenFactories(); WriteLine("}"); WriteLine(); WriteLine("namespace Microsoft.CodeAnalysis.CSharp.Syntax"); WriteLine("{"); WriteLine(); this.WriteRedTypes(); WriteLine("}"); WriteLine(); WriteLine("namespace Microsoft.CodeAnalysis.CSharp"); WriteLine("{"); WriteLine(" using Microsoft.CodeAnalysis.CSharp.Syntax;"); WriteLine(); this.WriteRedVisitors(); this.WriteRedRewriter(); this.WriteRedFactories(); WriteLine("}"); } private void WriteGreenTypes() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode)).ToList(); for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i]; WriteLine(); this.WriteGreenType(node); } } private void WriteGreenType(TreeType node) { WriteComment(node.TypeComment, " "); if (node is AbstractNode) { AbstractNode nd = (AbstractNode)node; WriteLine(" internal abstract partial class {0} : {1}", node.Name, node.Base); WriteLine(" {"); // ctor with diagnostics and annotations WriteLine(" internal {0}(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations)", node.Name); WriteLine(" : base(kind, diagnostics, annotations)"); WriteLine(" {"); if (node.Name == "DirectiveTriviaSyntax") { WriteLine(" this.flags |= NodeFlags.ContainsDirectives;"); } WriteLine(" }"); // ctor without diagnostics and annotations WriteLine(" internal {0}(SyntaxKind kind)", node.Name); WriteLine(" : base(kind)"); WriteLine(" {"); if (node.Name == "DirectiveTriviaSyntax") { WriteLine(" this.flags |= NodeFlags.ContainsDirectives;"); } WriteLine(" }"); // object reader constructor WriteLine(); WriteLine(" protected {0}(ObjectReader reader)", node.Name); WriteLine(" : base(reader)"); WriteLine(" {"); if (node.Name == "DirectiveTriviaSyntax") { WriteLine(" this.flags |= NodeFlags.ContainsDirectives;"); } WriteLine(" }"); var valueFields = nd.Fields.Where(n => !IsNodeOrNodeList(n.Type)).ToList(); var nodeFields = nd.Fields.Where(n => IsNodeOrNodeList(n.Type)).ToList(); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (IsNodeOrNodeList(field.Type)) { WriteLine(); WriteComment(field.PropertyComment, " "); WriteLine(" public abstract {0}{1} {2} {{ get; }}", (IsNew(field) ? "new " : ""), field.Type, field.Name); } } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; WriteLine(); WriteComment(field.PropertyComment, " "); WriteLine(" public abstract {0}{1} {2} {{ get; }}", (IsNew(field) ? "new " : ""), field.Type, field.Name); } WriteLine(" }"); } else if (node is Node) { Node nd = (Node)node; WriteLine(" internal sealed partial class {0} : {1}", node.Name, node.Base); WriteLine(" {"); var valueFields = nd.Fields.Where(n => !IsNodeOrNodeList(n.Type)).ToList(); var nodeFields = nd.Fields.Where(n => IsNodeOrNodeList(n.Type)).ToList(); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; var type = GetFieldType(field); WriteLine(" internal readonly {0} {1};", type, CamelCase(field.Name)); } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; WriteLine(" internal readonly {0} {1};", field.Type, CamelCase(field.Name)); } // write constructor with diagnostics and annotations WriteLine(); Write(" internal {0}(SyntaxKind kind", node.Name); WriteGreenNodeConstructorArgs(nodeFields, valueFields); WriteLine(", DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations)"); WriteLine(" : base(kind, diagnostics, annotations)"); WriteLine(" {"); WriteCtorBody(valueFields, nodeFields); WriteLine(" }"); WriteLine(); // write constructor with async WriteLine(); Write(" internal {0}(SyntaxKind kind", node.Name); WriteGreenNodeConstructorArgs(nodeFields, valueFields); WriteLine(", SyntaxFactoryContext context)"); WriteLine(" : base(kind)"); WriteLine(" {"); WriteLine(" this.SetFactoryContext(context);"); WriteCtorBody(valueFields, nodeFields); WriteLine(" }"); WriteLine(); // write constructor without diagnostics and annotations WriteLine(); Write(" internal {0}(SyntaxKind kind", node.Name); WriteGreenNodeConstructorArgs(nodeFields, valueFields); WriteLine(")"); WriteLine(" : base(kind)"); WriteLine(" {"); WriteCtorBody(valueFields, nodeFields); WriteLine(" }"); WriteLine(); // property accessors for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; WriteComment(field.PropertyComment, " "); if (IsNodeList(field.Type)) { WriteLine(" public {0}{1} {2} {{ get {{ return new {1}(this.{3}); }} }}", OverrideOrNewModifier(field), field.Type, field.Name, CamelCase(field.Name) ); } else if (IsSeparatedNodeList(field.Type)) { WriteLine(" public {0}{1} {2} {{ get {{ return new {1}(new SyntaxList<CSharpSyntaxNode>(this.{3})); }} }}", OverrideOrNewModifier(field), field.Type, field.Name, CamelCase(field.Name), i ); } else if (field.Type == "SyntaxNodeOrTokenList") { WriteLine(" public {0}SyntaxList<CSharpSyntaxNode> {1} {{ get {{ return new SyntaxList<CSharpSyntaxNode>(this.{2}); }} }}", OverrideOrNewModifier(field), field.Name, CamelCase(field.Name) ); } else { WriteLine(" public {0}{1} {2} {{ get {{ return this.{3}; }} }}", OverrideOrNewModifier(field), field.Type, field.Name, CamelCase(field.Name) ); } } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; WriteComment(field.PropertyComment, " "); WriteLine(" public {0}{1} {2} {{ get {{ return this.{3}; }} }}", OverrideOrNewModifier(field), field.Type, field.Name, CamelCase(field.Name) ); } // GetSlot WriteLine(); WriteLine(" internal override GreenNode GetSlot(int index)"); WriteLine(" {"); WriteLine(" switch (index)"); WriteLine(" {"); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; WriteLine(" case {0}: return this.{1};", i, CamelCase(field.Name)); } WriteLine(" default: return null;"); WriteLine(" }"); WriteLine(" }"); WriteLine(); WriteLine(" internal override SyntaxNode CreateRed(SyntaxNode parent, int position)"); WriteLine(" {"); WriteLine(" return new CSharp.Syntax.{0}(this, parent, position);", node.Name); WriteLine(" }"); this.WriteGreenAcceptMethods(nd); this.WriteGreenUpdateMethod(nd); this.WriteSetDiagnostics(nd); this.WriteSetAnnotations(nd); this.WriteGreenSerialization(nd); WriteLine(" }"); } } private void WriteGreenNodeConstructorArgs(List<Field> nodeFields, List<Field> valueFields) { for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; string type = GetFieldType(field); Write(", {0} {1}", type, CamelCase(field.Name)); } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; Write(", {0} {1}", field.Type, CamelCase(field.Name)); } } private void WriteGreenSerialization(Node node) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)).ToList(); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)).ToList(); // object reader constructor WriteLine(); WriteLine(" internal {0}(ObjectReader reader)", node.Name); WriteLine(" : base(reader)"); WriteLine(" {"); WriteLine(" this.SlotCount = {0};", nodeFields.Count); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; string type = GetFieldType(field); WriteLine(" var {0} = ({1})reader.ReadValue();", CamelCase(field.Name), type); WriteLine(" if ({0} != null)", CamelCase(field.Name)); WriteLine(" {"); WriteLine(" AdjustFlagsAndWidth({0});", CamelCase(field.Name)); WriteLine(" this.{0} = {0};", CamelCase(field.Name), type); WriteLine(" }"); } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; string type = GetFieldType(field); WriteLine(" this.{0} = ({1})reader.{2}();", CamelCase(field.Name), type, GetReaderMethod(type)); } WriteLine(" }"); // IWritable WriteLine(); WriteLine(" internal override void WriteTo(ObjectWriter writer)"); WriteLine(" {"); WriteLine(" base.WriteTo(writer);"); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; string type = GetFieldType(field); WriteLine(" writer.WriteValue(this.{0});", CamelCase(field.Name)); } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; var type = GetFieldType(field); WriteLine(" writer.{0}(this.{1});", GetWriterMethod(type), CamelCase(field.Name)); } WriteLine(" }"); // IReadable WriteLine(); WriteLine(" internal override Func<ObjectReader, object> GetReader()"); WriteLine(" {"); WriteLine(" return r => new {0}(r);", node.Name); WriteLine(" }"); } private string GetWriterMethod(string type) { switch (type) { case "bool": return "WriteBoolean"; default: throw new InvalidOperationException(string.Format("Type '{0}' not supported for object reader serialization.", type)); } } private string GetReaderMethod(string type) { switch (type) { case "bool": return "ReadBoolean"; default: throw new InvalidOperationException(string.Format("Type '{0}' not supported for object reader serialization.", type)); } } private void WriteCtorBody(List<Field> valueFields, List<Field> nodeFields) { // constructor body WriteLine(" this.SlotCount = {0};", nodeFields.Count); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (IsAnyList(field.Type) || IsOptional(field)) { WriteLine(" if ({0} != null)", CamelCase(field.Name)); WriteLine(" {"); WriteLine(" this.AdjustFlagsAndWidth({0});", CamelCase(field.Name)); WriteLine(" this.{0} = {0};", CamelCase(field.Name)); WriteLine(" }"); } else { WriteLine(" this.AdjustFlagsAndWidth({0});", CamelCase(field.Name)); WriteLine(" this.{0} = {0};", CamelCase(field.Name)); } } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; WriteLine(" this.{0} = {0};", CamelCase(field.Name)); } } private void WriteSetAnnotations(Node node) { WriteLine(); WriteLine(" internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations)"); WriteLine(" {"); Write(" return new {0}(", node.Name); Write("this.Kind, "); for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); Write("this.{0}", CamelCase(field.Name)); } WriteLine(", GetDiagnostics(), annotations);"); WriteLine(" }"); } private void WriteSetDiagnostics(Node node) { WriteLine(); WriteLine(" internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics)"); WriteLine(" {"); Write(" return new {0}(", node.Name); Write("this.Kind, "); for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); Write("this.{0}", CamelCase(field.Name)); } WriteLine(", diagnostics, GetAnnotations());"); WriteLine(" }"); } private void WriteGreenAcceptMethods(Node node) { //WriteLine(); //WriteLine(" public override TResult Accept<TArgument, TResult>(SyntaxVisitor<TArgument, TResult> visitor, TArgument argument)"); //WriteLine(" {"); //WriteLine(" return visitor.Visit{0}(this, argument);", StripPost(node.Name, "Syntax")); //WriteLine(" }"); WriteLine(); WriteLine(" public override TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor)"); WriteLine(" {"); WriteLine(" return visitor.Visit{0}(this);", StripPost(node.Name, "Syntax")); WriteLine(" }"); WriteLine(); WriteLine(" public override void Accept(CSharpSyntaxVisitor visitor)"); WriteLine(" {"); WriteLine(" visitor.Visit{0}(this);", StripPost(node.Name, "Syntax")); WriteLine(" }"); } private void WriteGreenVisitors() { //WriteGreenVisitor(true, true); //WriteLine(); WriteGreenVisitor(false, true); WriteLine(); WriteGreenVisitor(false, false); } private void WriteGreenVisitor(bool withArgument, bool withResult) { var nodes = Tree.Types.Where(n => !(n is PredefinedNode)).ToList(); WriteLine(); WriteLine(" internal partial class CSharpSyntaxVisitor" + (withResult ? "<" + (withArgument ? "TArgument, " : "") + "TResult>" : "")); WriteLine(" {"); int nWritten = 0; for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i] as Node; if (node != null) { if (nWritten > 0) WriteLine(); nWritten++; WriteLine(" public virtual " + (withResult ? "TResult" : "void") + " Visit{0}({1} node{2})", StripPost(node.Name, "Syntax"), node.Name, withArgument ? ", TArgument argument" : ""); WriteLine(" {"); WriteLine(" " + (withResult ? "return " : "") + "this.DefaultVisit(node{0});", withArgument ? ", argument" : ""); WriteLine(" }"); } } WriteLine(" }"); } private void WriteGreenUpdateMethod(Node node) { WriteLine(); Write(" public {0} Update(", node.Name); // parameters for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); var type = field.Type == "SyntaxNodeOrTokenList" ? "SyntaxList<CSharpSyntaxNode>" : field.Type == "SyntaxTokenList" ? "SyntaxList<SyntaxToken>" : field.Type; Write("{0} {1}", type, CamelCase(field.Name)); } WriteLine(")"); WriteLine(" {"); Write(" if ("); int nCompared = 0; for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (IsDerivedOrListOfDerived("SyntaxNode", field.Type) || IsDerivedOrListOfDerived("SyntaxToken", field.Type) || field.Type == "SyntaxNodeOrTokenList") { if (nCompared > 0) Write(" || "); Write("{0} != this.{1}", CamelCase(field.Name), field.Name); nCompared++; } } if (nCompared > 0) { WriteLine(")"); WriteLine(" {"); Write(" var newNode = SyntaxFactory.{0}(", StripPost(node.Name, "Syntax")); if (node.Kinds.Count > 1) { Write("this.Kind, "); } for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); Write(CamelCase(field.Name)); } WriteLine(");"); WriteLine(" var diags = this.GetDiagnostics();"); WriteLine(" if (diags != null && diags.Length > 0)"); WriteLine(" newNode = newNode.WithDiagnosticsGreen(diags);"); WriteLine(" var annotations = this.GetAnnotations();"); WriteLine(" if (annotations != null && annotations.Length > 0)"); WriteLine(" newNode = newNode.WithAnnotationsGreen(annotations);"); WriteLine(" return newNode;"); WriteLine(" }"); } WriteLine(); WriteLine(" return this;"); WriteLine(" }"); } private void WriteGreenRewriter() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode)).ToList(); WriteLine(); WriteLine(" internal partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<CSharpSyntaxNode>"); WriteLine(" {"); int nWritten = 0; for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i] as Node; if (node != null) { var nodeFields = node.Fields.Where(nd => IsNodeOrNodeList(nd.Type)).ToList(); if (nWritten > 0) WriteLine(); nWritten++; WriteLine(" public override CSharpSyntaxNode Visit{0}({1} node)", StripPost(node.Name, "Syntax"), node.Name); WriteLine(" {"); for (int f = 0; f < nodeFields.Count; f++) { var field = nodeFields[f]; if (IsAnyList(field.Type)) { WriteLine(" var {0} = this.VisitList(node.{1});", CamelCase(field.Name), field.Name); } else { WriteLine(" var {0} = ({1})this.Visit(node.{2});", CamelCase(field.Name), field.Type, field.Name); } } if (nodeFields.Count > 0) { Write(" return node.Update("); for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); if (IsNodeOrNodeList(field.Type)) { Write(CamelCase(field.Name)); } else { Write("node.{0}", field.Name); } } WriteLine(");"); } else { WriteLine(" return node;"); } WriteLine(" }"); } } WriteLine(" }"); } private void WriteContextualGreenFactories() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)).ToList(); WriteLine(); WriteLine(" internal class ContextAwareSyntax"); WriteLine(" {"); WriteLine(); WriteLine(" private SyntaxFactoryContext context;"); WriteLine(); WriteLine(); WriteLine(" public ContextAwareSyntax(SyntaxFactoryContext context)"); WriteLine(" {"); WriteLine(" this.context = context;"); WriteLine(" }"); WriteGreenFactories(nodes, withSyntaxFactoryContext: true); WriteLine(" }"); } private void WriteStaticGreenFactories() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)).ToList(); WriteLine(); WriteLine(" internal static partial class SyntaxFactory"); WriteLine(" {"); WriteGreenFactories(nodes); WriteGreenTypeList(); WriteLine(" }"); } private void WriteGreenFactories(List<TreeType> nodes, bool withSyntaxFactoryContext = false) { for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i]; this.WriteGreenFactory((Node)node, withSyntaxFactoryContext); if (i < n - 1) WriteLine(); } } private void WriteGreenTypeList() { WriteLine(); WriteLine(" internal static IEnumerable<Type> GetNodeTypes()"); WriteLine(" {"); WriteLine(" return new Type[] {"); var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)).ToList(); for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i]; Write(" typeof({0})", node.Name); if (i < n - 1) Write(","); WriteLine(); } WriteLine(" };"); WriteLine(" }"); } private void WriteGreenFactory(Node nd, bool withSyntaxFactoryContext = false) { var valueFields = nd.Fields.Where(n => !IsNodeOrNodeList(n.Type)).ToList(); var nodeFields = nd.Fields.Where(n => IsNodeOrNodeList(n.Type)).ToList(); bool anyList = false; Write(" public {0}{1} {2}(", withSyntaxFactoryContext ? "" : "static ", nd.Name, StripPost(nd.Name, "Syntax")); if (nd.Kinds.Count > 1) { Write("SyntaxKind kind, "); } for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (i > 0) Write(", "); anyList |= IsAnyList(field.Type); var type = field.Type; if (type == "SyntaxNodeOrTokenList") type = "SyntaxList<CSharpSyntaxNode>"; Write("{0} {1}", type, CamelCase(field.Name)); } WriteLine(")"); WriteLine(" {"); // validate kind if (nd.Kinds.Count > 1) { WriteLine(" switch (kind)"); WriteLine(" {"); foreach (var k in nd.Kinds) { WriteLine(" case SyntaxKind.{0}:", k.Name); } WriteLine(" break;"); WriteLine(" default:"); WriteLine(" throw new ArgumentException(\"kind\");"); WriteLine(" }"); } // validate parameters WriteLine("#if DEBUG"); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; var pname = CamelCase(field.Name); if (!IsAnyList(field.Type) && !IsOptional(field)) { WriteLine(" if ({0} == null)", CamelCase(field.Name)); WriteLine(" throw new ArgumentNullException(\"{0}\");", CamelCase(field.Name)); } if (field.Type == "SyntaxToken" && field.Kinds != null && field.Kinds.Count > 0) { if (IsOptional(field)) { WriteLine(" if ({0} != null)", CamelCase(field.Name)); WriteLine(" {"); } WriteLine(" switch ({0}.Kind)", pname); WriteLine(" {"); foreach (var kind in field.Kinds) { WriteLine(" case SyntaxKind.{0}:", kind.Name); } //we need to check for Kind=None as well as node == null because that's what the red factory will pass if (IsOptional(field)) { WriteLine(" case SyntaxKind.None:"); } WriteLine(" break;"); WriteLine(" default:"); WriteLine(" throw new ArgumentException(\"{0}\");", pname); WriteLine(" }"); if (IsOptional(field)) { WriteLine(" }"); } } } WriteLine("#endif"); if (nd.Name != "SkippedTokensTriviaSyntax" && nd.Name != "DocumentationCommentTriviaSyntax" && nd.Name != "IncompleteMemberSyntax" && valueFields.Count + nodeFields.Count <= 3) { //int hash; //var cached = SyntaxNodeCache.TryGetNode((int)SyntaxKind.IdentifierName, identifier, this.context, out hash); //if (cached != null) return (IdentifierNameSyntax)cached; //var result = new IdentifierNameSyntax(SyntaxKind.IdentifierName, identifier, this.context); //if (hash >= 0) //{ // SyntaxNodeCache.AddNode(result, hash); //} //return result; WriteLine(); //int hash; WriteLine(" int hash;"); //SyntaxNode cached = SyntaxNodeCache.TryGetNode(SyntaxKind.IdentifierName, identifier, this.context, out hash); Write(" var cached = SyntaxNodeCache.TryGetNode((int)"); WriteCtorArgList(nd, withSyntaxFactoryContext, valueFields, nodeFields); WriteLine(", out hash);"); // if (cached != null) return (IdentifierNameSyntax)cached; WriteLine(" if (cached != null) return ({0})cached;", nd.Name); WriteLine(); //var result = new IdentifierNameSyntax(SyntaxKind.IdentifierName, identifier); Write(" var result = new {0}(", nd.Name); WriteCtorArgList(nd, withSyntaxFactoryContext, valueFields, nodeFields); WriteLine(");"); //if (hash >= 0) WriteLine(" if (hash >= 0)"); //{ WriteLine(" {"); // SyntaxNodeCache.AddNode(result, hash); WriteLine(" SyntaxNodeCache.AddNode(result, hash);"); //} WriteLine(" }"); WriteLine(); //return result; WriteLine(" return result;"); } else { WriteLine(); Write(" return new {0}(", nd.Name); WriteCtorArgList(nd, withSyntaxFactoryContext, valueFields, nodeFields); WriteLine(");"); } WriteLine(" }"); } private void WriteCtorArgList(Node nd, bool withSyntaxFactoryContext, List<Field> valueFields, List<Field> nodeFields) { if (nd.Kinds.Count == 1) { Write("SyntaxKind."); Write(nd.Kinds[0].Name); } else { Write("kind"); } for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; Write(", "); if (field.Type == "SyntaxList<SyntaxToken>" || IsAnyList(field.Type)) { Write("{0}.Node", CamelCase(field.Name)); } else { Write(CamelCase(field.Name)); } } // values are at end for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; Write(", "); Write(CamelCase(field.Name)); } if (withSyntaxFactoryContext) { Write(", this.context"); } } private void WriteRedTypes() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode)).ToList(); for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i]; WriteLine(); this.WriteRedType(node); } } private void WriteRedType(TreeType node) { WriteComment(node.TypeComment, " "); if (node is AbstractNode) { AbstractNode nd = (AbstractNode)node; WriteLine(" public abstract partial class {0} : {1}", node.Name, node.Base); WriteLine(" {"); WriteLine(" internal {0}(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode parent, int position)", node.Name); WriteLine(" : base(green, parent, position)"); WriteLine(" {"); WriteLine(" }"); var valueFields = nd.Fields.Where(n => !IsNodeOrNodeList(n.Type)).ToList(); var nodeFields = nd.Fields.Where(n => IsNodeOrNodeList(n.Type)).ToList(); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (IsNodeOrNodeList(field.Type)) { //red SyntaxLists can't contain tokens, so we switch to SyntaxTokenList var fieldType = field.Type == "SyntaxList<SyntaxToken>" ? "SyntaxTokenList" : field.Type; WriteLine(); WriteComment(field.PropertyComment, " "); WriteLine(" public abstract {0}{1} {2} {{ get; }}", (IsNew(field) ? "new " : ""), fieldType, field.Name); } } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; WriteLine(); WriteComment(field.PropertyComment, " "); WriteLine(" public abstract {0}{1} {2} {{ get; }}", (IsNew(field) ? "new " : ""), field.Type, field.Name); } WriteLine(" }"); } else if (node is Node) { Node nd = (Node)node; WriteLine(" public sealed partial class {0} : {1}", node.Name, node.Base); WriteLine(" {"); var valueFields = nd.Fields.Where(n => !IsNodeOrNodeList(n.Type)).ToList(); var nodeFields = nd.Fields.Where(n => IsNodeOrNodeList(n.Type)).ToList(); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (field.Type != "SyntaxToken" && field.Type != "SyntaxList<SyntaxToken>" ) { if (IsSeparatedNodeList(field.Type) || field.Type == "SyntaxNodeOrTokenList") { WriteLine(" private SyntaxNode {0};", CamelCase(field.Name)); } else { var type = GetFieldType(field); WriteLine(" private {0} {1};", type, CamelCase(field.Name)); } } } // write constructor WriteLine(); WriteLine(" internal {0}(Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode green, SyntaxNode parent, int position)", node.Name); WriteLine(" : base(green, parent, position)"); WriteLine(" {"); WriteLine(" }"); WriteLine(); // property accessors for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (field.Type == "SyntaxToken") { WriteComment(field.PropertyComment, " "); WriteLine(" public {0}{1} {2} ", OverrideOrNewModifier(field), field.Type, field.Name); WriteLine(" {"); if (IsOptional(field)) { WriteLine(" get"); WriteLine(" {"); WriteLine(" var slot = ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.{0})this.Green).{1};", node.Name, CamelCase(field.Name)); WriteLine(" if (slot != null)"); WriteLine(" return new SyntaxToken(this, slot, {0}, {1});", GetChildPosition(i), GetChildIndex(i)); WriteLine(); WriteLine(" return default(SyntaxToken);"); WriteLine(" }"); } else { WriteLine(" get {{ return new SyntaxToken(this, ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.{0})this.Green).{1}, {2}, {3}); }}", node.Name, CamelCase(field.Name), GetChildPosition(i), GetChildIndex(i)); } WriteLine(" }"); } else if (field.Type == "SyntaxList<SyntaxToken>") { WriteComment(field.PropertyComment, " "); WriteLine(" public {0}SyntaxTokenList {1} ", OverrideOrNewModifier(field), field.Name); WriteLine(" {"); WriteLine(" get"); WriteLine(" {"); WriteLine(" var slot = this.Green.GetSlot({0});", i); WriteLine(" if (slot != null)"); WriteLine(" return new SyntaxTokenList(this, slot, {0}, {1});", GetChildPosition(i), GetChildIndex(i)); WriteLine(); WriteLine(" return default(SyntaxTokenList);"); WriteLine(" }"); WriteLine(" }"); } else { WriteComment(field.PropertyComment, " "); WriteLine(" public {0}{1} {2} ", OverrideOrNewModifier(field), field.Type, field.Name); WriteLine(" {"); WriteLine(" get"); WriteLine(" {"); if (IsNodeList(field.Type)) { WriteLine(" return new {0}(this.GetRed(ref this.{1}, {2}));", field.Type, CamelCase(field.Name), i); } else if (IsSeparatedNodeList(field.Type)) { WriteLine(" var red = this.GetRed(ref this.{0}, {1});", CamelCase(field.Name), i); WriteLine(" if (red != null)", i); WriteLine(" return new {0}(red, {1});", field.Type, GetChildIndex(i)); WriteLine(); WriteLine(" return default({0});", field.Type); } else if (field.Type == "SyntaxNodeOrTokenList") { throw new InvalidOperationException("field cannot be a random SyntaxNodeOrTokenList"); } else { if (i == 0) { WriteLine(" return this.GetRedAtZero(ref this.{0});", CamelCase(field.Name)); } else { WriteLine(" return this.GetRed(ref this.{0}, {1});", CamelCase(field.Name), i); } } WriteLine(" }"); WriteLine(" }"); } WriteLine(); } for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; WriteComment(field.PropertyComment, " "); WriteLine(" public {0}{1} {2} {{ get {{ return ((Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.{3})this.Green).{2}; }} }}", OverrideOrNewModifier(field), field.Type, field.Name, node.Name ); WriteLine(); } //GetNodeSlot forces creation of a red node. WriteLine(" internal override SyntaxNode GetNodeSlot(int index)"); WriteLine(" {"); WriteLine(" switch (index)"); WriteLine(" {"); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (field.Type != "SyntaxToken" && field.Type != "SyntaxList<SyntaxToken>") { if (i == 0) { WriteLine(" case {0}: return this.GetRedAtZero(ref this.{1});", i, CamelCase(field.Name)); } else { WriteLine(" case {0}: return this.GetRed(ref this.{1}, {0});", i, CamelCase(field.Name)); } } } WriteLine(" default: return null;"); WriteLine(" }"); WriteLine(" }"); //GetCachedSlot returns a red node if we have it. WriteLine(" internal override SyntaxNode GetCachedSlot(int index)"); WriteLine(" {"); WriteLine(" switch (index)"); WriteLine(" {"); for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (field.Type != "SyntaxToken" && field.Type != "SyntaxList<SyntaxToken>") { WriteLine(" case {0}: return this.{1};", i, CamelCase(field.Name)); } } WriteLine(" default: return null;"); WriteLine(" }"); WriteLine(" }"); this.WriteRedAcceptMethods(nd); this.WriteRedUpdateMethod(nd); // this.WriteRedWithMethod(nd); this.WriteRedSetters(nd); this.WriteRedListHelperMethods(nd); WriteLine(" }"); } } private string GetChildPosition(int i) { if (i == 0) { return "this.Position"; } else { return "this.GetChildPosition(" + i + ")"; } } private string GetChildIndex(int i) { if (i == 0) { return "0"; } else { return "this.GetChildIndex(" + i + ")"; } } private void WriteRedAcceptMethods(Node node) { //WriteRedAcceptMethod(node, true, true); WriteRedAcceptMethod(node, false, true); WriteRedAcceptMethod(node, false, false); } private void WriteRedAcceptMethod(Node node, bool genericArgument, bool genericResult) { string genericArgs = (genericResult && genericArgument) ? "<TArgument, TResult>" : genericResult ? "<TResult>" : ""; WriteLine(); WriteLine(" public override " + (genericResult ? "TResult" : "void") + " Accept" + genericArgs + "(CSharpSyntaxVisitor" + genericArgs + " visitor{0})", genericArgument ? ", TArgument argument" : ""); WriteLine(" {"); WriteLine(" " + (genericResult ? "return " : "") + "visitor.Visit{0}(this{1});", StripPost(node.Name, "Syntax"), genericArgument ? ", argument" : ""); WriteLine(" }"); } private void WriteRedVisitors() { //WriteRedVisitor(true, true); WriteRedVisitor(false, true); WriteRedVisitor(false, false); } private void WriteRedVisitor(bool genericArgument, bool genericResult) { string genericArgs = (genericResult && genericArgument) ? "<TArgument, TResult>" : genericResult ? "<TResult>" : ""; var nodes = Tree.Types.Where(n => !(n is PredefinedNode)).ToList(); WriteLine(); WriteLine(" public partial class CSharpSyntaxVisitor" + genericArgs); WriteLine(" {"); int nWritten = 0; for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i] as Node; if (node != null) { if (nWritten > 0) WriteLine(); nWritten++; WriteComment(string.Format("<summary>Called when the visitor visits a {0} node.</summary>", node.Name), " "); WriteLine(" public virtual " + (genericResult ? "TResult" : "void") + " Visit{0}({1} node{2})", StripPost(node.Name, "Syntax"), node.Name, genericArgument ? ", TArgument argument" : ""); WriteLine(" {"); WriteLine(" " + (genericResult ? "return " : "") + "this.DefaultVisit(node{0});", genericArgument ? ", argument" : ""); WriteLine(" }"); } } WriteLine(" }"); } private void WriteRedUpdateMethod(Node node) { WriteLine(); Write(" public {0} Update(", node.Name); // parameters for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); var type = field.Type == "SyntaxList<SyntaxToken>" ? "SyntaxTokenList" : field.Type; Write("{0} {1}", type, CamelCase(field.Name)); } WriteLine(")"); WriteLine(" {"); Write(" if ("); int nCompared = 0; for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (IsDerivedOrListOfDerived("SyntaxNode", field.Type) || IsDerivedOrListOfDerived("SyntaxToken", field.Type) || field.Type == "SyntaxNodeOrTokenList") { if (nCompared > 0) Write(" || "); Write("{0} != this.{1}", CamelCase(field.Name), field.Name); nCompared++; } } if (nCompared > 0) { WriteLine(")"); WriteLine(" {"); Write(" var newNode = SyntaxFactory.{0}(", StripPost(node.Name, "Syntax")); if (node.Kinds.Count > 1) { Write("this.CSharpKind(), "); } for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); Write(CamelCase(field.Name)); } WriteLine(");"); WriteLine(" var annotations = this.GetAnnotations();"); WriteLine(" if (annotations != null && annotations.Length > 0)"); WriteLine(" return newNode.WithAnnotations(annotations);"); WriteLine(" return newNode;"); WriteLine(" }"); } WriteLine(); WriteLine(" return this;"); WriteLine(" }"); } private void WriteRedWithMethod(Node node) { WriteLine(); Write(" public {0} With(", node.Name); // parameters for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; var type = this.GetRedPropertyType(field); Write("Optional<{0}> {1} = default(Optional<{0}>)", type, CamelCase(field.Name)); if (f < node.Fields.Count - 1) Write(", "); } WriteLine(")"); WriteLine(" {"); Write(" return this.Update("); for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; var parameterName = CamelCase(field.Name); WriteLine(); Write(" {0}.HasValue ? {0}.Value : this.{1}", parameterName, field.Name); if (f < node.Fields.Count - 1) Write(","); } WriteLine(); WriteLine(" );"); WriteLine(" }"); } private void WriteRedSetters(Node node) { for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; var type = this.GetRedPropertyType(field); WriteLine(); WriteLine(" public {0} With{1}({2} {3})", node.Name, StripPost(field.Name, "Opt"), type, CamelCase(field.Name)); WriteLine(" {"); //WriteLine(" return this.With({0}: {0});", CamelCase(field.Name)); // call update inside each setter Write(" return this.Update("); for (int f2 = 0; f2 < node.Fields.Count; f2++) { var field2 = node.Fields[f2]; if (f2 > 0) Write(", "); if (field2 == field) { this.Write("{0}", CamelCase(field2.Name)); } else { this.Write("this.{0}", field2.Name); } } WriteLine(");"); WriteLine(" }"); } } private void WriteRedListHelperMethods(Node node) { for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (IsAnyList(field.Type)) { // write list helper methods for list properties WriteRedListHelperMethods(node, field); } else { Node referencedNode = GetNode(field.Type); if (referencedNode != null && (!IsOptional(field) || RequiredFactoryArgumentCount(referencedNode) == 0)) { // look for list members... for (int rf = 0; rf < referencedNode.Fields.Count; rf++) { var referencedNodeField = referencedNode.Fields[rf]; if (IsAnyList(referencedNodeField.Type)) { WriteRedNestedListHelperMethods(node, field, referencedNode, referencedNodeField); } } } } } } private void WriteRedListHelperMethods(Node node, Field field) { var argType = GetElementType(field.Type); WriteLine(); WriteLine(" public {0} Add{1}(params {2}[] items)", node.Name, field.Name, argType); WriteLine(" {"); WriteLine(" return this.With{0}(this.{1}.AddRange(items));", StripPost(field.Name, "Opt"), field.Name); WriteLine(" }"); } private void WriteRedNestedListHelperMethods(Node node, Field field, Node referencedNode, Field referencedNodeField) { var argType = GetElementType(referencedNodeField.Type); // AddBaseListTypes WriteLine(); WriteLine(" public {0} Add{1}{2}(params {3}[] items)", node.Name, StripPost(field.Name, "Opt"), referencedNodeField.Name, argType); WriteLine(" {"); if (IsOptional(field)) { var factoryName = StripPost(referencedNode.Name, "Syntax"); var varName = StripPost(CamelCase(field.Name), "Opt"); WriteLine(" var {0} = this.{1} ?? SyntaxFactory.{2}();", varName, field.Name, factoryName); WriteLine(" return this.With{0}({1}.With{2}({1}.{3}.AddRange(items)));", StripPost(field.Name, "Opt"), varName, StripPost(referencedNodeField.Name, "Opt"), referencedNodeField.Name); } else { WriteLine(" return this.With{0}(this.{1}.With{2}(this.{1}.{3}.AddRange(items)));", StripPost(field.Name, "Opt"), field.Name, StripPost(referencedNodeField.Name, "Opt"), referencedNodeField.Name); } WriteLine(" }"); } private void WriteRedRewriter() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode)).ToList(); WriteLine(); WriteLine(" public partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<SyntaxNode>"); WriteLine(" {"); int nWritten = 0; for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i] as Node; if (node != null) { var nodeFields = node.Fields.Where(nd => IsNodeOrNodeList(nd.Type)).ToList(); if (nWritten > 0) WriteLine(); nWritten++; WriteLine(" public override SyntaxNode Visit{0}({1} node)", StripPost(node.Name, "Syntax"), node.Name); WriteLine(" {"); for (int f = 0; f < nodeFields.Count; f++) { var field = nodeFields[f]; if (IsAnyList(field.Type)) { WriteLine(" var {0} = this.VisitList(node.{1});", CamelCase(field.Name), field.Name); } else if (field.Type == "SyntaxToken") { WriteLine(" var {0} = this.VisitToken(node.{1});", CamelCase(field.Name), field.Name); } else { WriteLine(" var {0} = ({1})this.Visit(node.{2});", CamelCase(field.Name), field.Type, field.Name); } } if (nodeFields.Count > 0) { Write(" return node.Update("); for (int f = 0; f < node.Fields.Count; f++) { var field = node.Fields[f]; if (f > 0) Write(", "); if (IsNodeOrNodeList(field.Type)) { Write(CamelCase(field.Name)); } else { Write("node.{0}", field.Name); } } WriteLine(");"); } else { WriteLine(" return node;"); } WriteLine(" }"); } } WriteLine(" }"); } private void WriteRedFactories() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)).OfType<Node>().ToList(); WriteLine(); WriteLine(" public static partial class SyntaxFactory"); WriteLine(" {"); for (int i = 0, n = nodes.Count; i < n; i++) { var node = nodes[i]; this.WriteRedFactory(node); this.WriteRedFactoryWithNoAutoCreatableTokens(node); this.WriteRedMinimalFactory(node); this.WriteRedMinimalFactory(node, withStringNames: true); this.WriteKindConverters(node); } WriteLine(" }"); } protected bool CanBeAutoCreated(Node node, Field field) { return IsAutoCreatableToken(node, field) || IsAutoCreateableNode(node, field); } private bool IsAutoCreatableToken(Node node, Field field) { return field.Type == "SyntaxToken" && field.Kinds != null && ((field.Kinds.Count == 1 && field.Kinds[0].Name != "IdentifierToken" && !field.Kinds[0].Name.EndsWith("LiteralToken")) || (field.Kinds.Count > 1 && field.Kinds.Count == node.Kinds.Count)); } private bool IsAutoCreateableNode(Node node, Field field) { var referencedNode = GetNode(field.Type); return (referencedNode != null && RequiredFactoryArgumentCount(referencedNode) == 0); } private bool IsRequiredFactoryField(Node node, Field field) { return (!IsOptional(field) && !IsAnyList(field.Type) && !CanBeAutoCreated(node, field)) || IsValueField(field); } private bool IsValueField(Field field) { return !IsNodeOrNodeList(field.Type); } private int RequiredFactoryArgumentCount(Node nd, bool includeKind = true) { int count = 0; // kind must be specified in factory if (nd.Kinds.Count > 1 && includeKind) { count++; } for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (IsRequiredFactoryField(nd, field)) { count++; } } return count; } private int OptionalFactoryArgumentCount(Node nd) { int count = 0; for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (IsOptional(field) || CanBeAutoCreated(nd, field) || IsAnyList(field.Type)) { count++; } } return count; } // full factory signature with nothing optional private void WriteRedFactory(Node nd) { this.WriteLine(); var valueFields = nd.Fields.Where(n => IsValueField(n)).ToList(); var nodeFields = nd.Fields.Where(n => !IsValueField(n)).ToList(); WriteComment(string.Format("<summary>Creates a new {0} instance.</summary>", nd.Name), " "); Write(" public static {0} {1}(", nd.Name, StripPost(nd.Name, "Syntax")); if (nd.Kinds.Count > 1) { Write("SyntaxKind kind, "); } for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (i > 0) Write(", "); var type = this.GetRedPropertyType(field); Write("{0} {1}", type, CamelCase(field.Name)); } WriteLine(")"); WriteLine(" {"); // validate kinds if (nd.Kinds.Count > 1) { WriteLine(" switch (kind)"); WriteLine(" {"); foreach (var kind in nd.Kinds) { WriteLine(" case SyntaxKind.{0}:", kind.Name); } WriteLine(" break;"); WriteLine(" default:"); WriteLine(" throw new ArgumentException(\"kind\");"); WriteLine(" }"); } // validate parameters for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; var pname = CamelCase(field.Name); if (field.Type == "SyntaxToken") { if (field.Kinds != null && field.Kinds.Count > 0) { WriteLine(" switch ({0}.CSharpKind())", pname); WriteLine(" {"); foreach (var kind in field.Kinds) { WriteLine(" case SyntaxKind.{0}:", kind.Name); } if (IsOptional(field)) { WriteLine(" case SyntaxKind.None:"); } WriteLine(" break;"); WriteLine(" default:"); WriteLine(" throw new ArgumentException(\"{0}\");", pname); WriteLine(" }"); } } else if (!IsAnyList(field.Type) && !IsOptional(field)) { WriteLine(" if ({0} == null)", CamelCase(field.Name)); WriteLine(" throw new ArgumentNullException(\"{0}\");", CamelCase(field.Name)); } } Write(" return ({0})Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory.{1}(", nd.Name, StripPost(nd.Name, "Syntax")); if (nd.Kinds.Count > 1) { Write("kind, "); } for (int i = 0, n = nodeFields.Count; i < n; i++) { var field = nodeFields[i]; if (i > 0) Write(", "); if (field.Type == "SyntaxToken") { Write("(Syntax.InternalSyntax.SyntaxToken){0}.Node", CamelCase(field.Name)); } else if (field.Type == "SyntaxList<SyntaxToken>") { Write("{0}.Node.ToGreenList<Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode>()", CamelCase(field.Name)); } else if (IsNodeList(field.Type)) { Write("{0}.Node.ToGreenList<Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.{1}>()", CamelCase(field.Name), GetElementType(field.Type)); } else if (IsSeparatedNodeList(field.Type)) { Write("{0}.Node.ToGreenSeparatedList<Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.{1}>()", CamelCase(field.Name), GetElementType(field.Type)); } else if (field.Type == "SyntaxNodeOrTokenList") { Write("{0}.Node.ToGreenList<Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.CSharpSyntaxNode>()", CamelCase(field.Name)); } else { Write("{0} == null ? null : (Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.{1}){0}.Green", CamelCase(field.Name), field.Type); } } // values are at end for (int i = 0, n = valueFields.Count; i < n; i++) { var field = valueFields[i]; Write(", "); Write(CamelCase(field.Name)); } WriteLine(").CreateRed();"); WriteLine(" }"); } private string GetRedPropertyType(Field field) { if (field.Type == "SyntaxList<SyntaxToken>") return "SyntaxTokenList"; return field.Type; } private string GetDefaultValue(Node nd, Field field) { System.Diagnostics.Debug.Assert(!IsRequiredFactoryField(nd, field)); if (IsOptional(field) || IsAnyList(field.Type)) { return string.Format("default({0})", GetRedPropertyType(field)); } else if (field.Type == "SyntaxToken") { // auto construct token? if (field.Kinds.Count == 1) { return string.Format("SyntaxFactory.Token(SyntaxKind.{0})", field.Kinds[0].Name); } else { return string.Format("SyntaxFactory.Token(Get{0}{1}Kind(kind))", StripPost(nd.Name, "Syntax"), StripPost(field.Name, "Opt")); } } else { var referencedNode = GetNode(field.Type); return string.Format("SyntaxFactory.{0}()", StripPost(referencedNode.Name, "Syntax")); } } // Writes Get<Property>Kind() methods for converting between node kind and member token kinds... private void WriteKindConverters(Node nd) { for (int f = 0; f < nd.Fields.Count; f++) { var field = nd.Fields[f]; if (field.Type == "SyntaxToken" && CanBeAutoCreated(nd, field) && field.Kinds.Count > 1) { WriteLine(); WriteLine(" private static SyntaxKind Get{0}{1}Kind(SyntaxKind kind)", StripPost(nd.Name, "Syntax"), StripPost(field.Name, "Opt")); WriteLine(" {"); WriteLine(" switch (kind)"); WriteLine(" {"); for (int k = 0; k < field.Kinds.Count; k++) { var nKind = nd.Kinds[k]; var pKind = field.Kinds[k]; WriteLine(" case SyntaxKind.{0}:", nKind.Name); WriteLine(" return SyntaxKind.{0};", pKind.Name); } WriteLine(" default:"); WriteLine(" throw new ArgumentOutOfRangeException();"); WriteLine(" }"); WriteLine(" }"); } } } private IEnumerable<Field> DetermineRedFactoryWithNoAutoCreatableTokenFields(Node nd) { return nd.Fields.Where(f => !IsAutoCreatableToken(nd, f)); } // creates a factory without auto-creatable token arguments private void WriteRedFactoryWithNoAutoCreatableTokens(Node nd) { var nAutoCreatableTokens = nd.Fields.Count(f => IsAutoCreatableToken(nd, f)); if (nAutoCreatableTokens == 0) return; // already handled by general factory var factoryWithNoAutoCreatableTokenFields = new HashSet<Field>(DetermineRedFactoryWithNoAutoCreatableTokenFields(nd)); var minimalFactoryFields = DetermineMinimalFactoryFields(nd); if (minimalFactoryFields != null && factoryWithNoAutoCreatableTokenFields.SetEquals(minimalFactoryFields)) { return; // will be handled in minimal factory case } this.WriteLine(); WriteComment(string.Format("<summary>Creates a new {0} instance.</summary>", nd.Name), " "); Write(" public static {0} {1}(", nd.Name, StripPost(nd.Name, "Syntax")); bool hasPreviousParameter = false; if (nd.Kinds.Count > 1) { Write("SyntaxKind kind"); hasPreviousParameter = true; } for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (factoryWithNoAutoCreatableTokenFields.Contains(field)) { if (hasPreviousParameter) Write(", "); Write("{0} {1}", GetRedPropertyType(field), CamelCase(field.Name)); hasPreviousParameter = true; } } WriteLine(")"); WriteLine(" {"); Write(" return SyntaxFactory.{0}(", StripPost(nd.Name, "Syntax")); bool hasPreviousArgument = false; if (nd.Kinds.Count > 1) { Write("kind"); hasPreviousArgument = true; } for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (hasPreviousArgument) Write(", "); if (factoryWithNoAutoCreatableTokenFields.Contains(field)) { // pass supplied parameter on to general factory Write("{0}", CamelCase(field.Name)); } else { // pass an auto-created token to the general factory Write("{0}", GetDefaultValue(nd, field)); } hasPreviousArgument = true; } WriteLine(");"); WriteLine(" }"); } private Field DetermineMinimalOptionalField(Node nd) { // first if there is a single list, then choose the list because it would not have been optional int listCount = nd.Fields.Count(f => IsAnyNodeList(f.Type)); if (listCount == 1) { return nd.Fields.First(f => IsAnyNodeList(f.Type)); } else { // otherwise, if there there is a single optional node, use that.. int nodeCount = nd.Fields.Count(f => IsNode(f.Type) && f.Type != "SyntaxToken"); if (nodeCount == 1) { return nd.Fields.First(f => IsNode(f.Type) && f.Type != "SyntaxToken"); } else { return null; } } } private IEnumerable<Field> DetermineMinimalFactoryFields(Node nd) { // special case to allow a single optional argument if there would have been no arguments // and we can determine a best single argument. Field allowOptionalField = null; var optionalCount = OptionalFactoryArgumentCount(nd); if (optionalCount == 0) { return null; // no fields... } var requiredCount = RequiredFactoryArgumentCount(nd, includeKind: false); if (requiredCount == 0 && optionalCount > 1) { allowOptionalField = DetermineMinimalOptionalField(nd); } return nd.Fields.Where(f => IsRequiredFactoryField(nd, f) || allowOptionalField == f); } // creates a factory with only the required arguments (everything else is defaulted) private void WriteRedMinimalFactory(Node nd, bool withStringNames = false) { var optionalCount = OptionalFactoryArgumentCount(nd); if (optionalCount == 0) return; // already handled w/ general factory method var minimalFactoryfields = new HashSet<Field>(DetermineMinimalFactoryFields(nd)); if (withStringNames && minimalFactoryfields.Count(f => IsRequiredFactoryField(nd, f) && CanAutoConvertFromString(f)) == 0) return; // no string-name overload necessary this.WriteLine(); WriteComment(string.Format("<summary>Creates a new {0} instance.</summary>", nd.Name), " "); Write(" public static {0} {1}(", nd.Name, StripPost(nd.Name, "Syntax")); bool hasPreviousParameter = false; if (nd.Kinds.Count > 1) { Write("SyntaxKind kind"); hasPreviousParameter = true; } for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (minimalFactoryfields.Contains(field)) { var type = GetRedPropertyType(field); if (IsRequiredFactoryField(nd, field)) { if (hasPreviousParameter) Write(", "); if (withStringNames && CanAutoConvertFromString(field)) { type = "string"; } Write("{0} {1}", type, CamelCase(field.Name)); hasPreviousParameter = true; } else { if (hasPreviousParameter) Write(", "); Write("{0} {1} = default({0})", type, CamelCase(field.Name)); hasPreviousParameter = true; } } } WriteLine(")"); WriteLine(" {"); Write(" return SyntaxFactory.{0}(", StripPost(nd.Name, "Syntax")); bool hasPreviousArgument = false; if (nd.Kinds.Count > 1) { Write("kind"); hasPreviousArgument = true; } for (int i = 0, n = nd.Fields.Count; i < n; i++) { var field = nd.Fields[i]; if (hasPreviousArgument) Write(", "); if (minimalFactoryfields.Contains(field)) { if (IsRequiredFactoryField(nd, field)) { if (withStringNames && CanAutoConvertFromString(field)) { Write("{0}({1})", GetStringConverterMethod(field), CamelCase(field.Name)); } else { Write("{0}", CamelCase(field.Name)); } } else { if (IsOptional(field) || IsAnyList(field.Type)) { Write("{0}", CamelCase(field.Name)); } else { Write("{0} ?? {1}", CamelCase(field.Name), GetDefaultValue(nd, field)); } } } else { var defaultValue = GetDefaultValue(nd, field); Write(defaultValue); } hasPreviousArgument = true; } WriteLine(");"); WriteLine(" }"); } private bool CanAutoConvertFromString(Field field) { return IsIdentifierToken(field) || IsIdentifierNameSyntax(field); } private bool IsIdentifierToken(Field field) { return field.Type == "SyntaxToken" && field.Kinds != null && field.Kinds.Count == 1 && field.Kinds[0].Name == "IdentifierToken"; } private bool IsIdentifierNameSyntax(Field field) { return field.Type == "IdentifierNameSyntax"; } private string GetStringConverterMethod(Field field) { if (IsIdentifierToken(field)) { return "SyntaxFactory.Identifier"; } else if (IsIdentifierNameSyntax(field)) { return "SyntaxFactory.IdentifierName"; } else { throw new NotSupportedException(); } } /// <summary> /// Anything inside a &lt;Comment&gt; tag gets written out (escaping untouched) as the /// XML doc comment. Line breaks will be preserved. /// </summary> private void WriteComment(string comment, string indent) { if (comment != null) { var lines = comment.Split(new string[] { "\r", "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines.Where(l => !string.IsNullOrWhiteSpace(l))) { WriteLine("{0}/// {1}", indent, line.TrimStart()); } } } /// <summary> /// Anything inside a &lt;Comment&gt; tag gets written out (escaping untouched) as the /// XML doc comment. Line breaks will be preserved. /// </summary> private void WriteComment(Comment comment, string indent) { if (comment != null) { foreach (XmlElement element in comment.Body) { string[] lines = element.OuterXml.Split(new string[] { "\r", "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines.Where(l => !string.IsNullOrWhiteSpace(l))) { WriteLine("{0}/// {1}", indent, line.TrimStart()); } } } } } }
40.002468
245
0.433771
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceWriter.cs
81,047
C#
using NUnit.Framework; using System; namespace ItalianSyllabaryTests.Helpers { internal static class TestHelper { /// <summary> /// Method used to assert simple cases /// </summary> /// <param name="_syllabary">_syllabary instance</param> /// <param name="word">word to be tested with _syllabary</param> /// <param name="expected">string array that should be the result</param> /// <param name="errorMessage">message to print in case of error</param> public static void SimpleTestProcedure(ItalianSyllabary.ItalianSyllabary _syllabary, string word, string[] expected, string errorMessage) { if (_syllabary is null) { Assert.Fail("Not instantiated"); ArgumentNullException.ThrowIfNull(_syllabary); } var result = _syllabary.GetSyllables(word) .Result; Assert.That( result, Is.EquivalentTo(expected), errorMessage ); } } }
30.75
145
0.568202
[ "MIT" ]
CarloP95/ItalianSyllabary
ItalianSyllabary/ItalianSyllabaryTests/Helpers/TestHelper.cs
1,109
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 enable using System.Collections.Generic; using System.Diagnostics; using System.Net.Http.HPack; namespace System.Net.Http.QPack { internal class QPackEncoder { private IEnumerator<KeyValuePair<string, string>>? _enumerator; // https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-4.5.2 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 1 | T | Index (6+) | // +---+---+-----------------------+ // // Note for this method's implementation of above: // - T is constant 1 here, indicating a static table reference. public static bool EncodeStaticIndexedHeaderField(int index, Span<byte> destination, out int bytesWritten) { if (!destination.IsEmpty) { destination[0] = 0b11000000; return IntegerEncoder.Encode(index, 6, destination, out bytesWritten); } else { bytesWritten = 0; return false; } } public static byte[] EncodeStaticIndexedHeaderFieldToArray(int index) { Span<byte> buffer = stackalloc byte[IntegerEncoder.MaxInt32EncodedLength]; bool res = EncodeStaticIndexedHeaderField(index, buffer, out int bytesWritten); Debug.Assert(res == true); return buffer.Slice(0, bytesWritten).ToArray(); } // https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-4.5.4 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 1 | N | T |Name Index (4+)| // +---+---+---+---+---------------+ // | H | Value Length (7+) | // +---+---------------------------+ // | Value String (Length bytes) | // +-------------------------------+ // // Note for this method's implementation of above: // - N is constant 0 here, indicating intermediates (proxies) can compress the header when fordwarding. // - T is constant 1 here, indicating a static table reference. // - H is constant 0 here, as we do not yet perform Huffman coding. public static bool EncodeLiteralHeaderFieldWithStaticNameReference(int index, string value, Span<byte> destination, out int bytesWritten) { // Requires at least two bytes (one for name reference header, one for value length) if (destination.Length >= 2) { destination[0] = 0b01010000; if (IntegerEncoder.Encode(index, 4, destination, out int headerBytesWritten)) { destination = destination.Slice(headerBytesWritten); if (EncodeValueString(value, destination, out int valueBytesWritten)) { bytesWritten = headerBytesWritten + valueBytesWritten; return true; } } } bytesWritten = 0; return false; } /// <summary> /// Encodes just the name part of a Literal Header Field With Static Name Reference. Must call <see cref="EncodeValueString(string, Span{byte}, out int)"/> after to encode the header's value. /// </summary> public static byte[] EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(int index) { Span<byte> temp = stackalloc byte[IntegerEncoder.MaxInt32EncodedLength]; temp[0] = 0b01110000; bool res = IntegerEncoder.Encode(index, 4, temp, out int headerBytesWritten); Debug.Assert(res == true); return temp.Slice(0, headerBytesWritten).ToArray(); } public static byte[] EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(int index, string value) { Span<byte> temp = value.Length < 256 ? stackalloc byte[256 + IntegerEncoder.MaxInt32EncodedLength * 2] : new byte[value.Length + IntegerEncoder.MaxInt32EncodedLength * 2]; bool res = EncodeLiteralHeaderFieldWithStaticNameReference(index, value, temp, out int bytesWritten); Debug.Assert(res == true); return temp.Slice(0, bytesWritten).ToArray(); } // https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-4.5.6 // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 1 | N | H |NameLen(3+)| // +---+---+---+---+---+-----------+ // | Name String (Length bytes) | // +---+---------------------------+ // | H | Value Length (7+) | // +---+---------------------------+ // | Value String (Length bytes) | // +-------------------------------+ // // Note for this method's implementation of above: // - N is constant 0 here, indicating intermediates (proxies) can compress the header when fordwarding. // - H is constant 0 here, as we do not yet perform Huffman coding. public static bool EncodeLiteralHeaderFieldWithoutNameReference(string name, string value, Span<byte> destination, out int bytesWritten) { if (EncodeNameString(name, destination, out int nameLength) && EncodeValueString(value, destination.Slice(nameLength), out int valueLength)) { bytesWritten = nameLength + valueLength; return true; } else { bytesWritten = 0; return false; } } /// <summary> /// Encodes a Literal Header Field Without Name Reference, building the value by concatenating a collection of strings with separators. /// </summary> public static bool EncodeLiteralHeaderFieldWithoutNameReference(string name, ReadOnlySpan<string> values, string valueSeparator, Span<byte> destination, out int bytesWritten) { if (EncodeNameString(name, destination, out int nameLength) && EncodeValueString(values, valueSeparator, destination.Slice(nameLength), out int valueLength)) { bytesWritten = nameLength + valueLength; return true; } bytesWritten = 0; return false; } /// <summary> /// Encodes just the value part of a Literawl Header Field Without Static Name Reference. Must call <see cref="EncodeValueString(string, Span{byte}, out int)"/> after to encode the header's value. /// </summary> public static byte[] EncodeLiteralHeaderFieldWithoutNameReferenceToArray(string name) { Span<byte> temp = name.Length < 256 ? stackalloc byte[256 + IntegerEncoder.MaxInt32EncodedLength] : new byte[name.Length + IntegerEncoder.MaxInt32EncodedLength]; bool res = EncodeNameString(name, temp, out int nameLength); Debug.Assert(res == true); return temp.Slice(0, nameLength).ToArray(); } public static byte[] EncodeLiteralHeaderFieldWithoutNameReferenceToArray(string name, string value) { Span<byte> temp = (name.Length + value.Length) < 256 ? stackalloc byte[256 + IntegerEncoder.MaxInt32EncodedLength * 2] : new byte[name.Length + value.Length + IntegerEncoder.MaxInt32EncodedLength * 2]; bool res = EncodeLiteralHeaderFieldWithoutNameReference(name, value, temp, out int bytesWritten); Debug.Assert(res == true); return temp.Slice(0, bytesWritten).ToArray(); } private static bool EncodeValueString(string s, Span<byte> buffer, out int length) { if (buffer.Length != 0) { buffer[0] = 0; if (IntegerEncoder.Encode(s.Length, 7, buffer, out int nameLength)) { buffer = buffer.Slice(nameLength); if (buffer.Length >= s.Length) { EncodeValueStringPart(s, buffer); length = nameLength + s.Length; return true; } } } length = 0; return false; } /// <summary> /// Encodes a value by concatenating a collection of strings, separated by a separator string. /// </summary> public static bool EncodeValueString(ReadOnlySpan<string> values, string? separator, Span<byte> buffer, out int length) { if (values.Length == 1) { return EncodeValueString(values[0], buffer, out length); } if (values.Length == 0) { // TODO: this will be called with a string array from HttpHeaderCollection. Can we ever get a 0-length array from that? Assert if not. return EncodeValueString(string.Empty, buffer, out length); } if (buffer.Length > 0) { Debug.Assert(separator != null); int valueLength = separator.Length * (values.Length - 1); for (int i = 0; i < values.Length; ++i) { valueLength += values[i].Length; } buffer[0] = 0; if (IntegerEncoder.Encode(valueLength, 7, buffer, out int nameLength)) { buffer = buffer.Slice(nameLength); if (buffer.Length >= valueLength) { string value = values[0]; EncodeValueStringPart(value, buffer); buffer = buffer.Slice(value.Length); for (int i = 1; i < values.Length; ++i) { EncodeValueStringPart(separator, buffer); buffer = buffer.Slice(separator.Length); value = values[i]; EncodeValueStringPart(value, buffer); buffer = buffer.Slice(value.Length); } length = nameLength + valueLength; return true; } } } length = 0; return false; } private static void EncodeValueStringPart(string s, Span<byte> buffer) { Debug.Assert(buffer.Length >= s.Length); for (int i = 0; i < s.Length; ++i) { char ch = s[i]; if (ch > 127) { throw new QPackEncodingException("ASCII header value."); } buffer[i] = (byte)ch; } } private static bool EncodeNameString(string s, Span<byte> buffer, out int length) { const int toLowerMask = 0x20; if (buffer.Length != 0) { buffer[0] = 0x30; if (IntegerEncoder.Encode(s.Length, 3, buffer, out int nameLength)) { buffer = buffer.Slice(nameLength); if (buffer.Length >= s.Length) { for (int i = 0; i < s.Length; ++i) { int ch = s[i]; Debug.Assert(ch <= 127, "HttpHeaders prevents adding non-ASCII header names."); if ((uint)(ch - 'A') <= 'Z' - 'A') { ch |= toLowerMask; } buffer[i] = (byte)ch; } length = nameLength + s.Length; return true; } } } length = 0; return false; } /* * 0 1 2 3 4 5 6 7 +---+---+---+---+---+---+---+---+ | Required Insert Count (8+) | +---+---------------------------+ | S | Delta Base (7+) | +---+---------------------------+ | Compressed Headers ... +-------------------------------+ * */ private static bool EncodeHeaderBlockPrefix(Span<byte> destination, out int bytesWritten) { int length; bytesWritten = 0; // Required insert count as first int if (!IntegerEncoder.Encode(0, 8, destination, out length)) { return false; } bytesWritten += length; destination = destination.Slice(length); // Delta base if (destination.IsEmpty) { return false; } destination[0] = 0x00; if (!IntegerEncoder.Encode(0, 7, destination, out length)) { return false; } bytesWritten += length; return true; } public bool BeginEncode(IEnumerable<KeyValuePair<string, string>> headers, Span<byte> buffer, out int length) { _enumerator = headers.GetEnumerator(); bool hasValue = _enumerator.MoveNext(); Debug.Assert(hasValue == true); buffer[0] = 0; buffer[1] = 0; bool doneEncode = Encode(buffer.Slice(2), out length); // Add two for the first two bytes. length += 2; return doneEncode; } public bool BeginEncode(int statusCode, IEnumerable<KeyValuePair<string, string>> headers, Span<byte> buffer, out int length) { _enumerator = headers.GetEnumerator(); bool hasValue = _enumerator.MoveNext(); Debug.Assert(hasValue == true); // https://quicwg.org/base-drafts/draft-ietf-quic-qpack.html#header-prefix buffer[0] = 0; buffer[1] = 0; int statusCodeLength = EncodeStatusCode(statusCode, buffer.Slice(2)); bool done = Encode(buffer.Slice(statusCodeLength + 2), throwIfNoneEncoded: false, out int headersLength); length = statusCodeLength + headersLength + 2; return done; } public bool Encode(Span<byte> buffer, out int length) { return Encode(buffer, throwIfNoneEncoded: true, out length); } private bool Encode(Span<byte> buffer, bool throwIfNoneEncoded, out int length) { length = 0; do { if (!EncodeLiteralHeaderFieldWithoutNameReference(_enumerator!.Current.Key, _enumerator.Current.Value, buffer.Slice(length), out int headerLength)) { if (length == 0 && throwIfNoneEncoded) { throw new QPackEncodingException("TODO sync with corefx" /* CoreStrings.HPackErrorNotEnoughBuffer */); } return false; } length += headerLength; } while (_enumerator.MoveNext()); return true; } // TODO: use H3StaticTable? private int EncodeStatusCode(int statusCode, Span<byte> buffer) { switch (statusCode) { case 200: case 204: case 206: case 304: case 400: case 404: case 500: // TODO this isn't safe, some index can be larger than 64. Encoded here! buffer[0] = (byte)(0xC0 | H3StaticTable.StatusIndex[statusCode]); return 1; default: // Send as Literal Header Field Without Indexing - Indexed Name buffer[0] = 0x08; ReadOnlySpan<byte> statusBytes = StatusCodes.ToStatusBytes(statusCode); buffer[1] = (byte)statusBytes.Length; statusBytes.CopyTo(buffer.Slice(2)); return 2 + statusBytes.Length; } } } }
38.260369
213
0.502198
[ "MIT" ]
06needhamt/runtime
src/libraries/Common/src/System/Net/Http/aspnetcore/Http3/QPack/QPackEncoder.cs
16,605
C#
using System.Data; namespace Sikiro.Dapper.Extension.Core { public abstract class AbstractSet { public SqlProvider SqlProvider { get; protected set; } public IDbConnection DbCon { get; protected set; } public IDbTransaction DbTransaction { get; protected set; } protected AbstractSet(IDbConnection dbCon, SqlProvider sqlProvider, IDbTransaction dbTransaction) { SqlProvider = sqlProvider; DbCon = dbCon; DbTransaction = dbTransaction; } protected AbstractSet(IDbConnection dbCon, SqlProvider sqlProvider) { SqlProvider = sqlProvider; DbCon = dbCon; } } }
28.12
105
0.634424
[ "MIT" ]
SkyChenSky/Sikiro.Dapper.Extension
src/Sikiro.Dapper.Extension/Core/AbstractSet.cs
705
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Northwind.Dal.Models { [Table("ProductPhoto", Schema = "Production")] public partial class ProductPhoto { public ProductPhoto() { ProductProductPhoto = new HashSet<ProductProductPhoto>(); } [Key] [Column("ProductPhotoID")] public int ProductPhotoId { get; set; } public byte[] ThumbNailPhoto { get; set; } [StringLength(50)] public string ThumbnailPhotoFileName { get; set; } public byte[] LargePhoto { get; set; } [StringLength(50)] public string LargePhotoFileName { get; set; } [Column(TypeName = "datetime")] public DateTime ModifiedDate { get; set; } [InverseProperty("ProductPhoto")] public virtual ICollection<ProductProductPhoto> ProductProductPhoto { get; set; } } }
30.96875
89
0.64884
[ "BSD-3-Clause", "MIT" ]
MalikWaseemJaved/presentations
.NETCore/WhatsNewInDotNetCore3/Northwind.DAL/Models/ProductPhoto.cs
993
C#
// <copyright file="VectorXD.cs" company="Shkyrockett" > // Copyright © 2020 Shkyrockett. All rights reserved. // </copyright> // <author id="shkyrockett">Shkyrockett</author> // <license> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </license> // <date></date> // <summary></summary> // <remarks></remarks> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using System.Xml.Serialization; namespace Engine { /// <summary> /// /// </summary> /// <seealso cref="System.IEquatable{T}" /> [DebuggerDisplay("{" + nameof(ToString) + "(),nq}")] public struct VectorXD : IVector<VectorXD> { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="VectorXD"/> class. /// </summary> /// <param name="values">The values.</param> public VectorXD(double[] values) { Values = values; } /// <summary> /// Initializes a new instance of the <see cref="VectorXD"/> class. /// </summary> /// <param name="rows">The rows.</param> public VectorXD(int rows) { Values = new double[rows]; } #endregion #region Indexers /// <summary> /// Gets or sets the <see cref="System.Double"/> with the specified index1. /// </summary> /// <value> /// The <see cref="System.Double"/>. /// </value> /// <param name="index">The index.</param> /// <returns></returns> public double this[int index] { get { return Values[index]; } set { Values[index] = value; } } #endregion #region Properties /// <summary> /// Gets the values. /// </summary> /// <value> /// The values. /// </value> public double[] Values { get; set; } /// <summary> /// Gets the number of components in the Vector. /// </summary> /// <value> /// The count. /// </value> [IgnoreDataMember, XmlIgnore, SoapIgnore] public int Count => Values.Length; #endregion #region Operators /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator ==(VectorXD left, VectorXD right) => EqualityComparer<VectorXD>.Default.Equals(left, right); /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator !=(VectorXD left, VectorXD right) => !(left == right); /// <summary> /// Performs an implicit conversion from <see cref="Array" /> to <see cref="VectorXD" />. /// </summary> /// <param name="array">The array.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator VectorXD(double[] array) => ToVector(array); #endregion #region Operator Backing MEthods /// <summary> /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <see langword="true" /> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <see langword="false" />. /// </returns> public override bool Equals(object obj) => obj is VectorXD vector && Equals(vector); /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// <see langword="true" /> if the current object is equal to the <paramref name="other" /> parameter; otherwise, <see langword="false" />. /// </returns> public bool Equals(VectorXD other) => other != null && EqualityComparer<double[]>.Default.Equals(Values, other.Values); /// <summary> /// Converts to vector. /// </summary> /// <param name="array">The array.</param> /// <returns></returns> private static VectorXD ToVector(double[] array) => new VectorXD(array); #endregion #region Standard Methods /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() => HashCode.Combine(Values); /// <summary> /// Converts to string. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() => ToString("R" /* format string */, CultureInfo.InvariantCulture /* format provider */); /// <summary> /// Converts to string. /// </summary> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public string ToString(IFormatProvider formatProvider) => ToString("R" /* format string */, formatProvider); /// <summary> /// Converts to string. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ToString(string format, IFormatProvider formatProvider) { var sb = new StringBuilder(); sb.Append("{"); for (var i = 0; i < Values.Length; i++) { sb.Append($"{Values[i].ToString(format, formatProvider)},\t"); } sb.Append("}"); return sb.ToString(); } #endregion } }
34.989744
149
0.550931
[ "MIT" ]
Shkyrockett/engine
Engine.Mathematics/Primitives/VectorXD.cs
6,826
C#
using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace System.Linq.Sql.Tests { [TestClass] public class CompositeExpressionTests { private readonly APredicateExpression left = new BooleanExpression(true); private readonly APredicateExpression right = new BooleanExpression(true); private CompositeExpression expression = null; [TestInitialize] public void TestInitialize() { expression = new CompositeExpression(left, right, CompositeOperator.Or); } [TestMethod] public void CompositeExpression_Constructor_Exceptions() { Assert.ThrowsException<ArgumentNullException>(() => new CompositeExpression(null, right)); Assert.ThrowsException<ArgumentNullException>(() => new CompositeExpression(left, null)); } [TestMethod] public void CompositeExpression_Properties() { Assert.AreEqual(ExpressionType.Extension, expression.NodeType); Assert.AreEqual(typeof(object), expression.Type); Assert.AreEqual(CompositeOperator.Or, expression.Operator); Assert.AreSame(left, expression.Left); Assert.AreSame(right, expression.Right); } [TestMethod] public void CompositeExpression_Accept() { // Setup test MockExpressionVisitor visitor = new MockExpressionVisitor(); // Perform the test operation visitor.Visit(expression); // Check test result Assert.IsTrue(visitor.CompositeVisited); } } }
32.54902
102
0.648795
[ "MIT" ]
buzzytom/System.Linq.Sql
src/LinqSql.Tests/Expressions/Implementations/CompositeExpressionTests.cs
1,662
C#
using Fitbit.API.Model.User; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fitbit.API.Client { public partial class FitbitClient : BaseClient { public async Task<GetUserResponse> GetUser() { string query = "/1/user/-/profile.json"; return await GetAsync<GetUserResponse>(query); } public async Task<GetUserResponse> GetUser(int userid) { string query = string.Format("/1/user/{0}/profile.json", userid); return await GetAsync<GetUserResponse>(query); } public async Task<UpdateUserResponse> UpdateUser(UpdateUserRequest request) { string query = "/1/user/-/profile.json?"; string queryParams = SerializeToQueryString<UpdateUserRequest>(request); return await PostAsync<UpdateUserResponse>(query + queryParams); } } }
29.424242
84
0.645726
[ "MIT" ]
bobbykaz/Async-Fitbit-Client
Fitbit.API.Client/UserClient.cs
973
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DocumentFormat.OpenXml.Generator.Editor; using DocumentFormat.OpenXml.Generator.Generators.Elements; using Microsoft.CodeAnalysis; using System.CodeDom.Compiler; using System.Text; namespace DocumentFormat.OpenXml.Generator; [Generator] public class SchemaGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { var openXmlContext = context.GetOpenXmlGeneratorContext(); var ns = openXmlContext.SelectMany((s, _) => s.Namespaces); var services = openXmlContext.GetOpenXmlServices(); var options = context.GetOpenXmlOptions().Select(static (o, _) => o.GenerateSchema); context.RegisterSourceOutput(ns.Combine(services).Combine(options), (context, data) => { if (!data.Right) { return; } var openXml = data.Left.Right; var sw = new StringWriter(); var writer = new IndentedTextWriter(sw); writer.WriteFileHeader(); writer.WriteLine("#pragma warning disable CS0618 // Type or member is obsolete"); writer.WriteLine(); if (writer.GetDataModelSyntax(openXml, data.Left.Left)) { context.AddSource(GetPath(data.Left.Left.TargetNamespace), sw.ToString()); } }); } private static string GetPath(string ns) { var sb = new StringBuilder(ns); sb.Replace("http://", string.Empty); sb.Replace("urn:", string.Empty); sb.Replace('/', '_'); sb.Replace('.', '_'); sb.Replace(':', '_'); return sb.ToString(); } }
32.105263
101
0.630601
[ "MIT" ]
LaudateCorpus1/Open-XML-SDK
gen/DocumentFormat.OpenXml.Generator/SchemaGenerator.cs
1,832
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.Concurrent; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { /// <summary> /// Keeps a sliding buffer over the SourceText of a file for the lexer. Also /// provides the lexer with the ability to keep track of a current "lexeme" /// by leaving a marker and advancing ahead the offset. The lexer can then /// decide to "keep" the lexeme by erasing the marker, or abandon the current /// lexeme by moving the offset back to the marker. /// </summary> internal sealed class SlidingTextWindow : IDisposable { /// <summary> /// In many cases, e.g. PeekChar, we need the ability to indicate that there are /// no characters left and we have reached the end of the stream, or some other /// invalid or not present character was asked for. Due to perf concerns, things /// like nullable or out variables are not viable. Instead we need to choose a /// char value which can never be legal. /// /// In .NET, all characters are represented in 16 bits using the UTF-16 encoding. /// Fortunately for us, there are a variety of different bit patterns which /// are *not* legal UTF-16 characters. 0xffff (char.MaxValue) is one of these /// characters -- a legal Unicode code point, but not a legal UTF-16 bit pattern. /// </summary> public const char InvalidCharacter = char.MaxValue; private const int DefaultWindowLength = 2048; private readonly SourceText _text; // Source of text to parse. private int _basis; // Offset of the window relative to the SourceText start. private int _offset; // Offset from the start of the window. private readonly int _textEnd; // Absolute end position private char[] _characterWindow; // Moveable window of chars from source text private int _characterWindowCount; // # of valid characters in chars buffer private int _lexemeStart; // Start of current lexeme relative to the window start. // Example for the above variables: // The text starts at 0. // The window onto the text starts at basis. // The current character is at (basis + offset), AKA the current "Position". // The current lexeme started at (basis + lexemeStart), which is <= (basis + offset) // The current lexeme is the characters between the lexemeStart and the offset. private readonly StringTable _strings; private static readonly ObjectPool<char[]> s_windowPool = new ObjectPool<char[]>(() => new char[DefaultWindowLength]); public SlidingTextWindow(SourceText text) { _text = text; _basis = 0; _offset = 0; _textEnd = text.Length; _strings = StringTable.GetInstance(); _characterWindow = s_windowPool.Allocate(); _lexemeStart = 0; } public void Dispose() { if (_characterWindow != null) { s_windowPool.Free(_characterWindow); _characterWindow = null; _strings.Free(); } } public SourceText Text => _text; /// <summary> /// The current absolute position in the text file. /// </summary> public int Position { get { return _basis + _offset; } } /// <summary> /// The current offset inside the window (relative to the window start). /// </summary> public int Offset { get { return _offset; } } /// <summary> /// The buffer backing the current window. /// </summary> public char[] CharacterWindow { get { return _characterWindow; } } /// <summary> /// Returns the start of the current lexeme relative to the window start. /// </summary> public int LexemeRelativeStart { get { return _lexemeStart; } } /// <summary> /// Number of characters in the character window. /// </summary> public int CharacterWindowCount { get { return _characterWindowCount; } } /// <summary> /// The absolute position of the start of the current lexeme in the given /// SourceText. /// </summary> public int LexemeStartPosition { get { return _basis + _lexemeStart; } } /// <summary> /// The number of characters in the current lexeme. /// </summary> public int Width { get { return _offset - _lexemeStart; } } /// <summary> /// Start parsing a new lexeme. /// </summary> public void Start() { _lexemeStart = _offset; } public void Reset(int position) { // if position is within already read character range then just use what we have int relative = position - _basis; if (relative >= 0 && relative <= _characterWindowCount) { _offset = relative; } else { // we need to reread text buffer int amountToRead = Math.Min(_text.Length, position + _characterWindow.Length) - position; amountToRead = Math.Max(amountToRead, 0); if (amountToRead > 0) { _text.CopyTo(position, _characterWindow, 0, amountToRead); } _lexemeStart = 0; _offset = 0; _basis = position; _characterWindowCount = amountToRead; } } private bool MoreChars() { if (_offset >= _characterWindowCount) { if (this.Position >= _textEnd) { return false; } // if lexeme scanning is sufficiently into the char buffer, // then refocus the window onto the lexeme if (_lexemeStart > (_characterWindowCount / 4)) { Array.Copy(_characterWindow, _lexemeStart, _characterWindow, 0, _characterWindowCount - _lexemeStart); _characterWindowCount -= _lexemeStart; _offset -= _lexemeStart; _basis += _lexemeStart; _lexemeStart = 0; } if (_characterWindowCount >= _characterWindow.Length) { // grow char array, since we need more contiguous space char[] oldWindow = _characterWindow; char[] newWindow = new char[_characterWindow.Length * 2]; Array.Copy(oldWindow, 0, newWindow, 0, _characterWindowCount); s_windowPool.ForgetTrackedObject(oldWindow, newWindow); _characterWindow = newWindow; } int amountToRead = Math.Min(_textEnd - (_basis + _characterWindowCount), _characterWindow.Length - _characterWindowCount); _text.CopyTo(_basis + _characterWindowCount, _characterWindow, _characterWindowCount, amountToRead); _characterWindowCount += amountToRead; return amountToRead > 0; } return true; } /// <summary> /// After reading <see cref=" InvalidCharacter"/>, a consumer can determine /// if the InvalidCharacter was in the user's source or a sentinel. /// /// Comments and string literals are allowed to contain any Unicode character. /// </summary> /// <returns></returns> internal bool IsReallyAtEnd() { return _offset >= _characterWindowCount && Position >= _textEnd; } /// <summary> /// Advance the current position by one. No guarantee that this /// position is valid. /// </summary> public void AdvanceChar() { _offset++; } /// <summary> /// Advance the current position by n. No guarantee that this position /// is valid. /// </summary> public void AdvanceChar(int n) { _offset += n; } /// <summary> /// Grab the next character and advance the position. /// </summary> /// <returns> /// The next character, <see cref="InvalidCharacter" /> if there were no characters /// remaining. /// </returns> public char NextChar() { char c = PeekChar(); if (c != InvalidCharacter) { this.AdvanceChar(); } return c; } /// <summary> /// Gets the next character if there are any characters in the /// SourceText. May advance the window if we are at the end. /// </summary> /// <returns> /// The next character if any are available. InvalidCharacter otherwise. /// </returns> public char PeekChar() { if (_offset >= _characterWindowCount && !MoreChars()) { return InvalidCharacter; } // N.B. MoreChars may update the offset. return _characterWindow[_offset]; } /// <summary> /// Gets the character at the given offset to the current position if /// the position is valid within the SourceText. /// </summary> /// <returns> /// The next character if any are available. InvalidCharacter otherwise. /// </returns> public char PeekChar(int delta) { int position = this.Position; this.AdvanceChar(delta); char ch; if (_offset >= _characterWindowCount && !MoreChars()) { ch = InvalidCharacter; } else { // N.B. MoreChars may update the offset. ch = _characterWindow[_offset]; } this.Reset(position); return ch; } public bool IsUnicodeEscape() { if (this.PeekChar() == '\\') { var ch2 = this.PeekChar(1); if (ch2 == 'U' || ch2 == 'u') { return true; } } return false; } public char PeekCharOrUnicodeEscape(out char surrogateCharacter) { if (this.IsUnicodeEscape()) { return this.PeekUnicodeEscape(out surrogateCharacter); } else { surrogateCharacter = InvalidCharacter; return this.PeekChar(); } } public char PeekUnicodeEscape(out char surrogateCharacter) { int position = this.Position; // if we're peeking, then we don't want to change the position SyntaxDiagnosticInfo info; var ch = this.ScanUnicodeEscape(peek: true, surrogateCharacter: out surrogateCharacter, info: out info); Debug.Assert(info == null, "Never produce a diagnostic while peeking."); this.Reset(position); return ch; } public char NextCharOrUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo info) { var ch = this.PeekChar(); Debug.Assert(ch != InvalidCharacter, "Precondition established by all callers; required for correctness of AdvanceChar() call."); if (ch == '\\') { var ch2 = this.PeekChar(1); if (ch2 == 'U' || ch2 == 'u') { return this.ScanUnicodeEscape(peek: false, surrogateCharacter: out surrogateCharacter, info: out info); } } surrogateCharacter = InvalidCharacter; info = null; this.AdvanceChar(); return ch; } public char NextUnicodeEscape(out char surrogateCharacter, out SyntaxDiagnosticInfo info) { return ScanUnicodeEscape(peek: false, surrogateCharacter: out surrogateCharacter, info: out info); } private char ScanUnicodeEscape(bool peek, out char surrogateCharacter, out SyntaxDiagnosticInfo info) { surrogateCharacter = InvalidCharacter; info = null; int start = this.Position; char character = this.PeekChar(); Debug.Assert(character == '\\'); this.AdvanceChar(); character = this.PeekChar(); if (character == 'U') { uint uintChar = 0; this.AdvanceChar(); if (!SyntaxFacts.IsHexDigit(this.PeekChar())) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { for (int i = 0; i < 8; i++) { character = this.PeekChar(); if (!SyntaxFacts.IsHexDigit(character)) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } break; } uintChar = (uint)((uintChar << 4) + SyntaxFacts.HexValue(character)); this.AdvanceChar(); } if (uintChar > 0x0010FFFF) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { character = GetCharsFromUtf32(uintChar, out surrogateCharacter); } } } else { Debug.Assert(character == 'u' || character == 'x'); int intChar = 0; this.AdvanceChar(); if (!SyntaxFacts.IsHexDigit(this.PeekChar())) { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } else { for (int i = 0; i < 4; i++) { char ch2 = this.PeekChar(); if (!SyntaxFacts.IsHexDigit(ch2)) { if (character == 'u') { if (!peek) { info = CreateIllegalEscapeDiagnostic(start); } } break; } intChar = (intChar << 4) + SyntaxFacts.HexValue(ch2); this.AdvanceChar(); } character = (char)intChar; } } return character; } /// <summary> /// Given that the next character is an ampersand ('&amp;'), attempt to interpret the /// following characters as an XML entity. On success, populate the out parameters /// with the low and high UTF-16 surrogates for the character represented by the /// entity. /// </summary> /// <param name="ch">e.g. '&lt;' for &amp;lt;.</param> /// <param name="surrogate">e.g. '\uDC00' for &amp;#x10000; (ch == '\uD800').</param> /// <returns>True if a valid XML entity was consumed.</returns> /// <remarks> /// NOTE: Always advances, even on failure. /// </remarks> public bool TryScanXmlEntity(out char ch, out char surrogate) { Debug.Assert(this.PeekChar() == '&'); ch = '&'; this.AdvanceChar(); surrogate = InvalidCharacter; switch (this.PeekChar()) { case 'l': if (AdvanceIfMatches("lt;")) { ch = '<'; return true; } break; case 'g': if (AdvanceIfMatches("gt;")) { ch = '>'; return true; } break; case 'a': if (AdvanceIfMatches("amp;")) { ch = '&'; return true; } else if (AdvanceIfMatches("apos;")) { ch = '\''; return true; } break; case 'q': if (AdvanceIfMatches("quot;")) { ch = '"'; return true; } break; case '#': { this.AdvanceChar(); //# uint uintChar = 0; if (AdvanceIfMatches("x")) { char digit; while (SyntaxFacts.IsHexDigit(digit = this.PeekChar())) { this.AdvanceChar(); // disallow overflow if (uintChar <= 0x7FFFFFF) { uintChar = (uintChar << 4) + (uint)SyntaxFacts.HexValue(digit); } else { return false; } } } else { char digit; while (SyntaxFacts.IsDecDigit(digit = this.PeekChar())) { this.AdvanceChar(); // disallow overflow if (uintChar <= 0x7FFFFFF) { uintChar = (uintChar << 3) + (uintChar << 1) + (uint)SyntaxFacts.DecValue(digit); } else { return false; } } } if (AdvanceIfMatches(";")) { ch = GetCharsFromUtf32(uintChar, out surrogate); return true; } break; } } return false; } /// <summary> /// If the next characters in the window match the given string, /// then advance past those characters. Otherwise, do nothing. /// </summary> private bool AdvanceIfMatches(string desired) { int length = desired.Length; for (int i = 0; i < length; i++) { if (PeekChar(i) != desired[i]) { return false; } } AdvanceChar(length); return true; } private SyntaxDiagnosticInfo CreateIllegalEscapeDiagnostic(int start) { return new SyntaxDiagnosticInfo(start - this.LexemeStartPosition, this.Position - start, ErrorCode.ERR_IllegalEscape); } public string Intern(StringBuilder text) { return _strings.Add(text); } public string Intern(char[] array, int start, int length) { return _strings.Add(array, start, length); } public string GetInternedText() { return this.Intern(_characterWindow, _lexemeStart, this.Width); } public string GetText(bool intern) { return this.GetText(this.LexemeStartPosition, this.Width, intern); } public string GetText(int position, int length, bool intern) { int offset = position - _basis; // PERF: Whether interning or not, there are some frequently occurring // easy cases we can pick off easily. switch (length) { case 0: return string.Empty; case 1: if (_characterWindow[offset] == ' ') { return " "; } if (_characterWindow[offset] == '\n') { return "\n"; } break; case 2: char firstChar = _characterWindow[offset]; if (firstChar == '\r' && _characterWindow[offset + 1] == '\n') { return "\r\n"; } if (firstChar == '/' && _characterWindow[offset + 1] == '/') { return "//"; } break; case 3: if (_characterWindow[offset] == '/' && _characterWindow[offset + 1] == '/' && _characterWindow[offset + 2] == ' ') { return "// "; } break; } if (intern) { return this.Intern(_characterWindow, offset, length); } else { return new string(_characterWindow, offset, length); } } internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate) { if (codepoint < (uint)0x00010000) { lowSurrogate = InvalidCharacter; return (char)codepoint; } else { Debug.Assert(codepoint > 0x0000FFFF && codepoint <= 0x0010FFFF); lowSurrogate = (char)((codepoint - 0x00010000) % 0x0400 + 0xDC00); return (char)((codepoint - 0x00010000) / 0x0400 + 0xD800); } } } }
33.543329
141
0.448618
[ "MIT" ]
333fred/roslyn
src/Compilers/CSharp/Portable/Parser/SlidingTextWindow.cs
24,388
C#
// HttpJsonRequests.cs // Copyright (c) 2007 - 2021 Brain Health Alliance. All Rights Reserved. // Code license: the OSI approved Apache 2.0 License (https://opensource.org/licenses/Apache-2.0). using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace PDP.DREAM.CoreDataLib.Utilities; public static class NetHttpJsonRequests { private const string jsonMediaType = "application/json"; private static readonly HttpClientHandler hcHandlerEtol; // error tolerant handler private static readonly HttpClient httpClientEtol; // error tolerant client private static readonly HttpClient httpClient; static NetHttpJsonRequests() { hcHandlerEtol = new HttpClientHandler() { ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true }; httpClientEtol = new HttpClient(hcHandlerEtol); httpClient = new HttpClient(); } // https://docs.microsoft.com/en-us/archive/msdn-magazine/2015/july/async-programming-brownfield-async-development // https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.json?view=net-5.0 public static string? GetJsonString(string strUrl, bool ignoreSslError = false) { var jsonString = GetJsonStringAsync(strUrl, ignoreSslError).GetAwaiter().GetResult(); return jsonString; } public static async Task<string?> GetJsonStringAsync(string strUrl, bool ignoreSslError = false) { HttpClient hc; if (ignoreSslError) { hc = httpClientEtol; } else { hc = httpClient; } hc.DefaultRequestHeaders.Accept.Clear(); hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonMediaType)); string? strJson; try { strJson = await hc.GetStringAsync(strUrl); } catch (HttpRequestException) { strJson = null; } return strJson; } }
39.183673
116
0.753646
[ "Apache-2.0" ]
BHAVIUS/PDP-DREAM
PDP.DREAM.CoreDataLib/Utilities/NetHttpJsonRequests.cs
1,922
C#
using Hl.Core.ClassMapper; using System; namespace Hl.BasicData.Domain { public class SystemConfClassMapper : HlClassMapper<SystemConf> { public SystemConfClassMapper() { Table("bd_systemconf"); AutoMap(); } } }
17.1875
66
0.603636
[ "MIT" ]
DotNetExample/Surging.Sample
src/Servers/BasicData/Hl.BasicData.Domain/SystemConfs/ClassMapper/SystemConfClassMapper.cs
277
C#
/************************************************* Copyright (c) 2021 Undersoft System.Sets.Card64.cs @project: Undersoft.Vegas.Sdk @stage: Development @author: Dariusz Hanc @date: (05.06.2021) @licence MIT *************************************************/ /****************************************************************** Copyright (c) 2020 Undersoft System.Sets.Card64 Implementation of Card abstract class using 64 bit hash code and long representation; @author Darius Hanc @project NETStandard.Undersoft.SDK @version 0.8.D (Feb 7, 2020) @licence MIT ******************************************************************/ namespace System.Sets { using System.Runtime.InteropServices; using System.Uniques; /// <summary> /// Defines the <see cref="Card64{V}" />. /// </summary> /// <typeparam name="V">.</typeparam> [Serializable] [StructLayout(LayoutKind.Sequential)] public class Card64<V> : BaseCard<V> { #region Fields private ulong _key; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Card64{V}"/> class. /// </summary> public Card64() { } /// <summary> /// Initializes a new instance of the <see cref="Card64{V}"/> class. /// </summary> /// <param name="value">The value<see cref="ICard{V}"/>.</param> public Card64(ICard<V> value) : base(value) { } /// <summary> /// Initializes a new instance of the <see cref="Card64{V}"/> class. /// </summary> /// <param name="key">The key<see cref="object"/>.</param> /// <param name="value">The value<see cref="V"/>.</param> public Card64(object key, V value) : base(key, value) { } /// <summary> /// Initializes a new instance of the <see cref="Card64{V}"/> class. /// </summary> /// <param name="key">The key<see cref="ulong"/>.</param> /// <param name="value">The value<see cref="V"/>.</param> public Card64(ulong key, V value) : base(key, value) { } /// <summary> /// Initializes a new instance of the <see cref="Card64{V}"/> class. /// </summary> /// <param name="value">The value<see cref="V"/>.</param> public Card64(V value) : base(value) { } #endregion #region Properties /// <summary> /// Gets or sets the Key. /// </summary> public override ulong Key { get { return _key; } set { _key = value; } } #endregion #region Methods /// <summary> /// The CompareTo. /// </summary> /// <param name="other">The other<see cref="ICard{V}"/>.</param> /// <returns>The <see cref="int"/>.</returns> public override int CompareTo(ICard<V> other) { return (int)(Key - other.Key); } /// <summary> /// The CompareTo. /// </summary> /// <param name="other">The other<see cref="object"/>.</param> /// <returns>The <see cref="int"/>.</returns> public override int CompareTo(object other) { return (int)(Key - other.UniqueKey64()); } /// <summary> /// The CompareTo. /// </summary> /// <param name="key">The key<see cref="ulong"/>.</param> /// <returns>The <see cref="int"/>.</returns> public override int CompareTo(ulong key) { return (int)(Key - key); } /// <summary> /// The Equals. /// </summary> /// <param name="y">The y<see cref="object"/>.</param> /// <returns>The <see cref="bool"/>.</returns> public override bool Equals(object y) { return Key.Equals(y.UniqueKey64()); } /// <summary> /// The Equals. /// </summary> /// <param name="key">The key<see cref="ulong"/>.</param> /// <returns>The <see cref="bool"/>.</returns> public override bool Equals(ulong key) { return Key == key; } /// <summary> /// The GetBytes. /// </summary> /// <returns>The <see cref="byte[]"/>.</returns> public override byte[] GetBytes() { return GetUniqueBytes(); } /// <summary> /// The GetHashCode. /// </summary> /// <returns>The <see cref="int"/>.</returns> public override int GetHashCode() { return (int)Key; } /// <summary> /// The GetUniqueBytes. /// </summary> /// <returns>The <see cref="byte[]"/>.</returns> public unsafe override byte[] GetUniqueBytes() { byte[] b = new byte[8]; fixed (byte* s = b) *(ulong*)s = _key; return b; } /// <summary> /// The Set. /// </summary> /// <param name="card">The card<see cref="ICard{V}"/>.</param> public override void Set(ICard<V> card) { this.value = card.Value; _key = card.Key; } /// <summary> /// The Set. /// </summary> /// <param name="key">The key<see cref="object"/>.</param> /// <param name="value">The value<see cref="V"/>.</param> public override void Set(object key, V value) { this.value = value; _key = key.UniqueKey64(); } /// <summary> /// The Set. /// </summary> /// <param name="value">The value<see cref="V"/>.</param> public override void Set(V value) { this.value = value; _key = value.UniqueKey64(); } #endregion } }
28.202703
76
0.448011
[ "MIT" ]
undersoft-org/NET.Undersoft.Sdk.Devel
NET.Undersoft.Vegas.Sdk/Undersoft.System.Sets/Objects/Cards/Card64.cs
6,263
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; using System.IO; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return File.Exists(Interop.procfs.GetStatFilePathForProcess(processId)); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { // Parse /proc for any directory that's named with a number. Each such // directory represents a process. var pids = new List<int>(); foreach (string procDir in Directory.EnumerateDirectories(Interop.procfs.RootPath)) { string dirName = Path.GetFileName(procDir); int pid; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out pid)) { Debug.Assert(pid >= 0); pids.Add(pid); } } return pids.ToArray(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private static ProcessInfo CreateProcessInfo(int pid) { // Read /proc/pid/stat to get information about the process, and churn that into a ProcessInfo ProcessInfo pi; try { Interop.procfs.ParsedStat procFsStat = Interop.procfs.ReadStatFile(pid); pi = new ProcessInfo { _processId = pid, _processName = procFsStat.comm, _basePriority = (int)procFsStat.nice, _virtualBytes = (long)procFsStat.vsize, _workingSet = procFsStat.rss, _sessionId = procFsStat.session, _handleCount = 0, // not a Unix concept // We don't currently fill in the following values. // A few of these could probably be filled in from getrusage, // but only for the current process or its children, not for // arbitrary other processes. _poolPagedBytes = 0, _poolNonpagedBytes = 0, _virtualBytesPeak = 0, _workingSetPeak = 0, _pageFileBytes = 0, _pageFileBytesPeak = 0, _privateBytes = 0, }; } catch (FileNotFoundException) { // Between the time that we get an ID and the time that we try to read the associated stat // file(s), the process could be gone. return null; } // Then read through /proc/pid/task/ to find each thread in the process... try { string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid); foreach (string taskDir in Directory.EnumerateDirectories(tasksDir)) { string dirName = Path.GetFileName(taskDir); int tid; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid)) { // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo Interop.procfs.ParsedStat stat = Interop.procfs.ReadStatFile(pid, tid); pi._threadInfoList.Add(new ThreadInfo { _processId = pid, _threadId = tid, _basePriority = pi._basePriority, _currentPriority = (int)stat.nice, _startAddress = (IntPtr)stat.startstack, _threadState = ProcFsStateToThreadState(stat.state), _threadWaitReason = ThreadWaitReason.Unknown }); } } } catch (FileNotFoundException) { } // process and/or threads may go away by the time we try to read from them catch (DirectoryNotFoundException) { } // Finally return what we've built up return pi; } /// <summary>Gets a ThreadState to represent the value returned from the status field of /proc/pid/stat.</summary> /// <param name="c">The status field value.</param> /// <returns></returns> private static ThreadState ProcFsStateToThreadState(char c) { switch (c) { case 'R': return ThreadState.Running; case 'S': case 'D': case 'T': return ThreadState.Wait; case 'Z': return ThreadState.Terminated; case 'W': return ThreadState.Transition; default: Debug.Fail("Unexpected status character"); return ThreadState.Unknown; } } } }
41.635036
122
0.511045
[ "MIT" ]
josephwinston/corefx
src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs
5,704
C#
// ******************************************************************* // // Copyright (c) 2013-2014, Antmicro Ltd <antmicro.com> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // ******************************************************************* namespace AntShell.Terminal { public interface IIOSource { void Flush(); void Write(byte b); } }
39.222222
73
0.664306
[ "MIT" ]
UPBIoT/renode-iot
lib/AntShell/AntShell/Terminal/IIOSource.cs
1,414
C#
namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [GET] /cgi-bin/menu/delete 接口的请求。</para> /// </summary> public class CgibinMenuDeleteRequest : WechatApiRequest, IMapResponse<CgibinMenuDeleteRequest, CgibinMenuDeleteResponse> { } }
28.6
124
0.699301
[ "MIT" ]
vst-h/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinMenu/CgibinMenuDeleteRequest.cs
304
C#
namespace VitaliiPianykh.FileWall.Shared { public enum ServiceMode { Normal, BlockUndefined, AllowUndefined } }
16.444444
41
0.621622
[ "Apache-2.0" ]
caidongyun/FileWall
Shared/ServiceMode.cs
150
C#
using System; namespace DIGNDB.APP.SmitteStop.Jobs.CovidStatisticsFiles.Exceptions { public class CovidStatisticsCsvContentMultipleContentsOfTheSameTypeException : Exception { private const string ExceptionMessage = "CovidStatisticsContent cannot contain multiple definitions for files of the same type"; public CovidStatisticsCsvContentMultipleContentsOfTheSameTypeException() : base(ExceptionMessage) { } } }
32.266667
106
0.731405
[ "MIT" ]
folkehelseinstituttet/Fhi.Smittestopp.Backend
DIGNDB.APP.SmitteStop.Jobs/CovidStatisticsFiles/Exceptions/CovidStatisticsCsvContentMultipleContentsOfTheSameTypeException.cs
486
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("MedicalInsuranceOperation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MedicalInsuranceOperation")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("61d93cee-38e6-4040-b3fe-c20f16b02a21")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.243243
56
0.721936
[ "MIT" ]
axzxs2001/ChinaMedicalInsurance
ChinaMedicalInsurance/MedicalInsuranceOperation/Properties/AssemblyInfo.cs
1,322
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParkingMaster.Models.Constants { public class ErrorStrings { // Error numbers are meant to help insure that ResponseManager takes care of every error case public const string SESSION_EXPIRED = "Session has expired."; // Error 0 public const string SESSION_NOT_FOUND = "Session does not exist."; // Error 1 public const string UNAUTHORIZED_ACTION = "User is not allowed to perform requested action."; // Error 2 public const string REQUEST_FORMAT = "Invalid request format."; // Error 3 public const string FAILED_CONNECTION_CHECK = "Database connection check failed."; // Error 4 public const string DATA_ACCESS_ERROR = "Error when interacting with the data store."; // Error 5 public const string OLD_SSO_REQUEST = "Timestamp on request is too old to be processed."; // Error 6 public const string NO_FUNCTION_TO_AUTHORIZE = "No function claim provided to authorization client."; // Error 7 public const string RESOURCE_NOT_FOUND = "Requested resource does not exist."; // Error 8 public const string USER_NOT_FOUND = "User does not exist."; // Error 9 public const string USER_DISABLED = "User is currently disabled."; // Error 10 public const string USER_TOS_NOT_ACCEPTED = "User has yet to accepted the Terms of Service."; // Error 11 } }
57.192308
120
0.718225
[ "Apache-2.0" ]
CECS-491A/TM-parkingMaster
Backend/ParkingMaster.Models/Constants/ErrorStrings.cs
1,489
C#