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;
using System.Reflection;
namespace ODataDemo.Areas.HelpPage.ModelDescriptions
{
public interface IModelDocumentationProvider
{
string GetDocumentation(MemberInfo member);
string GetDocumentation(Type type);
}
} | 21.166667 | 52 | 0.748031 | [
"MIT"
] | mihairada/ODataDemo | ODataDemo/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs | 254 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
using OpenCVApp.Commands;
using OpenCVApp.Utils;
namespace OpenCVApp.ViewModels
{
internal class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _message;
private readonly bool _canExecute;
private List<MatchAndFeatureResult> _foundImageFiles;
private string _selectFolderButtonContent;
private string _searchButtonContent;
private ICommand _searchCommand;
private ICommand _cancelCommand;
private ICommand _selectFileCommand;
private ICommand _selectFolderCommand;
private ICommand _doubleClickCommandHandler;
public MainViewModel()
{
_message = "Welcome to Open CV Application";
_selectFolderButtonContent = "Select folder";
_searchButtonContent = "Search";
_canExecute = true;
}
public string Message
{
get => _message;
set
{
_message += "\n";
_message += value;
OnPropertyChanged(nameof(Message));
}
}
public string SelectFolderButtonContent
{
get => _selectFolderButtonContent;
set
{
_selectFolderButtonContent = value;
OnPropertyChanged(nameof(SelectFolderButtonContent));
}
}
public string SearchButtonContent
{
get => _searchButtonContent;
set
{
_searchButtonContent = value;
OnPropertyChanged(nameof(SearchButtonContent));
}
}
public List<MatchAndFeatureResult> FoundImageFiles
{
get => _foundImageFiles;
set
{
_foundImageFiles = value;
OnPropertyChanged(nameof(FoundImageFiles));
}
}
private MatchAndFeatureResult _displayResult;
public MatchAndFeatureResult DisplayResult
{
get => _displayResult;
set
{
_displayResult = value;
OnPropertyChanged(nameof(DisplayResult));
}
}
private void OnPropertyChanged(string message)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(message));
}
public ICommand SearchCommand => _searchCommand ?? (_searchCommand = new SearchCommandHandler(this, _canExecute));
public ICommand SelectFileCommand => _selectFileCommand ?? (_selectFileCommand = new SelectFileCommandHandler(this, _canExecute));
public ICommand SelectFolderCommand => _selectFolderCommand ?? (_selectFolderCommand = new SelectFolderCommandHandler(this, _canExecute));
public ICommand DoubleClickCommand => _doubleClickCommandHandler ?? (_doubleClickCommandHandler = new DoubleClickCommandHandler(this, _canExecute));
}
}
| 32.385417 | 156 | 0.615954 | [
"Apache-2.0"
] | mikkokok/OpenCVApp | OpenCVApp/ViewModels/MainViewModel.cs | 3,111 | C# |
namespace GitHub.ViewModels.Documents
{
/// <summary>
/// Displays a one-line summary of a commit in a pull request timeline.
/// </summary>
public interface ICommitSummaryViewModel : IViewModel
{
/// <summary>
/// Gets the abbreviated OID (SHA) of the commit.
/// </summary>
string AbbreviatedOid { get; }
/// <summary>
/// Gets the commit author.
/// </summary>
ICommitActorViewModel Author { get; }
/// <summary>
/// Gets the commit message header.
/// </summary>
string Header { get; }
/// <summary>
/// Gets the OID (SHA) of the commit.
/// </summary>
string Oid { get; }
}
} | 26.285714 | 75 | 0.529891 | [
"MIT"
] | 123balu42/VisualStudio | src/GitHub.Exports.Reactive/ViewModels/Documents/ICommitSummaryViewModel.cs | 738 | C# |
namespace MS.Lib.Data.Abstractions.Entities
{
/// <summary>
/// 实体Sql生成器
/// </summary>
public interface IEntitySqlBuilder
{
/// <summary>
/// 生成
/// </summary>
/// <returns></returns>
EntitySql Build();
}
} | 19.428571 | 44 | 0.5 | [
"MIT"
] | billowliu2/MS | src/Framework/Data/Core/Data.Abstractions/Entities/IEntitySqlBuilder.cs | 288 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using GitHub.DistributedTask.Expressions2;
using GitHub.DistributedTask.ObjectTemplating.Tokens;
using GitHub.DistributedTask.Pipelines.ContextData;
using GitHub.DistributedTask.Pipelines.ObjectTemplating;
using GitHub.DistributedTask.WebApi;
using GitHub.Runner.Common;
using GitHub.Runner.Common.Util;
using GitHub.Runner.Sdk;
using Pipelines = GitHub.DistributedTask.Pipelines;
namespace GitHub.Runner.Worker
{
[DataContract]
public class SetupInfo
{
[DataMember]
public string Group { get; set; }
[DataMember]
public string Detail { get; set; }
}
[ServiceLocator(Default = typeof(JobExtension))]
public interface IJobExtension : IRunnerService
{
Task<List<IStep>> InitializeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message);
void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc);
}
public sealed class JobExtension : RunnerService, IJobExtension
{
private readonly HashSet<string> _existingProcesses = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private bool _processCleanup;
private string _processLookupId = $"github_{Guid.NewGuid()}";
// Download all required actions.
// Make sure all condition inputs are valid.
// Build up three list of steps for jobrunner (pre-job, job, post-job).
public async Task<List<IStep>> InitializeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message)
{
Trace.Entering();
ArgUtil.NotNull(jobContext, nameof(jobContext));
ArgUtil.NotNull(message, nameof(message));
// Create a new timeline record for 'Set up job'
IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Set up job", $"{nameof(JobExtension)}_Init", null, null);
List<IStep> preJobSteps = new List<IStep>();
List<IStep> jobSteps = new List<IStep>();
using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
{
try
{
context.Start();
context.Debug($"Starting: Set up job");
context.Output($"Current runner version: '{BuildConstants.RunnerPackage.Version}'");
var setupInfoFile = HostContext.GetConfigFile(WellKnownConfigFile.SetupInfo);
if (File.Exists(setupInfoFile))
{
Trace.Info($"Load machine setup info from {setupInfoFile}");
try
{
var setupInfo = IOUtil.LoadObject<List<SetupInfo>>(setupInfoFile);
if (setupInfo?.Count > 0)
{
foreach (var info in setupInfo)
{
if (!string.IsNullOrEmpty(info?.Detail))
{
var groupName = info.Group;
if (string.IsNullOrEmpty(groupName))
{
groupName = "Machine Setup Info";
}
context.Output($"##[group]{groupName}");
var multiLines = info.Detail.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
foreach (var line in multiLines)
{
context.Output(line);
}
context.Output("##[endgroup]");
}
}
}
}
catch (Exception ex)
{
context.Output($"Fail to load and print machine setup info: {ex.Message}");
Trace.Error(ex);
}
}
var repoFullName = context.GetGitHubContext("repository");
ArgUtil.NotNull(repoFullName, nameof(repoFullName));
context.Debug($"Primary repository: {repoFullName}");
// Print proxy setting information for better diagnostic experience
if (!string.IsNullOrEmpty(HostContext.WebProxy.HttpProxyAddress))
{
context.Output($"Runner is running behind proxy server '{HostContext.WebProxy.HttpProxyAddress}' for all HTTP requests.");
}
if (!string.IsNullOrEmpty(HostContext.WebProxy.HttpsProxyAddress))
{
context.Output($"Runner is running behind proxy server '{HostContext.WebProxy.HttpsProxyAddress}' for all HTTPS requests.");
}
// Prepare the workflow directory
context.Output("Prepare workflow directory");
var directoryManager = HostContext.GetService<IPipelineDirectoryManager>();
TrackingConfig trackingConfig = directoryManager.PrepareDirectory(
context,
message.Workspace);
// Set the directory variables
context.Debug("Update context data");
string _workDirectory = HostContext.GetDirectory(WellKnownDirectory.Work);
context.SetRunnerContext("workspace", Path.Combine(_workDirectory, trackingConfig.PipelineDirectory));
context.SetGitHubContext("workspace", Path.Combine(_workDirectory, trackingConfig.WorkspaceDirectory));
// Temporary hack for GHES alpha
var configurationStore = HostContext.GetService<IConfigurationStore>();
var runnerSettings = configurationStore.GetSettings();
if (string.IsNullOrEmpty(context.GetGitHubContext("url")) && !runnerSettings.IsHostedServer && !string.IsNullOrEmpty(runnerSettings.GitHubUrl))
{
var url = new Uri(runnerSettings.GitHubUrl);
var portInfo = url.IsDefaultPort ? string.Empty : $":{url.Port.ToString(CultureInfo.InvariantCulture)}";
context.SetGitHubContext("url", $"{url.Scheme}://{url.Host}{portInfo}");
context.SetGitHubContext("api_url", $"{url.Scheme}://{url.Host}{portInfo}/api/v3");
}
// Evaluate the job-level environment variables
context.Debug("Evaluating job-level environment variables");
var templateEvaluator = context.ToPipelineTemplateEvaluator();
foreach (var token in message.EnvironmentVariables)
{
var environmentVariables = templateEvaluator.EvaluateStepEnvironment(token, jobContext.ExpressionValues, jobContext.ExpressionFunctions, VarUtil.EnvironmentVariableKeyComparer);
foreach (var pair in environmentVariables)
{
context.EnvironmentVariables[pair.Key] = pair.Value ?? string.Empty;
context.SetEnvContext(pair.Key, pair.Value ?? string.Empty);
}
}
// Evaluate the job container
context.Debug("Evaluating job container");
var container = templateEvaluator.EvaluateJobContainer(message.JobContainer, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
if (container != null)
{
jobContext.Container = new Container.ContainerInfo(HostContext, container);
}
// Evaluate the job service containers
context.Debug("Evaluating job service containers");
var serviceContainers = templateEvaluator.EvaluateJobServiceContainers(message.JobServiceContainers, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
if (serviceContainers?.Count > 0)
{
foreach (var pair in serviceContainers)
{
var networkAlias = pair.Key;
var serviceContainer = pair.Value;
jobContext.ServiceContainers.Add(new Container.ContainerInfo(HostContext, serviceContainer, false, networkAlias));
}
}
// Evaluate the job defaults
context.Debug("Evaluating job defaults");
foreach (var token in message.Defaults)
{
var defaults = token.AssertMapping("defaults");
if (defaults.Any(x => string.Equals(x.Key.AssertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase)))
{
context.JobDefaults["run"] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var defaultsRun = defaults.First(x => string.Equals(x.Key.AssertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase));
var jobDefaults = templateEvaluator.EvaluateJobDefaultsRun(defaultsRun.Value, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
foreach (var pair in jobDefaults)
{
if (!string.IsNullOrEmpty(pair.Value))
{
context.JobDefaults["run"][pair.Key] = pair.Value;
}
}
}
}
// Build up 2 lists of steps, pre-job, job
// Download actions not already in the cache
Trace.Info("Downloading actions");
var actionManager = HostContext.GetService<IActionManager>();
var prepareResult = await actionManager.PrepareActionsAsync(context, message.Steps);
preJobSteps.AddRange(prepareResult.ContainerSetupSteps);
// Add start-container steps, record and stop-container steps
if (jobContext.Container != null || jobContext.ServiceContainers.Count > 0)
{
var containerProvider = HostContext.GetService<IContainerOperationProvider>();
var containers = new List<Container.ContainerInfo>();
if (jobContext.Container != null)
{
containers.Add(jobContext.Container);
}
containers.AddRange(jobContext.ServiceContainers);
preJobSteps.Add(new JobExtensionRunner(runAsync: containerProvider.StartContainersAsync,
condition: $"{PipelineTemplateConstants.Success}()",
displayName: "Initialize containers",
data: (object)containers));
}
// Add action steps
foreach (var step in message.Steps)
{
if (step.Type == Pipelines.StepType.Action)
{
var action = step as Pipelines.ActionStep;
Trace.Info($"Adding {action.DisplayName}.");
var actionRunner = HostContext.CreateService<IActionRunner>();
actionRunner.Action = action;
actionRunner.Stage = ActionRunStage.Main;
actionRunner.Condition = step.Condition;
var contextData = new Pipelines.ContextData.DictionaryContextData();
if (message.ContextData?.Count > 0)
{
foreach (var pair in message.ContextData)
{
contextData[pair.Key] = pair.Value;
}
}
actionRunner.TryEvaluateDisplayName(contextData, context);
jobSteps.Add(actionRunner);
if (prepareResult.PreStepTracker.TryGetValue(step.Id, out var preStep))
{
Trace.Info($"Adding pre-{action.DisplayName}.");
preStep.TryEvaluateDisplayName(contextData, context);
preStep.DisplayName = $"Pre {preStep.DisplayName}";
preJobSteps.Add(preStep);
}
}
}
var intraActionStates = new Dictionary<Guid, Dictionary<string, string>>();
foreach (var preStep in prepareResult.PreStepTracker)
{
intraActionStates[preStep.Key] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
// Create execution context for pre-job steps
foreach (var step in preJobSteps)
{
if (step is JobExtensionRunner)
{
JobExtensionRunner extensionStep = step as JobExtensionRunner;
ArgUtil.NotNull(extensionStep, extensionStep.DisplayName);
Guid stepId = Guid.NewGuid();
extensionStep.ExecutionContext = jobContext.CreateChild(stepId, extensionStep.DisplayName, null, null, stepId.ToString("N"));
}
else if (step is IActionRunner actionStep)
{
ArgUtil.NotNull(actionStep, step.DisplayName);
Guid stepId = Guid.NewGuid();
actionStep.ExecutionContext = jobContext.CreateChild(stepId, actionStep.DisplayName, stepId.ToString("N"), null, null, intraActionStates[actionStep.Action.Id]);
}
}
// Create execution context for job steps
foreach (var step in jobSteps)
{
if (step is IActionRunner actionStep)
{
ArgUtil.NotNull(actionStep, step.DisplayName);
intraActionStates.TryGetValue(actionStep.Action.Id, out var intraActionState);
actionStep.ExecutionContext = jobContext.CreateChild(actionStep.Action.Id, actionStep.DisplayName, actionStep.Action.Name, actionStep.Action.ScopeName, actionStep.Action.ContextName, intraActionState);
}
}
List<IStep> steps = new List<IStep>();
steps.AddRange(preJobSteps);
steps.AddRange(jobSteps);
// Prepare for orphan process cleanup
_processCleanup = false; // Disable process cleanup
if (_processCleanup)
{
// Set the RUNNER_TRACKING_ID env variable.
Environment.SetEnvironmentVariable(Constants.ProcessTrackingId, _processLookupId);
context.Debug("Collect running processes for tracking orphan processes.");
// Take a snapshot of current running processes
Dictionary<int, Process> processes = SnapshotProcesses();
foreach (var proc in processes)
{
// Pid_ProcessName
_existingProcesses.Add($"{proc.Key}_{proc.Value.ProcessName}");
}
}
return steps;
}
catch (OperationCanceledException ex) when (jobContext.CancellationToken.IsCancellationRequested)
{
// Log the exception and cancel the JobExtension Initialization.
Trace.Error($"Caught cancellation exception from JobExtension Initialization: {ex}");
context.Error(ex);
context.Result = TaskResult.Canceled;
throw;
}
catch (Exception ex)
{
// Log the error and fail the JobExtension Initialization.
Trace.Error($"Caught exception from JobExtension Initialization: {ex}");
context.Error(ex);
context.Result = TaskResult.Failed;
throw;
}
finally
{
context.Debug("Finishing: Set up job");
context.Complete();
}
}
}
public void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc)
{
Trace.Entering();
ArgUtil.NotNull(jobContext, nameof(jobContext));
// create a new timeline record node for 'Finalize job'
IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Complete job", $"{nameof(JobExtension)}_Final", null, null);
using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
{
try
{
context.Start();
context.Debug("Starting: Complete job");
// Evaluate job outputs
if (message.JobOutputs != null && message.JobOutputs.Type != TokenType.Null)
{
try
{
context.Output($"Evaluate and set job outputs");
// Populate env context for each step
Trace.Info("Initialize Env context for evaluating job outputs");
#if OS_WINDOWS
var envContext = new DictionaryContextData();
#else
var envContext = new CaseSensitiveDictionaryContextData();
#endif
context.ExpressionValues["env"] = envContext;
foreach (var pair in context.EnvironmentVariables)
{
envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
}
Trace.Info("Initialize steps context for evaluating job outputs");
context.ExpressionValues["steps"] = context.StepsContext.GetScope(context.ScopeName);
var templateEvaluator = context.ToPipelineTemplateEvaluator();
var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
foreach (var output in outputs)
{
if (string.IsNullOrEmpty(output.Value))
{
context.Debug($"Skip output '{output.Key}' since it's empty");
continue;
}
if (!string.Equals(output.Value, HostContext.SecretMasker.MaskSecrets(output.Value)))
{
context.Warning($"Skip output '{output.Key}' since it may contain secret.");
continue;
}
context.Output($"Set output '{output.Key}'");
jobContext.JobOutputs[output.Key] = output.Value;
}
}
catch (Exception ex)
{
context.Result = TaskResult.Failed;
context.Error($"Fail to evaluate job outputs");
context.Error(ex);
jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
}
}
if (context.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
{
Trace.Info("Support log upload starting.");
context.Output("Uploading runner diagnostic logs");
IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>();
try
{
diagnosticLogManager.UploadDiagnosticLogs(executionContext: context, parentContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc);
Trace.Info("Support log upload complete.");
context.Output("Completed runner diagnostic log upload");
}
catch (Exception ex)
{
// Log the error but make sure we continue gracefully.
Trace.Info("Error uploading support logs.");
context.Output("Error uploading runner diagnostic logs");
Trace.Error(ex);
}
}
if (_processCleanup)
{
context.Output("Cleaning up orphan processes");
// Only check environment variable for any process that doesn't run before we invoke our process.
Dictionary<int, Process> currentProcesses = SnapshotProcesses();
foreach (var proc in currentProcesses)
{
if (proc.Key == Process.GetCurrentProcess().Id)
{
// skip for current process.
continue;
}
if (_existingProcesses.Contains($"{proc.Key}_{proc.Value.ProcessName}"))
{
Trace.Verbose($"Skip existing process. PID: {proc.Key} ({proc.Value.ProcessName})");
}
else
{
Trace.Info($"Inspecting process environment variables. PID: {proc.Key} ({proc.Value.ProcessName})");
string lookupId = null;
try
{
lookupId = proc.Value.GetEnvironmentVariable(HostContext, Constants.ProcessTrackingId);
}
catch (Exception ex)
{
Trace.Warning($"Ignore exception during read process environment variables: {ex.Message}");
Trace.Verbose(ex.ToString());
}
if (string.Equals(lookupId, _processLookupId, StringComparison.OrdinalIgnoreCase))
{
context.Output($"Terminate orphan process: pid ({proc.Key}) ({proc.Value.ProcessName})");
try
{
proc.Value.Kill();
}
catch (Exception ex)
{
Trace.Error("Catch exception during orphan process cleanup.");
Trace.Error(ex);
}
}
}
}
}
}
catch (Exception ex)
{
// Log and ignore the error from JobExtension finalization.
Trace.Error($"Caught exception from JobExtension finalization: {ex}");
context.Output(ex.Message);
}
finally
{
context.Debug("Finishing: Complete job");
context.Complete();
}
}
}
private Dictionary<int, Process> SnapshotProcesses()
{
Dictionary<int, Process> snapshot = new Dictionary<int, Process>();
foreach (var proc in Process.GetProcesses())
{
try
{
// On Windows, this will throw exception on error.
// On Linux, this will be NULL on error.
if (!string.IsNullOrEmpty(proc.ProcessName))
{
snapshot[proc.Id] = proc;
}
}
catch (Exception ex)
{
Trace.Verbose($"Ignore any exception during taking process snapshot of process pid={proc.Id}: '{ex.Message}'.");
}
}
Trace.Info($"Total accessible running process: {snapshot.Count}.");
return snapshot;
}
}
}
| 52.02729 | 229 | 0.484938 | [
"MIT"
] | base-up/runner | src/Runner.Worker/JobExtension.cs | 26,692 | C# |
namespace LegoTrainProject.Main_UI
{
partial class FormWelcome
{
/// <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(FormWelcome));
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.button1 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.richTextBox1.Location = new System.Drawing.Point(10, 141);
this.richTextBox1.Margin = new System.Windows.Forms.Padding(8, 8, 8, 8);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.RightMargin = 500;
this.richTextBox1.ShowSelectionMargin = true;
this.richTextBox1.Size = new System.Drawing.Size(483, 264);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = resources.GetString("richTextBox1.Text");
this.richTextBox1.TextChanged += new System.EventHandler(this.richTextBox1_TextChanged);
//
// button1
//
this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.button1.Location = new System.Drawing.Point(407, 11);
this.button1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(76, 27);
this.button1.TabIndex = 2;
this.button1.Text = "Close";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// pictureBox1
//
this.pictureBox1.Image = global::LegoTrainProject.Properties.Resources._2019_02_09_17_51_12;
this.pictureBox1.Location = new System.Drawing.Point(10, 11);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(134, 119);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 3;
this.pictureBox1.TabStop = false;
//
// richTextBox2
//
this.richTextBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.richTextBox2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.richTextBox2.Location = new System.Drawing.Point(153, 11);
this.richTextBox2.Margin = new System.Windows.Forms.Padding(8, 8, 8, 8);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.ShowSelectionMargin = true;
this.richTextBox2.Size = new System.Drawing.Size(244, 119);
this.richTextBox2.TabIndex = 4;
this.richTextBox2.Text = resources.GetString("richTextBox2.Text");
//
// FormWelcome
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(501, 420);
this.Controls.Add(this.richTextBox2);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.richTextBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Name = "FormWelcome";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Welcome & Thank you!";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.RichTextBox richTextBox2;
}
} | 42.378151 | 152 | 0.729526 | [
"MIT"
] | Cosmik42/BAP | LTP.Desktop/Main UI/FormWelcome.Designer.cs | 5,045 | C# |
namespace CloudinaryDotNet.Actions
{
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// Parsed result of folder deletion.
/// </summary>
[DataContract]
public class DeleteFolderResult : BaseResult
{
/// <summary>
/// The list of media assets requested for deletion, with the status of each asset (deleted unless there was an issue).
/// </summary>
[DataMember(Name = "deleted")]
public List<string> Deleted { get; protected set; }
}
}
| 28.947368 | 127 | 0.636364 | [
"MIT"
] | jordansjones/CloudinaryDotNet | Shared/Actions/DeleteFolderResult.cs | 552 | C# |
namespace Epsiloner.Wpf.Keyboard.KeyBinding
{
/// <summary>
/// Manager update mode.
/// </summary>
public enum ManagerUpdateMode
{
/// <summary>
/// Can only update gestures for existing configs.
/// </summary>
OnlyUpdateExisting,
/// <summary>
/// Updates existing gestures and creates new.
/// </summary>
Full,
}
} | 22.611111 | 58 | 0.545455 | [
"MIT"
] | Epsil0neR/Epsiloner.Wpf.Keyboard | Epsiloner.Wpf.Keyboard/Epsiloner.Wpf.Keyboard/KeyBinding/ManagerUpdateMode.cs | 409 | C# |
//#define MB_DEBUG
using UnityEngine;
using static MenteBacata.ScivoloCharacterController.Internal.ShapeCaster;
namespace MenteBacata.ScivoloCharacterController.Internal
{
public static class CapsuleSweepTester
{
private const float extraDistanceOverBuffer = 8f;
/// <summary>
/// It sweeps the capsule along the given direction. The returned hit distance accounts for the buffer distance as if the
/// capsule stopped at a buffer distance from the hit point surface. Buffer distance is not guaranteed be kept if the
/// capsule starts inside the buffer distance or the angle between the direction and the hit normal is too small.
/// </summary>
public static bool CapsuleSweepTestWithBuffer(in Vector3 lowerCenter, in Vector3 upperCenter, float radius, in Vector3 direction,
float maxDistance, float buffer, LayerMask collisionMask, Collider colliderToIgnore, out RaycastHit hit)
{
float extraDistance = extraDistanceOverBuffer * buffer;
if (CapsuleCast(lowerCenter, upperCenter, radius, direction, maxDistance + extraDistance, collisionMask, colliderToIgnore, out hit))
{
float dot = Math.Dot(direction, hit.normal);
if (dot >= 0f)
{
hit.distance -= extraDistance;
}
else
{
hit.distance -= Mathf.Min(-buffer / dot, extraDistance);
}
if (hit.distance >= maxDistance)
{
return false;
}
if (hit.distance < 0f)
hit.distance = 0f;
return true;
}
else
{
return false;
}
}
}
}
| 36.557692 | 145 | 0.565492 | [
"MIT"
] | zaun/endless-world | E09/unity/Assets/Scripts/3rd Party/Scivolo Character Controller/Scripts/Internal/CapsuleSweepTester.cs | 1,903 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Elb.V3.Model
{
/// <summary>
/// Response Object
/// </summary>
public class UpdateIpListResponse : SdkResponse
{
/// <summary>
///
/// </summary>
[JsonProperty("ipgroup", NullValueHandling = NullValueHandling.Ignore)]
public IpGroup Ipgroup { get; set; }
/// <summary>
/// 请求ID。 注:自动生成 。
/// </summary>
[JsonProperty("request_id", NullValueHandling = NullValueHandling.Ignore)]
public string RequestId { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UpdateIpListResponse {\n");
sb.Append(" ipgroup: ").Append(Ipgroup).Append("\n");
sb.Append(" requestId: ").Append(RequestId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as UpdateIpListResponse);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(UpdateIpListResponse input)
{
if (input == null)
return false;
return
(
this.Ipgroup == input.Ipgroup ||
(this.Ipgroup != null &&
this.Ipgroup.Equals(input.Ipgroup))
) &&
(
this.RequestId == input.RequestId ||
(this.RequestId != null &&
this.RequestId.Equals(input.RequestId))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Ipgroup != null)
hashCode = hashCode * 59 + this.Ipgroup.GetHashCode();
if (this.RequestId != null)
hashCode = hashCode * 59 + this.RequestId.GetHashCode();
return hashCode;
}
}
}
}
| 28.766667 | 82 | 0.501352 | [
"Apache-2.0"
] | huaweicloud/huaweicloud-sdk-net | Services/Elb/V3/Model/UpdateIpListResponse.cs | 2,609 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Perfon.Core.Common;
using Perfon.Core.PerfCounters;
using Perfon.Interfaces.Common;
using Perfon.Interfaces.PerfCounterStorage;
namespace Perfon.Core.PerfCounterStorages.CSVFileStorage
{
/// <summary>
/// Driver for store/restore performance counter values in simple CSV file
/// Fie names are one per date: perfCounters_yyyy-MM-dd.csv
/// </summary>
public class PerfCounterCSVFileStorage:IPerfomanceCountersStorage
{
private string PathToDb { get; set; }
public string ColumnDelimiter { get; set; }
public PerfCounterCSVFileStorage(string pathToDb)
{
PathToDb = pathToDb+"\\";
ColumnDelimiter = ";";
}
/// <summary>
/// Awaitable.
/// Stores perf counters into file as a line
/// Add headers if file doesn't exists
/// </summary>
/// <param name="counters"></param>
/// <returns></returns>
public async Task StorePerfCounters(IEnumerable<IPerfCounterInputData> counters, DateTime? now = null, string appId = null)
{
try
{
var sb = new StringBuilder();
DateTime date = DateTime.Now.Date;
var dbName = GetDbName(date);
if (!File.Exists(PathToDb + dbName))
{
//store headers
sb.Append("time").Append(ColumnDelimiter);
foreach (var item in counters)
{
sb.Append(item.Name).Append(ColumnDelimiter);
}
sb.Append(Environment.NewLine);
}
sb.Append(DateTime.Now).Append(ColumnDelimiter);
foreach (var item in counters)
{
sb.Append(item.FormattedValue).Append(ColumnDelimiter);
}
sb.Append(Environment.NewLine);
var file = File.AppendText(PathToDb + dbName);
await file.WriteAsync(sb.ToString());
file.Flush();
file.Dispose();
}
catch (Exception exc)
{
if (OnError != null)
{
OnError(new object(), new PerfonErrorEventArgs(exc.ToString()));
}
}
}
public Task<IEnumerable<IPerfCounterValue>> QueryCounterValues(string counterName, DateTime? date = null, int skip = 0, string appId = null)
{
var list = new List<IPerfCounterValue>();
if (!date.HasValue)
{
date = DateTime.Now;
}
var dbName = GetDbName(date.Value);
if (File.Exists(PathToDb + dbName))
{
var lines = File.ReadLines(PathToDb + dbName).GetEnumerator();
if (lines != null)
{
lines.MoveNext();
var headers = lines.Current.ToString().Split(new string[] { ColumnDelimiter }, StringSplitOptions.RemoveEmptyEntries);
var columnIdx = headers.ToList().IndexOf(counterName);
if (columnIdx >= 0)
{
while (lines.MoveNext())
{
var values = lines.Current.ToString().Split(new string[] { ColumnDelimiter }, StringSplitOptions.RemoveEmptyEntries);
if (columnIdx < values.Length)
{
var item = new PerfCounterValue(DateTime.Parse(values[0]), float.Parse(values[columnIdx]));
if (item.Timestamp.Date == date.Value.Date)
{
list.Add(item);
}
}
}
}
}
}
return Task.FromResult(list as IEnumerable<IPerfCounterValue>);
}
public Task<IEnumerable<string>> GetCountersList()
{
var res = new List<string>();
DateTime date = DateTime.Now.Date;
var dbName = GetDbName(date);
if (File.Exists(PathToDb + dbName))
{
var lines = File.ReadLines(PathToDb + dbName);
if (lines != null)
{
var line = lines.FirstOrDefault();
if (line != null)
{
var headers = line.Split(new string[]{ColumnDelimiter}, StringSplitOptions.RemoveEmptyEntries);
res = headers.ToList<string>();
}
}
}
return Task.FromResult(res as IEnumerable<string>);
}
/// <summary>
/// Reports about errors and exceptions occured.
/// </summary>
public event EventHandler<IPerfonErrorEventArgs> OnError;
private static string GetDbName(DateTime now)
{
return "perfCounters_" + now.ToString("yyyy-MM-dd") + ".csv";
}
}
}
| 34.031847 | 148 | 0.493917 | [
"MIT"
] | magsoft2/Perfon.Net | Perfon.Core/PerfCounterStorages/CSVFileStorage/PerfCounterCSVFileStorage.cs | 5,345 | C# |
// <copyright file="MeasureMapBase.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// 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.
// </copyright>
using OpenTelemetry.Context;
using OpenTelemetry.Stats.Measures;
namespace OpenTelemetry.Stats
{
public abstract class MeasureMapBase : IMeasureMap
{
public abstract IMeasureMap Put(IMeasureDouble measure, double value);
public abstract IMeasureMap Put(IMeasureLong measure, long value);
public abstract void Record();
public abstract void Record(ITagContext tags);
}
}
| 34.5625 | 78 | 0.74141 | [
"Apache-2.0"
] | alexvaluyskiy/opentelemetry-dotnet | src/OpenTelemetry/Stats/MeasureMapBase.cs | 1,108 | C# |
using System.Text;
namespace Page316.HideInHouse
{
public abstract class Location
{
protected Location(string name)
{
this.name = name;
}
private readonly string name;
public string Name
{
get { return name; }
}
public Location[] Exists;
public virtual string Description
{
get
{
var description = new StringBuilder();
description.Append("You're standing in the ");
description.Append(name);
description.Append(". You see exits to the following places: ");
for (int i = 0; i < Exists.Length; i++)
{
description.Append(" " + Exists[i].Name);
if (i != Exists.Length - 1)
description.Append(", ");
}
description.Append(".");
return description.ToString(); ;
}
}
}
} | 25.9 | 80 | 0.457529 | [
"MIT"
] | renebentes/HeadFirstCSharp | Cap7/Page316.HideInHouse/Location.cs | 1,038 | C# |
using System;
using System.Windows.Media.Media3D;
using System.Windows.Media;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Dynamic;
using ESAPIX.Extensions;
using VMS.TPS.Common.Model.Types;
using XC = ESAPIX.Common.AppComThread;
using V = VMS.TPS.Common.Model.API;
using Types = VMS.TPS.Common.Model.Types;
namespace ESAPIX.Facade.API
{
public class Application : ESAPIX.Facade.API.SerializableObject, System.Xml.Serialization.IXmlSerializable, System.IDisposable
{
public ESAPIX.Facade.API.User CurrentUser
{
get
{
if ((_client) is System.Dynamic.ExpandoObject)
{
if (((ExpandoObject)(_client)).HasProperty("CurrentUser"))
{
return _client.CurrentUser;
}
else
{
return default (ESAPIX.Facade.API.User);
}
}
else if ((XC.Instance) != (null))
{
return XC.Instance.GetValue(sc =>
{
if ((_client.CurrentUser) != (null))
{
return new ESAPIX.Facade.API.User(_client.CurrentUser);
}
else
{
return null;
}
}
);
}
else
{
return default (ESAPIX.Facade.API.User);
}
}
set
{
if ((_client) is System.Dynamic.ExpandoObject)
{
_client.CurrentUser = (value);
}
else
{
}
}
}
public IEnumerable<ESAPIX.Facade.API.PatientSummary> PatientSummaries
{
get
{
if (_client is ExpandoObject)
{
if ((_client as ExpandoObject).HasProperty("PatientSummaries"))
{
foreach (var item in _client.PatientSummaries)
{
yield return item;
}
}
else
{
yield break;
}
}
else
{
IEnumerator enumerator = null;
XC.Instance.Invoke(() =>
{
var asEnum = (IEnumerable)_client.PatientSummaries;
if ((asEnum) != null)
{
enumerator = asEnum.GetEnumerator();
}
}
);
if (enumerator == null)
{
yield break;
}
while (XC.Instance.GetValue<bool>(sc => enumerator.MoveNext()))
{
var facade = new ESAPIX.Facade.API.PatientSummary();
XC.Instance.Invoke(() =>
{
var vms = enumerator.Current;
if (vms != null)
{
facade._client = vms;
}
}
);
if (facade._client != null)
{
yield return facade;
}
}
}
}
set
{
if (_client is ExpandoObject)
_client.PatientSummaries = value;
}
}
public static ESAPIX.Facade.API.Application CreateApplication(System.String username, System.String password)
{
return StaticHelper.Application_CreateApplication(username, password);
}
public static ESAPIX.Facade.API.Application CreateApplication()
{
return StaticHelper.Application_CreateApplication();
}
public ESAPIX.Facade.API.Patient OpenPatient(ESAPIX.Facade.API.PatientSummary patientSummary)
{
if ((XC.Instance) != (null))
{
var vmsResult = (XC.Instance.GetValue(sc =>
{
var fromClient = (_client.OpenPatient(patientSummary._client));
if ((fromClient) == (null))
{
return null;
}
return new ESAPIX.Facade.API.Patient(fromClient);
}
));
return vmsResult;
}
else
{
return (ESAPIX.Facade.API.Patient)(_client.OpenPatient(patientSummary));
}
}
public ESAPIX.Facade.API.Patient OpenPatientById(System.String id)
{
if ((XC.Instance) != (null))
{
var vmsResult = (XC.Instance.GetValue(sc =>
{
var fromClient = (_client.OpenPatientById(id));
if ((fromClient) == (null))
{
return null;
}
return new ESAPIX.Facade.API.Patient(fromClient);
}
));
return vmsResult;
}
else
{
return (ESAPIX.Facade.API.Patient)(_client.OpenPatientById(id));
}
}
public void ClosePatient()
{
if ((XC.Instance) != (null))
{
XC.Instance.Invoke(() =>
{
_client.ClosePatient();
}
);
}
else
{
_client.ClosePatient();
}
}
public void SaveModifications()
{
if ((XC.Instance) != (null))
{
XC.Instance.Invoke(() =>
{
_client.SaveModifications();
}
);
}
else
{
_client.SaveModifications();
}
}
public void Dispose()
{
if ((XC.Instance) != (null))
{
XC.Instance.Invoke(() =>
{
_client.Dispose();
}
);
}
else
{
_client.Dispose();
}
}
public Application()
{
_client = (new ExpandoObject());
}
public Application(dynamic client)
{
_client = (client);
}
}
} | 28.432 | 130 | 0.376618 | [
"MIT"
] | avalgoma/ESAPIX | ESAPIX/Facade/API15.0/Application.cs | 7,108 | C# |
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
public class Mole : MonoBehaviour
{
/// <summary>
/// Used to animate and scale the mole
/// </summary>
public MoleVisuals visuals;
public UnityAction<Mole, bool> OnMoleDied;
[HideInInspector]
public MoleData data;
/// <summary>
/// Spawn the mole at a given position.
/// </summary>
/// <param name="pos"> randon position to spawn at </param>
/// <param name="d"> data as a scriptable object </param>
public void Respawn(Vector2 pos, MoleData d)
{
data = d;
gameObject.GetComponent<RectTransform>().localPosition = pos;
gameObject.SetActive(true);
StartCoroutine("Timer");
visuals.Respawn(data);
}
/// <summary>
/// Despawn the mole.
/// </summary>
public void Despawn()
{
if (gameObject.activeSelf == false)
return;
gameObject.SetActive(false);
}
/// <summary>
/// Called when the mole is clicked.
/// </summary>
public void MoleClicked()
{
StopCoroutine("Timer");
OnMoleDied(this, true);
Despawn();
}
IEnumerator Timer()
{
yield return new WaitForSeconds(data.timeOnScreen);
OnMoleDied(this, false);
Despawn();
}
}
| 21.967213 | 69 | 0.586567 | [
"MIT"
] | amnasheikh1/WackAMoleMSFinal | Whack-A-Mole/Assets/Scripts/Mole.cs | 1,342 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT license.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1601:EnableXmlDocumentationOutput", Justification = "Reviewed.")]
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1652:PartialElementsMustBeDocumented", Justification = "Reviewed.")]
[assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1309:FieldNamesMustNotBeginWithUnderscore", Justification = "Reviewed.")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:PrefixLocalCallsWithThis", Justification = "Reviewed.")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Reviewed.")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1121:UseBuiltInTypeAlias", Justification = "Reviewed.")] | 77.833333 | 136 | 0.810493 | [
"MIT"
] | pareshjoshi/MSBuildSdks | src/GlobalSuppressions.cs | 936 | 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 imagebuilder-2019-12-02.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.Imagebuilder.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Imagebuilder.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteComponent operation
/// </summary>
public class DeleteComponentResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DeleteComponentResponse response = new DeleteComponentResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("componentBuildVersionArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.ComponentBuildVersionArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("requestId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.RequestId = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("CallRateLimitExceededException"))
{
return new CallRateLimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ClientException"))
{
return new ClientException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException"))
{
return new ForbiddenException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException"))
{
return new InvalidRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceDependencyException"))
{
return new ResourceDependencyException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException"))
{
return new ServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return new ServiceUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonImagebuilderException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DeleteComponentResponseUnmarshaller _instance = new DeleteComponentResponseUnmarshaller();
internal static DeleteComponentResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteComponentResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 44.091603 | 174 | 0.658068 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/Imagebuilder/Generated/Model/Internal/MarshallTransformations/DeleteComponentResponseUnmarshaller.cs | 5,776 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Akamai.Inputs
{
public sealed class GtmAsmapDefaultDatacenterGetArgs : Pulumi.ResourceArgs
{
[Input("datacenterId", required: true)]
public Input<int> DatacenterId { get; set; } = null!;
[Input("nickname")]
public Input<string>? Nickname { get; set; }
public GtmAsmapDefaultDatacenterGetArgs()
{
}
}
}
| 27.115385 | 88 | 0.678014 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-akamai | sdk/dotnet/Inputs/GtmAsmapDefaultDatacenterGetArgs.cs | 705 | C# |
//
// MenuItems.cs
//
// Author:
// JasonXuDeveloper(傑) <jasonxudeveloper@gmail.com>
//
// Copyright (c) 2020 JEngine
//
// 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.
#if UNITY_EDITOR
using System.Diagnostics;
using System.Reflection;
using JEngine.Core;
using UnityEditor;
using UnityEngine;
namespace JEngine.Editor
{
[Obfuscation(Exclude = true)]
internal class MenuItems
{
[MenuItem("JEngine/Open Documents",priority = 1999)]
public static void OpenDocument()
{
Application.OpenURL("https://docs.xgamedev.net/");
}
[MenuItem("JEngine/Open on Github",priority = 2000)]
public static void OpenGithub()
{
Application.OpenURL("https://github.com/JasonXuDeveloper/JEngine");
}
}
}
#endif
| 35.25 | 80 | 0.713039 | [
"MIT"
] | mudbee111/JEngine | UnityProject/Assets/Dependencies/JEngine/Editor/JEngineTools/UnityEditor/MenuItems.cs | 1,839 | C# |
#region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// 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.
#endregion
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
public static TSource Last<TSource>(
this IEnumerable<TSource> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Sequence was empty");
}
return list[list.Count - 1];
}
using (IEnumerator<TSource> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource last = iterator.Current;
while (iterator.MoveNext())
{
last = iterator.Current;
}
return last;
}
}
public static TSource Last<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
bool foundAny = false;
TSource last = default(TSource);
foreach (TSource item in source)
{
if (predicate(item))
{
foundAny = true;
last = item;
}
}
if (!foundAny)
{
throw new InvalidOperationException("No items matched the predicate");
}
return last;
}
}
}
| 31.755814 | 87 | 0.499817 | [
"Apache-2.0"
] | Anojsingh/edulinq | src/Edulinq/Last.cs | 2,733 | C# |
/*
* Copyright © 2011, Petro Protsyk, Denys Vuika
*
* 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 Scripting.SSharp
{
internal static class HashSetExtensions
{
public static void AddRange<T>(this HashSet<T> hashset, IEnumerable<T> values)
{
foreach (T value in values)
hashset.Add(value);
}
}
}
| 29.633333 | 82 | 0.71766 | [
"Apache-2.0"
] | JackWangCUMT/SSharp | SSharp.Net/Extensions/HashSetExtensions.cs | 892 | C# |
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace CalculatorDemoApp {
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
| 25.117647 | 94 | 0.632319 | [
"MIT"
] | sonnemaf/XamlCalculatorBehavior | CalculatorDemoApp/MainPage.xaml.cs | 429 | C# |
using NBitcoin;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WalletWasabi.JsonConverters;
using WalletWasabi.Models;
namespace WalletWasabi.Blockchain.Keys
{
[JsonObject(MemberSerialization.OptIn)]
public class BlockchainState
{
[JsonConstructor]
public BlockchainState(Network network, Height height)
{
Network = network;
Height = height;
}
public BlockchainState()
{
Network = Network.Main;
Height = 0;
}
[JsonProperty]
[JsonConverter(typeof(NetworkJsonConverter))]
public Network Network { get; set; }
[JsonProperty]
[JsonConverter(typeof(HeightJsonConverter))]
public Height Height { get; set; }
}
}
| 19.459459 | 56 | 0.744444 | [
"MIT"
] | 2pac1/WalletWasabi | WalletWasabi/Blockchain/Keys/BlockchainState.cs | 720 | C# |
// <copyright file="IPropagationComponent.cs" company="OpenCensus Authors">
// Copyright 2018, OpenCensus Authors
//
// 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.
// </copyright>
namespace OpenCensus.Trace.Propagation
{
/// <summary>
/// Configuration of wire protocol to use to extract and inject span context from the wire.
/// </summary>
public interface IPropagationComponent
{
/// <summary>
/// Gets the binary format propagator.
/// </summary>
IBinaryFormat BinaryFormat { get; }
/// <summary>
/// Gets the text format propagator.
/// </summary>
ITextFormat TextFormat { get; }
}
} | 34.911765 | 95 | 0.680708 | [
"Apache-2.0"
] | PriceSpider-NeuIntel/opencensus-csharp | src/OpenCensus.Abstractions/Trace/Propagation/IPropagationComponent.cs | 1,189 | C# |
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// AdditionalPropertiesString
/// </summary>
[DataContract]
public partial class AdditionalPropertiesString : Dictionary<String, string>, IEquatable<AdditionalPropertiesString>
{
/// <summary>
/// Initializes a new instance of the <see cref="AdditionalPropertiesString" /> class.
/// </summary>
/// <param name="name">name.</param>
public AdditionalPropertiesString(string name = default(string)) : base()
{
this.Name = name;
}
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AdditionalPropertiesString {\n");
sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as AdditionalPropertiesString);
}
/// <summary>
/// Returns true if AdditionalPropertiesString instances are equal
/// </summary>
/// <param name="input">Instance of AdditionalPropertiesString to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AdditionalPropertiesString input)
{
if (input == null)
return false;
return base.Equals(input) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = base.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
return hashCode;
}
}
}
}
| 32.119658 | 159 | 0.577435 | [
"Apache-2.0"
] | 0x0c/openapi-generator | samples/client/petstore/csharp/OpenAPIClientNet35/src/Org.OpenAPITools/Model/AdditionalPropertiesString.cs | 3,758 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.AI.QnA;
using Newtonsoft.Json;
namespace EnterpriseBotSample.Middleware.Telemetry
{
/// <summary>
/// TelemetryQnaRecognizer invokes the Qna Maker and logs some results into Application Insights.
/// Logs the score, and (optionally) question
/// Along with Conversation and ActivityID.
/// The Custom Event name this logs is "QnaMessage"
/// See <seealso cref="QnaMaker"/> for additional information.
/// </summary>
public class TelemetryQnAMaker : QnAMaker
{
public const string QnaMsgEvent = "QnaMessage";
private QnAMakerEndpoint _endpoint;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryQnAMaker"/> class.
/// </summary>
/// <param name="endpoint">The endpoint of the knowledge base to query.</param>
/// <param name="options">The options for the QnA Maker knowledge base.</param>
/// <param name="logUserName">The flag to include username in logs.</param>
/// <param name="logOriginalMessage">The flag to include original message in logs.</param>
/// <param name="httpClient">An alternate client with which to talk to QnAMaker.
/// If null, a default client is used for this instance.</param>
public TelemetryQnAMaker(QnAMakerEndpoint endpoint, QnAMakerOptions options = null, bool logUserName = false, bool logOriginalMessage = false, HttpClient httpClient = null)
: base(endpoint, options, httpClient)
{
LogUserName = logUserName;
LogOriginalMessage = logOriginalMessage;
_endpoint = endpoint;
}
public bool LogUserName { get; }
public bool LogOriginalMessage { get; }
public async Task<QueryResult[]> GetAnswersAsync(ITurnContext context)
{
// Call Qna Maker
var queryResults = await base.GetAnswersAsync(context);
// Find the Application Insights Telemetry Client
if (queryResults != null && context.TurnState.TryGetValue(TelemetryLoggerMiddleware.AppInsightsServiceKey, out var telemetryClient))
{
var telemetryProperties = new Dictionary<string, string>();
var telemetryMetrics = new Dictionary<string, double>();
telemetryProperties.Add(QnATelemetryConstants.KnowledgeBaseIdProperty, _endpoint.KnowledgeBaseId);
// Make it so we can correlate our reports with Activity or Conversation
telemetryProperties.Add(QnATelemetryConstants.ActivityIdProperty, context.Activity.Id);
var conversationId = context.Activity.Conversation.Id;
if (!string.IsNullOrEmpty(conversationId))
{
telemetryProperties.Add(QnATelemetryConstants.ConversationIdProperty, conversationId);
}
// For some customers, logging original text name within Application Insights might be an issue
var text = context.Activity.Text;
if (LogOriginalMessage && !string.IsNullOrWhiteSpace(text))
{
telemetryProperties.Add(QnATelemetryConstants.OriginalQuestionProperty, text);
}
// For some customers, logging user name within Application Insights might be an issue
var userName = context.Activity.From.Name;
if (LogUserName && !string.IsNullOrWhiteSpace(userName))
{
telemetryProperties.Add(QnATelemetryConstants.UsernameProperty, userName);
}
// Fill in Qna Results (found or not)
if (queryResults.Length > 0)
{
var queryResult = queryResults[0];
telemetryProperties.Add(QnATelemetryConstants.QuestionProperty, JsonConvert.SerializeObject(queryResult.Questions));
telemetryProperties.Add(QnATelemetryConstants.AnswerProperty, queryResult.Answer);
telemetryMetrics.Add(QnATelemetryConstants.ScoreProperty, queryResult.Score);
telemetryProperties.Add(QnATelemetryConstants.ArticleFoundProperty, "true");
}
else
{
telemetryProperties.Add(QnATelemetryConstants.QuestionProperty, "No Qna Question matched");
telemetryProperties.Add(QnATelemetryConstants.AnswerProperty, "No Qna Answer matched");
telemetryProperties.Add(QnATelemetryConstants.ArticleFoundProperty, "true");
}
// Track the event
((IBotTelemetryClient)telemetryClient).TrackEvent(QnaMsgEvent, telemetryProperties, telemetryMetrics);
}
return queryResults;
}
}
} | 48.219048 | 180 | 0.64369 | [
"MIT"
] | SVemulapalli/AI | templates/Enterprise-Template/src/csharp/EnterpriseBotSample/Middleware/Telemetry/TelemetryQnAMaker.cs | 5,065 | C# |
//
// Copyright (c) Microsoft and contributors. 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.
// 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure;
using Microsoft.WindowsAzure.Commands.Compute.Automation.Models;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.WindowsAzure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateVirtualMachineOSImageDeleteDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pImageName = new RuntimeDefinedParameter();
pImageName.Name = "ImageName";
pImageName.ParameterType = typeof(System.String);
pImageName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pImageName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ImageName", pImageName);
var pDeleteFromStorage = new RuntimeDefinedParameter();
pDeleteFromStorage.Name = "DeleteFromStorage";
pDeleteFromStorage.ParameterType = typeof(System.Boolean);
pDeleteFromStorage.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pDeleteFromStorage.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("DeleteFromStorage", pDeleteFromStorage);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 3,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteVirtualMachineOSImageDeleteMethod(object[] invokeMethodInputParameters)
{
string imageName = (string)ParseParameter(invokeMethodInputParameters[0]);
bool deleteFromStorage = (bool)ParseParameter(invokeMethodInputParameters[1]);
var result = VirtualMachineOSImageClient.Delete(imageName, deleteFromStorage);
WriteObject(result);
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateVirtualMachineOSImageDeleteParameters()
{
string imageName = string.Empty;
bool deleteFromStorage = new bool();
return ConvertFromObjectsToArguments(new string[] { "ImageName", "DeleteFromStorage" }, new object[] { imageName, deleteFromStorage });
}
}
}
| 41.142857 | 148 | 0.660714 | [
"MIT"
] | Andrean/azure-powershell | src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Generated/VirtualMachineOSImage/VirtualMachineOSImageDeleteMethod.cs | 3,935 | C# |
using SuperSocket.Common;
using SuperSocket.SocketBase.Config;
using System;
using System.Collections.Generic;
namespace SuperSocket.SocketBase.Command
{
/// <summary>
/// CommandLoader base class
/// </summary>
public abstract class CommandLoaderBase<TCommand> : ICommandLoader<TCommand>
where TCommand : ICommand
{
/// <summary>
/// Initializes the command loader by the root config and appserver instance.
/// </summary>
/// <param name="rootConfig">The root config.</param>
/// <param name="appServer">The app server.</param>
/// <returns></returns>
public abstract bool Initialize(IRootConfig rootConfig, IAppServer appServer);
/// <summary>
/// Tries to load commands.
/// </summary>
/// <param name="commands">The commands.</param>
/// <returns></returns>
public abstract bool TryLoadCommands(out IEnumerable<TCommand> commands);
/// <summary>
/// Called when [updated].
/// </summary>
/// <param name="commands">The commands.</param>
protected void OnUpdated(IEnumerable<CommandUpdateInfo<TCommand>> commands)
{
Updated?.Invoke(this, new CommandUpdateEventArgs<TCommand>(commands));
}
/// <summary>
/// Occurs when [updated].
/// </summary>
public event EventHandler<CommandUpdateEventArgs<TCommand>> Updated;
/// <summary>
/// Called when [error].
/// </summary>
/// <param name="message">The message.</param>
protected void OnError(string message)
{
OnError(new Exception(message));
}
/// <summary>
/// Called when [error].
/// </summary>
/// <param name="e">The e.</param>
protected void OnError(Exception e)
{
Error?.Invoke(this, new ErrorEventArgs(e));
}
/// <summary>
/// Occurs when [error].
/// </summary>
public event EventHandler<ErrorEventArgs> Error;
}
}
| 31.149254 | 86 | 0.578342 | [
"Apache-2.0"
] | fwyhq/SupperSocket | SuperSocket.SocketBase/Command/CommandLoaderBase.cs | 2,089 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace d
{
class Program
{
static void Main(string[] args)
{
string s = Console.ReadLine();
if (s[0] == s[1])
{
Console.WriteLine("1 2");
return;
}
for (int i = 0; i < s.Length - 2; i++)
{
string t = s.Substring(i, 3);
if (t[0] == t[1] || t[1] == t[2] || t[2] == t[0])
{
Console.WriteLine("{0} {1}", i + 1, i + 3);
return;
}
}
Console.WriteLine("-1 -1");
}
}
}
| 23.4375 | 65 | 0.386667 | [
"MIT"
] | yu3mars/procon | atcoder/abc/abc043/d/Program.cs | 752 | C# |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace src.Shared
{
public static class BitmapExtensions
{
//
// https://stackoverflow.com/questions/32066893/changing-datetaken-of-a-photo
//
public static void ModifyDateTaken( this Bitmap image, DateTime newDate)
{
// PropertyItem class has no public constructors. One way to work around this restriction is
// to obtain a PropertyItem by retrieving the PropertyItems property value or calling the
// GetPropertyItem method of an Image that already has property items
var propItems = image.PropertyItems;
var encoding = Encoding.UTF8;
var prop9003 = propItems.Where(a => a.Id.ToString("x") == "9003").FirstOrDefault();
if (prop9003 != null)
{
prop9003.Value = encoding.GetBytes(newDate.ToString("yyyy:MM:dd HH:mm:ss") + '\0');
image.SetPropertyItem(prop9003);
}
}
}
}
| 35.25 | 105 | 0.62766 | [
"MIT"
] | vladlee098/img_tool | src/Shared/BitmapExtensions.cs | 1,128 | 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 mediaconnect-2018-11-14.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.MediaConnect.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaConnect.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for VpcInterfaceAttachment Object
/// </summary>
public class VpcInterfaceAttachmentUnmarshaller : IUnmarshaller<VpcInterfaceAttachment, XmlUnmarshallerContext>, IUnmarshaller<VpcInterfaceAttachment, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
VpcInterfaceAttachment IUnmarshaller<VpcInterfaceAttachment, 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 VpcInterfaceAttachment Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
VpcInterfaceAttachment unmarshalledObject = new VpcInterfaceAttachment();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("vpcInterfaceName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.VpcInterfaceName = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static VpcInterfaceAttachmentUnmarshaller _instance = new VpcInterfaceAttachmentUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static VpcInterfaceAttachmentUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.73913 | 179 | 0.65363 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/MediaConnect/Generated/Model/Internal/MarshallTransformations/VpcInterfaceAttachmentUnmarshaller.cs | 3,196 | C# |
#define DEBUG_CC2D_RAYS
using Assets.Scripts.Helpers;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Assets.Scripts.Movement
{
public class MovementHandler
{
private readonly IMotor _motor;
private RaycastHit2D _downHit;
private ColliderPoint _previousColliderPoint;
private float _angle;
private RaycastHit2D _lipHit;
private bool _leftHit = false;
private bool _rightHit = false;
private Transform _currentPlatform;
private bool _reset = false;
public MovementHandler(IMotor motor)
{
_motor = motor;
}
public bool MoveLinearly(float speed, bool applyRotation = false, bool forceOffEdge = false)
{
if (_motor.MovementState.PivotCollider == null)
return false;
IgnorePlatforms(true);
_motor.MovementState.UpdatePivotToTarget(forceOffEdge);
float distance;
Vector2 characterPoint = _motor.Collider.GetPoint(_motor.MovementState.CharacterPoint);
Vector3 movement = MoveTowardsPivot(out distance, speed, characterPoint);
_motor.Transform.Translate(movement, Space.World);
if (applyRotation)
{
float angle = _motor.MovementState.GetCornerAngle();
float rotation = Mathf.Lerp(angle, 0, distance);
if (_angle != angle)
_motor.Transform.rotation = Quaternion.Euler(0,0, rotation);
_angle = angle;
}
else
_motor.Transform.rotation = Quaternion.Euler(0, 0, 0);
return true;
}
public bool IsCollidingWithNonPivot(bool lowerHalf)
{
float collisionFudge = 0.2f;
Bounds bounds = _motor.Collider.bounds;
float startY = lowerHalf ? bounds.center.y : bounds.max.y;
float distance = lowerHalf ? bounds.extents.y : bounds.size.y;
RaycastHit2D[] hits = Physics2D.BoxCastAll(new Vector2(bounds.center.x, startY - collisionFudge), new Vector2(bounds.size.x - (collisionFudge * 2), 0.001f), 0, Vector2.down, distance - (collisionFudge * 2), Layers.Platforms);
return ClimbCollision.IsCollisionInvalid(hits, _motor.MovementState.Pivot.transform);
}
public void SetMovementCollisions(Vector3 deltaMovement, bool jumping)
{
BoxCastSetup(deltaMovement);
Bounds bounds = _motor.Collider.bounds;
List<RaycastHit2D> downHits = Physics2D.BoxCastAll(new Vector2(bounds.center.x, bounds.min.y + 0.5f), new Vector2(bounds.size.x, 0.001f), 0, Vector2.down, 1f, Layers.Platforms).ToList();
if (jumping)
RemoveCurrentPlatform(downHits);
else
_currentPlatform = null;
_downHit = GetDownwardsHit(downHits);
if (_downHit)
_motor.MovementState.OnGroundHit();
bool offGround = jumping || _downHit == false;
_leftHit = _motor.MovementState.CurrentAcceleration.x > 0 ? false : DirectionCast(bounds, DirectionTravelling.Left, offGround);
_rightHit = _motor.MovementState.CurrentAcceleration.x < 0 ? false : DirectionCast(bounds, DirectionTravelling.Right, offGround);
}
private void RemoveCurrentPlatform(List<RaycastHit2D> hits)
{
if (_currentPlatform == null)
_currentPlatform = _motor.MovementState.Pivot.transform.parent;
RaycastHit2D hitToRemove = hits.SingleOrDefault(h => h.collider.transform == _currentPlatform);
hits.Remove(hitToRemove);
}
public void BoxCastMove()
{
if (Time.timeSinceLevelLoad < 1)
return;
Bounds bounds = _motor.Collider.bounds;
if (_downHit)
{
ColliderPoint hitLocation;
float n = _downHit.normal.x;
if (Mathf.Abs(n) < 0.02f)
hitLocation = ColliderPoint.BottomFace;
else if (n > 0)
hitLocation = ColliderPoint.BottomLeft;
else
hitLocation = ColliderPoint.BottomRight;
_motor.MovementState.CharacterPoint = hitLocation;
Vector3 offset = _motor.Collider.GetPoint(hitLocation);
float x = hitLocation == ColliderPoint.BottomFace ? bounds.center.x : _downHit.point.x;
var pivotPosition = new Vector3(x, _downHit.point.y);
float rotation = _motor.Transform.rotation.eulerAngles.z;
if (rotation != 0)
{
if (rotation < 180)
_motor.Transform.RotateAround(pivotPosition, Vector3.forward, -rotation / 2);
else
_motor.Transform.RotateAround(pivotPosition, Vector3.forward, (360 - rotation) / 2);
}
_motor.MovementState.TrappedBetweenSlopes = _motor.MovementState.IsOnSlope
&& ((_leftHit && _downHit.normal.x < 0)
|| (_rightHit && _downHit.normal.x > 0));
bool directionHit = _leftHit || _rightHit;
if ((_reset && directionHit == false) || _motor.MovementState.Pivot.transform.parent == null || hitLocation != _previousColliderPoint || _downHit.collider != _motor.MovementState.PivotCollider || Vector2.Distance(_motor.MovementState.Pivot.transform.localPosition, _motor.MovementState.Pivot.transform.parent.InverseTransformPoint(pivotPosition)) > 0.05f)// _downHit.collider != _motor.MovementState.PivotCollider || leftHit || rightHit || hitLocation != _previousColliderPoint || Vector2.Distance(_motor.MovementState.Pivot.transform.position, bounds.center) > 10f)
{
_motor.MovementState.SetPivotPoint(_downHit.collider, pivotPosition, _downHit.normal);
}
_previousColliderPoint = hitLocation;
_reset = directionHit;
if (_motor.MovementState.TrappedBetweenSlopes == false && directionHit == false)
{
if (_lipHit)
{
_motor.MovementState.SetPivotPoint(_lipHit.collider, _lipHit.point, _lipHit.normal);
_motor.Transform.position = _motor.MovementState.Pivot.transform.position + _motor.Transform.position - offset;
}
else
{
_motor.MovementState.Normal = _downHit.normal;
_motor.MovementState.Pivot.transform.Translate(MoveAlongSurface(), Space.World);
_motor.Rigidbody.MovePosition(_motor.MovementState.Pivot.transform.position + _motor.Transform.position - offset);
}
}
}
else
{
float rotation = _motor.Transform.rotation.eulerAngles.z;
if (rotation != 0)
{
if (rotation < 180)
_motor.Transform.Rotate(Vector3.forward, -rotation / 2);
else
_motor.Transform.Rotate(Vector3.forward, (360 - rotation) / 2);
}
_motor.MovementState.PivotCollider = null;
_motor.Transform.Translate(_motor.MovementState.CurrentAcceleration, Space.World);
}
}
private void BoxCastSetup(Vector3 deltaMovement)
{
_angle = 0;
_lipHit = new RaycastHit2D();
_leftHit = false;
_rightHit = false;
if (Mathf.Abs(deltaMovement.x) < 0.05f)
deltaMovement.x = 0;
IgnorePlatforms(false);
_motor.MovementState.Reset(deltaMovement);
}
public void IgnorePlatforms(bool ignore)
{
_motor.Rigidbody.isKinematic = ignore;
int layer = _motor.Transform.gameObject.layer;
Physics2D.IgnoreLayerCollision(layer, LayerMask.NameToLayer(Layers.OutdoorMetal), ignore);
Physics2D.IgnoreLayerCollision(layer, LayerMask.NameToLayer(Layers.OutdoorWood), ignore);
Physics2D.IgnoreLayerCollision(layer, LayerMask.NameToLayer(Layers.IndoorMetal), ignore);
Physics2D.IgnoreLayerCollision(layer, LayerMask.NameToLayer(Layers.IndoorWood), ignore);
}
private bool DirectionCast(Bounds bounds, DirectionTravelling direction, bool offGround)
{
Vector2 dir = direction == DirectionTravelling.Left ? Vector2.left : Vector2.right;
RaycastHit2D hit = GetDirectionHit(bounds, dir);
if (hit)
{
if (hit.collider.gameObject.layer == LayerMask.NameToLayer(Layers.Ice))
_motor.MovementState.ApproachingSnow = true;
float lipHeight = bounds.min.y + ConstantVariables.MaxLipHeight;
if (offGround || hit.point.y > lipHeight)
{
if (direction == DirectionTravelling.Left)
_motor.MovementState.OnLeftCollision();
else
_motor.MovementState.OnRightCollision();
return hit;
}
if (direction == DirectionTravelling.Left)
{
//special player crouch check/set
RaycastHit2D lipHit = Physics2D.Raycast(new Vector2(bounds.min.x - 0.3f, bounds.max.y), Vector2.down, bounds.size.y, Layers.Platforms);
if (ActualSidewaysCollision(lipHit, lipHeight))
_motor.MovementState.OnLeftCollision();
else
{
hit = new RaycastHit2D();
_lipHit = lipHit;
}
}
else
{
RaycastHit2D lipHit = Physics2D.Raycast(new Vector2(bounds.max.x + 0.3f, bounds.max.y), Vector2.down, bounds.size.y, Layers.Platforms);
if (ActualSidewaysCollision(lipHit, lipHeight))
_motor.MovementState.OnRightCollision();
else
{
hit = new RaycastHit2D();
_lipHit = lipHit;
}
}
}
if (offGround)
return false;
else
return hit || AtEdge(bounds, direction);
}
private bool AtEdge(Bounds bounds, DirectionTravelling direction)
{
if (_motor.MovementState.IsOnSlope || _downHit.transform.gameObject.layer == LayerMask.NameToLayer(Layers.Ice))
return false;
float xOrigin = direction == DirectionTravelling.Right
? bounds.max.x + 0.1f
: bounds.min.x - 0.1f;
var edgeRay = new Vector2(xOrigin, bounds.min.y);
Debug.DrawRay(edgeRay, _motor.MovementState.GetSurfaceDownDirection(), Color.blue);
RaycastHit2D hit = Physics2D.Raycast(edgeRay, _motor.MovementState.GetSurfaceDownDirection(), 1.5f, Layers.Platforms);
bool atEdge = hit == false ? true : Vector2.Angle(Vector2.up, hit.normal) > _motor.SlopeLimit;
if (atEdge)
{
edgeRay += new Vector2(direction == DirectionTravelling.Right ? 1 : -1, ConstantVariables.MaxLipHeight);
RaycastHit2D hit2 = Physics2D.Raycast(edgeRay, Vector2.down, 1.5f + ConstantVariables.MaxLipHeight, Layers.Platforms);
atEdge = hit2 == false ? true : Vector2.Angle(Vector2.up, hit2.normal) > _motor.SlopeLimit;
}
if (atEdge)
{
if (direction == DirectionTravelling.Right)
_motor.MovementState.OnRightEdge();
else
_motor.MovementState.OnLeftEdge();
}
return atEdge;
}
private bool ActualSidewaysCollision(RaycastHit2D lipCast, float lipHeight)
{
return lipCast && (lipCast.collider == _downHit.collider || lipCast.point.y > lipHeight || Vector2.Angle(lipCast.normal, Vector2.up) > _motor.SlopeLimit);
}
private RaycastHit2D GetDirectionHit(Bounds bounds, Vector2 direction)
{
RaycastHit2D[] cast = Physics2D.BoxCastAll(bounds.center, new Vector2(0.01f, bounds.size.y), 0, direction, bounds.extents.x + 0.1f, Layers.Platforms);
foreach (RaycastHit2D hit in cast.Where(hit => hit.collider != _downHit.collider && hit.transform != _currentPlatform && Vector2.Angle(hit.normal, Vector2.up) > _motor.SlopeLimit))
{
return hit;
}
return new RaycastHit2D();
}
private RaycastHit2D GetDownwardsHit(List<RaycastHit2D> hits)
{
var validHit = new RaycastHit2D();
const float maxAngle = 90f;
float hitAngle = maxAngle;
if (_motor.MovementState.CurrentAcceleration.x < 0)
hits.OrderBy(h => h.point.x);
else
hits.OrderByDescending(h => h.point.x);
foreach (RaycastHit2D hit in hits)
{
hitAngle = Vector2.Angle(hit.normal, Vector2.up);
if (hit.collider.gameObject.layer == LayerMask.NameToLayer(Layers.Ice) && hitAngle <= 90)
{
_motor.MovementState.ApproachingSnow = true;
_motor.MovementState.IsGrounded = true;
return hit;
}
if (_downHit && _downHit.collider != hit.collider && hitAngle >= _motor.SlopeLimit)
{
hitAngle = maxAngle;
continue;
}
if (hitAngle < maxAngle)
{
validHit = hit;
break;
}
}
if (hitAngle < _motor.SlopeLimit)
_motor.MovementState.IsGrounded = true;
else if (hitAngle < maxAngle)
_motor.MovementState.IsOnSlope = true;
return validHit;
}
private Vector3 MoveAlongSurface()
{
bool moveRight;
float speed;
moveRight = _motor.MovementState.CurrentAcceleration.x > 0;
speed = Mathf.Abs(_motor.MovementState.CurrentAcceleration.x);
Vector3 direction = _motor.MovementState.GetSurfaceDirection(moveRight ? DirectionTravelling.Right : DirectionTravelling.Left);
bool isGoingUpSteepSlope = direction.y > 0 && Vector2.Angle(direction, moveRight ? Vector2.right : Vector2.left) > _motor.SlopeLimit + 10;
return isGoingUpSteepSlope
? Vector3.zero
: direction.normalized * speed;
}
private Vector3 MoveTowardsPivot(out float distance, float speed, Vector3 offset)
{
Vector3 pivotPosition = _motor.MovementState.Pivot.transform.position + _motor.Transform.position - offset;
distance = Vector2.Distance(_motor.Transform.position, pivotPosition);
Vector3 newPosition = Vector3.MoveTowards(_motor.Transform.position, pivotPosition, speed);
return newPosition - _motor.Transform.position;
}
[System.Diagnostics.Conditional("DEBUG_CC2D_RAYS")]
void DrawRay(Vector3 start, Vector3 dir, Color color)
{
Debug.DrawRay(start, dir, color);
}
}
}
| 35.743316 | 572 | 0.677962 | [
"MIT"
] | CannibalK9/fireperson | Assets/Scripts/Movement/MovementHandler.cs | 13,370 | C# |
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
namespace AzurePubSubServerlessCSharp
{
public class SubscribeFunctionInput
{
[JsonProperty("subscriptionTopic")]
public string SubscriptionTopic { get; set; }
[JsonProperty("functionType")]
public string FunctionType { get; set; }
[JsonProperty("subscriberId")]
public string SubscriberId { get; set; }
[JsonProperty("matchingInputs")]
public string MatchingInputs { get; set; }
[JsonProperty("matchingFunction")]
public string MatchingFunction { get; set; }
}
internal class FunctionEntity : TableEntity
{
public FunctionEntity(string subscriptionTopic, string subscriberId, string functionType, string matchinFunction, string matchingInputs)
{
PartitionKey = subscriptionTopic;
RowKey = subscriberId;
FunctionType = functionType;
MatchingFunction = matchinFunction;
MatchingInputs = matchingInputs;
}
public FunctionEntity() { }
public string FunctionType { get; set; }
public string MatchingFunction { get; set; }
public string MatchingInputs { get; set; }
}
public static class SubscribeFunction
{
[FunctionName("SubscribeFunction")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]HttpRequest req, TraceWriter log)
{
var input = Common.GetPostObject<SubscribeFunctionInput>(req);
var table = Common.GetAzureTable(Common.FunctionsTableName);
var insertOperation = TableOperation.Insert(new FunctionEntity(input.SubscriptionTopic, input.SubscriberId, input.FunctionType, input.MatchingFunction, input.MatchingInputs));
try
{
table.ExecuteAsync(insertOperation);
}
catch (Exception e)
{
Console.WriteLine(e);
}
return new OkObjectResult(Common.GetSubscriberResponse(input.SubscriberId));
}
}
}
| 33.328571 | 187 | 0.660952 | [
"Apache-2.0"
] | i13tum/serverless-pubsub | AzurePubSubServerless/SubscribeFunction.cs | 2,333 | C# |
using System;
namespace Confuser.Core.Project {
/// <summary>
/// The exception that is thrown when attempted to parse an invalid pattern.
/// </summary>
public class InvalidPatternException : Exception {
/// <summary>
/// Initializes a new instance of the <see cref="ConfuserException" /> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public InvalidPatternException(string message)
: base(message) {
}
/// <summary>
/// Initializes a new instance of the <see cref="ConfuserException" /> class.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">
/// The exception that is the cause of the current exception, or a null reference (Nothing in
/// Visual Basic) if no inner exception is specified.
/// </param>
public InvalidPatternException(string message, Exception innerException)
: base(message, innerException) {
}
}
}
| 35.448276 | 99 | 0.685798 | [
"MIT"
] | Deltafox79/ConfuserEx | Confuser.Core/Project/InvalidPatternException.cs | 1,030 | C# |
namespace BaristaLabs.Skrapr.ChromeDevTools.Accessibility
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
/// <summary>
/// Enum of possible property sources.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum AXValueSourceType
{
[EnumMember(Value = "attribute")]
Attribute,
[EnumMember(Value = "implicit")]
Implicit,
[EnumMember(Value = "style")]
Style,
[EnumMember(Value = "contents")]
Contents,
[EnumMember(Value = "placeholder")]
Placeholder,
[EnumMember(Value = "relatedElement")]
RelatedElement,
}
} | 27.307692 | 57 | 0.619718 | [
"MIT"
] | BaristaLabs/BaristaLabs.Skrapr | src/BaristaLabs.Skrapr.ChromeDevTools/Accessibility/AXValueSourceType.cs | 710 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Collections.Immutable;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using static Root;
using CA = Microsoft.CodeAnalysis;
partial struct CodeSymbolModels
{
public readonly struct PointerTypeSymbol : ICodeSymbol<PointerTypeSymbol,IPointerTypeSymbol>
{
public IPointerTypeSymbol Source {get;}
[MethodImpl(Inline)]
public PointerTypeSymbol(IPointerTypeSymbol src)
{
Source = src;
}
public bool IsEmpty
{
[MethodImpl(Inline)]
get => Source == null;
}
public bool IsNonEmpty
{
[MethodImpl(Inline)]
get => Source != null;
}
public ITypeSymbol PointedAtType => Source.PointedAtType;
public ImmutableArray<CustomModifier> CustomModifiers => Source.CustomModifiers;
public CA.TypeKind TypeKind => Source.TypeKind;
public INamedTypeSymbol BaseType => Source.BaseType;
public ImmutableArray<INamedTypeSymbol> Interfaces => Source.Interfaces;
public ImmutableArray<INamedTypeSymbol> AllInterfaces => Source.AllInterfaces;
public bool IsReferenceType => Source.IsReferenceType;
public bool IsValueType => Source.IsValueType;
public bool IsAnonymousType => Source.IsAnonymousType;
public bool IsTupleType => Source.IsTupleType;
public bool IsNativeIntegerType => Source.IsNativeIntegerType;
public ITypeSymbol OriginalDefinition => Source.OriginalDefinition;
public SpecialType SpecialType => Source.SpecialType;
public bool IsRefLikeType => Source.IsRefLikeType;
public bool IsUnmanagedType => Source.IsUnmanagedType;
public bool IsReadOnly => Source.IsReadOnly;
public NullableAnnotation NullableAnnotation => Source.NullableAnnotation;
public bool IsNamespace => Source.IsNamespace;
public bool IsType => Source.IsType;
public SymbolKind Kind => Source.Kind;
public string Language => Source.Language;
public string Name => Source.Name;
public string MetadataName => Source.MetadataName;
public ISymbol ContainingSymbol => Source.ContainingSymbol;
public IAssemblySymbol ContainingAssembly => Source.ContainingAssembly;
public IModuleSymbol ContainingModule => Source.ContainingModule;
public INamedTypeSymbol ContainingType => Source.ContainingType;
public INamespaceSymbol ContainingNamespace => Source.ContainingNamespace;
public bool IsDefinition => Source.IsDefinition;
public bool IsStatic => Source.IsStatic;
public bool IsVirtual => Source.IsVirtual;
public bool IsOverride => Source.IsOverride;
public bool IsAbstract => Source.IsAbstract;
public bool IsSealed => Source.IsSealed;
public bool IsExtern => Source.IsExtern;
public bool IsImplicitlyDeclared => Source.IsImplicitlyDeclared;
public bool CanBeReferencedByName => Source.CanBeReferencedByName;
public ImmutableArray<Location> Locations => Source.Locations;
public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => Source.DeclaringSyntaxReferences;
public Accessibility DeclaredAccessibility => Source.DeclaredAccessibility;
public bool HasUnsupportedMetadata => Source.HasUnsupportedMetadata;
[MethodImpl(Inline)]
public static implicit operator PointerTypeSymbol(CodeSymbol<IPointerTypeSymbol> src)
=> new PointerTypeSymbol(src.Source);
public ISymbol FindImplementationForInterfaceMember(ISymbol interfaceMember)
{
return Source.FindImplementationForInterfaceMember(interfaceMember);
}
public string ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return Source.ToDisplayString(topLevelNullability, format);
}
public ImmutableArray<SymbolDisplayPart> ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return Source.ToDisplayParts(topLevelNullability, format);
}
public string ToMinimalDisplayString(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null)
{
return Source.ToMinimalDisplayString(semanticModel, topLevelNullability, position, format);
}
public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null)
{
return Source.ToMinimalDisplayParts(semanticModel, topLevelNullability, position, format);
}
public ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation)
{
return Source.WithNullableAnnotation(nullableAnnotation);
}
public ImmutableArray<ISymbol> GetMembers()
{
return Source.GetMembers();
}
public ImmutableArray<ISymbol> GetMembers(string name)
{
return Source.GetMembers(name);
}
public ImmutableArray<INamedTypeSymbol> GetTypeMembers()
{
return Source.GetTypeMembers();
}
public ImmutableArray<INamedTypeSymbol> GetTypeMembers(string name)
{
return Source.GetTypeMembers(name);
}
public ImmutableArray<INamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return Source.GetTypeMembers(name, arity);
}
public ReadOnlySpan<AttributeData> GetAttributes()
=> Source.GetAttributes().AsSpan();
public void Accept(SymbolVisitor visitor)
=> Source.Accept(visitor);
public TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
=> Source.Accept(visitor);
public string GetDocumentationCommentId()
=> Source.GetDocumentationCommentId();
public string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default)
=> Source.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken);
public string ToDisplayString(SymbolDisplayFormat format = null)
=> Source.ToDisplayString(format);
public ReadOnlySpan<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null)
=> Source.ToDisplayParts(format).AsSpan();
public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null)
=> Source.ToMinimalDisplayString(semanticModel, position, format);
public ReadOnlySpan<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null)
=> Source.ToMinimalDisplayParts(semanticModel, position, format).AsSpan();
public bool Equals(PointerTypeSymbol src)
=> Source.Equals(src.Source);
public override string ToString()
=> ToDisplayString();
}
}
} | 37.229358 | 191 | 0.636028 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/symbolic/src/models/specific/PointerTypeSymbol.cs | 8,116 | C# |
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace WinDynamicDesktop
{
class MainMenu
{
private static readonly Func<string, string> _ = Localization.GetTranslation;
public static ToolStripMenuItem themeItem;
public static ToolStripMenuItem darkModeItem;
public static ToolStripMenuItem startOnBootItem;
public static ToolStripMenuItem enableScriptsItem;
public static ToolStripMenuItem shuffleItem;
public static ToolStripMenuItem fullScreenItem;
public static ContextMenuStrip GetMenu()
{
List<ToolStripItem> menuItems = GetMenuItems();
UwpDesktop.GetHelper().CheckStartOnBoot();
ContextMenuStrip menuStrip = new ContextMenuStrip();
menuStrip.Items.AddRange(menuItems.ToArray());
IntPtr handle = menuStrip.Handle; // Handle needed for BeginInvoke to work
return menuStrip;
}
private static List<ToolStripItem> GetMenuItems()
{
List<ToolStripItem> items = new List<ToolStripItem>();
themeItem = new ToolStripMenuItem(_("&Select Theme..."), null, OnThemeItemClick);
items.AddRange(new List<ToolStripItem>()
{
new ToolStripMenuItem("WinDynamicDesktop"),
new ToolStripSeparator(),
new ToolStripMenuItem(_("&Configure Schedule..."), null, OnScheduleItemClick),
themeItem
});
items[0].Enabled = false;
darkModeItem = new ToolStripMenuItem(_("&Night Mode"), null, OnDarkModeClick);
darkModeItem.Checked = JsonConfig.settings.darkMode;
startOnBootItem = new ToolStripMenuItem(_("Start on &Boot"), null, OnStartOnBootClick);
ToolStripMenuItem optionsItem = new ToolStripMenuItem(_("More &Options"));
optionsItem.DropDownItems.AddRange(GetOptionsMenuItems().ToArray());
items.AddRange(new List<ToolStripItem>()
{
new ToolStripMenuItem(_("&Refresh Wallpaper"), null, OnRefreshItemClick),
new ToolStripSeparator(),
darkModeItem,
startOnBootItem,
optionsItem,
new ToolStripSeparator(),
new ToolStripMenuItem(_("&Check for Updates"), null, OnUpdateItemClick),
new ToolStripMenuItem(_("&About"), null, OnAboutItemClick),
new ToolStripSeparator(),
new ToolStripMenuItem(_("E&xit"), null, OnExitItemClick)
});
return items;
}
private static List<ToolStripItem> GetOptionsMenuItems()
{
List<ToolStripItem> items = new List<ToolStripItem>();
items.Add(new ToolStripMenuItem(_("Select &Language..."), null, OnLanguageItemClick));
items.Add(new ToolStripSeparator());
shuffleItem = new ToolStripMenuItem(_("Shuffle theme daily"), null, OnShuffleItemClick);
shuffleItem.Checked = JsonConfig.settings.enableShuffle;
items.Add(shuffleItem);
fullScreenItem = new ToolStripMenuItem(_("Pause while fullscreen apps running"), null, OnFullScreenItemClick);
fullScreenItem.Checked = JsonConfig.settings.fullScreenPause;
items.Add(fullScreenItem);
items.AddRange(UpdateChecker.GetMenuItems());
items.Add(new ToolStripSeparator());
items.Add(new ToolStripMenuItem(_("Edit configuration file"), null, OnEditConfigFileClick));
items.Add(new ToolStripMenuItem(_("Reload configuration file"), null, OnReloadConfigFileClick));
items.Add(new ToolStripSeparator());
enableScriptsItem = new ToolStripMenuItem(_("Enable PowerShell scripts"), null, OnEnableScriptsClick);
enableScriptsItem.Checked = JsonConfig.settings.enableScripts;
items.Add(enableScriptsItem);
items.Add(new ToolStripMenuItem(_("Manage installed scripts"), null, OnManageScriptsClick));
return items;
}
private static void OnScheduleItemClick(object sender, EventArgs e)
{
LocationManager.ChangeLocation();
}
private static void OnThemeItemClick(object sender, EventArgs e)
{
ThemeManager.SelectTheme();
}
private static void OnRefreshItemClick(object sender, EventArgs e)
{
AppContext.wpEngine.RunScheduler(true);
}
private static void OnDarkModeClick(object sender, EventArgs e)
{
AppContext.wpEngine.ToggleDarkMode();
}
private static void OnStartOnBootClick(object sender, EventArgs e)
{
UwpDesktop.GetHelper().ToggleStartOnBoot();
}
private static void OnUpdateItemClick(object sender, EventArgs e)
{
UpdateChecker.CheckManual();
}
private static void OnAboutItemClick(object sender, EventArgs e)
{
(new AboutDialog()).Show();
}
private static void OnExitItemClick(object sender, EventArgs e)
{
Application.Exit();
}
private static void OnLanguageItemClick(object sender, EventArgs e)
{
Localization.SelectLanguage();
}
private static void OnShuffleItemClick(object sender, EventArgs e)
{
WallpaperShuffler.ToggleShuffle();
}
private static void OnFullScreenItemClick(object sender, EventArgs e)
{
AppContext.wpEngine.fullScreenChecker.ToggleFullScreenPause();
}
private static void OnEditConfigFileClick(object sender, EventArgs e)
{
Process.Start("explorer", "settings.json");
}
private static void OnReloadConfigFileClick(object sender, EventArgs e)
{
JsonConfig.ReloadConfig();
}
private static void OnEnableScriptsClick(object sender, EventArgs e)
{
ScriptManager.ToggleEnableScripts();
}
private static void OnManageScriptsClick(object sender, EventArgs e)
{
Process.Start("explorer", "scripts");
}
}
}
| 37.469274 | 123 | 0.612345 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | 3prm3/WinDynamicDesktop | src/MainMenu.cs | 6,709 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using LINQPad.Extensibility.DataContext;
namespace TestWindow
{
class ConnectionInfo : IConnectionInfo
{
XElement data = new XElement("blah");
public XElement DriverData
{
get { return data; }
set { data = value; }
}
public bool Persist { get; set; }
public string Encrypt(string data)
{
return data;
//throw new NotImplementedException();
}
public string Decrypt(string data)
{
return data;
//throw new NotImplementedException();
}
public IDatabaseInfo DatabaseInfo
{
get { throw new NotImplementedException(); }
}
public ICustomTypeInfo CustomTypeInfo
{
get { throw new NotImplementedException(); }
}
public IDynamicSchemaOptions DynamicSchemaOptions
{
get { throw new NotImplementedException(); }
}
public string DisplayName
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string AppConfigPath
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public IDictionary<string, object> SessionData
{
get { throw new NotImplementedException(); }
}
}
}
| 18.925373 | 51 | 0.701104 | [
"MIT"
] | zyonet/linqpad-soap-driver | Window/ConnectionInfo.cs | 1,270 | 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 lakeformation-2017-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.LakeFormation.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.LakeFormation.Model.Internal.MarshallTransformations
{
/// <summary>
/// PutDataLakeSettings Request Marshaller
/// </summary>
public class PutDataLakeSettingsRequestMarshaller : IMarshaller<IRequest, PutDataLakeSettingsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((PutDataLakeSettingsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(PutDataLakeSettingsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.LakeFormation");
string target = "AWSLakeFormation.PutDataLakeSettings";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-03-31";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetCatalogId())
{
context.Writer.WritePropertyName("CatalogId");
context.Writer.Write(publicRequest.CatalogId);
}
if(publicRequest.IsSetDataLakeSettings())
{
context.Writer.WritePropertyName("DataLakeSettings");
context.Writer.WriteObjectStart();
var marshaller = DataLakeSettingsMarshaller.Instance;
marshaller.Marshall(publicRequest.DataLakeSettings, context);
context.Writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static PutDataLakeSettingsRequestMarshaller _instance = new PutDataLakeSettingsRequestMarshaller();
internal static PutDataLakeSettingsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static PutDataLakeSettingsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37 | 154 | 0.609506 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/LakeFormation/Generated/Model/Internal/MarshallTransformations/PutDataLakeSettingsRequestMarshaller.cs | 4,292 | C# |
using System.Threading.Tasks;
namespace SimpleIdServer.MobileApp.Services
{
public interface IMessageService
{
Task Show(string title, string message);
Task<bool> Show(string title, string message, string accept, string cancel);
}
}
| 23.909091 | 84 | 0.711027 | [
"Apache-2.0"
] | LaTranche31/SimpleIdServer | src/Mobile/SimpleIdServer.MobileApp/Services/IMessageService.cs | 265 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
namespace AndroidSdk
{
public class JdkLocator
{
string PlatformJavaCExtension => IsWindows ? ".exe" : string.Empty;
protected bool IsWindows
=> RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
protected bool IsMac
=> RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
public IEnumerable<JdkInfo> Find()
{
var paths = new List<JdkInfo>();
if (IsWindows)
{
SearchDirectoryForJdks(paths,
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Android", "Jdk"), true);
var pfmsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Microsoft");
try
{
if (Directory.Exists(pfmsDir))
{
var msJdkDirs = Directory.EnumerateDirectories(pfmsDir, "jdk-*", SearchOption.TopDirectoryOnly);
foreach (var msJdkDir in msJdkDirs)
SearchDirectoryForJdks(paths, msJdkDir, false);
}
}
catch { }
SearchDirectoryForJdks(paths,
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Microsoft", "Jdk"), true);
}
else if (IsMac)
{
var ms11Dir = Path.Combine("/Library", "Java", "JavaVirtualMachines", "microsoft-11.jdk", "Contents", "Home");
SearchDirectoryForJdks(paths, ms11Dir, true);
var msDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Developer", "Xamarin", "jdk");
SearchDirectoryForJdks(paths, msDir, true);
// /Library/Java/JavaVirtualMachines/
try
{
var javaVmDir = Path.Combine("Library", "Java", "JavaVirtualMachines");
if (Directory.Exists(javaVmDir))
{
var javaVmJdkDirs = Directory.EnumerateDirectories(javaVmDir, "*.jdk", SearchOption.TopDirectoryOnly);
foreach (var javaVmJdkDir in javaVmJdkDirs)
SearchDirectoryForJdks(paths, javaVmDir, true);
javaVmJdkDirs = Directory.EnumerateDirectories(javaVmDir, "jdk-*", SearchOption.TopDirectoryOnly);
foreach (var javaVmJdkDir in javaVmJdkDirs)
SearchDirectoryForJdks(paths, javaVmDir, true);
}
}
catch
{
}
}
SearchDirectoryForJdks(paths, Environment.GetEnvironmentVariable("JAVA_HOME") ?? string.Empty, true);
SearchDirectoryForJdks(paths, Environment.GetEnvironmentVariable("JDK_HOME") ?? string.Empty, true);
var environmentPaths = Environment.GetEnvironmentVariable("PATH")?.Split(';') ?? Array.Empty<string>();
foreach (var envPath in environmentPaths)
{
string ep = envPath?.ToLowerInvariant() ?? string.Empty;
if (ep.Contains("java") || ep.Contains("jdk"))
SearchDirectoryForJdks(paths, envPath, true);
}
return paths
.GroupBy(i => i.JavaC.FullName)
.Select(g => g.First());
}
void SearchDirectoryForJdks(IList<JdkInfo> found, string directory, bool recursive = true)
{
if (string.IsNullOrEmpty(directory))
return;
var dir = new DirectoryInfo(directory);
if (dir.Exists)
{
var files = dir.EnumerateFileSystemInfos($"javac{PlatformJavaCExtension}", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
if (!found.Any(f => f.JavaC.FullName.Equals(file.FullName)) && TryGetJavaJdkInfo(file.FullName, out var jdkInfo))
found.Add(jdkInfo);
}
}
}
static readonly Regex rxJavaCVersion = new Regex("[0-9\\.\\-_]+", RegexOptions.Singleline);
bool TryGetJavaJdkInfo(string javacFilename, out JdkInfo javaJdkInfo)
{
var args = new ProcessArgumentBuilder();
args.Append("-version");
var p = new ProcessRunner(new FileInfo(javacFilename), args);
var result = p.WaitForExit();
var m = rxJavaCVersion.Match(result.GetOutput() ?? string.Empty);
var v = m?.Value;
if (!string.IsNullOrEmpty(v))
{
javaJdkInfo = new JdkInfo(javacFilename, v);
return true;
}
javaJdkInfo = default;
return false;
}
}
}
| 29.594203 | 152 | 0.701273 | [
"MIT"
] | Redth/Android.Tool | AndroidSdk/JdkLocator.cs | 4,086 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using AmblOn.State.API.Users.Models;
using Fathym;using Microsoft.Azure.WebJobs.Extensions.SignalRService;using AmblOn.State.API.Users.State;using Microsoft.Azure.Storage.Blob;using LCU.StateAPI.Utilities;
using Microsoft.WindowsAzure.Storage;
using System.Runtime.Serialization;
using System.Collections.Generic;
using AmblOn.State.API.Users.Graphs;
using AmblOn.State.API.Locations.State;
using AmblOn.State.API.AmblOn.State;
namespace AmblOn.State.API.Users
{
[DataContract]
public class DeleteLocationRequest
{
[DataMember]
public virtual Guid LocationID { get; set; }
}
public class DeleteLocation
{
#region Fields
protected AmblOnGraph amblGraph;
#endregion
#region Constructors
public DeleteLocation(AmblOnGraph amblGraph)
{
this.amblGraph = amblGraph;
}
#endregion
[FunctionName("DeleteLocation")]
public virtual async Task<Status> Run([HttpTrigger(AuthorizationLevel.Admin)] HttpRequest req, ILogger log,
[SignalR(HubName = AmblOnState.HUB_NAME)]IAsyncCollector<SignalRMessage> signalRMessages,
[Blob("state-api/{headers.lcu-ent-lookup}/{headers.lcu-hub-name}/{headers.x-ms-client-principal-id}/{headers.lcu-state-key}", FileAccess.ReadWrite)] CloudBlockBlob stateBlob)
{
return await stateBlob.WithStateHarness<LocationsState, DeleteLocationRequest, LocationsStateHarness>(req, signalRMessages, log,
async (harness, reqData, actReq) =>
{
log.LogInformation($"DeleteLocation");
var stateDetails = StateUtils.LoadStateDetails(req);
//await harness.DeleteLocation(amblGraph, stateDetails.Username, stateDetails.EnterpriseLookup, reqData.LocationID);
return Status.Success;
});
}
}
}
| 35.866667 | 186 | 0.705855 | [
"Apache-2.0"
] | ttrichar/state-api-users | state-api-users/DeleteLocation.cs | 2,152 | C# |
using System.Linq;
using System.Threading.Tasks;
using DevToys.Api.Tools;
using DevToys.Core.Threading;
using DevToys.ViewModels.Tools.Base64EncoderDecoder;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DevToys.Tests.Providers.Tools
{
[TestClass]
public class Base64EncoderDecoderTests : MefBaseTest
{
[DataTestMethod]
[DataRow(null, false)]
[DataRow("", false)]
[DataRow(" ", false)]
[DataRow("aGVsbG8gd29ybGQ=", true)]
[DataRow("aGVsbG8gd2f9ybGQ=", false)]
[DataRow("SGVsbG8gV29y", true)]
[DataRow("SGVsbG8gVa29y", false)]
public async Task CanBeTreatedByTool(string input, bool expectedResult)
{
await ThreadHelper.RunOnUIThreadAsync(async () =>
{
System.Collections.Generic.IEnumerable<MatchedToolProvider> result = ExportProvider.Import<IToolProviderFactory>().GetAllTools();
MatchedToolProvider base64Tool = result.First(item => item.Metadata.ProtocolName == "base64");
Assert.AreEqual(expectedResult, base64Tool.ToolProvider.CanBeTreatedByTool(input));
});
}
[DataTestMethod]
[DataRow(null, "")]
[DataRow("", "")]
[DataRow(" ", "")]
[DataRow("Hello There", "SGVsbG8gVGhlcmU=")]
public async Task EncoderAsync(string input, string expectedResult)
{
Base64EncoderDecoderToolViewModel viewModel = ExportProvider.Import<Base64EncoderDecoderToolViewModel>();
await ThreadHelper.RunOnUIThreadAsync(() =>
{
viewModel.ConversionMode = "Encode";
viewModel.InputValue = input;
});
await Task.Delay(100);
Assert.AreEqual(expectedResult, viewModel.OutputValue);
}
[DataTestMethod]
[DataRow(null, "")]
[DataRow("", "")]
[DataRow(" ", "")]
[DataRow("SGVsbG8gVGhlcmU=", "Hello There")]
public async Task DecodeAsync(string input, string expectedResult)
{
Base64EncoderDecoderToolViewModel viewModel = ExportProvider.Import<Base64EncoderDecoderToolViewModel>();
await ThreadHelper.RunOnUIThreadAsync(() =>
{
viewModel.ConversionMode = "Decode";
viewModel.InputValue = input;
});
await Task.Delay(100);
Assert.AreEqual(expectedResult, viewModel.OutputValue);
}
}
}
| 34.328767 | 145 | 0.613727 | [
"MIT"
] | kawnnor/DevToys | src/tests/DevToys.Tests/Providers/Tools/Base64EncoderDecoderTests.cs | 2,508 | C# |
using UnityEngine;
namespace VmodMonkeMapLoader.Behaviours
{
[System.Serializable]
public class ObjectTrigger : GorillaMapTriggerBase
{
public GameObject ObjectToTrigger;
public bool DisableObject = false;
public bool OnlyTriggerOnce = false;
#if PLUGIN
private bool _triggered = false;
void Start()
{
if (!DisableObject) ObjectToTrigger.SetActive(false);
else ObjectToTrigger.SetActive(true);
}
void OnEnable()
{
if (!DisableObject) ObjectToTrigger.SetActive(false);
else ObjectToTrigger.SetActive(true);
_triggered = false;
}
public override void Trigger(Collider collider)
{
if (_triggered && OnlyTriggerOnce)
return;
ObjectToTrigger.SetActive(DisableObject);
ObjectToTrigger.SetActive(!DisableObject);
_triggered = true;
base.Trigger(collider);
}
#endif
}
}
| 22.652174 | 65 | 0.588292 | [
"MIT"
] | AHauntedArmy/MonkeMapLoaderPC | MonkeMapLoader/Behaviours/ObjectTrigger.cs | 1,044 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using PS.Build.Types;
namespace PS.Build.Tasks.Services
{
class TimeMacroHandler : IMacroHandler
{
#region Properties
public string ID => "time";
int IMacroHandler.Order => 100;
#endregion
#region IMacroHandler Members
bool IMacroHandler.CanHandle(string key, string value, string formatting)
{
return string.Equals(key, "time", StringComparison.InvariantCultureIgnoreCase);
}
HandledMacro IMacroHandler.Handle(string key, string value, string formatting)
{
if (string.IsNullOrWhiteSpace(value)) return new HandledMacro(new ValidationResult($"Invalid {ID} option"));
switch (value.ToLowerInvariant())
{
case "now":
return new HandledMacro(DateTimeOffset.Now.ToString(formatting));
}
return new HandledMacro(new ValidationResult($"Not supported {ID} option"));
}
#endregion
}
} | 28.894737 | 121 | 0.605647 | [
"MIT"
] | BlackGad/PS.Build | PS.Build.Tasks/Services/MacroResolver/TimeMacroHandler.cs | 1,100 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace L8_App4
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
| 26.322581 | 106 | 0.723039 | [
"MIT"
] | emenifee/ecm-mva-w10dab | L8 App4/L8 App4/MainPage.xaml.cs | 818 | C# |
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AspNetRunBasic.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(maxLength: 80, nullable: false),
Description = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(maxLength: 80, nullable: false),
Description = table.Column<string>(maxLength: 255, nullable: false),
UnitPrice = table.Column<int>(nullable: false),
CategoryId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
table.ForeignKey(
name: "FK_Products_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Products_CategoryId",
table: "Products",
column: "CategoryId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Categories");
}
}
}
| 39.096774 | 122 | 0.518977 | [
"MIT"
] | aspnetrun/run-aspnetcore-basic | AspNetRunBasic/Migrations/20190502061258_Initial.cs | 2,426 | 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("WWCP_OICPv2.3_WebAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WWCP_OICPv2.3_WebAPI")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("6e17fb20-ff8b-453f-9304-1ed055b581c1")]
// 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.054054 | 84 | 0.74929 | [
"Apache-2.0"
] | OpenChargingCloud/WWCP_OICP | WWCP_OICPv2.3_WebAPI/Properties/AssemblyInfo.cs | 1,411 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static partial class ExtensionOrderer
{
internal static IList<Lazy<TExtension, TMetadata>> Order<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : IOrderableMetadata
{
var graph = GetGraph(extensions);
return graph.TopologicalSort();
}
private static Graph<TExtension, TMetadata> GetGraph<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : IOrderableMetadata
{
var list = extensions.ToList();
var graph = new Graph<TExtension, TMetadata>();
foreach (var extension in list)
{
graph.Nodes.Add(extension, new Node<TExtension, TMetadata>(extension));
}
foreach (var extension in list)
{
var extensionNode = graph.Nodes[extension];
foreach (var before in Before(extension))
{
foreach (var beforeExtension in graph.FindExtensions(before))
{
var otherExtensionNode = graph.Nodes[beforeExtension];
otherExtensionNode.ExtensionsBeforeMeSet.Add(extensionNode);
}
}
foreach (var after in After(extension))
{
foreach (var afterExtension in graph.FindExtensions(after))
{
var otherExtensionNode = graph.Nodes[afterExtension];
extensionNode.ExtensionsBeforeMeSet.Add(otherExtensionNode);
}
}
}
return graph;
}
private static IEnumerable<string> Before<TExtension, TMetadata>(Lazy<TExtension, TMetadata> extension)
where TMetadata : IOrderableMetadata
{
return extension.Metadata.Before ?? SpecializedCollections.EmptyEnumerable<string>();
}
private static IEnumerable<string> After<TExtension, TMetadata>(Lazy<TExtension, TMetadata> extension)
where TMetadata : IOrderableMetadata
{
return extension.Metadata.After ?? SpecializedCollections.EmptyEnumerable<string>();
}
internal static class TestAccessor
{
/// <summary>
/// Helper for checking whether cycles exist in the extension ordering.
/// Throws <see cref="ArgumentException"/> if a cycle is detected.
/// </summary>
/// <exception cref="ArgumentException">A cycle was detected in the extension ordering.</exception>
internal static void CheckForCycles<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : IOrderableMetadata
{
var graph = GetGraph(extensions);
graph.CheckForCycles();
}
}
}
}
| 39.023256 | 161 | 0.589392 | [
"Apache-2.0"
] | GKotfis/roslyn | src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.cs | 3,358 | C# |
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using BlazorProject.Backend.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace BlazorProject.Backend.Payments.Dto
{
[AutoMapFrom(typeof(Payment))]
public class PaymentListDto:EntityDto
{
public string Name { get; set; }
}
}
| 21.5 | 44 | 0.744186 | [
"MIT"
] | 274188A/BlazorProjectASPBoilerplateBackend | aspnet-core/src/BlazorProject.Backend.Application/Payments/Dto/PaymentListDto.cs | 346 | C# |
using System;
using System.Collections.Generic;
namespace Tracker.Domain.Models
{
public partial class UserLoginUpdateModel
{
#region Generated Properties
public Guid Id { get; set; }
public string EmailAddress { get; set; }
public Guid? UserId { get; set; }
public string UserAgent { get; set; }
public string Browser { get; set; }
public string OperatingSystem { get; set; }
public string DeviceFamily { get; set; }
public string DeviceBrand { get; set; }
public string DeviceModel { get; set; }
public string IpAddress { get; set; }
public bool IsSuccessful { get; set; }
public string FailureMessage { get; set; }
public DateTime Created { get; set; }
public string CreatedBy { get; set; }
public DateTime Updated { get; set; }
public string UpdatedBy { get; set; }
public Byte[] RowVersion { get; set; }
#endregion
}
}
| 21.425532 | 51 | 0.599801 | [
"Apache-2.0"
] | BartBr/EntityFrameworkCore.Generator | sample/Tracker.PostgreSQL/Tracker.PostgreSQL.Core/Domain/Models/UserLoginUpdateModel.cs | 1,007 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
namespace Infranstructure.Behaviors
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
[MetadataAttribute]
public sealed class ViewExportAttribute : ExportAttribute, IViewRegionRegistration
{
public ViewExportAttribute()
: base(typeof(object))
{ }
public ViewExportAttribute(string viewName)
: base(viewName, typeof(object))
{ }
public string ViewName { get { return base.ContractName; } }
public string RegionName { get; set; }
}
}
| 25.846154 | 86 | 0.684524 | [
"MIT"
] | SaberGuo/KMP | KMP/Infranstructure/Behaviors/ViewExportAttribute.cs | 674 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GoToWindow.Api.Tests
{
[TestClass]
public class WindowEntryFactoryTests
{
[TestMethod]
public void GetGetWindowEntry_FromTestWindow()
{
using (var app = new GivenAnApp("GoToWindow.GetGetWindowEntry_FromTestWindow"))
{
var expectedWindowHandle = app.Process.MainWindowHandle;
var window = WindowEntryFactory.Create(expectedWindowHandle);
Assert.AreEqual(expectedWindowHandle, window.HWnd);
Assert.AreEqual((uint)app.Process.Id, window.ProcessId);
Assert.AreEqual(app.ExpectedWindow.Title, window.Title);
Assert.AreNotEqual(IntPtr.Zero, window.IconHandle);
Assert.IsNull(window.ProcessName);
}
}
}
}
| 27.923077 | 82 | 0.764463 | [
"MIT"
] | christianrondeau/GoToWindow | GoToWindow.Api.Tests/WindowEntryFactoryTests.cs | 728 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.PowerPointApi
{
/// <summary>
/// DispatchInterface Axis
/// SupportByVersion PowerPoint, 14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744572.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
[TypeId("92D41A53-F07E-4CA4-AF6F-BEF486AA4E6F")]
public interface Axis : ICOMObject
{
#region Properties
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745589.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool AxisBetweenCategories { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744123.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlAxisGroup AxisGroup { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746159.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.AxisTitle AxisTitle { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746687.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
object CategoryNames { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745651.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlAxisCrosses Crosses { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746282.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double CrossesAt { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745884.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool HasMajorGridlines { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744847.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool HasMinorGridlines { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff743898.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool HasTitle { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746330.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Gridlines MajorGridlines { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745421.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlTickMark MajorTickMark { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745026.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double MajorUnit { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746487.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double LogBase { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746691.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool TickLabelSpacingIsAuto { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746838.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool MajorUnitIsAuto { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746268.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double MaximumScale { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746704.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool MaximumScaleIsAuto { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745624.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double MinimumScale { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745391.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool MinimumScaleIsAuto { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746773.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Gridlines MinorGridlines { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744253.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlTickMark MinorTickMark { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746830.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double MinorUnit { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744117.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool MinorUnitIsAuto { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745065.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool ReversePlotOrder { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746084.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlScaleType ScaleType { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744718.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlTickLabelPosition TickLabelPosition { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745407.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.TickLabels TickLabels { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745736.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Int32 TickLabelSpacing { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745472.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Int32 TickMarkSpacing { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746690.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlAxisType Type { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745843.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlTimeUnit BaseUnit { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744623.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool BaseUnitIsAuto { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744714.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlTimeUnit MajorUnitScale { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744083.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlTimeUnit MinorUnitScale { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746102.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlCategoryType CategoryType { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746324.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double Left { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff743906.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double Top { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745897.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double Width { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746380.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double Height { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745098.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Enums.XlDisplayUnit DisplayUnit { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746148.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Double DisplayUnitCustom { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745935.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
bool HasDisplayUnitLabel { get; set; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745287.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.DisplayUnitLabel DisplayUnitLabel { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746825.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.ChartBorder Border { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746150.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.ChartFormat Format { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745944.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
Int32 Creator { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744067.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16), ProxyResult]
object Parent { get; }
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746674.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
NetOffice.PowerPointApi.Application Application { get; }
#endregion
#region Methods
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746130.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
object Delete();
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744150.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
object Select();
#endregion
}
}
| 35.483568 | 106 | 0.672665 | [
"MIT"
] | igoreksiz/NetOffice | Source/PowerPoint/DispatchInterfaces/Axis.cs | 15,118 | C# |
using System.Collections;
using System.Web;
using OptimizelySDK.Entity;
namespace Foundation.Experiments.Core.Interfaces
{
/// <summary>
/// Used to get the user Id and attributes of the user to be used in roll outs and experimentation
/// </summary>
public interface IUserRetriever
{
/// <summary>
/// Returns the user Id of the current user if one is found, String.Empty if none found
/// </summary>
/// <returns></returns>
string GetUserId(HttpContextBase httpContext);
/// <summary>
/// Returns attributes of the current user
/// </summary>
/// <returns></returns>
UserAttributes GetUserAttributes(HttpContextBase httpContext);
/// <summary>
/// Returns attributes of the current user
/// </summary>
/// <returns></returns>
UserAttributes GetUserAttributes(HttpContextBase httpContext, bool includeVisitorGroups);
}
} | 32.3 | 102 | 0.637771 | [
"Apache-2.0"
] | JoshuaFolkerts/foundation-experiments | src/Foundation.Experiments/Core/Interfaces/IUserRetriever.cs | 971 | C# |
#region copyright
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using CiccioSoft.Inventory.Data;
using CiccioSoft.Inventory.Data.Services;
using CiccioSoft.Inventory.Uwp.Models;
namespace CiccioSoft.Inventory.Uwp.Services
{
public class OrderItemService : IOrderItemService
{
public OrderItemService(IDataServiceFactory dataServiceFactory)
{
DataServiceFactory = dataServiceFactory;
}
public IDataServiceFactory DataServiceFactory { get; }
public async Task<OrderItemModel> GetOrderItemAsync(long orderID, int lineID)
{
using (var dataService = DataServiceFactory.CreateDataService())
{
return await GetOrderItemAsync(dataService, orderID, lineID);
}
}
static private async Task<OrderItemModel> GetOrderItemAsync(IDataService dataService, long orderID, int lineID)
{
var item = await dataService.GetOrderItemAsync(orderID, lineID);
if (item != null)
{
return await CreateOrderItemModelAsync(item, includeAllFields: true);
}
return null;
}
public Task<IList<OrderItemModel>> GetOrderItemsAsync(DataRequest<OrderItem> request)
{
// OrderItems are not virtualized
return GetOrderItemsAsync(0, 100, request);
}
public async Task<IList<OrderItemModel>> GetOrderItemsAsync(int skip, int take, DataRequest<OrderItem> request)
{
var models = new List<OrderItemModel>();
using (var dataService = DataServiceFactory.CreateDataService())
{
var items = await dataService.GetOrderItemsAsync(skip, take, request);
foreach (var item in items)
{
models.Add(await CreateOrderItemModelAsync(item, includeAllFields: false));
}
return models;
}
}
public async Task<int> GetOrderItemsCountAsync(DataRequest<OrderItem> request)
{
using (var dataService = DataServiceFactory.CreateDataService())
{
return await dataService.GetOrderItemsCountAsync(request);
}
}
public async Task<int> UpdateOrderItemAsync(OrderItemModel model)
{
using (var dataService = DataServiceFactory.CreateDataService())
{
var orderItem = model.OrderLine > 0 ? await dataService.GetOrderItemAsync(model.OrderID, model.OrderLine) : new OrderItem();
if (orderItem != null)
{
UpdateOrderItemFromModel(orderItem, model);
await dataService.UpdateOrderItemAsync(orderItem);
model.Merge(await GetOrderItemAsync(dataService, orderItem.OrderID, orderItem.OrderLine));
}
return 0;
}
}
public async Task<int> DeleteOrderItemAsync(OrderItemModel model)
{
var orderItem = new OrderItem { OrderID = model.OrderID, OrderLine = model.OrderLine };
using (var dataService = DataServiceFactory.CreateDataService())
{
return await dataService.DeleteOrderItemsAsync(orderItem);
}
}
public async Task<int> DeleteOrderItemRangeAsync(int index, int length, DataRequest<OrderItem> request)
{
using (var dataService = DataServiceFactory.CreateDataService())
{
var items = await dataService.GetOrderItemKeysAsync(index, length, request);
return await dataService.DeleteOrderItemsAsync(items.ToArray());
}
}
static public async Task<OrderItemModel> CreateOrderItemModelAsync(OrderItem source, bool includeAllFields)
{
var model = new OrderItemModel()
{
OrderID = source.OrderID,
OrderLine = source.OrderLine,
ProductID = source.ProductID,
Quantity = source.Quantity,
UnitPrice = source.UnitPrice,
Discount = source.Discount,
TaxType = source.TaxType,
Product = await ProductService.CreateProductModelAsync(source.Product, includeAllFields)
};
return model;
}
private void UpdateOrderItemFromModel(OrderItem target, OrderItemModel source)
{
target.OrderID = source.OrderID;
target.OrderLine = source.OrderLine;
target.ProductID = source.ProductID;
target.Quantity = source.Quantity;
target.UnitPrice = source.UnitPrice;
target.Discount = source.Discount;
target.TaxType = source.TaxType;
}
}
}
| 39.858156 | 140 | 0.607473 | [
"MIT"
] | FrancescoCrimi/InventorySample | src/Inventory.App/Services/OrderItemService.cs | 5,622 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.451)
// Version 5.451.0.0 www.ComponentFactory.com
// *****************************************************************************
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Redirect back/border/content based on the incoming grid state and style.
/// </summary>
public class PaletteRedirectBreadCrumb : PaletteRedirect
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the PaletteRedirectBreadCrumb class.
/// </summary>
/// <param name="target">Initial palette target for redirection.</param>
public PaletteRedirectBreadCrumb(IPalette target)
: base(target)
{
Left = false;
Right = false;
TopBottom = true;
}
#endregion
#region Left
/// <summary>
/// Gets and sets if the left border should be removed.
/// </summary>
public bool Left { get; set; }
#endregion
#region Right
/// <summary>
/// Gets and sets if the right border should be removed.
/// </summary>
public bool Right { get; set; }
#endregion
#region TopBottom
/// <summary>
/// Gets and sets if the top and bottom borders should be removed.
/// </summary>
public bool TopBottom { get; set; }
#endregion
#region GetBorderDrawBorders
/// <summary>
/// Gets a value indicating which borders to draw.
/// </summary>
/// <param name="style">Border style.</param>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>PaletteDrawBorders value.</returns>
public override PaletteDrawBorders GetBorderDrawBorders(PaletteBorderStyle style, PaletteState state)
{
PaletteDrawBorders borders = base.GetBorderDrawBorders(style, state);
// We are only interested in bread crums buttons
if (style == PaletteBorderStyle.ButtonBreadCrumb)
{
if (Left)
{
borders &= ~PaletteDrawBorders.Left;
}
if (Right)
{
borders &= ~PaletteDrawBorders.Right;
}
if (TopBottom)
{
borders &= ~PaletteDrawBorders.TopBottom;
}
}
return borders;
}
#endregion
}
}
| 33.416667 | 157 | 0.548317 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.451 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Controls/PaletteRedirectBreadCrumb.cs | 3,211 | 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.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.DotNet.RemoteExecutor;
using System.Windows.Forms.TestUtilities;
using Xunit;
using static Interop;
using static Interop.ComCtl32;
namespace System.Windows.Forms.Tests
{
public class ListViewGroupTests : IClassFixture<ThreadExceptionFixture>
{
[WinFormsFact]
public void ListViewGroup_Ctor_Default()
{
var group = new ListViewGroup();
Assert.Empty(group.Footer);
Assert.Equal(HorizontalAlignment.Left, group.FooterAlignment);
Assert.Equal("ListViewGroup", group.Header);
Assert.Equal(HorizontalAlignment.Left, group.HeaderAlignment);
Assert.Empty(group.Subtitle);
Assert.Empty(group.Items);
Assert.Same(group.Items, group.Items);
Assert.Null(group.ListView);
Assert.Null(group.Name);
Assert.Null(group.Tag);
Assert.Equal(ListViewGroupCollapsedState.Default, group.CollapsedState);
Assert.Empty(group.TaskLink);
Assert.Empty(group.TitleImageKey);
Assert.Equal(-1, group.TitleImageIndex);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public void ListViewGroup_Ctor_String(string header, string expectedHeader)
{
var group = new ListViewGroup(header);
Assert.Empty(group.Footer);
Assert.Equal(HorizontalAlignment.Left, group.FooterAlignment);
Assert.Equal(expectedHeader, group.Header);
Assert.Equal(HorizontalAlignment.Left, group.HeaderAlignment);
Assert.Empty(group.Subtitle);
Assert.Empty(group.Items);
Assert.Same(group.Items, group.Items);
Assert.Null(group.ListView);
Assert.Null(group.Name);
Assert.Null(group.Tag);
Assert.Equal(ListViewGroupCollapsedState.Default, group.CollapsedState);
Assert.Empty(group.TaskLink);
Assert.Empty(group.TitleImageKey);
Assert.Equal(-1, group.TitleImageIndex);
}
public static IEnumerable<object[]> Ctor_String_HorizontalAlignment_TestData()
{
yield return new object[] { null, HorizontalAlignment.Left, string.Empty };
yield return new object[] { string.Empty, HorizontalAlignment.Right, string.Empty };
yield return new object[] { "reasonable", HorizontalAlignment.Center, "reasonable" };
yield return new object[] { "reasonable", (HorizontalAlignment)(HorizontalAlignment.Left - 1), "reasonable" };
yield return new object[] { "reasonable", (HorizontalAlignment)(HorizontalAlignment.Center + 1), "reasonable" };
}
[WinFormsTheory]
[MemberData(nameof(Ctor_String_HorizontalAlignment_TestData))]
public void ListViewGroup_Ctor_String_HorizontalAlignment(string header, HorizontalAlignment headerAlignment, string expectedHeader)
{
var group = new ListViewGroup(header, headerAlignment);
Assert.Empty(group.Footer);
Assert.Equal(HorizontalAlignment.Left, group.FooterAlignment);
Assert.Equal(expectedHeader, group.Header);
Assert.Equal(headerAlignment, group.HeaderAlignment);
Assert.Empty(group.Subtitle);
Assert.Empty(group.Items);
Assert.Equal(group.Items, group.Items);
Assert.Null(group.ListView);
Assert.Null(group.Name);
Assert.Null(group.Tag);
Assert.Equal(ListViewGroupCollapsedState.Default, group.CollapsedState);
Assert.Empty(group.TaskLink);
Assert.Empty(group.TitleImageKey);
Assert.Equal(-1, group.TitleImageIndex);
}
public static IEnumerable<object[]> Ctor_String_String_TestData()
{
yield return new object[] { null, null, string.Empty };
yield return new object[] { string.Empty, string.Empty, string.Empty };
yield return new object[] { "key", "header", "header" };
}
[WinFormsTheory]
[MemberData(nameof(Ctor_String_String_TestData))]
public void ListViewGroup_Ctor_String_String(string key, string header, string expectedHeader)
{
var group = new ListViewGroup(key, header);
Assert.Empty(group.Footer);
Assert.Equal(HorizontalAlignment.Left, group.FooterAlignment);
Assert.Equal(expectedHeader, group.Header);
Assert.Equal(HorizontalAlignment.Left, group.HeaderAlignment);
Assert.Empty(group.Subtitle);
Assert.Empty(group.Items);
Assert.Same(group.Items, group.Items);
Assert.Null(group.ListView);
Assert.Equal(key, group.Name);
Assert.Null(group.Tag);
Assert.Equal(ListViewGroupCollapsedState.Default, group.CollapsedState);
Assert.Empty(group.TaskLink);
Assert.Empty(group.TitleImageKey);
Assert.Equal(-1, group.TitleImageIndex);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetNonNegativeIntTheoryData))]
[InlineData(-1)]
public void ListViewGroup_TitleImageIndex_SetWithoutListView_GetReturnsExpected(int value)
{
var group = new ListViewGroup
{
TitleImageIndex = value
};
Assert.Equal(value, group.TitleImageIndex);
// Set same.
group.TitleImageIndex = value;
Assert.Equal(value, group.TitleImageIndex);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetNonNegativeIntTheoryData))]
[InlineData(-1)]
public void ListViewGroup_TitleImageIndex_SetWithListView_GetReturnsExpected(int value)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
group.TitleImageIndex = value;
Assert.Equal(value, group.TitleImageIndex);
Assert.False(listView.IsHandleCreated);
// Set same.
group.TitleImageIndex = value;
Assert.Equal(value, group.TitleImageIndex);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetNonNegativeIntTheoryData))]
[InlineData(-1)]
public void ListViewGroup_TitleImageIndex_SetWithListViewWithHandle_GetReturnsExpected(int value)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.TitleImageIndex = value;
Assert.Equal(value, group.TitleImageIndex);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.TitleImageIndex = value;
Assert.Equal(value, group.TitleImageIndex);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
// Need to verify test once RE fixed.
[WinFormsFact(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
public unsafe void ListViewGroup_TitleImageIndex_GetGroupInfo_Success()
{
// Run this from another thread as we call Application.EnableVisualStyles.
using RemoteInvokeHandle invokerHandle = RemoteExecutor.Invoke(() =>
{
var data = new (int, int)[] { (-1, -1), (0, 0), (1, 1), (2, -1) };
foreach ((int Index, int Expected) value in data)
{
Application.EnableVisualStyles();
using var listView = new ListView();
using var groupImageList = new ImageList();
groupImageList.Images.Add(new Bitmap(10, 10));
groupImageList.Images.Add(new Bitmap(20, 20));
listView.GroupImageList = groupImageList;
Assert.Equal(groupImageList.Handle,
User32.SendMessageW(listView.Handle, (User32.WM)LVM.SETIMAGELIST, (IntPtr)LVSIL.GROUPHEADER, groupImageList.Handle));
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group.TitleImageIndex = value.Index;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.TITLEIMAGE | LVGF.GROUPID,
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(value.Expected, lvgroup.iTitleImage);
Assert.True(lvgroup.iGroupId >= 0);
}
});
// verify the remote process succeeded
Assert.Equal(0, invokerHandle.ExitCode);
}
[WinFormsFact]
public void ListViewGroup_TitleImageIndex_SetInvalid_ThrowsArgumentOutOfRangeException()
{
var random = new Random();
int value = random.Next(2, int.MaxValue) * -1;
var group = new ListViewGroup();
Assert.Throws<ArgumentOutOfRangeException>("value", () => group.TitleImageIndex = value);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public void ListViewGroup_TitleImageIndex_SetTitleImageKey_GetReturnsExpected(string key, string expected)
{
var group = new ListViewGroup
{
TitleImageIndex = 0
};
Assert.Equal(0, group.TitleImageIndex);
// verify TitleImageIndex resets to default once TitleImageKey is set
group.TitleImageKey = key;
Assert.Equal(expected, group.TitleImageKey);
Assert.Equal(ImageList.Indexer.DefaultIndex, group.TitleImageIndex);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_TitleImageKey_SetWithoutListView_GetReturnsExpected(string value, string expected)
{
var group = new ListViewGroup
{
TitleImageKey = value
};
Assert.Equal(expected, group.TitleImageKey);
// Set same.
group.TitleImageKey = value;
Assert.Equal(expected, group.TitleImageKey);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_TitleImageKey_SetWithListView_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
group.TitleImageKey = value;
Assert.Equal(expected, group.TitleImageKey);
Assert.False(listView.IsHandleCreated);
// Set same.
group.TitleImageKey = value;
Assert.Equal(expected, group.TitleImageKey);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData("header", "header")]
[InlineData("te\0xt", "te\0xt")]
[InlineData("ListViewGroup", "ListViewGroup")]
public void ListViewGroup_TitleImageKey_SetWithListViewWithHandle_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.TitleImageKey = value;
Assert.Equal(expected, group.TitleImageKey);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.TitleImageKey = value;
Assert.Equal(expected, group.TitleImageKey);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
// Need to verify test once RE fixed.
[WinFormsFact(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
public unsafe void ListViewGroup_TitleImageKey_GetGroupInfo_Success()
{
// Run this from another thread as we call Application.EnableVisualStyles.
using RemoteInvokeHandle invokerHandle = RemoteExecutor.Invoke(() =>
{
var data = new (string, int)[] { (null, -1), (string.Empty, -1), ("text", 0), ("te\0t", 0) };
foreach ((string Key, int ExpectedIndex) value in data)
{
Application.EnableVisualStyles();
using var listView = new ListView();
using var groupImageList = new ImageList();
groupImageList.Images.Add(value.Key, new Bitmap(10, 10));
listView.GroupImageList = groupImageList;
Assert.Equal(groupImageList.Handle,
User32.SendMessageW(listView.Handle, (User32.WM)LVM.SETIMAGELIST, (IntPtr)LVSIL.GROUPHEADER, groupImageList.Handle));
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group.TitleImageKey = value.Key;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.TITLEIMAGE | LVGF.GROUPID
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(value.ExpectedIndex, lvgroup.iTitleImage);
Assert.True(lvgroup.iGroupId >= 0);
}
});
// verify the remote process succeeded
Assert.Equal(0, invokerHandle.ExitCode);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetNonNegativeIntTheoryData))]
[InlineData(-1)]
public void ListViewGroup_TitleImageKey_SetTitleImageIndex_GetReturnsExpected(int value)
{
var group = new ListViewGroup
{
TitleImageKey = "key"
};
Assert.Equal("key", group.TitleImageKey);
// verify TitleImageKey resets to default once TitleImageIndex is set
group.TitleImageIndex = value;
Assert.Equal(value, group.TitleImageIndex);
Assert.Equal(ImageList.Indexer.DefaultKey, group.TitleImageKey);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Subtitle_SetWithoutListView_GetReturnsExpected(string value, string expected)
{
var group = new ListViewGroup
{
Subtitle = value
};
Assert.Equal(expected, group.Subtitle);
// Set same.
group.Subtitle = value;
Assert.Equal(expected, group.Subtitle);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Subtitle_SetWithListView_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
group.Subtitle = value;
Assert.Equal(expected, group.Subtitle);
Assert.False(listView.IsHandleCreated);
// Set same.
group.Subtitle = value;
Assert.Equal(expected, group.Subtitle);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData("header", "header")]
[InlineData("te\0xt", "te\0xt")]
[InlineData("ListViewGroup", "ListViewGroup")]
public void ListViewGroup_Subtitle_SetWithListViewWithHandle_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.Subtitle = value;
Assert.Equal(expected, group.Subtitle);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.Subtitle = value;
Assert.Equal(expected, group.Subtitle);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
public static IEnumerable<object[]> Property_TypeString_GetGroupInfo_TestData()
{
yield return new object[] { null, string.Empty };
yield return new object[] { string.Empty, string.Empty };
yield return new object[] { "text", "text" };
yield return new object[] { "te\0t", "te" };
}
[WinFormsFact(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
public unsafe void ListViewGroup_Subtitle_GetGroupInfo_Success()
{
// Run this from another thread as we call Application.EnableVisualStyles.
using RemoteInvokeHandle invokerHandle = RemoteExecutor.Invoke(() =>
{
foreach (object[] data in Property_TypeString_GetGroupInfo_TestData())
{
string value = (string)data[0];
string expected = (string)data[1];
Application.EnableVisualStyles();
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group.Subtitle = value;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
char* buffer = stackalloc char[256];
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.SUBTITLE | LVGF.GROUPID,
pszSubtitle = buffer,
cchSubtitle = 256
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(expected, new string(lvgroup.pszSubtitle));
Assert.True(lvgroup.iGroupId >= 0);
}
});
// verify the remote process succeeded
Assert.Equal(0, invokerHandle.ExitCode);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Footer_SetWithoutListView_GetReturnsExpected(string value, string expected)
{
var group = new ListViewGroup
{
Footer = value
};
Assert.Equal(expected, group.Footer);
// Set same.
group.Footer = value;
Assert.Equal(expected, group.Footer);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Footer_SetWithListView_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
group.Footer = value;
Assert.Equal(expected, group.Footer);
Assert.False(listView.IsHandleCreated);
// Set same.
group.Footer = value;
Assert.Equal(expected, group.Footer);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData("header", "header")]
[InlineData("te\0xt", "te\0xt")]
[InlineData("ListViewGroup", "ListViewGroup")]
public void ListViewGroup_Footer_SetWithListViewWithHandle_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.Footer = value;
Assert.Equal(expected, group.Footer);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.Footer = value;
Assert.Equal(expected, group.Footer);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
[WinFormsFact(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
public unsafe void ListViewGroup_Footer_GetGroupInfo_Success()
{
// Run this from another thread as we call Application.EnableVisualStyles.
using RemoteInvokeHandle invokerHandle = RemoteExecutor.Invoke(() =>
{
foreach (object[] data in Property_TypeString_GetGroupInfo_TestData())
{
string value = (string)data[0];
string expected = (string)data[1];
Application.EnableVisualStyles();
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group.Footer = value;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
char* buffer = stackalloc char[256];
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.FOOTER | LVGF.GROUPID | LVGF.ALIGN,
pszFooter = buffer,
cchFooter = 256
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(expected, new string(lvgroup.pszFooter));
Assert.True(lvgroup.iGroupId >= 0);
Assert.Equal(LVGA.HEADER_LEFT | LVGA.FOOTER_LEFT, lvgroup.uAlign);
}
});
// verify the remote process succeeded
Assert.Equal(0, invokerHandle.ExitCode);
}
public static IEnumerable<object[]> Alignment_Set_TestData()
{
foreach (HorizontalAlignment value in Enum.GetValues(typeof(HorizontalAlignment)))
{
yield return new object[] { null, value, string.Empty };
yield return new object[] { string.Empty, value, string.Empty };
yield return new object[] { "text", value, "text" };
}
}
[WinFormsTheory]
[MemberData(nameof(Alignment_Set_TestData))]
public void ListViewGroup_FooterAlignment_SetWithoutListView_GetReturnsExpected(string footer, HorizontalAlignment value, string expectedFooter)
{
var group = new ListViewGroup
{
Footer = footer,
FooterAlignment = value
};
Assert.Equal(value, group.FooterAlignment);
Assert.Equal(expectedFooter, group.Footer);
// Set same.
group.FooterAlignment = value;
Assert.Equal(value, group.FooterAlignment);
Assert.Equal(expectedFooter, group.Footer);
}
[WinFormsTheory]
[MemberData(nameof(Alignment_Set_TestData))]
public void ListViewGroup_FooterAlignment_SetWithListView_GetReturnsExpected(string footer, HorizontalAlignment value, string expectedFooter)
{
using var listView = new ListView();
var group = new ListViewGroup
{
Footer = footer
};
listView.Groups.Add(group);
group.FooterAlignment = value;
Assert.Equal(value, group.FooterAlignment);
Assert.Equal(expectedFooter, group.Footer);
Assert.False(listView.IsHandleCreated);
// Set same.
group.FooterAlignment = value;
Assert.Equal(value, group.FooterAlignment);
Assert.Equal(expectedFooter, group.Footer);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[MemberData(nameof(Alignment_Set_TestData))]
public void ListViewGroup_FooterAlignment_SetWithListViewWithHandle_GetReturnsExpected(string footer, HorizontalAlignment value, string expectedFooter)
{
using var listView = new ListView();
var group = new ListViewGroup
{
Footer = footer
};
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.FooterAlignment = value;
Assert.Equal(value, group.FooterAlignment);
Assert.Equal(expectedFooter, group.Footer);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.FooterAlignment = value;
Assert.Equal(value, group.FooterAlignment);
Assert.Equal(expectedFooter, group.Footer);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
public static IEnumerable<object[]> FooterAlignment_GetGroupInfo_TestData()
{
yield return new object[] { string.Empty, HorizontalAlignment.Left, 0x00000008 | (int)LVGA.HEADER_LEFT };
yield return new object[] { string.Empty, HorizontalAlignment.Center, 0x00000010 | (int)LVGA.HEADER_LEFT };
yield return new object[] { string.Empty, HorizontalAlignment.Right, 0x00000020 | (int)LVGA.HEADER_LEFT };
yield return new object[] { "footer", HorizontalAlignment.Left, 0x00000008 | (int)LVGA.HEADER_LEFT };
yield return new object[] { "footer", HorizontalAlignment.Center, 0x00000010 | (int)LVGA.HEADER_LEFT };
yield return new object[] { "footer", HorizontalAlignment.Right, 0x00000020 | (int)LVGA.HEADER_LEFT };
}
[WinFormsTheory(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
[MemberData(nameof(FooterAlignment_GetGroupInfo_TestData))]
public unsafe void ListView_FooterAlignment_GetGroupInfo_Success(string footerParam, HorizontalAlignment valueParam, int expectedAlignParam)
{
// Run this from another thread as we call Application.EnableVisualStyles.
RemoteExecutor.Invoke((footer, valueString, expectedAlignString) =>
{
HorizontalAlignment value = (HorizontalAlignment)Enum.Parse(typeof(HorizontalAlignment), valueString);
int expectedAlign = int.Parse(expectedAlignString);
Application.EnableVisualStyles();
using var listView = new ListView();
var group1 = new ListViewGroup
{
Footer = footer
};
listView.Groups.Add(group1);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group1.FooterAlignment = value;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
char* buffer = stackalloc char[256];
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.FOOTER | LVGF.GROUPID | LVGF.ALIGN,
pszFooter = buffer,
cchFooter = 256
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(footer, new string(lvgroup.pszFooter));
Assert.True(lvgroup.iGroupId >= 0);
Assert.Equal(expectedAlign, (int)lvgroup.uAlign);
}, footerParam, valueParam.ToString(), expectedAlignParam.ToString()).Dispose();
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(HorizontalAlignment))]
public void ListViewGroup_FooterAlignment_SetInvalid_ThrowsInvalidEnumArgumentException(HorizontalAlignment value)
{
var group = new ListViewGroup();
Assert.Throws<InvalidEnumArgumentException>("value", () => group.FooterAlignment = value);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Header_SetWithoutListView_GetReturnsExpected(string value, string expected)
{
var group = new ListViewGroup
{
Header = value
};
Assert.Equal(expected, group.Header);
// Set same.
group.Header = value;
Assert.Equal(expected, group.Header);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Header_SetWithListView_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
group.Header = value;
Assert.Equal(expected, group.Header);
Assert.False(listView.IsHandleCreated);
// Set same.
group.Header = value;
Assert.Equal(expected, group.Header);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData("header", "header")]
[InlineData("te\0xt", "te\0xt")]
[InlineData("ListViewGroup", "ListViewGroup")]
public void ListViewGroup_Header_SetWithListViewWithHandle_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.Header = value;
Assert.Equal(expected, group.Header);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.Header = value;
Assert.Equal(expected, group.Header);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
[WinFormsFact(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
public unsafe void ListViewGroup_Header_GetGroupInfo_Success()
{
// Run this from another thread as we call Application.EnableVisualStyles.
using RemoteInvokeHandle invokerHandle = RemoteExecutor.Invoke(() =>
{
foreach (object[] data in Property_TypeString_GetGroupInfo_TestData())
{
string value = (string)data[0];
string expected = (string)data[1];
Application.EnableVisualStyles();
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group.Header = value;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
char* buffer = stackalloc char[256];
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.HEADER | LVGF.GROUPID | LVGF.ALIGN,
pszHeader = buffer,
cchHeader = 256
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(expected, new string(lvgroup.pszHeader));
Assert.True(lvgroup.iGroupId >= 0);
Assert.Equal(LVGA.HEADER_LEFT | LVGA.FOOTER_LEFT, lvgroup.uAlign);
}
});
// verify the remote process succeeded
Assert.Equal(0, invokerHandle.ExitCode);
}
[WinFormsTheory]
[MemberData(nameof(Alignment_Set_TestData))]
public void ListViewGroup_HeaderAlignment_SetWithoutListView_GetReturnsExpected(string header, HorizontalAlignment value, string expectedHeader)
{
var group = new ListViewGroup
{
Header = header,
HeaderAlignment = value
};
Assert.Equal(value, group.HeaderAlignment);
Assert.Equal(expectedHeader, group.Header);
// Set same.
group.HeaderAlignment = value;
Assert.Equal(value, group.HeaderAlignment);
Assert.Equal(expectedHeader, group.Header);
}
[WinFormsTheory]
[MemberData(nameof(Alignment_Set_TestData))]
public void ListViewGroup_HeaderAlignment_SetWithListView_GetReturnsExpected(string header, HorizontalAlignment value, string expectedHeader)
{
using var listView = new ListView();
var group = new ListViewGroup
{
Header = header
};
listView.Groups.Add(group);
group.HeaderAlignment = value;
Assert.Equal(value, group.HeaderAlignment);
Assert.Equal(expectedHeader, group.Header);
Assert.False(listView.IsHandleCreated);
// Set same.
group.HeaderAlignment = value;
Assert.Equal(value, group.HeaderAlignment);
Assert.Equal(expectedHeader, group.Header);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[MemberData(nameof(Alignment_Set_TestData))]
public void ListViewGroup_HeaderAlignment_SetWithListViewWithHandle_GetReturnsExpected(string header, HorizontalAlignment value, string expectedHeader)
{
using var listView = new ListView();
var group = new ListViewGroup
{
Header = header
};
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.HeaderAlignment = value;
Assert.Equal(value, group.HeaderAlignment);
Assert.Equal(expectedHeader, group.Header);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.HeaderAlignment = value;
Assert.Equal(value, group.HeaderAlignment);
Assert.Equal(expectedHeader, group.Header);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
public static IEnumerable<object[]> HeaderAlignment_GetGroupInfo_TestData()
{
yield return new object[] { string.Empty, HorizontalAlignment.Left, 0x00000001 | (int)LVGA.FOOTER_LEFT };
yield return new object[] { string.Empty, HorizontalAlignment.Center, 0x00000002 | (int)LVGA.FOOTER_LEFT };
yield return new object[] { string.Empty, HorizontalAlignment.Right, 0x00000004 | (int)LVGA.FOOTER_LEFT };
yield return new object[] { "header", HorizontalAlignment.Left, 0x00000001 | (int)LVGA.FOOTER_LEFT };
yield return new object[] { "header", HorizontalAlignment.Center, 0x00000002 | (int)LVGA.FOOTER_LEFT };
yield return new object[] { "header", HorizontalAlignment.Right, 0x00000004 | (int)LVGA.FOOTER_LEFT };
}
[WinFormsTheory(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
[MemberData(nameof(HeaderAlignment_GetGroupInfo_TestData))]
public unsafe void ListView_HeaderAlignment_GetGroupInfo_Success(string headerParam, HorizontalAlignment valueParam, int expectedAlignParam)
{
// Run this from another thread as we call Application.EnableVisualStyles.
RemoteExecutor.Invoke((header, valueString, expectedAlignString) =>
{
HorizontalAlignment value = (HorizontalAlignment)Enum.Parse(typeof(HorizontalAlignment), valueString);
int expectedAlign = int.Parse(expectedAlignString);
Application.EnableVisualStyles();
using var listView = new ListView();
var group1 = new ListViewGroup
{
Header = header
};
listView.Groups.Add(group1);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group1.HeaderAlignment = value;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
char* buffer = stackalloc char[256];
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.HEADER | LVGF.GROUPID | LVGF.ALIGN,
pszHeader = buffer,
cchHeader = 256
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(header, new string(lvgroup.pszHeader));
Assert.True(lvgroup.iGroupId >= 0);
Assert.Equal(expectedAlign, (int)lvgroup.uAlign);
}, headerParam, valueParam.ToString(), expectedAlignParam.ToString()).Dispose();
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(HorizontalAlignment))]
public void ListViewGroup_HeaderAlignment_SetInvalid_ThrowsInvalidEnumArgumentException(HorizontalAlignment value)
{
var group = new ListViewGroup();
Assert.Throws<InvalidEnumArgumentException>("value", () => group.HeaderAlignment = value);
}
public static IEnumerable<object[]> CollapsedState_TestData()
{
yield return new object[] { ListViewGroupCollapsedState.Default, ListViewGroupCollapsedState.Default };
yield return new object[] { ListViewGroupCollapsedState.Expanded, ListViewGroupCollapsedState.Expanded };
yield return new object[] { ListViewGroupCollapsedState.Collapsed, ListViewGroupCollapsedState.Collapsed };
}
[WinFormsTheory]
[MemberData(nameof(CollapsedState_TestData))]
public void ListViewGroup_Collapse_SetWithoutListView_GetReturnsExpected(ListViewGroupCollapsedState value, ListViewGroupCollapsedState expected)
{
var group = new ListViewGroup()
{
CollapsedState = value
};
Assert.Equal(expected, group.CollapsedState);
// Set same.
group.CollapsedState = value;
Assert.Equal(expected, group.CollapsedState);
}
[WinFormsTheory]
[MemberData(nameof(CollapsedState_TestData))]
public void ListViewGroup_Collapse_SetWithListView_GetReturnsExpected(ListViewGroupCollapsedState value, ListViewGroupCollapsedState expected)
{
using var listView = new ListView();
var group = new ListViewGroup
{
CollapsedState = value
};
listView.Groups.Add(group);
Assert.Equal(expected, group.CollapsedState);
Assert.Equal(group.CollapsedState, listView.Groups[0].CollapsedState);
Assert.False(listView.IsHandleCreated);
// Set same.
group.CollapsedState = value;
Assert.Equal(expected, group.CollapsedState);
Assert.Equal(group.CollapsedState, listView.Groups[0].CollapsedState);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[MemberData(nameof(CollapsedState_TestData))]
public void ListViewGroup_Collapse_SetWithListViewWithHandle_GetReturnsExpected(ListViewGroupCollapsedState value, ListViewGroupCollapsedState expected)
{
using var listView = new ListView();
var group = new ListViewGroup
{
CollapsedState = value
};
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
Assert.Equal(expected, group.CollapsedState);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.CollapsedState = value;
Assert.Equal(expected, group.CollapsedState);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
[WinFormsFact(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
public unsafe void ListViewGroup_Collapse_GetGroupInfo_Success()
{
// Run this from another thread as we call Application.EnableVisualStyles.
using RemoteInvokeHandle invokerHandle = RemoteExecutor.Invoke(() =>
{
foreach (object[] data in CollapsedState_TestData())
{
Application.EnableVisualStyles();
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group.CollapsedState = (ListViewGroupCollapsedState)data[0];
ListViewGroupCollapsedState expectedCollapsedState = (ListViewGroupCollapsedState)data[1];
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.STATE | LVGF.GROUPID,
stateMask = LVGS.COLLAPSIBLE | LVGS.COLLAPSED
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.True(lvgroup.iGroupId >= 0);
Assert.Equal(expectedCollapsedState, group.CollapsedState);
if (expectedCollapsedState == ListViewGroupCollapsedState.Default)
{
Assert.Equal(LVGS.NORMAL, lvgroup.state);
}
else if (expectedCollapsedState == ListViewGroupCollapsedState.Expanded)
{
Assert.Equal(LVGS.COLLAPSIBLE, lvgroup.state);
}
else
{
Assert.Equal(LVGS.COLLAPSIBLE | LVGS.COLLAPSED, lvgroup.state);
}
}
});
// verify the remote process succeeded
Assert.Equal(0, invokerHandle.ExitCode);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(ListViewGroupCollapsedState))]
public void ListViewGroup_CollapsedState_SetInvalid_ThrowsInvalidEnumArgumentException(ListViewGroupCollapsedState value)
{
var group = new ListViewGroup();
Assert.Throws<InvalidEnumArgumentException>("value", () => group.CollapsedState = value);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringWithNullTheoryData))]
public void ListViewGroup_Name_Set_GetReturnsExpected(string value)
{
var group = new ListViewGroup
{
Name = value
};
Assert.Same(value, group.Name);
// Set same.
group.Name = value;
Assert.Same(value, group.Name);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Task_SetWithoutListView_GetReturnsExpected(string value, string expected)
{
var group = new ListViewGroup
{
TaskLink = value
};
Assert.Equal(expected, group.TaskLink);
// Set same.
group.TaskLink = value;
Assert.Equal(expected, group.TaskLink);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
[InlineData("te\0xt", "te\0xt")]
public void ListViewGroup_Task_SetWithListView_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
group.TaskLink = value;
Assert.Equal(expected, group.TaskLink);
Assert.False(listView.IsHandleCreated);
// Set same.
group.TaskLink = value;
Assert.Equal(expected, group.TaskLink);
Assert.False(listView.IsHandleCreated);
}
[WinFormsTheory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData("header", "header")]
[InlineData("te\0xt", "te\0xt")]
[InlineData("ListViewGroup", "ListViewGroup")]
public void ListViewGroup_Task_SetWithListViewWithHandle_GetReturnsExpected(string value, string expected)
{
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
int invalidatedCallCount = 0;
listView.Invalidated += (sender, e) => invalidatedCallCount++;
int styleChangedCallCount = 0;
listView.StyleChanged += (sender, e) => styleChangedCallCount++;
int createdCallCount = 0;
listView.HandleCreated += (sender, e) => createdCallCount++;
group.TaskLink = value;
Assert.Equal(expected, group.TaskLink);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
// Set same.
group.TaskLink = value;
Assert.Equal(expected, group.TaskLink);
Assert.True(listView.IsHandleCreated);
Assert.Equal(0, invalidatedCallCount);
Assert.Equal(0, styleChangedCallCount);
Assert.Equal(0, createdCallCount);
}
[WinFormsFact(Skip = "Crash with AbandonedMutexException. See: https://github.com/dotnet/arcade/issues/5325")]
public unsafe void ListViewGroup_Task_GetGroupInfo_Success()
{
// Run this from another thread as we call Application.EnableVisualStyles.
using RemoteInvokeHandle invokerHandle = RemoteExecutor.Invoke(() =>
{
foreach (object[] data in Property_TypeString_GetGroupInfo_TestData())
{
string value = (string)data[0];
string expected = (string)data[1];
Application.EnableVisualStyles();
using var listView = new ListView();
var group = new ListViewGroup();
listView.Groups.Add(group);
Assert.NotEqual(IntPtr.Zero, listView.Handle);
group.TaskLink = value;
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPCOUNT, IntPtr.Zero, IntPtr.Zero));
char* buffer = stackalloc char[256];
var lvgroup = new LVGROUPW
{
cbSize = (uint)sizeof(LVGROUPW),
mask = LVGF.TASK | LVGF.GROUPID,
pszTask = buffer,
cchTask = 256
};
Assert.Equal((IntPtr)1, User32.SendMessageW(listView.Handle, (User32.WM)LVM.GETGROUPINFOBYINDEX, (IntPtr)0, ref lvgroup));
Assert.Equal(expected, new string(lvgroup.pszTask));
Assert.True(lvgroup.iGroupId >= 0);
}
});
// verify the remote process succeeded
Assert.Equal(0, invokerHandle.ExitCode);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringWithNullTheoryData))]
public void ListViewGroup_Tag_Set_GetReturnsExpected(string value)
{
var group = new ListViewGroup
{
Tag = value
};
Assert.Same(value, group.Tag);
// Set same.
group.Tag = value;
Assert.Same(value, group.Tag);
}
public static IEnumerable<object[]> Serialize_Deserialize_TestData()
{
yield return new object[] { new ListViewGroup() };
yield return new object[] { new ListViewGroup("header", HorizontalAlignment.Center) { Name = "name", Tag = "tag" } };
var groupWithEmptyItems = new ListViewGroup();
Assert.Empty(groupWithEmptyItems.Items);
yield return new object[] { groupWithEmptyItems };
var groupWithItems = new ListViewGroup();
groupWithItems.Items.Add(new ListViewItem("text"));
yield return new object[] { groupWithItems };
}
[WinFormsTheory]
[MemberData(nameof(Serialize_Deserialize_TestData))]
public void ListViewGroup_Serialize_Deserialize_Success(ListViewGroup group)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
#pragma warning disable SYSLIB0011 // Type or member is obsolete
formatter.Serialize(stream, group);
stream.Seek(0, SeekOrigin.Begin);
ListViewGroup result = Assert.IsType<ListViewGroup>(formatter.Deserialize(stream));
#pragma warning restore SYSLIB0011 // Type or member is obsolete
Assert.Equal(group.Header, result.Header);
Assert.Equal(group.HeaderAlignment, result.HeaderAlignment);
Assert.Equal(group.Items.Cast<ListViewItem>().Select(i => i.Text), result.Items.Cast<ListViewItem>().Select(i => i.Text));
Assert.Equal(group.Name, result.Name);
Assert.Equal(group.Tag, result.Tag);
}
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public void ListViewGroup_ToString_Invoke_ReturnsExpected(string header, string expected)
{
var group = new ListViewGroup(header);
Assert.Equal(expected, group.ToString());
}
[WinFormsFact]
public void ListViewGroup_ISerializableGetObjectData_InvokeSimple_Success()
{
var group = new ListViewGroup();
ISerializable iSerializable = group;
var info = new SerializationInfo(typeof(ListViewGroup), new FormatterConverter());
var context = new StreamingContext();
iSerializable.GetObjectData(info, context);
Assert.Equal("ListViewGroup", info.GetString("Header"));
Assert.Equal(HorizontalAlignment.Left, info.GetValue("HeaderAlignment", typeof(HorizontalAlignment)));
Assert.Throws<SerializationException>(() => info.GetString("Name"));
Assert.Null(info.GetValue("Tag", typeof(object)));
Assert.Throws<SerializationException>(() => info.GetInt32("ItemsCount"));
}
[WinFormsFact]
public void ListViewGroup_ISerializableGetObjectData_InvokeWithEmptyItems_Success()
{
var group = new ListViewGroup();
Assert.Empty(group.Items);
ISerializable iSerializable = group;
var info = new SerializationInfo(typeof(ListViewGroup), new FormatterConverter());
var context = new StreamingContext();
iSerializable.GetObjectData(info, context);
Assert.Equal("ListViewGroup", info.GetString("Header"));
Assert.Equal(HorizontalAlignment.Left, info.GetValue("HeaderAlignment", typeof(HorizontalAlignment)));
Assert.Throws<SerializationException>(() => info.GetString("Name"));
Assert.Null(info.GetValue("Tag", typeof(object)));
Assert.Throws<SerializationException>(() => info.GetInt32("ItemsCount"));
}
[WinFormsFact]
public void ListViewGroup_ISerializableGetObjectData_InvokeWithItems_Success()
{
var group = new ListViewGroup();
group.Items.Add(new ListViewItem("text"));
ISerializable iSerializable = group;
var info = new SerializationInfo(typeof(ListViewGroup), new FormatterConverter());
var context = new StreamingContext();
iSerializable.GetObjectData(info, context);
Assert.Equal("ListViewGroup", info.GetString("Header"));
Assert.Equal(HorizontalAlignment.Left, info.GetValue("HeaderAlignment", typeof(HorizontalAlignment)));
Assert.Throws<SerializationException>(() => info.GetString("Name"));
Assert.Null(info.GetValue("Tag", typeof(object)));
Assert.Equal(1, info.GetInt32("ItemsCount"));
Assert.Equal("text", ((ListViewItem)info.GetValue("Item0", typeof(ListViewItem))).Text);
}
[WinFormsFact]
public void ListViewGroup_ISerializableGetObjectData_NullInfo_ThrowsArgumentNullException()
{
var group = new ListViewGroup();
ISerializable iSerializable = group;
var context = new StreamingContext();
Assert.Throws<ArgumentNullException>("info", () => iSerializable.GetObjectData(null, context));
}
[WinFormsFact]
public void ListViewGroup_InvokeAdd_DoesNotAddTreeViewItemToList()
{
using var listView = new ListView();
ListViewItem listViewItem = new ListViewItem();
ListViewItem listViewItemGroup = new ListViewItem();
ListViewGroup listViewGroup = new ListViewGroup();
var accessor = KeyboardToolTipStateMachine.Instance.TestAccessor();
listView.Groups.Add(listViewGroup);
listView.Items.Add(listViewItem);
listViewGroup.Items.Add(listViewItemGroup);
Assert.True(accessor.IsToolTracked(listViewItem));
Assert.False(accessor.IsToolTracked(listViewItemGroup));
}
[WinFormsFact]
public void ListViewGroup_InvokeRemove_DoesNotRemoveTreeViewItemFromList()
{
using var listView = new ListView();
ListViewItem listViewItem = new ListViewItem();
ListViewGroup listViewGroup = new ListViewGroup();
var accessor = KeyboardToolTipStateMachine.Instance.TestAccessor();
listView.Groups.Add(listViewGroup);
listView.Items.Add(listViewItem);
listViewGroup.Items.Add(listViewItem);
Assert.True(accessor.IsToolTracked(listViewItem));
listViewGroup.Items.Remove(listViewItem);
Assert.True(accessor.IsToolTracked(listViewItem));
}
}
}
| 44.109875 | 160 | 0.604225 | [
"MIT"
] | abdullah1133/winforms | src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupTests.cs | 63,432 | C# |
using Xunit;
using AliceInventory.Logic;
using AliceInventory.Logic.Cache;
namespace AliceInventory.UnitTests
{
public class ResultCacheTests
{
[Fact]
public void GetEmptyResultFromCache()
{
ResultCache sut = new ResultCache();
ProcessingResult cachedResultUser1 = sut.Get("testUser1");
sut.Set("testUser3", new ProcessingResult());
ProcessingResult cachedResultUser2 = sut.Get("testUser2");
Assert.Null(cachedResultUser1);
Assert.Null(cachedResultUser2);
}
[Fact]
public void GetResultFromCacheAfterInitialAdd()
{
ResultCache sut = new ResultCache();
ProcessingResult resultUser1 = new ProcessingResult();
ProcessingResult resultUser2 = new ProcessingResult();
sut.Set("testUser1", resultUser1);
sut.Set("testUser2", resultUser2);
ProcessingResult cachedResultUser1 = sut.Get("testUser1");
ProcessingResult cachedResultUser2 = sut.Get("testUser2");
Assert.Equal(resultUser1, cachedResultUser1);
Assert.Equal(resultUser2, cachedResultUser2);
}
[Fact]
public void GetResultFromCacheAfterRewrite()
{
ResultCache sut = new ResultCache();
ProcessingResult result1 = new ProcessingResult();
sut.Set("testUser", result1);
ProcessingResult cachedResult1 = sut.Get("testUser");
Assert.Equal(result1, cachedResult1);
ProcessingResult Result = new ProcessingResult();
sut.Set("testUser", Result);
ProcessingResult cachedResult2 = sut.Get("testUser");
Assert.Equal(Result, cachedResult2);
}
}
} | 32.178571 | 70 | 0.614317 | [
"MIT"
] | artemziz/yandex-dialogs-inventory | src/AliceInventory.UnitTests/ResultCacheTests.cs | 1,802 | C# |
namespace HiddenTear_Message
{
partial class Form1
{
/// <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(Form1));
this.webBrowser1 = new System.Windows.Forms.WebBrowser();
this.SuspendLayout();
//
// webBrowser1
//
this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowser1.Location = new System.Drawing.Point(0, 0);
this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowser1.Name = "webBrowser1";
this.webBrowser1.ScriptErrorsSuppressed = true;
this.webBrowser1.ScrollBarsEnabled = false;
this.webBrowser1.Size = new System.Drawing.Size(292, 273);
this.webBrowser1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.ControlBox = false;
this.Controls.Add(this.webBrowser1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.WebBrowser webBrowser1;
}
}
| 39.608696 | 138 | 0.583242 | [
"MIT"
] | Harot5001/HiddenTear | HiddenTear-Message/Form1.Designer.cs | 2,735 | C# |
namespace XMetadata.MetadataDescriptors
{
/// <summary>
/// Definition of the <see cref="ShortMetadata"/> class.
/// </summary>
public class ShortMetadata : ABoundableMetadata<short>
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ShortMetadata"/> class.
/// </summary>
/// <param name="pId">The metadata identifier.</param>
public ShortMetadata(string pId)
: base(pId)
{
this.Min = short.MinValue;
this.Max = short.MaxValue;
}
#endregion // Constructors.
#region Methods
/// <summary>
/// Gets the default value.
/// </summary>
/// <returns>The default value.</returns>
public override object GetDefautValue()
{
return 0;
}
#endregion // Methods.
}
}
| 24.026316 | 80 | 0.535597 | [
"MIT"
] | mastertnt/XRay | XMetadata/MetadataDescriptors/ShortMetadata.cs | 915 | C# |
using FlexibleProxy;
using FlexibleProxy.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FlexibleProxyTests
{
[TestClass]
public class ArgumentsParserTests
{
[TestMethod]
public void ParseTest()
{
var parser = new ArgumentsParser(new[] { "-Arg1", "Value1", "-Arg2", "/Arg3", "Value2" });
Assert.IsTrue(parser.GetValue<bool>("Arg2"));
Assert.AreEqual(parser.GetValue<string>("Arg1"), "Value1");
Assert.AreEqual(parser.GetValue<string>("Arg3"), "Value2");
}
}
}
| 29.15 | 102 | 0.622642 | [
"MIT"
] | sts11vcd71/NetworkTools | FlexibleProxy/FlexibleProxyTests/ArgumentsParserTests.cs | 585 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Domain.Apps.Core.ExtractReferenceIds;
using Squidex.Domain.Apps.Entities.Contents.DomainObject;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Reflection;
using Squidex.Infrastructure.States;
using Squidex.Log;
namespace Squidex.Domain.Apps.Entities.MongoDb.Contents
{
public partial class MongoContentRepository : ISnapshotStore<ContentDomainObject.State>
{
Task ISnapshotStore<ContentDomainObject.State>.ReadAllAsync(Func<ContentDomainObject.State, long, Task> callback,
CancellationToken ct)
{
return Task.CompletedTask;
}
async Task<(ContentDomainObject.State Value, bool Valid, long Version)> ISnapshotStore<ContentDomainObject.State>.ReadAsync(DomainId key)
{
using (Profiler.TraceMethod<MongoContentRepository>())
{
var version = await collectionAll.FindVersionAsync(key);
return (null!, false, version);
}
}
async Task ISnapshotStore<ContentDomainObject.State>.ClearAsync()
{
using (Profiler.TraceMethod<MongoContentRepository>())
{
await collectionAll.ClearAsync();
await collectionPublished.ClearAsync();
}
}
async Task ISnapshotStore<ContentDomainObject.State>.RemoveAsync(DomainId key)
{
using (Profiler.TraceMethod<MongoContentRepository>())
{
await collectionAll.RemoveAsync(key);
await collectionPublished.RemoveAsync(key);
}
}
async Task ISnapshotStore<ContentDomainObject.State>.WriteAsync(DomainId key, ContentDomainObject.State value, long oldVersion, long newVersion)
{
using (Profiler.TraceMethod<MongoContentRepository>())
{
if (value.SchemaId.Id == DomainId.Empty)
{
return;
}
await Task.WhenAll(
UpsertDraftContentAsync(value, oldVersion, newVersion),
UpsertOrDeletePublishedAsync(value, oldVersion, newVersion));
}
}
async Task ISnapshotStore<ContentDomainObject.State>.WriteManyAsync(IEnumerable<(DomainId Key, ContentDomainObject.State Value, long Version)> snapshots)
{
using (Profiler.TraceMethod<MongoContentRepository>())
{
var entitiesPublished = new List<MongoContentEntity>();
var entitiesAll = new List<MongoContentEntity>();
foreach (var (_, value, version) in snapshots)
{
if (ShouldWritePublished(value))
{
entitiesPublished.Add(await CreatePublishedContentAsync(value, version));
}
entitiesAll.Add(await CreateDraftContentAsync(value, version));
}
await Task.WhenAll(
collectionPublished.InsertManyAsync(entitiesPublished),
collectionAll.InsertManyAsync(entitiesAll));
}
}
private async Task UpsertOrDeletePublishedAsync(ContentDomainObject.State value, long oldVersion, long newVersion)
{
if (ShouldWritePublished(value))
{
await UpsertPublishedContentAsync(value, oldVersion, newVersion);
}
else
{
await DeletePublishedContentAsync(value.AppId.Id, value.Id);
}
}
private Task DeletePublishedContentAsync(DomainId appId, DomainId id)
{
var documentId = DomainId.Combine(appId, id);
return collectionPublished.RemoveAsync(documentId);
}
private async Task UpsertDraftContentAsync(ContentDomainObject.State value, long oldVersion, long newVersion)
{
var entity = await CreateDraftContentAsync(value, newVersion);
await collectionAll.UpsertVersionedAsync(entity.DocumentId, oldVersion, entity);
}
private async Task UpsertPublishedContentAsync(ContentDomainObject.State value, long oldVersion, long newVersion)
{
var entity = await CreatePublishedContentAsync(value, newVersion);
await collectionPublished.UpsertVersionedAsync(entity.DocumentId, oldVersion, entity);
}
private async Task<MongoContentEntity> CreatePublishedContentAsync(ContentDomainObject.State value, long newVersion)
{
var entity = await CreateContentAsync(value, value.CurrentVersion.Data, newVersion);
entity.ScheduledAt = null;
entity.ScheduleJob = null;
entity.NewStatus = null;
return entity;
}
private async Task<MongoContentEntity> CreateDraftContentAsync(ContentDomainObject.State value, long newVersion)
{
var entity = await CreateContentAsync(value, value.Data, newVersion);
entity.ScheduledAt = value.ScheduleJob?.DueTime;
entity.ScheduleJob = value.ScheduleJob;
entity.NewStatus = value.NewStatus;
return entity;
}
private async Task<MongoContentEntity> CreateContentAsync(ContentDomainObject.State value, ContentData data, long newVersion)
{
var entity = SimpleMapper.Map(value, new MongoContentEntity());
entity.Data = data;
entity.DocumentId = value.UniqueId;
entity.IndexedAppId = value.AppId.Id;
entity.IndexedSchemaId = value.SchemaId.Id;
entity.Version = newVersion;
var schema = await appProvider.GetSchemaAsync(value.AppId.Id, value.SchemaId.Id, true);
if (schema != null)
{
entity.ReferencedIds = entity.Data.GetReferencedIds(schema.SchemaDef);
}
else
{
entity.ReferencedIds = new HashSet<DomainId>();
}
return entity;
}
private static bool ShouldWritePublished(ContentDomainObject.State value)
{
return value.Status == Status.Published && !value.IsDeleted;
}
}
}
| 37.458564 | 161 | 0.603097 | [
"MIT"
] | BrightsDigi/squidex | backend/src/Squidex.Domain.Apps.Entities.MongoDb/Contents/MongoContentRepository_SnapshotStore.cs | 6,782 | C# |
// GBEmmy
// Copyright (C) 2014 Tim Potze
//
// 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 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.
//
// For more information, please refer to <http://unlicense.org>
namespace GBEmmy.Processor.Opcode.Operation
{
public interface IOperation
{
bool Call(Z80 cpu, Operand operand1, Operand operand2, byte embedded);
}
} | 37.35 | 78 | 0.73494 | [
"Unlicense"
] | ikkentim/GBEmmy | src/GBEmmyOld/Processor/Opcode/Operation/IOperation.cs | 749 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("dropdownTextBoxApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("dropdownTextBoxApp")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请在
//<PropertyGroup> 中的 .csproj 文件中
//设置 <UICulture>CultureYouAreCodingWith</UICulture>。 例如,如果您在源文件中
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(在页面或应用程序资源词典中
// 未找到某个资源的情况下使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(在页面、应用程序或任何主题特定资源词典中
// 未找到某个资源的情况下使用)
)]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 26.553571 | 91 | 0.732347 | [
"Apache-2.0"
] | zollty/CryptoTools | Properties/AssemblyInfo.cs | 2,144 | C# |
using GroupDocs.Metadata.WebForms.Products.Common.Config;
using GroupDocs.Metadata.WebForms.Products.Common.Util.Parser;
using GroupDocs.Metadata.WebForms.Products.Metadata.Util;
using Newtonsoft.Json;
using System;
using System.IO;
namespace GroupDocs.Metadata.WebForms.Products.Metadata.Config
{
/// <summary>
/// MetadataConfiguration
/// </summary>
public class MetadataConfiguration : CommonConfiguration
{
private string filesDirectory = "DocumentSamples/Metadata";
[JsonProperty]
private string defaultDocument = "";
[JsonProperty]
private int preloadPageCount;
[JsonProperty]
private bool htmlMode = true;
[JsonProperty]
private bool cache = true;
/// <summary>
/// Constructor
/// </summary>
public MetadataConfiguration()
{
YamlParser parser = new YamlParser();
dynamic configuration = parser.GetConfiguration("metadata");
ConfigurationValuesGetter valuesGetter = new ConfigurationValuesGetter(configuration);
// get Metadata configuration section from the web.config
filesDirectory = valuesGetter.GetStringPropertyValue("filesDirectory", filesDirectory);
if (!DirectoryUtils.IsFullPath(filesDirectory))
{
filesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filesDirectory);
if (!Directory.Exists(filesDirectory))
{
Directory.CreateDirectory(filesDirectory);
}
}
defaultDocument = valuesGetter.GetStringPropertyValue("defaultDocument", defaultDocument);
preloadPageCount = valuesGetter.GetIntegerPropertyValue("preloadPageCount", preloadPageCount);
htmlMode = valuesGetter.GetBooleanPropertyValue("htmlMode", htmlMode);
cache = valuesGetter.GetBooleanPropertyValue("cache", cache);
browse = valuesGetter.GetBooleanPropertyValue("browse", browse);
upload = valuesGetter.GetBooleanPropertyValue("upload", upload);
}
public void SetFilesDirectory(string filesDirectory)
{
this.filesDirectory = filesDirectory;
}
public string GetFilesDirectory()
{
return filesDirectory;
}
public void SetDefaultDocument(string defaultDocument)
{
this.defaultDocument = defaultDocument;
}
public string GetDefaultDocument()
{
return defaultDocument;
}
public void SetPreloadPageCount(int preloadPageCount)
{
this.preloadPageCount = preloadPageCount;
}
public int GetPreloadPageCount()
{
return preloadPageCount;
}
public void SetIsHtmlMode(bool isHtmlMode)
{
this.htmlMode = isHtmlMode;
}
public bool GetIsHtmlMode()
{
return htmlMode;
}
public void SetCache(bool Cache)
{
this.cache = Cache;
}
public bool GetCache()
{
return cache;
}
public string GetAbsolutePath(string filePath)
{
if (!Path.IsPathRooted(filePath))
{
return Path.Combine(GetFilesDirectory(), filePath);
}
string absolutePath = Path.GetFullPath(filePath);
string fileDirectory = Path.GetFullPath(GetFilesDirectory());
if (!fileDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
fileDirectory += Path.DirectorySeparatorChar;
}
if (!absolutePath.StartsWith(fileDirectory))
{
throw new ArgumentException("Invalid file path");
}
return absolutePath;
}
}
} | 31.432 | 106 | 0.605752 | [
"MIT"
] | groupdocs-metadata/GroupDocs.Metadata-for-.NET | Demos/WebForms/src/Products/Metadata/Config/MetadataConfiguration.cs | 3,931 | C# |
namespace SFA.DAS.ApprenticeCommitments.Configuration
{
public class AzureManagedIdentityApiConfiguration
{
public string Identifier { get; set; }
public string Url { get; set; }
}
}
| 23.555556 | 54 | 0.683962 | [
"MIT"
] | SkillsFundingAgency/das-apim-endpoints | src/SFA.DAS.ApprenticeCommitments/Configuration/AzureManagedIdentityApiConfiguration.cs | 214 | C# |
using System;
using System.Collections.Generic;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace Kinetix.Reporting.TagHandlers {
/// <summary>
/// Utility TagHandler.
/// </summary>
internal static class CustomNodeProcessor {
/// <summary>
/// Nom du tag CustomOpenXml représentant les Fields text.
/// </summary>
private const string FieldTagName = "field";
/// <summary>
/// Nom du tag CustomOpenXml représentant les Fields NewLine.
/// </summary>
private const string FieldNewLine = "fieldNewLine";
/// <summary>
/// Nom du tag CustomOpenXml représentant les Fields Currency.
/// </summary>
private const string FieldCurrencyTagName = "fieldCurrency";
/// <summary>
/// Nom du tag CustomOpenXml représentant les boucles.
/// </summary>
private const string ForTagName = "for";
/// <summary>
/// Nom du tag CustomOpenXml représentant les images.
/// </summary>
private const string ImageTagName = "image";
/// <summary>
/// Nom du tag CustomOpenXml représentant les conditions.
/// </summary>
private const string IfTagName = "if";
/// <summary>
/// Remplacer les éléments trouvés.
/// </summary>
/// <param name="currentPart">OpenXmlPart courant.</param>
/// <param name="currentXmlElement">XmlElement courant.</param>
/// <param name="currentDataSource">Source de données courante.</param>
/// <param name="documentId">Id document en cours.</param>
/// <param name="isXmlData">Si la source en xml.</param>
public static void Process(OpenXmlPart currentPart, CustomXmlElement currentXmlElement, object currentDataSource, Guid documentId, bool isXmlData) {
using (ITagHandler tagHandler = CreateTagHandler(currentPart, currentXmlElement, currentDataSource, documentId, isXmlData)) {
IEnumerable<OpenXmlElement> newElementList = tagHandler.HandleTag();
OpenXmlElement parent = currentXmlElement.Parent;
if (newElementList == null) {
if (currentXmlElement.Parent.GetType() != typeof(Paragraph) && currentXmlElement.Parent.GetType() != typeof(TableRow) && currentXmlElement.Parent.GetType() != typeof(Table) && currentXmlElement.Parent.GetType() != typeof(Body) && currentXmlElement.Parent.GetType() != typeof(CustomXmlRow)) {
Paragraph p = new Paragraph();
if (currentXmlElement.Parent.GetType() == typeof(TableCell)) {
if (currentXmlElement.Descendants<ParagraphProperties>() != null) {
IEnumerator<ParagraphProperties> ppEnum = currentXmlElement.Descendants<ParagraphProperties>().GetEnumerator();
ppEnum.MoveNext();
if (ppEnum.Current != null) {
p.AppendChild<OpenXmlElement>(ppEnum.Current.CloneNode(true));
}
}
}
parent.InsertBefore(p, currentXmlElement);
} else if (parent.GetType() == typeof(TableRow)) {
Paragraph p2 = new Paragraph();
TableCell tc = new TableCell();
if (currentXmlElement.Descendants<ParagraphProperties>() != null) {
IEnumerator<ParagraphProperties> ppEnum = currentXmlElement.Descendants<ParagraphProperties>().GetEnumerator();
ppEnum.MoveNext();
p2.AppendChild<OpenXmlElement>(ppEnum.Current.CloneNode(true));
}
tc.AppendChild<Paragraph>(p2);
parent.InsertBefore(tc, currentXmlElement);
}
} else {
OpenXmlElement lastElement = currentXmlElement;
foreach (OpenXmlElement currentChild in newElementList) {
OpenXmlElement currentChildClone = (OpenXmlElement)currentChild;
parent.InsertAfter(currentChildClone, lastElement);
lastElement = currentChildClone;
}
newElementList = null;
}
currentXmlElement.Remove();
currentXmlElement = null;
}
}
/// <summary>
/// Création du Handler.
/// </summary>
/// <param name="currentPart">OpenXmlPart courant.</param>
/// <param name="currentXmlElement">XmlElement courant.</param>
/// <param name="currentDataSource">Source de données courante.</param>
/// <param name="documentId">Id document en cours.</param>
/// <param name="isXmlData">Si la source en xml.</param>
/// <returns>ITagHandler.</returns>
private static ITagHandler CreateTagHandler(OpenXmlPart currentPart, CustomXmlElement currentXmlElement, object currentDataSource, Guid documentId, bool isXmlData) {
if (currentXmlElement.Element == null) {
throw new NotSupportedException("The property 'Element' of currentXmlElement is null.");
}
switch (currentXmlElement.Element.Value) {
case FieldTagName:
return new FieldHandler(currentPart, currentXmlElement, currentDataSource, documentId, isXmlData);
case FieldNewLine:
return new FieldNewLineHandler(currentPart, currentXmlElement, currentDataSource, documentId, isXmlData);
case FieldCurrencyTagName:
return new FieldCurrencyHandler(currentPart, currentXmlElement, currentDataSource, documentId, isXmlData);
case ForTagName:
return new ForHandler(currentPart, currentXmlElement, currentDataSource, documentId, isXmlData);
case ImageTagName:
return new ImageHandler(currentPart, currentXmlElement, currentDataSource, documentId, isXmlData);
case IfTagName:
return new IfHandler(currentPart, currentXmlElement, currentDataSource, documentId, isXmlData);
default:
throw new ReportException("Tag " + currentXmlElement.Element.Value + " has no defined handler.");
}
}
}
}
| 50.580153 | 311 | 0.590552 | [
"Apache-2.0"
] | KleeGroup/kinetix | Kinetix/Kinetix.Reporting/TagHandlers/CustomNodeProcessor.cs | 6,640 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Reaqtive;
using Reaqtive.Scheduler;
namespace Test.Reaqtive
{
[TestClass]
public class OperatorContextTests
{
[TestMethod]
public void OperatorContext_ArgumentChecking()
{
var ur = new Uri("bing://foo/bar");
using var ph = PhysicalScheduler.Create();
using var sh = new LogicalScheduler(ph);
var tc = new TraceSource("foo");
var ee = new Environment();
#pragma warning disable IDE0034 // Simplify 'default' expression (illustrative of method signature)
Assert.ThrowsException<ArgumentNullException>(() => new OperatorContext(default(Uri), sh, tc, ee));
Assert.ThrowsException<ArgumentNullException>(() => new OperatorContext(ur, default(IScheduler), tc, ee));
#pragma warning restore IDE0034 // Simplify 'default' expression
}
[TestMethod]
public void OperatorContext_Simple()
{
var ur = new Uri("bing://foo/bar");
using var ph = PhysicalScheduler.Create();
using var sh = new LogicalScheduler(ph);
var tc = new TraceSource("foo");
var ee = new Environment();
var ctx = new OperatorContext(ur, sh, tc, ee);
Assert.AreSame(ur, ctx.InstanceId);
Assert.AreSame(sh, ctx.Scheduler);
Assert.AreSame(tc, ctx.TraceSource);
Assert.AreSame(ee, ctx.ExecutionEnvironment);
Assert.IsFalse(ctx.TryGetElement<string>("foo", out var s) && s == null);
}
private sealed class Environment : IExecutionEnvironment
{
public IMultiSubject<TInput, TOutput> GetSubject<TInput, TOutput>(Uri uri)
{
throw new NotImplementedException();
}
public ISubscription GetSubscription(Uri uri)
{
throw new NotImplementedException();
}
}
}
}
| 32.085714 | 118 | 0.617097 | [
"MIT"
] | Botcoin-com/reaqtor | Reaqtive/Core/Tests.Reaqtive.Core/Reaqtive/Operators/OperatorContextTests.cs | 2,248 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace MTP.VueltaAtras {
/*
* El laberinto
* Una matriz bidimensional NxN puede representar un laberinto cuadrado. Cada posición contiene
* un entero no negativo que indica si la casilla es transitable (0) o si no lo es (∞). Las
* casillas (1, 1) y (n, n) corresponden a la entrada y salida del laberinto y siempre son
* transitables.
*
* Dada una matriz con un laberinto, el problema consiste en diseñar un algoritmo que encuentre
* un camino, si existe, para ir de la entrada a la salida.
*
* Por ejemplo, podemos considerar el siguiente laberinto:
* 1 2 3 4 5
* |---|---|---|---|---|
* 1 | E | | | | |
* |---|---|---|---|---|
* 2 | | ∞ | ∞ | ∞ | |
* |---|---|---|---|---|
* 3 | | | | | |
* |---|---|---|---|---|
* 4 | | ∞ | ∞ | ∞ | ∞ |
* |---|---|---|---|---|
* 5 | | | | | S |
* |---|---|---|---|---|
*
* + ¿Cómo se generan los movimientos en el laberinto?
* + ¿Cuál es el camino que va a seleccionar el algoritmo?
*/
public static class Ejercicio307 {
const int I = int.MaxValue; // Infinito
struct Punto {
public Punto(int f, int c) {
this.f = f;
this.c = c;
}
public int f;
public int c;
}
static bool Camino(int[,] mapa, int N, int M, int x, int y,
LinkedList<Punto> r) {
if(0 <= x && x < N && 0 <= y && y < M && mapa[y, x] == 0) {
r.AddLast(new Punto(y, x));
if(x == N - 1 && y == M - 1) {
return true;
} else {
mapa[y, x] = 1;
if(Camino(mapa, N, M, x, y + 1, r)) return true;
if(Camino(mapa, N, M, x + 1, y, r)) return true;
if(Camino(mapa, N, M, x, y - 1, r)) return true;
if(Camino(mapa, N, M, x - 1, y, r)) return true;
mapa[y, x] = 0;
r.RemoveLast();
return false;
}
} else {
return false;
}
}
static Punto[] Camino(int[,] mapa, int N, int M) {
LinkedList<Punto> r = new LinkedList<Punto>();
if(Camino(mapa, N, M, 0, 0, r)) {
return r.ToArray();
} else {
return null;
}
}
static void Mostrar(int[,] mapa, int N, int M) {
for(int j = 0; j < N + 1; j++) {
Console.Write("***");
}
Console.WriteLine();
for(int i = 0; i < M; i++) {
Console.Write("* ");
for(int j = 0; j < N; j++) {
if(mapa[i, j] == I) {
Console.Write("***");
} else {
Console.Write(" ");
}
}
Console.WriteLine("*");
}
for(int j = 0; j < N + 1; j++) {
Console.Write("***");
}
Console.WriteLine("\n");
}
static void GotoXY(int x, int y) {
Console.CursorLeft = x;
Console.CursorTop = y;
}
static void Mostrar(Punto[] r, int Alto) {
int n = 1;
foreach(Punto p in r) {
GotoXY(2 + p.c * 3, 1 + p.f);
if(n < 10) {
Console.Write(n.ToString(" 0"));
} else {
Console.Write(n.ToString("00"));
}
n++;
}
GotoXY(0, Alto + 3);
}
public static void Resolver() {
const int Ancho = 5;
const int Alto = 5;
int[,] mapa =
{
{ 0, 0, 0, 0, 0 },
{ 0, I, I, I, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, I, I, I, I },
{ 0, 0, 0, 0, 0 },
};
Punto[] r = Camino(mapa, Ancho, Alto);
Mostrar(mapa, Ancho, Alto);
Mostrar(r, Alto);
}
}
}
| 32.518797 | 99 | 0.371098 | [
"MIT"
] | gorkinovich/MTP | MTP/VueltaAtras/Ejercicio307.cs | 4,349 | C# |
// Copyright (c) r12f. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Confidence.Utilities;
namespace Confidence
{
/// <summary>
/// Extensions for validating is all child items in collection matches predicate.
/// </summary>
public static class CollectionAllValidationExtensions
{
/// <summary>
/// Validate if all child items of this target item will pass with predicate.
/// </summary>
/// <typeparam name="TCollection">Target type.</typeparam>
/// <typeparam name="TItem">Child item type.</typeparam>
/// <param name="target">Validate target.</param>
/// <param name="predicate">Predicate for testing child items.</param>
/// <param name="getErrorMessage">Custom error message.</param>
/// <returns>The same validate target as passed in.</returns>
[ValidationMethod(ValidationTargetTypes.Collection, ValidationMethodTypes.Children)]
[DebuggerStepThrough]
public static ValidateTarget<TCollection> All<TCollection, TItem>([ValidatedNotNull] this ValidateTarget<TCollection> target, Func<TItem, bool> predicate, Func<string> getErrorMessage = null)
where TCollection : IEnumerable<TItem>
{
bool passedPredicate = true;
if (target.Value != null)
{
foreach (var item in target.Value)
{
if (!predicate.Invoke(item))
{
passedPredicate = false;
break;
}
}
}
if (!passedPredicate)
{
ExceptionFactory.ThrowException(target.Traits.GenericFailureExceptionType, getErrorMessage != null ? getErrorMessage.Invoke() : ErrorMessageFactory.ShouldAllBe(target));
}
return target;
}
/// <summary>
/// Validate if all child items of this target item will pass with predicate.
/// </summary>
/// <typeparam name="TCollection">Target type.</typeparam>
/// <param name="target">Validate target.</param>
/// <param name="predicate">Predicate for testing child items.</param>
/// <param name="getErrorMessage">Custom error message.</param>
/// <returns>The same validate target as passed in.</returns>
[ValidationMethod(ValidationTargetTypes.Collection, ValidationMethodTypes.Children)]
[DebuggerStepThrough]
public static ValidateTarget<TCollection> UntypedAll<TCollection>([ValidatedNotNull] this ValidateTarget<TCollection> target, Func<object, bool> predicate, Func<string> getErrorMessage = null)
where TCollection : IEnumerable
{
bool passedPredicate = true;
if (target.Value != null)
{
foreach (var item in target.Value)
{
if (!predicate.Invoke(item))
{
passedPredicate = false;
break;
}
}
}
if (!passedPredicate)
{
ExceptionFactory.ThrowException(target.Traits.GenericFailureExceptionType, getErrorMessage != null ? getErrorMessage.Invoke() : ErrorMessageFactory.ShouldAllBe(target));
}
return target;
}
}
} | 41.674419 | 200 | 0.597377 | [
"MIT"
] | r12f/Confidence | Confidence/Validations/Collection/CollectionAllValidationExtensions.cs | 3,586 | C# |
// Copyright (c) János Janka. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Mvc;
namespace Partnerinfo.Controllers
{
/// <summary>
/// Provides methods that respond to HTTP requests that are made to an ASP.NET MVC Web site.
/// </summary>
public sealed class HomeController : Controller
{
/// <summary>
/// Creates a ViewResult object that renders a view to the response.
/// </summary>
public IActionResult Index() => View();
}
} | 33.944444 | 111 | 0.661211 | [
"Apache-2.0"
] | janosjanka/Partnerinfo | src/Partnerinfo.Web.Site/Controllers/HomeController.cs | 614 | 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 greengrass-2017-06-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Greengrass.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Greengrass.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeviceDefinitionVersion Marshaller
/// </summary>
public class DeviceDefinitionVersionMarshaller : IRequestMarshaller<DeviceDefinitionVersion, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(DeviceDefinitionVersion requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetDevices())
{
context.Writer.WritePropertyName("Devices");
context.Writer.WriteArrayStart();
foreach(var requestObjectDevicesListValue in requestObject.Devices)
{
context.Writer.WriteObjectStart();
var marshaller = DeviceMarshaller.Instance;
marshaller.Marshall(requestObjectDevicesListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static DeviceDefinitionVersionMarshaller Instance = new DeviceDefinitionVersionMarshaller();
}
} | 35.694444 | 121 | 0.649416 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Greengrass/Generated/Model/Internal/MarshallTransformations/DeviceDefinitionVersionMarshaller.cs | 2,570 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/imapi2.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='IWriteSpeedDescriptor.xml' path='doc/member[@name="IWriteSpeedDescriptor"]/*' />
[Guid("27354144-7F64-5B0F-8F00-5D77AFBE261E")]
[NativeTypeName("struct IWriteSpeedDescriptor : IDispatch")]
[NativeInheritance("IDispatch")]
public unsafe partial struct IWriteSpeedDescriptor : IWriteSpeedDescriptor.Interface
{
public void** lpVtbl;
/// <inheritdoc cref="IUnknown.QueryInterface" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, Guid*, void**, int>)(lpVtbl[0]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
/// <inheritdoc cref="IUnknown.AddRef" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, uint>)(lpVtbl[1]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IUnknown.Release" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, uint>)(lpVtbl[2]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IDispatch.GetTypeInfoCount" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public HRESULT GetTypeInfoCount(uint* pctinfo)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, uint*, int>)(lpVtbl[3]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), pctinfo);
}
/// <inheritdoc cref="IDispatch.GetTypeInfo" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
public HRESULT GetTypeInfo(uint iTInfo, [NativeTypeName("LCID")] uint lcid, ITypeInfo** ppTInfo)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, uint, uint, ITypeInfo**, int>)(lpVtbl[4]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), iTInfo, lcid, ppTInfo);
}
/// <inheritdoc cref="IDispatch.GetIDsOfNames" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public HRESULT GetIDsOfNames([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LPOLESTR *")] ushort** rgszNames, uint cNames, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("DISPID *")] int* rgDispId)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, Guid*, ushort**, uint, uint, int*, int>)(lpVtbl[5]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), riid, rgszNames, cNames, lcid, rgDispId);
}
/// <inheritdoc cref="IDispatch.Invoke" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
public HRESULT Invoke([NativeTypeName("DISPID")] int dispIdMember, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("WORD")] ushort wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO* pExcepInfo, uint* puArgErr)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int>)(lpVtbl[6]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
/// <include file='IWriteSpeedDescriptor.xml' path='doc/member[@name="IWriteSpeedDescriptor.get_MediaType"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
public HRESULT get_MediaType(IMAPI_MEDIA_PHYSICAL_TYPE* value)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, IMAPI_MEDIA_PHYSICAL_TYPE*, int>)(lpVtbl[7]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), value);
}
/// <include file='IWriteSpeedDescriptor.xml' path='doc/member[@name="IWriteSpeedDescriptor.get_RotationTypeIsPureCAV"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
public HRESULT get_RotationTypeIsPureCAV([NativeTypeName("VARIANT_BOOL *")] short* value)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, short*, int>)(lpVtbl[8]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), value);
}
/// <include file='IWriteSpeedDescriptor.xml' path='doc/member[@name="IWriteSpeedDescriptor.get_WriteSpeed"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(9)]
public HRESULT get_WriteSpeed([NativeTypeName("LONG *")] int* value)
{
return ((delegate* unmanaged<IWriteSpeedDescriptor*, int*, int>)(lpVtbl[9]))((IWriteSpeedDescriptor*)Unsafe.AsPointer(ref this), value);
}
public interface Interface : IDispatch.Interface
{
[VtblIndex(7)]
HRESULT get_MediaType(IMAPI_MEDIA_PHYSICAL_TYPE* value);
[VtblIndex(8)]
HRESULT get_RotationTypeIsPureCAV([NativeTypeName("VARIANT_BOOL *")] short* value);
[VtblIndex(9)]
HRESULT get_WriteSpeed([NativeTypeName("LONG *")] int* value);
}
public partial struct Vtbl<TSelf>
where TSelf : unmanaged, Interface
{
[NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> AddRef;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> Release;
[NativeTypeName("HRESULT (UINT *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint*, int> GetTypeInfoCount;
[NativeTypeName("HRESULT (UINT, LCID, ITypeInfo **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint, uint, ITypeInfo**, int> GetTypeInfo;
[NativeTypeName("HRESULT (const IID &, LPOLESTR *, UINT, LCID, DISPID *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, ushort**, uint, uint, int*, int> GetIDsOfNames;
[NativeTypeName("HRESULT (DISPID, const IID &, LCID, WORD, DISPPARAMS *, VARIANT *, EXCEPINFO *, UINT *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int> Invoke;
[NativeTypeName("HRESULT (IMAPI_MEDIA_PHYSICAL_TYPE *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IMAPI_MEDIA_PHYSICAL_TYPE*, int> get_MediaType;
[NativeTypeName("HRESULT (VARIANT_BOOL *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, short*, int> get_RotationTypeIsPureCAV;
[NativeTypeName("HRESULT (LONG *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int*, int> get_WriteSpeed;
}
}
| 49.439189 | 280 | 0.703704 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/imapi2/IWriteSpeedDescriptor.cs | 7,319 | C# |
using System;
using System.Threading;
using Meadow;
namespace PwmLed_Sample
{
class MainClass
{
static IApp app;
public static void Main(string[] args)
{
app = new PwmLedApp();
Thread.Sleep(Timeout.Infinite);
}
}
}
| 15.888889 | 46 | 0.566434 | [
"Apache-2.0"
] | patridge/Meadow.Foundation | Source/Samples/Leds/PwmLed_Sample/Program.cs | 288 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.LocationService;
using Amazon.LocationService.Model;
namespace Amazon.PowerShell.Cmdlets.LOC
{
/// <summary>
/// Deletes a map resource from your AWS account.
///
/// <note><para>
/// This action deletes the resource permanently. You cannot undo this action. If the
/// map is being used in an application, the map may not render.
/// </para></note>
/// </summary>
[Cmdlet("Remove", "LOCMap", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]
[OutputType("None")]
[AWSCmdlet("Calls the Amazon Location Service DeleteMap API operation.", Operation = new[] {"DeleteMap"}, SelectReturnType = typeof(Amazon.LocationService.Model.DeleteMapResponse))]
[AWSCmdletOutput("None or Amazon.LocationService.Model.DeleteMapResponse",
"This cmdlet does not generate any output." +
"The service response (type Amazon.LocationService.Model.DeleteMapResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class RemoveLOCMapCmdlet : AmazonLocationServiceClientCmdlet, IExecutor
{
#region Parameter MapName
/// <summary>
/// <para>
/// <para>The name of the map resource to be deleted.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String MapName { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.LocationService.Model.DeleteMapResponse).
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the MapName parameter.
/// The -PassThru parameter is deprecated, use -Select '^MapName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^MapName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.MapName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-LOCMap (DeleteMap)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.LocationService.Model.DeleteMapResponse, RemoveLOCMapCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.MapName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.MapName = this.MapName;
#if MODULAR
if (this.MapName == null && ParameterWasBound(nameof(this.MapName)))
{
WriteWarning("You are passing $null as a value for parameter MapName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.LocationService.Model.DeleteMapRequest();
if (cmdletContext.MapName != null)
{
request.MapName = cmdletContext.MapName;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.LocationService.Model.DeleteMapResponse CallAWSServiceOperation(IAmazonLocationService client, Amazon.LocationService.Model.DeleteMapRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Location Service", "DeleteMap");
try
{
#if DESKTOP
return client.DeleteMap(request);
#elif CORECLR
return client.DeleteMapAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String MapName { get; set; }
public System.Func<Amazon.LocationService.Model.DeleteMapResponse, RemoveLOCMapCmdlet, object> Select { get; set; } =
(response, cmdlet) => null;
}
}
}
| 43.713636 | 278 | 0.604658 | [
"Apache-2.0"
] | hevaldez07/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/LocationService/Basic/Remove-LOCMap-Cmdlet.cs | 9,617 | C# |
using System;
using System.Management.Automation;
namespace office365.PORTAL.Core
{
[Cmdlet("Remove", "PORTALDomain")]
public class RemovePORTALDomain : PSCmdlet
{
[Parameter(Position=1)]
public string Message { get; set; } = string.Empty;
protected override void EndProcessing()
{
this.WriteObject($"not implemented yet. :(");
base.EndProcessing();
}
}
}
| 26.55 | 64 | 0.504708 | [
"MIT"
] | MartinGudel/PowerShell-PORTAL-module | office365.MSOnline.Core/RemoveMsolDomain.cs | 533 | C# |
//=====================================================================
// http://www.cocoa-mono.org
//
// Copyright (c) 2011 Kenneth J. Pouncey
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreVideo;
using MonoMac.OpenGL;
namespace GLSLShader
{
public partial class MyOpenGLView : MonoMac.AppKit.NSView
{
NSOpenGLContext openGLContext;
NSOpenGLPixelFormat pixelFormat;
MainWindowController controller;
CVDisplayLink displayLink;
NSObject notificationProxy;
[Export("initWithFrame:")]
public MyOpenGLView (RectangleF frame) : this(frame, null)
{
}
public MyOpenGLView (RectangleF frame,NSOpenGLContext context) : base(frame)
{
var attribs = new object [] {
NSOpenGLPixelFormatAttribute.Accelerated,
NSOpenGLPixelFormatAttribute.NoRecovery,
NSOpenGLPixelFormatAttribute.DoubleBuffer,
NSOpenGLPixelFormatAttribute.ColorSize, 24,
NSOpenGLPixelFormatAttribute.DepthSize, 16 };
pixelFormat = new NSOpenGLPixelFormat (attribs);
if (pixelFormat == null)
Console.WriteLine ("No OpenGL pixel format");
// NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead
openGLContext = new NSOpenGLContext (pixelFormat, context);
openGLContext.MakeCurrentContext ();
// Synchronize buffer swaps with vertical refresh rate
openGLContext.SwapInterval = true;
// Initialize our newly created view.
InitGL ();
SetupDisplayLink ();
// Look for changes in view size
// Note, -reshape will not be called automatically on size changes because NSView does not export it to override
notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.NSViewGlobalFrameDidChangeNotification, HandleReshape);
}
public override void DrawRect (RectangleF dirtyRect)
{
// Ignore if the display link is still running
if (!displayLink.IsRunning && controller != null)
DrawView ();
}
public override bool AcceptsFirstResponder ()
{
// We want this view to be able to receive key events
return true;
}
public override void LockFocus ()
{
base.LockFocus ();
if (openGLContext.View != this)
openGLContext.View = this;
}
public override void KeyDown (NSEvent theEvent)
{
controller.KeyDown (theEvent);
}
public override void MouseDown (NSEvent theEvent)
{
controller.MouseDown (theEvent);
}
// All Setup For OpenGL Goes Here
public bool InitGL ()
{
// Enables Smooth Shading
GL.ShadeModel (ShadingModel.Smooth);
// Set background color to black
GL.ClearColor (Color.Black);
// Setup Depth Testing
// Depth Buffer setup
GL.ClearDepth (1.0);
// Enables Depth testing
GL.Enable (EnableCap.DepthTest);
// The type of depth testing to do
GL.DepthFunc (DepthFunction.Lequal);
// Really Nice Perspective Calculations
GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
return true;
}
private void DrawView ()
{
// This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop)
// Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Make sure we draw to the right context
openGLContext.MakeCurrentContext ();
// Delegate to the scene object for rendering
controller.Scene.DrawGLScene ();
openGLContext.FlushBuffer ();
openGLContext.CGLContext.Unlock ();
}
private void SetupDisplayLink ()
{
// Create a display link capable of being used with all active displays
displayLink = new CVDisplayLink ();
// Set the renderer output callback function
displayLink.SetOutputCallback (MyDisplayLinkOutputCallback);
// Set the display link for the current renderer
CGLContext cglContext = openGLContext.CGLContext;
CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat;
displayLink.SetCurrentDisplay (cglContext, cglPixelFormat);
}
public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut)
{
CVReturn result = GetFrameForTime (inOutputTime);
return result;
}
private CVReturn GetFrameForTime (CVTimeStamp outputTime)
{
// There is no autorelease pool when this method is called because it will be called from a background thread
// It's important to create one or you will leak objects
using (NSAutoreleasePool pool = new NSAutoreleasePool ()) {
// Update the animation
BeginInvokeOnMainThread (DrawView);
}
return CVReturn.Success;
}
public NSOpenGLContext OpenGLContext {
get { return openGLContext; }
}
public NSOpenGLPixelFormat PixelFormat {
get { return pixelFormat; }
}
public MainWindowController MainController {
set { controller = value; }
}
public void UpdateView ()
{
// This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Delegate to the scene object to update for a change in the view size
controller.Scene.ResizeGLScene (Bounds);
openGLContext.Update ();
openGLContext.CGLContext.Unlock ();
}
private void HandleReshape (NSNotification note)
{
UpdateView ();
}
public void StartAnimation ()
{
if (displayLink != null && !displayLink.IsRunning)
displayLink.Start ();
}
public void StopAnimation ()
{
if (displayLink != null && displayLink.IsRunning)
displayLink.Stop ();
}
// Clean up the notifications
public void DeAllocate ()
{
displayLink.Stop ();
displayLink.SetOutputCallback (null);
NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy);
}
[Export("toggleFullScreen:")]
public void toggleFullScreen (NSObject sender)
{
controller.toggleFullScreen (sender);
}
}
}
| 29.375 | 177 | 0.727111 | [
"MIT"
] | Devolutions/monomac | samples/GLSLShader/MyOpenGLView.cs | 7,285 | 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.
namespace System.Windows.Forms
{
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates"]/*' />
[
Flags,
System.Runtime.InteropServices.ComVisible(true)
]
public enum DataGridViewElementStates
{
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.None"]/*' />
None = 0x0000,
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.Displayed"]/*' />
Displayed = 0x0001,
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.Frozen"]/*' />
Frozen = 0x0002,
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.ReadOnly"]/*' />
ReadOnly = 0x0004,
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.Resizable"]/*' />
Resizable = 0x0008,
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.ResizableSet"]/*' />
ResizableSet = 0x0010,
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.Selected"]/*' />
Selected = 0x0020,
/// <include file='doc\DataGridViewElementStates.uex' path='docs/doc[@for="DataGridViewElementStates.Visible"]/*' />
Visible = 0x0040
}
}
| 55.21875 | 129 | 0.661007 | [
"MIT"
] | OliaG/winforms | src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewElementStates.cs | 1,767 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Diagnostics
{
using Microsoft.Azure.Cosmos.Query.Core.Metrics;
using static Microsoft.Azure.Cosmos.Diagnostics.BackendMetricsExtractor;
/// <summary>
/// Extracts the aggregated <see cref="BackendMetrics"/> from a <see cref="CosmosDiagnostics"/>.
/// </summary>
internal sealed class BackendMetricsExtractor : CosmosDiagnosticsInternalVisitor<(ParseFailureReason, BackendMetrics)>
{
public static readonly BackendMetricsExtractor Singleton = new BackendMetricsExtractor();
private static readonly (ParseFailureReason, BackendMetrics) MetricsNotFound = (ParseFailureReason.MetricsNotFound, default);
private BackendMetricsExtractor()
{
// Private default constructor.
}
public override (ParseFailureReason, BackendMetrics) Visit(PointOperationStatistics pointOperationStatistics)
{
return BackendMetricsExtractor.MetricsNotFound;
}
public override (ParseFailureReason, BackendMetrics) Visit(CosmosDiagnosticsContext cosmosDiagnosticsContext)
{
BackendMetrics.Accumulator accumulator = default;
bool metricsFound = false;
foreach (CosmosDiagnosticsInternal cosmosDiagnostics in cosmosDiagnosticsContext)
{
(ParseFailureReason parseFailureReason, BackendMetrics backendMetrics) = cosmosDiagnostics.Accept(this);
switch (parseFailureReason)
{
case ParseFailureReason.None:
metricsFound = true;
accumulator = accumulator.Accumulate(backendMetrics);
break;
case ParseFailureReason.MalformedString:
return (parseFailureReason, default);
default:
break;
}
}
(ParseFailureReason parseFailureReason, BackendMetrics backendMetrics) failureReasonAndMetrics;
if (metricsFound)
{
failureReasonAndMetrics = (ParseFailureReason.None, BackendMetrics.Accumulator.ToBackendMetrics(accumulator));
}
else
{
failureReasonAndMetrics = (ParseFailureReason.MetricsNotFound, default);
}
return failureReasonAndMetrics;
}
public override (ParseFailureReason, BackendMetrics) Visit(CosmosDiagnosticScope cosmosDiagnosticScope)
{
return BackendMetricsExtractor.MetricsNotFound;
}
public override (ParseFailureReason, BackendMetrics) Visit(QueryPageDiagnostics queryPageDiagnostics)
{
if (!BackendMetrics.TryParseFromDelimitedString(queryPageDiagnostics.QueryMetricText, out BackendMetrics backendMetrics))
{
return (ParseFailureReason.MalformedString, default);
}
return (ParseFailureReason.None, backendMetrics);
}
public override (ParseFailureReason, BackendMetrics) Visit(AddressResolutionStatistics addressResolutionStatistics)
{
return BackendMetricsExtractor.MetricsNotFound;
}
public override (ParseFailureReason, BackendMetrics) Visit(StoreResponseStatistics storeResponseStatistics)
{
return BackendMetricsExtractor.MetricsNotFound;
}
public override (ParseFailureReason, BackendMetrics) Visit(CosmosClientSideRequestStatistics clientSideRequestStatistics)
{
return BackendMetricsExtractor.MetricsNotFound;
}
public enum ParseFailureReason
{
None,
MetricsNotFound,
MalformedString
}
}
}
| 39.356436 | 133 | 0.633962 | [
"MIT"
] | cgelon/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/Diagnostics/BackendMetricsExtractor.cs | 3,977 | C# |
namespace Buildalyzer.Build;
public static class Settings
{
public const string IsBuildServer = nameof(IsBuildServer);
} | 20.833333 | 62 | 0.792 | [
"MIT"
] | AdaskoTheBeAsT/Buildalyzer | build/Buildalyzer.Build/Settings.cs | 125 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.IO;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
///<summary>
/// This is the object used by Runspace,pipeline,host to send data
/// to remote end. Transport layer owns breaking this into fragments
/// and sending to other end
///</summary>
internal class RemoteDataObject<T>
{
#region Private Members
private const int destinationOffset = 0;
private const int dataTypeOffset = 4;
private const int rsPoolIdOffset = 8;
private const int psIdOffset = 24;
private const int headerLength = 4 + 4 + 16 + 16;
private const int SessionMask = 0x00010000;
private const int RunspacePoolMask = 0x00021000;
private const int PowerShellMask = 0x00041000;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructs a RemoteDataObject from its
/// individual components.
/// </summary>
/// <param name="destination">
/// Destination this object is going to.
/// </param>
/// <param name="dataType">
/// Payload type this object represents.
/// </param>
/// <param name="runspacePoolId">
/// Runspace id this object belongs to.
/// </param>
/// <param name="powerShellId">
/// PowerShell (pipeline) id this object belongs to.
/// This may be null if the payload belongs to runspace.
/// </param>
/// <param name="data">
/// Actual payload.
/// </param>
protected RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
Destination = destination;
DataType = dataType;
RunspacePoolId = runspacePoolId;
PowerShellId = powerShellId;
Data = data;
}
#endregion Constructors
#region Properties
internal RemotingDestination Destination { get; }
/// <summary>
/// Gets the target (Runspace / Pipeline / Powershell / Host)
/// the payload belongs to.
/// </summary>
internal RemotingTargetInterface TargetInterface
{
get
{
int dt = (int)DataType;
// get the most used ones in the top.
if ((dt & PowerShellMask) == PowerShellMask)
{
return RemotingTargetInterface.PowerShell;
}
if ((dt & RunspacePoolMask) == RunspacePoolMask)
{
return RemotingTargetInterface.RunspacePool;
}
if ((dt & SessionMask) == SessionMask)
{
return RemotingTargetInterface.Session;
}
return RemotingTargetInterface.InvalidTargetInterface;
}
}
internal RemotingDataType DataType { get; }
internal Guid RunspacePoolId { get; }
internal Guid PowerShellId { get; }
internal T Data { get; }
#endregion Properties
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, data);
}
/// <summary>
/// Creates a RemoteDataObject by deserializing <paramref name="data"/>.
/// </summary>
/// <param name="serializedDataStream"></param>
/// <param name="defragmentor">
/// Defragmentor used to deserialize an object.
/// </param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(Stream serializedDataStream, Fragmentor defragmentor)
{
Dbg.Assert(serializedDataStream != null, "cannot construct a RemoteDataObject from null data");
Dbg.Assert(defragmentor != null, "defragmentor cannot be null.");
if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength)
{
PSRemotingTransportException e =
new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject,
RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject,
headerLength + FragmentedRemoteObject.HeaderLength);
throw e;
}
RemotingDestination destination = (RemotingDestination)DeserializeUInt(serializedDataStream);
RemotingDataType dataType = (RemotingDataType)DeserializeUInt(serializedDataStream);
Guid runspacePoolId = DeserializeGuid(serializedDataStream);
Guid powerShellId = DeserializeGuid(serializedDataStream);
object actualData = null;
if ((serializedDataStream.Length - headerLength) > 0)
{
actualData = defragmentor.DeserializeToPSObject(serializedDataStream);
}
T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T),
System.Globalization.CultureInfo.CurrentCulture);
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, deserializedObject);
}
#region Serialize / Deserialize
/// <summary>
/// Serializes the object into the stream specified. The serialization mechanism uses
/// UTF8 encoding to encode data.
/// </summary>
/// <param name="streamToWriteTo"></param>
/// <param name="fragmentor">
/// fragmentor used to serialize and fragment the object.
/// </param>
internal virtual void Serialize(Stream streamToWriteTo, Fragmentor fragmentor)
{
Dbg.Assert(streamToWriteTo != null, "Stream to write to cannot be null.");
Dbg.Assert(fragmentor != null, "Fragmentor cannot be null.");
SerializeHeader(streamToWriteTo);
if (Data != null)
{
fragmentor.SerializeToBytes(Data, streamToWriteTo);
}
return;
}
/// <summary>
/// Serializes only the header portion of the object. ie., runspaceId,
/// powerShellId, destination and dataType.
/// </summary>
/// <param name="streamToWriteTo">
/// place where the serialized data is stored into.
/// </param>
/// <returns></returns>
private void SerializeHeader(Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
// Serialize destination
SerializeUInt((uint)Destination, streamToWriteTo);
// Serialize data type
SerializeUInt((uint)DataType, streamToWriteTo);
// Serialize runspace guid
SerializeGuid(RunspacePoolId, streamToWriteTo);
// Serialize powershell guid
SerializeGuid(PowerShellId, streamToWriteTo);
return;
}
private void SerializeUInt(uint data, Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
byte[] result = new byte[4]; // size of int
int idx = 0;
result[idx++] = (byte)(data & 0xFF);
result[idx++] = (byte)((data >> 8) & 0xFF);
result[idx++] = (byte)((data >> (2 * 8)) & 0xFF);
result[idx++] = (byte)((data >> (3 * 8)) & 0xFF);
streamToWriteTo.Write(result, 0, 4);
}
private static uint DeserializeUInt(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 4, "Not enough data to get Int.");
uint result = 0;
result |= (((uint)(serializedDataStream.ReadByte())) & 0xFF);
result |= (((uint)(serializedDataStream.ReadByte() << 8)) & 0xFF00);
result |= (((uint)(serializedDataStream.ReadByte() << (2 * 8))) & 0xFF0000);
result |= (((uint)(serializedDataStream.ReadByte() << (3 * 8))) & 0xFF000000);
return result;
}
private void SerializeGuid(Guid guid, Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
byte[] guidArray = guid.ToByteArray();
streamToWriteTo.Write(guidArray, 0, guidArray.Length);
}
private static Guid DeserializeGuid(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 16, "Not enough data to get Guid.");
byte[] guidarray = new byte[16]; // Size of GUID.
for (int idx = 0; idx < 16; idx++)
{
guidarray[idx] = (byte)serializedDataStream.ReadByte();
}
return new Guid(guidarray);
}
#endregion
}
internal class RemoteDataObject : RemoteDataObject<object>
{
#region Constructors / Factory
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
private RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data) : base(destination, dataType, runspacePoolId, powerShellId, data)
{
}
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static new RemoteDataObject CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data)
{
return new RemoteDataObject(destination, dataType, runspacePoolId,
powerShellId, data);
}
#endregion Constructors
}
}
| 35.462783 | 116 | 0.5762 | [
"MIT"
] | DCtheGeek/PowerShell | src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs | 10,958 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IMethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IImportedDeviceIdentityImportDeviceIdentityListRequest.
/// </summary>
public partial interface IImportedDeviceIdentityImportDeviceIdentityListRequest : IBaseRequest
{
/// <summary>
/// Gets the request body.
/// </summary>
ImportedDeviceIdentityImportDeviceIdentityListRequestBody RequestBody { get; }
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<IImportedDeviceIdentityImportDeviceIdentityListCollectionPage> PostAsync(
CancellationToken cancellationToken = default);
/// <summary>
/// Issues the POST request and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse"/> object of the request</returns>
System.Threading.Tasks.Task<GraphResponse<ImportedDeviceIdentityImportDeviceIdentityListCollectionResponse>> PostResponseAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IImportedDeviceIdentityImportDeviceIdentityListRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IImportedDeviceIdentityImportDeviceIdentityListRequest Select(string value);
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
IImportedDeviceIdentityImportDeviceIdentityListRequest Top(int value);
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
IImportedDeviceIdentityImportDeviceIdentityListRequest Filter(string value);
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
IImportedDeviceIdentityImportDeviceIdentityListRequest Skip(int value);
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
IImportedDeviceIdentityImportDeviceIdentityListRequest OrderBy(string value);
}
}
| 42.505618 | 182 | 0.630981 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IImportedDeviceIdentityImportDeviceIdentityListRequest.cs | 3,783 | C# |
// <copyright file="IUmbracoToDataTransferObjectProvider{T}.cs" company="Logikfabrik">
// Copyright (c) 2015 anton(at)logikfabrik.se. Licensed under the MIT license.
// </copyright>
namespace Logikfabrik.Umbraco.Jet.Social
{
/// <summary>
/// The <see cref="IUmbracoToDataTransferObjectProvider{T}" /> interface.
/// </summary>
/// <typeparam name="T">The data transfer object type.</typeparam>
public interface IUmbracoToDataTransferObjectProvider<T> : IDataTransferObjectProvider<T>
where T : DataTransferObject
{
/// <summary>
/// Gets the data transfer object with the specified Umbraco identifier.
/// </summary>
/// <param name="id">The Umbraco identifier.</param>
/// <returns>The data transfer object with the specified Umbraco identifier.</returns>
T GetByUmbracoId(int id);
}
}
| 39.818182 | 94 | 0.676941 | [
"MIT"
] | logikfabrik/uJetSocial | src/Logikfabrik.Umbraco.Jet.Social/IUmbracoToDataTransferObjectProvider{T}.cs | 878 | C# |
// Copyright (c) 2021 Salim Mayaleh. All Rights Reserved
// Licensed under the BSD-3-Clause License
// Generated at 08.11.2021 21:25:55 by RaynetApiDocToDotnet.ApiDocParser, created by Salim Mayaleh.
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Maya.Raynet.Crm.Request.Get
{
public class BusinessCase : GetRequest
{
protected override List<string> Actions { get; set; } = new List<string>();
public BusinessCase(long businessCaseId)
{
Actions.Add("businessCase");
Actions.Add(businessCaseId.ToString());
}
public new async Task<Model.DataResult<Response.Get.BusinessCase>> ExecuteAsync(ApiClient apiClient)
{
return await base.ExecuteAsync<Response.Get.BusinessCase>(apiClient);
}
}
}
| 32.88 | 108 | 0.684915 | [
"BSD-3-Clause"
] | mayaleh/Maya.Raynet.Crm | src/Maya.Raynet.Crm/Request/Get/BusinessCase.cs | 822 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.AnalysisServices.V20170801Beta
{
public static class GetServerDetails
{
/// <summary>
/// Represents an instance of an Analysis Services resource.
/// </summary>
public static Task<GetServerDetailsResult> InvokeAsync(GetServerDetailsArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetServerDetailsResult>("azure-nextgen:analysisservices/v20170801beta:getServerDetails", args ?? new GetServerDetailsArgs(), options.WithVersion());
}
public sealed class GetServerDetailsArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the Azure Resource group of which a given Analysis Services server is part. This name must be at least 1 character in length, and no more than 90.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the Analysis Services server. It must be a minimum of 3 characters, and a maximum of 63.
/// </summary>
[Input("serverName", required: true)]
public string ServerName { get; set; } = null!;
public GetServerDetailsArgs()
{
}
}
[OutputType]
public sealed class GetServerDetailsResult
{
/// <summary>
/// A collection of AS server administrators
/// </summary>
public readonly Outputs.ServerAdministratorsResponse? AsAdministrators;
/// <summary>
/// The SAS container URI to the backup container.
/// </summary>
public readonly string? BackupBlobContainerUri;
/// <summary>
/// The gateway details configured for the AS server.
/// </summary>
public readonly Outputs.GatewayDetailsResponse? GatewayDetails;
/// <summary>
/// An identifier that represents the Analysis Services resource.
/// </summary>
public readonly string Id;
/// <summary>
/// The firewall settings for the AS server.
/// </summary>
public readonly Outputs.IPv4FirewallSettingsResponse? IpV4FirewallSettings;
/// <summary>
/// Location of the Analysis Services resource.
/// </summary>
public readonly string Location;
/// <summary>
/// The managed mode of the server (0 = not managed, 1 = managed).
/// </summary>
public readonly int? ManagedMode;
/// <summary>
/// The name of the Analysis Services resource.
/// </summary>
public readonly string Name;
/// <summary>
/// The current deployment state of Analysis Services resource. The provisioningState is to indicate states for resource provisioning.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// How the read-write server's participation in the query pool is controlled.<br/>It can have the following values: <ul><li>readOnly - indicates that the read-write server is intended not to participate in query operations</li><li>all - indicates that the read-write server can participate in query operations</li></ul>Specifying readOnly when capacity is 1 results in error.
/// </summary>
public readonly string? QuerypoolConnectionMode;
/// <summary>
/// The full name of the Analysis Services resource.
/// </summary>
public readonly string ServerFullName;
/// <summary>
/// The server monitor mode for AS server
/// </summary>
public readonly int? ServerMonitorMode;
/// <summary>
/// The SKU of the Analysis Services resource.
/// </summary>
public readonly Outputs.ResourceSkuResponse Sku;
/// <summary>
/// The current state of Analysis Services resource. The state is to indicate more states outside of resource provisioning.
/// </summary>
public readonly string State;
/// <summary>
/// Key-value pairs of additional resource provisioning properties.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// The type of the Analysis Services resource.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetServerDetailsResult(
Outputs.ServerAdministratorsResponse? asAdministrators,
string? backupBlobContainerUri,
Outputs.GatewayDetailsResponse? gatewayDetails,
string id,
Outputs.IPv4FirewallSettingsResponse? ipV4FirewallSettings,
string location,
int? managedMode,
string name,
string provisioningState,
string? querypoolConnectionMode,
string serverFullName,
int? serverMonitorMode,
Outputs.ResourceSkuResponse sku,
string state,
ImmutableDictionary<string, string>? tags,
string type)
{
AsAdministrators = asAdministrators;
BackupBlobContainerUri = backupBlobContainerUri;
GatewayDetails = gatewayDetails;
Id = id;
IpV4FirewallSettings = ipV4FirewallSettings;
Location = location;
ManagedMode = managedMode;
Name = name;
ProvisioningState = provisioningState;
QuerypoolConnectionMode = querypoolConnectionMode;
ServerFullName = serverFullName;
ServerMonitorMode = serverMonitorMode;
Sku = sku;
State = state;
Tags = tags;
Type = type;
}
}
}
| 37.546012 | 426 | 0.626634 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/AnalysisServices/V20170801Beta/GetServerDetails.cs | 6,120 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiByValue(fqn: "aws.Wafv2RuleGroupRuleStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchMethod")]
public class Wafv2RuleGroupRuleStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchMethod : aws.IWafv2RuleGroupRuleStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchMethod
{
}
}
| 41.25 | 243 | 0.882828 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/Wafv2RuleGroupRuleStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchMethod.cs | 495 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using UIToolbox;
namespace ExampleApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkGroupBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (CheckBox)sender;
if(checkBox.Checked)
Trace.WriteLine("checkGroupBox1 was checked");
else
Trace.WriteLine("checkGroupBox1 was unchecked");
}
}
} | 19.689655 | 72 | 0.751313 | [
"MIT"
] | chromhelm/the-dot-factory | CheckGroupBoxAndRadioGroupBox_1_1/CheckGroupBox/ExampleApplication/Form1.cs | 571 | C# |
using System.Runtime.Serialization;
namespace Trakt.Api.DataContracts
{
[DataContract]
public class TraktEpisodeDataContract
{
[DataMember(Name = "season")]
public int Season { get; set; }
[DataMember(Name = "number")]
public int Number { get; set; }
[DataMember(Name = "episode")]
public int Episode { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "overview")]
public string Overview { get; set; }
[DataMember(Name = "url")]
public string Url { get; set; }
[DataMember(Name = "first_aired")]
public int FirstAired { get; set; }
[DataMember(Name = "images")]
public TraktImagesDataContract Images { get; set; }
[DataMember(Name = "ratings")]
public TraktRatingsDataContract Ratings { get; set; }
[DataMember(Name = "watched")]
public bool Watched { get; set; }
[DataMember(Name = "plays")]
public int Plays { get; set; }
[DataMember(Name = "rating")]
public string Rating { get; set; }
[DataMember(Name = "in_watchlist")]
public bool InWatchlist { get; set; }
}
}
| 26.041667 | 61 | 0.5728 | [
"MIT"
] | snazy2000/MediaBrowser.Plugins | Trakt/Api/DataContracts/TraktEpisodeDataContract.cs | 1,252 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DevnotMentor.Common.Requests;
using DevnotMentor.Data.Entities;
using DevnotMentor.Data.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace DevnotMentor.Data
{
public class MentorRepository : BaseRepository<Mentor>, IMentorRepository
{
public MentorRepository(MentorDBContext context) : base(context)
{
}
public Task<List<Mentor>> SearchAsync(SearchRequest request)
{
if (request is null || request.IsNotValid())
{
return DbContext
.Mentors
.Include(mentor => mentor.User)
.Include(mentor => mentor.MentorTags)
.ThenInclude(mentorTag => mentorTag.Tag)
.ToListAsync();
}
var queryableMentor = DbContext.Mentors.AsQueryable();
if (!string.IsNullOrEmpty(request.FullName))
{
queryableMentor = queryableMentor.Where(mentor => (mentor.User.Name + " " + mentor.User.SurName).Contains(request.FullName));
}
if (!string.IsNullOrEmpty(request.Title))
{
queryableMentor = queryableMentor.Where(mentor => mentor.Title.Contains(request.Title));
}
if (!string.IsNullOrEmpty(request.Description))
{
queryableMentor = queryableMentor.Where(mentor => mentor.Description.Contains(request.Description));
}
if (request.Tags.Any())
{
queryableMentor = queryableMentor.Where(mentor => mentor.MentorTags.Any(tags => request.Tags.Contains(tags.Tag.Name)));
}
return queryableMentor
.Include(mentor => mentor.User)
.Include(mentor => mentor.MentorTags)
.ThenInclude(mentorTag => mentorTag.Tag)
.ToListAsync();
}
public async Task<int> GetIdByUserIdAsync(int userId)
{
return await DbContext.Mentors.Where(i => i.UserId == userId).Select(i => i.Id).FirstOrDefaultAsync();
}
public async Task<Mentor> GetByUserNameAsync(string userName)
{
return await DbContext.Mentors.Include(x => x.User).Where(i => i.User.UserName == userName).FirstOrDefaultAsync();
}
public async Task<Mentor> GetByUserIdAsync(int userId)
{
return await DbContext.Mentors.Where(i => i.UserId == userId).FirstOrDefaultAsync();
}
public async Task<bool> IsExistsByUserIdAsync(int userId)
{
return await DbContext.Mentors.AnyAsync(i => i.UserId == userId);
}
public async Task<IEnumerable<Mentee>> GetPairedMenteesByMentorIdAsync(int mentorId)
{
return await DbContext.Mentorships.Where(x => x.MentorId == mentorId)
.Include(x => x.Mentee)
.ThenInclude(x => x.User)
.Select(x => x.Mentee)
.ToListAsync();
}
public async Task<Mentor> GetByIdAsync(int mentorId)
{
return await DbContext.Mentors.Include(x=>x.User).Where(x => x.Id == mentorId).FirstOrDefaultAsync();
}
}
}
| 35.698925 | 141 | 0.584337 | [
"MIT"
] | SabitKondakci/devnot-mentor-back-end | src/DevnotMentor.Data/MentorRepository.cs | 3,322 | C# |
using System;
using System.IO;
using GroupDocs.Conversion.Options.Convert;
namespace GroupDocs.Conversion.Examples.CSharp.AdvancedUsage
{
/// <summary>
/// This example demonstrates how to convert document from stream.
/// </summary>
class LoadDocumentFromStream
{
public static void Run()
{
string outputDirectory = Constants.GetOutputDirectoryPath();
string outputFile = Path.Combine(outputDirectory, "converted.pdf");
using (Converter converter = new Converter(GetFileStream))
{
PdfConvertOptions options = new PdfConvertOptions();
converter.Convert(outputFile, options);
}
Console.WriteLine($"\nSource document converted successfully.\nCheck output in {outputDirectory}.");
}
private static Stream GetFileStream() =>
File.OpenRead(Constants.SAMPLE_DOCX);
}
}
| 31.193548 | 112 | 0.62668 | [
"MIT"
] | ExplodedRiot/MachineLearning2 | Examples/GroupDocs.Conversion.Examples.CSharp/AdvancedUsage/Loading/LoadingDocumentsFromDifferentSources/LoadDocumentFromStream.cs | 969 | C# |
// Copyright (c) 2014-2022 Sarin Na Wangkanai, All Rights Reserved.Apache License, Version 2.0
namespace Microsoft.Extensions.DependencyInjection;
public class WebserverOptions
{
} | 23.5 | 95 | 0.781915 | [
"Apache-2.0"
] | wangkanai/BrowserDetection | Webserver/src/DependencyInjection/Options/WebserverOptions.cs | 190 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SupportChat;
namespace AOP
{
//Caches messages to make calls to the database rarer
public class ChatDatabaseAdvice: Advice<IChatDatabase>
{
private static Dictionary<int, List<MessageDTO>> messageCache = new Dictionary<int, List<MessageDTO>>();
protected override void After(MethodInfo methodInfo, object[] args, object result)
{
if (methodInfo.Name == "GetMessages")
{
var userId = (int)args[0];
if (userId != -1 && !messageCache.ContainsKey(userId) && result != null)
{
messageCache[userId] = (List<MessageDTO>) result;
}
}
}
protected override void Before(MethodInfo methodInfo, object[] args)
{
if (methodInfo.Name is "AddMessage" or "RemoveAllUserMessages") //Methods which change state of database, cache becomes outdated
{
var userId = (int)args[0];
messageCache.Remove(userId);
}
}
protected override object Around(MethodInfo methodInfo, object[] args)
{
if (methodInfo.Name == "GetMessages")
{
var userId = (int)args[0];
if (userId != -1)
{
if (messageCache.ContainsKey(userId))
return messageCache[userId];
//messageCache[userId] = (List<MessageDTO>) methodInfo.Invoke(_decorated, args); //Can't add so far, we need to wait to the end of task
}
}
return methodInfo.Invoke(_decorated, args); //Just call method normally if nothing else returned so far
}
}
} | 36.7 | 155 | 0.554223 | [
"MIT"
] | artemgur/sem2 | SupportChat/ChatDatabaseAdvice.cs | 1,835 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ShopKeeper.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("C:\\Data\\Enquiry.mdb")]
public string DataFilePath {
get {
return ((string)(this["DataFilePath"]));
}
set {
this["DataFilePath"] = value;
}
}
}
}
| 39.820513 | 152 | 0.55763 | [
"MIT"
] | abhcr/adGiga | adGiga Projects/Backup/DailyExpense/Properties/Settings.Designer.cs | 1,555 | C# |
using System.Collections.Generic;
using FubuCore;
using StoryTeller.Domain;
using StoryTeller.Execution;
using StoryTeller.Model;
namespace StoryTeller.Engine
{
public class TestRunner : ITestRunner
{
private readonly ISystem _system;
private readonly FixtureLibrary _library;
private TestRun _currentRun;
private ITestObserver _listener = new TraceListener();
public static ITestRunner ForSystem<T>() where T : ISystem, new()
{
var system = new T();
return ForSystem(system);
}
public static ITestRunner ForSystem(ISystem system)
{
return new TestRunner(system, FixtureGraph.Library);
}
public TestRunner() : this(new NulloSystem(), FixtureGraph.Library)
{
}
public TestRunner(ISystem system, FixtureLibrary library)
{
_system = system;
_library = library;
}
#region ITestRunner Members
public FixtureLibrary Library
{
get { return _library; }
}
public ITestObserver Listener
{
get { return _listener; }
set { _listener = value; }
}
public virtual void RunTests(IEnumerable<Test> tests, IBatchListener listener)
{
var batch = new BatchRunner(tests, listener, this);
batch.Execute();
}
public virtual TestResult RunTest(TestExecutionRequest request)
{
try
{
_currentRun = new TestRun(request, _listener, _library, _system);
// Setting the LastResult on the test here is just a convenience
// for testing
TestResult result = _currentRun.Execute();
return result;
}
finally
{
_currentRun = null;
}
}
public void Dispose()
{
_system.SafeDispose();
}
public void Abort()
{
if (_currentRun != null) _currentRun.Abort();
}
#endregion
public bool IsExecuting()
{
return _currentRun != null;
}
}
} | 25.537634 | 87 | 0.517895 | [
"Apache-2.0"
] | mtscout6/StoryTeller2 | src/StoryTeller/Engine/TestRunner.cs | 2,375 | C# |
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Management.Automation;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace PowerLFRepository
{
public class RepositoryCmdlet : PSCmdlet
{
[Parameter]
public LFSession Session { get; set; }
protected RepositoryCmdlet()
{
}
protected SecurityIdentifier GetSidForIdentity(string identity)
{
var ctx = new PrincipalContext(ContextType.Domain);
var principal = Principal.FindByIdentity(ctx, identity);
if (principal != null) return principal.Sid;
try
{
var acct = new NTAccount(identity);
return (SecurityIdentifier) acct.Translate(typeof(SecurityIdentifier));
}
catch
{
throw new ArgumentException($"Could not determine Security Identifier for {identity}", nameof(identity));
}
}
protected override void BeginProcessing()
{
Session = SessionState.PSVariable.GetValue("script:DefaultLFSession", Session) as LFSession;
if (Session == null)
{
throw new PSArgumentException("No Laserfiche Session", "Session");
}
}
}
}
| 27.882353 | 121 | 0.605485 | [
"MIT"
] | MedAmericaBillingServices/PowerLF | PowerLFRepository/RepositoryCmdlet.cs | 1,424 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.GoogleNative.Container.V1Beta1.Outputs
{
/// <summary>
/// Allows filtering to one or more specific event types. If event types are present, those and only those event types will be transmitted to the cluster. Other types will be skipped. If no filter is specified, or no event types are present, all event types will be sent
/// </summary>
[OutputType]
public sealed class FilterResponse
{
/// <summary>
/// Event types to allowlist.
/// </summary>
public readonly ImmutableArray<string> EventType;
[OutputConstructor]
private FilterResponse(ImmutableArray<string> eventType)
{
EventType = eventType;
}
}
}
| 33.225806 | 274 | 0.685437 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Container/V1Beta1/Outputs/FilterResponse.cs | 1,030 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
* 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.
*/
namespace TencentCloud.Tiems.V20190416.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeRuntimesRequest : AbstractModel
{
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
}
}
}
| 28.351351 | 83 | 0.686368 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Tiems/V20190416/Models/DescribeRuntimesRequest.cs | 1,071 | C# |
using System;
using System.Threading.Tasks;
using DevOpen.Application.Mediators;
using DevOpen.Domain;
namespace DevOpen.Application.Handlers.Commands
{
public interface ICommandHandler
{
Type CommandType { get; }
Task<CommandExecutionResult> Handle(Command command);
}
public interface ICommandHandler<in T> : ICommandHandler
where T : Command
{
Task<CommandExecutionResult> Handle(T command);
}
} | 23.45 | 61 | 0.690832 | [
"MIT"
] | nissbran/collector-open-es | src/core/DevOpen.Application/Handlers/Commands/ICommandHandler.cs | 469 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Diagnostics.Contracts;
using System;
namespace System.Runtime.Serialization
{
public interface ISurrogateSelector
{
void ChainSelector(ISurrogateSelector selector);
/*
Contract.Requires(selector != null);
Contract.Requires(selector != this);
*/
ISurrogateSelector GetNextSelector();
ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
// FIXME - why aren't these allowed?
// Contract.Requires(type != null);
//Contract.Requires(surrogate != null);
}
public class SurrogateSelector : ISurrogateSelector
{
public void RemoveSurrogate (Type type, StreamingContext context) {
Contract.Requires(type != null);
}
public ISerializationSurrogate GetSurrogate (Type type, StreamingContext context, out ISurrogateSelector selector) {
//Contract.Requires(type != null);
return default(ISerializationSurrogate);
}
public ISurrogateSelector GetNextSelector () {
return default(ISurrogateSelector);
}
public void ChainSelector (ISurrogateSelector selector) {
/*
Contract.Requires(selector != null);
Contract.Requires(selector != this);
*/
}
public void AddSurrogate (Type type, StreamingContext context, out ISerializationSurrogate surrogate) {
Contract.Requires(type != null);
Contract.Requires(surrogate != null);
}
public SurrogateSelector () {
return default(SurrogateSelector);
}
}
}
| 40.785714 | 463 | 0.688967 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/MsCorlib/System.Runtime.Serialization.SurrogateSelector.cs | 2,855 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.