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 |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression
{
public class DeflateStreamUnitTests : CompressionStreamUnitTestBase
{
public override Stream CreateStream(Stream stream, CompressionMode mode) => new DeflateStream(stream, mode);
public override Stream CreateStream(Stream stream, CompressionMode mode, bool leaveOpen) => new DeflateStream(stream, mode, leaveOpen);
public override Stream CreateStream(Stream stream, CompressionLevel level) => new DeflateStream(stream, level);
public override Stream CreateStream(Stream stream, CompressionLevel level, bool leaveOpen) => new DeflateStream(stream, level, leaveOpen);
public override Stream BaseStream(Stream stream) => ((DeflateStream)stream).BaseStream;
protected override string CompressedTestFile(string uncompressedPath) => Path.Combine("DeflateTestData", Path.GetFileName(uncompressedPath));
public static IEnumerable<object[]> DecompressFailsWithWrapperStream_MemberData()
{
foreach (object[] testFile in UncompressedTestFiles())
{
yield return new object[] { testFile[0], "GZipTestData", ".gz" };
yield return new object[] { testFile[0], "ZLibTestData", ".z" };
}
}
/// <summary>Test to pass GZipStream data and ZLibStream data to a DeflateStream</summary>
[Theory]
[MemberData(nameof(DecompressFailsWithWrapperStream_MemberData))]
public async Task DecompressFailsWithWrapperStream(string uncompressedPath, string newDirectory, string newSuffix)
{
string fileName = Path.Combine(newDirectory, Path.GetFileName(uncompressedPath) + newSuffix);
using (LocalMemoryStream baseStream = await LocalMemoryStream.readAppFileAsync(fileName))
using (Stream cs = CreateStream(baseStream, CompressionMode.Decompress))
{
int _bufferSize = 2048;
var bytes = new byte[_bufferSize];
Assert.Throws<InvalidDataException>(() => { cs.Read(bytes, 0, _bufferSize); });
}
}
[Fact]
public void DerivedStream_ReadWriteSpan_UsesReadWriteArray()
{
var ms = new MemoryStream();
using (var compressor = new DerivedDeflateStream(ms, CompressionMode.Compress, leaveOpen: true))
{
compressor.Write(new Span<byte>(new byte[1]));
Assert.True(compressor.WriteArrayInvoked);
}
ms.Position = 0;
using (var compressor = new DerivedDeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
{
compressor.Read(new Span<byte>(new byte[1]));
Assert.True(compressor.ReadArrayInvoked);
}
ms.Position = 0;
using (var compressor = new DerivedDeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
{
compressor.ReadAsync(new Memory<byte>(new byte[1])).AsTask().Wait();
Assert.True(compressor.ReadArrayInvoked);
}
ms.Position = 0;
using (var compressor = new DerivedDeflateStream(ms, CompressionMode.Compress, leaveOpen: true))
{
compressor.WriteAsync(new ReadOnlyMemory<byte>(new byte[1])).AsTask().Wait();
Assert.True(compressor.WriteArrayInvoked);
}
}
private sealed class DerivedDeflateStream : DeflateStream
{
public bool ReadArrayInvoked = false, WriteArrayInvoked = false;
internal DerivedDeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) : base(stream, mode, leaveOpen) { }
public override int Read(byte[] array, int offset, int count)
{
ReadArrayInvoked = true;
return base.Read(array, offset, count);
}
public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
ReadArrayInvoked = true;
return base.ReadAsync(array, offset, count, cancellationToken);
}
public override void Write(byte[] array, int offset, int count)
{
WriteArrayInvoked = true;
base.Write(array, offset, count);
}
public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
WriteArrayInvoked = true;
return base.WriteAsync(array, offset, count, cancellationToken);
}
}
}
}
| 46.933333 | 149 | 0.63332 | [
"MIT"
] | MattGal/runtime | src/libraries/System.IO.Compression/tests/CompressionStreamUnitTests.Deflate.cs | 4,928 | C# |
// Copyright (c) 2021 homuler
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
using System.Collections;
using UnityEngine;
namespace Mediapipe.Unity.HairSegmentation
{
public class HairSegmentationSolution : ImageSourceSolution<HairSegmentationGraph>
{
[SerializeField] private MaskAnnotationController _hairMaskAnnotationController;
protected override void OnStartRun()
{
graphRunner.OnHairMaskOutput.AddListener(_hairMaskAnnotationController.DrawLater);
SetupAnnotationController(_hairMaskAnnotationController, ImageSourceProvider.ImageSource);
_hairMaskAnnotationController.InitScreen();
}
protected override void AddTextureFrameToInputStream(TextureFrame textureFrame)
{
graphRunner.AddTextureFrameToInputStream(textureFrame);
}
protected override IEnumerator WaitForNextValue()
{
if (runningMode == RunningMode.Sync)
{
var _ = graphRunner.TryGetNext(out var _, true);
}
else if (runningMode == RunningMode.NonBlockingSync)
{
yield return new WaitUntil(() => graphRunner.TryGetNext(out var _, false));
}
}
}
}
| 30.390244 | 96 | 0.73756 | [
"MIT"
] | Kim-JeongUng/MediaPipeUnityPlugin | Assets/Mediapipe/Samples/Scenes/Hair Segmentation/HairSegmentationSolution.cs | 1,246 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ResxSync.UI.Controls
{
public class SelectableWorkspaceControlEventArgs : EventArgs
{
public SelectableWorkspaceControl Control;
public WorkspaceControl Workspace;
}
/// <summary>
/// Interaction logic for SelectableWorkspaceControl.xaml
/// </summary>
public partial class SelectableWorkspaceControl : UserControl
{
public event EventHandler<SelectableWorkspaceControlEventArgs> Deleted;
public event EventHandler<SelectableWorkspaceControlEventArgs> Selected;
public event EventHandler<SelectableWorkspaceControlEventArgs> Deselected;
private WorkspaceControl _workspace;
public WorkspaceControl Workspace
{
get
{
return _workspace;
}
}
private bool _isSelected = false;
public bool IsSelected
{
get
{
return _isSelected;
}
}
public SelectableWorkspaceControl()
{
InitializeComponent();
_workspace = new WorkspaceControl();
}
public void Select()
{
_isSelected = true;
SWCBorder.Background = new SolidColorBrush(Color.FromArgb(30, 255, 255, 255));
Selected?.Invoke(this, new SelectableWorkspaceControlEventArgs() { Control = this, Workspace = _workspace });
}
public void Delete()
{
Deleted?.Invoke(this, new SelectableWorkspaceControlEventArgs() { Control = this, Workspace = _workspace });
}
public void Deselect()
{
_isSelected = false;
SWCBorder.Background = new SolidColorBrush(Color.FromArgb(0, 255, 255, 255));
Deselected?.Invoke(this, new SelectableWorkspaceControlEventArgs() { Control = this, Workspace = _workspace });
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("You sure?", "Deleting a workspace", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No)
{
return;
}
Delete();
}
private void AddResxFileButton_Click(object sender, RoutedEventArgs e)
{
_workspace.AddResx();
}
private void SaveWorkspaceToDiskButton_Click(object sender, RoutedEventArgs e)
{
}
}
}
| 28.178218 | 141 | 0.631061 | [
"MIT"
] | meJevin/ResxSync | Source/ResxSync/ResxSync.UI/Controls/SelectableWorkspaceControl.xaml.cs | 2,848 | C# |
using System;
using MediatR;
namespace Episememe.Application.Features.VerifyBrowseToken
{
public class VerifyBrowseTokenQuery : IRequest<bool>
{
public string TokenValue { get; }
private VerifyBrowseTokenQuery(string token)
=> TokenValue = token;
public static VerifyBrowseTokenQuery Create(string token)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentException("Token is null or empty.", nameof(token));
return new VerifyBrowseTokenQuery(token);
}
}
}
| 25.818182 | 86 | 0.649648 | [
"BSD-3-Clause"
] | marax27/Episememe | server/Episememe.Application/Features/VerifyBrowseToken/VerifyBrowseTokenQuery.cs | 570 | C# |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Windows.Media;
using SyNet.MessageTypes;
using SyNet.Protocol;
using UserControl = System.Windows.Controls.UserControl;
using System.Globalization;
using System.Threading;
namespace SyNet.GuiControls {
/// <summary>
/// Interaction logic for DeviceUpdater.xaml
/// </summary>
public partial class DeviceUpdater : UserControl, INotifyPropertyChanged {
////////////////////////////////////////////////////////////////////////////
#region Member variables
private MsgDispatcher.CallbackStruct m_cs;
/// <summary>
/// Structure of all necessary thread worker references
/// </summary>
protected struct WorkerArgs {
/// <summary>
/// Target xbee device
/// </summary>
public DeviceXBee TargetDevice;
/// <summary>
/// Reference to the message dispatcher
/// </summary>
public MsgDispatcher MessageDispatcher;
/// <summary>
/// Update filename
/// </summary>
public String Filename;
}
/// <summary>
/// Structure of progress arguments
/// </summary>
protected struct ProgressArgs {
// State machine of current progress
/// <summary>
///
/// </summary>
public String Status;
/// <summary>
///
/// </summary>
public String Download;
/// <summary>
///
/// </summary>
public int Retries;
/// <summary>
///
/// </summary>
public Color ColorConnect;
/// <summary>
///
/// </summary>
public Color ColorDownload;
/// <summary>
///
/// </summary>
public Color ColorComplete;
/// <summary>
///
/// </summary>
/// <param name="p_status"></param>
/// <param name="p_downloadP"></param>
/// <param name="p_retriesP"></param>
/// <param name="p_cconP"></param>
/// <param name="p_cdP"></param>
/// <param name="p_ccP"></param>
public ProgressArgs(String p_status, String p_downloadP,
int p_retriesP, Color p_cconP, Color p_cdP, Color p_ccP)
{
Status = p_status;
Download = p_downloadP;
Retries = p_retriesP;
ColorConnect = p_cconP;
ColorDownload = p_cdP;
ColorComplete = p_ccP;
}
}
private const string FILENAME_DEFAULT = "[No file selected]";
private byte[] fileBuffer = new byte[16384];
private string m_filename = FILENAME_DEFAULT;
private BackgroundWorker m_backgroundWorker1;
#endregion
////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Filename of update file
/// </summary>
public string FileName
{
get { return m_filename; }
set
{
m_filename = value;
OnPropertyChanged("FileName");
}
}
/// <summary>
/// Default constructor
/// </summary>
public DeviceUpdater()
{
InitializeComponent();
InitializeBackgroundWorker();
}
/// <summary>
/// Initialize the background worker for the download
/// </summary>
private void InitializeBackgroundWorker()
{
m_backgroundWorker1 = new BackgroundWorker();
m_backgroundWorker1.DoWork += DownloadFile;
m_backgroundWorker1.WorkerReportsProgress = true;
m_backgroundWorker1.WorkerSupportsCancellation = true;
m_backgroundWorker1.ProgressChanged += ProgressChanged;
m_backgroundWorker1.RunWorkerCompleted += RunWorkerCompleted;
}
private void DownloadFile(object s, DoWorkEventArgs args)
{
BackgroundWorker worker = s as BackgroundWorker;
ProgressArgs progArgs = new ProgressArgs("Idle.",
"Idle.",
0,
Colors.Yellow,
Colors.Blue,
Colors.Blue);
int pageSize = 64; // For ATmega168, we have to load 128 bytes at a time (program full page). Document: AVR095
int memoryAddressHigh;
int memoryAddressLow;
int lastAddress;
int currentAddress;
int progress = 0;
bool msgResponse;
string currentFile = string.Empty;
byte[] buffer = new byte[pageSize + 4];
string filename = string.Empty;
WorkerArgs wArgs = (WorkerArgs)args.Argument;
MsgDispatcher msgProc = wArgs.MessageDispatcher;
DeviceXBee xbeeTarget = wArgs.TargetDevice;
String hexFileName = wArgs.Filename;
Debug.WriteLine("[DBG] Starting download file worker");
// Try and do this
//try {
worker.ReportProgress(progress, progArgs);
////////////////////////////////////////////////////////////////////////
#region -- Take hex file and store it sequentially into large array
filename = Path.GetFileName(hexFileName);
if (!ParseFile(FileName, out currentAddress, out lastAddress)) {
MessageBox.Show("Could not parse file");
return;
}
#endregion
////////////////////////////////////////////////////////////////////////
if (worker.CancellationPending) {
args.Cancel = true;
return;
}
////////////////////////////////////////////////////////////////////////
#region -- Send reset message
progArgs.ColorConnect = Colors.Yellow;
progArgs.Status = ("Sending Reset Message.");
worker.ReportProgress(progress, progArgs);
msgResponse = false;
m_cs.Reset();
// Send reset message
msgProc.SendMsg(
new MsgSyNetBootloadTransmit(xbeeTarget,
EsnAPIBootloadTransmit.REBOOT_DEVICE)
);
// Wait for a response
if (m_cs.CallbackEvent.WaitOne(TimeSpan.FromSeconds(30), true))
{
// Make sure it's the correct response
MsgSyNetDeviceStatus msg = m_cs.ResponseMsgs[0] as MsgSyNetDeviceStatus;
if (msg != null && msg.DeviceStatus == EsnAPIDeviceStatusValues.HW_RESET)
{
msgResponse = true;
}
}
// If the response is bad, bail
if (!msgResponse) {
progArgs.ColorConnect = Colors.Red;
progArgs.Status = ("The target IC did not broadcast reset");
worker.ReportProgress(progress, progArgs);
return;
}
#endregion
////////////////////////////////////////////////////////////////////////
if (worker.CancellationPending) {
args.Cancel = true;
return;
}
////////////////////////////////////////////////////////////////////////
#region -- send bootloading message
progArgs.Status = ("Sending Bootload Request.");
worker.ReportProgress(progress, progArgs);
// Send a bootload message to the device
msgResponse = false;
// Reset the callback
m_cs.Reset();
int tmpCount = 0;
while (!msgResponse && (tmpCount++) < 5) {
msgResponse = msgProc.SendMsgWithResponse(
new MsgSyNetBootloadTransmit(xbeeTarget,
EsnAPIBootloadTransmit.BOOTLOAD_REQUEST),
TimeSpan.FromSeconds(20),
m_cs
);
}
// Make sure it's the right message
if (msgResponse) {
msgResponse = false;
MsgSyNetBootloadResponse msg = m_cs.ResponseMsgs[0] as
MsgSyNetBootloadResponse;
if (msg != null) {
if (msg.Response ==
EsnAPIBootloadResponse.BOOTLOAD_READY) {
msgResponse = true;
}
}
}
// If we didn't make it, there was an error
if (!msgResponse) {
progArgs.ColorConnect = Colors.Red;
progArgs.Status = ("The target IC did not broadcast bootload");
worker.ReportProgress(progress, progArgs);
return;
}
progArgs.ColorConnect = Colors.Green;
worker.ReportProgress(progress, progArgs);
#endregion
////////////////////////////////////////////////////////////////////////
if (worker.CancellationPending) {
args.Cancel = true;
return;
}
int block_size = 0;
int checkSum;
bool datablockSuccess = false;
int startAddress = currentAddress;
// Begin download loop
while (currentAddress <= lastAddress) {
if (worker.CancellationPending) {
args.Cancel = true;
return;
}
block_size = Math.Min(pageSize, lastAddress - currentAddress + 1);
// Convert 16-bit current_memory_address into two 8-bit characters
memoryAddressHigh = currentAddress / 256;
memoryAddressLow = currentAddress % 256;
// Calculate current check_sum
checkSum = 0;
checkSum = checkSum + block_size;
checkSum = checkSum + memoryAddressHigh;
checkSum = checkSum + memoryAddressLow;
for (int j = 0; j < block_size; j++)
checkSum = checkSum + fileBuffer[currentAddress + j];
// Now reduce check_sum to 8 bits
while (checkSum > 256)
checkSum -= 256;
// Now take 2's compliment
checkSum = 256 - checkSum;
// Send the record header
buffer[0] = (byte)block_size;
buffer[1] = (byte)memoryAddressHigh;
buffer[2] = (byte)memoryAddressLow;
buffer[3] = (byte)checkSum;
Array.Copy(fileBuffer, currentAddress, buffer, 4, block_size);
// Send the record data
m_cs.Reset();
msgProc.SendMsg(
new MsgSyNetBootloadTransmit(
xbeeTarget,
EsnAPIBootloadTransmit.DATA_TRANSMIT,
buffer)
);
datablockSuccess = false;
if (m_cs.CallbackEvent.WaitOne(TimeSpan.FromSeconds(10), false)) {
//Debug.WriteLine("[DBG] SyNetBootload - Response ");
MsgSyNetBootloadResponse msg = m_cs.ResponseMsgs[0] as MsgSyNetBootloadResponse;
// Check that the essage was cast successfully
// and it's a data success response
if (msg != null &&
msg.Response == EsnAPIBootloadResponse.DATA_SUCCESS) {
// Make sure its for the right data
if (msg.MemoryAddress == (UInt16)currentAddress) {
datablockSuccess = true;
} else {
Debug.WriteLine(String.Format("[ERR] Return for {0} expected {1}",
msg.MemoryAddress,
currentAddress));
if (msg.MemoryAddress < currentAddress)
{
currentAddress = msg.MemoryAddress + block_size;
}
progArgs.Retries++;
}
}
} else {
progArgs.Retries++;
Debug.WriteLine("[ERR] SyNetBootload - No response");
}
if (datablockSuccess) {
progress = (int)(((float)currentAddress - (float)startAddress) /
((float)lastAddress - (float)startAddress + 1.0) * 100.0);
currentAddress = currentAddress + block_size;
progArgs.Status = String.Format("Loaded {0} data words.", currentAddress);
progArgs.Download = "Running...";
progArgs.ColorDownload = Colors.Green;
progArgs.ColorComplete = Colors.Yellow;
} else {
progArgs.ColorDownload = Colors.Yellow;
}
worker.ReportProgress(progress, progArgs);
// #endregion
}
worker.ReportProgress(100, progArgs);
// We're done
m_cs.Reset();
bool response = msgProc.SendMsgWithResponse(
new MsgSyNetBootloadTransmit(
xbeeTarget, EsnAPIBootloadTransmit.DATA_COMPLETE),
TimeSpan.FromSeconds(5),
m_cs);
progArgs.ColorConnect = Colors.Blue;
progArgs.ColorDownload = Colors.Blue;
progArgs.ColorComplete = Colors.Green;
progArgs.Status = ("Idle.");
progArgs.Download = "Download Complete.";
worker.ReportProgress(progress, progArgs);
//} catch (System.Exception ex) {
// if (string.IsNullOrEmpty(currentFile))
// MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// else
// MessageBox.Show(string.Format("Error in file {0}\n\n{1}", filename, ex.Message), "W00ter", MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
/// <summary>
/// Take in an Intel hex file and load it into a large array.
/// This allows us to read sequential data from the large array without having to
/// worry about weird character line-feed breaks in the text/HEX file.
/// </summary>
/// <returns>success</returns>
/// <remarks>For ATmega168, we have to load 128 bytes at a time (program full page). Document: AVR095</remarks>
private bool ParseFile(string path, out int minAddress, out int maxAddress)
{
int byteCount;
int memoryAddressHigh;
int memoryAddressLow;
int memoryAddress;
int lineNumber = 0;
string filename = Path.GetFileName(path);
maxAddress = int.MinValue;
minAddress = int.MaxValue;
// Pre-fill hex_array with 0xFF
for (int i = 0; i < fileBuffer.Length; i++)
fileBuffer[i] = 0xFF;
// Read in the HEX file - clean it up
try {
if (!File.Exists(path)) {
System.Windows.Forms.MessageBox.Show(string.Format("File not found {0}", path));
return false;
}
using (StreamReader f = new StreamReader(path, Encoding.ASCII)) {
string line;
while ((line = f.ReadLine()) != null) {
line = line.Trim();
lineNumber++;
if (line.Length == 0)
continue;
#region -- Intel file format
if (line.StartsWith(":")) {
switch (line.Substring(7, 2)) { // Ignore:
case "02": // 02 - extended segment address record
case "04": // 04 - extended linear address record
if (MessageBox.Show(
string.Format(
"Warning in line {0} of {1}\n\nUnsupported record type\n\nContinue download ?",
lineNumber, filename
),
string.Format("Title"),
MessageBoxButtons.YesNo
) == DialogResult.No) {
f.Close();
return false;
}
continue;
case "03":
continue;
case "01": // 01 - end-of-file record
f.Close();
return true;
case "00":
break;
default:
if (MessageBox.Show(
string.Format(
"Warning in line {0} of {1}\n\nUnknown record type {2}\n\nContinue download ?",
lineNumber, filename, line.Substring(7, 2)
),
"Caption",
MessageBoxButtons.YesNo,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1) == DialogResult.No) {
f.Close();
return false;
}
continue;
}
byteCount = int.Parse(line.Substring(1, 2), NumberStyles.HexNumber);
if (byteCount == 0)
continue;
// Get the memory address of this line
memoryAddressHigh = int.Parse(line.Substring(3, 2), NumberStyles.HexNumber);
memoryAddressLow = int.Parse(line.Substring(5, 2), NumberStyles.HexNumber);
memoryAddress = (memoryAddressHigh * 256) + memoryAddressLow;
for (int idx = 0; idx < byteCount; idx++) {
int address = memoryAddress + idx;
if (address >= fileBuffer.Length) {
MessageBox.Show(
string.Format("Error in line {0} of {1}\n\nAddress {2:X} out of buffer (max. {3:X})", lineNumber, filename, address, fileBuffer.Length),
"Caption",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
f.Close();
return false;
}
if (maxAddress < address)
maxAddress = address;
if (minAddress > address)
minAddress = address;
fileBuffer[address] = byte.Parse(line.Substring(9 + idx * 2, 2), NumberStyles.HexNumber);
}
continue;
}
#endregion
#region -- Motorola S format
if (line.StartsWith("S")) {
MessageBox.Show(
string.Format("Error in line {0} of {1}\n\nMotorols S format not supported.", lineNumber, filename),
"Caption",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
f.Close();
return false;
}
#endregion
}
f.Close();
}
} catch (System.Exception ex) {
// see http://en.wikipedia.org/wiki/S-record for detail
MessageBox.Show(
string.Format("Error in line {0} of {1}\n\n{2}", lineNumber, filename, ex.Message),
"Caption",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
return false;
}
return true;
}
/// <summary>
/// This sub resets all the GUI stuff and displays the given error to the user
/// </summary>
/// <param name="error_msg"></param>
private void ErrorOut(string error_msg)
{
m_LabelStatus.Content = "Idle";
m_LabelDownload.Content = "Idle";
MessageBox.Show(error_msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
/// <summary>
/// Property changed event handler
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
///
/// </summary>
/// <param name="propertyName"></param>
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private void UpdateProgressArgs(ProgressArgs progArgs)
{
m_LabelStatus.Content = progArgs.Status;
m_LabelDownload.Content = progArgs.Download;
m_LabelRetries.Content = progArgs.Retries;
m_RectDownload.Fill = new SolidColorBrush(progArgs.ColorDownload);
m_RectConnect.Fill = new SolidColorBrush(progArgs.ColorConnect);
m_RectComplete.Fill = new SolidColorBrush(progArgs.ColorComplete);
}
/// <summary>
/// Event for when the progress needs to be updated
/// </summary>
/// <param name="s"></param>
/// <param name="args"></param>
private void ProgressChanged(object s, ProgressChangedEventArgs args)
{
ProgressArgs progArgs = (ProgressArgs)args.UserState;
UpdateProgressArgs(progArgs);
m_ProgressBarDownload.Value = args.ProgressPercentage;
}
/// <summary>
/// Event when the download worker has completed
/// </summary>
/// <param name="s"></param>
/// <param name="args"></param>
private void RunWorkerCompleted(object s, RunWorkerCompletedEventArgs args)
{
m_ButtonDownload.IsEnabled = true;
m_ButtonCancel.IsEnabled = false;
m_ProgressBarDownload.Value = 0;
// Remove the callback
MsgDispatcher msgProc = DataContext as MsgDispatcher;
if (msgProc != null) {
msgProc.RemoveCallback(m_cs);
}
// Renable the node manager poking
NodeManager.Instance.PeriodicCheck = true;
}
/// <summary>
/// Hex file selection button click handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonFileSelect_Click(object sender, System.Windows.RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "Data Sources (*.hex)|*.hex*";
if (ofd.ShowDialog() == DialogResult.OK) {
FileName = ofd.FileName;
}
}
/// <summary>
/// Start the download
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDownload_Click(object sender, System.Windows.RoutedEventArgs e)
{
// Check to make sure a file is selected
if (FileName.Equals(FILENAME_DEFAULT)) {
MessageBox.Show("Please select a file");
return;
}
// Check to make sure a node is selected
if (m_ComboBoxNodeList.SelectedIndex == -1) {
MessageBox.Show("Select a node");
return;
}
DeviceXBee xbeeTarget = m_ComboBoxNodeList.SelectionBoxItem as DeviceXBee;
if (xbeeTarget == null) {
MessageBox.Show("Could not cast target device");
return;
}
WorkerArgs args = new WorkerArgs();
args.TargetDevice = xbeeTarget;
args.MessageDispatcher = MsgDispatcher.Instance;
args.Filename = FileName;
m_cs = MsgDispatcher.Instance.RegisterCallback(xbeeTarget.SerialNumber);
m_ButtonDownload.IsEnabled = false;
m_ButtonCancel.IsEnabled = true;
// Disable the node manager from poking around
NodeManager.Instance.PeriodicCheck = false;
// Start the downloader thread
m_backgroundWorker1.RunWorkerAsync(args);
}
/// <summary>
/// Cancel the download
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStop_Click(object sender, System.Windows.RoutedEventArgs e)
{
m_backgroundWorker1.CancelAsync();
}
}
}
| 33.722787 | 157 | 0.53045 | [
"Apache-2.0"
] | mkurdziel/BitHome-Hub-CSharp-V1 | SyNet Controller/XamlPanels/DeviceUpdater.xaml.cs | 23,237 | C# |
using System;
using System.IO;
namespace Sharer.FunctionCall
{
public enum SharerType : byte
{
@void,
@bool,
@byte,
@short,
@int,
@uint,
@long,
@ulong,
int64,
uint64,
@float,
@double
}
public static class SharerTypeHelper
{
public static int Sizeof(SharerType type)
{
switch (type)
{
case SharerType.@bool:
case SharerType.@byte:
case SharerType.@short:
return 1;
case SharerType.@int:
case SharerType.@uint:
return 2;
case SharerType.@long:
case SharerType.@ulong:
case SharerType.@float:
return 4;
case SharerType.int64:
case SharerType.uint64:
case SharerType.@double:
return 8;
default:
return 0;
}
}
public static void Encode(SharerType type, BinaryWriter writer, object value)
{
if (value == null) throw new ArgumentNullException("value");
switch (type)
{
case SharerType.@bool:
var boolValue = Boolean.Parse(value.ToString());
writer.Write((byte)(boolValue? 1:0));
break;
case SharerType.@byte:
writer.Write(Byte.Parse(value.ToString()));
break;
case SharerType.@short:
writer.Write(SByte.Parse(value.ToString()));
break;
case SharerType.@int:
writer.Write(Int16.Parse(value.ToString()));
break;
case SharerType.@uint:
writer.Write(UInt16.Parse(value.ToString()));
break;
case SharerType.@long:
writer.Write(Int32.Parse(value.ToString()));
break;
case SharerType.@ulong:
writer.Write(UInt32.Parse(value.ToString()));
break;
case SharerType.@float:
writer.Write(float.Parse(value.ToString().Replace(",","."), System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture));
break;
case SharerType.int64:
writer.Write(Int64.Parse(value.ToString()));
break;
case SharerType.uint64:
writer.Write(UInt64.Parse(value.ToString()));
break;
case SharerType.@double:
writer.Write(double.Parse(value.ToString().Replace(",", "."), System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture));
break;
default:
throw new Exception("Type " + type.ToString() + " not supported");
}
}
public static object Decode(SharerType type, byte[] buffer)
{
using (MemoryStream memory = new MemoryStream(buffer))
{
using (BinaryReader reader = new BinaryReader(memory))
{
switch (type)
{
case SharerType.@bool:
return reader.ReadByte() != 0;
case SharerType.@byte:
return reader.ReadByte();
case SharerType.@short:
return reader.ReadSByte();
case SharerType.@int:
return reader.ReadInt16();
case SharerType.@uint:
return reader.ReadUInt16();
case SharerType.@long:
return reader.ReadInt32();
case SharerType.@ulong:
return reader.ReadUInt32();
case SharerType.@float:
return reader.ReadSingle();
case SharerType.int64:
return reader.ReadInt64();
case SharerType.uint64:
return reader.ReadUInt64();
case SharerType.@double:
return reader.ReadDouble();
default:
return null;
}
}
}
}
}
}
| 36.358779 | 187 | 0.440479 | [
"MIT"
] | devdotnetorg/Sharer-NETStandard | Sharer-NETStandard/FunctionCall/SharerType.cs | 4,765 | C# |
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
//-----------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Z3AxiomProfiler
{
public partial class LoadingProgressForm : Form
{
private Loader loader;
public LoadingProgressForm(Loader loader)
{
this.loader = loader;
InitializeComponent();
runningZ3.Text = String.Format("Running Z3");
}
private void processLoaderOutput(string line)
{
//processor.ParseSingleLine(line);
}
private void LoadingProgressForm_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
loader.statusUpdate += this.loaderProgressChanged;
//loader.lineOutput += this.processLoaderOutput;
loader.Load();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
loader.Cancel();
}
private void loaderProgressChanged(int perc, int a)
{
backgroundWorker1.ReportProgress(perc, a);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int a = (int)e.UserState;
if (e.ProgressPercentage != 0) {
progressBar1.Style = ProgressBarStyle.Blocks;
int perc = e.ProgressPercentage;
if (perc <= progressBar1.Maximum)
progressBar1.Value = perc;
}
switch (a)
{
case 0:
runningBoogie.Checked = false;
runningZ3.Checked = false;
runningParser.Checked = false;
break;
case 1:
runningBoogie.Checked = true;
runningZ3.Checked = false;
runningParser.Checked = false;
break;
case 2:
runningBoogie.Checked = true;
runningZ3.Checked = true;
runningParser.Checked = false;
break;
case 3:
runningBoogie.Checked = true;
runningZ3.Checked = true;
runningParser.Checked = true;
break;
}
}
}
}
| 26.315217 | 99 | 0.586534 | [
"MIT"
] | Jiacheng/vcc | vcc/Tools/Z3Visualizer/Z3Visualizer/LoadingProgressForm.cs | 2,423 | C# |
using System.Runtime.InteropServices;
using Sharpen;
namespace android.graphics
{
/// <summary>
/// A subclass of shader that returns the coposition of two other shaders, combined by
/// an
/// <see cref="Xfermode">Xfermode</see>
/// subclass.
/// </summary>
[Sharpen.Sharpened]
public class ComposeShader : android.graphics.Shader
{
/// <summary>Hold onto the shaders to avoid GC.</summary>
/// <remarks>Hold onto the shaders to avoid GC.</remarks>
private readonly android.graphics.Shader mShaderA;
private readonly android.graphics.Shader mShaderB;
/// <summary>Create a new compose shader, given shaders A, B, and a combining mode.</summary>
/// <remarks>
/// Create a new compose shader, given shaders A, B, and a combining mode.
/// When the mode is applied, it will be given the result from shader A as its
/// "dst", and the result from shader B as its "src".
/// </remarks>
/// <param name="shaderA">The colors from this shader are seen as the "dst" by the mode
/// </param>
/// <param name="shaderB">The colors from this shader are seen as the "src" by the mode
/// </param>
/// <param name="mode">
/// The mode that combines the colors from the two shaders. If mode
/// is null, then SRC_OVER is assumed.
/// </param>
public ComposeShader(android.graphics.Shader shaderA, android.graphics.Shader shaderB
, android.graphics.Xfermode mode)
{
mShaderA = shaderA;
mShaderB = shaderB;
native_instance = nativeCreate1(shaderA.native_instance, shaderB.native_instance,
(mode != null) ? mode.native_instance : null);
if (mode is android.graphics.PorterDuffXfermode)
{
android.graphics.PorterDuff.Mode pdMode = ((android.graphics.PorterDuffXfermode)mode
).mode;
native_shader = nativePostCreate2(native_instance, shaderA.native_shader, shaderB
.native_shader, pdMode != null ? (int)pdMode : 0);
}
else
{
native_shader = nativePostCreate1(native_instance, shaderA.native_shader, shaderB
.native_shader, mode != null ? mode.native_instance : null);
}
}
/// <summary>Create a new compose shader, given shaders A, B, and a combining PorterDuff mode.
/// </summary>
/// <remarks>
/// Create a new compose shader, given shaders A, B, and a combining PorterDuff mode.
/// When the mode is applied, it will be given the result from shader A as its
/// "dst", and the result from shader B as its "src".
/// </remarks>
/// <param name="shaderA">The colors from this shader are seen as the "dst" by the mode
/// </param>
/// <param name="shaderB">The colors from this shader are seen as the "src" by the mode
/// </param>
/// <param name="mode">The PorterDuff mode that combines the colors from the two shaders.
/// </param>
public ComposeShader(android.graphics.Shader shaderA, android.graphics.Shader shaderB
, android.graphics.PorterDuff.Mode mode)
{
mShaderA = shaderA;
mShaderB = shaderB;
native_instance = nativeCreate2(shaderA.native_instance, shaderB.native_instance,
(int)mode);
native_shader = nativePostCreate2(native_instance, shaderA.native_shader, shaderB
.native_shader, (int)mode);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern android.graphics.Shader.NativeShader libxobotos_ComposeShader_ComposeShader_create
(android.graphics.Shader.NativeShader native_shaderA, android.graphics.Shader.NativeShader
native_shaderB, android.graphics.Xfermode.NativeXfermode native_mode);
private static android.graphics.Shader.NativeShader nativeCreate1(android.graphics.Shader.NativeShader
native_shaderA, android.graphics.Shader.NativeShader native_shaderB, android.graphics.Xfermode.NativeXfermode
native_mode)
{
return libxobotos_ComposeShader_ComposeShader_create(native_shaderA, native_shaderB
, native_mode != null ? native_mode : android.graphics.Xfermode.NativeXfermode.Zero
);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern android.graphics.Shader.NativeShader libxobotos_ComposeShader_ComposeShader_create_0
(android.graphics.Shader.NativeShader native_shaderA, android.graphics.Shader.NativeShader
native_shaderB, int porterDuffMode);
private static android.graphics.Shader.NativeShader nativeCreate2(android.graphics.Shader.NativeShader
native_shaderA, android.graphics.Shader.NativeShader native_shaderB, int porterDuffMode
)
{
return libxobotos_ComposeShader_ComposeShader_create_0(native_shaderA, native_shaderB
, porterDuffMode);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern System.IntPtr libxobotos_ComposeShader_ComposeShader_postCreate
(android.graphics.Shader.NativeShader native_shader, System.IntPtr native_skiaShaderA
, System.IntPtr native_skiaShaderB, android.graphics.Xfermode.NativeXfermode native_mode
);
private static System.IntPtr nativePostCreate1(android.graphics.Shader.NativeShader
native_shader, System.IntPtr native_skiaShaderA, System.IntPtr native_skiaShaderB
, android.graphics.Xfermode.NativeXfermode native_mode)
{
return libxobotos_ComposeShader_ComposeShader_postCreate(native_shader, native_skiaShaderA
, native_skiaShaderB, native_mode);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern System.IntPtr libxobotos_ComposeShader_ComposeShader_postCreate_0
(android.graphics.Shader.NativeShader native_shader, System.IntPtr native_skiaShaderA
, System.IntPtr native_skiaShaderB, int porterDuffMode);
private static System.IntPtr nativePostCreate2(android.graphics.Shader.NativeShader
native_shader, System.IntPtr native_skiaShaderA, System.IntPtr native_skiaShaderB
, int porterDuffMode)
{
return libxobotos_ComposeShader_ComposeShader_postCreate_0(native_shader, native_skiaShaderA
, native_skiaShaderB, porterDuffMode);
}
}
}
| 43.985612 | 113 | 0.759732 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/android/graphics/ComposeShader.cs | 6,114 | C# |
using System;
using System.Collections.Generic;
using System.Numerics.Tensors;
using System.Text;
using NnCase.IR;
using NnCase.IR.Operators;
namespace NnCase.Importer
{
/// <summary>
/// TFLite importer convolution ops lowering.
/// </summary>
public partial class TFLiteImporter
{
private void ConvertReshape(tflite.Operator op)
{
var input = GetTensor(op.Inputs(0));
var options = op.BuiltinOptions<tflite.ReshapeOptions>().Value;
var reshape = _graph.AddNode(new Reshape(ToDataType(input.Type), GetShape(input), options.GetNewShapeSpan()));
_inputTensors.Add(reshape.Input, op.Inputs(0));
_outputTensors.Add(op.Outputs(0), reshape.Output);
}
}
}
| 28.222222 | 122 | 0.660105 | [
"Apache-2.0"
] | dotnetGame/nncase | src/NnCase.Importer/TFLite/Reshape.cs | 764 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* 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;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Driver.Core.Clusters;
namespace MongoDB.Driver.Tests.Specifications.crud
{
public abstract class CrudOperationTestBase : ICrudOperationTest
{
public Exception ActualException { get; set; }
protected ClusterDescription ClusterDescription { get; private set; }
public virtual void SkipIfNotSupported(BsonDocument arguments)
{
}
public void Execute(
ClusterDescription clusterDescription,
IMongoDatabase database,
IMongoCollection<BsonDocument> collection,
BsonDocument arguments,
BsonDocument outcome,
bool isErrorExpected,
bool async)
{
ClusterDescription = clusterDescription;
foreach (var argument in arguments.Elements)
{
if (!TrySetArgument(argument.Name, argument.Value))
{
throw new NotImplementedException("The argument " + argument.Name + " has not been implemented in " + GetType());
}
}
try
{
Execute(database, collection, outcome, async);
}
catch (Exception ex) when (isErrorExpected)
{
ActualException = ex;
}
AssertOutcome(outcome, database, collection);
}
protected virtual void AssertOutcome(BsonDocument outcome, IMongoDatabase database, IMongoCollection<BsonDocument> collection)
{
if (outcome != null && outcome.Contains("collection"))
{
var collectionToVerify = collection;
if (outcome["collection"].AsBsonDocument.Contains("name"))
{
collectionToVerify = database.GetCollection<BsonDocument>(outcome["collection"]["name"].ToString());
}
VerifyCollection(collectionToVerify, (BsonArray)outcome["collection"]["data"]);
}
}
protected virtual bool TrySetArgument(string name, BsonValue value)
{
return false;
}
protected abstract void Execute(IMongoDatabase database, IMongoCollection<BsonDocument> collection, BsonDocument outcome, bool async);
protected virtual void VerifyCollection(IMongoCollection<BsonDocument> collection, BsonArray expectedData)
{
var data = collection.FindSync("{}").ToList();
data.Should().BeEquivalentTo(expectedData);
}
}
public abstract class CrudOperationWithResultTestBase<TResult> : CrudOperationTestBase
{
private TResult _result;
protected sealed override void Execute(IMongoDatabase database, IMongoCollection<BsonDocument> collection, BsonDocument outcome, bool async)
{
_result = ExecuteAndGetResult(database, collection, async);
}
protected override void AssertOutcome(BsonDocument outcome, IMongoDatabase database, IMongoCollection<BsonDocument> collection)
{
if (outcome != null && outcome.Contains("result"))
{
var expectedResult = ConvertExpectedResult(outcome["result"]);
VerifyResult(_result, expectedResult);
}
base.AssertOutcome(outcome, database, collection);
}
protected abstract TResult ConvertExpectedResult(BsonValue expectedResult);
protected abstract TResult ExecuteAndGetResult(IMongoDatabase database, IMongoCollection<BsonDocument> collection, bool async);
protected abstract void VerifyResult(TResult actualResult, TResult expectedResult);
}
}
| 36.91453 | 148 | 0.648067 | [
"Apache-2.0"
] | ksadoff/mongo-csharp-driver | tests/MongoDB.Driver.Tests/Specifications/crud/CrudOperationTestBase.cs | 4,321 | C# |
using OpenCNCPilot.GCode;
using OpenCNCPilot.GCode.GCodeCommands;
using OpenCNCPilot.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace OpenCNCPilot.Communication
{
enum ConnectionType
{
Serial
}
class Machine
{
public enum OperatingMode
{
Manual,
SendFile,
Probe,
Disconnected,
SendMacro
}
public event Action<Vector3, bool> ProbeFinished;
public event Action<string> NonFatalException;
public event Action<string> Info;
public event Action<string> LineReceived;
public event Action<string> StatusReceived;
public event Action<string> LineSent;
public event Action ConnectionStateChanged;
public event Action PositionUpdateReceived;
public event Action StatusChanged;
public event Action DistanceModeChanged;
public event Action UnitChanged;
public event Action PlaneChanged;
public event Action BufferStateChanged;
public event Action PinStateChanged;
public event Action OperatingModeChanged;
public event Action FileChanged;
public event Action FilePositionChanged;
public event Action OverrideChanged;
public Vector3 MachinePosition { get; private set; } = new Vector3(); //No events here, the parser triggers a single event for both
public Vector3 WorkOffset { get; private set; } = new Vector3();
public Vector3 WorkPosition { get { return MachinePosition - WorkOffset; } }
public Vector3 LastProbePosMachine { get; private set; }
public Vector3 LastProbePosWork { get; private set; }
public int FeedOverride { get; private set; } = 100;
public int RapidOverride { get; private set; } = 100;
public int SpindleOverride { get; private set; } = 100;
public bool PinStateProbe { get; private set; } = false;
public bool PinStateLimitX { get; private set; } = false;
public bool PinStateLimitY { get; private set; } = false;
public bool PinStateLimitZ { get; private set; } = false;
public double FeedRateRealtime { get; private set; } = 0;
public double SpindleSpeedRealtime { get; private set; } = 0;
public double CurrentTLO { get; private set; } = 0;
public bool RunningJog { get; set; } = false;
private bool FileError = false;
private int FileErrorLastPosition = 0;
private Calculator _calculator;
public Calculator Calculator { get { return _calculator; } }
private ReadOnlyCollection<bool> _pauselines = new ReadOnlyCollection<bool>(new bool[0]);
public ReadOnlyCollection<bool> PauseLines
{
get { return _pauselines; }
private set { _pauselines = value; }
}
private ReadOnlyCollection<string> _file = new ReadOnlyCollection<string>(new string[0]);
public ReadOnlyCollection<string> File
{
get { return _file; }
private set
{
_file = value;
FilePosition = 0;
RaiseEvent(FileChanged);
}
}
private int _filePosition = 0;
public int FilePosition
{
get { return _filePosition; }
private set
{
_filePosition = value;
}
}
private OperatingMode _mode = OperatingMode.Disconnected;
public OperatingMode Mode
{
get { return _mode; }
private set
{
if (_mode == value)
return;
_mode = value;
RaiseEvent(OperatingModeChanged);
}
}
#region Status
private string _status = "Disconnected";
public string Status
{
get { return _status; }
private set
{
if (_status == value)
return;
_status = value;
RaiseEvent(StatusChanged);
}
}
private ParseDistanceMode _distanceMode = ParseDistanceMode.Absolute;
public ParseDistanceMode DistanceMode
{
get { return _distanceMode; }
private set
{
if (_distanceMode == value)
return;
_distanceMode = value;
RaiseEvent(DistanceModeChanged);
}
}
private ParseUnit _unit = ParseUnit.Metric;
public ParseUnit Unit
{
get { return _unit; }
private set
{
if (_unit == value)
return;
_unit = value;
RaiseEvent(UnitChanged);
}
}
private ArcPlane _plane = ArcPlane.XY;
public ArcPlane Plane
{
get { return _plane; }
private set
{
if (_plane == value)
return;
_plane = value;
RaiseEvent(PlaneChanged);
}
}
private bool _connected = false;
public bool Connected
{
get { return _connected; }
private set
{
if (value == _connected)
return;
_connected = value;
if (!Connected)
Mode = OperatingMode.Disconnected;
RaiseEvent(ConnectionStateChanged);
}
}
private int _bufferState;
public int BufferState
{
get { return _bufferState; }
private set
{
if (_bufferState == value)
return;
_bufferState = value;
RaiseEvent(BufferStateChanged);
}
}
#endregion Status
public bool SyncBuffer { get; set; }
private Stream Connection;
private Thread WorkerThread;
private StreamWriter Log;
private void RecordLog(string message)
{
if (Log != null)
{
try
{
Log.WriteLine(message);
}
catch { throw; }
}
}
public Machine()
{
_calculator = new Calculator(this);
}
Queue Sent = Queue.Synchronized(new Queue());
Queue ToSend = Queue.Synchronized(new Queue());
Queue ToSendPriority = Queue.Synchronized(new Queue()); //contains characters (for soft reset, feed hold etc)
Queue ToSendMacro = Queue.Synchronized(new Queue());
private void Work()
{
try
{
StreamReader reader = new StreamReader(Connection);
StreamWriter writer = new StreamWriter(Connection);
int StatusPollInterval = Properties.Settings.Default.StatusPollInterval;
int ControllerBufferSize = Properties.Settings.Default.ControllerBufferSize;
BufferState = 0;
TimeSpan WaitTime = TimeSpan.FromMilliseconds(0.5);
DateTime LastStatusPoll = DateTime.Now + TimeSpan.FromSeconds(0.5);
DateTime StartTime = DateTime.Now;
DateTime LastFilePosUpdate = DateTime.Now;
bool filePosChanged = false;
bool SendMacroStatusReceived = false;
bool RepeatWrongCode = Properties.Settings.Default.GCodeRepeatWrongCode;
writer.Write("\n$G\n");
writer.Write("\n$#\n");
writer.Flush();
while (true)
{
Task<string> lineTask = reader.ReadLineAsync();
while (!lineTask.IsCompleted)
{
if (!Connected)
{
return;
}
while (ToSendPriority.Count > 0)
{
writer.Write((char)ToSendPriority.Dequeue());
writer.Flush();
}
if (Mode == OperatingMode.SendFile)
{
if (File.Count > FilePosition && (File[FilePosition].Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = File[FilePosition].Replace(" ", ""); // don't send whitespace to machine
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
int index = FilePosition + 1;
send_line += " Line: " + index.ToString();
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
if (PauseLines[FilePosition] && Properties.Settings.Default.PauseFileOnHold)
{
Mode = OperatingMode.Manual;
}
if (++FilePosition >= File.Count)
{
Mode = OperatingMode.Manual;
}
filePosChanged = true;
}
}
else if (Mode == OperatingMode.SendMacro)
{
switch (Status)
{
case "Idle":
if (BufferState == 0 && SendMacroStatusReceived)
{
SendMacroStatusReceived = false;
string send_line = (string)ToSendMacro.Dequeue();
send_line = Calculator.Evaluate(send_line, out bool success);
if (!success)
{
ReportError("Error while evaluating macro!");
ReportError(send_line);
ToSendMacro.Clear();
}
else
{
send_line = send_line.Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
}
break;
case "Run":
case "Hold":
break;
default: // grbl is in some kind of alarm state
ToSendMacro.Clear();
break;
}
if (ToSendMacro.Count == 0)
Mode = OperatingMode.Manual;
}
else if (ToSend.Count > 0 && (((string)ToSend.Peek()).Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = ((string)ToSend.Dequeue()).Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
DateTime Now = DateTime.Now;
if ((Now - LastStatusPoll).TotalMilliseconds > StatusPollInterval)
{
writer.Write('?');
writer.Flush();
LastStatusPoll = Now;
}
//only update file pos every X ms
if (filePosChanged && (Now - LastFilePosUpdate).TotalMilliseconds > 500)
{
RaiseEvent(FilePositionChanged);
LastFilePosUpdate = Now;
filePosChanged = false;
}
Thread.Sleep(WaitTime);
}
string line = lineTask.Result;
RecordLog("< " + line);
if (line == "ok")
{
if (Sent.Count != 0)
{
BufferState -= ((string)Sent.Dequeue()).Length + 1;
}
else
{
Console.WriteLine("Received OK without anything in the Sent Buffer");
BufferState = 0;
}
}
else
{
if (line.StartsWith("error:"))
{
int fileErrorLine = 0;
if (Sent.Count != 0)
{
string errorline = (string)Sent.Dequeue();
RaiseEvent(ReportError, $"{line}: {errorline}");
RecordLog(errorline);
BufferState -= errorline.Length + 1;
if (int.TryParse(errorline.Substring(errorline.IndexOf(":") + 1), out int index))
fileErrorLine = index;
}
else
{
if ((DateTime.Now - StartTime).TotalMilliseconds > 200)
RaiseEvent(ReportError, $"Received <{line}> without anything in the Sent Buffer");
BufferState = 0;
}
Mode = OperatingMode.Manual;
// always returns the position on the error line
if (fileErrorLine > 0)
{
FileGoto(fileErrorLine - 1);
FileError = true;
}
}
else if (line.StartsWith("<"))
{
RaiseEvent(ParseStatus, line);
SendMacroStatusReceived = true;
}
else if (line.StartsWith("[PRB:"))
{
RaiseEvent(ParseProbe, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("["))
{
RaiseEvent(UpdateStatus, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("ALARM"))
{
RaiseEvent(ReportError, line);
Mode = OperatingMode.Manual;
ToSend.Clear();
ToSendMacro.Clear();
}
else if (line.StartsWith("grbl"))
{
RaiseEvent(LineReceived, line);
RaiseEvent(ParseStartup, line);
}
else if (line.Length > 0)
RaiseEvent(LineReceived, line);
if (FileError && FileErrorLastPosition != FilePosition && Status == "Idle")
{
FileError = false;
FileErrorLastPosition = FilePosition;
Sent.Clear();
BufferState = 0;
if (RepeatWrongCode)
FileStart();
}
}
}
}
catch (Exception ex)
{
RaiseEvent(ReportError, $"Fatal Error in Work Loop: {ex.Message}");
RaiseEvent(() => Disconnect());
}
}
public void Connect()
{
if (Connected)
throw new Exception("Can't Connect: Already Connected");
switch (Properties.Settings.Default.ConnectionType)
{
case ConnectionType.Serial:
SerialPort port = new SerialPort(Properties.Settings.Default.SerialPortName, Properties.Settings.Default.SerialPortBaud);
port.DtrEnable = Properties.Settings.Default.SerialPortDTR;
port.Open();
Connection = port.BaseStream;
break;
default:
throw new Exception("Invalid Connection Type");
}
if (Properties.Settings.Default.LogTraffic)
{
try
{
Log = new StreamWriter(Constants.LogFile);
}
catch (Exception e)
{
NonFatalException("could not open logfile: " + e.Message);
}
}
Connected = true;
ToSend.Clear();
ToSendPriority.Clear();
Sent.Clear();
ToSendMacro.Clear();
Mode = OperatingMode.Manual;
if (PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
WorkerThread = new Thread(Work);
WorkerThread.Priority = ThreadPriority.AboveNormal;
WorkerThread.Start();
}
public void Disconnect()
{
if (Log != null)
Log.Close();
Log = null;
Connected = false;
WorkerThread.Join();
try
{
Connection.Close();
}
catch { }
Connection.Dispose();
Connection = null;
Mode = OperatingMode.Disconnected;
MachinePosition = new Vector3();
WorkOffset = new Vector3();
FeedRateRealtime = 0;
CurrentTLO = 0;
if (PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
Status = "Disconnected";
DistanceMode = ParseDistanceMode.Absolute;
Unit = ParseUnit.Metric;
Plane = ArcPlane.XY;
BufferState = 0;
FeedOverride = 100;
RapidOverride = 100;
SpindleOverride = 100;
if (OverrideChanged != null)
OverrideChanged.Invoke();
PinStateLimitX = false;
PinStateLimitY = false;
PinStateLimitZ = false;
PinStateProbe = false;
if (PinStateChanged != null)
PinStateChanged.Invoke();
ToSend.Clear();
ToSendPriority.Clear();
Sent.Clear();
ToSendMacro.Clear();
}
public void SendLine(string line)
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
if (Mode != OperatingMode.Manual && Mode != OperatingMode.Probe)
{
RaiseEvent(Info, "Not in Manual Mode");
return;
}
ToSend.Enqueue(line);
}
public void SoftReset()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
Mode = OperatingMode.Manual;
ToSend.Clear();
ToSendPriority.Clear();
Sent.Clear();
ToSendMacro.Clear();
ToSendPriority.Enqueue((char)0x18);
BufferState = 0;
FeedOverride = 100;
RapidOverride = 100;
SpindleOverride = 100;
if (OverrideChanged != null)
OverrideChanged.Invoke();
SendLine("$G");
SendLine("$#");
}
public void SendMacroLines(params string[] lines)
{
if (Mode != OperatingMode.Manual)
{
RaiseEvent(Info, "Not in Manual Mode");
return;
}
foreach (string line in lines)
ToSendMacro.Enqueue(line.Trim());
Mode = OperatingMode.SendMacro;
}
//probably shouldn't expose this, but adding overrides would be much more effort otherwise
public void SendControl(byte controlchar)
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
ToSendPriority.Enqueue((char)controlchar);
}
public void FeedHold()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
ToSendPriority.Enqueue('!');
}
public void CycleStart()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
ToSendPriority.Enqueue('~');
}
public void JogCancel()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
ToSendPriority.Enqueue((char)0x85);
}
public void SetFile(IList<string> file)
{
if (Mode == OperatingMode.SendFile)
{
RaiseEvent(Info, "Can't change file while active");
return;
}
bool[] pauselines = new bool[file.Count];
for (int line = 0; line < file.Count; line++)
{
var matches = GCodeParser.GCodeSplitter.Matches(file[line]);
foreach (Match m in matches)
{
if (m.Groups[1].Value == "M")
{
int code = int.MinValue;
if (int.TryParse(m.Groups[2].Value, out code))
{
if (code == 0 || code == 1 || code == 2 || code == 30 || code == 6)
pauselines[line] = true;
}
}
}
}
File = new ReadOnlyCollection<string>(file);
PauseLines = new ReadOnlyCollection<bool>(pauselines);
FilePosition = 0;
RaiseEvent(FilePositionChanged);
}
public void ClearFile()
{
if (Mode == OperatingMode.SendFile)
{
RaiseEvent(Info, "Can't change file while active");
return;
}
File = new ReadOnlyCollection<string>(new string[0]);
FilePosition = 0;
RaiseEvent(FilePositionChanged);
}
public void FileStart()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
if (Mode != OperatingMode.Manual)
{
RaiseEvent(Info, "Not in Manual Mode");
return;
}
Mode = OperatingMode.SendFile;
}
public void FilePause()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
if (Mode != OperatingMode.SendFile)
{
RaiseEvent(Info, "Not in SendFile Mode");
return;
}
Mode = OperatingMode.Manual;
}
public void ProbeStart()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
if (Mode != OperatingMode.Manual)
{
RaiseEvent(Info, "Can't start probing while running!");
return;
}
Mode = OperatingMode.Probe;
}
public void ProbeStop()
{
if (!Connected)
{
RaiseEvent(Info, "Not Connected");
return;
}
if (Mode != OperatingMode.Probe)
{
RaiseEvent(Info, "Not in Probe mode");
return;
}
Mode = OperatingMode.Manual;
}
public void FileGoto(int lineNumber)
{
if (Mode == OperatingMode.SendFile)
return;
if (lineNumber >= File.Count || lineNumber < 0)
{
RaiseEvent(NonFatalException, "Line Number outside of file length");
return;
}
FilePosition = lineNumber;
RaiseEvent(FilePositionChanged);
}
public void ClearQueue()
{
if (Mode != OperatingMode.Manual)
{
RaiseEvent(Info, "Not in Manual mode");
return;
}
ToSend.Clear();
}
private static Regex GCodeSplitter = new Regex(@"([GZ])\s*(\-?\d+\.?\d*)", RegexOptions.Compiled);
/// <summary>
/// Updates Status info from each line sent
/// </summary>
/// <param name="line"></param>
private void UpdateStatus(string line)
{
if (!Connected)
return;
if (line.Contains("$J=") || RunningJog) {
RunningJog = false;
return;
}
if (line.StartsWith("[TLO:"))
{
try
{
CurrentTLO = double.Parse(line.Substring(5, line.Length - 6), Constants.DecimalParseFormat);
RaiseEvent(PositionUpdateReceived);
}
catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
return;
}
try
{
//we use a Regex here so G91.1 etc don't get recognized as G91
MatchCollection mc = GCodeSplitter.Matches(line);
for (int i = 0; i < mc.Count; i++)
{
Match m = mc[i];
if (m.Groups[1].Value != "G")
continue;
double code = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
if (code == 17)
Plane = ArcPlane.XY;
if (code == 18)
Plane = ArcPlane.YZ;
if (code == 19)
Plane = ArcPlane.ZX;
if (code == 20)
Unit = ParseUnit.Imperial;
if (code == 21)
Unit = ParseUnit.Metric;
if (code == 90)
DistanceMode = ParseDistanceMode.Absolute;
if (code == 91)
DistanceMode = ParseDistanceMode.Incremental;
if (code == 49)
CurrentTLO = 0;
if (code == 43.1)
{
if (mc.Count > (i + 1))
{
if (mc[i + 1].Groups[1].Value == "Z")
{
CurrentTLO = double.Parse(mc[i + 1].Groups[2].Value, Constants.DecimalParseFormat);
RaiseEvent(PositionUpdateReceived);
}
i += 1;
}
}
}
}
catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
}
private static Regex StatusEx = new Regex(@"(?<=[<|])(\w+):?([^|>]*)?(?=[|>])", RegexOptions.Compiled);
/// <summary>
/// Parses a recevied status report (answer to '?')
/// </summary>
private void ParseStatus(string line)
{
MatchCollection statusMatch = StatusEx.Matches(line);
if (statusMatch.Count == 0)
{
NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line));
return;
}
bool posUpdate = false;
bool overrideUpdate = false;
bool pinStateUpdate = false;
bool resetPins = true;
foreach (Match m in statusMatch)
{
if (m.Index == 1)
{
Status = m.Groups[1].Value;
continue;
}
if (m.Groups[1].Value == "Ov")
{
try
{
string[] parts = m.Groups[2].Value.Split(',');
FeedOverride = int.Parse(parts[0]);
RapidOverride = int.Parse(parts[1]);
SpindleOverride = int.Parse(parts[2]);
overrideUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "WCO")
{
try
{
string OffsetString = m.Groups[2].Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = OffsetString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
OffsetString = string.Join(",", parts);
}
}
WorkOffset = Vector3.Parse(OffsetString);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (SyncBuffer && m.Groups[1].Value == "Bf")
{
try
{
int availableBytes = int.Parse(m.Groups[2].Value.Split(',')[1]);
int used = Properties.Settings.Default.ControllerBufferSize - availableBytes;
if (used < 0)
used = 0;
BufferState = used;
RaiseEvent(Info, $"Buffer State Synced ({availableBytes} bytes free)");
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "Pn")
{
resetPins = false;
string states = m.Groups[2].Value;
bool stateX = states.Contains("X");
if (stateX != PinStateLimitX)
pinStateUpdate = true;
PinStateLimitX = stateX;
bool stateY = states.Contains("Y");
if (stateY != PinStateLimitY)
pinStateUpdate = true;
PinStateLimitY = stateY;
bool stateZ = states.Contains("Z");
if (stateZ != PinStateLimitZ)
pinStateUpdate = true;
PinStateLimitZ = stateZ;
bool stateP = states.Contains("P");
if (stateP != PinStateProbe)
pinStateUpdate = true;
PinStateProbe = stateP;
}
else if (m.Groups[1].Value == "F")
{
try
{
FeedRateRealtime = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "FS")
{
try
{
string[] parts = m.Groups[2].Value.Split(',');
FeedRateRealtime = double.Parse(parts[0], Constants.DecimalParseFormat);
SpindleSpeedRealtime = double.Parse(parts[1], Constants.DecimalParseFormat);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
}
SyncBuffer = false; //only run this immediately after button press
//run this later to catch work offset changes before parsing position
Vector3 NewMachinePosition = MachinePosition;
foreach (Match m in statusMatch)
{
if (m.Groups[1].Value == "MPos" || m.Groups[1].Value == "WPos")
{
try
{
string PositionString = m.Groups[2].Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = PositionString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
PositionString = string.Join(",", parts);
}
}
NewMachinePosition = Vector3.Parse(PositionString);
if (m.Groups[1].Value == "WPos")
NewMachinePosition += WorkOffset;
if (NewMachinePosition != MachinePosition)
{
posUpdate = true;
MachinePosition = NewMachinePosition;
}
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
}
if (posUpdate && Connected && PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
if (overrideUpdate && Connected && OverrideChanged != null)
OverrideChanged.Invoke();
if (resetPins) //no pin state received in status -> all zero
{
pinStateUpdate = PinStateLimitX | PinStateLimitY | PinStateLimitZ | PinStateProbe; //was any pin set before
PinStateLimitX = false;
PinStateLimitY = false;
PinStateLimitZ = false;
PinStateProbe = false;
}
if (pinStateUpdate && Connected && PinStateChanged != null)
PinStateChanged.Invoke();
if (Connected && StatusReceived != null)
StatusReceived.Invoke(line);
}
private static Regex ProbeEx = new Regex(@"\[PRB:(?'Pos'\-?[0-9\.]*(?:,\-?[0-9\.]*)+):(?'Success'0|1)\]", RegexOptions.Compiled);
/// <summary>
/// Parses a recevied probe report
/// </summary>
private void ParseProbe(string line)
{
if (ProbeFinished == null)
return;
Match probeMatch = ProbeEx.Match(line);
Group pos = probeMatch.Groups["Pos"];
Group success = probeMatch.Groups["Success"];
if (!probeMatch.Success || !(pos.Success & success.Success))
{
NonFatalException.Invoke($"Received Bad Probe: '{line}'");
return;
}
string PositionString = pos.Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = PositionString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
PositionString = string.Join(",", parts);
}
}
Vector3 ProbePos = Vector3.Parse(PositionString);
LastProbePosMachine = ProbePos;
ProbePos -= WorkOffset;
LastProbePosWork = ProbePos;
bool ProbeSuccess = success.Value == "1";
ProbeFinished.Invoke(ProbePos, ProbeSuccess);
}
private static Regex StartupRegex = new Regex("grbl v([0-9])\\.([0-9])([a-z])");
private void ParseStartup(string line)
{
Match m = StartupRegex.Match(line);
int major, minor;
char rev;
if (!m.Success ||
!int.TryParse(m.Groups[1].Value, out major) ||
!int.TryParse(m.Groups[2].Value, out minor) ||
!char.TryParse(m.Groups[3].Value, out rev))
{
RaiseEvent(Info, "Could not parse startup message.");
return;
}
Version v = new Version(major, minor, (int)rev);
if (v < Constants.MinimumGrblVersion)
{
ReportError("Outdated version of grbl detected!");
ReportError($"Please upgrade to at least grbl v{Constants.MinimumGrblVersion.Major}.{Constants.MinimumGrblVersion.Minor}{(char)Constants.MinimumGrblVersion.Build}");
}
}
/// <summary>
/// Reports error. This is there to offload the ExpandError function from the "Real-Time" worker thread to the application thread
/// also used for alarms
/// </summary>
private void ReportError(string error)
{
if (NonFatalException != null)
NonFatalException.Invoke(GrblCodeTranslator.ExpandError(error));
}
private void RaiseEvent(Action<string> action, string param)
{
if (action == null)
return;
Application.Current.Dispatcher.BeginInvoke(action, param);
}
private void RaiseEvent(Action action)
{
if (action == null)
return;
Application.Current.Dispatcher.BeginInvoke(action);
}
}
}
| 22.946122 | 169 | 0.62062 | [
"MIT"
] | zsmisek/OpenCNCPilot | OpenCNCPilot/Communication/Machine.cs | 28,111 | C# |
using System.Collections;
using Improbable.Gdk.Core;
using UnityEditor;
using UnityEngine;
namespace Fps.Editor
{
public class MapBuilderVisualisationWindow : EditorWindow
{
private const int WarnTilesThreshold = 2500;
private int layerCount = 4;
private string seed = "SpatialOS GDK for Unity";
private MapBuilder mapBuilder;
private MapBuilderSettings mapBuilderSettings;
private const string MapBuilderMenuItem = "SpatialOS/Map Builder";
private const int MapBuilderMenuPriority = 52;
[MenuItem(MapBuilderMenuItem, false, MapBuilderMenuPriority)]
private static void LaunchMapBuilderMenu()
{
// Show existing window instance. If one doesn't exist, make one.
var inspectorWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.InspectorWindow");
var deploymentWindow = GetWindow<MapBuilderVisualisationWindow>(inspectorWindowType);
deploymentWindow.titleContent.text = "Map Builder Visualisation";
deploymentWindow.titleContent.tooltip = "A tool for visualising the level to be generated at runtime.";
deploymentWindow.Show();
}
private void SetupMapBuilder()
{
mapBuilder = new MapBuilder(mapBuilderSettings, new GameObject("FPS-Level_Visualisation"));
}
public void OnGUI()
{
layerCount = Mathf.Max(0,
EditorGUILayout.IntField(new GUIContent(
"Number of Tile Layers",
"N layers corresponds to 4*(N^2) tiles."), layerCount));
var numTiles = Mathf.RoundToInt(GetTotalTilesFromLayers(layerCount));
GUI.color = numTiles < WarnTilesThreshold ? Color.white : Color.yellow;
GUILayout.Label($"Number of tiles to generate: ~{numTiles}");
GUI.color = Color.white;
seed = EditorGUILayout.TextField(new GUIContent(
"Seed for Map Generator",
"Different seeds produce different maps."),
seed);
mapBuilderSettings = (MapBuilderSettings) EditorGUILayout.ObjectField(new GUIContent(
"Map Builder Settings",
"Different seeds produce different maps."),
mapBuilderSettings,
typeof(MapBuilderSettings),
false);
EditorGUI.BeginDisabledGroup(mapBuilderSettings == null);
if (GUILayout.Button("Generate Map"))
{
if (numTiles < WarnTilesThreshold
|| GetGenerationUserConfirmation(numTiles))
{
if (mapBuilder == null || mapBuilder.InvalidMapBuilder)
{
SetupMapBuilder();
}
var volumesPrefab = mapBuilderSettings.WorldTileVolumes == null
? null
: Instantiate(mapBuilderSettings.WorldTileVolumes);
UnwindCoroutine(mapBuilder.CleanAndBuild(layerCount, seed));
if (volumesPrefab != null)
{
UnityObjectDestroyer.Destroy(volumesPrefab);
}
}
}
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(mapBuilder == null);
if (GUILayout.Button("Clear Map"))
{
mapBuilder.Clean();
}
EditorGUI.EndDisabledGroup();
}
private bool GetGenerationUserConfirmation(int numTiles)
{
return EditorUtility.DisplayDialog("Generate Map Confirmation",
$"You are generating {numTiles} tiles. This can potentially take a VERY long time, " +
"and it is recommended that you save first!\n" +
"Do you wish to continue?",
"Continue",
"Cancel");
}
private int GetTotalTilesFromLayers(int layers)
{
return Mathf.RoundToInt(Mathf.Pow(layers * 2, 2));
}
private void UnwindCoroutine(IEnumerator enumerator)
{
while (enumerator.MoveNext())
{
if (enumerator.Current is IEnumerator nestedEnumerator)
{
UnwindCoroutine(nestedEnumerator);
}
}
}
}
}
| 36.104839 | 115 | 0.569131 | [
"MIT"
] | Dechichi01/gdk-for-unity-fps-starter-project | workers/unity/Assets/Fps/Scripts/Editor/MapBuilderVisualisationWindow.cs | 4,477 | C# |
namespace WinUX.Xaml.VisualStateTriggers.MaxWindowWidthTrigger
{
using Windows.UI.Core;
using Windows.UI.Xaml;
/// <summary>
/// Defines a visual state trigger that checks whether a condition is met within a specified max window width.
/// </summary>
/// <remarks>
/// This is useful where the standard AdaptiveTrigger doesn't meet needs of combining a boolean condition with the window width.
/// </remarks>
public sealed partial class MaxWindowWidthTrigger : VisualStateTriggerBase
{
/// <summary>
/// Initializes a new instance of the <see cref="MaxWindowWidthTrigger"/> class.
/// </summary>
public MaxWindowWidthTrigger()
{
Window.Current.SizeChanged += this.Window_OnSizeChanged;
}
private void Window_OnSizeChanged(object sender, WindowSizeChangedEventArgs args)
{
if (args != null)
{
this.CheckTriggerState(this.Trigger, args.Size.Width);
}
}
private void OnTriggerChanged(bool trigger)
{
this.CheckTriggerState(trigger, this.WindowWidth);
}
private void CheckTriggerState(bool trigger, double windowWidth)
{
var withinWindowBounds = this.MaxWindowWidth >= windowWidth;
this.IsActive = trigger && withinWindowBounds;
}
}
} | 33.333333 | 132 | 0.630714 | [
"MIT"
] | lindexi/WinUX-UWP-Toolkit | WinUX.UWP.Xaml/VisualStateTriggers/MaxWindowWidthTrigger/MaxWindowWidthTrigger.cs | 1,402 | C# |
// Generated class v2.14.0.0, can be modified
namespace NHtmlUnit.Javascript.Host.Geo
{
public partial class Position
{
}
}
| 13.272727 | 46 | 0.643836 | [
"Apache-2.0"
] | HtmlUnit/NHtmlUnit | app/NHtmlUnit/NonGenerated/Javascript/Host/Geo/Position.cs | 146 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.Data.Entity.AzureTableStorage.Adapters;
using Microsoft.Data.Entity.AzureTableStorage.Query;
using Microsoft.Data.Entity.AzureTableStorage.Requests;
using Microsoft.Data.Entity.ChangeTracking;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Query;
using Microsoft.Data.Entity.Utilities;
using Microsoft.Framework.Logging;
using Moq;
using Xunit;
namespace Microsoft.Data.Entity.AzureTableStorage.Tests.Query
{
public class QueryCachingTests
{
private readonly Mock<AtsConnection> _connection;
private readonly AtsDataStore _dataStore;
public QueryCachingTests()
{
_connection = new Mock<AtsConnection>();
_connection
.Setup(s => s.ExecuteRequest(It.IsAny<TableRequest<bool>>(), It.IsAny<ILogger>()))
.Returns(false); // keep all requests in memory
var configuration = new Mock<DbContextConfiguration>();
configuration.SetupGet(s => s.Connection).Returns(_connection.Object);
configuration.SetupGet(s => s.Model).Returns(CreateModel());
configuration.SetupGet(s => s.StateManager).Returns(new Mock<StateManager>().Object);
configuration.SetupGet(s => s.Services.EntityKeyFactorySource).Returns(new Mock<EntityKeyFactorySource>().Object);
configuration.SetupGet(s => s.Services.StateEntryFactory).Returns(new Mock<StateEntryFactory>().Object);
configuration.SetupGet(s => s.Services.EntityMaterializerSource).Returns(new Mock<EntityMaterializerSource>().Object);
configuration.SetupGet(s => s.Services.ClrCollectionAccessorSource).Returns(new Mock<ClrCollectionAccessorSource>().Object);
configuration.SetupGet(s => s.Services.ClrPropertySetterSource).Returns(new Mock<ClrPropertySetterSource>().Object);
_dataStore = new AtsDataStore(
Mock.Of<StateManager>(),
new LazyRef<IModel>(CreateModel),
Mock.Of<EntityKeyFactorySource>(),
Mock.Of<EntityMaterializerSource>(),
Mock.Of<ClrCollectionAccessorSource>(),
Mock.Of<ClrPropertySetterSource>(),
_connection.Object,
new AtsQueryFactory(new AtsValueReaderFactory()),
new TableEntityAdapterFactory(),
new LazyRef<DbContext>(() => null),
new LoggerFactory());
}
[Fact]
public void Multiple_identical_queries()
{
AssertQuery<Customer>(Times.Once(), cs =>
(from c in cs
orderby cs.Any(c2 => c2.CustomerID == c.CustomerID)
select c).AsNoTracking());
}
private void AssertQuery<T>(Times times, Expression<Func<DbSet<T>, IQueryable>> expression) where T : class, new()
{
var query = expression.Compile()(new DbSet<T>(Mock.Of<DbContext>()));
var queryModel = new EntityQueryProvider(new EntityQueryExecutor(Mock.Of<DbContext>(), new LazyRef<ILoggerFactory>(new LoggerFactory()))).GenerateQueryModel(query.Expression);
_connection.Setup(s => s.ExecuteRequest(
It.IsAny<QueryTableRequest<T>>(),
It.IsAny<ILogger>()))
.Returns(NewTCallback<T>);
_dataStore.Query<T>(queryModel).ToList();
_connection.Verify(s => s.ExecuteRequest(
It.IsAny<QueryTableRequest<T>>(),
It.IsAny<ILogger>()),
times);
}
private static T[] NewTCallback<T>() where T : class, new()
{
return new[] { new T() };
}
private IModel CreateModel()
{
var model = new Model();
var builder = new BasicModelBuilder(model);
builder.Entity<Customer>().Property(s => s.CustomerID);
return model;
}
internal class Customer
{
public string CustomerID { get; set; }
}
}
}
| 41.625 | 187 | 0.632017 | [
"Apache-2.0"
] | matteo-mosca-easydom/EntityFramework | test/EntityFramework.AzureTableStorage.Tests/Query/QueryCachingTests.cs | 4,329 | C# |
using PlayersAndMonsters.Repositories.Contracts;
namespace PlayersAndMonsters.Models.Players.PlayerModels
{
public class Beginner : Player
{
private const int INITIAL_HEALTH_POINTS = 50;
public Beginner(ICardRepository cardRepository, string username)
: base(cardRepository, username, INITIAL_HEALTH_POINTS)
{
}
}
} | 26.714286 | 72 | 0.703209 | [
"MIT"
] | danstoyanov/CSharp-Advanced-Tasks | 02 - [CSharp OOP]/[CSharp OOP - Exams]/06 - [C# OOP Basics Exam Retake - 19 April 2019]/PlayersAndMonsters/Models/Players/PlayerModels/Beginner.cs | 376 | C# |
using SC2APIProtocol;
using SC2Sharp.Agents;
using SC2Sharp.Builds.BuildLists;
using SC2Sharp.Managers;
using SC2Sharp.Micro;
using SC2Sharp.StrategyAnalysis;
using SC2Sharp.Tasks;
namespace SC2Sharp.Builds.Protoss
{
public class TwoBaseRoboPvT : Build
{
private TimingAttackTask attackTask = new TimingAttackTask() { RequiredSize = 35, RetreatSize = 12 };
private TimingAttackTask PokeTask = new TimingAttackTask() { RequiredSize = 10 };
private WorkerScoutTask WorkerScoutTask = new WorkerScoutTask() { StartFrame = 600 };
private DefenseTask defenseTask = new DefenseTask() { ExpandDefenseRadius = 18 };
private bool Attacking = false;
public bool DefendMech = false;
private bool SmellCheese = false;
public override string Name()
{
return "TwoBaseRobo";
}
public override void OnStart(Bot bot)
{
bot.TaskManager.Add(defenseTask);
bot.TaskManager.Add(attackTask);
bot.TaskManager.Add(WorkerScoutTask);
bot.TaskManager.Add(new ObserverScoutTask());
if (bot.BaseManager.Pocket != null)
bot.TaskManager.Add(new ScoutProxyTask(bot.BaseManager.Pocket.BaseLocation.Pos));
bot.TaskManager.Add(new AdeptKillSquadTask());
bot.TaskManager.Add(new ElevatorChaserTask());
MicroControllers.Add(new StalkerController());
MicroControllers.Add(new StutterController());
MicroControllers.Add(new ColloxenController());
Set += ProtossBuildUtil.Pylons();
Set += NaturalDefenses();
Set += BuildStargatesAgainstLifters();
Set += Nexii();
foreach (Base b in bot.BaseManager.Bases)
if (b != Main && b != Natural)
Set += ExpansionDefenses(b);
Set += MainBuild();
}
private BuildList NaturalDefenses()
{
BuildList result = new BuildList();
result.If(() => { return SmellCheese && Count(UnitTypes.ADEPT) >= 10; });
result.Building(UnitTypes.FORGE);
result.If(() => { return Attacking; });
result.Building(UnitTypes.PHOTON_CANNON, Main, MainDefensePos, 4);
return result;
}
private BuildList BuildStargatesAgainstLifters()
{
BuildList result = new BuildList();
result.If(() => { return Lifting.Get().Detected; });
result += new BuildingStep(UnitTypes.GATEWAY);
result += new BuildingStep(UnitTypes.ASSIMILATOR);
result += new BuildingStep(UnitTypes.CYBERNETICS_CORE);
result += new BuildingStep(UnitTypes.ASSIMILATOR);
result += new BuildingStep(UnitTypes.STARGATE, 2);
return result;
}
private BuildList Nexii()
{
BuildList result = new BuildList();
result.If(() => { return Count(UnitTypes.GATEWAY) >= 2 && (!SmellCheese || Count(UnitTypes.ADEPT) + Count(UnitTypes.STALKER) >= 8); });
result.Building(UnitTypes.NEXUS, 2);
result.If(() => { return Attacking; });
result.Building(UnitTypes.NEXUS);
return result;
}
private BuildList ExpansionDefenses(Base expansion)
{
BuildList result = new BuildList();
result.If(() => { return expansion.Owner == Bot.Main.PlayerId; });
result.Building(UnitTypes.FORGE);
result.Building(UnitTypes.PYLON, expansion);
result.If(() => { return Completed(expansion, UnitTypes.PYLON) > 0; });
result.Building(UnitTypes.PHOTON_CANNON, expansion);
return result;
}
private BuildList MainBuild()
{
BuildList result = new BuildList();
Point2D shieldBatteryPos = Bot.Main.MapAnalyzer.Walk(NaturalDefensePos, Bot.Main.MapAnalyzer.EnemyDistances, 3);
result.Building(UnitTypes.PYLON);
result.Building(UnitTypes.GATEWAY);
result.Building(UnitTypes.ASSIMILATOR);
result.Building(UnitTypes.CYBERNETICS_CORE);
result.Building(UnitTypes.PYLON, Natural, NaturalDefensePos, () => { return !SmellCheese; });
result.Building(UnitTypes.PYLON, 2, () => { return Minerals() >= 350; });
result.Building(UnitTypes.GATEWAY);
result.Building(UnitTypes.GATEWAY, () => { return SmellCheese; });
result.Building(UnitTypes.SHIELD_BATTERY, Main, MainDefensePos, 2, () => { return SmellCheese; });
result.If(() => { return Count(UnitTypes.NEXUS) >= 2; });
result.Building(UnitTypes.GATEWAY, () => { return !SmellCheese; });
result.Building(UnitTypes.SHIELD_BATTERY, Natural, shieldBatteryPos, () => { return !SmellCheese; });
result.Building(UnitTypes.ASSIMILATOR, 3);
result.If(() => { return Count(UnitTypes.ADEPT) + Count(UnitTypes.STALKER) >= 10; });
result.Building(UnitTypes.PYLON);
result.Building(UnitTypes.PYLON, Natural);
result.Building(UnitTypes.ROBOTICS_FACILITY);
result.Building(UnitTypes.TWILIGHT_COUNSEL);
result.Building(UnitTypes.PYLON, 2);
result.Building(UnitTypes.ROBOTICS_BAY, () => { return !DefendMech; });
result.Building(UnitTypes.GATEWAY);
result.Building(UnitTypes.PYLON, Natural);
result.Building(UnitTypes.ROBOTICS_FACILITY, () => { return Count(UnitTypes.COLOSUS) > 0; });
result.Building(UnitTypes.PYLON, Natural);
result.Building(UnitTypes.PYLON, Natural);
return result;
}
public override void OnFrame(Bot bot)
{
if (Count(UnitTypes.ZEALOT) + Count(UnitTypes.ADEPT) + Count(UnitTypes.STALKER) + Count(UnitTypes.COLOSUS) + Count(UnitTypes.IMMORTAL) >= attackTask.RequiredSize)
Attacking = true;
if (FourRax.Get().Detected
|| (bot.Frame >= 22.4 * 85 && !bot.EnemyStrategyAnalyzer.NoProxyTerranConfirmed && bot.TargetManager.PotentialEnemyStartLocations.Count == 1)
|| ReaperRush.Get().Detected)
{
SmellCheese = true;
defenseTask.MainDefenseRadius = 21;
}
if (!TerranTech.Get().DetectedPreviously
&& (ReaperRush.Get().DetectedPreviously || FourRax.Get().DetectedPreviously))
SmellCheese = true;
if (bot.EnemyRace == Race.Zerg && !PokeTask.Stopped)
{
if (bot.EnemyStrategyAnalyzer.Count(UnitTypes.ZERGLING) >= 10
|| bot.EnemyStrategyAnalyzer.Count(UnitTypes.SPINE_CRAWLER) >= 2
|| bot.EnemyStrategyAnalyzer.Count(UnitTypes.ROACH) >= 5)
{
PokeTask.Stopped = true;
PokeTask.Clear();
}
}
if (SmellCheese)
{
attackTask.RequiredSize = 15;
attackTask.RetreatSize = 8;
}
if (SmellCheese && Completed(UnitTypes.ADEPT) < 8)
{
foreach (Agent agent in bot.UnitManager.Agents.Values)
if (agent.Unit.UnitType == UnitTypes.NEXUS
&& agent.Unit.BuildProgress < 0.99)
agent.Order(Abilities.CANCEL);
}
if (Bio.Get().Detected)
DefendMech = false;
else if (Mech.Get().Detected)
DefendMech = true;
else if (Bio.Get().DetectedPreviously)
DefendMech = false;
else if (Mech.Get().DetectedPreviously)
DefendMech = true;
else DefendMech = false;
}
public override void Produce(Bot bot, Agent agent)
{
if (Count(UnitTypes.PROBE) >= 24
&& Count(UnitTypes.NEXUS) < 2
&& Minerals() < 450)
return;
if (agent.Unit.UnitType == UnitTypes.NEXUS
&& Minerals() >= 50
&& Count(UnitTypes.PROBE) < 44 - Completed(UnitTypes.ASSIMILATOR)
&& (Count(UnitTypes.NEXUS) >= 2 || Count(UnitTypes.PROBE) < 18 + 2 * Completed(UnitTypes.ASSIMILATOR)))
{
if (Count(UnitTypes.PROBE) < 13 || Count(UnitTypes.PYLON) > 0)
agent.Order(1006);
}
else if (agent.Unit.UnitType == UnitTypes.GATEWAY)
{
if (SmellCheese)
{
if (Count(UnitTypes.ADEPT) >= 15 && Count(UnitTypes.NEXUS) < 2)
return;
}
else
{
if (Attacking && Count(UnitTypes.NEXUS) < 3)
return;
}
if (Completed(UnitTypes.CYBERNETICS_CORE) == 0)
return;
if (Count(UnitTypes.STALKER) + Count(UnitTypes.ADEPT) >= 20
&& Count(UnitTypes.ROBOTICS_FACILITY) == 0)
return;
if (Count(UnitTypes.STALKER) + Count(UnitTypes.ADEPT) >= 23
&& Count(UnitTypes.ROBOTICS_BAY) == 0 && !DefendMech)
return;
if (Count(UnitTypes.STALKER) + Count(UnitTypes.ADEPT) >= 25
&& Count(UnitTypes.COLOSUS) + Count(UnitTypes.IMMORTAL) == 0)
return;
int extraAdepts;
if (SmellCheese)
extraAdepts = 15;
else
extraAdepts = 12;
if (Minerals() >= 100
&& Gas() >= 25
&& (!DefendMech || SmellCheese || Count(UnitTypes.ADEPT) < 2)
&& Count(UnitTypes.ADEPT) - extraAdepts < Count(UnitTypes.STALKER))
agent.Order(922);
else if (Minerals() >= 125
&& Gas() >= 50)
agent.Order(917);
return;
}
else if (agent.Unit.UnitType == UnitTypes.ROBOTICS_FACILITY)
{
if (Attacking && Count(UnitTypes.NEXUS) < 3)
return;
if (Count(UnitTypes.OBSERVER) == 0
&& Minerals() >= 25
&& Gas() >= 75)
{
agent.Order(977);
}
else if (Completed(UnitTypes.ROBOTICS_BAY) > 0
&& Minerals() >= 300
&& Gas() >= 200
&& !DefendMech)
{
agent.Order(978);
}
else if (Minerals() >= 250
&& Gas() >= 100
&& DefendMech)
{
agent.Order(979);
}
}
else if (agent.Unit.UnitType == UnitTypes.ROBOTICS_BAY)
{
if (Minerals() >= 150
&& Gas() >= 150
&& !Bot.Main.Observation.Observation.RawData.Player.UpgradeIds.Contains(50)
&& !DefendMech
&& Count(UnitTypes.COLOSUS) > 0)
{
agent.Order(1097);
}
}
else if (agent.Unit.UnitType == UnitTypes.TWILIGHT_COUNSEL)
{
if (!Bot.Main.Observation.Observation.RawData.Player.UpgradeIds.Contains(130)
&& Minerals() >= 100
&& Gas() >= 100
&& !DefendMech)
agent.Order(1594);
else if (!Bot.Main.Observation.Observation.RawData.Player.UpgradeIds.Contains(87)
&& Minerals() >= 150
&& Gas() >= 150)
agent.Order(1593);
}
else if (agent.Unit.UnitType == UnitTypes.STARGATE
&& Minerals() >= 250
&& Gas() >= 150
&& FoodUsed() + 4 <= 200)
agent.Order(950);
}
}
}
| 40.503311 | 174 | 0.518476 | [
"MIT"
] | SimonPrins/TyrSc2 | Tyr/Builds/Protoss/TwoBaseRoboPvT.cs | 12,234 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HTLLBB.Services
{
public interface IEmailSender
{
Task SendEmailAsync(string email, string subject, string message);
}
}
| 20.153846 | 75 | 0.706107 | [
"MIT"
] | BestFriendForever/HTLLBB | src/Services/IEmailSender.cs | 264 | C# |
//-----------------------------------------------------------------------
// <copyright company="Sherlock">
// Copyright 2013 Sherlock. Licensed under the Apache License, Version 2.0.
// </copyright>
//-----------------------------------------------------------------------
using System;
namespace Sherlock.Shared.DataAccess
{
/// <content>
/// Defines the public API part for the test step parameter class.
/// </content>
[Serializable]
public sealed partial class TestStepParameter
{
/// <summary>
/// Gets or sets a value indicating whether the object is currently undergoing patching, i.e.
/// adding all values from the database.
/// </summary>
internal bool IsPatching
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the object has been patched, i.e. all values have been
/// extracted from the database, or not.
/// </summary>
internal bool IsPatched
{
get;
set;
}
/// <summary>
/// Gets the ID of the test step parameter.
/// </summary>
public int Id
{
get
{
return pk_TestStepParameterId;
}
}
/// <summary>
/// Gets or sets the ID of the test step that the current parameter is linked to.
/// </summary>
public int TestStepId
{
get
{
return fk_TestStepId;
}
set
{
fk_TestStepId = value;
}
}
}
}
| 26.815385 | 107 | 0.44062 | [
"Apache-2.0"
] | pvandervelde/Sherlock | src/shared.dataaccess/TestStepParameter.Public.cs | 1,745 | C# |
//-------------------------------------------------------------------------
// Copyright © 2020 Province of British Columbia
//
// 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 Keycloak.Authorization
{
/// <summary>Keycloak Service URL Constant template Url paths... well known Urls.</summary>
public static class ServiceUrlConstants
{
/// <summary>The path to the authorization endpoint.</summary>
public const string AuthPath = "/realms/{realm-name}/protocol/openid-connect/auth";
/// <summary>The path to the token endpoint.</summary>
public const string TokenPath = "/realms/{realm-name}/protocol/openid-connect/token";
/// <summary>The path to the token logout endpoint.</summary>
public const string TokenServiceLogoutPath = "/realms/{realm-name}/protocol/openid-connect/logout";
/// <summary>The path to the account endpoint.</summary>
public const string AccountServicePath = "/realms/{realm-name}/account";
/// <summary>The path to the realm info endpoint.</summary>
public const string RealmInfoPath = "/realms/{realm-name}";
/// <summary>The path to the clients management register node endpoint.</summary>
public const string ClientsManagementRegisterNodePath = "/realms/{realm-name}/clients-managements/register-node";
/// <summary>The path to the clients management unregister node endpoint.</summary>
public const string ClientsManagementUnRegisterNodePath = "/realms/{realm-name}/clients-managements/unregister-node";
/// <summary>The path to the JWKS endpoint.</summary>
public const string JwksUrl = "/realms/{realm-name}/protocol/openid-connect/certs";
/// <summary>The path to the openid discovery configuration endpoint.</summary>
public const string DiscoveryUrl = "/realms/{realm-name}/.well-known/openid-configuration";
/// <summary>The path to the UMA 2.0 discovery configuration endpoint.</summary>
public const string Uma2DiscoveryUrl = "/realms/{realm-name}/.well-known/uma2-configuration";
}
} | 52.843137 | 125 | 0.672727 | [
"Apache-2.0"
] | bradhead/Keycloak-AuthZClient-DotNetCore | sdk/src/Authorization/Constants/ServiceUrlConstants.cs | 2,696 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Newtonsoft.Json.Linq;
#nullable enable
namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage.MessageInterception
{
/// <summary>
/// Contains an updated message token and a signal of whether the document Uri was changed.
/// </summary>
public struct InterceptionResult
{
public InterceptionResult(JToken? newToken, bool changedDocumentUri)
{
UpdatedToken = newToken;
ChangedDocumentUri = changedDocumentUri;
}
public JToken? UpdatedToken { get; }
public bool ChangedDocumentUri { get; }
}
}
| 30.76 | 111 | 0.695709 | [
"Apache-2.0"
] | Chatina73/AspNetCore-Tooling | src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/MessageInterception/InterceptionResult.cs | 771 | C# |
using System.Collections.Generic;
namespace Parser
{
internal static class Tokenizer
{
private static readonly HashSet<char> WHITESPACE = new HashSet<char>() { ' ', '\r', '\n', '\t' };
private static Dictionary<char, bool> IDENTIFIER_CHARS_CACHE = new Dictionary<char, bool>();
private static bool IsIdentifierCharImpl(char c)
{
switch (c)
{
case '$':
case '_':
return true;
default:
switch (Common.Localization.CharSetDetector.GetCharType(c))
{
case Common.Localization.CharType.ACCENTED:
case Common.Localization.CharType.LETTER:
case Common.Localization.CharType.NUMBER:
case Common.Localization.CharType.KANJI:
case Common.Localization.CharType.HIRAGANA:
case Common.Localization.CharType.KATAKANA:
return true;
default:
return false;
}
}
}
public static bool IsIdentifierChar(char c)
{
bool result;
if (!IDENTIFIER_CHARS_CACHE.TryGetValue(c, out result))
{
result = IsIdentifierCharImpl(c);
IDENTIFIER_CHARS_CACHE[c] = result;
}
return result;
}
private enum TokenMode
{
NORMAL,
COMMENT,
WORD,
STRING,
}
public static Token[] Tokenize(FileScope file)
{
Common.Localization.Locale locale = file.CompilationScope.Locale;
string code = file.Content;
// Add a newline and a dummy character at the end.
// Set the length equal to the code with the newline but without the null terminator.
// This makes dereferencing the index + 1 code simpler and all makes the check for the end
// of word tokens and single-line comments easy.
code += "\n\0";
int length = code.Length - 1;
int[] lineByIndex = new int[code.Length];
int[] colByIndex = new int[code.Length];
char c;
int line = 0;
int col = 0;
for (int i = 0; i < code.Length; ++i)
{
c = code[i];
lineByIndex[i] = line;
colByIndex[i] = col;
if (c == '\n')
{
++line;
col = -1;
}
++col;
}
List<Token> tokens = new List<Token>();
TokenMode mode = TokenMode.NORMAL;
char modeSubtype = ' ';
int tokenStart = 0;
string tokenValue;
char c2;
bool isTokenEnd = false;
bool stringIsRaw = false;
for (int i = 0; i < length; ++i)
{
c = code[i];
switch (mode)
{
case TokenMode.COMMENT:
if (modeSubtype == '*')
{
if (c == '*' && code[i + 1] == '/')
{
++i;
mode = TokenMode.NORMAL;
}
}
else
{
if (c == '\n')
{
mode = TokenMode.NORMAL;
}
}
break;
case TokenMode.NORMAL:
if (WHITESPACE.Contains(c))
{
// do nothing
}
else if (c == '/' && (code[i + 1] == '/' || code[i + 1] == '*'))
{
mode = TokenMode.COMMENT;
modeSubtype = code[++i];
}
else if (IsIdentifierChar(c))
{
tokenStart = i;
mode = TokenMode.WORD;
}
else if (c == '"' | c == '\'')
{
tokenStart = i;
mode = TokenMode.STRING;
modeSubtype = c;
stringIsRaw = tokens.Count > 0 && tokens[tokens.Count - 1].Value == "@";
}
else
{
if (c == '.')
{
c2 = code[i + 1];
if (c2 >= '0' && c2 <= '9')
{
mode = TokenMode.WORD;
tokenStart = i++;
}
}
if (mode == TokenMode.NORMAL)
{
tokens.Add(new Token(c.ToString(), TokenType.PUNCTUATION, file, lineByIndex[i], colByIndex[i]));
}
}
break;
case TokenMode.STRING:
if (c == modeSubtype)
{
tokenValue = code.Substring(tokenStart, i - tokenStart + 1);
tokens.Add(new Token(tokenValue, TokenType.STRING, file, lineByIndex[i], colByIndex[i]));
mode = TokenMode.NORMAL;
}
else if (!stringIsRaw && c == '\\')
{
++i;
}
break;
case TokenMode.WORD:
isTokenEnd = false;
if (IsIdentifierChar(c))
{
// do nothing
}
else if (c == '.')
{
if (code[tokenStart] >= '0' && code[tokenStart] <= '9')
{
// do nothing
}
else
{
isTokenEnd = true;
}
}
else
{
isTokenEnd = true;
}
if (isTokenEnd)
{
tokenValue = code.Substring(tokenStart, i - tokenStart);
c = tokenValue[0];
TokenType type = TokenType.WORD;
if ((c >= '0' && c <= '9') || c == '.')
{
type = TokenType.NUMBER;
}
else if (!locale.Keywords.IsValidVariable(tokenValue))
{
type = TokenType.KEYWORD;
}
tokens.Add(new Token(tokenValue, type, file, lineByIndex[tokenStart], colByIndex[tokenStart]));
mode = TokenMode.NORMAL;
--i;
}
break;
}
}
switch (mode)
{
case TokenMode.COMMENT:
throw new ParserException(file, "There is an unclosed comment in this file.");
case TokenMode.STRING:
throw new ParserException(file, "There is an unclosed string in this file.");
case TokenMode.WORD:
throw new System.InvalidOperationException();
default:
break;
}
return tokens.ToArray();
}
}
}
| 37.017167 | 129 | 0.32858 | [
"MIT"
] | blakeohare/crayon | Compiler/Parser/Tokenizer.cs | 8,627 | C# |
using System.CodeDom.Compiler;
using System.Threading;
using System.Threading.Tasks;
//------------------------------------------------------------------------------
// This code was auto-generated by ApiGenerator 2.0.121.412.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
namespace Demo.Api.Generated.Contracts.Users
{
/// <summary>
/// Domain Interface for RequestHandler.
/// Description: Update gender on a user.
/// Operation: UpdateMyTestGender.
/// Area: Users.
/// </summary>
[GeneratedCode("ApiGenerator", "2.0.121.412")]
public interface IUpdateMyTestGenderHandler
{
/// <summary>
/// Execute method.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="cancellationToken">The cancellation token.</param>
Task<UpdateMyTestGenderResult> ExecuteAsync(UpdateMyTestGenderParameters parameters, CancellationToken cancellationToken = default);
}
} | 38.344828 | 140 | 0.58723 | [
"MIT"
] | atc-net/atc-rest-api-generator-cli | sample/src/Demo.Api.Generated/Contracts/Users/Interfaces/IUpdateMyTestGenderHandler.cs | 1,114 | 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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class ProjectState
{
private readonly ProjectInfo _projectInfo;
private readonly HostLanguageServices _languageServices;
private readonly SolutionServices _solutionServices;
/// <summary>
/// The documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for
/// <see cref="GetChecksumAsync(CancellationToken)"/>.
/// </summary>
private readonly ImmutableSortedDictionary<DocumentId, DocumentState> _documentStates;
/// <summary>
/// The additional documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for
/// <see cref="GetChecksumAsync(CancellationToken)"/>.
/// </summary>
private readonly ImmutableSortedDictionary<DocumentId, TextDocumentState> _additionalDocumentStates;
/// <summary>
/// The analyzer config documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for
/// <see cref="GetChecksumAsync(CancellationToken)"/>.
/// </summary>
private readonly ImmutableSortedDictionary<DocumentId, AnalyzerConfigDocumentState> _analyzerConfigDocumentStates;
private readonly ImmutableList<DocumentId> _documentIds;
private readonly ImmutableList<DocumentId> _additionalDocumentIds;
private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentVersion;
private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentTopLevelChangeVersion;
// Checksums for this solution state
private readonly ValueSource<ProjectStateChecksums> _lazyChecksums;
/// <summary>
/// The <see cref="AnalyzerConfigSet"/> to be used for analyzer options for specific trees.
/// </summary>
private readonly ValueSource<AnalyzerConfigSet> _lazyAnalyzerConfigSet;
// this will be initialized lazily.
private AnalyzerOptions _analyzerOptionsDoNotAccessDirectly;
private ProjectState(
ProjectInfo projectInfo,
HostLanguageServices languageServices,
SolutionServices solutionServices,
ImmutableList<DocumentId> documentIds,
ImmutableList<DocumentId> additionalDocumentIds,
ImmutableSortedDictionary<DocumentId, DocumentState> documentStates,
ImmutableSortedDictionary<DocumentId, TextDocumentState> additionalDocumentStates,
ImmutableSortedDictionary<DocumentId, AnalyzerConfigDocumentState> analyzerConfigDocumentStates,
AsyncLazy<VersionStamp> lazyLatestDocumentVersion,
AsyncLazy<VersionStamp> lazyLatestDocumentTopLevelChangeVersion,
ValueSource<AnalyzerConfigSet> lazyAnalyzerConfigSet)
{
_solutionServices = solutionServices;
_languageServices = languageServices;
_documentIds = documentIds;
_additionalDocumentIds = additionalDocumentIds;
_documentStates = documentStates;
_additionalDocumentStates = additionalDocumentStates;
_analyzerConfigDocumentStates = analyzerConfigDocumentStates;
_lazyLatestDocumentVersion = lazyLatestDocumentVersion;
_lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion;
_lazyAnalyzerConfigSet = lazyAnalyzerConfigSet;
// ownership of information on document has moved to project state. clear out documentInfo the state is
// holding on. otherwise, these information will be held onto unnecesarily by projectInfo even after
// the info has changed by DocumentState.
_projectInfo = ClearAllDocumentsFromProjectInfo(projectInfo);
_lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true);
}
public ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices)
{
Contract.ThrowIfNull(projectInfo);
Contract.ThrowIfNull(languageServices);
Contract.ThrowIfNull(solutionServices);
_languageServices = languageServices;
_solutionServices = solutionServices;
var projectInfoFixed = FixProjectInfo(projectInfo);
// We need to compute our AnalyerConfigDocumentStates first, since we use those to produce our DocumentStates
_analyzerConfigDocumentStates = ImmutableSortedDictionary.CreateRange(DocumentIdComparer.Instance,
projectInfoFixed.AnalyzerConfigDocuments.Select(d =>
KeyValuePairUtil.Create(d.Id, new AnalyzerConfigDocumentState(d, solutionServices))));
_lazyAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(_analyzerConfigDocumentStates.Values);
_documentIds = projectInfoFixed.Documents.Select(d => d.Id).ToImmutableList();
_additionalDocumentIds = projectInfoFixed.AdditionalDocuments.Select(d => d.Id).ToImmutableList();
var parseOptions = projectInfoFixed.ParseOptions;
var docStates = ImmutableSortedDictionary.CreateRange(DocumentIdComparer.Instance,
projectInfoFixed.Documents.Select(d =>
new KeyValuePair<DocumentId, DocumentState>(d.Id,
CreateDocument(d, parseOptions))));
_documentStates = docStates;
var additionalDocStates = ImmutableSortedDictionary.CreateRange(DocumentIdComparer.Instance,
projectInfoFixed.AdditionalDocuments.Select(d =>
new KeyValuePair<DocumentId, TextDocumentState>(d.Id, new TextDocumentState(d, solutionServices))));
_additionalDocumentStates = additionalDocStates;
_lazyLatestDocumentVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(docStates, additionalDocStates, c), cacheResult: true);
_lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(docStates, additionalDocStates, c), cacheResult: true);
// ownership of information on document has moved to project state. clear out documentInfo the state is
// holding on. otherwise, these information will be held onto unnecesarily by projectInfo even after
// the info has changed by DocumentState.
// we hold onto the info so that we don't need to duplicate all information info already has in the state
_projectInfo = ClearAllDocumentsFromProjectInfo(projectInfoFixed);
_lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true);
}
private static ProjectInfo ClearAllDocumentsFromProjectInfo(ProjectInfo projectInfo)
{
return projectInfo
.WithDocuments(ImmutableArray<DocumentInfo>.Empty)
.WithAdditionalDocuments(ImmutableArray<DocumentInfo>.Empty)
.WithAnalyzerConfigDocuments(ImmutableArray<DocumentInfo>.Empty);
}
private ProjectInfo FixProjectInfo(ProjectInfo projectInfo)
{
if (projectInfo.CompilationOptions == null)
{
var compilationFactory = _languageServices.GetService<ICompilationFactoryService>();
if (compilationFactory != null)
{
projectInfo = projectInfo.WithCompilationOptions(compilationFactory.GetDefaultCompilationOptions());
}
}
if (projectInfo.ParseOptions == null)
{
var syntaxTreeFactory = _languageServices.GetService<ISyntaxTreeFactoryService>();
if (syntaxTreeFactory != null)
{
projectInfo = projectInfo.WithParseOptions(syntaxTreeFactory.GetDefaultParseOptions());
}
}
return projectInfo;
}
private static async Task<VersionStamp> ComputeLatestDocumentVersionAsync(IImmutableDictionary<DocumentId, DocumentState> documentStates, IImmutableDictionary<DocumentId, TextDocumentState> additionalDocumentStates, CancellationToken cancellationToken)
{
// this may produce a version that is out of sync with the actual Document versions.
var latestVersion = VersionStamp.Default;
foreach (var (_, doc) in documentStates)
{
cancellationToken.ThrowIfCancellationRequested();
if (!doc.IsGenerated)
{
var version = await doc.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
latestVersion = version.GetNewerVersion(latestVersion);
}
}
foreach (var (_, additionalDoc) in additionalDocumentStates)
{
cancellationToken.ThrowIfCancellationRequested();
var version = await additionalDoc.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
latestVersion = version.GetNewerVersion(latestVersion);
}
return latestVersion;
}
private AsyncLazy<VersionStamp> CreateLazyLatestDocumentTopLevelChangeVersion(
TextDocumentState newDocument,
IImmutableDictionary<DocumentId, DocumentState> newDocumentStates,
IImmutableDictionary<DocumentId, TextDocumentState> newAdditionalDocumentStates)
{
if (_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var oldVersion))
{
return new AsyncLazy<VersionStamp>(c => ComputeTopLevelChangeTextVersionAsync(oldVersion, newDocument, c), cacheResult: true);
}
else
{
return new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true);
}
}
private static async Task<VersionStamp> ComputeTopLevelChangeTextVersionAsync(VersionStamp oldVersion, TextDocumentState newDocument, CancellationToken cancellationToken)
{
var newVersion = await newDocument.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false);
return newVersion.GetNewerVersion(oldVersion);
}
private static async Task<VersionStamp> ComputeLatestDocumentTopLevelChangeVersionAsync(IImmutableDictionary<DocumentId, DocumentState> documentStates, IImmutableDictionary<DocumentId, TextDocumentState> additionalDocumentStates, CancellationToken cancellationToken)
{
// this may produce a version that is out of sync with the actual Document versions.
var latestVersion = VersionStamp.Default;
foreach (var (_, doc) in documentStates)
{
cancellationToken.ThrowIfCancellationRequested();
var version = await doc.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false);
latestVersion = version.GetNewerVersion(latestVersion);
}
foreach (var (_, additionalDoc) in additionalDocumentStates)
{
cancellationToken.ThrowIfCancellationRequested();
var version = await additionalDoc.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false);
latestVersion = version.GetNewerVersion(latestVersion);
}
return latestVersion;
}
internal DocumentState CreateDocument(DocumentInfo documentInfo, ParseOptions parseOptions)
{
var doc = new DocumentState(documentInfo, parseOptions, _lazyAnalyzerConfigSet, _languageServices, _solutionServices);
if (doc.SourceCodeKind != documentInfo.SourceCodeKind)
{
doc = doc.UpdateSourceCodeKind(documentInfo.SourceCodeKind);
}
return doc;
}
public AnalyzerOptions AnalyzerOptions
{
get
{
if (_analyzerOptionsDoNotAccessDirectly == null)
{
_analyzerOptionsDoNotAccessDirectly = new AnalyzerOptions(
_additionalDocumentStates.Values.Select(d => new AdditionalTextDocument(d)).ToImmutableArray<AdditionalText>(),
new WorkspaceAnalyzerConfigOptionsProvider(this));
}
return _analyzerOptionsDoNotAccessDirectly;
}
}
private sealed class WorkspaceAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider
{
private readonly ProjectState _projectState;
public WorkspaceAnalyzerConfigOptionsProvider(ProjectState projectState)
{
_projectState = projectState;
}
public override AnalyzerConfigOptions GetOptions(SyntaxTree tree)
{
return new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(tree.FilePath));
}
public override AnalyzerConfigOptions GetOptions(AdditionalText textFile)
{
// TODO: correctly find the file path, since it looks like we give this the document's .Name under the covers if we don't have one
return new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(textFile.Path));
}
// PROTOTYPE: why isn't this just a provided implementation?
private sealed class WorkspaceAnalyzerConfigOptions : AnalyzerConfigOptions
{
private readonly ImmutableDictionary<string, string> _analyzerOptions;
public WorkspaceAnalyzerConfigOptions(AnalyzerConfigOptionsResult analyzerConfigOptions)
{
_analyzerOptions = analyzerConfigOptions.AnalyzerOptions;
}
public override bool TryGetValue(string key, out string value) => _analyzerOptions.TryGetValue(key, out value);
}
}
private static ValueSource<AnalyzerConfigSet> ComputeAnalyzerConfigSetValueSource(IEnumerable<AnalyzerConfigDocumentState> analyzerConfigDocumentStates)
{
return new AsyncLazy<AnalyzerConfigSet>(
asynchronousComputeFunction: async cancellationToken =>
{
var tasks = analyzerConfigDocumentStates.Select(a => a.GetAnalyzerConfigAsync(cancellationToken));
var analyzerConfigs = await Task.WhenAll(tasks).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
return AnalyzerConfigSet.Create(analyzerConfigs);
},
synchronousComputeFunction: cancellationToken =>
{
var analyzerConfigs = analyzerConfigDocumentStates.SelectAsArray(a => a.GetAnalyzerConfig(cancellationToken));
return AnalyzerConfigSet.Create(analyzerConfigs);
},
cacheResult: true);
}
public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken)
{
return _lazyLatestDocumentVersion.GetValueAsync(cancellationToken);
}
public Task<VersionStamp> GetLatestDocumentTopLevelChangeVersionAsync(CancellationToken cancellationToken)
{
return _lazyLatestDocumentTopLevelChangeVersion.GetValueAsync(cancellationToken);
}
public async Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default)
{
var docVersion = await this.GetLatestDocumentTopLevelChangeVersionAsync(cancellationToken).ConfigureAwait(false);
return docVersion.GetNewerVersion(this.Version);
}
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public ProjectId Id => this.ProjectInfo.Id;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public string FilePath => this.ProjectInfo.FilePath;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public string OutputFilePath => this.ProjectInfo.OutputFilePath;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public string OutputRefFilePath => this.ProjectInfo.OutputRefFilePath;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public string DefaultNamespace => this.ProjectInfo.DefaultNamespace;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public HostLanguageServices LanguageServices => _languageServices;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public string Language => LanguageServices.Language;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public string Name => this.ProjectInfo.Name;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public bool IsSubmission => this.ProjectInfo.IsSubmission;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public Type HostObjectType => this.ProjectInfo.HostObjectType;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public VersionStamp Version => this.ProjectInfo.Version;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public ProjectInfo ProjectInfo => _projectInfo;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public string AssemblyName => this.ProjectInfo.AssemblyName;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public CompilationOptions CompilationOptions => this.ProjectInfo.CompilationOptions;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public ParseOptions ParseOptions => this.ProjectInfo.ParseOptions;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IReadOnlyList<MetadataReference> MetadataReferences => this.ProjectInfo.MetadataReferences;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IReadOnlyList<AnalyzerReference> AnalyzerReferences => this.ProjectInfo.AnalyzerReferences;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IReadOnlyList<ProjectReference> ProjectReferences => this.ProjectInfo.ProjectReferences;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public bool HasAllInformation => this.ProjectInfo.HasAllInformation;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public bool HasDocuments => _documentIds.Count > 0;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IEnumerable<DocumentState> OrderedDocumentStates => this.DocumentIds.Select(GetDocumentState);
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IReadOnlyList<DocumentId> DocumentIds => _documentIds;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IReadOnlyList<DocumentId> AdditionalDocumentIds => _additionalDocumentIds;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
// Regular documents and additionald documents have an ordering, and so we maintain lists of the IDs in order; in the case of analyzerconfig documents,
// we don't define a workspace ordering because they are ordered via fancier algorithms in the compiler based on directory depth.
public IEnumerable<DocumentId> AnalyzerConfigDocumentIds => _analyzerConfigDocumentStates.Keys;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IImmutableDictionary<DocumentId, DocumentState> DocumentStates => _documentStates;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IImmutableDictionary<DocumentId, TextDocumentState> AdditionalDocumentStates => _additionalDocumentStates;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public IImmutableDictionary<DocumentId, AnalyzerConfigDocumentState> AnalyzerConfigDocumentStates => _analyzerConfigDocumentStates;
public bool ContainsDocument(DocumentId documentId)
{
return _documentStates.ContainsKey(documentId);
}
public bool ContainsAdditionalDocument(DocumentId documentId)
{
return _additionalDocumentStates.ContainsKey(documentId);
}
public bool ContainsAnalyzerConfigDocument(DocumentId documentId)
{
return _analyzerConfigDocumentStates.ContainsKey(documentId);
}
public DocumentState GetDocumentState(DocumentId documentId)
{
_documentStates.TryGetValue(documentId, out var state);
return state;
}
public TextDocumentState GetAdditionalDocumentState(DocumentId documentId)
{
_additionalDocumentStates.TryGetValue(documentId, out var state);
return state;
}
public AnalyzerConfigDocumentState GetAnalyzerConfigDocumentState(DocumentId documentId)
{
_analyzerConfigDocumentStates.TryGetValue(documentId, out var state);
return state;
}
private ProjectState With(
ProjectInfo projectInfo = null,
ImmutableList<DocumentId> documentIds = default,
ImmutableList<DocumentId> additionalDocumentIds = default,
ImmutableSortedDictionary<DocumentId, DocumentState> documentStates = null,
ImmutableSortedDictionary<DocumentId, TextDocumentState> additionalDocumentStates = null,
ImmutableSortedDictionary<DocumentId, AnalyzerConfigDocumentState> analyzerConfigDocumentStates = null,
AsyncLazy<VersionStamp> latestDocumentVersion = null,
AsyncLazy<VersionStamp> latestDocumentTopLevelChangeVersion = null,
ValueSource<AnalyzerConfigSet> analyzerConfigSet = null)
{
return new ProjectState(
projectInfo ?? _projectInfo,
_languageServices,
_solutionServices,
documentIds ?? _documentIds,
additionalDocumentIds ?? _additionalDocumentIds,
documentStates ?? _documentStates,
additionalDocumentStates ?? _additionalDocumentStates,
analyzerConfigDocumentStates ?? _analyzerConfigDocumentStates,
latestDocumentVersion ?? _lazyLatestDocumentVersion,
latestDocumentTopLevelChangeVersion ?? _lazyLatestDocumentTopLevelChangeVersion,
analyzerConfigSet ?? _lazyAnalyzerConfigSet);
}
public ProjectState UpdateName(string name)
{
if (name == this.Name)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithName(name).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState UpdateFilePath(string filePath)
{
if (filePath == this.FilePath)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithFilePath(filePath).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState UpdateAssemblyName(string assemblyName)
{
if (assemblyName == this.AssemblyName)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithAssemblyName(assemblyName).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState UpdateOutputFilePath(string outputFilePath)
{
if (outputFilePath == this.OutputFilePath)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithOutputFilePath(outputFilePath).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState UpdateOutputRefFilePath(string outputRefFilePath)
{
if (outputRefFilePath == this.OutputRefFilePath)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithOutputRefFilePath(outputRefFilePath).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState UpdateDefaultNamespace(string defaultNamespace)
{
if (defaultNamespace == this.DefaultNamespace)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithDefaultNamespace(defaultNamespace).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState UpdateCompilationOptions(CompilationOptions options)
{
if (options == this.CompilationOptions)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithCompilationOptions(options).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState UpdateParseOptions(ParseOptions options)
{
if (options == this.ParseOptions)
{
return this;
}
// update parse options for all documents too
var docMap = _documentStates;
foreach (var (docId, _) in _documentStates)
{
var oldDocState = this.GetDocumentState(docId);
var newDocState = oldDocState.UpdateParseOptions(options);
docMap = docMap.SetItem(docId, newDocState);
}
return this.With(
projectInfo: this.ProjectInfo.WithParseOptions(options).WithVersion(this.Version.GetNewerVersion()),
documentStates: docMap);
}
public ProjectState UpdateHasAllInformation(bool hasAllInformation)
{
if (hasAllInformation == this.HasAllInformation)
{
return this;
}
return this.With(projectInfo: this.ProjectInfo.WithHasAllInformation(hasAllInformation).WithVersion(this.Version.GetNewerVersion()));
}
public static bool IsSameLanguage(ProjectState project1, ProjectState project2)
{
return project1.LanguageServices == project2.LanguageServices;
}
public ProjectState RemoveProjectReference(ProjectReference projectReference)
{
Debug.Assert(this.ProjectReferences.Contains(projectReference));
return this.With(
projectInfo: this.ProjectInfo.WithProjectReferences(this.ProjectReferences.ToImmutableArray().Remove(projectReference)).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState AddProjectReferences(IEnumerable<ProjectReference> projectReferences)
{
var newProjectRefs = this.ProjectReferences;
foreach (var projectReference in projectReferences)
{
Debug.Assert(!newProjectRefs.Contains(projectReference));
newProjectRefs = newProjectRefs.ToImmutableArray().Add(projectReference);
}
return this.With(
projectInfo: this.ProjectInfo.WithProjectReferences(newProjectRefs).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState WithProjectReferences(IEnumerable<ProjectReference> projectReferences)
{
return this.With(
projectInfo: this.ProjectInfo.WithProjectReferences(projectReferences).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState AddMetadataReference(MetadataReference toMetadata)
{
Debug.Assert(!this.MetadataReferences.Contains(toMetadata));
return this.With(
projectInfo: this.ProjectInfo.WithMetadataReferences(this.MetadataReferences.ToImmutableArray().Add(toMetadata)).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState RemoveMetadataReference(MetadataReference toMetadata)
{
Debug.Assert(this.MetadataReferences.Contains(toMetadata));
return this.With(
projectInfo: this.ProjectInfo.WithMetadataReferences(this.MetadataReferences.ToImmutableArray().Remove(toMetadata)).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences)
{
var newMetaRefs = this.MetadataReferences;
foreach (var metadataReference in metadataReferences)
{
Debug.Assert(!newMetaRefs.Contains(metadataReference));
newMetaRefs = newMetaRefs.ToImmutableArray().Add(metadataReference);
}
return this.With(
projectInfo: this.ProjectInfo.WithMetadataReferences(newMetaRefs).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences)
{
return this.With(
projectInfo: this.ProjectInfo.WithMetadataReferences(metadataReferences).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState AddAnalyzerReference(AnalyzerReference analyzerReference)
{
Debug.Assert(!this.AnalyzerReferences.Contains(analyzerReference));
return this.With(
projectInfo: this.ProjectInfo.WithAnalyzerReferences(this.AnalyzerReferences.ToImmutableArray().Add(analyzerReference)).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState RemoveAnalyzerReference(AnalyzerReference analyzerReference)
{
Debug.Assert(this.AnalyzerReferences.Contains(analyzerReference));
return this.With(
projectInfo: this.ProjectInfo.WithAnalyzerReferences(this.AnalyzerReferences.ToImmutableArray().Remove(analyzerReference)).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences)
{
var newAnalyzerReferences = this.AnalyzerReferences;
foreach (var analyzerReference in analyzerReferences)
{
Debug.Assert(!newAnalyzerReferences.Contains(analyzerReference));
newAnalyzerReferences = newAnalyzerReferences.ToImmutableArray().Add(analyzerReference);
}
return this.With(
projectInfo: this.ProjectInfo.WithAnalyzerReferences(newAnalyzerReferences).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences)
{
return this.With(
projectInfo: this.ProjectInfo.WithAnalyzerReferences(analyzerReferences).WithVersion(this.Version.GetNewerVersion()));
}
public ProjectState AddDocuments(ImmutableArray<DocumentState> documents)
{
Debug.Assert(!documents.Any(d => this.DocumentStates.ContainsKey(d.Id)));
return this.With(
projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()),
documentIds: _documentIds.AddRange(documents.Select(d => d.Id)),
documentStates: _documentStates.AddRange(documents.Select(d => KeyValuePairUtil.Create(d.Id, d))));
}
public ProjectState AddAdditionalDocuments(ImmutableArray<TextDocumentState> documents)
{
Debug.Assert(!documents.Any(d => this.AdditionalDocumentStates.ContainsKey(d.Id)));
return this.With(
projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()),
additionalDocumentIds: _additionalDocumentIds.AddRange(documents.Select(d => d.Id)),
additionalDocumentStates: _additionalDocumentStates.AddRange(documents.Select(d => KeyValuePairUtil.Create(d.Id, d))));
}
public ProjectState AddAnalyzerConfigDocuments(ImmutableArray<AnalyzerConfigDocumentState> documents)
{
Debug.Assert(!documents.Any(d => this._analyzerConfigDocumentStates.ContainsKey(d.Id)));
var newAnalyzerConfigDocumentStates = _analyzerConfigDocumentStates.AddRange(documents.Select(d => KeyValuePairUtil.Create(d.Id, d)));
return CreateNewStateForChangedAnalyzerConfigDocuments(newAnalyzerConfigDocumentStates);
}
private ProjectState CreateNewStateForChangedAnalyzerConfigDocuments(ImmutableSortedDictionary<DocumentId, AnalyzerConfigDocumentState> newAnalyzerConfigDocumentStates)
{
var newAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(newAnalyzerConfigDocumentStates.Values);
// The addition of any .editorconfig can modify the diagnostic reporting options that are on
// a specific syntax tree; therefore we must update all our syntax trees.
var docMap = _documentStates;
foreach (var (docId, _) in _documentStates)
{
var oldDocState = this.GetDocumentState(docId);
var newDocState = oldDocState.UpdateAnalyzerConfigSet(newAnalyzerConfigSet);
docMap = docMap.SetItem(docId, newDocState);
}
return this.With(
projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()),
analyzerConfigDocumentStates: newAnalyzerConfigDocumentStates,
documentStates: docMap,
analyzerConfigSet: newAnalyzerConfigSet);
}
public ProjectState RemoveDocument(DocumentId documentId)
{
Debug.Assert(this.DocumentStates.ContainsKey(documentId));
return this.With(
projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()),
documentIds: _documentIds.Remove(documentId),
documentStates: _documentStates.Remove(documentId));
}
public ProjectState RemoveAdditionalDocument(DocumentId documentId)
{
Debug.Assert(this.AdditionalDocumentStates.ContainsKey(documentId));
return this.With(
projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()),
additionalDocumentIds: _additionalDocumentIds.Remove(documentId),
additionalDocumentStates: _additionalDocumentStates.Remove(documentId));
}
public ProjectState RemoveAnalyzerConfigDocument(DocumentId documentId)
{
Debug.Assert(_analyzerConfigDocumentStates.ContainsKey(documentId));
var newAnalyzerConfigDocumentStates = _analyzerConfigDocumentStates.Remove(documentId);
return CreateNewStateForChangedAnalyzerConfigDocuments(newAnalyzerConfigDocumentStates);
}
public ProjectState RemoveAllDocuments()
{
return this.With(
projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()).WithDocuments(SpecializedCollections.EmptyEnumerable<DocumentInfo>()),
documentIds: ImmutableList<DocumentId>.Empty,
documentStates: ImmutableSortedDictionary.Create<DocumentId, DocumentState>(DocumentIdComparer.Instance));
}
public ProjectState UpdateDocument(DocumentState newDocument, bool textChanged, bool recalculateDependentVersions)
{
Debug.Assert(this.ContainsDocument(newDocument.Id));
var oldDocument = this.GetDocumentState(newDocument.Id);
if (oldDocument == newDocument)
{
return this;
}
var newDocumentStates = _documentStates.SetItem(newDocument.Id, newDocument);
GetLatestDependentVersions(
newDocumentStates, _additionalDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged,
out var dependentDocumentVersion, out var dependentSemanticVersion);
return this.With(
documentStates: newDocumentStates,
latestDocumentVersion: dependentDocumentVersion,
latestDocumentTopLevelChangeVersion: dependentSemanticVersion);
}
public ProjectState UpdateAdditionalDocument(TextDocumentState newDocument, bool textChanged, bool recalculateDependentVersions)
{
Debug.Assert(this.ContainsAdditionalDocument(newDocument.Id));
var oldDocument = this.GetAdditionalDocumentState(newDocument.Id);
if (oldDocument == newDocument)
{
return this;
}
var newDocumentStates = _additionalDocumentStates.SetItem(newDocument.Id, newDocument);
GetLatestDependentVersions(
_documentStates, newDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged,
out var dependentDocumentVersion, out var dependentSemanticVersion);
return this.With(
additionalDocumentStates: newDocumentStates,
latestDocumentVersion: dependentDocumentVersion,
latestDocumentTopLevelChangeVersion: dependentSemanticVersion);
}
public ProjectState UpdateAnalyzerConfigDocument(AnalyzerConfigDocumentState newDocument, bool textChanged, bool recalculateDependentVersions)
{
Debug.Assert(this.ContainsAnalyzerConfigDocument(newDocument.Id));
var oldDocument = this.GetAnalyzerConfigDocumentState(newDocument.Id);
if (oldDocument == newDocument)
{
return this;
}
var newDocumentStates = _analyzerConfigDocumentStates.SetItem(newDocument.Id, newDocument);
return CreateNewStateForChangedAnalyzerConfigDocuments(newDocumentStates);
}
public ProjectState UpdateDocumentsOrder(ImmutableList<DocumentId> documentIds)
{
if (documentIds.IsEmpty)
{
throw new ArgumentOutOfRangeException("The specified documents are empty.", nameof(documentIds));
}
if (documentIds.Count != _documentIds.Count)
{
throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds));
}
var hasOrderChanged = false;
for (var i = 0; i < documentIds.Count; ++i)
{
var documentId = documentIds[i];
if (!ContainsDocument(documentId))
{
throw new InvalidOperationException($"The document '{documentId}' does not exist in the project.");
}
if (DocumentIds[i] != documentId)
{
hasOrderChanged = true;
}
}
if (!hasOrderChanged)
{
return this;
}
return this.With(
projectInfo: this.ProjectInfo.WithVersion(this.Version.GetNewerVersion()),
documentIds: documentIds);
}
private void GetLatestDependentVersions(
IImmutableDictionary<DocumentId, DocumentState> newDocumentStates,
IImmutableDictionary<DocumentId, TextDocumentState> newAdditionalDocumentStates,
TextDocumentState oldDocument, TextDocumentState newDocument,
bool recalculateDependentVersions, bool textChanged,
out AsyncLazy<VersionStamp> dependentDocumentVersion, out AsyncLazy<VersionStamp> dependentSemanticVersion)
{
var recalculateDocumentVersion = false;
var recalculateSemanticVersion = false;
if (recalculateDependentVersions)
{
if (oldDocument.TryGetTextVersion(out var oldVersion))
{
if (!_lazyLatestDocumentVersion.TryGetValue(out var documentVersion) || documentVersion == oldVersion)
{
recalculateDocumentVersion = true;
}
if (!_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var semanticVersion) || semanticVersion == oldVersion)
{
recalculateSemanticVersion = true;
}
}
}
dependentDocumentVersion = recalculateDocumentVersion ?
new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) :
textChanged ?
new AsyncLazy<VersionStamp>(newDocument.GetTextVersionAsync, cacheResult: true) :
_lazyLatestDocumentVersion;
dependentSemanticVersion = recalculateSemanticVersion ?
new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) :
textChanged ?
CreateLazyLatestDocumentTopLevelChangeVersion(newDocument, newDocumentStates, newAdditionalDocumentStates) :
_lazyLatestDocumentTopLevelChangeVersion;
}
private sealed class DocumentIdComparer : IComparer<DocumentId>
{
public static IComparer<DocumentId> Instance = new DocumentIdComparer();
private DocumentIdComparer()
{
}
public int Compare(DocumentId x, DocumentId y)
{
return x.Id.CompareTo(y.Id);
}
}
}
}
| 46.446137 | 274 | 0.677022 | [
"Apache-2.0"
] | mmihaly/roslyn | src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs | 42,686 | C# |
//-----------------------------------------------------------------------------
// FILE: NamespaceDoc.cs
// CONTRIBUTOR: Jeff Lill
// COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using Neon.Common;
namespace Neon.Service
{
/// <summary>
/// This namespace defines types used to describe an application service.
/// </summary>
[System.Runtime.CompilerServices.CompilerGenerated]
class NamespaceDoc
{
}
}
| 32.361111 | 80 | 0.685837 | [
"Apache-2.0"
] | codelastnight/neonKUBE | Lib/Neon.Common/Service/NamespaceDoc.cs | 1,167 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Designer.Source.Controls
{
public partial class DynamicPanel : UserControl
{
#region Attributes
private int _InitX;
private bool _IsCaptured;
#endregion
public DynamicPanel()
{
InitializeComponent();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
Capture = _IsCaptured;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left)
{
if ((_InitX - e.X) % 32 == 0)
{
// Left
if (_InitX > e.X)
{
Left = Left + e.X;
Width = Width + 32;
}
}
}
}
private void DynamicPanel_MouseDown(object sender, MouseEventArgs e)
{
_InitX = e.X - (e.X % 32);
_IsCaptured = true;
}
private void DynamicPanel_MouseUp(object sender, MouseEventArgs e)
{
_IsCaptured = false;
}
}
}
| 22.875 | 76 | 0.468384 | [
"Apache-2.0"
] | TheCharmingCthulhu/CSharp | Projects/Windows Forms/Designer/Designer/Source/Controls/DynamicPanel.cs | 1,283 | C# |
using System.Collections.Generic;
using Orchard.Tags.Models;
namespace Orchard.Tags.ViewModels {
public class TagsAdminIndexViewModel {
public IList<TagEntry> Tags { get; set; }
public TagAdminIndexBulkAction BulkAction { get; set; }
}
public class TagEntry {
public TagRecord Tag { get; set; }
public bool IsChecked { get; set; }
}
public enum TagAdminIndexBulkAction {
None,
Delete,
}
}
| 24.2 | 64 | 0.619835 | [
"BSD-3-Clause"
] | Christerinho/chrisdesign | Modules/Orchard.Tags/ViewModels/TagsAdminIndexViewModel.cs | 486 | C# |
//-----------------------------------------------------------------------
// <copyright file="ActorRefIgnoreSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Threading;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Serialization;
using Akka.TestKit;
using Akka.TestKit.TestActors;
using Xunit;
using Akka.Util.Internal;
using FluentAssertions;
namespace Akka.Tests.Actor
{
public class ActorRefIgnoreSpec : AkkaSpec, INoImplicitSender
{
[Fact]
public void IgnoreActorRef_should_ignore_all_incoming_messages()
{
var askMeRef = Sys.ActorOf(Props.Create(() => new AskMeActor()));
var probe = CreateTestProbe("response-probe");
askMeRef.Tell(new Request(probe.Ref));
probe.ExpectMsg(1);
// this is more a compile-time proof
// since the reply is ignored, we can't check that a message was sent to it
askMeRef.Tell(new Request(Sys.IgnoreRef));
probe.ExpectNoMsg();
// but we do check that the counter has increased when we used the ActorRef.ignore
askMeRef.Tell(new Request(probe.Ref));
probe.ExpectMsg(3);
}
[Fact]
public void IgnoreActorRef_should_make_a_Future_timeout_when_used_in_a_ask()
{
// this is kind of obvious, the Future won't complete because the ignoreRef is used
var timeout = TimeSpan.FromMilliseconds(500);
var askMeRef = Sys.ActorOf(Props.Create(() => new AskMeActor()));
Assert.Throws<AskTimeoutException>(() =>
{
_ = askMeRef.Ask(new Request(Sys.IgnoreRef), timeout).GetAwaiter().GetResult();
});
}
[Fact]
public void IgnoreActorRef_should_be_watchable_from_another_actor_without_throwing_an_exception()
{
var probe = CreateTestProbe("probe-response");
var forwardMessageRef = Sys.ActorOf(Props.Create(() => new ForwardMessageWatchActor(probe)));
// this proves that the actor started and is operational and 'watch' didn't impact it
forwardMessageRef.Tell("abc");
probe.ExpectMsg("abc");
}
[Fact]
public void IgnoreActorRef_should_be_a_singleton()
{
Sys.IgnoreRef.Should().BeSameAs(Sys.IgnoreRef);
}
/// <summary>
/// this Actor behavior receives simple request and answers back total number of
/// messages it received so far
/// </summary>
internal class AskMeActor : ActorBase
{
private int counter;
public AskMeActor()
{
}
protected override bool Receive(object message)
{
switch (message)
{
case Request r:
counter++;
r.ReplyTo.Tell(counter);
return true;
}
return false;
}
}
internal class Request
{
public Request(IActorRef replyTo)
{
ReplyTo = replyTo;
}
public IActorRef ReplyTo { get; }
}
internal class ForwardMessageWatchActor : ActorBase
{
private readonly IActorRef probe;
public ForwardMessageWatchActor(IActorRef probe)
{
Context.Watch(Context.System.IgnoreRef);
this.probe = probe;
}
protected override bool Receive(object message)
{
switch (message)
{
case string str:
probe.Tell(str);
return true;
}
return false;
}
}
}
}
| 31.142857 | 105 | 0.535249 | [
"Apache-2.0"
] | baronfel/akka.net | src/core/Akka.Tests/Actor/ActorRefIgnoreSpec.cs | 4,144 | 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.DotNet.Framework.Docker.Tests
{
public class ImageTestHelper
{
private static Lazy<JArray> ImageInfoData;
public DockerHelper DockerHelper { get; }
private ITestOutputHelper _outputHelper;
public ImageTestHelper(ITestOutputHelper outputHelper)
{
_outputHelper = outputHelper;
DockerHelper = new DockerHelper(outputHelper);
}
static ImageTestHelper()
{
ImageInfoData = new Lazy<JArray>(() =>
{
string imageInfoPath = Environment.GetEnvironmentVariable("IMAGE_INFO_PATH");
if (!String.IsNullOrEmpty(imageInfoPath))
{
string imageInfoContents = File.ReadAllText(imageInfoPath);
return JsonConvert.DeserializeObject<JArray>(imageInfoContents);
}
return null;
});
}
public static IEnumerable<object[]> ApplyImageDataFilters(IEnumerable<ImageDescriptor> imageDescriptors)
{
string versionPattern =
Config.Version != null ? Config.GetFilterRegexPattern(Config.Version) : null;
string osPattern =
Config.OS != null ? Config.GetFilterRegexPattern(Config.OS) : null;
// Filter out test data that does not match the active os and version filters.
return imageDescriptors
.Where(imageDescriptor => Config.OS == null
|| Regex.IsMatch(imageDescriptor.OsVariant, osPattern, RegexOptions.IgnoreCase))
.Where(imageDescriptor => Config.Version == null
|| Regex.IsMatch(imageDescriptor.Version, versionPattern, RegexOptions.IgnoreCase))
.Select(imageDescriptor => new object[] { imageDescriptor });
}
public string BuildAndTestImage(
ImageDescriptor imageDescriptor,
IEnumerable<string> buildArgs,
string appDescriptor,
string runCommand,
string testUrl)
{
string appId = $"{appDescriptor}-{DateTime.Now.ToFileTime()}";
string workDir = Path.Combine(
Directory.GetCurrentDirectory(),
"projects",
$"{appDescriptor}-{imageDescriptor.Version}");
string output;
try
{
DockerHelper.Build(
tag: appId,
dockerfile: Path.Combine(workDir, "Dockerfile"),
contextDir: workDir,
buildArgs: buildArgs.ToArray());
output = DockerHelper.Run(image: appId, name: appId, command: runCommand, detach: !string.IsNullOrEmpty(testUrl));
if (!string.IsNullOrEmpty(testUrl))
{
VerifyHttpResponseFromContainer(appId, testUrl);
}
}
finally
{
DockerHelper.DeleteContainer(appId, !string.IsNullOrEmpty(testUrl));
DockerHelper.DeleteImage(appId);
}
return output;
}
public string GetImage(string imageType, string version, string osVariant)
{
string repo = $"dotnet/framework/{imageType}";
string tag = $"{version}-{osVariant}";
string registry = GetRegistryNameWithRepoPrefix(repo, tag);
string image = $"{registry}{repo}:{tag}";
// Ensure image exists locally
if (Config.PullImages)
{
DockerHelper.Pull(image);
}
else
{
Assert.True(DockerHelper.ImageExists(image), $"`{image}` could not be found on disk.");
}
return image;
}
private static string GetRegistryNameWithRepoPrefix(string repo, string tag)
{
bool isUsingCustomRegistry = true;
// In the case of running this in a local development environment, there would likely be no image info file
// provided. In that case, the assumption is that the images exist in the custom configured location.
if (ImageTestHelper.ImageInfoData.Value != null)
{
JObject repoInfo = (JObject)ImageTestHelper.ImageInfoData.Value
.FirstOrDefault(imageInfoRepo => imageInfoRepo["repo"].ToString() == repo);
if (repoInfo["images"] != null)
{
isUsingCustomRegistry = repoInfo["images"]
.Cast<JProperty>()
.Any(imageInfo => imageInfo.Value["simpleTags"].Any(imageTag => imageTag.ToString() == tag));
}
else
{
isUsingCustomRegistry = false;
}
}
return isUsingCustomRegistry ? $"{Config.Registry}/{Config.RepoPrefix}" : $"{Config.GetManifestRegistry()}/";
}
private void VerifyHttpResponseFromContainer(string containerName, string urlPath)
{
var retries = 30;
// Can't use localhost when running inside containers or Windows.
var url = $"http://{DockerHelper.GetContainerAddress(containerName)}" + urlPath;
using (HttpClient client = new HttpClient())
{
while (retries > 0)
{
retries--;
Thread.Sleep(TimeSpan.FromSeconds(2));
try
{
using (HttpResponseMessage result = client.GetAsync(url).Result)
{
result.EnsureSuccessStatusCode();
}
_outputHelper.WriteLine($"Successfully accessed {url}");
return;
}
catch (Exception ex)
{
_outputHelper.WriteLine($"Request to {url} failed - retrying: {ex.ToString()}");
}
}
}
throw new TimeoutException($"Timed out attempting to access the endpoint {url} on container {containerName}");
}
}
}
| 37.137363 | 130 | 0.552597 | [
"MIT"
] | vitaliitylyk/dotnet-framework-docker | tests/Microsoft.DotNet.Framework.Docker.Tests/ImageTestHelper.cs | 6,761 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Error_Handler_Control {
public partial class SiteMaster {
/// <summary>
/// NavigationMenu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Menu NavigationMenu;
/// <summary>
/// MainContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent;
/// <summary>
/// ErrorSuccessNotifier control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Error_Handler_Control.ErrorSuccessNotifier ErrorSuccessNotifier;
}
}
| 34.023256 | 90 | 0.525632 | [
"MIT"
] | EmilMitev/Telerik-Academy | ASP.NET Web Forms/13. User Controls/Demo/Error-Handler-Control/Site.Master.designer.cs | 1,465 | C# |
using Engine.GIS.GLayer.GRasterLayer;
using Engine.GIS.GOperation.Arithmetic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Host.UI.SettingForm
{
public partial class KappaOaForm : Form
{
public KappaOaForm()
{
InitializeComponent();
}
Dictionary<string, GRasterLayer> _rasterDic;
public Dictionary<string, GRasterLayer> RasterDic
{
set
{
_rasterDic = value;
Initial(_rasterDic);
}
}
public void Initial(Dictionary<string, GRasterLayer> rasterDic)
{
comboBox1.Items.Clear();
rasterDic.Keys.ToList().ForEach(p => {
comboBox1.Items.Add(p);
});
rasterDic.Keys.ToList().ForEach(p => {
comboBox2.Items.Add(p);
});
}
string truthKey, predKey;
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string key = (sender as ComboBox).SelectedItem as string;
predKey = key;
}
private void button3_Click(object sender, EventArgs e)
{
//计算kappa,并输出矩阵
GRasterLayer truthLayer = _rasterDic[truthKey];
GRasterLayer predLayer = _rasterDic[predKey];
var (matrix, kappa, actionsNumber,oa) = KappaIndex.Calcute(truthLayer, predLayer);
//matrix for binding and kappa for display
kappa_label.Text = string.Format("kappa:{0:P} oa:{1:P}", kappa,oa);
//绘表头
webBrowser1.DocumentText = GenericTable(matrix);
}
/// <summary>
/// html绘制表
/// </summary>
/// <param name="matrix"></param>
/// <returns></returns>
private string GenericTable(int[,] matrix)
{
StringBuilder sb = new StringBuilder("");
int rows = matrix.GetLength(0);
int cols = rows;
sb.Append("<table style='margin:0 auto;'>");
for (int i = 0; i < rows; i++)
{
sb.Append("<tr>");
for (int j = 0; j < cols; j++)
{
sb.Append("<td style='border:1px solid gray;'>");
sb.Append(matrix[i, j]);
sb.Append("</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
return sb.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string key = (sender as ComboBox).SelectedItem as string;
truthKey = key;
}
}
}
| 30.184783 | 94 | 0.516385 | [
"MIT"
] | KIWI-ST/kiwi.server | Host.UI/Forms/Tools/KappaForm.cs | 2,805 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel.Email.DataProvider
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class EmailMailboxDownloadAttachmentRequestEventArgs
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.ApplicationModel.Email.DataProvider.EmailMailboxDownloadAttachmentRequest Request
{
get
{
throw new global::System.NotImplementedException("The member EmailMailboxDownloadAttachmentRequest EmailMailboxDownloadAttachmentRequestEventArgs.Request is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.ApplicationModel.Email.DataProvider.EmailMailboxDownloadAttachmentRequestEventArgs.Request.get
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Foundation.Deferral GetDeferral()
{
throw new global::System.NotImplementedException("The member Deferral EmailMailboxDownloadAttachmentRequestEventArgs.GetDeferral() is not implemented in Uno.");
}
#endif
}
}
| 41.033333 | 187 | 0.787977 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Email.DataProvider/EmailMailboxDownloadAttachmentRequestEventArgs.cs | 1,231 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections;
using Xunit;
using ActiveDirectoryComInterop;
namespace System.DirectoryServices.Tests
{
public partial class DirectoryServicesTests
{
[ConditionalFact(nameof(IsActiveDirectoryServer))]
public void TestComInterfaces()
{
using (DirectoryEntry de = CreateRootEntry())
{
DeleteOU(de, "dateRoot");
try
{
using (DirectoryEntry rootOU = CreateOU(de, "dateRoot", "Date OU"))
{
long deTime = GetTimeValue(
(IADsLargeInteger)de.Properties["uSNCreated"].Value
);
long rootOUTime = GetTimeValue(
(IADsLargeInteger)rootOU.Properties["uSNCreated"].Value
);
// we are sure rootOU is created after de
Assert.True(rootOUTime > deTime);
IADs iads = (IADs)rootOU.NativeObject;
Assert.Equal("ou=dateRoot", iads.Name);
Assert.Equal("Class", iads.Class);
Assert.Contains(
LdapConfiguration.Configuration.ServerName,
iads.ADsPath,
StringComparison.OrdinalIgnoreCase
);
IADsSecurityDescriptor iadsSD = (IADsSecurityDescriptor)de.Properties[
"ntSecurityDescriptor"
].Value;
Assert.Contains(
iadsSD.Owner.Split('\\')[0],
LdapConfiguration.Configuration.SearchDn,
StringComparison.OrdinalIgnoreCase
);
Assert.Contains(
iadsSD.Group.Split('\\')[0],
LdapConfiguration.Configuration.SearchDn,
StringComparison.OrdinalIgnoreCase
);
}
}
finally
{
DeleteOU(de, "dateRoot");
}
}
}
private long GetTimeValue(IADsLargeInteger largeInteger)
{
return (long)largeInteger.LowPart | (long)(largeInteger.HighPart << 32);
}
}
}
| 37.222222 | 94 | 0.478358 | [
"MIT"
] | belav/runtime | src/libraries/System.DirectoryServices/tests/System/DirectoryServices/DirectoryServicesTests.Windows.cs | 2,680 | C# |
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using IdentityAPI.Entities;
using Manga.Application.Boundaries;
using Manga.Application.Repositories;
using Manga.Application.UseCases;
using Manga.Domain;
using Manga.Infrastructure.EntityFrameworkDataAccess;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.Swagger;
using System.Text;
using Swashbuckle.AspNetCore.Filters;
namespace Manga.WebApi
{
public sealed class StartupDevelopment
{
public StartupDevelopment(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AuthenticationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<AuthenticationDbContext>()
.AddDefaultTokenProviders();
// ===== Add Jwt Authentication ========
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = Configuration["JwtIssuer"],
ValidAudience = Configuration["JwtIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
ClockSkew = TimeSpan.Zero // remove delay of token when expire
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
AddSwagger(services);
AddMangaCore(services);
AddSQLPersistence(services);
}
private void AddSQLPersistence(IServiceCollection services)
{
services.AddDbContext<MangaContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IAccountRepository, AccountRepository>();
services.AddScoped<IAccountRepository, AccountRepository>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
}
private void AddSwagger(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API (Authentication-Production)", Version = "v1" });
// Global metadata to be included in the Swagger output
c.AddSecurityDefinition("oauth2", new ApiKeyScheme
{
Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
In = "header",
Name = "Authorization",
Type = "apiKey"
});
c.OperationFilter<SecurityRequirementsOperationFilter>();
});
}
private void AddMangaCore(IServiceCollection services)
{
services.AddScoped<IEntitiesFactory, DefaultEntitiesFactory>();
services.AddScoped<Manga.WebApi.UseCases.CloseAccount.Presenter, Manga.WebApi.UseCases.CloseAccount.Presenter>();
services.AddScoped<Manga.WebApi.UseCases.Deposit.Presenter, Manga.WebApi.UseCases.Deposit.Presenter>();
services.AddScoped<Manga.WebApi.UseCases.GetAccountDetails.Presenter, Manga.WebApi.UseCases.GetAccountDetails.Presenter>();
services.AddScoped<Manga.WebApi.UseCases.GetCustomerDetails.Presenter, Manga.WebApi.UseCases.GetCustomerDetails.Presenter>();
services.AddScoped<Manga.WebApi.UseCases.Register.Presenter, Manga.WebApi.UseCases.Register.Presenter>();
services.AddScoped<Manga.WebApi.UseCases.Withdraw.Presenter, Manga.WebApi.UseCases.Withdraw.Presenter>();
services.AddScoped<Manga.Application.Boundaries.CloseAccount.IOutputHandler>(x => x.GetRequiredService<Manga.WebApi.UseCases.CloseAccount.Presenter>());
services.AddScoped<Manga.Application.Boundaries.Deposit.IOutputHandler>(x => x.GetRequiredService<Manga.WebApi.UseCases.Deposit.Presenter>());
services.AddScoped<Manga.Application.Boundaries.GetAccountDetails.IOutputHandler>(x => x.GetRequiredService<Manga.WebApi.UseCases.GetAccountDetails.Presenter>());
services.AddScoped<Manga.Application.Boundaries.GetCustomerDetails.IOutputHandler>(x => x.GetRequiredService<Manga.WebApi.UseCases.GetCustomerDetails.Presenter>());
services.AddScoped<Manga.Application.Boundaries.Register.IOutputHandler>(x => x.GetRequiredService<Manga.WebApi.UseCases.Register.Presenter>());
services.AddScoped<Manga.Application.Boundaries.Withdraw.IOutputHandler>(x => x.GetRequiredService<Manga.WebApi.UseCases.Withdraw.Presenter>());
services.AddScoped<Manga.Application.Boundaries.CloseAccount.IUseCase, Manga.Application.UseCases.CloseAccount>();
services.AddScoped<Manga.Application.Boundaries.Deposit.IUseCase, Manga.Application.UseCases.Deposit>();
services.AddScoped<Manga.Application.Boundaries.GetAccountDetails.IUseCase, Manga.Application.UseCases.GetAccountDetails>();
services.AddScoped<Manga.Application.Boundaries.GetCustomerDetails.IUseCase, Manga.Application.UseCases.GetCustomerDetails>();
services.AddScoped<Manga.Application.Boundaries.Register.IUseCase, Manga.Application.UseCases.Register>();
services.AddScoped<Manga.Application.Boundaries.Withdraw.IUseCase, Manga.Application.UseCases.Withdraw>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, AuthenticationDbContext dbContext)
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
UseSwagger(app);
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
dbContext.Database.EnsureCreated();
}
private void UseSwagger(IApplicationBuilder app)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
}
);
}
}
} | 48.678161 | 176 | 0.666942 | [
"Apache-2.0"
] | Prachi-Parekh/Clean-Architecture-Manga | source/Manga.WebApi/StartupDevelopment.cs | 8,470 | C# |
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace FinderOuter.Views
{
public class MissingBase16View : UserControl
{
public MissingBase16View()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| 18.3 | 48 | 0.60929 | [
"MIT"
] | 1Biggirl/FinderOuter | Src/FinderOuter/Views/MissingBase16View.xaml.cs | 368 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ProtoBuf.Reflection
{
internal static class TokenExtensions
{
public static bool Is(this Peekable<Token> tokens, TokenType type, string value = null)
=> tokens.Peek(out var val) && val.Is(type, value);
public static void Consume(this Peekable<Token> tokens, TokenType type, string value)
{
var token = tokens.Read();
token.Assert(type, value);
tokens.Consume();
}
public static bool ConsumeIf(this Peekable<Token> tokens, TokenType type, string value)
{
if (tokens.Peek(out var token) && token.Is(type, value))
{
tokens.Consume();
return true;
}
return false;
}
public static Token Read(this Peekable<Token> tokens)
{
if (!tokens.Peek(out Token val))
{
throw new ParserException(tokens.Previous, "Unexpected end of file", true, ErrorCode.UnexpectedEOF);
}
return val;
}
public static bool SkipToEndOptions(this Peekable<Token> tokens)
{
while (tokens.Peek(out var token))
{
if (token.Is(TokenType.Symbol, ";") || token.Is(TokenType.Symbol, "}"))
return true; // but don't consume
tokens.Consume();
if (token.Is(TokenType.Symbol, "]"))
return true;
}
return false;
}
public static bool SkipToEndStatement(this Peekable<Token> tokens)
{
while (tokens.Peek(out var token))
{
if (token.Is(TokenType.Symbol, "}"))
return true; // but don't consume
tokens.Consume();
if (token.Is(TokenType.Symbol, ";"))
return true;
}
return false;
}
public static bool SkipToEndObject(this Peekable<Token> tokens) => SkipToSymbol(tokens, "}");
private static bool SkipToSymbol(this Peekable<Token> tokens, string symbol)
{
while (tokens.Peek(out var token))
{
tokens.Consume();
if (token.Is(TokenType.Symbol, symbol))
return true;
}
return false;
}
public static bool SkipToEndStatementOrObject(this Peekable<Token> tokens)
{
while (tokens.Peek(out var token))
{
tokens.Consume();
if (token.Is(TokenType.Symbol, "}") || token.Is(TokenType.Symbol, ";"))
return true;
}
return false;
}
public static string Consume(this Peekable<Token> tokens, TokenType type)
{
var token = tokens.Read();
token.Assert(type);
string s = token.Value;
tokens.Consume();
return s;
}
private static class EnumCache<T>
{
private static readonly Dictionary<string, T> lookup;
public static bool TryGet(string name, out T value) => lookup.TryGetValue(name, out value);
static EnumCache()
{
var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
var tmp = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
foreach (var field in fields)
{
string name = field.Name;
var attrib = (ProtoEnumAttribute)field.GetCustomAttributes(false).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(attrib?.Name)) name = attrib.Name;
var val = (T)field.GetValue(null);
tmp.Add(name, val);
}
lookup = tmp;
}
}
internal static T ConsumeEnum<T>(this Peekable<Token> tokens) where T : struct
{
var token = tokens.Read();
var value = tokens.ConsumeString();
if (!EnumCache<T>.TryGet(token.Value, out T val))
token.Throw(ErrorCode.InvalidEnum, "Unable to parse " + typeof(T).Name);
return val;
}
internal static bool TryParseUInt32(string token, out uint val, uint? max = null)
{
if (max.HasValue && token == "max")
{
val = max.GetValueOrDefault();
return true;
}
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && uint.TryParse(token.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out val))
{
return true;
}
return uint.TryParse(token, NumberStyles.Integer | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out val);
}
internal static bool TryParseUInt64(string token, out ulong val, ulong? max = null)
{
if (max.HasValue && token == "max")
{
val = max.GetValueOrDefault();
return true;
}
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && ulong.TryParse(token.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out val))
{
return true;
}
return ulong.TryParse(token, NumberStyles.Integer | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out val);
}
internal static bool TryParseInt32(string token, out int val, int? max = null)
{
if (max.HasValue && token == "max")
{
val = max.GetValueOrDefault();
return true;
}
if (token.StartsWith("-0x", StringComparison.OrdinalIgnoreCase) && int.TryParse(token.Substring(3), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out val))
{
val = -val;
return true;
}
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && int.TryParse(token.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out val))
{
return true;
}
return int.TryParse(token, NumberStyles.Integer | NumberStyles.AllowLeadingSign | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out val);
}
internal static bool TryParseInt64(string token, out long val, long? max = null)
{
if (max.HasValue && token == "max")
{
val = max.GetValueOrDefault();
return true;
}
if (token.StartsWith("-0x", StringComparison.OrdinalIgnoreCase) && long.TryParse(token.Substring(3), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out val))
{
val = -val;
return true;
}
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && long.TryParse(token.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out val))
{
return true;
}
return long.TryParse(token, NumberStyles.Integer | NumberStyles.AllowLeadingSign | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out val);
}
internal static int ConsumeInt32(this Peekable<Token> tokens, int? max = null)
{
var token = tokens.Read();
token.Assert(TokenType.AlphaNumeric);
tokens.Consume();
if (TryParseInt32(token.Value, out int val, max)) return val;
throw token.Throw(ErrorCode.InvalidInteger, "Unable to parse integer");
}
internal static string ConsumeString(this Peekable<Token> tokens, bool asBytes = false)
{
var token = tokens.Read();
switch (token.Type)
{
case TokenType.StringLiteral:
MemoryStream ms = null;
do
{
ReadStringBytes(ref ms, token.Value);
tokens.Consume();
} while (tokens.Peek(out token) && token.Type == TokenType.StringLiteral); // literal concat is a thing
if (ms == null) return "";
if (!asBytes)
{
#if NETSTANDARD1_3
string s = ms.TryGetBuffer(out var segment)
? Encoding.UTF8.GetString(segment.Array, segment.Offset, segment.Count)
: Encoding.UTF8.GetString(ms.ToArray());
#else
string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
#endif
return s.Replace("\\", @"\\")
.Replace("\'", @"\'")
.Replace("\"", @"\""")
.Replace("\r", @"\r")
.Replace("\n", @"\n")
.Replace("\t", @"\t");
}
var sb = new StringBuilder((int)ms.Length);
int b;
ms.Position = 0;
while ((b = ms.ReadByte()) >= 0)
{
switch (b)
{
case '\n': sb.Append(@"\n"); break;
case '\r': sb.Append(@"\r"); break;
case '\t': sb.Append(@"\t"); break;
case '\'': sb.Append(@"\'"); break;
case '\"': sb.Append(@"\"""); break;
case '\\': sb.Append(@"\\"); break;
default:
if (b >= 32 && b < 127)
{
sb.Append((char)b);
}
else
{
// encode as 3-part octal
sb.Append('\\')
.Append((char)(((b >> 6) & 7) + (int)'0'))
.Append((char)(((b >> 3) & 7) + (int)'0'))
.Append((char)(((b >> 0) & 7) + (int)'0'));
}
break;
}
}
return sb.ToString();
case TokenType.AlphaNumeric:
tokens.Consume();
return token.Value;
default:
throw token.Throw(ErrorCode.InvalidString);
}
}
// the normalized output *includes* the slashes, but expands octal to 3 places;
// it is the job of codegen to change this normalized form to the target language form
internal static void ReadStringBytes(ref MemoryStream ms, string value)
{
void AppendAscii(MemoryStream target, string ascii)
{
foreach (char c in ascii)
target.WriteByte(checked((byte)c));
}
void AppendByte(MemoryStream target, ref uint codePoint, ref int len)
{
if (len != 0)
{
target.WriteByte(checked((byte)codePoint));
}
codePoint = 0;
len = 0;
}
unsafe void AppendNormalized(MemoryStream target, ref uint codePoint, ref int len)
{
if (len == 0)
{
codePoint = 0;
return;
}
byte* b = stackalloc byte[10];
char c = checked((char)codePoint);
int count = Encoding.UTF8.GetBytes(&c, 1, b, 10);
for (int i = 0; i < count; i++)
{
target.WriteByte(b[i]);
}
}
void AppendEscaped(MemoryStream target, char c)
{
uint codePoint;
switch (c)
{
// encoded as octal
case 'a': codePoint = '\a'; break;
case 'b': codePoint = '\b'; break;
case 'f': codePoint = '\f'; break;
case 'v': codePoint = '\v'; break;
case 't': codePoint = '\t'; break;
case 'n': codePoint = '\n'; break;
case 'r': codePoint = '\r'; break;
case '\\':
case '?':
case '\'':
case '\"':
codePoint = c;
break;
default:
codePoint = '?';
break;
}
int len = 1;
AppendNormalized(target, ref codePoint, ref len);
}
bool GetHexValue(char c, out uint val, ref int len)
{
len++;
if (c >= '0' && c <= '9')
{
val = (uint)c - (uint)'0';
return true;
}
if (c >= 'a' && c <= 'f')
{
val = 10 + (uint)c - (uint)'a';
return true;
}
if (c >= 'A' && c <= 'F')
{
val = 10 + (uint)c - (uint)'A';
return true;
}
len--;
val = 0;
return false;
}
const int STATE_NORMAL = 0, STATE_ESCAPE = 1, STATE_OCTAL = 2, STATE_HEX = 3;
int state = STATE_NORMAL;
if (value == null || value.Length == 0) return;
if (ms == null) ms = new MemoryStream(value.Length);
uint escapedCodePoint = 0;
int escapeLength = 0;
foreach (char c in value)
{
switch (state)
{
case STATE_ESCAPE:
if (c >= '0' && c <= '7')
{
state = STATE_OCTAL;
GetHexValue(c, out escapedCodePoint, ref escapeLength); // not a typo; all 1-char octal values are also the same in hex
}
else if (c == 'x')
{
state = STATE_HEX;
}
else if (c == 'u' || c == 'U')
{
throw new NotSupportedException("Unicode escape points: on my todo list");
}
else
{
state = STATE_NORMAL;
AppendEscaped(ms, c);
}
break;
case STATE_OCTAL:
if (c >= '0' && c <= '7')
{
GetHexValue(c, out var x, ref escapeLength);
escapedCodePoint = (escapedCodePoint << 3) | x;
if (escapeLength == 3)
{
AppendByte(ms, ref escapedCodePoint, ref escapeLength);
state = STATE_NORMAL;
}
}
else
{
// not an octal char - regular append
if (escapeLength == 0)
{
// include the malformed \x
AppendAscii(ms, @"\x");
}
else
{
AppendByte(ms, ref escapedCodePoint, ref escapeLength);
}
state = STATE_NORMAL;
goto case STATE_NORMAL;
}
break;
case STATE_HEX:
{
if (GetHexValue(c, out var x, ref escapeLength))
{
escapedCodePoint = (escapedCodePoint << 4) | x;
if (escapeLength == 2)
{
AppendByte(ms, ref escapedCodePoint, ref escapeLength);
state = STATE_NORMAL;
}
}
else
{
// not a hex char - regular append
AppendByte(ms, ref escapedCodePoint, ref escapeLength);
state = STATE_NORMAL;
goto case STATE_NORMAL;
}
}
break;
case STATE_NORMAL:
if (c == '\\')
{
state = STATE_ESCAPE;
}
else
{
uint codePoint = (uint)c;
int len = 1;
AppendNormalized(ms, ref codePoint, ref len);
}
break;
default:
throw new InvalidOperationException();
}
}
// append any trailing escaped data
AppendByte(ms, ref escapedCodePoint, ref escapeLength);
}
internal static bool ConsumeBoolean(this Peekable<Token> tokens)
{
var token = tokens.Read();
token.Assert(TokenType.AlphaNumeric);
tokens.Consume();
if (string.Equals("true", token.Value, StringComparison.OrdinalIgnoreCase)) return true;
if (string.Equals("false", token.Value, StringComparison.OrdinalIgnoreCase)) return false;
throw token.Throw(ErrorCode.InvalidBoolean, "Unable to parse boolean");
}
private static TokenType Identify(char c)
{
if (c == '"' || c == '\'') return TokenType.StringLiteral;
if (char.IsWhiteSpace(c)) return TokenType.Whitespace;
if (char.IsLetterOrDigit(c)) return TokenType.AlphaNumeric;
switch (c)
{
case '_':
case '.':
case '-':
return TokenType.AlphaNumeric;
}
return TokenType.Symbol;
}
public static IEnumerable<Token> RemoveCommentsAndWhitespace(this IEnumerable<Token> tokens)
{
int commentLineNumber = -1;
bool isBlockComment = false;
foreach (var token in tokens)
{
if (isBlockComment)
{
// swallow everything until the end of the block comment
if (token.Is(TokenType.Symbol, "*/"))
isBlockComment = false;
}
else if (commentLineNumber == token.LineNumber)
{
// swallow everything else on that line
}
else if (token.Is(TokenType.Whitespace))
{
continue;
}
else if (token.Is(TokenType.Symbol, "//"))
{
commentLineNumber = token.LineNumber;
}
else if (token.Is(TokenType.Symbol, "/*"))
{
isBlockComment = true;
}
else
{
yield return token;
}
}
}
private static bool CanCombine(TokenType type, int len, char prev, char next)
=> type != TokenType.Symbol
|| (len == 1 && prev == '/' && (next == '/' || next == '*'))
|| (len == 1 && prev == '*' && next == '/');
public static IEnumerable<Token> Tokenize(this TextReader reader, string file)
{
var buffer = new StringBuilder();
int lineNumber = 0, offset = 0;
string line;
string lastLine = null;
while ((line = reader.ReadLine()) != null)
{
lastLine = line;
lineNumber++;
int columnNumber = 0, tokenStart = 1;
char lastChar = '\0', stringType = '\0';
TokenType type = TokenType.None;
bool isEscaped = false;
foreach (char c in line)
{
columnNumber++;
if (type == TokenType.StringLiteral)
{
if (c == stringType && !isEscaped)
{
yield return new Token(buffer.ToString(), lineNumber, tokenStart, type, line, offset++, file);
buffer.Clear();
type = TokenType.None;
}
else
{
buffer.Append(c);
isEscaped = !isEscaped && c == '\\'; // ends an existing escape or starts a new one
}
}
else
{
var newType = Identify(c);
if (newType == type && CanCombine(type, buffer.Length, lastChar, c))
{
buffer.Append(c);
}
else
{
if (buffer.Length != 0)
{
yield return new Token(buffer.ToString(), lineNumber, tokenStart, type, line, offset++, file);
buffer.Clear();
}
type = newType;
tokenStart = columnNumber;
if (newType == TokenType.StringLiteral)
{
stringType = c;
}
else
{
buffer.Append(c);
}
}
}
lastChar = c;
}
if (buffer.Length != 0)
{
yield return new Token(buffer.ToString(), lineNumber, tokenStart, type, lastLine, offset++, file);
buffer.Clear();
}
}
}
internal static bool TryParseSingle(string token, out float val)
{
if (token == "nan")
{
val = float.NaN;
return true;
}
if (token == "inf")
{
val = float.PositiveInfinity;
return true;
}
if (token == "-inf")
{
val = float.NegativeInfinity;
return true;
}
return float.TryParse(token, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out val);
}
internal static bool TryParseDouble(string token, out double val)
{
if (token == "nan")
{
val = double.NaN;
return true;
}
if (token == "inf")
{
val = double.PositiveInfinity;
return true;
}
if (token == "-inf")
{
val = double.NegativeInfinity;
return true;
}
return double.TryParse(token, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out val);
}
}
}
| 39.083861 | 184 | 0.418445 | [
"Apache-2.0"
] | 2bam-at-tlon/protobuf-net | src/protobuf-net.Reflection/TokenExtensions.cs | 24,703 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Devvcat.SSMS.Options
{
[Guid("5F238789-E306-48AE-93D6-44FCC2EAAC80")]
internal class GeneralOptionsPage : DialogPage
{
[Category("Execute Options")]
[DisplayName("Execute inner statements")]
[Description("Execute inner statements instead of block")]
[DefaultValue(false)]
public bool ExecuteInnerStatements { get; set; }
protected override void OnActivate(CancelEventArgs e)
{
ExecuteInnerStatements = Properties.Settings.Default.ExecuteInnerStatements;
base.OnActivate(e);
}
protected override void OnApply(PageApplyEventArgs e)
{
Properties.Settings.Default.ExecuteInnerStatements = ExecuteInnerStatements;
Properties.Settings.Default.Save();
base.OnApply(e);
}
}
}
| 28.837838 | 88 | 0.686973 | [
"MIT"
] | devvcat/ssms-executor | SSMSExecutor/Options/GeneralOptionsPage.cs | 1,069 | C# |
using WebPlatform.Core.Composition;
using WebPlatform.Core.Validation;
namespace WebPlatform.Core.Logging
{
/// <summary>
/// Provides logging services.
/// </summary>
public class LoggingModule : Module
{
/// <summary>
/// Initializes a new instance of the <see cref="LoggingModule"/> class.
/// </summary>
/// <param name="registrar">The service registrar. Must not be <see langword="null" />.</param>
public LoggingModule([NotNull] IRegistrar registrar) :
base(registrar)
{
registrar.Register(typeof(ILogger<>), typeof(Logger<>));
}
}
} | 29.714286 | 101 | 0.628205 | [
"MIT"
] | urahnung/webplatform | src/Core/Logging/LoggingModule.cs | 626 | C# |
namespace BenMAP
{
partial class ManageIncidenceDataSets
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.grpCancelOK = new System.Windows.Forms.GroupBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnViewMetadata = new System.Windows.Forms.Button();
this.grpDataSetIncidenceRate = new System.Windows.Forms.GroupBox();
this.chbGroup = new System.Windows.Forms.CheckBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.txtFilter = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.cboEndpointGroup = new System.Windows.Forms.ComboBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.cboEndpoint = new System.Windows.Forms.ComboBox();
this.olvIncidenceRates = new BrightIdeasSoftware.DataListView();
this.olvcEndpointGroup = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvcEndpoint = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn3 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn4 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn5 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn6 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn7 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.olvColumn8 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
this.grpAvailableDataSets = new System.Windows.Forms.GroupBox();
this.btnEdit = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.lstAvailableDataSets = new System.Windows.Forms.ListBox();
this.grpCancelOK.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.grpDataSetIncidenceRate.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.olvIncidenceRates)).BeginInit();
this.grpAvailableDataSets.SuspendLayout();
this.SuspendLayout();
//
// grpCancelOK
//
this.grpCancelOK.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grpCancelOK.Controls.Add(this.flowLayoutPanel1);
this.grpCancelOK.Location = new System.Drawing.Point(12, 402);
this.grpCancelOK.Name = "grpCancelOK";
this.grpCancelOK.Size = new System.Drawing.Size(770, 53);
this.grpCancelOK.TabIndex = 2;
this.grpCancelOK.TabStop = false;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.btnOK);
this.flowLayoutPanel1.Controls.Add(this.btnCancel);
this.flowLayoutPanel1.Controls.Add(this.btnViewMetadata);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 18);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(764, 32);
this.flowLayoutPanel1.TabIndex = 0;
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.Location = new System.Drawing.Point(686, 3);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 27);
this.btnOK.TabIndex = 2;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.Location = new System.Drawing.Point(605, 3);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 27);
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Visible = false;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnViewMetadata
//
this.btnViewMetadata.Enabled = false;
this.btnViewMetadata.Location = new System.Drawing.Point(487, 3);
this.btnViewMetadata.Name = "btnViewMetadata";
this.btnViewMetadata.Size = new System.Drawing.Size(112, 27);
this.btnViewMetadata.TabIndex = 0;
this.btnViewMetadata.Text = "View Metadata";
this.btnViewMetadata.UseVisualStyleBackColor = true;
this.btnViewMetadata.Click += new System.EventHandler(this.btnViewMetadata_Click);
//
// grpDataSetIncidenceRate
//
this.grpDataSetIncidenceRate.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.grpDataSetIncidenceRate.Controls.Add(this.chbGroup);
this.grpDataSetIncidenceRate.Controls.Add(this.groupBox3);
this.grpDataSetIncidenceRate.Controls.Add(this.groupBox1);
this.grpDataSetIncidenceRate.Controls.Add(this.groupBox2);
this.grpDataSetIncidenceRate.Controls.Add(this.olvIncidenceRates);
this.grpDataSetIncidenceRate.Location = new System.Drawing.Point(233, 8);
this.grpDataSetIncidenceRate.Name = "grpDataSetIncidenceRate";
this.grpDataSetIncidenceRate.Size = new System.Drawing.Size(549, 388);
this.grpDataSetIncidenceRate.TabIndex = 1;
this.grpDataSetIncidenceRate.TabStop = false;
this.grpDataSetIncidenceRate.Text = "Dataset Incidence Rates";
//
// chbGroup
//
this.chbGroup.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.chbGroup.AutoSize = true;
this.chbGroup.Location = new System.Drawing.Point(481, 357);
this.chbGroup.Name = "chbGroup";
this.chbGroup.Size = new System.Drawing.Size(59, 18);
this.chbGroup.TabIndex = 4;
this.chbGroup.Text = "Group";
this.chbGroup.UseVisualStyleBackColor = true;
this.chbGroup.CheckedChanged += new System.EventHandler(this.chbGroup_CheckedChanged);
//
// groupBox3
//
this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.groupBox3.Controls.Add(this.txtFilter);
this.groupBox3.Location = new System.Drawing.Point(375, 337);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(100, 46);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Filter";
//
// txtFilter
//
this.txtFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.txtFilter.Location = new System.Drawing.Point(6, 16);
this.txtFilter.Name = "txtFilter";
this.txtFilter.Size = new System.Drawing.Size(88, 22);
this.txtFilter.TabIndex = 0;
this.txtFilter.TextChanged += new System.EventHandler(this.txtFilter_TextChanged);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.groupBox1.Controls.Add(this.cboEndpointGroup);
this.groupBox1.Location = new System.Drawing.Point(6, 337);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 46);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Filter Endpoint Group";
//
// cboEndpointGroup
//
this.cboEndpointGroup.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cboEndpointGroup.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboEndpointGroup.FormattingEnabled = true;
this.cboEndpointGroup.Location = new System.Drawing.Point(6, 16);
this.cboEndpointGroup.Name = "cboEndpointGroup";
this.cboEndpointGroup.Size = new System.Drawing.Size(188, 22);
this.cboEndpointGroup.TabIndex = 0;
this.cboEndpointGroup.SelectedIndexChanged += new System.EventHandler(this.cboEndpointGroup_SelectedIndexChanged);
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.groupBox2.Controls.Add(this.cboEndpoint);
this.groupBox2.Location = new System.Drawing.Point(211, 337);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(160, 46);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Filter Endpoint";
//
// cboEndpoint
//
this.cboEndpoint.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cboEndpoint.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboEndpoint.FormattingEnabled = true;
this.cboEndpoint.Location = new System.Drawing.Point(6, 16);
this.cboEndpoint.Name = "cboEndpoint";
this.cboEndpoint.Size = new System.Drawing.Size(148, 22);
this.cboEndpoint.TabIndex = 0;
this.cboEndpoint.SelectedIndexChanged += new System.EventHandler(this.cboEndpoint_SelectedIndexChanged);
//
// olvIncidenceRates
//
this.olvIncidenceRates.AllColumns.Add(this.olvcEndpointGroup);
this.olvIncidenceRates.AllColumns.Add(this.olvcEndpoint);
this.olvIncidenceRates.AllColumns.Add(this.olvColumn3);
this.olvIncidenceRates.AllColumns.Add(this.olvColumn4);
this.olvIncidenceRates.AllColumns.Add(this.olvColumn5);
this.olvIncidenceRates.AllColumns.Add(this.olvColumn6);
this.olvIncidenceRates.AllColumns.Add(this.olvColumn7);
this.olvIncidenceRates.AllColumns.Add(this.olvColumn8);
this.olvIncidenceRates.AllowColumnReorder = true;
this.olvIncidenceRates.AllowDrop = true;
this.olvIncidenceRates.AlternateRowBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(240)))), ((int)(((byte)(220)))));
this.olvIncidenceRates.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.olvIncidenceRates.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvcEndpointGroup,
this.olvcEndpoint,
this.olvColumn3,
this.olvColumn4,
this.olvColumn5,
this.olvColumn6,
this.olvColumn7,
this.olvColumn8});
this.olvIncidenceRates.Cursor = System.Windows.Forms.Cursors.Default;
this.olvIncidenceRates.DataSource = null;
this.olvIncidenceRates.EmptyListMsg = "This list is empty.";
this.olvIncidenceRates.FullRowSelect = true;
this.olvIncidenceRates.GridLines = true;
this.olvIncidenceRates.GroupWithItemCountFormat = "";
this.olvIncidenceRates.GroupWithItemCountSingularFormat = "";
this.olvIncidenceRates.HeaderUsesThemes = false;
this.olvIncidenceRates.HideSelection = false;
this.olvIncidenceRates.Location = new System.Drawing.Point(3, 17);
this.olvIncidenceRates.MultiSelect = false;
this.olvIncidenceRates.Name = "olvIncidenceRates";
this.olvIncidenceRates.OwnerDraw = true;
this.olvIncidenceRates.SelectColumnsOnRightClickBehaviour = BrightIdeasSoftware.ObjectListView.ColumnSelectBehaviour.Submenu;
this.olvIncidenceRates.ShowCommandMenuOnRightClick = true;
this.olvIncidenceRates.ShowGroups = false;
this.olvIncidenceRates.ShowImagesOnSubItems = true;
this.olvIncidenceRates.ShowItemToolTips = true;
this.olvIncidenceRates.Size = new System.Drawing.Size(543, 318);
this.olvIncidenceRates.TabIndex = 0;
this.olvIncidenceRates.UseAlternatingBackColors = true;
this.olvIncidenceRates.UseCompatibleStateImageBehavior = false;
this.olvIncidenceRates.UseFiltering = true;
this.olvIncidenceRates.UseHotItem = true;
this.olvIncidenceRates.UseHyperlinks = true;
this.olvIncidenceRates.View = System.Windows.Forms.View.Details;
this.olvIncidenceRates.SelectedIndexChanged += new System.EventHandler(this.olvIncidenceRates_SelectedIndexChanged);
//
// olvcEndpointGroup
//
this.olvcEndpointGroup.AspectName = "EndPointGroupName";
this.olvcEndpointGroup.Text = "Endpoint Group";
this.olvcEndpointGroup.Width = 98;
//
// olvcEndpoint
//
this.olvcEndpoint.AspectName = "EndPointName";
this.olvcEndpoint.Text = "Endpoint";
this.olvcEndpoint.Width = 78;
//
// olvColumn3
//
this.olvColumn3.AspectName = "Prevalence";
this.olvColumn3.Text = "Type";
//
// olvColumn4
//
this.olvColumn4.AspectName = "RaceName";
this.olvColumn4.Text = "Race";
//
// olvColumn5
//
this.olvColumn5.AspectName = "EthnicityName";
this.olvColumn5.Text = "Ethnicity";
//
// olvColumn6
//
this.olvColumn6.AspectName = "GenderName";
this.olvColumn6.Text = "Gender";
//
// olvColumn7
//
this.olvColumn7.AspectName = "StartAge";
this.olvColumn7.Text = "Start Age";
//
// olvColumn8
//
this.olvColumn8.AspectName = "EndAge";
this.olvColumn8.Text = "End Age";
//
// grpAvailableDataSets
//
this.grpAvailableDataSets.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.grpAvailableDataSets.Controls.Add(this.btnEdit);
this.grpAvailableDataSets.Controls.Add(this.btnAdd);
this.grpAvailableDataSets.Controls.Add(this.btnDelete);
this.grpAvailableDataSets.Controls.Add(this.lstAvailableDataSets);
this.grpAvailableDataSets.Location = new System.Drawing.Point(13, 8);
this.grpAvailableDataSets.Name = "grpAvailableDataSets";
this.grpAvailableDataSets.Size = new System.Drawing.Size(214, 388);
this.grpAvailableDataSets.TabIndex = 0;
this.grpAvailableDataSets.TabStop = false;
this.grpAvailableDataSets.Text = "Available Datasets";
//
// btnEdit
//
this.btnEdit.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnEdit.Location = new System.Drawing.Point(147, 349);
this.btnEdit.Name = "btnEdit";
this.btnEdit.Size = new System.Drawing.Size(61, 27);
this.btnEdit.TabIndex = 3;
this.btnEdit.Text = "Edit";
this.btnEdit.UseVisualStyleBackColor = true;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// btnAdd
//
this.btnAdd.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnAdd.Location = new System.Drawing.Point(82, 349);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(59, 27);
this.btnAdd.TabIndex = 2;
this.btnAdd.Text = "Add";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnDelete
//
this.btnDelete.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnDelete.Location = new System.Drawing.Point(17, 348);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(59, 27);
this.btnDelete.TabIndex = 1;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// lstAvailableDataSets
//
this.lstAvailableDataSets.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.lstAvailableDataSets.FormattingEnabled = true;
this.lstAvailableDataSets.HorizontalScrollbar = true;
this.lstAvailableDataSets.ItemHeight = 14;
this.lstAvailableDataSets.Location = new System.Drawing.Point(7, 17);
this.lstAvailableDataSets.Name = "lstAvailableDataSets";
this.lstAvailableDataSets.Size = new System.Drawing.Size(201, 312);
this.lstAvailableDataSets.TabIndex = 0;
this.lstAvailableDataSets.SelectedValueChanged += new System.EventHandler(this.lstAvailableDataSets_SelectedValueChanged);
//
// ManageIncidenceDataSets
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 14F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(794, 459);
this.Controls.Add(this.grpCancelOK);
this.Controls.Add(this.grpDataSetIncidenceRate);
this.Controls.Add(this.grpAvailableDataSets);
this.Name = "ManageIncidenceDataSets";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Manage Incidence Datasets";
this.Load += new System.EventHandler(this.ManageIncidenceDataSets_Load);
this.grpCancelOK.ResumeLayout(false);
this.flowLayoutPanel1.ResumeLayout(false);
this.grpDataSetIncidenceRate.ResumeLayout(false);
this.grpDataSetIncidenceRate.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.olvIncidenceRates)).EndInit();
this.grpAvailableDataSets.ResumeLayout(false);
this.ResumeLayout(false);
}
private System.Windows.Forms.GroupBox grpAvailableDataSets;
private System.Windows.Forms.ListBox lstAvailableDataSets;
private System.Windows.Forms.GroupBox grpDataSetIncidenceRate;
private System.Windows.Forms.Button btnEdit;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.GroupBox grpCancelOK;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private BrightIdeasSoftware.OLVColumn olvcEndpointGroup;
private BrightIdeasSoftware.OLVColumn olvcEndpoint;
private BrightIdeasSoftware.OLVColumn olvColumn3;
private BrightIdeasSoftware.OLVColumn olvColumn4;
private BrightIdeasSoftware.OLVColumn olvColumn5;
private BrightIdeasSoftware.OLVColumn olvColumn6;
private BrightIdeasSoftware.OLVColumn olvColumn7;
private BrightIdeasSoftware.OLVColumn olvColumn8;
public BrightIdeasSoftware.DataListView olvIncidenceRates;
private System.Windows.Forms.CheckBox chbGroup;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.TextBox txtFilter;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ComboBox cboEndpointGroup;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.ComboBox cboEndpoint;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Button btnViewMetadata;
}
} | 47.73747 | 163 | 0.737376 | [
"Apache-2.0"
] | BenMAPCE/BenMAP-CE | BenMAP/ManageSetup/ManageIncidenceDataSets.Designer.cs | 20,002 | C# |
// MIT License
//
// Copyright(c) 2017 Luciano (Xeeynamo) Ciccariello
//
// 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.IO;
using RSDK;
namespace RSDK2
{
public class Frame : IFrame
{
public int SpriteSheet { get; set; }
public int CollisionBox { get; set; }
public int Id { get => 0; set { } }
public bool flag1 { get => false; set { } }
public bool flag2 { get => false; set { } }
public int Duration
{
get => 256;
set { }
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int CenterX { get; set; }
public int CenterY { get; set; }
public IHitbox GetHitbox(int index)
{
return new Hitbox();
}
public void SaveChanges(BinaryWriter writer)
{
Write(writer);
}
public void Read(BinaryReader reader)
{
// byte 1 - Number of image the frame is located in
// byte 2 - Collision Box
// byte 3 - X position in image of the frame
// byte 4 - Y position in image of the frame
// byte 5 - Width of frame
// byte 6 - Height of frame
// byte 7 - Hot spot horizontal displacement
// byte 8 - Hot spot vertical displacement
SpriteSheet = reader.ReadByte();
CollisionBox = reader.ReadByte();
X = reader.ReadByte();
Y = reader.ReadByte();
Width = reader.ReadByte();
Height = reader.ReadByte();
CenterX = reader.ReadSByte();
CenterY = reader.ReadSByte();
Id = 0;
}
public void Read(BinaryReader reader, bool BitFlipped = false)
{
// byte 1 - Number of image the frame is located in
// byte 2 - Collision Box
// byte 3 - X position in image of the frame
// byte 4 - Y position in image of the frame
// byte 5 - Width of frame
// byte 6 - Height of frame
// byte 7 - Hot spot horizontal displacement
// byte 8 - Hot spot vertical displacement
SpriteSheet = reader.ReadByte();
CollisionBox = reader.ReadByte();
X = reader.ReadByte();
Y = reader.ReadByte();
Width = reader.ReadByte();
Height = reader.ReadByte();
CenterX = reader.ReadSByte();
CenterY = reader.ReadSByte();
if (BitFlipped)
{
SpriteSheet ^= 255;
CollisionBox ^= 255;
X ^= 255;
Y ^= 255;
Width ^= 255;
Height ^= 255;
byte cx = (byte)CenterX;
byte cy = (byte)CenterY;
cx ^= 255;
cy ^= 255;
CenterX = (sbyte)cx;
CenterY = (sbyte)cy;
}
Id = 0;
}
public void Write(BinaryWriter writer)
{
writer.Write((byte)SpriteSheet);
writer.Write((byte)CollisionBox);
writer.Write((byte)X);
writer.Write((byte)Y);
writer.Write((byte)Width);
writer.Write((byte)Height);
writer.Write((byte)CenterX);
writer.Write((byte)CenterY);
}
public object Clone()
{
return new Frame()
{
SpriteSheet = SpriteSheet,
CollisionBox = CollisionBox,
X = X,
Y = Y,
Width = Width,
Height = Height,
CenterX = CenterX,
CenterY = CenterY
};
}
}
}
| 33.006536 | 82 | 0.518416 | [
"MIT"
] | Rubberduckycooly/RSDK | RSDK2/Animation.Frame.cs | 5,052 | C# |
/*
* nlpapiv2
*
* The powerful Natural Language Processing APIs (v2) let you perform part of speech tagging, entity identification, sentence parsing, and much more to help you understand the meaning of unstructured text.
*
* OpenAPI spec version: v1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = Cloudmersive.APIClient.NETCore.NLP.Client.SwaggerDateConverter;
namespace Cloudmersive.APIClient.NETCore.NLP.Model
{
/// <summary>
/// Output of a similarity analysis operation
/// </summary>
[DataContract]
public partial class SimilarityAnalysisResponse : IEquatable<SimilarityAnalysisResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="SimilarityAnalysisResponse" /> class.
/// </summary>
/// <param name="successful">True if the similarity analysis operation was successful, false otherwise.</param>
/// <param name="similarityScoreResult">Similarity score between 0.0 and 1.0 where scores closer to zero have a low probability of semantic similarity, while scores close to 1.0 have a high probability of semantic similarity..</param>
/// <param name="sentenceCount">Number of sentences in input text.</param>
public SimilarityAnalysisResponse(bool? successful = default(bool?), double? similarityScoreResult = default(double?), int? sentenceCount = default(int?))
{
this.Successful = successful;
this.SimilarityScoreResult = similarityScoreResult;
this.SentenceCount = sentenceCount;
}
/// <summary>
/// True if the similarity analysis operation was successful, false otherwise
/// </summary>
/// <value>True if the similarity analysis operation was successful, false otherwise</value>
[DataMember(Name="Successful", EmitDefaultValue=false)]
public bool? Successful { get; set; }
/// <summary>
/// Similarity score between 0.0 and 1.0 where scores closer to zero have a low probability of semantic similarity, while scores close to 1.0 have a high probability of semantic similarity.
/// </summary>
/// <value>Similarity score between 0.0 and 1.0 where scores closer to zero have a low probability of semantic similarity, while scores close to 1.0 have a high probability of semantic similarity.</value>
[DataMember(Name="SimilarityScoreResult", EmitDefaultValue=false)]
public double? SimilarityScoreResult { get; set; }
/// <summary>
/// Number of sentences in input text
/// </summary>
/// <value>Number of sentences in input text</value>
[DataMember(Name="SentenceCount", EmitDefaultValue=false)]
public int? SentenceCount { 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 SimilarityAnalysisResponse {\n");
sb.Append(" Successful: ").Append(Successful).Append("\n");
sb.Append(" SimilarityScoreResult: ").Append(SimilarityScoreResult).Append("\n");
sb.Append(" SentenceCount: ").Append(SentenceCount).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 virtual 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 SimilarityAnalysisResponse);
}
/// <summary>
/// Returns true if SimilarityAnalysisResponse instances are equal
/// </summary>
/// <param name="input">Instance of SimilarityAnalysisResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SimilarityAnalysisResponse input)
{
if (input == null)
return false;
return
(
this.Successful == input.Successful ||
(this.Successful != null &&
this.Successful.Equals(input.Successful))
) &&
(
this.SimilarityScoreResult == input.SimilarityScoreResult ||
(this.SimilarityScoreResult != null &&
this.SimilarityScoreResult.Equals(input.SimilarityScoreResult))
) &&
(
this.SentenceCount == input.SentenceCount ||
(this.SentenceCount != null &&
this.SentenceCount.Equals(input.SentenceCount))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Successful != null)
hashCode = hashCode * 59 + this.Successful.GetHashCode();
if (this.SimilarityScoreResult != null)
hashCode = hashCode * 59 + this.SimilarityScoreResult.GetHashCode();
if (this.SentenceCount != null)
hashCode = hashCode * 59 + this.SentenceCount.GetHashCode();
return hashCode;
}
}
}
}
| 42.02027 | 242 | 0.609905 | [
"Apache-2.0"
] | Cloudmersive/Cloudmersive.APIClient.NETCore.NLP | client/src/Cloudmersive.APIClient.NETCore.NLP/Model/SimilarityAnalysisResponse.cs | 6,219 | C# |
using System.Web;
using System.Web.Mvc;
namespace ExpressFormsExample
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | 20.846154 | 80 | 0.667897 | [
"MIT"
] | DanielLangdon/ExpressForms | ExpressForms/ExpressFormsExample/App_Start/FilterConfig.cs | 273 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.Language.Intellisense
{
/// <summary>
/// Represents an individual parameter description inside the description of a signature.
/// </summary>
public interface IParameter
{
/// <summary>
/// Gets the signature of which this parameter is a part.
/// </summary>
ISignature Signature { get; }
/// <summary>
/// Gets the name of this parameter.
/// </summary>
/// <remarks>
/// This is displayed to identify the parameter.
/// </remarks>
string Name { get; }
/// <summary>
/// Gets the documentation associated with the parameter.
/// </summary>
/// <remarks>
/// This is displayed to describe
/// the parameter.
/// </remarks>
string Documentation { get; }
/// <summary>
/// Gets the text location of this parameter relative to the signature's content.
/// </summary>
Span Locus { get; }
/// <summary>
/// Gets the text location of this parameter relative to the signature's pretty-printed content.
/// </summary>
Span PrettyPrintedLocus { get; }
}
}
| 33.914894 | 133 | 0.478043 | [
"MIT"
] | AmadeusW/vs-editor-api | src/Editor/Language/Def/Intellisense/IParameter.cs | 1,596 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpIRC.API
{
public class Permissions {
public static bool RequirePermission(Permission permission) { return false; }
public enum Permission {
ACCESS_CONFIGURATION_FILE,
ACCESS_ADMINLIST,
ACCESS_IGNORELIST,
ACCESS_CONNECTIONS
}
}
}
| 22.888889 | 85 | 0.660194 | [
"Apache-2.0"
] | kibmcz/SharpIRC | SharpIRC/SharpIRC/API/Permissions.cs | 414 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core;
using Azure.Core.Pipeline;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Security.KeyVault.Certificates
{
/// <summary>
/// The CertificateClient provides synchronous and asynchronous methods to manage <see cref="Certificate"/>s in Azure Key Vault. The client
/// supports creating, retrieving, updating, deleting, purging, backing up, restoring and listing the <see cref="Certificate"/>, along with managing
/// certificate <see cref="Issuer"/>s and <see cref="Contact"/>s. The client also supports listing <see cref="DeletedCertificate"/> for a soft-delete
/// enabled key vault.
/// </summary>
public class CertificateClient
{
private readonly KeyVaultPipeline _pipeline;
private readonly CertificatePolicy _defaultPolicy;
private const string CertificatesPath = "/certificates/";
private const string DeletedCertificatesPath = "/deletedcertificates/";
private const string IssuersPath = "/certificates/issuers/";
private const string ContactsPath = "/contacts/";
/// <summary>
/// Initializes a new instance of the <see cref="CertificateClient"/> class for mocking.
/// </summary>
protected CertificateClient()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CertificateClient"/> class for the specified vault.
/// </summary>
/// <param name="vaultUri">A <see cref="Uri"/> to the vault on which the client operates. Appears as "DNS Name" in the Azure portal.</param>
/// <param name="credential">A <see cref="TokenCredential"/> used to authenticate requests to the vault, such as DefaultAzureCredential.</param>
public CertificateClient(Uri vaultUri, TokenCredential credential)
: this(vaultUri, credential, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CertificateClient"/> class for the specified vault.
/// </summary>
/// <param name="vaultUri">A <see cref="Uri"/> to the vault on which the client operates. Appears as "DNS Name" in the Azure portal.</param>
/// <param name="credential">A <see cref="TokenCredential"/> used to authenticate requests to the vault, such as DefaultAzureCredential.</param>
/// <param name="options"><see cref="CertificateClientOptions"/> that allow to configure the management of the request sent to Key Vault.</param>
public CertificateClient(Uri vaultUri, TokenCredential credential, CertificateClientOptions options)
{
Argument.AssertNotNull(vaultUri, nameof(vaultUri));
options ??= new CertificateClientOptions();
HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new ChallengeBasedAuthenticationPolicy(credential));
_defaultPolicy = options.DefaultPolicy ?? CreateDefaultPolicy();
_pipeline = new KeyVaultPipeline(vaultUri, options.GetVersionString(), pipeline);
}
// Certificates API
/// <summary>
/// Starts a long running operation to create a self-signed <see cref="Certificate"/> in the vault, using the default certificate policy.
/// </summary>
/// <remarks>
/// If no certificate with the specified name exists it will be created, otherwise a new version of the existing certificate will be created. This operation requires the certificates/create permission.
/// </remarks>
/// <param name="name">The name of the certificate to create</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="CertificateOperation"/> which contians details on the create operation, and can be used to retrieve updated status</returns>
public virtual CertificateOperation StartCreateCertificate(string name, CancellationToken cancellationToken = default)
{
return StartCreateCertificate(name, _defaultPolicy, cancellationToken: cancellationToken);
}
/// <summary>
/// Starts a long running operation to create a <see cref="Certificate"/> in the vault, using the default certificate policy.
/// </summary>
/// <remarks>
/// If no certificate with the specified name exists it will be created, otherwise a new version of the existing certificate will be created. This operation requires the certificates/create permission.
/// </remarks>
/// <param name="name">The name of the certificate to create</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="CertificateOperation"/> which contians details on the create operation, and can be used to retrieve updated status</returns>
public virtual async Task<CertificateOperation> StartCreateCertificateAsync(string name, CancellationToken cancellationToken = default)
{
return await StartCreateCertificateAsync(name, _defaultPolicy, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Starts a long running operation to create a <see cref="Certificate"/> in the vault with the specified certificate policy.
/// </summary>
/// <remarks>
/// If no certificate with the specified name exists it will be created, otherwise a new version of the existing certificate will be created. This operation requires the certificates/create permission.
/// </remarks>
/// <param name="name">The name of the certificate to create</param>
/// <param name="policy">The <see cref="CertificatePolicy"/> which governs the proprerties and lifecycle of the created certificate</param>
/// <param name="enabled">Specifies whether the certificate should be created in an enabled state</param>
/// <param name="tags">Tags to be applied to the created certificate</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="CertificateOperation"/> which contians details on the create operation, and can be used to retrieve updated status</returns>
public virtual CertificateOperation StartCreateCertificate(string name, CertificatePolicy policy, bool? enabled = default, IDictionary<string, string> tags = default, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
Argument.AssertNotNull(policy, nameof(policy));
var parameters = new CertificateCreateParameters(policy, enabled, tags);
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.StartCreateCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
Response<CertificateOperationProperties> response = _pipeline.SendRequest(RequestMethod.Post, parameters, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, name, "/create");
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Starts a long running operation to create a <see cref="Certificate"/> in the vault with the specified certificate policy.
/// </summary>
/// <remarks>
/// If no certificate with the specified name exists it will be created, otherwise a new version of the existing certificate will be created. This operation requires the certificates/create permission.
/// </remarks>
/// <param name="name">The name of the certificate to create</param>
/// <param name="policy">The <see cref="CertificatePolicy"/> which governs the proprerties and lifecycle of the created certificate</param>
/// <param name="enabled">Specifies whether the certificate should be created in an enabled state</param>
/// <param name="tags">Tags to be applied to the created certificate</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="CertificateOperation"/> which contians details on the create operation, and can be used to retrieve updated status</returns>
public virtual async Task<CertificateOperation> StartCreateCertificateAsync(string name, CertificatePolicy policy, bool? enabled = default, IDictionary<string, string> tags = default, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
Argument.AssertNotNull(policy, nameof(policy));
var parameters = new CertificateCreateParameters(policy, enabled, tags);
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.StartCreateCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
Response<CertificateOperationProperties> response = await _pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, name, "/create").ConfigureAwait(false);
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Returns the latest version of the <see cref="Certificate"/> along with it's <see cref="CertificatePolicy"/>. This operation requires the certificates/get permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to retrieve</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A response containing the certificate and policy as a <see cref="CertificateWithPolicy"/> instance</returns>
public virtual Response<CertificateWithPolicy> GetCertificateWithPolicy(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificateWithPolicy");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Get, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Returns the latest version of the <see cref="Certificate"/> along with it's <see cref="CertificatePolicy"/>. This operation requires the certificates/get permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to retrieve</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A response containing the certificate and policy as a <see cref="CertificateWithPolicy"/> instance</returns>
public virtual async Task<Response<CertificateWithPolicy>> GetCertificateWithPolicyAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificateWithPolicy");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets a specific version of the <see cref="Certificate"/>. This operation requires the certificates/get permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to retrieve</param>
/// <param name="version">Ther version of the <see cref="Certificate"/> to retrieve</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The requested <see cref="Certificate"/></returns>
public virtual Response<Certificate> GetCertificate(string name, string version, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Get, () => new Certificate(), cancellationToken, CertificatesPath, name, "/", version);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets a specific version of the <see cref="Certificate"/>. This operation requires the certificates/get permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to retrieve</param>
/// <param name="version">Ther version of the <see cref="Certificate"/> to retrieve</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The requested <see cref="Certificate"/></returns>
public virtual async Task<Response<Certificate>> GetCertificateAsync(string name, string version, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
Argument.AssertNotNullOrEmpty(version, nameof(version));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new Certificate(), cancellationToken, CertificatesPath, name, "/", version).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates the specified <see cref="Certificate"/> with the specified values for its mutable properties. This operation requires the certificates/update permission.
/// </summary>
/// <param name="properties">The <see cref="CertificateProperties"/> object with updated properties.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated <see cref="Certificate"/></returns>
public virtual Response<Certificate> UpdateCertificateProperties(CertificateProperties properties, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(properties, nameof(properties));
var parameters = new CertificateUpdateParameters(properties);
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.UpdateCertificateProperties");
scope.AddAttribute("certificate", properties.Name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Patch, parameters, () => new Certificate(), cancellationToken, CertificatesPath, properties.Name, "/", properties.Version);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates the specified <see cref="Certificate"/> with the specified values for its mutable properties. This operation requires the certificates/update permission.
/// </summary>
/// <param name="properties">The <see cref="CertificateProperties"/> object with updated properties.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated <see cref="Certificate"/></returns>
public virtual async Task<Response<Certificate>> UpdateCertificatePropertiesAsync(CertificateProperties properties, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(properties, nameof(properties));
var parameters = new CertificateUpdateParameters(properties);
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.UpdateCertificateProperties");
scope.AddAttribute("certificate", properties.Name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Patch, parameters, () => new Certificate(), cancellationToken, CertificatesPath, properties.Name, "/", properties.Version).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes all versions of the specified <see cref="Certificate"/>. If the vault is soft delete enabled, the <see cref="Certificate"/> will be marked for perminent deletion
/// and can be recovered with <see cref="RecoverDeletedCertificate"/>, or purged with <see cref="PurgeDeletedCertificate"/>. This operation requires the certificates/delete permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to delete</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The details of the <see cref="DeletedCertificate"/></returns>
public virtual Response<DeletedCertificate> DeleteCertificate(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Delete, () => new DeletedCertificate(), cancellationToken, CertificatesPath, name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes all versions of the specified <see cref="Certificate"/>. If the vault is soft delete enabled, the <see cref="Certificate"/> will be marked for perminent deletion
/// and can be recovered with <see cref="RecoverDeletedCertificate"/>, or purged with <see cref="PurgeDeletedCertificate"/>. This operation requires the certificates/delete permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to delete</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The details of the <see cref="DeletedCertificate"/></returns>
public virtual async Task<Response<DeletedCertificate>> DeleteCertificateAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Delete, () => new DeletedCertificate(), cancellationToken, CertificatesPath, name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Retrieves information about the specified deleted <see cref="Certificate"/>. This operation is only applicable in vaults enabled for soft-delete, and
/// requires the certificates/get permission.
/// </summary>
/// <param name="name">The name of the <see cref="DeletedCertificate"/></param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The details of the <see cref="DeletedCertificate"/></returns>
public virtual Response<DeletedCertificate> GetDeletedCertificate(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetDeletedCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Get, () => new DeletedCertificate(), cancellationToken, DeletedCertificatesPath, name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Retrieves information about the specified deleted <see cref="Certificate"/>. This operation is only applicable in vaults enabled for soft-delete, and
/// requires the certificates/get permission.
/// </summary>
/// <param name="name">The name of the <see cref="DeletedCertificate"/></param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The details of the <see cref="DeletedCertificate"/></returns>
public virtual async Task<Response<DeletedCertificate>> GetDeletedCertificateAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetDeletedCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new DeletedCertificate(), cancellationToken, DeletedCertificatesPath, name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Recovers the <see cref="DeletedCertificate"/> to its pre-deleted state. This operation is only applicable in vaults enabled for soft-delete, and
/// requires the certificates/recover permission.
/// </summary>
/// <param name="name">The name of the <see cref="DeletedCertificate"/></param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The recovered certificate and policy</returns>
public virtual Response<CertificateWithPolicy> RecoverDeletedCertificate(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.RecoverDeletedCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Post, () => new CertificateWithPolicy(), cancellationToken, DeletedCertificatesPath, name, "/recover");
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Recovers the <see cref="DeletedCertificate"/> to its pre-deleted state. This operation is only applicable in vaults enabled for soft-delete, and
/// requires the certificates/recover permission.
/// </summary>
/// <param name="name">The name of the <see cref="DeletedCertificate"/></param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The recovered certificate and policy</returns>
public virtual async Task<Response<CertificateWithPolicy>> RecoverDeletedCertificateAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.RecoverDeletedCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Post, () => new CertificateWithPolicy(), cancellationToken, DeletedCertificatesPath, name, "/recover").ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Permanently and irreversibly deletes the specified deleted certificate, without the possibility of recovery. This operation is only applicable in vaults enabled for soft-delete, and
/// requires the certificates/purge permission. The operation is not available if the DeletedCertificate.RecoveryLevel of the DeletedCertificate does not specify 'Purgeable'.
/// </summary>
/// <param name="name">The name of the <see cref="DeletedCertificate"/> to perminantly delete</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The http response from the service</returns>
public virtual Response PurgeDeletedCertificate(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.PurgeDeletedCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Delete, cancellationToken, DeletedCertificatesPath, name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Permanently and irreversibly deletes the specified deleted certificate, without the possibility of recovery. This operation is only applicable in vaults enabled for soft-delete, and
/// requires the certificates/purge permission. The operation is not available if the DeletedCertificate.RecoveryLevel of the DeletedCertificate does not specify 'Purgeable'.
/// </summary>
/// <param name="name">The name of the <see cref="DeletedCertificate"/> to perminantly delete</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public virtual async Task<Response> PurgeDeletedCertificateAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.PurgeDeletedCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Delete, cancellationToken, DeletedCertificatesPath, name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Creates a backup of the certificate, including all versions, which can be used to restore the certificate to the state at the time of the backup in the case the certificate is deleted, or to
/// restore the certificate to a different vault in the same region as the original value. This operation requires the certificate/backup permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to backup</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The certificate backup</returns>
public virtual Response<byte[]> BackupCertificate(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.BackupCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
Response<CertificateBackup> backup = _pipeline.SendRequest(RequestMethod.Post, () => new CertificateBackup(), cancellationToken, CertificatesPath, name, "/backup");
return Response.FromValue(backup.Value.Value, backup.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Creates a backup of the certificate, including all versions, which can be used to restore the certificate to the state at the time of the backup in the case the certificate is deleted, or to
/// restore the certificate to a different vault in the same region as the original value. This operation requires the certificate/backup permission.
/// </summary>
/// <param name="name">The name of the <see cref="Certificate"/> to backup</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The certificate backup</returns>
public virtual async Task<Response<byte[]>> BackupCertificateAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.BackupCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
Response<CertificateBackup> backup = await _pipeline.SendRequestAsync(RequestMethod.Post, () => new CertificateBackup(), cancellationToken, CertificatesPath, name, "/backup").ConfigureAwait(false);
return Response.FromValue(backup.Value.Value, backup.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Restores a <see cref="Certificate"/>, including all versions, from a backup created from the <see cref="BackupCertificate"/> or <see cref="BackupCertificateAsync"/>. The backup must be restored
/// to a vault in the same region as its original vault. This operation requires the certificate/restore permission.
/// </summary>
/// <param name="backup">The backup of the <see cref="Certificate"/> to restore</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The restored certificate and policy</returns>
public virtual Response<CertificateWithPolicy> RestoreCertificate(byte[] backup, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(backup, nameof(backup));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.RestoreCertificate");
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Post, new CertificateBackup { Value = backup }, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, "/restore");
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Restores a <see cref="Certificate"/>, including all versions, from a backup created from the <see cref="BackupCertificate"/> or <see cref="BackupCertificateAsync"/>. The backup must be restored
/// to a vault in the same region as its original vault. This operation requires the certificate/restore permission.
/// </summary>
/// <param name="backup">The backup of the <see cref="Certificate"/> to restore</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The restored certificate and policy</returns>
public virtual async Task<Response<CertificateWithPolicy>> RestoreCertificateAsync(byte[] backup, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(backup, nameof(backup));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.RestoreCertificate");
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Post, new CertificateBackup { Value = backup }, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, "/restore").ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Imports a pre-existing certificate to the key vault. The specified certificate must be in PFX or PEM format, and must contain the private key as well as the x509 certificates. This operation requires the
/// certifcates/import permission
/// </summary>
/// <param name="certificateImportOptions">The details of the certificate to import to the key vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The imported certificate and policy</returns>
public virtual Response<CertificateWithPolicy> ImportCertificate(CertificateImportOptions certificateImportOptions, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(certificateImportOptions, nameof(certificateImportOptions));
Argument.AssertNotNullOrEmpty(certificateImportOptions.Name, nameof(certificateImportOptions.Name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.ImportCertificate");
scope.AddAttribute("certificate", certificateImportOptions.Name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Post, certificateImportOptions, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, "/", certificateImportOptions.Name, "/import");
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Imports a pre-existing certificate to the key vault. The specified certificate must be in PFX or PEM format, and must contain the private key as well as the x509 certificates. This operation requires the
/// certifcates/import permission
/// </summary>
/// <param name="certificateImportOptions">The details of the certificate to import to the key vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The imported certificate and policy</returns>
public virtual async Task<Response<CertificateWithPolicy>> ImportCertificateAsync(CertificateImportOptions certificateImportOptions, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(certificateImportOptions, nameof(certificateImportOptions));
Argument.AssertNotNullOrEmpty(certificateImportOptions.Name, nameof(certificateImportOptions.Name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.ImportCertificate");
scope.AddAttribute("certificate", certificateImportOptions.Name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Post, certificateImportOptions, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, "/", certificateImportOptions.Name, "/import").ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Enumerates the certificates in the vault, returning select properties of the certificate, sensative feilds of the certificate will not be returned. This operation requires the certificates/list permission.
/// </summary>
/// <param name="includePending">Specifies whether to include certificates in a pending state as well</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of certificate metadata</returns>
public virtual Pageable<CertificateProperties> GetCertificates(bool? includePending = default, CancellationToken cancellationToken = default)
{
Uri firstPageUri = includePending.HasValue ? _pipeline.CreateFirstPageUri(CertificatesPath, new ValueTuple<string, string>("includePending", includePending.Value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())) : _pipeline.CreateFirstPageUri(CertificatesPath);
return PageResponseEnumerator.CreateEnumerable(nextLink => _pipeline.GetPage(firstPageUri, nextLink, () => new CertificateProperties(), "Azure.Security.KeyVault.Keys.KeyClient.GetCertificates", cancellationToken));
}
/// <summary>
/// Enumerates the certificates in the vault, returning select properties of the certificate, sensative feilds of the certificate will not be returned. This operation requires the certificates/list permission.
/// </summary>
/// <param name="includePending">Specifies whether to include certificates in a pending state as well</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of certificate metadata</returns>
public virtual AsyncPageable<CertificateProperties> GetCertificatesAsync(bool? includePending = default, CancellationToken cancellationToken = default)
{
Uri firstPageUri = includePending.HasValue ? _pipeline.CreateFirstPageUri(CertificatesPath, new ValueTuple<string, string>("includePending", includePending.Value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())) : _pipeline.CreateFirstPageUri(CertificatesPath);
return PageResponseEnumerator.CreateAsyncEnumerable(nextLink => _pipeline.GetPageAsync(firstPageUri, nextLink, () => new CertificateProperties(), "Azure.Security.KeyVaultCertificates.CertificateClient.GetCertificates", cancellationToken));
}
/// <summary>
/// Enumerates the versions of a specific certificate in the vault, returning select properties of the certificate versions, sensative feilds of the certificate will not be returned. This operation requires
/// the certificates/list permission.
/// </summary>
/// <param name="name">The name of the certificate to retrieve the versions of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of the certificate's versions</returns>
public virtual IEnumerable<CertificateProperties> GetCertificateVersions(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
Uri firstPageUri = _pipeline.CreateFirstPageUri($"{CertificatesPath}{name}/versions");
return PageResponseEnumerator.CreateEnumerable(nextLink => _pipeline.GetPage(firstPageUri, nextLink, () => new CertificateProperties(), "Azure.Security.KeyVaultCertificates.CertificateClient.GetCertificateVersions", cancellationToken));
}
/// <summary>
/// Enumerates the versions of a specific certificate in the vault, returning select properties of the certificate versions, sensative feilds of the certificate will not be returned. This operation requires
/// the certificates/list permission.
/// </summary>
/// <param name="name">The name of the certificate to retrieve the versions of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of the certificate's versions</returns>
public virtual AsyncPageable<CertificateProperties> GetCertificateVersionsAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
Uri firstPageUri = _pipeline.CreateFirstPageUri($"{CertificatesPath}{name}/versions");
return PageResponseEnumerator.CreateAsyncEnumerable(nextLink => _pipeline.GetPageAsync(firstPageUri, nextLink, () => new CertificateProperties(), "Azure.Security.KeyVaultCertificates.CertificateClient.GetCertificateVersions", cancellationToken));
}
/// <summary>
/// Enumerates the deleted certificates in the vault. This operation is only available on soft-delete enabled vaults, and requires the certificates/list/get permissions.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of deleted certificates</returns>
public virtual Pageable<DeletedCertificate> GetDeletedCertificates(CancellationToken cancellationToken = default)
{
Uri firstPageUri = _pipeline.CreateFirstPageUri(DeletedCertificatesPath);
return PageResponseEnumerator.CreateEnumerable(nextLink => _pipeline.GetPage(firstPageUri, nextLink, () => new DeletedCertificate(), "Azure.Security.KeyVaultCertificates.CertificateClient.GetDeletedCertificates", cancellationToken));
}
/// <summary>
/// Enumerates the deleted certificates in the vault. This operation is only available on soft-delete enabled vaults, and requires the certificates/list/get permissions.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of deleted certificates</returns>
public virtual AsyncPageable<DeletedCertificate> GetDeletedCertificatesAsync(CancellationToken cancellationToken = default)
{
Uri firstPageUri = _pipeline.CreateFirstPageUri(DeletedCertificatesPath);
return PageResponseEnumerator.CreateAsyncEnumerable(nextLink => _pipeline.GetPageAsync(firstPageUri, nextLink, () => new DeletedCertificate(), "Azure.Security.KeyVaultCertificates.CertificateClient.GetDeletedCertificates", cancellationToken));
}
//
// Policy
//
/// <summary>
/// Retrieves the <see cref="CertificatePolicy"/> of the specified certificate. This operation requires the certificate/get permission.
/// </summary>
/// <param name="certificateName">The name of the certificate to retrieve the policy of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="CertificatePolicy"/> of the specified certificate</returns>
public virtual Response<CertificatePolicy> GetCertificatePolicy(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificatePolicy");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Get, () => new CertificatePolicy(), cancellationToken, CertificatesPath, certificateName, "/policy");
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Retrieves the <see cref="CertificatePolicy"/> of the specified certificate. This operation requires the certificate/get permission.
/// </summary>
/// <param name="certificateName">The name of the certificate to retrieve the policy of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="CertificatePolicy"/> of the specified certificate</returns>
public virtual async Task<Response<CertificatePolicy>> GetCertificatePolicyAsync(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificatePolicy");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new CertificatePolicy(), cancellationToken, CertificatesPath, certificateName, "/policy").ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates the <see cref="CertificatePolicy"/> of the specified certificate. This operation requires the certificate/update permission.
/// </summary>
/// <param name="certificateName">The name of the certificate to update the policy of</param>
/// <param name="policy">The updated policy for the specified certificate</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated certificate policy</returns>
public virtual Response<CertificatePolicy> UpdateCertificatePolicy(string certificateName, CertificatePolicy policy, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.UpdateCertificatePolicy");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Patch, policy, () => new CertificatePolicy(), cancellationToken, CertificatesPath, certificateName, "/policy");
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates the <see cref="CertificatePolicy"/> of the specified certificate. This operation requires the certificate/update permission.
/// </summary>
/// <param name="certificateName">The name of the certificate to update the policy of</param>
/// <param name="policy">The updated policy for the specified certificate</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated certificate policy</returns>
public virtual async Task<Response<CertificatePolicy>> UpdateCertificatePolicyAsync(string certificateName, CertificatePolicy policy, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.UpdateCertificatePolicy");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Patch, policy, () => new CertificatePolicy(), cancellationToken, CertificatesPath, certificateName, "/policy").ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
//
// Issuer
//
/// <summary>
/// Creates or replaces a certificate <see cref="Issuer"/> in the key vault. This operation requires the certificates/setissuers permission.
/// </summary>
/// <param name="issuer">The <see cref="Issuer"/> to add or replace in the vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The created certificate issuer</returns>
public virtual Response<Issuer> CreateIssuer(Issuer issuer, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(issuer, nameof(issuer));
Argument.AssertNotNullOrEmpty(issuer.Name, nameof(issuer.Name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.CreateIssuer");
scope.AddAttribute("issuer", issuer.Name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Put, issuer, () => new Issuer(), cancellationToken, IssuersPath, issuer.Name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Creates or replaces a certificate <see cref="Issuer"/> in the key vault. This operation requires the certificates/setissuers permission.
/// </summary>
/// <param name="issuer">The <see cref="Issuer"/> to add or replace in the vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The created certificate issuer</returns>
public virtual async Task<Response<Issuer>> CreateIssuerAsync(Issuer issuer, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(issuer, nameof(issuer));
Argument.AssertNotNullOrEmpty(issuer.Name, nameof(issuer.Name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.CreateIssuer");
scope.AddAttribute("issuer", issuer.Name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Put, issuer, () => new Issuer(), cancellationToken, IssuersPath, issuer.Name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Retrieves the specified certificate <see cref="Issuer"/> from the vault. This operation requires the certificates/getissuers permission.
/// </summary>
/// <param name="name">The name of the <see cref="Issuer"/> to retreive</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The retrieved certificate issuer</returns>
public virtual Response<Issuer> GetIssuer(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetIssuer");
scope.AddAttribute("issuer", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Get, () => new Issuer(), cancellationToken, IssuersPath, name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Retrieves the specified certificate <see cref="Issuer"/> from the vault. This operation requires the certificates/getissuers permission.
/// </summary>
/// <param name="name">The name of the <see cref="Issuer"/> to retreive</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The retrieved certificate issuer</returns>
public virtual async Task<Response<Issuer>> GetIssuerAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetIssuer");
scope.AddAttribute("issuer", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new Issuer(), cancellationToken, IssuersPath, name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates the specified certificate <see cref="Issuer"/> in the vault, only updating the specified fields, others will remain unchanged. This operation requires the certificates/setissuers permission.
/// </summary>
/// <param name="issuer">The <see cref="Issuer"/> to update in the vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated certificate issuer</returns>
public virtual Response<Issuer> UpdateIssuer(Issuer issuer, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(issuer, nameof(issuer));
Argument.AssertNotNullOrEmpty(issuer.Name, nameof(issuer.Name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.UpdateIssuer");
scope.AddAttribute("issuer", issuer.Name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Patch, issuer, () => new Issuer(), cancellationToken, IssuersPath, issuer.Name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates the specified certificate <see cref="Issuer"/> in the vault, only updating the specified fields, others will remain unchanged. This operation requires the certificates/setissuers permission.
/// </summary>
/// <param name="issuer">The <see cref="Issuer"/> to update in the vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated certificate issuer</returns>
public virtual async Task<Response<Issuer>> UpdateIssuerAsync(Issuer issuer, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(issuer, nameof(issuer));
Argument.AssertNotNullOrEmpty(issuer.Name, nameof(issuer.Name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.UpdateIssuer");
scope.AddAttribute("issuer", issuer.Name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Patch, issuer, () => new Issuer(), cancellationToken, IssuersPath, issuer.Name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes the specified certificate <see cref="Issuer"/> from the vault. This operation requires the certificates/deleteissuers permission.
/// </summary>
/// <param name="name">The name of the <see cref="Issuer"/> to delete</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The deleted certificate issuer</returns>
public virtual Response<Issuer> DeleteIssuer(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteIssuer");
scope.AddAttribute("issuer", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Delete, () => new Issuer(), cancellationToken, IssuersPath, name);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes the specified certificate <see cref="Issuer"/> from the vault. This operation requires the certificates/deleteissuers permission.
/// </summary>
/// <param name="name">The name of the <see cref="Issuer"/> to delete</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The deleted certificate issuer</returns>
public virtual async Task<Response<Issuer>> DeleteIssuerAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteIssuer");
scope.AddAttribute("issuer", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Delete, () => new Issuer(), cancellationToken, IssuersPath, name).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Enumerates the certificate issuers in the vault, returning select properties of the <see cref="Issuer"/>, sensative feilds of the <see cref="Issuer"/> will not be returned. This operation requires the certificates/getissuers permission.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of certificate issuers metadata</returns>
public virtual Pageable<IssuerProperties> GetIssuers(CancellationToken cancellationToken = default)
{
Uri firstPageUri = _pipeline.CreateFirstPageUri(IssuersPath);
return PageResponseEnumerator.CreateEnumerable(nextLink => _pipeline.GetPage(firstPageUri, nextLink, () => new IssuerProperties(), "Azure.Security.KeyVaultCertificates.CertificateClient.GetIssuers", cancellationToken));
}
/// <summary>
/// Enumerates the certificate issuers in the vault, returning select properties of the <see cref="Issuer"/>, sensative feilds of the <see cref="Issuer"/> will not be returned. This operation requires the certificates/getissuers permission.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An enumerable collection of certificate issuers metadata</returns>
public virtual AsyncPageable<IssuerProperties> GetIssuersAsync(CancellationToken cancellationToken = default)
{
Uri firstPageUri = _pipeline.CreateFirstPageUri(IssuersPath);
return PageResponseEnumerator.CreateAsyncEnumerable(nextLink => _pipeline.GetPageAsync(firstPageUri, nextLink, () => new IssuerProperties(), "Azure.Security.KeyVaultCertificates.CertificateClient.GetIssuers", cancellationToken));
}
//
// Operations
//
/// <summary>
/// Gets a pending <see cref="CertificateOperation"/> from the key vault. This operation requires the certificates/get permission.
/// </summary>
/// <param name="certificateName">The name of the <see cref="Certificate"/> to retrieve the current pending operation of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The given certificates current pending operation</returns>
public virtual CertificateOperation GetCertificateOperation(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificateOperation");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
Response<CertificateOperationProperties> response = _pipeline.SendRequest(RequestMethod.Get, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, certificateName, "/pending");
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets a pending <see cref="CertificateOperation"/> from the key vault. This operation requires the certificates/get permission.
/// </summary>
/// <param name="certificateName">The name of the <see cref="Certificate"/> to retrieve the current pending operation of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The given certificates current pending operation</returns>
public virtual async Task<CertificateOperation> GetCertificateOperationAsync(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificateOperation");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
Response<CertificateOperationProperties> response = await _pipeline.SendRequestAsync(RequestMethod.Get, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, certificateName, "/pending").ConfigureAwait(false);
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Cancels a pending <see cref="CertificateOperation"/> in the key vault. This operation requires the certificates/update permission.
/// </summary>
/// <param name="certificateName">The name of the <see cref="Certificate"/> to cancel the current pending operation of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The canceled certificate operation</returns>
public virtual CertificateOperation CancelCertificateOperation(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
var parameters = new CertificateOperationUpdateParameters(true);
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.CancelCertificateOperation");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
Response<CertificateOperationProperties> response = _pipeline.SendRequest(RequestMethod.Patch, parameters, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, certificateName, "/pending");
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Cancels a pending <see cref="CertificateOperation"/> in the key vault. This operation requires the certificates/update permission.
/// </summary>
/// <param name="certificateName">The name of the <see cref="Certificate"/> to cancel the current pending operation of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The canceled certificate operation</returns>
public virtual async Task<CertificateOperation> CancelCertificateOperationAsync(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
var parameters = new CertificateOperationUpdateParameters(true);
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.CancelCertificateOperation");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
Response<CertificateOperationProperties> response = await _pipeline.SendRequestAsync(RequestMethod.Patch, parameters, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, certificateName, "/pending").ConfigureAwait(false);
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a pending <see cref="CertificateOperation"/> in the key vault. This operation requires the certificates/delete permission.
/// </summary>
/// <param name="certificateName">The name of the <see cref="Certificate"/> to delete the current pending operation of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The deleted certificate operation</returns>
public virtual CertificateOperation DeleteCertificateOperation(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteCertificateOperation");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
Response<CertificateOperationProperties> response = _pipeline.SendRequest(RequestMethod.Delete, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, certificateName, "/pending");
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a pending <see cref="CertificateOperation"/> in the key vault. This operation requires the certificates/delete permission.
/// </summary>
/// <param name="certificateName">The name of the <see cref="Certificate"/> to delete the current pending operation of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The deleted certificate operation</returns>
public virtual async Task<CertificateOperation> DeleteCertificateOperationAsync(string certificateName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(certificateName, nameof(certificateName));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteCertificateOperation");
scope.AddAttribute("certificate", certificateName);
scope.Start();
try
{
Response<CertificateOperationProperties> response = await _pipeline.SendRequestAsync(RequestMethod.Delete, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, certificateName, "/pending").ConfigureAwait(false);
return new CertificateOperation(response, this);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
//
// Contacts
//
/// <summary>
/// Sets the certificate <see cref="Contact"/>s for the key vault, replacing any existing contacts. This operation requires the certificates/managecontacts permission.
/// </summary>
/// <param name="contacts">The certificate contacts for the vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated certificate contacts of the vault</returns>
public virtual Response<IList<Contact>> SetContacts(IEnumerable<Contact> contacts, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(contacts, nameof(contacts));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.SetContacts");
scope.Start();
try
{
Response<ContactList> contactList = _pipeline.SendRequest(RequestMethod.Put, new ContactList(contacts), () => new ContactList(), cancellationToken, ContactsPath);
return Response.FromValue(contactList.Value.ToList(), contactList.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Sets the certificate <see cref="Contact"/>s for the key vault, replacing any existing contacts. This operation requires the certificates/managecontacts permission.
/// </summary>
/// <param name="contacts">The certificate contacts for the vault</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The updated certificate contacts of the vault</returns>
public virtual async Task<Response<IList<Contact>>> SetContactsAsync(IEnumerable<Contact> contacts, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(contacts, nameof(contacts));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.SetContacts");
scope.Start();
try
{
Response<ContactList> contactList = await _pipeline.SendRequestAsync(RequestMethod.Put, new ContactList(contacts), () => new ContactList(), cancellationToken, ContactsPath).ConfigureAwait(false);
return Response.FromValue(contactList.Value.ToList(), contactList.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the certificate <see cref="Contact"/>s for the key vaults. This operation requires the certificates/managecontacts permission.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The certificate contacts of the vault</returns>
public virtual Response<IList<Contact>> GetContacts(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetContacts");
scope.Start();
try
{
Response<ContactList> contactList = _pipeline.SendRequest(RequestMethod.Get, () => new ContactList(), cancellationToken, ContactsPath);
return Response.FromValue(contactList.Value.ToList(), contactList.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the certificate <see cref="Contact"/>s for the key vaults. This operation requires the certificates/managecontacts permission.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The certificate contacts of the vault</returns>
public virtual async Task<Response<IList<Contact>>> GetContactsAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetContacts");
scope.Start();
try
{
Response<ContactList> contactList = await _pipeline.SendRequestAsync(RequestMethod.Get, () => new ContactList(), cancellationToken, ContactsPath).ConfigureAwait(false);
return Response.FromValue(contactList.Value.ToList(), contactList.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Delets all certificate <see cref="Contact"/>s from the key vault, replacing any existing contacts. This operation requires the certificates/managecontacts permission.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The certificate contacts deleted from the vault</returns>
public virtual Response<IList<Contact>> DeleteContacts(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteContacts");
scope.Start();
try
{
Response<ContactList> contactList = _pipeline.SendRequest(RequestMethod.Delete, () => new ContactList(), cancellationToken, ContactsPath);
return Response.FromValue(contactList.Value.ToList(), contactList.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Delets all certificate <see cref="Contact"/>s from the key vault, replacing any existing contacts. This operation requires the certificates/managecontacts permission.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The certificate contacts deleted from the vault</returns>
public virtual async Task<Response<IList<Contact>>> DeleteContactsAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.DeleteContacts");
scope.Start();
try
{
Response<ContactList> contactList = await _pipeline.SendRequestAsync(RequestMethod.Delete, () => new ContactList(), cancellationToken, ContactsPath).ConfigureAwait(false);
return Response.FromValue(contactList.Value.ToList(), contactList.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Merges a certificate or a certificate chain with a key pair currently available in the service. This operation requires the certificate/create permission.
/// </summary>
/// <param name="certificateMergeOptions">The details of the certificate or certificate chain to merge into the key vault.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The merged certificate.</returns>
public virtual Response<CertificateWithPolicy> MergeCertificate(CertificateMergeOptions certificateMergeOptions, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(certificateMergeOptions, nameof(certificateMergeOptions));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.MergeCertificate");
scope.AddAttribute("certificate", certificateMergeOptions.Name);
scope.Start();
try
{
Response<CertificateWithPolicy> certificate = _pipeline.SendRequest(RequestMethod.Post, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, certificateMergeOptions.Name, "/pending/merge");
return Response.FromValue(certificate.Value, certificate.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Merges a certificate or a certificate chain with a key pair currently available in the service. This operation requires the certificate/create permission.
/// </summary>
/// <param name="certificateMergeOptions">The details of the certificate or certificate chain to merge into the key vault.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The merged certificate.</returns>
public virtual async Task<Response<CertificateWithPolicy>> MergeCertificateAsync(CertificateMergeOptions certificateMergeOptions, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(certificateMergeOptions, nameof(certificateMergeOptions));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.MergeCertificate");
scope.AddAttribute("certificate", certificateMergeOptions.Name);
scope.Start();
try
{
Response<CertificateWithPolicy> certificate = await _pipeline.SendRequestAsync(RequestMethod.Post, () => new CertificateWithPolicy(), cancellationToken, CertificatesPath, certificateMergeOptions.Name, "/pending/merge").ConfigureAwait(false);
return Response.FromValue(certificate.Value, certificate.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
internal virtual Response<CertificateOperationProperties> GetPendingCertificate(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetPendingCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return _pipeline.SendRequest(RequestMethod.Get, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, name, "/pending");
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
internal virtual async Task<Response<CertificateOperationProperties>> GetPendingCertificateAsync(string name, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(name, nameof(name));
using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Certificates.CertificateClient.GetPendingCertificate");
scope.AddAttribute("certificate", name);
scope.Start();
try
{
return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new CertificateOperationProperties(), cancellationToken, CertificatesPath, name, "/pending").ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
internal CertificatePolicy CreateDefaultPolicy()
{
var policy = new CertificatePolicy
{
IssuerName = "Self",
Subject = "CN=default",
KeyType = CertificateKeyType.Rsa,
Exportable = true,
ReuseKey = false,
KeyUsage = new[]
{
CertificateKeyUsage.CrlSign,
CertificateKeyUsage.DataEncipherment,
CertificateKeyUsage.DigitalSignature,
CertificateKeyUsage.KeyEncipherment,
CertificateKeyUsage.KeyAgreement,
CertificateKeyUsage.KeyCertSign,
},
CertificateTransparency = false,
ContentType = CertificateContentType.Pkcs12
};
return policy;
}
}
}
| 54.827742 | 283 | 0.655402 | [
"MIT"
] | MAtifSaeed/azure-sdk-for-net | sdk/keyvault/Azure.Security.KeyVault.Certificates/src/CertificateClient.cs | 84,985 | 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.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchMethod
{
[OutputConstructor]
private WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchMethod()
{
}
}
}
| 34.909091 | 170 | 0.794271 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchMethod.cs | 768 | 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 Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
public sealed class RyuJitNodeFactory : NodeFactory
{
public RyuJitNodeFactory(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup, MetadataManager metadataManager,
InteropStubManager interopStubManager, NameMangler nameMangler, VTableSliceProvider vtableSliceProvider, DictionaryLayoutProvider dictionaryLayoutProvider)
: base(context, compilationModuleGroup, metadataManager, interopStubManager, nameMangler, new LazyGenericsDisabledPolicy(), vtableSliceProvider, dictionaryLayoutProvider, new ExternSymbolsImportedNodeProvider())
{
}
protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method)
{
if (method.IsInternalCall)
{
if (TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(method))
{
return MethodEntrypoint(TypeSystemContext.GetRealSpecialUnboxingThunkTargetMethod(method));
}
else if (method.IsArrayAddressMethod())
{
return MethodEntrypoint(((ArrayType)method.OwningType).GetArrayMethod(ArrayMethodKind.AddressWithHiddenArg));
}
else if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute"))
{
return new RuntimeImportMethodNode(method);
}
}
// MethodDesc that represents an unboxing thunk is a thing that is internal to the JitInterface.
// It should not leak out of JitInterface.
Debug.Assert(!Internal.JitInterface.UnboxingMethodDescExtensions.IsUnboxingThunk(method));
if (CompilationModuleGroup.ContainsMethodBody(method, false))
{
return new MethodCodeNode(method);
}
else
{
return _importedNodeProvider.ImportedMethodCodeNode(this, method, false);
}
}
protected override IMethodNode CreateUnboxingStubNode(MethodDesc method)
{
Debug.Assert(!method.Signature.IsStatic);
if (method.IsCanonicalMethod(CanonicalFormKind.Specific) && !method.HasInstantiation)
{
// Unboxing stubs to canonical instance methods need a special unboxing stub that unboxes
// 'this' and also provides an instantiation argument (we do a calling convention conversion).
// We don't do this for generic instance methods though because they don't use the EEType
// for the generic context anyway.
return new MethodCodeNode(TypeSystemContext.GetSpecialUnboxingThunk(method, TypeSystemContext.GeneratedAssembly));
}
else
{
// Otherwise we just unbox 'this' and don't touch anything else.
return new UnboxingStubNode(method, Target);
}
}
protected override ISymbolNode CreateReadyToRunHelperNode(ReadyToRunHelperKey helperCall)
{
return new ReadyToRunHelperNode(helperCall.HelperId, helperCall.Target);
}
}
}
| 45.102564 | 223 | 0.660034 | [
"MIT"
] | DjArt/corert | src/ILCompiler.RyuJit/src/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs | 3,520 | 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 medialive-2017-10-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.MediaLive.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaLive.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for HlsOutputSettings Object
/// </summary>
public class HlsOutputSettingsUnmarshaller : IUnmarshaller<HlsOutputSettings, XmlUnmarshallerContext>, IUnmarshaller<HlsOutputSettings, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
HlsOutputSettings IUnmarshaller<HlsOutputSettings, 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 HlsOutputSettings Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
HlsOutputSettings unmarshalledObject = new HlsOutputSettings();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("h265PackagingType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.H265PackagingType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("hlsSettings", targetDepth))
{
var unmarshaller = HlsSettingsUnmarshaller.Instance;
unmarshalledObject.HlsSettings = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("nameModifier", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.NameModifier = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("segmentModifier", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SegmentModifier = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static HlsOutputSettingsUnmarshaller _instance = new HlsOutputSettingsUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static HlsOutputSettingsUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.572727 | 164 | 0.619687 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/HlsOutputSettingsUnmarshaller.cs | 4,023 | C# |
//
// CAEnums.cs: definitions used for CoreAnimation
//
// Authors:
// Geoff Norton
// Miguel de Icaza
//
// Copyright 2009-2010, Novell, Inc.
// Copyright 2014 Xamarin Inc.
//
// 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 Foundation;
using System.Runtime.InteropServices;
using CoreGraphics;
using ObjCRuntime;
#nullable enable
namespace CoreAnimation {
// untyped enum -> CALayer.h
// note: edgeAntialiasingMask is an `unsigned int` @property
[Flags]
public enum CAEdgeAntialiasingMask : uint {
LeftEdge = 1 << 0,
RightEdge = 1 << 1,
BottomEdge = 1 << 2,
TopEdge = 1 << 3,
All = LeftEdge | RightEdge | BottomEdge | TopEdge,
LeftRightEdges = LeftEdge | RightEdge,
TopBottomEdges = TopEdge | BottomEdge
}
[NoWatch] // headers not updated
[iOS (11,0)][TV (11,0)][Mac (10,13)]
[Native][Flags]
public enum CACornerMask : ulong {
MinXMinYCorner = 1 << 0,
MaxXMinYCorner = 1 << 1,
MinXMaxYCorner = 1 << 2,
MaxXMaxYCorner = 1 << 3,
}
#if MONOMAC || __MACCATALYST__
// untyped enum -> CALayer.h (only on OSX headers)
// note: autoresizingMask is an `unsigned int` @property
[Flags]
public enum CAAutoresizingMask : uint {
NotSizable = 0,
MinXMargin = 1 << 0,
WidthSizable = 1 << 1,
MaxXMargin = 1 << 2,
MinYMargin = 1 << 3,
HeightSizable = 1 << 4,
MaxYMargin = 1 << 5
}
// typedef int -> CAConstraintLayoutManager.h
public enum CAConstraintAttribute {
MinX,
MidX,
MaxX,
Width,
MinY,
MidY,
MaxY,
Height,
};
#endif
}
| 28.566667 | 73 | 0.700117 | [
"BSD-3-Clause"
] | NormanChiflen/xamarin-all-IOS | src/CoreAnimation/CAEnums.cs | 2,571 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace laboratorioETEC.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("laboratorioETEC.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.708333 | 181 | 0.604234 | [
"MIT"
] | Danieljrsilva/exerc_csharp | down_c#/DS/laboratorioETEC/Properties/Resources.Designer.cs | 2,789 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Web.V20180201
{
/// <summary>
/// String dictionary resource.
/// </summary>
[AzureNativeResourceType("azure-native:web/v20180201:WebAppMetadata")]
public partial class WebAppMetadata : Pulumi.CustomResource
{
/// <summary>
/// Kind of resource.
/// </summary>
[Output("kind")]
public Output<string?> Kind { get; private set; } = null!;
/// <summary>
/// Resource Name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Settings.
/// </summary>
[Output("properties")]
public Output<ImmutableDictionary<string, string>> Properties { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a WebAppMetadata resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public WebAppMetadata(string name, WebAppMetadataArgs args, CustomResourceOptions? options = null)
: base("azure-native:web/v20180201:WebAppMetadata", name, args ?? new WebAppMetadataArgs(), MakeResourceOptions(options, ""))
{
}
private WebAppMetadata(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:web/v20180201:WebAppMetadata", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:web/v20180201:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20150801:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20150801:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20160801:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20160801:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20181101:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20181101:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20190801:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20190801:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20200601:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20200601:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20200901:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20200901:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20201001:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20201001:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-native:web/v20201201:WebAppMetadata"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20201201:WebAppMetadata"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing WebAppMetadata resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static WebAppMetadata Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new WebAppMetadata(name, id, options);
}
}
public sealed class WebAppMetadataArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Kind of resource.
/// </summary>
[Input("kind")]
public Input<string>? Kind { get; set; }
/// <summary>
/// Name of the app.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
[Input("properties")]
private InputMap<string>? _properties;
/// <summary>
/// Settings.
/// </summary>
public InputMap<string> Properties
{
get => _properties ?? (_properties = new InputMap<string>());
set => _properties = value;
}
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public WebAppMetadataArgs()
{
}
}
}
| 42.909722 | 137 | 0.587312 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/Web/V20180201/WebAppMetadata.cs | 6,179 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace ToDoList.Web
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| 22.730769 | 64 | 0.568528 | [
"MIT"
] | FlyLive/-Sclub2016Homework | Sclub2016Homework/ToDoList.Web/Program.cs | 593 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Network
{
/// <summary> A Class representing a VirtualNetworkGatewayNatRule along with the instance operations that can be performed on it. </summary>
public partial class VirtualNetworkGatewayNatRule : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="VirtualNetworkGatewayNatRule"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string virtualNetworkGatewayName, string natRuleName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules/{natRuleName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _virtualNetworkGatewayNatRuleClientDiagnostics;
private readonly VirtualNetworkGatewayNatRulesRestOperations _virtualNetworkGatewayNatRuleRestClient;
private readonly VirtualNetworkGatewayNatRuleData _data;
/// <summary> Initializes a new instance of the <see cref="VirtualNetworkGatewayNatRule"/> class for mocking. </summary>
protected VirtualNetworkGatewayNatRule()
{
}
/// <summary> Initializes a new instance of the <see cref = "VirtualNetworkGatewayNatRule"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal VirtualNetworkGatewayNatRule(ArmClient client, VirtualNetworkGatewayNatRuleData data) : this(client, new ResourceIdentifier(data.Id))
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="VirtualNetworkGatewayNatRule"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal VirtualNetworkGatewayNatRule(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_virtualNetworkGatewayNatRuleClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(ResourceType, out string virtualNetworkGatewayNatRuleApiVersion);
_virtualNetworkGatewayNatRuleRestClient = new VirtualNetworkGatewayNatRulesRestOperations(_virtualNetworkGatewayNatRuleClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, virtualNetworkGatewayNatRuleApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Network/virtualNetworkGateways/natRules";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual VirtualNetworkGatewayNatRuleData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Retrieves the details of a nat rule. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<VirtualNetworkGatewayNatRule>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _virtualNetworkGatewayNatRuleClientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Get");
scope.Start();
try
{
var response = await _virtualNetworkGatewayNatRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _virtualNetworkGatewayNatRuleClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new VirtualNetworkGatewayNatRule(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Retrieves the details of a nat rule. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<VirtualNetworkGatewayNatRule> Get(CancellationToken cancellationToken = default)
{
using var scope = _virtualNetworkGatewayNatRuleClientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Get");
scope.Start();
try
{
var response = _virtualNetworkGatewayNatRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _virtualNetworkGatewayNatRuleClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new VirtualNetworkGatewayNatRule(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a nat rule. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<ArmOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _virtualNetworkGatewayNatRuleClientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Delete");
scope.Start();
try
{
var response = await _virtualNetworkGatewayNatRuleRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new NetworkArmOperation(_virtualNetworkGatewayNatRuleClientDiagnostics, Pipeline, _virtualNetworkGatewayNatRuleRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a nat rule. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _virtualNetworkGatewayNatRuleClientDiagnostics.CreateScope("VirtualNetworkGatewayNatRule.Delete");
scope.Start();
try
{
var response = _virtualNetworkGatewayNatRuleRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new NetworkArmOperation(_virtualNetworkGatewayNatRuleClientDiagnostics, Pipeline, _virtualNetworkGatewayNatRuleRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 54.311765 | 292 | 0.684176 | [
"MIT"
] | vidai-msft/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/VirtualNetworkGatewayNatRule.cs | 9,233 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Routing.Constraints
{
/// <summary>
/// Constrains a route parameter to represent only 64-bit integer values.
/// </summary>
public class LongRouteConstraint : IRouteConstraint
{
/// <inheritdoc />
public bool Match(
HttpContext? httpContext,
IRouter? route,
string routeKey,
RouteValueDictionary values,
RouteDirection routeDirection)
{
if (routeKey == null)
{
throw new ArgumentNullException(nameof(routeKey));
}
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
if (values.TryGetValue(routeKey, out var value) && value != null)
{
if (value is long)
{
return true;
}
var valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
return long.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out _);
}
return false;
}
}
}
| 29.75 | 111 | 0.569328 | [
"Apache-2.0"
] | 1175169074/aspnetcore | src/Http/Routing/src/Constraints/LongRouteConstraint.cs | 1,428 | C# |
namespace LoggingKata
{
/// <summary>
/// Parses a POI file to locate all the Taco Bells
/// </summary>
public class TacoParser
{
readonly ILog logger = new TacoLogger();
public ITrackable Parse(string line)
{
logger.LogInfo("Begin parsing");
// Take your line and use line.Split(',') to split it up into an array of strings, separated by the char ','
var cells = line.Split(',');
// If your array.Length is less than 3, something went wrong
if (cells.Length < 3)
{
// Log that and return null
// Do not fail if one record parsing fails, return null
return null; // TODO Implement
}
// grab the latitude from your array at index 0
double lati = double.Parse(cells[0]);
// grab the longitude from your array at index 1
double longi = double.Parse(cells[1]);
// grab the name from your array at index 2
string name = cells[2];
// You're going to need to parse your string as a `double`
// which is similar to parsing a string as an `int`
// You'll need to create a TacoBell class
// that conforms to ITrackable
// Then, you'll need an instance of the TacoBell class
// With the name and point set correctly
// Then, return the instance of your TacoBell class
// Since it conforms to ITrackable
var TB = new TacoBell();
var point = new Point();
TB.Name = name;
point.Latitude = lati;
point.Longitude = longi;
TB.Location = point;
return TB;
}
}
} | 32.5 | 120 | 0.531319 | [
"MIT"
] | megamagicmonkey/TacoParser | LoggingKata/TacoParser.cs | 1,822 | C# |
using Improbable.Gdk.Subscriptions;
using MDG.Common.Interfaces;
using MDG.Common.MonoBehaviours;
using MDG.Common.MonoBehaviours.Synchronizers;
using MdgSchema.Common;
using System.Collections;
using UnityEngine;
using SpawnSchema = MdgSchema.Common.Spawn;
using StatSchema = MdgSchema.Common.Stats;
namespace MDG.Defender.Monobehaviours
{
// Finish synchronization of defender.
// Change this to PlayerSynchronizer as common end game behaviour
public class DefenderSynchronizer : MonoBehaviour, IPlayerSynchronizer
{
#pragma warning disable 649
[Require] SpawnSchema.PendingRespawnReader pendingRespawnReader;
[Require] StatSchema.StatsReader statsReader;
[Require] StatSchema.StatsMetadataReader statsMetadataReader;
#pragma warning restore 649
public DefenderHUD DefenderHUD { private set; get; }
TeamStatusUpdater teamStatusUpdater;
public UnityClientConnector ClientWorker { private set; get; }
private void Start()
{
pendingRespawnReader.OnRespawnActiveUpdate += OnRespawnActiveChange;
pendingRespawnReader.OnTimeTillRespawnUpdate += OnPendingRespawnTimerUpdate;
StartCoroutine(InitUIRefs());
statsReader.OnHealthUpdate += OnHealthUpdate;
}
private void OnPendingRespawnTimerUpdate(float time)
{
DefenderHUD.OnUpdateRespawn(time);
}
private IEnumerator InitUIRefs()
{
yield return new WaitUntil(() => ClientWorker != null && ClientWorker.LoadedUI != null);
// This method won't scale well.
ClientWorker.LoadedUI.TryGetValue("DefenderHud", out GameObject hudObject);
DefenderHUD = hudObject.GetComponent<DefenderHUD>();
ClientWorker.LoadedUI.TryGetValue("TeammateCanvas", out GameObject statusUpdater);
teamStatusUpdater = statusUpdater.transform.GetChild(0).GetComponent<TeamStatusUpdater>();
var defenderLinks = ClientWorker.ClientGameObjectCreator.OtherPlayerLinks.FindAll((link) => link.CompareTag(GameEntityTypes.Defender.ToString()));
for (int i = 0; i < defenderLinks.Count; ++i)
{
teamStatusUpdater.AddTeammate(defenderLinks[i]);
}
}
private void OnEntityAdded(Improbable.Gdk.GameObjectCreation.SpatialOSEntity obj)
{
if (obj.TryGetComponent(out GameMetadata.Component gameMetadata) && gameMetadata.Type == GameEntityTypes.Defender)
{
GameObject linkedDefender = ClientWorker.ClientGameObjectCreator.GetLinkedGameObjectById(obj.SpatialOSEntityId);
teamStatusUpdater.AddTeammate(linkedDefender.GetComponent<LinkedEntityComponent>());
}
}
private void OnHealthUpdate(int currentHealth)
{
float pct = currentHealth / (float)statsMetadataReader.Data.Health;
DefenderHUD.OnUpdateHealth(pct);
}
private void OnRespawnActiveChange(bool respawning)
{
gameObject.SetActive(!respawning);
if (respawning)
{
DefenderHUD.OnRespawning();
}
else
{
DefenderHUD.OnDoneRespawning();
}
}
public void LinkClientWorker(UnityClientConnector unityClientConnector)
{
ClientWorker = unityClientConnector;
unityClientConnector.ClientGameObjectCreator.OnEntityAdded += OnEntityAdded;
if (unityClientConnector.TryGetComponent(out GameStatusSynchronizer gameStatusSynchronizer))
{
if (TryGetComponent(out InputProcessorManager inputProcessorManager))
{
inputProcessorManager.SetSynchronizer(gameStatusSynchronizer);
}
else
{
Debug.LogError("Player synchronizer is missing input processor manager");
}
}
else
{
Debug.LogError("Client worker is missing game status synchronizer.");
}
}
}
} | 39.72381 | 158 | 0.650923 | [
"MIT"
] | ChristianBasiga/MDG | workers/unity/Assets/MDG/Scripts/Defender/Monobehaviours/DefenderSynchronizer.cs | 4,173 | C# |
using System;
namespace System.Reactive.Concurrency
{
public interface ISchedulerPeriodic
{
IDisposable SchedulePeriodic<TState> (TState state, TimeSpan period, Func<TState,TState> action);
}
}
| 19.181818 | 100 | 0.748815 | [
"MIT"
] | paulcbetts/mono-reactive | System.Reactive.Interfaces/System.Reactive.Concurrency/ISchedulerPeriodic.cs | 211 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.VFX;
using UnityEngine;
using UnityEngine.VFX;
using UnityObject = UnityEngine.Object;
namespace UnityEditor.VFX
{
static class VFXReflectionHelper
{
public static T[] CollectStaticReadOnlyExpression<T>(Type expressionType, System.Reflection.BindingFlags additionnalFlag = System.Reflection.BindingFlags.Public)
{
var members = expressionType.GetFields(System.Reflection.BindingFlags.Static | additionnalFlag)
.Where(m => m.IsInitOnly && m.FieldType == typeof(T))
.ToArray();
var expressions = members.Select(m => (T)m.GetValue(null)).ToArray();
return expressions;
}
}
abstract partial class VFXExpression
{
public struct Operands
{
public static readonly int OperandCount = 4;
int data0;
int data1;
int data2;
int data3;
public Operands(int defaultValue)
{
data0 = defaultValue;
data1 = defaultValue;
data2 = defaultValue;
data3 = defaultValue;
}
// This ugly code is for optimization purpose (no garbage created)
public int this[int index]
{
get
{
switch (index)
{
case 0: return data0;
case 1: return data1;
case 2: return data2;
case 3: return data3;
default: throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0: data0 = value; break;
case 1: data1 = value; break;
case 2: data2 = value; break;
case 3: data3 = value; break;
default: throw new IndexOutOfRangeException();
}
}
}
public int[] ToArray()
{
return new int[] { data0, data1, data2, data3 };
}
}
[Flags]
public enum Flags
{
None = 0,
Value = 1 << 0, // Expression is a value, get/set can be called on it
Foldable = 1 << 1, // Expression is not a constant but can be folded anyway
Constant = 1 << 2, // Expression is a constant, it can be folded
InvalidOnGPU = 1 << 3, // Expression can be evaluated on GPU
InvalidOnCPU = 1 << 4, // Expression can be evaluated on CPU
PerElement = 1 << 5, // Expression is per element
NotCompilableOnCPU = InvalidOnCPU | PerElement //Helper to filter out invalid expression on CPU
}
public static bool IsFloatValueType(VFXValueType valueType)
{
return valueType == VFXValueType.Float
|| valueType == VFXValueType.Float2
|| valueType == VFXValueType.Float3
|| valueType == VFXValueType.Float4;
}
public static bool IsUIntValueType(VFXValueType valueType)
{
return valueType == VFXValueType.Uint32;
}
public static bool IsIntValueType(VFXValueType valueType)
{
return valueType == VFXValueType.Int32;
}
public static bool IsBoolValueType(VFXValueType valueType)
{
return valueType == VFXValueType.Boolean;
}
public static int TypeToSize(VFXValueType type)
{
return VFXExpressionHelper.GetSizeOfType(type);
}
public static string TypeToCode(VFXValueType type)
{
switch (type)
{
case VFXValueType.Float: return "float";
case VFXValueType.Float2: return "float2";
case VFXValueType.Float3: return "float3";
case VFXValueType.Float4: return "float4";
case VFXValueType.Int32: return "int";
case VFXValueType.Uint32: return "uint";
case VFXValueType.Texture2D: return "Texture2D";
case VFXValueType.Texture2DArray: return "Texture2DArray";
case VFXValueType.Texture3D: return "Texture3D";
case VFXValueType.TextureCube: return "TextureCube";
case VFXValueType.TextureCubeArray: return "TextureCubeArray";
case VFXValueType.Matrix4x4: return "float4x4";
case VFXValueType.Boolean: return "bool";
}
throw new NotImplementedException(type.ToString());
}
// As certain type of uniforms are not handled in material, we need to use floats instead
public static string TypeToUniformCode(VFXValueType type)
{
switch (type)
{
case VFXValueType.Float: return "float";
case VFXValueType.Float2: return "float2";
case VFXValueType.Float3: return "float3";
case VFXValueType.Float4: return "float4";
case VFXValueType.Int32: return "float";
case VFXValueType.Uint32: return "float";
case VFXValueType.Matrix4x4: return "float4x4";
case VFXValueType.Boolean: return "float";
}
throw new NotImplementedException(type.ToString());
}
public static Type TypeToType(VFXValueType type)
{
switch (type)
{
case VFXValueType.Float: return typeof(float);
case VFXValueType.Float2: return typeof(Vector2);
case VFXValueType.Float3: return typeof(Vector3);
case VFXValueType.Float4: return typeof(Vector4);
case VFXValueType.Int32: return typeof(int);
case VFXValueType.Uint32: return typeof(uint);
case VFXValueType.Texture2D: return typeof(Texture);
case VFXValueType.Texture2DArray: return typeof(Texture);
case VFXValueType.Texture3D: return typeof(Texture);
case VFXValueType.TextureCube: return typeof(Texture);
case VFXValueType.TextureCubeArray: return typeof(Texture);
case VFXValueType.Matrix4x4: return typeof(Matrix4x4);
case VFXValueType.Mesh: return typeof(Mesh);
case VFXValueType.Curve: return typeof(AnimationCurve);
case VFXValueType.ColorGradient: return typeof(Gradient);
case VFXValueType.Boolean: return typeof(bool);
}
throw new NotImplementedException(type.ToString());
}
public static bool IsTypeValidOnGPU(VFXValueType type)
{
switch (type)
{
case VFXValueType.Float:
case VFXValueType.Float2:
case VFXValueType.Float3:
case VFXValueType.Float4:
case VFXValueType.Int32:
case VFXValueType.Uint32:
case VFXValueType.Texture2D:
case VFXValueType.Texture2DArray:
case VFXValueType.Texture3D:
case VFXValueType.TextureCube:
case VFXValueType.TextureCubeArray:
case VFXValueType.Matrix4x4:
case VFXValueType.Boolean:
return true;
}
return false;
}
public static bool IsTexture(VFXValueType type)
{
switch (type)
{
case VFXValueType.Texture2D:
case VFXValueType.Texture2DArray:
case VFXValueType.Texture3D:
case VFXValueType.TextureCube:
case VFXValueType.TextureCubeArray:
return true;
}
return false;
}
public static bool IsUniform(VFXValueType type)
{
switch (type)
{
case VFXValueType.Float:
case VFXValueType.Float2:
case VFXValueType.Float3:
case VFXValueType.Float4:
case VFXValueType.Int32:
case VFXValueType.Uint32:
case VFXValueType.Matrix4x4:
case VFXValueType.Boolean:
return true;
}
return false;
}
public static Type GetMatchingScalar(Type type)
{
var vfxType = GetVFXValueTypeFromType(type);
if (vfxType == VFXValueType.None)
{
var affinityFallback = VFXOperatorDynamicOperand.GetTypeAffinityList(type).GetEnumerator();
while (affinityFallback.MoveNext() && vfxType == VFXValueType.None)
{
vfxType = GetVFXValueTypeFromType(affinityFallback.Current);
}
}
return TypeToType(GetMatchingScalar(vfxType));
}
public static VFXValueType GetMatchingScalar(VFXValueType type)
{
if (IsFloatValueType(type))
return VFXValueType.Float;
if (IsUIntValueType(type))
return VFXValueType.Uint32;
if (IsIntValueType(type))
return VFXValueType.Int32;
return VFXValueType.None;
}
public static VFXValueType GetVFXValueTypeFromType(Type type)
{
if (type == typeof(float)) return VFXValueType.Float;
if (type == typeof(Vector2)) return VFXValueType.Float2;
if (type == typeof(Vector3)) return VFXValueType.Float3;
if (type == typeof(Vector4)) return VFXValueType.Float4;
if (type == typeof(Color)) return VFXValueType.Float4;
if (type == typeof(int)) return VFXValueType.Int32;
if (type == typeof(uint)) return VFXValueType.Uint32;
if (type == typeof(Texture2D)) return VFXValueType.Texture2D;
if (type == typeof(Texture2DArray)) return VFXValueType.Texture2DArray;
if (type == typeof(Texture3D)) return VFXValueType.Texture3D;
if (type == typeof(Cubemap)) return VFXValueType.TextureCube;
if (type == typeof(CubemapArray)) return VFXValueType.TextureCubeArray;
if (type == typeof(Matrix4x4)) return VFXValueType.Matrix4x4;
if (type == typeof(AnimationCurve)) return VFXValueType.Curve;
if (type == typeof(Gradient)) return VFXValueType.ColorGradient;
if (type == typeof(Mesh)) return VFXValueType.Mesh;
if (type == typeof(List<Vector3>)) return VFXValueType.Spline;
if (type == typeof(bool)) return VFXValueType.Boolean;
return VFXValueType.None;
}
private static Dictionary<VFXExpression, VFXExpression> s_ExpressionCache = new Dictionary<VFXExpression, VFXExpression>();
public static void ClearCache()
{
s_ExpressionCache.Clear();
}
//Ideally, we should use HashSet<T>.TryGetValue https://msdn.microsoft.com/en-us/library/mt829070(v=vs.110).aspx
//but it's available only in 4.7, Dictionary<T, T> is a workaround, sensible same performance but there is a waste of memory
private void SimplifyWithCacheParents()
{
for (int i = 0; i < m_Parents.Length; ++i)
{
VFXExpression parentEq;
if (!s_ExpressionCache.TryGetValue(parents[i], out parentEq))
{
s_ExpressionCache.Add(parents[i], parents[i]);
}
else
{
m_Parents[i] = parentEq;
}
}
}
protected VFXExpression(Flags flags, params VFXExpression[] parents)
{
m_Parents = parents;
SimplifyWithCacheParents();
m_Flags = flags;
PropagateParentsFlags();
}
// Only do that when constructing an instance if needed
private void Initialize(VFXExpression[] parents)
{
m_Parents = parents;
SimplifyWithCacheParents();
PropagateParentsFlags();
m_HashCodeCached = false; // as expression is mutated
}
//Helper using reflection to recreate a concrete type from an abstract class (useful with reduce behavior)
private static VFXExpression CreateNewInstance(Type expressionType)
{
var allconstructors = expressionType.GetConstructors().ToArray();
if (allconstructors.Length == 0)
return null; //Only static readonly expression allowed, constructors are private (attribute or builtIn)
var constructor = allconstructors
.OrderBy(o => o.GetParameters().Count()) //promote simplest (or default) constructors
.First();
var param = constructor.GetParameters().Select(o =>
{
var type = o.GetType();
return type.IsValueType ? Activator.CreateInstance(type) : null;
}).ToArray();
return (VFXExpression)constructor.Invoke(param);
}
private VFXExpression CreateNewInstance()
{
return CreateNewInstance(GetType());
}
// Reduce the expression
protected virtual VFXExpression Reduce(VFXExpression[] reducedParents)
{
if (reducedParents.Length == 0)
return this;
var reduced = CreateNewInstance();
reduced.Initialize(reducedParents);
return reduced;
}
// Evaluate the expression
protected virtual VFXExpression Evaluate(VFXExpression[] constParents)
{
throw new NotImplementedException();
}
// Get the HLSL code snippet
public virtual string GetCodeString(string[] parents)
{
throw new NotImplementedException(GetType().ToString());
}
// Get the operands for the runtime evaluation
public Operands GetOperands(VFXExpressionGraph graph)
{
var addOperands = additionnalOperands;
if (parents.Length + addOperands.Length > 4)
throw new Exception("Too much parameter for expression : " + this);
var data = new Operands(-1);
if (graph != null)
for (int i = 0; i < parents.Length; ++i)
data[i] = graph.GetFlattenedIndex(parents[i]);
for (int i = 0; i < addOperands.Length; ++i)
data[Operands.OperandCount - addOperands.Length + i] = addOperands[i];
return data;
}
public virtual IEnumerable<VFXAttributeInfo> GetNeededAttributes()
{
return Enumerable.Empty<VFXAttributeInfo>();
}
public bool Is(Flags flag) { return (m_Flags & flag) == flag; }
public bool IsAny(Flags flag) { return (m_Flags & flag) != 0; }
public virtual VFXValueType valueType
{
get
{
var data = GetOperands(null);
return VFXExpressionHelper.GetTypeOfOperation(operation, data[0], data[1], data[2], data[3]);
}
}
public abstract VFXExpressionOperation operation { get; }
public VFXExpression[] parents { get { return m_Parents; } }
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
return true;
var other = obj as VFXExpression;
if (other == null)
return false;
if (GetType() != other.GetType())
return false;
if (operation != other.operation)
return false;
if (valueType != other.valueType)
return false;
if (m_Flags != other.m_Flags)
return false;
if (GetHashCode() != other.GetHashCode())
return false;
var operands = additionnalOperands;
var otherOperands = other.additionnalOperands;
if (operands.Length != otherOperands.Length)
return false;
for (int i = 0; i < operands.Length; ++i)
if (operands[i] != otherOperands[i])
return false;
var thisParents = parents;
var otherParents = other.parents;
if (thisParents == null && otherParents == null)
return true;
if (thisParents == null || otherParents == null)
return false;
if (thisParents.Length != otherParents.Length)
return false;
for (int i = 0; i < thisParents.Length; ++i)
if (!thisParents[i].Equals(otherParents[i]))
return false;
return true;
}
public override sealed int GetHashCode()
{
if (!m_HashCodeCached)
{
m_HashCode = GetInnerHashCode();
m_HashCodeCached = true;
}
return m_HashCode;
}
protected virtual int GetInnerHashCode()
{
int hash = GetType().GetHashCode();
var parents = this.parents;
for (int i = 0; i < parents.Length; ++i)
hash = (hash * 397) ^ parents[i].GetHashCode(); // 397 taken from resharper
var operands = additionnalOperands;
for (int i = 0; i < operands.Length; ++i)
hash = (hash * 397) ^ operands[i].GetHashCode();
hash = (hash * 397) ^ m_Flags.GetHashCode();
hash = (hash * 397) ^ valueType.GetHashCode();
hash = (hash * 397) ^ operation.GetHashCode();
return hash;
}
private static readonly int[] k_EmptyOperands = Enumerable.Empty<int>().ToArray();
protected virtual int[] additionnalOperands { get { return k_EmptyOperands; } }
public virtual T Get<T>()
{
var value = (this as VFXValue<T>);
if (value == null)
{
throw new ArgumentException(string.Format("Get isn't available for {0} with {1}", typeof(T).FullName, GetType().FullName));
}
return value.Get();
}
public virtual object GetContent()
{
throw new ArgumentException(string.Format("GetContent isn't available for {0}", GetType().FullName));
}
private void PropagateParentsFlags()
{
if (m_Parents.Length > 0)
{
bool foldable = true;
foreach (var parent in m_Parents)
{
foldable &= parent.Is(Flags.Foldable);
m_Flags |= (parent.m_Flags & (Flags.NotCompilableOnCPU));
if (parent.IsAny(Flags.NotCompilableOnCPU) && parent.Is(Flags.InvalidOnGPU))
m_Flags |= Flags.InvalidOnGPU; // Only propagate GPU validity for per element expressions
}
if (foldable)
m_Flags |= Flags.Foldable;
else
m_Flags &= ~Flags.Foldable;
}
}
public static VFXExpression operator*(VFXExpression a, VFXExpression b) { return new VFXExpressionMul(a, b); }
public static VFXExpression operator/(VFXExpression a, VFXExpression b) { return new VFXExpressionDivide(a, b); }
public static VFXExpression operator+(VFXExpression a, VFXExpression b) { return new VFXExpressionAdd(a, b); }
public static VFXExpression operator-(VFXExpression a, VFXExpression b) { return new VFXExpressionSubtract(a, b); }
public static VFXExpression operator|(VFXExpression a, VFXExpression b) { return new VFXExpressionBitwiseOr(a, b); }
public static VFXExpression operator&(VFXExpression a, VFXExpression b) { return new VFXExpressionBitwiseAnd(a, b); }
public static VFXExpression operator|(VFXExpression a, uint b) { return new VFXExpressionBitwiseOr(a, VFXValue.Constant(b)); }
public static VFXExpression operator&(VFXExpression a, uint b) { return new VFXExpressionBitwiseAnd(a, VFXValue.Constant(b)); }
public static VFXExpression operator<<(VFXExpression a, int shift) { return new VFXExpressionBitwiseLeftShift(a, VFXValue.Constant((uint)shift)); }
public static VFXExpression operator>>(VFXExpression a, int shift) { return new VFXExpressionBitwiseRightShift(a, VFXValue.Constant((uint)shift)); }
public VFXExpression this[int index] { get { return new VFXExpressionExtractComponent(this, index); } }
public VFXExpression x { get { return new VFXExpressionExtractComponent(this, 0); } }
public VFXExpression y { get { return new VFXExpressionExtractComponent(this, 1); } }
public VFXExpression z { get { return new VFXExpressionExtractComponent(this, 2); } }
public VFXExpression w { get { return new VFXExpressionExtractComponent(this, 3); } }
public VFXExpression xxx { get { return new VFXExpressionCombine(x, x, x); } }
public VFXExpression yyy { get { return new VFXExpressionCombine(y, y, y); } }
public VFXExpression zzz { get { return new VFXExpressionCombine(z, z, z); } }
private Flags m_Flags = Flags.None;
private VFXExpression[] m_Parents;
private int m_HashCode;
private bool m_HashCodeCached = false;
}
}
| 40.247756 | 170 | 0.549157 | [
"MIT"
] | JesusGarciaValadez/RenderStreamingHDRP | RenderStreamingHDRP/Library/PackageCache/com.unity.visualeffectgraph@8.2.0/Editor/Expressions/VFXExpressionAbstract.cs | 22,418 | C# |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
namespace Wenzil.Console
{
/// <summary>
/// The interactive front-end of the console.
/// </summary>
[DisallowMultipleComponent]
[RequireComponent(typeof(ConsoleController))]
public class ConsoleUI : MonoBehaviour, IScrollHandler
{
public event Action<bool> onToggleConsole;
public event Action<string> onSubmitCommand;
public event Action onClearConsole;
public Scrollbar scrollbar;
public Text outputText;
public ScrollRect outputArea;
public InputField inputField;
//##
bool previousPauseState = false;
CanvasGroup cg;
/// <summary>
/// Indicates whether the console is currently open or close.
/// </summary>
public bool isConsoleOpen { get { return enabled; } }
void Awake()
{
Show(false);
}
/// <summary>
/// Opens or closes the console.
/// </summary>
public void ToggleConsole(bool force = false)
{
// Do nothing if HUD is not top window (e.g. player in some other menu)
if (!DaggerfallWorkshop.Game.GameManager.Instance.IsPlayerOnHUD && !force)
return;
// Do nothing if console not enabled in settings
if (!DaggerfallWorkshop.DaggerfallUnity.Settings.LypyL_GameConsole && !force)
return;
inputField.text = string.Empty;
enabled = !enabled;
if(enabled)
{
previousPauseState = DaggerfallWorkshop.Game.GameManager.IsGamePaused;
DaggerfallWorkshop.Game.GameManager.Instance.PauseGame(enabled, true);
}
else
DaggerfallWorkshop.Game.GameManager.Instance.PauseGame(previousPauseState);
if (!cg)
cg = this.GetComponent<CanvasGroup>();
if (cg != null)
cg.blocksRaycasts = enabled;
}
/// <summary>
/// Opens the console.
/// </summary>
public void OpenConsole()
{
enabled = true;
}
/// <summary>
/// Closes the console.
/// </summary>
public void CloseConsole()
{
enabled = false;
}
void OnEnable()
{
OnToggle(true);
}
void OnDisable()
{
OnToggle(false);
}
private void OnToggle(bool open)
{
Show(open);
if (open)
inputField.ActivateInputField();
else
ClearInput();
if (onToggleConsole != null)
onToggleConsole(open);
}
private void Show(bool show)
{
inputField.gameObject.SetActive(show);
outputArea.gameObject.SetActive(show);
scrollbar.gameObject.SetActive(show);
}
/// <summary>
/// What to do when the user wants to submit a command.
/// </summary>
public void OnSubmit(string input)
{
if (EventSystem.current.alreadySelecting) // if user selected something else, don't treat as a submit
return;
if (input.Length > 0)
{
if (onSubmitCommand != null)
onSubmitCommand(input);
scrollbar.value = 0;
ClearInput();
}
inputField.ActivateInputField();
}
/// <summary>
/// What to do when the user uses the scrollwheel while hovering the console input.
/// </summary>
public void OnScroll(PointerEventData eventData)
{
scrollbar.value += 0.08f * eventData.scrollDelta.y;
}
/// <summary>
/// Displays the given message as a new entry in the console output.
/// </summary>
public void AddNewOutputLine(string line)
{
outputText.text += Environment.NewLine + line;
}
/// <summary>
/// Clears the console output.
/// </summary>
public void ClearOutput()
{
outputText.text = "";
outputText.SetLayoutDirty();
if(onClearConsole != null)
onClearConsole();
}
/// <summary>
/// Clears the console input.
/// </summary>
public void ClearInput()
{
SetInputText("");
}
/// <summary>
/// Writes the given string into the console input, ready to be user submitted.
/// </summary>
public void SetInputText(string input)
{
inputField.MoveTextStart(false);
inputField.text = input;
inputField.MoveTextEnd(false);
}
}
} | 27.636872 | 113 | 0.524762 | [
"MIT"
] | InconsolableCellist/daggerfall-unity-1 | Assets/Game/Addons/UnityConsole/Console/Scripts/ConsoleUI.cs | 4,947 | C# |
/* License: http://www.apache.org/licenses/LICENSE-2.0 */
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using DotNetBrightener.LinQToSqlBuilder.Adapter;
namespace DotNetBrightener.LinQToSqlBuilder.Builder
{
/// <summary>
/// Provides methods to build up SQL query, adding up parameters and conditions to the query and generate the final SQL statement
/// </summary>
internal partial class SqlQueryBuilder
{
internal ISqlAdapter Adapter { get; set; }
internal SqlOperations Operation { get; set; } = SqlOperations.Query;
private const string ParameterPrefix = "Param";
private readonly List<string> _updateValues = new List<string>();
private List<string> TableNames { get; } = new List<string>();
private List<string> JoinExpressions { get; } = new List<string>();
private List<string> SelectionList { get; } = new List<string>();
private List<string> WhereConditions { get; } = new List<string>();
private List<string> OrderByList { get; } = new List<string>();
private List<string> GroupByList { get; } = new List<string>();
private List<string> HavingConditions { get; } = new List<string>();
internal List<string> SplitColumns { get; } = new List<string>();
public string InsertTarget
{
get
{
switch (Operation)
{
case SqlOperations.Insert:
return Adapter.Table(TableNames.First());
case SqlOperations.InsertFrom:
return Adapter.Table(TableNames.Last());
default:
throw new NotSupportedException("The property is not supported in other queries than INSERT query statement");
}
}
}
private int? _pageSize;
private int _pageIndex;
public int CurrentParamIndex { get; private set; }
private string Source
{
get
{
var joinExpression = string.Join(" ", JoinExpressions);
return $"{Adapter.Table(TableNames.First())} {joinExpression}";
}
}
private string Selection
{
get
{
if (SelectionList.Count == 0)
{
if (!JoinExpressions.Any())
return $"{Adapter.Table(TableNames.First())}.*";
var joinTables = TableNames.Select(_ => $"{Adapter.Table(_)}.*");
var selection = string.Join(", ", joinTables);
return selection;
}
return string.Join(", ", SelectionList);
}
}
private string Conditions => WhereConditions.Count == 0 ? "" : "WHERE " + string.Join("", WhereConditions);
private string UpdateValues => string.Join(", ", _updateValues);
private string _insertOutput { get; set; } = "";
private List<Dictionary<string, object>> InsertValues { get; } = new List<Dictionary<string, object>>();
private string Order => OrderByList.Count == 0 ? "" : "ORDER BY " + string.Join(", ", OrderByList);
private string Grouping => GroupByList.Count == 0 ? "" : "GROUP BY " + string.Join(", ", GroupByList);
private string Having => HavingConditions.Count == 0 ? "" : "HAVING " + string.Join(" ", HavingConditions);
public IDictionary<string, object> Parameters { get; private set; }
public string CommandText
{
get
{
switch (Operation)
{
case SqlOperations.Insert:
return Adapter.InsertCommand(InsertTarget, InsertValues, _insertOutput);
case SqlOperations.InsertFrom:
return Adapter.InsertFromCommand(InsertTarget, Source, InsertValues, Conditions);
case SqlOperations.Update:
return Adapter.UpdateCommand(UpdateValues, Source, Conditions);
case SqlOperations.Delete:
return Adapter.DeleteCommand(Source, Conditions);
default:
return GenerateQueryCommand();
}
}
}
internal SqlQueryBuilder(string tableName, ISqlAdapter adapter)
{
TableNames.Add(tableName);
Adapter = adapter;
Parameters = new ExpandoObject();
CurrentParamIndex = 0;
}
#region helpers
private string NextParamId()
{
++CurrentParamIndex;
return ParameterPrefix + CurrentParamIndex.ToString(CultureInfo.InvariantCulture);
}
private void AddParameter(string key, object value)
{
if(!Parameters.ContainsKey(key))
Parameters.Add(key, value);
}
#endregion
}
}
| 34.849315 | 134 | 0.556997 | [
"MIT"
] | DotNetBrightener/LinQ-To-Sql-Builder | LinQToSqlBuilder/Builder/SqlQueryBuilder.cs | 5,090 | C# |
using System.Security.Claims;
namespace GraphQL.Authorization
{
public interface IProvideClaimsPrincipal
{
ClaimsPrincipal User { get; }
}
} | 18 | 44 | 0.703704 | [
"MIT"
] | dnndevelopernc/authorization | src/GraphQL.Authorization/IProvideClaimsPrincipal.cs | 164 | C# |
using System;
using System.IO;
using System.Management.Automation;
namespace Axinom.LiveStreamValidation
{
[Cmdlet(VerbsDiagnostic.Test, "LiveStream")]
public class TestLiveStream : PSCmdlet
{
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Alias("Url")]
public Uri Uri { get; set; }
/// <summary>
/// Writes the manifest contents to this path, if specified.
/// </summary>
[Parameter]
[Alias("Save")]
public string ManifestOutputPath { get; set; }
protected override void ProcessRecord()
{
LiveStream.Validate(Uri, new PowerShellFeedback(this, ManifestOutputPath));
}
private sealed class PowerShellFeedback : IFeedbackSink
{
public PowerShellFeedback(Cmdlet cmdlet, string manifestOutputPath)
{
_cmdlet = cmdlet;
_manifestOutputPath = manifestOutputPath;
}
private readonly Cmdlet _cmdlet;
private readonly string _manifestOutputPath;
public void Info(string message)
{
_cmdlet.WriteVerbose(message);
}
public void InvalidContent(string message)
{
// The output from this is ugly and verbose but that's PowerShell for you.
_cmdlet.WriteError(new ErrorRecord(new Exception(message), "InvalidContent", ErrorCategory.InvalidData, null));
}
public void WillSkipSomeData(string message)
{
_cmdlet.WriteWarning(message);
}
public void DownloadedManifest(string contents)
{
if (string.IsNullOrWhiteSpace(_manifestOutputPath))
return;
var directory = Path.GetDirectoryName(_manifestOutputPath);
if (!string.IsNullOrWhiteSpace(directory))
Directory.CreateDirectory(directory);
File.WriteAllText(_manifestOutputPath, contents);
_cmdlet.WriteVerbose("Manifest saved to " + _manifestOutputPath);
}
}
}
} | 32.897059 | 127 | 0.59097 | [
"MIT"
] | Axinom/LiveStreamValidation | LiveStreamValidation.PowerShell/TestLiveStream.cs | 2,239 | C# |
using System.Configuration;
using System.Web.Mvc;
using Twilio.Auth;
using Faker;
namespace VideoQuickstart.Controllers
{
public class TokenController : Controller
{
// GET: /token
public ActionResult Index()
{
// Load Twilio configuration from Web.config
var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
var apiKey = ConfigurationManager.AppSettings["TwilioApiKey"];
var apiSecret = ConfigurationManager.AppSettings["TwilioApiSecret"];
var videoConfigSid = ConfigurationManager.AppSettings["TwilioConfigurationSid"];
// Create a random identity for the client
var identity = Internet.UserName();
// Create an Access Token generator
var token = new AccessToken(accountSid, apiKey, apiSecret);
token.Identity = identity;
// Create a video grant for this token
var grant = new VideoGrant();
grant.ConfigurationProfileSid = videoConfigSid;
token.AddGrant(grant);
return Json(new
{
identity,
token = token.ToJWT()
}, JsonRequestBehavior.AllowGet);
}
}
}
| 32.25641 | 92 | 0.614467 | [
"MIT"
] | KNovotny/TwilioVideoCaptureCSharp | VideoQuickstart/Controllers/TokenController.cs | 1,260 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using screen_fleet_admin.Models;
namespace screen_fleet_admin.Repositories
{
public interface ITVRepository
{
/*! \brief Get all the tv data from the Mongo context
* @return an async task containing a collection of TVModel
*/
Task<IEnumerable<TVModel>> GetAllTVScreens();
/*! \brief Get a specific tv screen according to its raw id
* @param[in] rawId the raw id of the tv screen
* @return an async task containing the tv model
*/
Task<TVModel> GetTVScreen(string name);
/*! \brief Add tv Model to the database
* @param[in] model the model to be inserted
*/
Task AddTVScreen(TVModel item);
/*! \brief Remove a specific tv with the specific RawId
* @param[in] rawId The raw id of the tv screen
* @return an asynchronous task wrapping a boolean, true if the deletion happened successfully,
* false otherwise
*/
Task<bool> RemoveTVScreen(string name);
/*! \brief Update the specific tv screen that maps the specific raw id
* @param[in] rawId The RawId of the specific model
* @param[in] tv The TV model
* @return an asynchronous task wrapping a boolean, return true if the modification has
* successfully done, false otherwise
*/
Task<bool> UpdateTVScreen(string name, TVModel tv);
/*! \brief Remove all the tv screens
* @return an asynchronous task wrapping a boolean, return true if the deletion has been
* successfully done, false otherwise
*/
Task<bool> RemoveAllTVScreen();
/*! \brief Modify the content of a TV screen by updating every resources in it
* @param[in] rawId the raw id of the TV screen
* @param[in] tv the model binding of the TV
* @return an asynchronous task set to true if the modification has been
* taken into account, false otherwise
*/
Task<bool> UpdateTVScreenContent(string rawId, TVModel tv);
}
}
| 40.807018 | 110 | 0.598452 | [
"MIT"
] | zed31/screen_fleet_admin | screen_fleet_admin/Repositories/ITVRepository.cs | 2,328 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace StorageMaster.Entities.Products
{
public class HradDrive : Product
{
private const double DEFAULT_WEIGHT = 1;
public HradDrive(double price)
: base(price, DEFAULT_WEIGHT)
{
}
}
}
| 19.6875 | 48 | 0.64127 | [
"MIT"
] | bodyquest/SoftwareUniversity-Bulgaria | C# OOP 2019/EXAM_PREP/C# OOP RE Exam 2018 26 April (StorageMaster)/StorageMaster/Entities/Products/HradDrive.cs | 317 | C# |
using Engine.Utilities.Mathematics;
using System;
using Color = Microsoft.Xna.Framework.Color;
// ReSharper disable PossibleLossOfFraction
namespace Engine.Utilities.Extensions
{
public static class ColorExtensions
{
public static Color FadeOut(this Color color)
{
color.A -= Convert.ToByte(1);
return color;
}
public static Color FadeIn(this Color color)
{
color.A += Convert.ToByte(1);
return color;
}
public static Color Darken(this Color color)
{
int r = Convert.ToInt32(color.R);
int g = Convert.ToInt32(color.G);
int b = Convert.ToInt32(color.B);
int total = 1 + r + g + b;
double rPercentValue = r / total;
double bPercentValue = b / total;
double chance;
for (int i = 0; i < 10; i++)
{
chance = Calculate.PercentValue();
if (chance <= rPercentValue)
{
color.R -= Convert.ToByte(1);
}
else if (chance <= bPercentValue + rPercentValue)
{
color.B -= Convert.ToByte(1);
}
else
color.G -= Convert.ToByte(1);
}
return color;
}
public static Color Brighten(this Color color)
{
int r = Convert.ToInt32(color.R);
int g = Convert.ToInt32(color.G);
int b = Convert.ToInt32(color.B);
int total = 1 + r + g + b;
double rPercentValue = r / total;
double bPercentValue = b / total;
double gPercentValue = g / total;
double chance;
for (int i = 0; i < 10; i++)
{
chance = Calculate.PercentValue();
if (chance <= rPercentValue)
{
//if (Convert.ToInt32(color.R) < 255)
color.R += Convert.ToByte(1);
}
else if (chance <= bPercentValue + rPercentValue)
{
//if (Convert.ToInt32(color.B) < 255)
color.G += Convert.ToByte(1);
}
else if (chance <= bPercentValue + rPercentValue + gPercentValue)
//if (Convert.ToInt32(color.G) < 255)
color.B += Convert.ToByte(1);
}
return color;
}
public static Color MutateToIndex(this Color color, double z)
{
for (double k = 0; k < z; k++)
color = color.Brighten();
for (double k = z; k < 0; k++)
color = color.Darken();
return color;
}
public static Color MutateBy(this Color baseColor, Color target)
{
Color newC = Color.Black;
newC.R = Convert.ToByte((baseColor.R + target.R) / 4);
newC.G = Convert.ToByte((baseColor.G + target.G) / 4);
newC.B = Convert.ToByte((baseColor.B + target.B) / 4);
return newC;
}
public static Color Half(this Color color)
{
return color.MutateBy(Color.Black);
}
public static Color Double(this Color color)
{
Color c = color;
int b = c.B * 2 > 255 ? 255 : c.B * 2;
c.B = Convert.ToByte(b);
int r = c.R * 2 > 255 ? 255 : c.R * 2;
c.R = Convert.ToByte(r);
int g = c.G * 2 > 255 ? 255 : c.G * 2;
c.G = Convert.ToByte(g);
return c;
}
public static Color Greenify(this Color color)
{
if (color.R > color.G || color.B > color.G)
{
Color target;
int chance = Calculate.PercentValue();
if (chance < 10)
target = Color.DarkGreen;
else if (chance < 20)
target = Color.LightGreen;
else if (chance < 30)
target = Color.MediumSpringGreen;
else if (chance < 40)
target = Color.SpringGreen;
else if (chance < 50)
target = Color.DarkOliveGreen;
else if (chance < 60)
target = Color.DarkGray;
else if (chance < 70)
target = Color.Olive;
else if (chance < 80)
target = Color.OliveDrab;
else if (chance < 90)
target = Color.DarkSeaGreen;
else
target = Color.ForestGreen;
color = color.MutateBy(target);
}
return color;
}
public static Color Redify(this Color color)
{
if (color.G > color.R || color.B > color.R)
{
Color target;
int chance = Calculate.PercentValue();
if (chance < 10)
target = Color.DarkRed;
else if (chance < 20)
target = Color.Maroon;
else if (chance < 30)
target = Color.Magenta;
else if (chance < 40)
target = Color.Red;
else if (chance < 50)
target = Color.IndianRed;
else if (chance < 60)
target = Color.MediumVioletRed;
else if (chance < 70)
target = Color.MistyRose;
else if (chance < 80)
target = Color.OrangeRed;
else if (chance < 90)
target = Color.PaleVioletRed;
else
target = Color.DeepPink;
color = color.MutateBy(target);
}
return color;
}
public static Color Blueify(this Color color)
{
if (color.R > color.B || color.G > color.B)
{
Color target;
int chance = Calculate.PercentValue();
if (chance < 10)
target = Color.DarkBlue;
else if (chance < 20)
target = Color.BlueViolet;
else if (chance < 30)
target = Color.AliceBlue;
else if (chance < 40)
target = Color.CadetBlue;
else if (chance < 50)
target = Color.CornflowerBlue;
else if (chance < 60)
target = Color.DarkSlateBlue;
else if (chance < 70)
target = Color.Navy;
else if (chance < 80)
target = Color.OliveDrab;
else if (chance < 90)
target = Color.DarkSeaGreen;
else
target = Color.ForestGreen;
color = color.MutateBy(target);
}
return color;
}
}
}
| 34.313084 | 82 | 0.42612 | [
"MIT"
] | fcheadle/HomicideDetective.Old | Engine/Utilities/Extensions/ColorExtensions.cs | 7,345 | C# |
using System;
using System.IO;
using System.Text;
using NUnit.Framework;
namespace MadMilkman.Ini.Tests
{
[TestFixture]
public class IniFileReadTests
{
[Test]
public void ReadDefaultTest()
{
string iniFileContent = ";Section's trailing comment." + Environment.NewLine +
"[Section's name];Section's leading comment." + Environment.NewLine +
";Key's trailing comment." + Environment.NewLine +
"Key's name = Key's value;Key's leading comment.";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions());
Assert.AreEqual(1, file.Sections.Count);
Assert.AreEqual("Section's trailing comment.", file.Sections[0].TrailingComment.Text);
Assert.AreEqual("Section's name", file.Sections[0].Name);
Assert.AreEqual("Section's leading comment.", file.Sections[0].LeadingComment.Text);
Assert.AreEqual(1, file.Sections[0].Keys.Count);
Assert.AreEqual("Key's trailing comment.", file.Sections[0].Keys[0].TrailingComment.Text);
Assert.AreEqual("Key's name", file.Sections[0].Keys[0].Name);
Assert.AreEqual("Key's value", file.Sections[0].Keys[0].Value);
Assert.AreEqual("Key's leading comment.", file.Sections[0].Keys[0].LeadingComment.Text);
}
[Test]
public void ReadCustomTest()
{
string iniFileContent = "#Section's trailing comment." + Environment.NewLine +
"{Section's name}#Section's leading comment." + Environment.NewLine +
"#Key's trailing comment." + Environment.NewLine +
"Key's name : Key's value#Key's leading comment.";
IniOptions options = new IniOptions()
{
CommentStarter = IniCommentStarter.Hash,
SectionWrapper = IniSectionWrapper.CurlyBrackets,
KeyDelimiter = IniKeyDelimiter.Colon
};
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, options);
Assert.AreEqual(1, file.Sections.Count);
Assert.AreEqual("Section's trailing comment.", file.Sections[0].TrailingComment.Text);
Assert.AreEqual("Section's name", file.Sections[0].Name);
Assert.AreEqual("Section's leading comment.", file.Sections[0].LeadingComment.Text);
Assert.AreEqual(1, file.Sections[0].Keys.Count);
Assert.AreEqual("Key's trailing comment.", file.Sections[0].Keys[0].TrailingComment.Text);
Assert.AreEqual("Key's name", file.Sections[0].Keys[0].Name);
Assert.AreEqual("Key's value", file.Sections[0].Keys[0].Value);
Assert.AreEqual("Key's leading comment.", file.Sections[0].Keys[0].LeadingComment.Text);
}
[Test]
public void ReadGlobalSectionTest()
{
string iniFileContent = ";Trailing comment1" + Environment.NewLine +
"Key1 = Value1" + Environment.NewLine +
";Trailing comment2" + Environment.NewLine +
"Key2 = Value2";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions());
Assert.AreEqual(1, file.Sections.Count);
Assert.AreEqual(IniSection.GlobalSectionName, file.Sections[0].Name);
Assert.AreEqual(2, file.Sections[0].Keys.Count);
Assert.AreEqual("Trailing comment1", file.Sections[0].Keys[0].TrailingComment.Text);
Assert.AreEqual("Key1", file.Sections[0].Keys[0].Name);
Assert.AreEqual("Value1", file.Sections[0].Keys[0].Value);
Assert.AreEqual("Trailing comment2", file.Sections[0].Keys[1].TrailingComment.Text);
Assert.AreEqual("Key2", file.Sections[0].Keys[1].Name);
Assert.AreEqual("Value2", file.Sections[0].Keys[1].Value);
}
[Test]
public void ReadMultipleGlobalSectionsTest()
{
string inputContent = "Key = Value" + Environment.NewLine +
"[Section]" + Environment.NewLine +
"Key = Value";
IniFile file = new IniFile();
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(inputContent)))
{
file.Load(stream);
file.Load(stream);
file.Load(stream);
}
Assert.AreEqual(6, file.Sections.Count);
Assert.AreEqual(IniSection.GlobalSectionName, file.Sections[0].Name);
Assert.AreEqual(IniSection.GlobalSectionName, file.Sections[2].Name);
Assert.AreEqual(IniSection.GlobalSectionName, file.Sections[4].Name);
Assert.AreEqual("Section", file.Sections[1].Name);
Assert.AreEqual("Section", file.Sections[3].Name);
Assert.AreEqual("Section", file.Sections[5].Name);
foreach (var section in file.Sections)
Assert.AreEqual(1, section.Keys.Count);
string outputContent;
using (var stream = new MemoryStream())
{
file.Save(stream);
outputContent = new StreamReader(stream, Encoding.ASCII).ReadToEnd();
}
file.Sections.Clear();
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(outputContent)))
file.Load(stream);
Assert.AreEqual(6, file.Sections.Count);
Assert.AreEqual(IniSection.GlobalSectionName, file.Sections[0].Name);
Assert.AreEqual(IniSection.GlobalSectionName, file.Sections[2].Name);
Assert.AreEqual(IniSection.GlobalSectionName, file.Sections[4].Name);
Assert.AreEqual("Section", file.Sections[1].Name);
Assert.AreEqual("Section", file.Sections[3].Name);
Assert.AreEqual("Section", file.Sections[5].Name);
foreach (var section in file.Sections)
Assert.AreEqual(1, section.Keys.Count);
}
[Test]
public void ReadUTF8EncodingTest()
{
string iniFileContent = "[Καλημέρα κόσμε]" + Environment.NewLine +
"こんにちは 世界 = ¥ £ € $ ¢ ₡ ₢ ₣ ₤ ₥ ₦ ₧ ₨ ₩ ₪ ₫ ₭ ₮ ₯ ₹";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions() { Encoding = Encoding.UTF8 });
Assert.AreEqual("Καλημέρα κόσμε", file.Sections[0].Name);
Assert.AreEqual("こんにちは 世界", file.Sections[0].Keys[0].Name);
Assert.AreEqual("¥ £ € $ ¢ ₡ ₢ ₣ ₤ ₥ ₦ ₧ ₨ ₩ ₪ ₫ ₭ ₮ ₯ ₹", file.Sections[0].Keys[0].Value);
}
[Test]
public void ReadEmptyLinesTest()
{
string iniFileContent = Environment.NewLine +
" \t " + Environment.NewLine +
"[Section]" + Environment.NewLine +
Environment.NewLine +
Environment.NewLine +
" \t " + Environment.NewLine +
"Key = Value" + Environment.NewLine +
Environment.NewLine +
" \t " + Environment.NewLine +
";" + Environment.NewLine +
"[Section]" + Environment.NewLine +
Environment.NewLine +
" \t " + Environment.NewLine +
Environment.NewLine +
";" + Environment.NewLine +
"Key = Value";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions());
Assert.AreEqual(2, file.Sections[0].LeadingComment.EmptyLinesBefore);
Assert.AreEqual(3, file.Sections[0].Keys[0].LeadingComment.EmptyLinesBefore);
Assert.AreEqual(2, file.Sections[1].TrailingComment.EmptyLinesBefore);
Assert.AreEqual(3, file.Sections[1].Keys[0].TrailingComment.EmptyLinesBefore);
}
[Test]
public void ReadCommentEdgeCasesTest()
{
string iniFileContent = ";" + Environment.NewLine +
";Section's trailing comment;" + Environment.NewLine +
"[Section]" + Environment.NewLine +
"[Section];" + Environment.NewLine +
"[Section] ;" + Environment.NewLine +
";" + Environment.NewLine +
";Key's trailing comment;" + Environment.NewLine +
"Key = Value " + Environment.NewLine +
"Key = Value;" + Environment.NewLine +
"Key = Value ;";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions());
Assert.AreEqual(Environment.NewLine + "Section's trailing comment;", file.Sections[0].TrailingComment.Text);
Assert.AreEqual("Section", file.Sections[0].Name);
Assert.IsNull(file.Sections[0].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].LeadingComment.LeftIndentation);
Assert.AreEqual("Section", file.Sections[1].Name);
Assert.IsEmpty(file.Sections[1].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[1].LeadingComment.LeftIndentation);
Assert.AreEqual("Section", file.Sections[2].Name);
Assert.IsEmpty(file.Sections[2].LeadingComment.Text);
Assert.AreEqual(2, file.Sections[2].LeadingComment.LeftIndentation);
Assert.AreEqual(Environment.NewLine + "Key's trailing comment;", file.Sections[2].Keys[0].TrailingComment.Text);
Assert.AreEqual("Key", file.Sections[2].Keys[0].Name);
Assert.AreEqual("Value ", file.Sections[2].Keys[0].Value);
Assert.IsNull(file.Sections[2].Keys[0].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[2].Keys[0].LeadingComment.LeftIndentation);
Assert.AreEqual("Key", file.Sections[2].Keys[1].Name);
Assert.AreEqual("Value", file.Sections[2].Keys[1].Value);
Assert.IsEmpty(file.Sections[2].Keys[1].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[2].Keys[1].LeadingComment.LeftIndentation);
Assert.AreEqual("Key", file.Sections[2].Keys[2].Name);
Assert.AreEqual("Value", file.Sections[2].Keys[2].Value);
Assert.IsEmpty(file.Sections[2].Keys[2].LeadingComment.Text);
Assert.AreEqual(2, file.Sections[2].Keys[2].LeadingComment.LeftIndentation);
}
[Test]
public void ReadValueEdgeCasesTest()
{
string iniFileContent = "[Section]" + Environment.NewLine +
"Key=" + Environment.NewLine +
"Key=;" + Environment.NewLine +
"Key= " + Environment.NewLine +
"Key= ;" + Environment.NewLine +
"Key =" + Environment.NewLine +
"Key =;" + Environment.NewLine +
"Key = " + Environment.NewLine +
"Key = ;" + Environment.NewLine +
"Key=;Test" + Environment.NewLine +
"Key = ;Test";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions());
Assert.IsEmpty(file.Sections[0].Keys[0].Value);
Assert.IsNull(file.Sections[0].Keys[0].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[0].LeadingComment.LeftIndentation);
Assert.IsEmpty(file.Sections[0].Keys[1].Value);
Assert.IsEmpty(file.Sections[0].Keys[1].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[1].LeadingComment.LeftIndentation);
Assert.AreEqual(" ", file.Sections[0].Keys[2].Value);
Assert.IsNull(file.Sections[0].Keys[2].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[2].LeadingComment.LeftIndentation);
Assert.AreEqual(" ", file.Sections[0].Keys[3].Value);
Assert.IsEmpty(file.Sections[0].Keys[3].LeadingComment.Text);
Assert.AreEqual(1, file.Sections[0].Keys[3].LeadingComment.LeftIndentation);
Assert.IsEmpty(file.Sections[0].Keys[4].Value);
Assert.IsNull(file.Sections[0].Keys[4].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[4].LeadingComment.LeftIndentation);
Assert.IsEmpty(file.Sections[0].Keys[5].Value);
Assert.IsEmpty(file.Sections[0].Keys[5].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[5].LeadingComment.LeftIndentation);
Assert.IsEmpty(file.Sections[0].Keys[6].Value);
Assert.IsNull(file.Sections[0].Keys[6].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[6].LeadingComment.LeftIndentation);
Assert.IsEmpty(file.Sections[0].Keys[7].Value);
Assert.IsEmpty(file.Sections[0].Keys[7].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[7].LeadingComment.LeftIndentation);
Assert.IsEmpty(file.Sections[0].Keys[8].Value);
Assert.AreEqual("Test", file.Sections[0].Keys[8].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[8].LeadingComment.LeftIndentation);
Assert.IsEmpty(file.Sections[0].Keys[9].Value);
Assert.AreEqual("Test", file.Sections[0].Keys[9].LeadingComment.Text);
Assert.AreEqual(0, file.Sections[0].Keys[9].LeadingComment.LeftIndentation);
}
[Test]
public void ReadSectionEdgeCasesTest()
{
string iniFileContent = "[" + Environment.NewLine +
"]" + Environment.NewLine +
"[]" + Environment.NewLine +
"[;]" + Environment.NewLine +
"[;;]" + Environment.NewLine +
"[[]]" + Environment.NewLine +
"[[]];" + Environment.NewLine +
"[[;]]" + Environment.NewLine +
"[[;]];";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions());
Assert.AreEqual(7, file.Sections.Count);
Assert.AreEqual(string.Empty, file.Sections[0].Name);
Assert.AreEqual(";", file.Sections[1].Name);
Assert.AreEqual(";;", file.Sections[2].Name);
Assert.AreEqual("[]", file.Sections[3].Name);
Assert.AreEqual("[]", file.Sections[4].Name);
Assert.AreEqual(string.Empty, file.Sections[4].LeadingComment.Text);
Assert.AreEqual("[;]", file.Sections[5].Name);
Assert.AreEqual("[;]", file.Sections[6].Name);
Assert.AreEqual(string.Empty, file.Sections[6].LeadingComment.Text);
}
[Test]
public void ReadQuotedValue()
{
string iniFileContent = "key1 = \"Test;Test\"" + Environment.NewLine +
"key2 = \"Test;Test\";" + Environment.NewLine +
"key3 = \"Test;Test" + Environment.NewLine +
"key4 = \"Test;Test;Test\"Test;Test;Test";
IniFile file = IniUtilities.LoadIniFileContent(iniFileContent, new IniOptions());
IniSection section = file.Sections[0];
Assert.AreEqual("\"Test;Test\"", file.Sections[0].Keys[0].Value);
Assert.IsNull(file.Sections[0].Keys[0].LeadingComment.Text);
Assert.AreEqual("\"Test;Test\"", file.Sections[0].Keys[1].Value);
Assert.AreEqual(string.Empty, file.Sections[0].Keys[1].LeadingComment.Text);
Assert.AreEqual("\"Test", file.Sections[0].Keys[2].Value);
Assert.AreEqual("Test", file.Sections[0].Keys[2].LeadingComment.Text);
Assert.AreEqual("\"Test;Test;Test\"Test", file.Sections[0].Keys[3].Value);
Assert.AreEqual("Test;Test", file.Sections[0].Keys[3].LeadingComment.Text);
}
}
}
| 53.310127 | 124 | 0.552238 | [
"MIT"
] | DrewNaylor/MadMilkman.Ini | MadMilkman.Ini.Tests/IniFileReadTests.cs | 16,972 | C# |
using System;
namespace Chaos.NaCl.Internal.Ed25519Ref10
{
internal static partial class ScalarOperations
{
/*
Input:
s[0]+256*s[1]+...+256^63*s[63] = s
Output:
s[0]+256*s[1]+...+256^31*s[31] = s mod l
where l = 2^252 + 27742317777372353535851937790883648493.
Overwrites s in place.
*/
public static void sc_reduce(byte[] s)
{
Int64 s0 = 2097151 & load_3(s, 0);
Int64 s1 = 2097151 & (load_4(s, 2) >> 5);
Int64 s2 = 2097151 & (load_3(s, 5) >> 2);
Int64 s3 = 2097151 & (load_4(s, 7) >> 7);
Int64 s4 = 2097151 & (load_4(s, 10) >> 4);
Int64 s5 = 2097151 & (load_3(s, 13) >> 1);
Int64 s6 = 2097151 & (load_4(s, 15) >> 6);
Int64 s7 = 2097151 & (load_3(s, 18) >> 3);
Int64 s8 = 2097151 & load_3(s, 21);
Int64 s9 = 2097151 & (load_4(s, 23) >> 5);
Int64 s10 = 2097151 & (load_3(s, 26) >> 2);
Int64 s11 = 2097151 & (load_4(s, 28) >> 7);
Int64 s12 = 2097151 & (load_4(s, 31) >> 4);
Int64 s13 = 2097151 & (load_3(s, 34) >> 1);
Int64 s14 = 2097151 & (load_4(s, 36) >> 6);
Int64 s15 = 2097151 & (load_3(s, 39) >> 3);
Int64 s16 = 2097151 & load_3(s, 42);
Int64 s17 = 2097151 & (load_4(s, 44) >> 5);
Int64 s18 = 2097151 & (load_3(s, 47) >> 2);
Int64 s19 = 2097151 & (load_4(s, 49) >> 7);
Int64 s20 = 2097151 & (load_4(s, 52) >> 4);
Int64 s21 = 2097151 & (load_3(s, 55) >> 1);
Int64 s22 = 2097151 & (load_4(s, 57) >> 6);
Int64 s23 = (load_4(s, 60) >> 3);
Int64 carry0;
Int64 carry1;
Int64 carry2;
Int64 carry3;
Int64 carry4;
Int64 carry5;
Int64 carry6;
Int64 carry7;
Int64 carry8;
Int64 carry9;
Int64 carry10;
Int64 carry11;
Int64 carry12;
Int64 carry13;
Int64 carry14;
Int64 carry15;
Int64 carry16;
s11 += s23 * 666643;
s12 += s23 * 470296;
s13 += s23 * 654183;
s14 -= s23 * 997805;
s15 += s23 * 136657;
s16 -= s23 * 683901;
s23 = 0;
s10 += s22 * 666643;
s11 += s22 * 470296;
s12 += s22 * 654183;
s13 -= s22 * 997805;
s14 += s22 * 136657;
s15 -= s22 * 683901;
s22 = 0;
s9 += s21 * 666643;
s10 += s21 * 470296;
s11 += s21 * 654183;
s12 -= s21 * 997805;
s13 += s21 * 136657;
s14 -= s21 * 683901;
s21 = 0;
s8 += s20 * 666643;
s9 += s20 * 470296;
s10 += s20 * 654183;
s11 -= s20 * 997805;
s12 += s20 * 136657;
s13 -= s20 * 683901;
s20 = 0;
s7 += s19 * 666643;
s8 += s19 * 470296;
s9 += s19 * 654183;
s10 -= s19 * 997805;
s11 += s19 * 136657;
s12 -= s19 * 683901;
s19 = 0;
s6 += s18 * 666643;
s7 += s18 * 470296;
s8 += s18 * 654183;
s9 -= s18 * 997805;
s10 += s18 * 136657;
s11 -= s18 * 683901;
s18 = 0;
carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; s6 -= carry6 << 21;
carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; s8 -= carry8 << 21;
carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; s10 -= carry10 << 21;
carry12 = (s12 + (1 << 20)) >> 21; s13 += carry12; s12 -= carry12 << 21;
carry14 = (s14 + (1 << 20)) >> 21; s15 += carry14; s14 -= carry14 << 21;
carry16 = (s16 + (1 << 20)) >> 21; s17 += carry16; s16 -= carry16 << 21;
carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; s7 -= carry7 << 21;
carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; s9 -= carry9 << 21;
carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; s11 -= carry11 << 21;
carry13 = (s13 + (1 << 20)) >> 21; s14 += carry13; s13 -= carry13 << 21;
carry15 = (s15 + (1 << 20)) >> 21; s16 += carry15; s15 -= carry15 << 21;
s5 += s17 * 666643;
s6 += s17 * 470296;
s7 += s17 * 654183;
s8 -= s17 * 997805;
s9 += s17 * 136657;
s10 -= s17 * 683901;
s17 = 0;
s4 += s16 * 666643;
s5 += s16 * 470296;
s6 += s16 * 654183;
s7 -= s16 * 997805;
s8 += s16 * 136657;
s9 -= s16 * 683901;
s16 = 0;
s3 += s15 * 666643;
s4 += s15 * 470296;
s5 += s15 * 654183;
s6 -= s15 * 997805;
s7 += s15 * 136657;
s8 -= s15 * 683901;
s15 = 0;
s2 += s14 * 666643;
s3 += s14 * 470296;
s4 += s14 * 654183;
s5 -= s14 * 997805;
s6 += s14 * 136657;
s7 -= s14 * 683901;
s14 = 0;
s1 += s13 * 666643;
s2 += s13 * 470296;
s3 += s13 * 654183;
s4 -= s13 * 997805;
s5 += s13 * 136657;
s6 -= s13 * 683901;
s13 = 0;
s0 += s12 * 666643;
s1 += s12 * 470296;
s2 += s12 * 654183;
s3 -= s12 * 997805;
s4 += s12 * 136657;
s5 -= s12 * 683901;
s12 = 0;
carry0 = (s0 + (1 << 20)) >> 21; s1 += carry0; s0 -= carry0 << 21;
carry2 = (s2 + (1 << 20)) >> 21; s3 += carry2; s2 -= carry2 << 21;
carry4 = (s4 + (1 << 20)) >> 21; s5 += carry4; s4 -= carry4 << 21;
carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; s6 -= carry6 << 21;
carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; s8 -= carry8 << 21;
carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; s10 -= carry10 << 21;
carry1 = (s1 + (1 << 20)) >> 21; s2 += carry1; s1 -= carry1 << 21;
carry3 = (s3 + (1 << 20)) >> 21; s4 += carry3; s3 -= carry3 << 21;
carry5 = (s5 + (1 << 20)) >> 21; s6 += carry5; s5 -= carry5 << 21;
carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; s7 -= carry7 << 21;
carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; s9 -= carry9 << 21;
carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; s11 -= carry11 << 21;
s0 += s12 * 666643;
s1 += s12 * 470296;
s2 += s12 * 654183;
s3 -= s12 * 997805;
s4 += s12 * 136657;
s5 -= s12 * 683901;
s12 = 0;
carry0 = s0 >> 21; s1 += carry0; s0 -= carry0 << 21;
carry1 = s1 >> 21; s2 += carry1; s1 -= carry1 << 21;
carry2 = s2 >> 21; s3 += carry2; s2 -= carry2 << 21;
carry3 = s3 >> 21; s4 += carry3; s3 -= carry3 << 21;
carry4 = s4 >> 21; s5 += carry4; s4 -= carry4 << 21;
carry5 = s5 >> 21; s6 += carry5; s5 -= carry5 << 21;
carry6 = s6 >> 21; s7 += carry6; s6 -= carry6 << 21;
carry7 = s7 >> 21; s8 += carry7; s7 -= carry7 << 21;
carry8 = s8 >> 21; s9 += carry8; s8 -= carry8 << 21;
carry9 = s9 >> 21; s10 += carry9; s9 -= carry9 << 21;
carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21;
carry11 = s11 >> 21; s12 += carry11; s11 -= carry11 << 21;
s0 += s12 * 666643;
s1 += s12 * 470296;
s2 += s12 * 654183;
s3 -= s12 * 997805;
s4 += s12 * 136657;
s5 -= s12 * 683901;
s12 = 0;
carry0 = s0 >> 21; s1 += carry0; s0 -= carry0 << 21;
carry1 = s1 >> 21; s2 += carry1; s1 -= carry1 << 21;
carry2 = s2 >> 21; s3 += carry2; s2 -= carry2 << 21;
carry3 = s3 >> 21; s4 += carry3; s3 -= carry3 << 21;
carry4 = s4 >> 21; s5 += carry4; s4 -= carry4 << 21;
carry5 = s5 >> 21; s6 += carry5; s5 -= carry5 << 21;
carry6 = s6 >> 21; s7 += carry6; s6 -= carry6 << 21;
carry7 = s7 >> 21; s8 += carry7; s7 -= carry7 << 21;
carry8 = s8 >> 21; s9 += carry8; s8 -= carry8 << 21;
carry9 = s9 >> 21; s10 += carry9; s9 -= carry9 << 21;
carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21;
unchecked
{
s[0] = (byte)(s0 >> 0);
s[1] = (byte)(s0 >> 8);
s[2] = (byte)((s0 >> 16) | (s1 << 5));
s[3] = (byte)(s1 >> 3);
s[4] = (byte)(s1 >> 11);
s[5] = (byte)((s1 >> 19) | (s2 << 2));
s[6] = (byte)(s2 >> 6);
s[7] = (byte)((s2 >> 14) | (s3 << 7));
s[8] = (byte)(s3 >> 1);
s[9] = (byte)(s3 >> 9);
s[10] = (byte)((s3 >> 17) | (s4 << 4));
s[11] = (byte)(s4 >> 4);
s[12] = (byte)(s4 >> 12);
s[13] = (byte)((s4 >> 20) | (s5 << 1));
s[14] = (byte)(s5 >> 7);
s[15] = (byte)((s5 >> 15) | (s6 << 6));
s[16] = (byte)(s6 >> 2);
s[17] = (byte)(s6 >> 10);
s[18] = (byte)((s6 >> 18) | (s7 << 3));
s[19] = (byte)(s7 >> 5);
s[20] = (byte)(s7 >> 13);
s[21] = (byte)(s8 >> 0);
s[22] = (byte)(s8 >> 8);
s[23] = (byte)((s8 >> 16) | (s9 << 5));
s[24] = (byte)(s9 >> 3);
s[25] = (byte)(s9 >> 11);
s[26] = (byte)((s9 >> 19) | (s10 << 2));
s[27] = (byte)(s10 >> 6);
s[28] = (byte)((s10 >> 14) | (s11 << 7));
s[29] = (byte)(s11 >> 1);
s[30] = (byte)(s11 >> 9);
s[31] = (byte)(s11 >> 17);
}
}
}
} | 38.501901 | 84 | 0.376852 | [
"MIT"
] | AndreiLuis/MySqlConnector | src/MySqlConnector.Authentication.Ed25519/Chaos.NaCl/Internal/Ed25519Ref10/sc_reduce.cs | 10,128 | 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("02. Numbers Not Divisible by 3 and 7")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. Numbers Not Divisible by 3 and 7")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1a09e401-035c-4e03-9edd-3c38b0d7d448")]
// 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")]
| 39.054054 | 84 | 0.742561 | [
"MIT"
] | Horwits/Telerik-Academy-2016-2017 | C#/C#-Part-One/06. Loops/02. Numbers Not Divisible by 3 and 7/Properties/AssemblyInfo.cs | 1,448 | C# |
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace ObjectObfuscator.Tests.Handlers
{
public class CollectionTestCases
{
public object[] Test14() => new object[] { typeof(ImmutableList<int>), true };
public object[] Test1() => new object[] { typeof(StringCollection), false };
public object[] Test10() => new object[] { typeof(Queue<int>), true };
public object[] Test11() => new object[] { typeof(Stack<int>), true };
public object[] Test12() => new object[] { typeof(ConcurrentQueue<int>), true };
public object[] Test13() => new object[] { typeof(ConcurrentStack<int>), true };
public object[] Test15() => new object[] { typeof(ImmutableQueue<int>), true };
public object[] Test16() => new object[] { typeof(ImmutableStack<int>), true };
public object[] Test17() => new object[] { typeof(ImmutableSortedSet<int>), true };
public object[] Test18() => new object[] { typeof(ImmutableHashSet<int>), true };
public object[] Test2() => new object[] { typeof(ArrayList), false };
public object[] Test3() => new object[] { typeof(Queue), false };
public object[] Test4() => new object[] { typeof(Stack), false };
public object[] Test5() => new object[] { typeof(List<int>), true };
public object[] Test6() => new object[] { typeof(LinkedList<int>), true };
public object[] Test7() => new object[] { typeof(ObservableCollection<int>), true };
public object[] Test8() => new object[] { typeof(HashSet<int>), true };
public object[] Test9() => new object[] { typeof(SortedSet<int>), true };
}
} | 38.104167 | 92 | 0.629306 | [
"Apache-2.0"
] | maciur/ObjectObfuscator | ObjectObfuscator.Tests/Handlers/CollectionTestCases.cs | 1,831 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Melee
{
public class B_Melee : MonoBehaviour
{
private bool team = false; // Indicador que é o time A
private float CoolDownDash = 3;
private float velocidade = 3;
private int vidinha = 6;
Rigidbody rb;
public Slider health;
public GameObject time;
//public Transform vortice;
//public Transform vortice1;
//public GameObject voce;
void Start()
{
rb = GetComponent<Rigidbody>();
health.value += vidinha;
}
void Update()
{
CoolDownDash -= Time.deltaTime;
velocidade = Library.Biblioteca.clampMelee(velocidade);
Transform ia = Library.Biblioteca.setTarget(rb, time);
Library.Biblioteca.Dash(rb, ia, CoolDownDash, velocidade);
}
private void OnCollisionStay(Collision collision)
{
//print(collision.gameObject.tag);
for (int i = 0; i < 3; i++)
{
if (i == 0) velocidade = Library.Biblioteca.onPlaneMelee(collision, velocidade, vidinha, health, i);
//if (i == 1) vidinha = (int) Library.Biblioteca.onPlaneMelee(collision, velocidade, vidinha, health, i);
//if (i == 2) health.value = Library.Biblioteca.onPlaneMelee(collision, velocidade, vidinha, health, i);
}
if (collision.gameObject.layer == 6)
{
if (CoolDownDash <= 0)
{
vidinha -= 2;
health.value -= 2;
CoolDownDash = 3;
}
}
}
private void OnCollisionEnter(Collision collision)
{
vidinha = Library.Biblioteca.damageLife(collision, vidinha, team);
health.value = Library.Biblioteca.damageSlider(collision, health, team);
velocidade = Library.Biblioteca.damageSpeed(collision, velocidade, team);
for (int i = 0; i < 2; i++)
{
if (i == 0) velocidade = Library.Biblioteca.melee(collision, velocidade, CoolDownDash,team, i);
if (i == 1) CoolDownDash = Library.Biblioteca.melee(collision, velocidade, CoolDownDash,team, i);
}
Library.Biblioteca.death(rb, vidinha, health);
}
}
}
/*if(collision.gameObject.CompareTag("Vortice"))
{
voce.transform.position = vortice1.transform.position;
}
if(collision.gameObject.CompareTag("Vortice1"))
{
voce.transform.position = vortice.transform.position.x;
}*/
/*private void OnTriggerEnter (Collider other)
{
if(GetComponent<Collider>().gameObject.CompareTag("Vortice"))
{
voce.transform.position = vortice1.transform.position;
}
if(GetComponent<Collider>().gameObject.CompareTag("Vortice1"))
{
voce.transform.position = vortice.transform.position;
}
}*/ | 30.384615 | 121 | 0.559177 | [
"MIT"
] | ProblemaTheu/IPJ-Hexagun | Assets/Script/Classes/ScriptTime2/B_Melee.cs | 3,163 | C# |
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.SecurityAccountsManager;
using System.Management.Automation.SecurityAccountsManager.Extensions;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The Get-LocalUser cmdlet gets local user accounts from the Windows Security
/// Accounts Manager. This includes local accounts that have been connected to a
/// Microsoft account.
/// </summary>
[Cmdlet(VerbsCommon.Get, "LocalUser",
DefaultParameterSetName = "Default",
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=717980")]
[Alias("glu")]
public class GetLocalUserCommand : Cmdlet
{
#region Instance Data
private Sam sam = null;
#endregion Instance Data
#region Parameter Properties
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies the local user accounts to get from the local Security Accounts
/// Manager. This accepts a name or wildcard string.
/// </summary>
[Parameter(Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "Default")]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return this.name; }
set { this.name = value; }
}
private string[] name;
/// <summary>
/// The following is the definition of the input parameter "SID".
/// Specifies a user from the local Security Accounts Manager.
/// </summary>
[Parameter(Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SecurityIdentifier")]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public System.Security.Principal.SecurityIdentifier[] SID
{
get { return this.sid; }
set { this.sid = value; }
}
private System.Security.Principal.SecurityIdentifier[] sid;
#endregion Parameter Properties
#region Cmdlet Overrides
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
sam = new Sam();
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
if (Name == null && SID == null)
{
foreach (var user in sam.GetAllLocalUsers())
WriteObject(user);
return;
}
ProcessNames();
ProcessSids();
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
if (sam != null)
{
sam.Dispose();
sam = null;
}
}
#endregion Cmdlet Overrides
#region Private Methods
/// <summary>
/// Process users requested by -Name
/// </summary>
/// <remarks>
/// All arguments to -Name will be treated as names,
/// even if a name looks like a SID.
/// Users may be specified using wildcards.
/// </remarks>
private void ProcessNames()
{
if (Name != null)
{
foreach (var nm in Name)
{
try
{
if (WildcardPattern.ContainsWildcardCharacters(nm))
{
var pattern = new WildcardPattern(nm, WildcardOptions.Compiled
| WildcardOptions.IgnoreCase);
foreach (var user in sam.GetMatchingLocalUsers(n => pattern.IsMatch(n)))
WriteObject(user);
}
else
{
WriteObject(sam.GetLocalUser(nm));
}
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
/// <summary>
/// Process users requested by -SID
/// </summary>
private void ProcessSids()
{
if (SID != null)
{
foreach (var s in SID)
{
try
{
WriteObject(sam.GetLocalUser(s));
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
#endregion Private Methods
}//End Class
}//End namespace
| 30.855491 | 100 | 0.493256 | [
"Apache-2.0",
"MIT"
] | HydAu/PowerShell | src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs | 5,338 | C# |
// <copyright file="ChannelSourceComponent.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// </copyright>
using Microsoft.Psi;
using Microsoft.Psi.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace AI4Bharat.ISLBot.Services.Psi
{
public class ChannelSourceComponent<T> : ISourceComponent
{
private readonly Pipeline pipeline;
private readonly ChannelReader<T> channelReader;
private readonly Func<T, DateTime> calculateOriginatingTime;
private Action<DateTime> notifyCompletionTime;
public Emitter<T> Out { get; }
private CancellationTokenSource cancellationSource;
public ChannelSourceComponent(Pipeline pipeline, ChannelReader<T> channelReader, Func<T, DateTime> calculateOriginatingTime)
{
this.pipeline = pipeline;
this.channelReader = channelReader;
this.calculateOriginatingTime = calculateOriginatingTime;
this.Out = pipeline.CreateEmitter<T>(this, "Channel Reader");
this.cancellationSource = new CancellationTokenSource();
Task.Run(() => this.ReadChannel(), cancellationSource.Token);
}
public void Start(Action<DateTime> notifyCompletionTime)
{
this.notifyCompletionTime = notifyCompletionTime;
}
public void Stop(DateTime finalOriginatingTime, Action notifyCompleted)
{
notifyCompleted();
}
public async Task ReadChannel()
{
while (await channelReader.WaitToReadAsync())
while (channelReader.TryRead(out T item))
this.Out.Post(item, this.calculateOriginatingTime(item));
this.notifyCompletionTime(DateTime.UtcNow);
}
}
}
| 33.87931 | 132 | 0.681425 | [
"MIT"
] | AI4Bharat/INCLUDE-MS-Teams-Integration | src/AI4Bharat.ISLBot.Services/psi/ChannelSourceComponent.cs | 1,967 | C# |
using UnityEditor;
using UnityEngine;
using System.IO;
public class TextureCreatorWindow : EditorWindow {
string filename = "myProceduralTexture";
float perlinXScale;
float perlinYScale;
int perlinOctaves;
float perlinPersistance;
float perlinHeightScale;
int perlinOffsetX;
int perlinOffsetY;
bool alphaToggle = false;
bool seamlessToggle = false;
bool mapToggle = false;
float brightness = 0.5f;
float contrast = 0.5f;
Texture2D pTexture;
[MenuItem("Window/TextureCreatorWindow")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(TextureCreatorWindow));
}
void OnEnable()
{
pTexture = new Texture2D(513, 513, TextureFormat.ARGB32, false);
}
void OnGUI()
{
GUILayout.Label("Settings", EditorStyles.boldLabel);
filename = EditorGUILayout.TextField("Texture Name", filename);
int wSize = (int)(EditorGUIUtility.currentViewWidth - 100);
perlinXScale = EditorGUILayout.Slider("X Scale", perlinXScale, 0, 0.1f);
perlinYScale = EditorGUILayout.Slider("Y Scale", perlinYScale, 0, 0.1f);
perlinOctaves = EditorGUILayout.IntSlider("Octaves", perlinOctaves, 1, 10);
perlinPersistance = EditorGUILayout.Slider("Persistance", perlinPersistance, 1, 10);
perlinHeightScale = EditorGUILayout.Slider("Height Scale", perlinHeightScale, 0, 1);
perlinOffsetX = EditorGUILayout.IntSlider("Offset X", perlinOffsetX, 0, 10000);
perlinOffsetY = EditorGUILayout.IntSlider("Offset Y", perlinOffsetY, 0, 10000);
brightness = EditorGUILayout.Slider("Brightness", brightness, 0, 2);
contrast = EditorGUILayout.Slider("Contrast", contrast, 0, 2);
alphaToggle = EditorGUILayout.Toggle("Alpha?", alphaToggle);
mapToggle = EditorGUILayout.Toggle("Map?", mapToggle);
seamlessToggle = EditorGUILayout.Toggle("Seamless", seamlessToggle);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
float minColour = 1;
float maxColour = 0;
if (GUILayout.Button("Generate", GUILayout.Width(wSize)))
{
int w = 513;
int h = 513;
float pValue;
Color pixCol = Color.white;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
if (seamlessToggle)
{
float u = (float)x / (float)w;
float v = (float)y / (float)h;
float noise00 = Utils.fBM((x + perlinOffsetX) * perlinXScale,
(y + perlinOffsetY) * perlinYScale,
perlinOctaves,
perlinPersistance) * perlinHeightScale;
float noise01 = Utils.fBM((x + perlinOffsetX) * perlinXScale,
(y + perlinOffsetY + h) * perlinYScale,
perlinOctaves,
perlinPersistance) * perlinHeightScale;
float noise10 = Utils.fBM((x + perlinOffsetX + w) * perlinXScale,
(y + perlinOffsetY) * perlinYScale,
perlinOctaves,
perlinPersistance) * perlinHeightScale;
float noise11 = Utils.fBM((x + perlinOffsetX + w) * perlinXScale,
(y + perlinOffsetY + h) * perlinYScale,
perlinOctaves,
perlinPersistance) * perlinHeightScale;
float noiseTotal = u * v * noise00 +
u * (1 - v) * noise01 +
(1 - u) * v * noise10 +
(1 - u) * (1 - v) * noise11;
float value = (int)(256 * noiseTotal) + 50;
float r = Mathf.Clamp((int) noise00,0,255);
float g = Mathf.Clamp(value, 0, 255);
float b = Mathf.Clamp(value + 50, 0, 255);
float a = Mathf.Clamp(value + 100, 0, 255);
pValue = (r + g + b) / (3 * 255.0f);
}
else
{
pValue = Utils.fBM((x + perlinOffsetX) * perlinXScale,
(y + perlinOffsetY) * perlinYScale,
perlinOctaves,
perlinPersistance) * perlinHeightScale;
}
float colValue = contrast * (pValue - 0.5f) + 0.5f * brightness;
if (minColour > colValue) minColour = colValue;
if (maxColour < colValue) maxColour = colValue;
pixCol = new Color(colValue, colValue, colValue, alphaToggle ? colValue : 1);
pTexture.SetPixel(x, y, pixCol);
}
}
if (mapToggle)
{
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
pixCol = pTexture.GetPixel(x, y);
float colValue = pixCol.r;
colValue = Utils.Mapping(colValue, minColour, maxColour, 0, 1);
pixCol.r = colValue;
pixCol.g = colValue;
pixCol.b = colValue;
pTexture.SetPixel(x, y, pixCol);
}
}
}
pTexture.Apply(false, false);
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(pTexture, GUILayout.Width(wSize), GUILayout.Height(wSize));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Save", GUILayout.Width(wSize)))
{
byte[] bytes = pTexture.EncodeToPNG();
System.IO.Directory.CreateDirectory(Application.dataPath + "/SavedTextures");
File.WriteAllBytes(Application.dataPath + "/SavedTextures/" + filename + ".png", bytes);
AssetDatabase.Refresh();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
}
| 41.439024 | 100 | 0.488228 | [
"Apache-2.0"
] | PastIsPower/Unity3DTerrainSeek | Assets/Editor/TextureCreatorWindow.cs | 6,798 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataFactory
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static partial class SdkInfo
{
public static IEnumerable<Tuple<string, string, string>> ApiInfo_DataFactoryManagementClient
{
get
{
return new Tuple<string, string, string>[]
{
new Tuple<string, string, string>("DataFactory", "ActivityRuns", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "DataFlowDebugSession", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "DataFlows", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "Datasets", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "ExposureControl", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "Factories", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "IntegrationRuntimeNodes", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "IntegrationRuntimeObjectMetadata", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "IntegrationRuntimes", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "LinkedServices", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "Operations", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "PipelineRuns", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "Pipelines", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "RerunTriggers", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "TriggerRuns", "2018-06-01"),
new Tuple<string, string, string>("DataFactory", "Triggers", "2018-06-01"),
}.AsEnumerable();
}
}
// BEGIN: Code Generation Metadata Section
public static readonly String AutoRestVersion = "latest";
public static readonly String AutoRestBootStrapperVersion = "autorest@2.0.4283";
public static readonly String AutoRestCmdExecuted = "cmd.exe /c autorest.cmd https://github.com/Azure/azure-rest-api-specs/blob/master/specification/datafactory/resource-manager/readme.md --csharp --version=latest --reflect-api-versions --tag=package-2018-06 --csharp-sdks-folder=C:\\Git\\azure-sdk-for-net\\sdk";
public static readonly String GithubForkName = "Azure";
public static readonly String GithubBranchName = "master";
public static readonly String GithubCommidId = "6560b6724324bc795979e807bac151336b2b3153";
public static readonly String CodeGenerationErrors = "";
public static readonly String GithubRepoName = "azure-rest-api-specs";
// END: Code Generation Metadata Section
}
}
| 57.851852 | 319 | 0.654609 | [
"MIT"
] | LingyunSu/azure-sdk-for-net | sdk/datafactory/Microsoft.Azure.Management.DataFactory/src/Generated/SdkInfo_DataFactoryManagementClient.cs | 3,124 | C# |
#region License
//--------------------------------------------------
// <License>
// <Copyright> 2018 © Top Nguyen </Copyright>
// <Url> http://topnguyen.net/ </Url>
// <Author> Top </Author>
// <Project> Elect </Project>
// <File>
// <Name> WithoutVirtualContractResolver.cs </Name>
// <Created> 15/03/2018 8:21:24 PM </Created>
// <Key> 6a7f2a2b-4c39-4406-9120-17c6d503c917 </Key>
// </File>
// <Summary>
// WithoutVirtualContractResolver.cs is a part of Elect
// </Summary>
// <License>
//--------------------------------------------------
#endregion License
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;
namespace Elect.Core.JsonContractResolver
{
public class WithoutVirtualContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
var propInfo = member as PropertyInfo;
if (propInfo == null)
{
return prop;
}
if (propInfo.GetMethod.IsVirtual && !propInfo.GetMethod.IsFinal)
{
prop.ShouldSerialize = obj => false;
}
return prop;
}
}
} | 30.217391 | 114 | 0.560432 | [
"MIT"
] | nminhduc/Elect | src/Elect.Core/JsonContractResolver/WithoutVirtualContractResolver.cs | 1,393 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core.Pipeline;
using Azure.Management.KeyVault.Models;
namespace Azure.Management.KeyVault
{
/// <summary> The PrivateLinkResources service client. </summary>
public partial class PrivateLinkResourcesClient
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal PrivateLinkResourcesRestClient RestClient { get; }
/// <summary> Initializes a new instance of PrivateLinkResourcesClient for mocking. </summary>
protected PrivateLinkResourcesClient()
{
}
/// <summary> Initializes a new instance of PrivateLinkResourcesClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
internal PrivateLinkResourcesClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null, string apiVersion = "2019-09-01")
{
RestClient = new PrivateLinkResourcesRestClient(clientDiagnostics, pipeline, subscriptionId, endpoint, apiVersion);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Gets the private link resources supported for the key vault. </summary>
/// <param name="resourceGroupName"> Name of the resource group that contains the key vault. </param>
/// <param name="vaultName"> The name of the key vault. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<PrivateLinkResourceListResult>> ListByVaultAsync(string resourceGroupName, string vaultName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateLinkResourcesClient.ListByVault");
scope.Start();
try
{
return await RestClient.ListByVaultAsync(resourceGroupName, vaultName, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the private link resources supported for the key vault. </summary>
/// <param name="resourceGroupName"> Name of the resource group that contains the key vault. </param>
/// <param name="vaultName"> The name of the key vault. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<PrivateLinkResourceListResult> ListByVault(string resourceGroupName, string vaultName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateLinkResourcesClient.ListByVault");
scope.Start();
try
{
return RestClient.ListByVault(resourceGroupName, vaultName, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 47.886076 | 195 | 0.668253 | [
"MIT"
] | LeighS/azure-sdk-for-net | sdk/keyvault/Azure.Management.KeyVault/src/Generated/PrivateLinkResourcesClient.cs | 3,783 | C# |
using GzyConcept.Core.Base;
using System;
using System.Collections.Generic;
namespace GzyConcept.Core.Entities
{
[Serializable]
public class Product : BaseEntity
{
public string Name { get; set; }
public string Image { get; set; }
public string Explanation { get; set; }
public bool IsSliderImage { get; set; }
public List<string> LabelCollection { get; set; }
public int? ProductCategoryId { get; set; }
public virtual ProductCategory Category { get; set; }
}
} | 21.72 | 61 | 0.640884 | [
"MIT"
] | kartalm/GzyConcept | GzyConcept.Core/Entities/Product.cs | 543 | 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/msxml.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IXMLElement" /> struct.</summary>
public static unsafe class IXMLElementTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IXMLElement" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IXMLElement).GUID, Is.EqualTo(IID_IXMLElement));
}
/// <summary>Validates that the <see cref="IXMLElement" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IXMLElement>(), Is.EqualTo(sizeof(IXMLElement)));
}
/// <summary>Validates that the <see cref="IXMLElement" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IXMLElement).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IXMLElement" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IXMLElement), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IXMLElement), Is.EqualTo(4));
}
}
}
}
| 35.557692 | 145 | 0.621958 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/msxml/IXMLElementTests.cs | 1,851 | C# |
using AllReady.Areas.Admin.Models;
using MediatR;
namespace AllReady.Areas.Admin.Features.Skills
{
public class SkillEditCommandAsync : IAsyncRequest<int>
{
public SkillEditModel Skill { get; set; }
}
} | 22.4 | 59 | 0.71875 | [
"MIT"
] | HydAu/AllReadyCopyJune10_2016 | AllReadyApp/Web-App/AllReady/Areas/Admin/Features/Skills/SkillEditCommandAsync.cs | 226 | C# |
namespace TeamBuilder.Models.Helpers
{
public class Constants
{
/* User */
public const int UsernameMinLength = 3;
public const int UsernameMaxLength = 25;
public const int UserFirstNameMaxLength = 25;
public const int UserLastNameMaxLength = 25;
public const int UserAgeMinLength = 0;
public const int UserAgeMaxLength = int.MaxValue;
public const int PasswordMinLength = 6;
public const int PasswordMaxLength = 30;
/* Team */
public const int TeamNameMaxLength = 25;
public const int TeamDescriptionMaxLength = 32;
public const int TeamAcronymExactLength = 3;
/* Events */
public const int EventNameMaxLength = 25;
public const int EventDescriptionMaxLength = 250;
public const int DefaultStringMinLength = 1;
public const string PasswordMissingDigitExceptionMessage = "Password must contain at least one Digit!";
public const string PasswordMissingUpperCaseExceptionMessage = "Password must contain at least one Upper Case Letter!";
public const string StringInvalidLengthExceptionMessage = "{0} must be long between ({1}-{2})!";
public const string IntegerRangeExceptionMessage = "{0} must be between ({1}-{2})!";
public const string StartDateErrorExceptionMessage = "Wrong start date!";
}
}
| 42.090909 | 127 | 0.683225 | [
"MIT"
] | RAstardzhiev/SoftUni-C- | Databases Advanced - Entity Framework Core/Workshop/TeamBuilder.Models/Helpers/Constants.cs | 1,391 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Diagnostics.DataProviders.DataProviderConfigurations;
using Diagnostics.DataProviders.Interfaces;
using Diagnostics.ModelsAndUtils.Models;
using Newtonsoft.Json;
namespace Diagnostics.DataProviders
{
public class AppInsightsDataProvider : DiagnosticDataProvider, IDiagnosticDataProvider, IAppInsightsDataProvider
{
const string AppInsightsTagName = "hidden-related:diagnostics/applicationInsightsSettings";
private readonly IAppInsightsClient _appInsightsClient;
private AppInsightsDataProviderConfiguration _configuration;
public AppInsightsDataProvider(OperationDataCache cache, AppInsightsDataProviderConfiguration configuration) : base(cache)
{
_configuration = configuration;
_appInsightsClient = new AppInsightsClient(_configuration);
Metadata = new DataProviderMetadata
{
ProviderName = "AppInsights"
};
}
public Task<bool> SetAppInsightsKey(string appId, string apiKey)
{
_appInsightsClient.SetAppInsightsKey(appId, apiKey);
return Task.FromResult(true);
}
public async Task<bool> SetAppInsightsKey(OperationContext<IResource> cxt)
{
bool keyFound = false;
if (cxt.Resource is App app && app.Tags != null)
{
var tag = GetAppIdAndKeyFromAppSettingsTags(app.Tags);
if (tag != null)
{
keyFound = await SetAppInsightsKey(tag.AppId, DecryptString(tag.ApiKey));
}
}
return keyFound;
}
private string DecryptString(string encryptedString)
{
byte[] iv = new byte[16];
byte[] buffer = Convert.FromBase64String(encryptedString);
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(_configuration.EncryptionKey);
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream(buffer))
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
}
private AppInsightsTag GetAppIdAndKeyFromAppSettingsTags(string tagsXml)
{
AppInsightsTag tag = null;
var tagValue = GetTagValue(tagsXml, AppInsightsTagName);
if (!string.IsNullOrWhiteSpace(tagValue))
{
tag = JsonConvert.DeserializeObject<AppInsightsTag>(tagValue);
}
return tag;
}
private string GetTagValue(string tagsXml, string key)
{
string tagValue = string.Empty;
var xDocument = XDocument.Parse(tagsXml);
XNamespace nsSys = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
IEnumerable<XElement> tag = from el in xDocument.Elements(nsSys + "ArrayOfKeyValueOfstringstring").Elements()
where (string)el.Element(nsSys + "Key") == key
select el;
if (tag != null && tag.Count() > 0)
{
var valueElement = tag.FirstOrDefault().Element(nsSys + "Value");
if (valueElement != null)
{
tagValue = valueElement.Value;
}
}
return tagValue;
}
public async Task<DataTable> ExecuteAppInsightsQuery(string query, string operationName)
{
AddQueryInformationToMetadata(query, operationName);
return await _appInsightsClient.ExecuteQueryAsync(query);
}
public async Task<DataTable> ExecuteAppInsightsQuery(string query)
{
return await ExecuteAppInsightsQuery(query, "");
}
private void AddQueryInformationToMetadata(string query, string operationName = "")
{
bool queryExists = Metadata.PropertyBag.Any(x => x.Key == "Query" &&
x.Value.GetType() == typeof(DataProviderMetadataQuery) &&
x.Value.CastTo<DataProviderMetadataQuery>().Text.Equals(query, StringComparison.OrdinalIgnoreCase));
if (!queryExists)
{
Metadata.PropertyBag.Add(new KeyValuePair<string, object>("Query",
new DataProviderMetadataQuery()
{
Text = query,
Url = "https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/log-query-overview",
OperationName = operationName
}
));
}
}
public DataProviderMetadata GetMetadata()
{
return Metadata;
}
}
}
| 37.773973 | 160 | 0.570444 | [
"MIT"
] | dejo-msft/Azure-AppServices-Diagnostics | src/Diagnostics.DataProviders/DataProviders/AppInsightsDataProvider.cs | 5,517 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using SnippetsApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SnippetsApp.Controllers
{
[AuthorizeForScopes(Scopes = new [] { GraphConstants.CalendarReadWrite })]
public class CalendarController : BaseController
{
private readonly string[] _calendarScopes =
new [] { GraphConstants.CalendarReadWrite };
public CalendarController(
ITokenAcquisition tokenAcquisition,
ILogger<HomeController> logger) : base(tokenAcquisition, logger)
{
}
// GET /Calendar
// Displays a calendar view of the current week for
// the logged-in user
public async Task<IActionResult> Index()
{
try
{
var userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(
User.GetUserGraphTimeZone());
var startOfWeek = CalendarController.GetUtcStartOfWeekInTimeZone(
DateTime.Today, userTimeZone);
var events = await GetUserWeekCalendar(startOfWeek);
var model = new CalendarViewModel(startOfWeek, events);
return View(model);
}
catch (ServiceException ex)
{
if (ex.InnerException is MsalUiRequiredException)
{
throw ex;
}
return View(new CalendarViewModel())
.WithError("Error getting calendar view", ex.Message);
}
}
// GET /Calendar/Display?eventId=""
// eventId: ID of the event to display
// Displays the requested event allowing the user
// to delete, update, or respond
public async Task<IActionResult> Display(string eventId)
{
if (string.IsNullOrEmpty(eventId))
{
return RedirectToAction("Index")
.WithError("Event ID cannot be empty.");
}
try
{
var graphClient = GetGraphClientForScopes(_calendarScopes);
// GET /me/events/eventId
var graphEvent = await graphClient.Me
.Events[eventId]
.Request()
// Send the Prefer header so times are in the user's timezone
.Header("Prefer", $"outlook.timezone=\"{User.GetUserGraphTimeZone()}\"")
// Request only the fields used by the app
.Select(e => new
{
e.Attendees,
e.Body,
e.End,
e.Id,
e.IsOrganizer,
e.Location,
e.Organizer,
e.ResponseStatus,
e.Start,
e.Subject
})
// Include attachments in the response
.Expand("attachments")
.GetAsync();
return View(graphEvent);
}
catch(ServiceException ex)
{
InvokeAuthIfNeeded(ex);
return RedirectToAction("Index")
.WithError($"Error getting event with ID {eventId}",
ex.Error.Message);
}
}
// GET /Calendar/New
// Gets the new event form
public IActionResult New()
{
return View();
}
// POST /Calendar/New
// Receives form data to create a new event
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> New([Bind("Subject,Attendees,Start,End,Body")] NewEvent newEvent)
{
var timeZone = User.GetUserGraphTimeZone();
// Create a Graph event with the required fields
var graphEvent = new Event
{
Subject = newEvent.Subject,
Start = new DateTimeTimeZone
{
DateTime = newEvent.Start.ToString("o"),
// Use the user's time zone
TimeZone = timeZone
},
End = new DateTimeTimeZone
{
DateTime = newEvent.End.ToString("o"),
// Use the user's time zone
TimeZone = timeZone
}
};
// Add body if present
if (!string.IsNullOrEmpty(newEvent.Body))
{
graphEvent.Body = new ItemBody
{
ContentType = BodyType.Text,
Content = newEvent.Body
};
}
// Add attendees if present
if (!string.IsNullOrEmpty(newEvent.Attendees))
{
var attendees =
newEvent.Attendees.Split(';', StringSplitOptions.RemoveEmptyEntries);
if (attendees.Length > 0)
{
var attendeeList = new List<Attendee>();
foreach (var attendee in attendees)
{
attendeeList.Add(new Attendee{
EmailAddress = new EmailAddress
{
Address = attendee
},
Type = AttendeeType.Required
});
}
}
}
try
{
var graphClient = GetGraphClientForScopes(_calendarScopes);
// Add the event
// POST /me/events
await graphClient.Me.Events
.Request()
.AddAsync(graphEvent);
// Redirect to the calendar view with a success message
return RedirectToAction("Index").WithSuccess("Event created");
}
catch (ServiceException ex)
{
// Redirect to the calendar view with an error message
return RedirectToAction("Index")
.WithError("Error creating event", ex.Error.Message);
}
}
// POST /Calendar/Update
// Receives form data to update the start and end times
// for an event
// eventId: ID of the event to update
// startTime: New start time
// startTimeZone: Time zone for start time
// endTime: New end time
// endTimeZone: Time zone for end time
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Update(string eventId,
string startTime,
string startTimeZone,
string endTime,
string endTimeZone)
{
if (string.IsNullOrEmpty(eventId))
{
return RedirectToAction("Index")
.WithError("Event ID cannot be empty.");
}
try
{
var graphClient = GetGraphClientForScopes(_calendarScopes);
// Create a new Event object with only the
// fields to update set
var updateEvent = new Event
{
Start = new DateTimeTimeZone
{
DateTime = startTime,
TimeZone = startTimeZone
},
End = new DateTimeTimeZone
{
DateTime = endTime,
TimeZone = endTimeZone
}
};
// PATCH /me/events/eventId
await graphClient.Me
.Events[eventId]
.Request()
.UpdateAsync(updateEvent);
return RedirectToAction("Display", new { eventId = eventId })
.WithSuccess("Event times updated");
}
catch(ServiceException ex)
{
InvokeAuthIfNeeded(ex);
return RedirectToAction("Display", new { eventId = eventId })
.WithError($"Error updating event with ID {eventId}",
ex.Error.Message);
}
}
// POST /Calendar/Accept
// Receives form data to accept an event
// eventId: ID of the event to accept
// sendResponse: True to send the response to the organizer
// comment: Optional message to include in response to organizer
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Accept(string eventId,
bool sendResponse,
string comment)
{
if (string.IsNullOrEmpty(eventId))
{
return RedirectToAction("Index")
.WithError("Event ID cannot be empty.");
}
try
{
var graphClient = GetGraphClientForScopes(_calendarScopes);
// POST /me/events/eventId/accept
await graphClient.Me
.Events[eventId]
.Accept(comment, sendResponse)
.Request()
.PostAsync();
return RedirectToAction("Display", new { eventId = eventId })
.WithSuccess("Meeting accepted");
}
catch(ServiceException ex)
{
InvokeAuthIfNeeded(ex);
return RedirectToAction("Display", new { eventId = eventId })
.WithError("Error accepting meeting",
ex.Error.Message);
}
}
// POST /Calendar/Tentative
// Receives form data to tentatively accept an event
// eventId: ID of the event to tentatively accept
// sendResponse: True to send the response to the organizer
// comment: Optional message to include in response to organizer
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Tentative(string eventId,
bool sendResponse,
string comment)
{
if (string.IsNullOrEmpty(eventId))
{
return RedirectToAction("Index")
.WithError("Event ID cannot be empty.");
}
try
{
var graphClient = GetGraphClientForScopes(_calendarScopes);
// POST /me/events/eventId/tentativelyAccept
await graphClient.Me
.Events[eventId]
.TentativelyAccept(comment, sendResponse)
.Request()
.PostAsync();
return RedirectToAction("Display", new { eventId = eventId })
.WithSuccess("Meeting tentatively accepted");
}
catch(ServiceException ex)
{
InvokeAuthIfNeeded(ex);
return RedirectToAction("Display", new { eventId = eventId })
.WithError("Error tentatively accepting meeting",
ex.Error.Message);
}
}
// POST /Calendar/Decline
// Receives form data to decline an event
// eventId: ID of the event to decline
// sendResponse: True to send the response to the organizer
// comment: Optional message to include in response to organizer
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Decline(string eventId,
bool sendResponse,
string comment)
{
if (string.IsNullOrEmpty(eventId))
{
return RedirectToAction("Index")
.WithError("Event ID cannot be empty.");
}
try
{
var graphClient = GetGraphClientForScopes(_calendarScopes);
// POST /me/events/eventId/decline
await graphClient.Me
.Events[eventId]
.Decline(comment, sendResponse)
.Request()
.PostAsync();
return RedirectToAction("Index")
.WithSuccess("Meeting declined");
}
catch(ServiceException ex)
{
InvokeAuthIfNeeded(ex);
return RedirectToAction("Display", new { eventId = eventId })
.WithError("Error declining meeting",
ex.Error.Message);
}
}
// POST /Calendar/Delete
// Deletes an event from the calendar
// If user is the organizer and there are attendees,
// attendees will receive a cancellation
// eventId: ID of the event to delete
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(string eventId)
{
if (string.IsNullOrEmpty(eventId))
{
return RedirectToAction("Index")
.WithError("Event ID cannot be empty.");
}
try
{
var graphClient = GetGraphClientForScopes(_calendarScopes);
// DELETE /me/events/eventId
await graphClient.Me
.Events[eventId]
.Request()
.DeleteAsync();
return RedirectToAction("Index")
.WithSuccess("Event deleted");
}
catch(ServiceException ex)
{
InvokeAuthIfNeeded(ex);
return RedirectToAction("Index")
.WithError($"Error deleting event with ID {eventId}",
ex.Error.Message);
}
}
private async Task<IList<Event>> GetUserWeekCalendar(DateTime startOfWeek)
{
var graphClient = GraphServiceClientFactory
.GetAuthenticatedGraphClient(async () =>
{
return await _tokenAcquisition
.GetAccessTokenForUserAsync(_calendarScopes);
}
);
// Configure a calendar view for the current week
var endOfWeek = startOfWeek.AddDays(7);
var viewOptions = new List<QueryOption>
{
new QueryOption("startDateTime", startOfWeek.ToString("o")),
new QueryOption("endDateTime", endOfWeek.ToString("o"))
};
var events = await graphClient.Me
.CalendarView
.Request(viewOptions)
// Send user time zone in request so date/time in
// response will be in preferred time zone
.Header("Prefer", $"outlook.timezone=\"{User.GetUserGraphTimeZone()}\"")
// Get max 50 per request
.Top(50)
// Only return fields app will use
.Select(e => new
{
e.Subject,
e.Organizer,
e.Start,
e.End
})
// Order results chronologically
.OrderBy("start/dateTime")
.GetAsync();
IList<Event> allEvents;
// Handle case where there are more than 50
if (events.NextPageRequest != null)
{
allEvents = new List<Event>();
// Create a page iterator to iterate over subsequent pages
// of results. Build a list from the results
var pageIterator = PageIterator<Event>.CreatePageIterator(
graphClient, events,
(e) => {
allEvents.Add(e);
return true;
}
);
await pageIterator.IterateAsync();
}
else
{
// If only one page, just use the result
allEvents = events.CurrentPage;
}
return allEvents;
}
private static DateTime GetUtcStartOfWeekInTimeZone(DateTime today, TimeZoneInfo timeZone)
{
// Assumes Sunday as first day of week
int diff = System.DayOfWeek.Sunday - today.DayOfWeek;
// create date as unspecified kind
var unspecifiedStart = DateTime.SpecifyKind(today.AddDays(diff), DateTimeKind.Unspecified);
// convert to UTC
return TimeZoneInfo.ConvertTimeToUtc(unspecifiedStart, timeZone);
}
}
}
| 35.349495 | 106 | 0.480512 | [
"MIT"
] | isabella232/aspnet-snippets-sample | SnippetsApp/Controllers/CalendarController.cs | 17,498 | C# |
using System.Xml.Serialization;
using Wps.Client.Utils;
namespace Wps.Client.Models.Ows
{
/// <summary>
/// General metadata for a specific server.
/// </summary>
[XmlRoot("ServiceIdentification", Namespace = ModelNamespaces.Ows)]
public class ServiceIdentification : DescriptiveObject
{
/// <summary>
/// A service type name from a registry of services.
/// </summary>
[XmlElement("ServiceType", Namespace = ModelNamespaces.Ows)]
public string Type { get; set; }
/// <summary>
/// Unordered list of one or more versions of this service type implemented by the server.
/// </summary>
[XmlElement("ServiceTypeVersion", Namespace = ModelNamespaces.Ows)]
public string Versions { get; set; }
/// <summary>
/// Fees and terms for retrieving data from or otherwise using this server, including the monetary units as specified in ISO 4217. The reserved value NONE (case insensitive) shall be used to mean no fees or terms.
/// </summary>
[XmlElement("Fees", Namespace = ModelNamespaces.Ows)]
public string Fees { get; set; }
/// <summary>
/// Access constraint applied to assure the protection of privacy or intellectual property, or any other restrictions on retrieving or using data from or otherwise using this server. The reserved value NONE (case insensitive) shall be used to mean no access constraints are imposed.
/// </summary>
[XmlElement("AccessConstraints", Namespace = ModelNamespaces.Ows)]
public string AccessConstraints { get; set; }
}
}
| 42.128205 | 290 | 0.665247 | [
"Apache-2.0"
] | 52North/wps.net | src/Wps/Wps.Client/Models/Ows/ServiceIdentification.cs | 1,645 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V3109</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V3109 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT130101UK03.PertinentInformation6", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("UKCT_MT130101UK03.PertinentInformation6", Namespace="urn:hl7-org:v3")]
public partial class UKCT_MT130101UK03PertinentInformation6 {
private BL seperatableIndField;
private UKCT_MT130101UK03PrescriberEndorsement pertinentPrescriberEndorsementField;
private string typeField;
private string typeCodeField;
private bool inversionIndField;
private bool contextConductionIndField;
private bool negationIndField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public UKCT_MT130101UK03PertinentInformation6() {
this.typeField = "ActRelationship";
this.typeCodeField = "PERT";
this.inversionIndField = false;
this.contextConductionIndField = true;
this.negationIndField = false;
}
public BL seperatableInd {
get {
return this.seperatableIndField;
}
set {
this.seperatableIndField = value;
}
}
public UKCT_MT130101UK03PrescriberEndorsement pertinentPrescriberEndorsement {
get {
return this.pertinentPrescriberEndorsementField;
}
set {
this.pertinentPrescriberEndorsementField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string typeCode {
get {
return this.typeCodeField;
}
set {
this.typeCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool inversionInd {
get {
return this.inversionIndField;
}
set {
this.inversionIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool contextConductionInd {
get {
return this.contextConductionIndField;
}
set {
this.contextConductionIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool negationInd {
get {
return this.negationIndField;
}
set {
this.negationIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT130101UK03PertinentInformation6));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current UKCT_MT130101UK03PertinentInformation6 object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an UKCT_MT130101UK03PertinentInformation6 object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output UKCT_MT130101UK03PertinentInformation6 object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out UKCT_MT130101UK03PertinentInformation6 obj, out System.Exception exception) {
exception = null;
obj = default(UKCT_MT130101UK03PertinentInformation6);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out UKCT_MT130101UK03PertinentInformation6 obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static UKCT_MT130101UK03PertinentInformation6 Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((UKCT_MT130101UK03PertinentInformation6)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current UKCT_MT130101UK03PertinentInformation6 object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an UKCT_MT130101UK03PertinentInformation6 object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output UKCT_MT130101UK03PertinentInformation6 object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out UKCT_MT130101UK03PertinentInformation6 obj, out System.Exception exception) {
exception = null;
obj = default(UKCT_MT130101UK03PertinentInformation6);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out UKCT_MT130101UK03PertinentInformation6 obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static UKCT_MT130101UK03PertinentInformation6 LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this UKCT_MT130101UK03PertinentInformation6 object
/// </summary>
public virtual UKCT_MT130101UK03PertinentInformation6 Clone() {
return ((UKCT_MT130101UK03PertinentInformation6)(this.MemberwiseClone()));
}
#endregion
}
}
| 40.420886 | 1,358 | 0.577155 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V3109/Generated/UKCT_MT130101UK03PertinentInformation6.cs | 12,773 | C# |
#region File Description
//-----------------------------------------------------------------------------
// BloomComponent.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace BloomPostprocess
{
public class BloomComponent : DrawableGameComponent
{
#region Fields
SpriteBatch spriteBatch;
Effect bloomExtractEffect;
Effect bloomCombineEffect;
Effect gaussianBlurEffect;
RenderTarget2D sceneRenderTarget;
RenderTarget2D renderTarget1;
RenderTarget2D renderTarget2;
// Choose what display settings the bloom should use.
public BloomSettings Settings
{
get { return settings; }
set { settings = value; }
}
BloomSettings settings = BloomSettings.PresetSettings[0];
// Optionally displays one of the intermediate buffers used
// by the bloom postprocess, so you can see exactly what is
// being drawn into each rendertarget.
public enum IntermediateBuffer
{
PreBloom,
BlurredHorizontally,
BlurredBothWays,
FinalResult,
}
public IntermediateBuffer ShowBuffer
{
get { return showBuffer; }
set { showBuffer = value; }
}
IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult;
#endregion
#region Initialization
public BloomComponent(Game game)
: base(game)
{
if (game == null)
throw new ArgumentNullException("game");
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
bloomExtractEffect = Game.Content.Load<Effect>("BloomExtract");
bloomCombineEffect = Game.Content.Load<Effect>("BloomCombine");
gaussianBlurEffect = Game.Content.Load<Effect>("GaussianBlur");
// Look up the resolution and format of our main backbuffer.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
int width = pp.BackBufferWidth;
int height = pp.BackBufferHeight;
SurfaceFormat format = pp.BackBufferFormat;
// Create a texture for rendering the main scene, prior to applying bloom.
sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false,
format, pp.DepthStencilFormat, pp.MultiSampleCount,
RenderTargetUsage.DiscardContents);
// Create two rendertargets for the bloom processing. These are half the
// size of the backbuffer, in order to minimize fillrate costs. Reducing
// the resolution in this way doesn't hurt quality, because we are going
// to be blurring the bloom images in any case.
width /= 2;
height /= 2;
renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
sceneRenderTarget.Dispose();
renderTarget1.Dispose();
renderTarget2.Dispose();
}
#endregion
#region Draw
/// <summary>
/// This should be called at the very start of the scene rendering. The bloom
/// component uses it to redirect drawing into its custom rendertarget, so it
/// can capture the scene image in preparation for applying the bloom filter.
/// </summary>
public void BeginDraw()
{
if (Visible)
{
GraphicsDevice.SetRenderTarget(sceneRenderTarget);
}
}
/// <summary>
/// This is where it all happens. Grabs a scene that has already been rendered,
/// and uses postprocess magic to add a glowing bloom effect over the top of it.
/// </summary>
public override void Draw(GameTime gameTime)
{
GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
// Pass 1: draw the scene into rendertarget 1, using a
// shader that extracts only the brightest parts of the image.
bloomExtractEffect.Parameters["BloomThreshold"].SetValue(
Settings.BloomThreshold);
DrawFullscreenQuad(sceneRenderTarget, renderTarget1,
bloomExtractEffect,
IntermediateBuffer.PreBloom);
// Pass 2: draw from rendertarget 1 into rendertarget 2,
// using a shader to apply a horizontal gaussian blur filter.
SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0);
DrawFullscreenQuad(renderTarget1, renderTarget2,
gaussianBlurEffect,
IntermediateBuffer.BlurredHorizontally);
// Pass 3: draw from rendertarget 2 back into rendertarget 1,
// using a shader to apply a vertical gaussian blur filter.
SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height);
DrawFullscreenQuad(renderTarget2, renderTarget1,
gaussianBlurEffect,
IntermediateBuffer.BlurredBothWays);
// Pass 4: draw both rendertarget 1 and the original scene
// image back into the main backbuffer, using a shader that
// combines them to produce the final bloomed result.
GraphicsDevice.SetRenderTarget(null);
EffectParameterCollection parameters = bloomCombineEffect.Parameters;
parameters["BloomIntensity"].SetValue(Settings.BloomIntensity);
parameters["BaseIntensity"].SetValue(Settings.BaseIntensity);
parameters["BloomSaturation"].SetValue(Settings.BloomSaturation);
parameters["BaseSaturation"].SetValue(Settings.BaseSaturation);
GraphicsDevice.Textures[1] = sceneRenderTarget;
Viewport viewport = GraphicsDevice.Viewport;
DrawFullscreenQuad(renderTarget1,
viewport.Width, viewport.Height,
bloomCombineEffect,
IntermediateBuffer.FinalResult);
}
/// <summary>
/// Helper for drawing a texture into a rendertarget, using
/// a custom shader to apply postprocessing effects.
/// </summary>
void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget,
Effect effect, IntermediateBuffer currentBuffer)
{
GraphicsDevice.SetRenderTarget(renderTarget);
DrawFullscreenQuad(texture,
renderTarget.Width, renderTarget.Height,
effect, currentBuffer);
}
/// <summary>
/// Helper for drawing a texture into the current rendertarget,
/// using a custom shader to apply postprocessing effects.
/// </summary>
void DrawFullscreenQuad(Texture2D texture, int width, int height,
Effect effect, IntermediateBuffer currentBuffer)
{
// If the user has selected one of the show intermediate buffer options,
// we still draw the quad to make sure the image will end up on the screen,
// but might need to skip applying the custom pixel shader.
if (showBuffer < currentBuffer)
{
effect = null;
}
spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
spriteBatch.End();
}
/// <summary>
/// Computes sample weightings and texture coordinate offsets
/// for one pass of a separable gaussian blur filter.
/// </summary>
void SetBlurEffectParameters(float dx, float dy)
{
// Look up the sample weight and offset effect parameters.
EffectParameter weightsParameter, offsetsParameter;
weightsParameter = gaussianBlurEffect.Parameters["SampleWeights"];
offsetsParameter = gaussianBlurEffect.Parameters["SampleOffsets"];
// Look up how many samples our gaussian blur effect supports.
int sampleCount = weightsParameter.Elements.Count;
// Create temporary arrays for computing our filter settings.
float[] sampleWeights = new float[sampleCount];
Vector2[] sampleOffsets = new Vector2[sampleCount];
// The first sample always has a zero offset.
sampleWeights[0] = ComputeGaussian(0);
sampleOffsets[0] = new Vector2(0);
// Maintain a sum of all the weighting values.
float totalWeights = sampleWeights[0];
// Add pairs of additional sample taps, positioned
// along a line in both directions from the center.
for (int i = 0; i < sampleCount / 2; i++)
{
// Store weights for the positive and negative taps.
float weight = ComputeGaussian(i + 1);
sampleWeights[i * 2 + 1] = weight;
sampleWeights[i * 2 + 2] = weight;
totalWeights += weight * 2;
// To get the maximum amount of blurring from a limited number of
// pixel shader samples, we take advantage of the bilinear filtering
// hardware inside the texture fetch unit. If we position our texture
// coordinates exactly halfway between two texels, the filtering unit
// will average them for us, giving two samples for the price of one.
// This allows us to step in units of two texels per sample, rather
// than just one at a time. The 1.5 offset kicks things off by
// positioning us nicely in between two texels.
float sampleOffset = i * 2 + 1.5f;
Vector2 delta = new Vector2(dx, dy) * sampleOffset;
// Store texture coordinate offsets for the positive and negative taps.
sampleOffsets[i * 2 + 1] = delta;
sampleOffsets[i * 2 + 2] = -delta;
}
// Normalize the list of sample weightings, so they will always sum to one.
for (int i = 0; i < sampleWeights.Length; i++)
{
sampleWeights[i] /= totalWeights;
}
// Tell the effect about our new filter settings.
weightsParameter.SetValue(sampleWeights);
offsetsParameter.SetValue(sampleOffsets);
}
/// <summary>
/// Evaluates a single point on the gaussian falloff curve.
/// Used for setting up the blur filter weightings.
/// </summary>
float ComputeGaussian(float n)
{
float theta = Settings.BlurAmount;
return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) *
Math.Exp(-(n * n) / (2 * theta * theta)));
}
#endregion
}
}
| 37.584906 | 111 | 0.583584 | [
"MIT"
] | SimonDarksideJ/XNAGameStudio | Samples/BloomSample_4_0/BloomPostprocess/BloomComponent.cs | 11,952 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using SadConsole.Input;
using Server;
using Server.Data;
using Server.Logic;
using C = System.Console;
namespace Client
{
public static partial class Consoles
{
public class Gameplay : SadConsole.Console, IResizeHandler
{
private readonly Consoles.DebugStats debugStats;
private readonly Consoles.TileMap tilemap;
private readonly Consoles.MessageLog messageLogConsole;
private readonly Consoles.MiniMap minimap;
public IClientContext ClientContext { get; }
public GameServer Server { get; }
public Choreographer<MapActor> Choreographer { get; } = new Choreographer<MapActor>();
public Util.CoroutineContainer Coroutines { get; } = new Util.CoroutineContainer();
public SadRogue.Primitives.Point MapTileSize => tilemap.TileSize;
public ActorSet MapActors { get; } = new ActorSet();
public GameMessageLog MessageLog { get; } = new GameMessageLog();
public bool ShouldReturnToTitle { get; private set; } = false;
private MapActor? CurrentPC => waitingActor.HasValue ? MapActors.Lookup(waitingActor.Value) : null;
private readonly GameplayMessageHandler msgHandler;
// The last valid key state. Consumed on use.
private SadConsole.Input.Keyboard? keyState = null;
// The actor the server is waiting on, if one exists.
private DataHandle<Actor>? waitingActor;
private MapActor? fallbackCameraFocusActor;
protected override void Dispose(bool disposing)
{
minimap.Dispose();
base.Dispose(disposing);
}
public Gameplay(IClientContext ctx, GameServer s) : base(1, 1)
{
ClientContext = ctx;
Server = s;
msgHandler = new GameplayMessageHandler(this);
tilemap = new TileMap(this);
messageLogConsole = new MessageLog(this, MessageLog);
minimap = new MiniMap(this);
debugStats = new DebugStats(this);
Coroutines.Add(SimulationLoop(false));
MapActors.OnAddActor += (a) =>
{
tilemap.EntityLayer.Children.Add(a);
};
MapActors.OnRemoveActor += (a) =>
{
if (fallbackCameraFocusActor == a)
fallbackCameraFocusActor = null;
tilemap.EntityLayer.Children.Remove(a);
};
Choreographer.OnMotionCompletion += UpdateActorsOnMinimap;
HandleMessages(Server.GetClientInitMessages());
OnWindowResize(SadConsole.Settings.Rendering.RenderWidth, SadConsole.Settings.Rendering.RenderHeight);
}
public void HandleMessages(IEnumerable<IGameMessage> messages)
{
foreach (var msg in messages)
msg.Dispatch(msgHandler);
}
private void ProcessSimulationResult(SimResult result)
{
if (result.Error != null)
C.WriteLine(result.Error.Message);
else
HandleMessages(result.Messages);
waitingActor = result.WaitingActor;
}
private static SimResult TimedRunSimulation(GameServer server,
IAction? nextAction,
Consoles.DebugStats? debugStats = null)
{
var updateTimer = Stopwatch.StartNew();
var result = server.Run(nextAction, 64);
if (debugStats != null)
debugStats.LastSimulationTime = updateTimer.ElapsedMilliseconds;
return result;
}
private IEnumerable SimulationLoop(bool async)
{
while (true)
{
IAction? userAction = null;
if (!Choreographer.IsBusy && keyState != null)
{
userAction = TrySelectAction(keyState, CurrentPC, MapActors);
keyState = null;
}
var simTask = Task.Run(() => TimedRunSimulation(Server, userAction, debugStats));
// TODO: async could work via two-bit prediction or something.
// if the last few significant updates have been >16ms,
// switch to async? or the other way around, keep a running
// average of the update delta, and if it's around
// <8ms, Sleep for 4ms to give the task time to complete?
// As written here, async incurs 1 frame of latency, which will
// cause slight but noticeable hitching when the player holds
// down a movement key! It does work, however, so with some
// clever prediction this could help with long updates.
if (async)
yield return simTask;
ProcessSimulationResult(simTask.Result);
yield return null;
}
}
public override void Update(TimeSpan timeElapsed)
{
debugStats.UpdateDelta = timeElapsed.Milliseconds;
Coroutines.Update();
base.Update(timeElapsed);
}
private static bool ManualFacing(SadConsole.Input.Keyboard keyboard)
=> keyboard.IsKeyDown(Keys.LeftControl) || keyboard.IsKeyDown(Keys.RightControl);
/// <summary>
/// Attempts to parse the user's input into a valid game action for the
/// given actor.
///
/// If the given actor is null or the player's input does not correspond
/// to any game action, returns null.
/// </summary>
private static IAction? TrySelectAction(SadConsole.Input.Keyboard info, MapActor? pc, ActorSet actors)
{
if (info.IsKeyPressed(Keys.Z))
{
return new Actions.TryAttack();
}
if (info.IsKeyPressed(Keys.Space))
{
return new Actions.Idle();
}
int dx = 0, dy = 0;
if (info.IsKeyDown(Keys.Left)) dx -= 1;
if (info.IsKeyDown(Keys.Right)) dx += 1;
if (info.IsKeyDown(Keys.Up)) dy -= 1;
if (info.IsKeyDown(Keys.Down)) dy += 1;
if (dx != 0 || dy != 0)
{
if (ManualFacing(info))
return new Actions.Face((dx, dy).ToClosestDirection());
else
return new Actions.Move(dx, dy);
}
return null;
}
private void CheckNonGameplayHotkeys(SadConsole.Input.Keyboard info)
{
if (info.IsKeyPressed(Keys.F1))
debugStats.IsVisible = !debugStats.IsVisible;
if (info.IsKeyPressed(Keys.Escape))
ShouldReturnToTitle = true;
if (info.IsKeyPressed(Keys.L))
messageLogConsole.ToggleVisible();
if (info.IsKeyPressed(Keys.F5))
{
string save = Server.ToSaveGame();
System.IO.Directory.CreateDirectory("Saves");
System.IO.File.WriteAllText("Saves/save.sav", save);
}
}
public void SetShowGrid(bool value)
{
foreach (var actor in MapActors.Actors)
actor.ShowFacingMarker = value;
tilemap.IsGridVisible = value;
}
public override bool ProcessKeyboard(SadConsole.Input.Keyboard info)
{
CheckNonGameplayHotkeys(info);
keyState = info;
SetShowGrid(ManualFacing(info));
return false;
}
public override void Render(TimeSpan timeElapsed)
{
debugStats.RenderDelta = timeElapsed.Milliseconds;
foreach (var actor in MapActors.Actors)
{
// Actors have their position offsets reset each frame to allow
// multiple motions to sum their individual offsets.
actor.PositionOffset = default;
}
Choreographer.Update(timeElapsed);
// capture the first player-controlled actor as a fallback
// in the event that we don't have a waitingActor to use as a
// camera target (most of the time these'll be the same)
fallbackCameraFocusActor ??=
waitingActor.HasValue ?
MapActors[waitingActor.Value] :
null;
// prioritize focusing the camera on the waiting actor over the fallback
var cameraFocus =
waitingActor.HasValue ?
MapActors[waitingActor.Value] :
fallbackCameraFocusActor;
if (cameraFocus != null)
tilemap.CenterViewOn(cameraFocus);
base.Render(timeElapsed);
}
public void OnWindowResize(int width, int height)
{
tilemap.ResizeViewportPx(width, height);
messageLogConsole.Reposition(width, height, MessageLog);
minimap.Reposition(width, height);
}
public void UpdateMapTerrain(Server.Data.TileMap terrainData)
{
tilemap.RebuildTileMap(terrainData);
minimap.RebuildTerrain(terrainData);
}
public void UpdateActorsOnMinimap()
{
minimap.RebuildLocalActorDisplay(MapActors.Actors, tilemap.TileSize);
}
}
}
} | 37.676157 | 118 | 0.520166 | [
"MIT"
] | jalbert-dev/mystower | Client/Consoles/Gameplay.cs | 10,587 | C# |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using NUnit.Framework;
namespace EventStore.Projections.Core.Tests.ClientAPI.when_handling_deleted.with_from_all_foreach_projection
{
[TestFixture]
public class when_running_and_no_indexing : specification_with_standard_projections_runnning
{
protected override bool GivenStandardProjectionsRunning()
{
return false;
}
protected override void Given()
{
base.Given();
PostEvent("stream-1", "type1", "{}");
PostEvent("stream-1", "type2", "{}");
PostEvent("stream-2", "type1", "{}");
PostEvent("stream-2", "type2", "{}");
WaitIdle();
PostProjection(@"
fromAll().foreachStream().when({
$init: function(){return {}},
type1: function(s,e){s.a=1},
type2: function(s,e){s.a=1},
$deleted: function(s,e){s.deleted=1;},
}).outputState();
");
}
protected override void When()
{
base.When();
this.HardDeleteStream("stream-1");
WaitIdle();
}
[Test, Category("Network")]
public void receives_deleted_notification()
{
AssertStreamTail(
"$projections-test-projection-stream-1-result", "Result:{\"a\":1}", "Result:{\"a\":1,\"deleted\":1}");
}
}
}
| 38.986486 | 118 | 0.67591 | [
"BSD-3-Clause"
] | ianbattersby/EventStore | src/EventStore/EventStore.Projections.Core.Tests/ClientAPI/when_handling_deleted/with_from_all_foreach_projection/when_running_and_no_indexing.cs | 2,887 | C# |
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mailjet.Client;
using Mailjet.Client.Resources;
using Mailjet.Client.TransactionalEmails;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
namespace Mailjet.Tests.Integration
{
[TestClass]
public class SendTransactionalEmailIntegrationTests
{
private MailjetClient _client;
private string _senderEmail;
[TestInitialize]
public async Task TestInitialize()
{
_client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"),
Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
_senderEmail = await GetValidSenderEmail(_client);
}
[TestMethod]
public async Task SendTransactionalEmailAsync_SendsEmail()
{
// arrange
var email = new TransactionalEmailBuilder()
.WithFrom(new SendContact(_senderEmail))
.WithSubject("Test subject")
.WithHtmlPart("<h1>Header</h1>")
.WithTo(new SendContact(_senderEmail))
.Build();
// act
var response = await _client.SendTransactionalEmailAsync(email);
// assert
Assert.AreEqual(1, response.Messages.Length);
var message = response.Messages[0];
Assert.AreEqual("success", message.Status);
Assert.AreEqual(_senderEmail, message.To.Single().Email);
}
[TestMethod]
public async Task SendTransactionalEmailAsync_WithCustomHeaders_SendsEmail()
{
// arrange
var base64Content = Convert.ToBase64String(Encoding.UTF8.GetBytes("Test file content"));
var attachment = new Attachment("test1.txt", "text/plain", base64Content);
var email = new TransactionalEmailBuilder()
.WithFrom(new SendContact(_senderEmail))
.WithSubject("Test subject")
.WithHtmlPart("<h1>Header</h1>")
.WithHeader("header1", "value1")
.WithHeader("header2", "value2")
.WithAttachment(attachment)
.WithCustomId("customIdValue")
.WithTo(new SendContact(_senderEmail))
.Build();
// act
var response = await _client.SendTransactionalEmailAsync(email);
// assert
Assert.AreEqual(1, response.Messages.Length);
var message = response.Messages[0];
Assert.AreEqual("success", message.Status);
Assert.AreEqual("customIdValue", message.CustomID);
Assert.AreEqual(_senderEmail, message.To.Single().Email);
}
[TestMethod]
public async Task SendTransactionalEmailAsync_TemplateIsMissing_ReturnsError()
{
// arrange
long nonExistentTemplateId = 12345;
var email = new TransactionalEmailBuilder()
.WithFrom(new SendContact(_senderEmail))
.WithSubject("Test subject")
.WithTemplateId(nonExistentTemplateId)
.WithTrackOpens(TrackOpens.enabled)
.WithTo(new SendContact(_senderEmail))
.Build();
// act
var response = await _client.SendTransactionalEmailAsync(email);
// assert
Assert.AreEqual(1, response.Messages.Length);
var message = response.Messages[0];
Assert.AreEqual("error", message.Status);
Assert.AreEqual(1, message.Errors.Count);
var error = message.Errors.Single();
Assert.AreEqual(400, error.StatusCode);
Assert.AreEqual("Template id \"12345\" doesn't exist for your account.", error.ErrorMessage);
Assert.AreEqual("send-0010", error.ErrorCode);
Assert.AreEqual("TemplateID", error.ErrorRelatedTo.Single());
}
public static async Task<string> GetValidSenderEmail(MailjetClient client)
{
MailjetRequest request = new MailjetRequest
{
Resource = Sender.Resource
};
MailjetResponse response = await client.GetAsync(request);
Assert.AreEqual(200, response.StatusCode);
foreach (var emailObject in response.GetData())
{
if (emailObject.Type != JTokenType.Object)
continue;
if (emailObject.Value<string>("Status") == "Active")
return emailObject.Value<string>("Email");
}
Assert.Fail("Cannot find Active sender address under given account");
throw new AssertFailedException();
}
}
}
| 35.644444 | 105 | 0.597049 | [
"MIT"
] | Samy-Farnaud/mailjet-apiv3-dotnet | Mailjet.Tests/Integration/SendTransactionalEmailIntegrationTests.cs | 4,814 | C# |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.IO;
namespace Org.Apache.REEF.Client.API.Exceptions
{
/// <summary>
/// Thrown when the java installation cannot be found on the client.
/// </summary>
public sealed class JavaNotFoundException : FileNotFoundException
{
public JavaNotFoundException(string message) : base(message)
{
}
public JavaNotFoundException(string message, string fileName) : base(message, fileName)
{
}
}
} | 35.513514 | 96 | 0.693303 | [
"Apache-2.0"
] | Gyeongin/incubator-reef | lang/cs/Org.Apache.REEF.Client/API/Exceptions/JavaNotFoundException.cs | 1,280 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using LastSeen.Core.Infrastructure.Deserialization;
using LastSeen.Core.POs;
namespace LastSeen.Core.Sevices.Implementations
{
public class LastSeenService : ILastSeenService
{
private const string DataFile = "LastSeen.data";
private List<LastSeenItem> _lastSeenItems;
private List<string> _sections;
private readonly IDataStorage _dataStorage;
public LastSeenService(IDataStorage dataStorage)
{
_dataStorage = dataStorage;
}
public Dictionary<string, List<ItemPO>> GetItems()
{
EnsureLoaded();
var sectionDictionary = new Dictionary<string, List<ItemPO>>();
_sections = _lastSeenItems.Select(e => e.Tag).Distinct().ToList();
foreach (var section in _sections)
{
var items = _lastSeenItems.Where(e => e.Tag == section);
sectionDictionary.Add(section, items.Select(Mapper.Map<ItemPO>).ToList());
}
return sectionDictionary;
}
public ItemPO GetItem(string id)
{
EnsureLoaded();
return Mapper.Map<ItemPO>(_lastSeenItems.FirstOrDefault(e => e.Id == id));
}
public void SaveItem(ItemPO itemPo)
{
EnsureLoaded();
var newItem = Mapper.Map<LastSeenItem>(itemPo);
var oldItem = _lastSeenItems.FirstOrDefault(e => e.Id == newItem.Id);
var index = _lastSeenItems.IndexOf(oldItem);
if (index != -1)
_lastSeenItems[index] = newItem;
else
{
_lastSeenItems.Add(newItem);
}
SaveAllItems();
}
public void DeleteItem(ItemPO itemPo)
{
EnsureLoaded();
var item = _lastSeenItems.FirstOrDefault(e => e.Id == itemPo.Id);
_lastSeenItems.Remove(item);
SaveAllItems();
}
private void SaveAllItems()
{
_dataStorage.Write(DataFile, _lastSeenItems);
}
private void EnsureLoaded()
{
if (_lastSeenItems != null)
return;
_lastSeenItems = _dataStorage.Read<List<LastSeenItem>>(DataFile);
if (_lastSeenItems == null)
{
_lastSeenItems = new List<LastSeenItem>
{
new LastSeenItem(true),
};
}
}
}
}
| 22.898876 | 78 | 0.698724 | [
"MIT"
] | spanishprisoner/lastseen | src/LastSeen.Core/Sevices/Implementations/LastSeenService.cs | 2,040 | C# |
using System.Collections.Generic;
using System.Linq;
using System;
namespace TravelWithUsService.DBContext.Repositories
{
public class OfertaParaReserva
{
public string Descripcion { get; private set; }
public int OfertaID { get; private set; }
public int HotelID { get; private set; }
public string HotelNombre { get; set; }
public decimal Price { get; set; }
public OfertaParaReserva(string descripcion, int ofertaId, int hotelId, string nombreh, decimal price)
{
this.Descripcion = descripcion;
this.OfertaID = ofertaId;
this.HotelID = hotelId;
this.HotelNombre = nombreh;
this.Price = price;
}
}
public class TuristaParaReserva
{
public int TuristaID { get; private set; }
public string Nombre { get; private set; }
public TuristaParaReserva(int turistaId, string nombre)
{
this.TuristaID = turistaId;
this.Nombre = nombre;
}
}
public class AgenciaParaReserva
{
public int AgenciaID { get; private set; }
public string Nombre { get; private set; }
public AgenciaParaReserva(int agenciaId, string nombre)
{
this.AgenciaID = agenciaId;
this.Nombre = nombre;
}
}
public class ReservaIndividualOpciones
{
public List<OfertaParaReserva> Ofertas { get; private set; }
public List<TuristaParaReserva> Turistas { get; private set; }
public List<AgenciaParaReserva> Agencias { get; private set; }
public ReservaIndividualOpciones(IEnumerable<OfertaParaReserva> ofertas, IEnumerable<TuristaParaReserva> turistas, IEnumerable<AgenciaParaReserva> agencias)
{
this.Ofertas = new List<OfertaParaReserva>(ofertas);
this.Turistas = new List<TuristaParaReserva>(turistas);
this.Agencias = new List<AgenciaParaReserva>(agencias);
}
}
}
| 30.119403 | 164 | 0.630823 | [
"MIT"
] | Equipo12-SBDII/TravelWithUs | TravelWithUsService/TravelWithUsContextLib/Repositories/AuxiliarClasses/ReservaIndividualOpciones.cs | 2,018 | C# |
using Albatross.Expression;
using Albatross.Expression.Tokens;
using DnDGen.RollGen.Expressions;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace DnDGen.RollGen.Tests.Unit.Expressions
{
[TestFixture]
public class AlbatrossExpressionEvaluatorTests
{
private const string Expression = "expression";
private ExpressionEvaluator expressionEvaluator;
private Mock<IParser> mockParser;
[SetUp]
public void Setup()
{
mockParser = new Mock<IParser>();
expressionEvaluator = new AlbatrossExpressionEvaluator(mockParser.Object);
SetUpExpression(Expression, 9266);
}
private void SetUpExpression(string expression, object result)
{
var mockToken = new Mock<IToken>();
var queue = new Queue<IToken>();
var stack = new Stack<IToken>();
mockParser.Setup(p => p.Tokenize(expression)).Returns(queue);
mockParser.Setup(p => p.BuildStack(queue)).Returns(stack);
mockParser.Setup(p => p.CreateTree(stack)).Returns(mockToken.Object);
mockToken.Setup(t => t.EvalValue(null)).Returns(result);
}
[Test]
public void EvaluateExpression()
{
var result = expressionEvaluator.Evaluate<int>(Expression);
Assert.That(result, Is.EqualTo(9266));
}
[Test]
public void EvaluateMultipleExpressions()
{
var result = expressionEvaluator.Evaluate<int>(Expression);
Assert.That(result, Is.EqualTo(9266));
SetUpExpression("other expression", 902.1);
result = expressionEvaluator.Evaluate<int>("other expression");
Assert.That(result, Is.EqualTo(902));
}
[Test]
public void EvaluateDouble()
{
SetUpExpression("other expression", 902.1);
var result = expressionEvaluator.Evaluate<double>("other expression");
Assert.That(result, Is.EqualTo(902.1));
}
[Test]
public void IfDieRollIsInExpression_ThrowArgumentException()
{
Assert.That(() => expressionEvaluator.Evaluate<int>("expression with 3 d 4+2"), Throws.ArgumentException.With.Message.EqualTo("Cannot evaluate unrolled die roll 3 d 4"));
}
[Test]
public void EvaluateTrueBooleanExpression()
{
SetUpExpression("boolean expression", bool.TrueString);
var result = expressionEvaluator.Evaluate<bool>("boolean expression");
Assert.That(result, Is.True);
}
[Test]
public void EvaluateFalseBooleanExpression()
{
SetUpExpression("boolean expression", bool.FalseString);
var result = expressionEvaluator.Evaluate<bool>("boolean expression");
Assert.That(result, Is.False);
}
[Test]
public void EvaluateExpressionThrowsException_WhenAlbatrossFailsToEvaluate()
{
var expression = "wrong expression";
var mockToken = new Mock<IToken>();
var queue = new Queue<IToken>();
var stack = new Stack<IToken>();
mockParser.Setup(p => p.Tokenize(expression)).Returns(queue);
mockParser.Setup(p => p.BuildStack(queue)).Returns(stack);
mockParser.Setup(p => p.CreateTree(stack)).Returns(mockToken.Object);
var exception = new Exception("I failed");
mockToken.Setup(t => t.EvalValue(null)).Throws(exception);
Assert.That(() => expressionEvaluator.Evaluate<int>(expression),
Throws.InvalidOperationException
.With.Message.EqualTo($"Expression 'wrong expression' is invalid")
.And.InnerException.EqualTo(exception));
}
}
}
| 33.517241 | 182 | 0.613683 | [
"MIT"
] | DnDGen/RollGen | DnDGen.RollGen.Tests.Unit/Expressions/AlbatrossExpressionEvaluatorTests.cs | 3,890 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace UnitCost.Dto.Catalalogs
{
public class UserDto
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Psswrd { get; set; }
public DateTime? Birthdate { get; set; }
}
}
| 23.823529 | 48 | 0.614815 | [
"MIT"
] | soyCardiel/UniCostApiNetCore | UnitCost.Api/UnitCost.Dto/Catalalogs/UserDto.cs | 407 | 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.IO;
using System.IO.Compression;
using System.Reflection;
using Microsoft.ML.Internal.Utilities;
namespace Microsoft.ML.Runtime
{
[Obsolete("The usage for this is intended for the internal command line utilities and is not intended for anything related to the API. " +
"Please consider another way of doing whatever it is you're attempting to accomplish.")]
[BestFriend]
internal static class AssemblyLoadingUtils
{
/// <summary>
/// Make sure the given assemblies are loaded and that their loadable classes have been catalogued.
/// </summary>
public static void LoadAndRegister(IHostEnvironment env, string[] assemblies)
{
Contracts.AssertValue(env);
if (Utils.Size(assemblies) > 0)
{
foreach (string path in assemblies)
{
Exception ex = null;
try
{
// REVIEW: Will LoadFrom ever return null?
Contracts.CheckNonEmpty(path, nameof(path));
var assem = LoadAssembly(env, path);
if (assem != null)
continue;
}
catch (Exception e)
{
ex = e;
}
// If it is a zip file, load it that way.
ZipArchive zip;
try
{
zip = ZipFile.OpenRead(path);
}
catch (Exception e)
{
// Couldn't load as an assembly and not a zip, so warn the user.
ex = ex ?? e;
Console.Error.WriteLine("Warning: Could not load '{0}': {1}", path, ex.Message);
continue;
}
string dir;
try
{
dir = CreateTempDirectory();
}
catch (Exception e)
{
throw Contracts.ExceptIO(e, "Creating temp directory for extra assembly zip extraction failed: '{0}'", path);
}
try
{
zip.ExtractToDirectory(dir);
}
catch (Exception e)
{
throw Contracts.ExceptIO(e, "Extracting extra assembly zip failed: '{0}'", path);
}
LoadAssembliesInDir(env, dir, false);
}
}
}
public static IDisposable CreateAssemblyRegistrar(IHostEnvironment env, string loadAssembliesPath = null)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValueOrNull(loadAssembliesPath);
return new AssemblyRegistrar(env, loadAssembliesPath);
}
public static void RegisterCurrentLoadedAssemblies(IHostEnvironment env)
{
Contracts.CheckValue(env, nameof(env));
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
TryRegisterAssembly(env.ComponentCatalog, a);
}
}
private static string CreateTempDirectory()
{
string dir = GetTempPath();
Directory.CreateDirectory(dir);
return dir;
}
private static string GetTempPath()
{
Guid guid = Guid.NewGuid();
return Path.GetFullPath(Path.Combine(Path.GetTempPath(), "MLNET_" + guid.ToString()));
}
private static readonly string[] _filePrefixesToAvoid = new string[] {
"api-ms-win",
"clr",
"coreclr",
"dbgshim",
"ext-ms-win",
"microsoft.bond.",
"microsoft.cosmos.",
"microsoft.csharp",
"microsoft.data.",
"microsoft.hpc.",
"microsoft.live.",
"microsoft.platformbuilder.",
"microsoft.visualbasic",
"microsoft.visualstudio.",
"microsoft.win32",
"microsoft.windowsapicodepack.",
"microsoft.windowsazure.",
"mscor",
"msvc",
"petzold.",
"roslyn.",
"sho",
"sni",
"sqm",
"system.",
"zlib",
};
private static bool ShouldSkipPath(string path)
{
string name = Path.GetFileName(path).ToLowerInvariant();
switch (name)
{
case "cpumathnative.dll":
case "cqo.dll":
case "fasttreenative.dll":
case "libiomp5md.dll":
case "ldanative.dll":
case "libvw.dll":
case "matrixinterf.dll":
case "microsoft.ml.neuralnetworks.gpucuda.dll":
case "mklimports.dll":
case "microsoft.research.controls.decisiontrees.dll":
case "microsoft.ml.neuralnetworks.sse.dll":
case "mklproxynative.dll":
case "neuraltreeevaluator.dll":
case "optimizationbuilderdotnet.dll":
case "parallelcommunicator.dll":
case "Microsoft.ML.runtests.dll":
case "scopecompiler.dll":
case "symsgdnative.dll":
case "tbb.dll":
case "internallearnscope.dll":
case "unmanagedlib.dll":
case "vcclient.dll":
case "libxgboost.dll":
case "zedgraph.dll":
case "__scopecodegen__.dll":
case "cosmosClientApi.dll":
return true;
}
foreach (var s in _filePrefixesToAvoid)
{
if (name.StartsWith(s, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
private static void LoadAssembliesInDir(IHostEnvironment env, string dir, bool filter)
{
if (!Directory.Exists(dir))
return;
// Load all dlls in the given directory.
var paths = Directory.EnumerateFiles(dir, "*.dll");
foreach (string path in paths)
{
if (filter && ShouldSkipPath(path))
{
continue;
}
LoadAssembly(env, path);
}
}
/// <summary>
/// Given an assembly path, load the assembly and register it with the ComponentCatalog.
/// </summary>
private static Assembly LoadAssembly(IHostEnvironment env, string path)
{
Assembly assembly = null;
try
{
assembly = Assembly.LoadFrom(path);
}
catch (Exception)
{
return null;
}
if (assembly != null)
{
TryRegisterAssembly(env.ComponentCatalog, assembly);
}
return assembly;
}
/// <summary>
/// Checks whether <paramref name="assembly"/> references the assembly containing LoadableClassAttributeBase,
/// and therefore can contain components.
/// </summary>
private static bool CanContainComponents(Assembly assembly)
{
var targetFullName = typeof(LoadableClassAttributeBase).Assembly.GetName().FullName;
bool found = false;
foreach (var name in assembly.GetReferencedAssemblies())
{
if (name.FullName == targetFullName)
{
found = true;
break;
}
}
return found;
}
private static void TryRegisterAssembly(ComponentCatalog catalog, Assembly assembly)
{
// Don't try to index dynamic generated assembly
if (assembly.IsDynamic)
return;
if (!CanContainComponents(assembly))
return;
catalog.RegisterAssembly(assembly);
}
private sealed class AssemblyRegistrar : IDisposable
{
private readonly IHostEnvironment _env;
public AssemblyRegistrar(IHostEnvironment env, string path)
{
_env = env;
RegisterCurrentLoadedAssemblies(_env);
if (!string.IsNullOrEmpty(path))
{
LoadAssembliesInDir(_env, path, true);
path = Path.Combine(path, "AutoLoad");
LoadAssembliesInDir(_env, path, true);
}
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomainAssemblyLoad;
}
public void Dispose()
{
AppDomain.CurrentDomain.AssemblyLoad -= CurrentDomainAssemblyLoad;
}
private void CurrentDomainAssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
TryRegisterAssembly(_env.ComponentCatalog, args.LoadedAssembly);
}
}
}
}
| 33.189655 | 142 | 0.493506 | [
"MIT"
] | AhmedsafwatEwida/machinelearning | src/Microsoft.ML.Core/ComponentModel/AssemblyLoadingUtils.cs | 9,625 | C# |
using Abp.AutoMapper;
using TestApp.Todo_list;
namespace TestApp.Todolist
{
[AutoMapTo(typeof(TodoList))]
public class GetTodoListInput
{
public int Id { get; set; }
}
} | 17.727273 | 35 | 0.666667 | [
"MIT"
] | hasan-ak1996/boilerplate | aspnet-core/src/TestApp.Application/Todolist/Dto/GetTodoListInput.cs | 197 | 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 SR = Bb.Sdk.Resources.Strings;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
namespace Microsoft.CSharp
{
internal sealed partial class CSharpCodeGenerator : /*ICodeCompiler,*/ ICodeGenerator
{
internal CSharpCodeGenerator() { }
internal CSharpCodeGenerator(IDictionary<string, string> providerOptions)
{
_provOptions = providerOptions;
}
private bool _generatingForLoop = false;
private string FileExtension { get { return ".cs"; } }
private string CurrentTypeName => _currentClass != null ? _currentClass.Name : "<% unknown %>";
private int Indent
{
get { return _output.Indent; }
set { _output.Indent = value; }
}
private bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false;
private bool IsCurrentClass => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false;
private bool IsCurrentStruct => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false;
private bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false;
private bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate;
private string NullToken => "null";
private CodeGeneratorOptions Options => _options;
private TextWriter Output => _output;
private string QuoteSnippetStringCStyle(string value)
{
var b = new StringBuilder(value.Length + 5);
var indentObj = new Indentation(_output, Indent + 1);
b.Append('\"');
int i = 0;
while (i < value.Length)
{
switch (value[i])
{
case '\r':
b.Append("\\r");
break;
case '\t':
b.Append("\\t");
break;
case '\"':
b.Append("\\\"");
break;
case '\'':
b.Append("\\\'");
break;
case '\\':
b.Append("\\\\");
break;
case '\0':
b.Append("\\0");
break;
case '\n':
b.Append("\\n");
break;
case '\u2028':
case '\u2029':
AppendEscapedChar(b, value[i]);
break;
default:
b.Append(value[i]);
break;
}
if (i > 0 && i % MaxLineLength == 0)
{
//
// If current character is a high surrogate and the following
// character is a low surrogate, don't break them.
// Otherwise when we write the string to a file, we might lose
// the characters.
//
if (char.IsHighSurrogate(value[i]) && (i < value.Length - 1) && char.IsLowSurrogate(value[i + 1]))
{
b.Append(value[++i]);
}
b.Append("\" +");
b.Append(Environment.NewLine);
b.Append(indentObj.IndentationString);
b.Append('\"');
}
++i;
}
b.Append('\"');
return b.ToString();
}
private string QuoteSnippetStringVerbatimStyle(string value)
{
var b = new StringBuilder(value.Length + 5);
b.Append("@\"");
for (int i = 0; i < value.Length; i++)
{
if (value[i] == '\"')
b.Append("\"\"");
else
b.Append(value[i]);
}
b.Append('\"');
return b.ToString();
}
private string QuoteSnippetString(string value)
{
// If the string is short, use C style quoting (e.g "\r\n")
// Also do it if it is too long to fit in one line
// If the string contains '\0', verbatim style won't work.
if (value.Length < 256 || value.Length > 1500 || (value.IndexOf('\0') != -1))
return QuoteSnippetStringCStyle(value);
// Otherwise, use 'verbatim' style quoting (e.g. @"foo")
return QuoteSnippetStringVerbatimStyle(value);
}
private void ContinueOnNewLine(string st) => Output.WriteLine(st);
private void OutputIdentifier(string ident) => Output.Write(CreateEscapedIdentifier(ident));
private void OutputType(CodeTypeReference typeRef) => Output.Write(GetTypeOutput(typeRef));
private void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
{
Output.Write("new ");
CodeExpressionCollection init = e.Initializers;
if (init.Count > 0)
{
OutputType(e.CreateType);
if (e.CreateType.ArrayRank == 0)
{
// Unfortunately, many clients are already calling this without array
// types. This will allow new clients to correctly use the array type and
// not break existing clients. For VNext, stop doing this.
Output.Write("[]");
}
Output.WriteLine(" {");
Indent++;
OutputExpressionList(init, newlineBetweenItems: true);
Indent--;
Output.Write('}');
}
else
{
Output.Write(GetBaseTypeOutput(e.CreateType));
Output.Write('[');
if (e.SizeExpression != null)
{
GenerateExpression(e.SizeExpression);
}
else
{
Output.Write(e.Size);
}
Output.Write(']');
int nestedArrayDepth = e.CreateType.NestedArrayDepth;
for (int i = 0; i < nestedArrayDepth - 1; i++)
{
Output.Write("[]");
}
}
}
private void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e) => Output.Write("base");
private void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e)
{
bool indentedExpression = false;
Output.Write('(');
GenerateExpression(e.Left);
Output.Write(' ');
if (e.Left is CodeBinaryOperatorExpression || e.Right is CodeBinaryOperatorExpression)
{
// In case the line gets too long with nested binary operators, we need to output them on
// different lines. However we want to indent them to maintain readability, but this needs
// to be done only once;
if (!_inNestedBinary)
{
indentedExpression = true;
_inNestedBinary = true;
Indent += 3;
}
// ContinueOnNewLine("");
}
OutputOperator(e.Operator);
Output.Write(' ');
GenerateExpression(e.Right);
Output.Write(')');
if (indentedExpression)
{
Indent -= 3;
_inNestedBinary = false;
}
}
private void GenerateCastExpression(CodeCastExpression e)
{
Output.Write("((");
OutputType(e.TargetType);
Output.Write(")(");
GenerateExpression(e.Expression);
Output.Write("))");
}
public void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options)
{
if (_output != null)
throw new InvalidOperationException(SR.CodeGenReentrance);
_options = options ?? new CodeGeneratorOptions();
_output = new ExposedTabStringIndentedTextWriter(writer, _options.IndentString);
try
{
CodeTypeDeclaration dummyClass = new CodeTypeDeclaration(member.Location.Offset);
_currentClass = dummyClass;
GenerateTypeMember(member, dummyClass);
}
finally
{
_currentClass = null;
_output = null;
_options = null;
}
}
private void GenerateDefaultValueExpression(CodeDefaultValueExpression e)
{
Output.Write("default(");
OutputType(e.Type);
Output.Write(')');
}
private void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e)
{
Output.Write("new ");
OutputType(e.DelegateType);
Output.Write('(');
GenerateExpression(e.TargetObject);
Output.Write('.');
OutputIdentifier(e.MethodName);
Output.Write(')');
}
private void GenerateEvents(CodeTypeDeclaration e)
{
foreach (CodeTypeMember current in e.Members)
{
if (current is CodeMemberEvent)
{
_currentMember = current;
if (_options.BlankLinesBetweenMembers)
Output.WriteLine();
CodeMemberEvent imp = (CodeMemberEvent)current;
GenerateEvent(imp, e);
}
}
}
private void GenerateFields(CodeTypeDeclaration e)
{
foreach (CodeTypeMember current in e.Members)
{
if (current is CodeMemberField)
{
_currentMember = current;
if (_options.BlankLinesBetweenMembers)
Output.WriteLine();
CodeMemberField imp = (CodeMemberField)current;
GenerateField(imp);
}
}
}
private void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write('.');
}
OutputIdentifier(e.FieldName);
}
private void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e) =>
OutputIdentifier(e.ParameterName);
private void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e) =>
OutputIdentifier(e.VariableName);
private void GenerateIndexerExpression(CodeIndexerExpression e)
{
GenerateExpression(e.TargetObject);
Output.Write('[');
bool first = true;
foreach (CodeExpression exp in e.Indices)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
GenerateExpression(exp);
}
Output.Write(']');
}
private void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
{
GenerateExpression(e.TargetObject);
Output.Write('[');
bool first = true;
foreach (CodeExpression exp in e.Indices)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
GenerateExpression(exp);
}
Output.Write(']');
}
private void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e)
{
GenerateMethodReferenceExpression(e.Method);
Output.Write('(');
OutputExpressionList(e.Parameters);
Output.Write(')');
}
private void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e)
{
if (e.TargetObject != null)
{
if (e.TargetObject is CodeBinaryOperatorExpression)
{
Output.Write('(');
GenerateExpression(e.TargetObject);
Output.Write(')');
}
else
{
GenerateExpression(e.TargetObject);
}
Output.Write('.');
}
OutputIdentifier(e.MethodName);
if (e.TypeArguments.Count > 0)
{
Output.Write(GetTypeArgumentsOutput(e.TypeArguments));
}
}
private void GenerateStatement(CodeStatement e)
{
if (e is CodeMethodReturnStatement)
GenerateMethodReturnStatement((CodeMethodReturnStatement)e);
else if (e is CodeConditionStatement)
GenerateConditionStatement((CodeConditionStatement)e);
else if (e is CodeTryCatchFinallyStatement)
GenerateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e);
else if (e is CodeAssignStatement)
GenerateAssignStatement((CodeAssignStatement)e);
else if (e is CodeExpressionStatement)
GenerateExpressionStatement((CodeExpressionStatement)e);
else if (e is CodeIterationStatement)
GenerateIterationStatement((CodeIterationStatement)e);
else if (e is CodeThrowExceptionStatement)
GenerateThrowExceptionStatement((CodeThrowExceptionStatement)e);
else if (e is CodeVariableDeclarationStatement)
GenerateVariableDeclarationStatement((CodeVariableDeclarationStatement)e);
else if (e is CodeAttachEventStatement)
GenerateAttachEventStatement((CodeAttachEventStatement)e);
else if (e is CodeRemoveEventStatement)
GenerateRemoveEventStatement((CodeRemoveEventStatement)e);
else if (e is CodeGotoStatement)
GenerateGotoStatement((CodeGotoStatement)e);
else if (e is CodeLabeledStatement)
GenerateLabeledStatement((CodeLabeledStatement)e);
else
throw new ArgumentException(string.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e));
}
private void GenerateStatements(CodeStatementCollection stmts)
{
foreach (CodeStatement stmt in stmts)
{
((ICodeGenerator)this).GenerateCodeFromStatement(stmt, _output.InnerWriter, _options);
}
}
private void GenerateEventReferenceExpression(CodeEventReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write('.');
}
OutputIdentifier(e.EventName);
}
private void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
}
Output.Write('(');
OutputExpressionList(e.Parameters);
Output.Write(')');
}
private void GenerateObjectCreateExpression(CodeObjectCreateExpression e)
{
Output.Write("new ");
OutputType(e.CreateType);
Output.Write('(');
OutputExpressionList(e.Parameters);
Output.Write(')');
}
private void GeneratePrimitiveExpression(CodePrimitiveExpression e)
{
if (e.Value is char)
{
GeneratePrimitiveChar((char)e.Value);
}
else if (e.Value is sbyte)
{
// C# has no literal marker for types smaller than Int32
Output.Write(((sbyte)e.Value).ToString(CultureInfo.InvariantCulture));
}
else if (e.Value is ushort)
{
// C# has no literal marker for types smaller than Int32, and you will
// get a conversion error if you use "u" here.
Output.Write(((ushort)e.Value).ToString(CultureInfo.InvariantCulture));
}
else if (e.Value is uint)
{
Output.Write(((uint)e.Value).ToString(CultureInfo.InvariantCulture));
Output.Write('u');
}
else if (e.Value is ulong)
{
Output.Write(((ulong)e.Value).ToString(CultureInfo.InvariantCulture));
Output.Write("ul");
}
else
{
GeneratePrimitiveExpressionBase(e);
}
}
private void GeneratePrimitiveExpressionBase(CodePrimitiveExpression e)
{
if (e.Value == null)
{
Output.Write(NullToken);
}
else if (e.Value is string)
{
Output.Write(QuoteSnippetString((string)e.Value));
}
else if (e.Value is char)
{
Output.Write("'" + e.Value.ToString() + "'");
}
else if (e.Value is byte)
{
Output.Write(((byte)e.Value).ToString(CultureInfo.InvariantCulture));
}
else if (e.Value is short)
{
Output.Write(((short)e.Value).ToString(CultureInfo.InvariantCulture));
}
else if (e.Value is int)
{
Output.Write(((int)e.Value).ToString(CultureInfo.InvariantCulture));
}
else if (e.Value is long)
{
Output.Write(((long)e.Value).ToString(CultureInfo.InvariantCulture));
}
else if (e.Value is float)
{
GenerateSingleFloatValue((float)e.Value);
}
else if (e.Value is double)
{
GenerateDoubleValue((double)e.Value);
}
else if (e.Value is decimal)
{
GenerateDecimalValue((decimal)e.Value);
}
else if (e.Value is bool)
{
if ((bool)e.Value)
{
Output.Write("true");
}
else
{
Output.Write("false");
}
}
else
{
throw new ArgumentException(string.Format(SR.InvalidPrimitiveType, e.Value.GetType().ToString()));
}
}
private void GeneratePrimitiveChar(char c)
{
Output.Write('\'');
switch (c)
{
case '\r':
Output.Write("\\r");
break;
case '\t':
Output.Write("\\t");
break;
case '\"':
Output.Write("\\\"");
break;
case '\'':
Output.Write("\\\'");
break;
case '\\':
Output.Write("\\\\");
break;
case '\0':
Output.Write("\\0");
break;
case '\n':
Output.Write("\\n");
break;
case '\u2028':
case '\u2029':
case '\u0084':
case '\u0085':
AppendEscapedChar(null, c);
break;
default:
if (char.IsSurrogate(c))
{
AppendEscapedChar(null, c);
}
else
{
Output.Write(c);
}
break;
}
Output.Write('\'');
}
private void AppendEscapedChar(StringBuilder b, char value)
{
if (b == null)
{
Output.Write("\\u");
Output.Write(((int)value).ToString("X4", CultureInfo.InvariantCulture));
}
else
{
b.Append("\\u");
b.Append(((int)value).ToString("X4", CultureInfo.InvariantCulture));
}
}
private void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) =>
Output.Write("value");
private void GenerateThisReferenceExpression(CodeThisReferenceExpression e) =>
Output.Write("this");
private void GenerateExpressionStatement(CodeExpressionStatement e)
{
GenerateExpression(e.Expression);
if (!_generatingForLoop)
{
Output.WriteLine(';');
}
}
private void GenerateIterationStatement(CodeIterationStatement e)
{
_generatingForLoop = true;
Output.Write("for (");
GenerateStatement(e.InitStatement);
Output.Write("; ");
GenerateExpression(e.TestExpression);
Output.Write("; ");
GenerateStatement(e.IncrementStatement);
Output.Write(')');
OutputStartingBrace();
_generatingForLoop = false;
Indent++;
GenerateStatements(e.Statements);
Indent--;
Output.WriteLine('}');
}
private void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e)
{
Output.Write("throw");
if (e.ToThrow != null)
{
Output.Write(' ');
GenerateExpression(e.ToThrow);
}
Output.WriteLine(';');
}
private void GenerateMethodReturnStatement(CodeMethodReturnStatement e)
{
Output.Write("return");
if (e.Expression != null)
{
Output.Write(' ');
GenerateExpression(e.Expression);
}
Output.WriteLine(';');
}
private void GenerateConditionStatement(CodeConditionStatement e)
{
Output.Write("if (");
GenerateExpression(e.Condition);
Output.Write(')');
OutputStartingBrace();
Indent++;
GenerateStatements(e.TrueStatements);
Indent--;
CodeStatementCollection falseStatemetns = e.FalseStatements;
if (falseStatemetns.Count > 0)
{
Output.Write('}');
if (Options.ElseOnClosing)
{
Output.Write(' ');
}
else
{
Output.WriteLine();
}
Output.Write("else");
OutputStartingBrace();
Indent++;
GenerateStatements(e.FalseStatements);
Indent--;
}
Output.WriteLine('}');
}
private void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
{
Output.Write("try");
OutputStartingBrace();
Indent++;
GenerateStatements(e.TryStatements);
Indent--;
CodeCatchClauseCollection catches = e.CatchClauses;
if (catches.Count > 0)
{
foreach (CodeCatchClause current in catches)
{
Output.Write('}');
if (Options.ElseOnClosing)
{
Output.Write(' ');
}
else
{
Output.WriteLine();
}
Output.Write("catch (");
OutputType(current.CatchExceptionType);
Output.Write(' ');
OutputIdentifier(current.LocalName);
Output.Write(')');
OutputStartingBrace();
Indent++;
GenerateStatements(current.Statements);
Indent--;
}
}
CodeStatementCollection finallyStatements = e.FinallyStatements;
if (finallyStatements.Count > 0)
{
Output.Write('}');
if (Options.ElseOnClosing)
{
Output.Write(' ');
}
else
{
Output.WriteLine();
}
Output.Write("finally");
OutputStartingBrace();
Indent++;
GenerateStatements(finallyStatements);
Indent--;
}
Output.WriteLine('}');
}
private void GenerateAssignStatement(CodeAssignStatement e)
{
GenerateExpression(e.Left);
Output.Write(" = ");
GenerateExpression(e.Right);
if (!_generatingForLoop)
{
Output.WriteLine(';');
}
}
private void GenerateAttachEventStatement(CodeAttachEventStatement e)
{
GenerateEventReferenceExpression(e.Event);
Output.Write(" += ");
GenerateExpression(e.Listener);
Output.WriteLine(';');
}
private void GenerateRemoveEventStatement(CodeRemoveEventStatement e)
{
GenerateEventReferenceExpression(e.Event);
Output.Write(" -= ");
GenerateExpression(e.Listener);
Output.WriteLine(';');
}
private void GenerateGotoStatement(CodeGotoStatement e)
{
Output.Write("goto ");
Output.Write(e.Label);
Output.WriteLine(';');
}
private void GenerateLabeledStatement(CodeLabeledStatement e)
{
Indent--;
Output.Write(e.Label);
Output.WriteLine(':');
Indent++;
if (e.Statement != null)
{
GenerateStatement(e.Statement);
}
}
private void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
{
OutputTypeNamePair(e.Type, e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
if (!_generatingForLoop)
{
Output.WriteLine(';');
}
}
private void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c)
{
if (IsCurrentDelegate || IsCurrentEnum) return;
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
if (e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
}
Output.Write("event ");
string name = e.Name;
if (e.PrivateImplementationType != null)
{
name = GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false) + "." + name;
}
OutputTypeNamePair(e.Type, name);
Output.WriteLine(';');
}
private void GenerateExpression(CodeExpression e)
{
if (e is CodeArrayCreateExpression)
GenerateArrayCreateExpression((CodeArrayCreateExpression)e);
else if (e is CodeBaseReferenceExpression)
GenerateBaseReferenceExpression((CodeBaseReferenceExpression)e);
else if (e is CodeBinaryOperatorExpression)
GenerateBinaryOperatorExpression((CodeBinaryOperatorExpression)e);
else if (e is CodeCastExpression)
GenerateCastExpression((CodeCastExpression)e);
else if (e is CodeDelegateCreateExpression)
GenerateDelegateCreateExpression((CodeDelegateCreateExpression)e);
else if (e is CodeFieldReferenceExpression)
GenerateFieldReferenceExpression((CodeFieldReferenceExpression)e);
else if (e is CodeArgumentReferenceExpression)
GenerateArgumentReferenceExpression((CodeArgumentReferenceExpression)e);
else if (e is CodeVariableReferenceExpression)
GenerateVariableReferenceExpression((CodeVariableReferenceExpression)e);
else if (e is CodeIndexerExpression)
GenerateIndexerExpression((CodeIndexerExpression)e);
else if (e is CodeArrayIndexerExpression)
GenerateArrayIndexerExpression((CodeArrayIndexerExpression)e);
else if (e is CodeMethodInvokeExpression)
GenerateMethodInvokeExpression((CodeMethodInvokeExpression)e);
else if (e is CodeMethodReferenceExpression)
GenerateMethodReferenceExpression((CodeMethodReferenceExpression)e);
else if (e is CodeEventReferenceExpression)
GenerateEventReferenceExpression((CodeEventReferenceExpression)e);
else if (e is CodeDelegateInvokeExpression)
GenerateDelegateInvokeExpression((CodeDelegateInvokeExpression)e);
else if (e is CodeObjectCreateExpression)
GenerateObjectCreateExpression((CodeObjectCreateExpression)e);
else if (e is CodeParameterDeclarationExpression)
GenerateParameterDeclarationExpression((CodeParameterDeclarationExpression)e);
else if (e is CodeDirectionExpression)
GenerateDirectionExpression((CodeDirectionExpression)e);
else if (e is CodePrimitiveExpression)
GeneratePrimitiveExpression((CodePrimitiveExpression)e);
else if (e is CodePropertyReferenceExpression)
GeneratePropertyReferenceExpression((CodePropertyReferenceExpression)e);
else if (e is CodePropertySetValueReferenceExpression)
GeneratePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e);
else if (e is CodeThisReferenceExpression)
GenerateThisReferenceExpression((CodeThisReferenceExpression)e);
else if (e is CodeTypeReferenceExpression)
GenerateTypeReferenceExpression((CodeTypeReferenceExpression)e);
else if (e is CodeTypeOfExpression)
GenerateTypeOfExpression((CodeTypeOfExpression)e);
else if (e is CodeDefaultValueExpression)
GenerateDefaultValueExpression((CodeDefaultValueExpression)e);
else
{
if (e == null)
throw new ArgumentNullException(nameof(e));
else
throw new ArgumentException(string.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e));
}
}
private void GenerateField(CodeMemberField e)
{
if (IsCurrentDelegate || IsCurrentInterface) return;
if (IsCurrentEnum)
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
OutputIdentifier(e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine(',');
}
else
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
OutputMemberAccessModifier(e.Attributes);
OutputVTableModifier(e.Attributes);
OutputFieldScopeModifier(e.Attributes);
OutputTypeNamePair(e.Type, e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine(';');
}
}
private void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e)
{
if (e.CustomAttributes.Count > 0)
{
// Parameter attributes should be in-line for readability
GenerateAttributes(e.CustomAttributes, null, true);
}
OutputDirection(e.Direction);
OutputTypeNamePair(e.Type, e.Name);
}
private void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c)
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
Output.Write("public static ");
OutputType(e.ReturnType);
Output.Write(" Main()");
OutputStartingBrace();
Indent++;
GenerateStatements(e.Statements);
Indent--;
Output.WriteLine('}');
}
private void GenerateMethods(CodeTypeDeclaration e)
{
foreach (CodeTypeMember current in e.Members)
{
if (current is CodeMemberMethod && !(current is CodeTypeConstructor) && !(current is CodeConstructor))
{
_currentMember = current;
if (_options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
CodeMemberMethod imp = (CodeMemberMethod)current;
if (current is CodeEntryPointMethod)
GenerateEntryPointMethod((CodeEntryPointMethod)current, e);
else
GenerateMethod(imp, e);
}
}
}
private void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c)
{
if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface)) return;
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
if (e.ReturnTypeCustomAttributes.Count > 0)
{
GenerateAttributes(e.ReturnTypeCustomAttributes, "return: ");
}
if (!IsCurrentInterface)
{
if (e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
OutputVTableModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
}
}
else
{
// interfaces still need "new"
OutputVTableModifier(e.Attributes);
}
OutputType(e.ReturnType);
Output.Write(' ');
if (e.PrivateImplementationType != null)
{
Output.Write(GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false));
Output.Write('.');
}
OutputIdentifier(e.Name);
OutputTypeParameters(e.TypeParameters);
Output.Write('(');
OutputParameters(e.Parameters);
Output.Write(')');
OutputTypeParameterConstraints(e.TypeParameters);
if (!IsCurrentInterface
&& (e.Attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract)
{
OutputStartingBrace();
Indent++;
GenerateStatements(e.Statements);
Indent--;
Output.WriteLine('}');
}
else
{
Output.WriteLine(';');
}
}
private void GenerateProperties(CodeTypeDeclaration e)
{
foreach (CodeTypeMember current in e.Members)
{
if (current is CodeMemberProperty)
{
_currentMember = current;
if (_options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
CodeMemberProperty imp = (CodeMemberProperty)current;
GenerateProperty(imp, e);
}
}
}
private void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c)
{
if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface)) return;
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
if (!IsCurrentInterface)
{
if (e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
OutputVTableModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
}
}
else
{
OutputVTableModifier(e.Attributes);
}
OutputType(e.Type);
Output.Write(' ');
if (e.PrivateImplementationType != null && !IsCurrentInterface)
{
Output.Write(GetBaseTypeOutput(e.PrivateImplementationType, preferBuiltInTypes: false));
Output.Write('.');
}
if (e.Parameters.Count > 0 && string.Equals(e.Name, "Item", StringComparison.OrdinalIgnoreCase))
{
Output.Write("this[");
OutputParameters(e.Parameters);
Output.Write(']');
}
else
{
OutputIdentifier(e.Name);
}
OutputStartingBrace();
Indent++;
if (e.HasGet)
{
if (IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)
{
Output.WriteLine("get;");
}
else
{
Output.Write("get");
OutputStartingBrace();
Indent++;
GenerateStatements(e.GetStatements);
Indent--;
Output.WriteLine('}');
}
}
if (e.HasSet)
{
if (IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)
{
Output.WriteLine("set;");
}
else
{
Output.Write("set");
OutputStartingBrace();
Indent++;
GenerateStatements(e.SetStatements);
Indent--;
Output.WriteLine('}');
}
}
Indent--;
Output.WriteLine('}');
}
private void GenerateSingleFloatValue(float s)
{
if (float.IsNaN(s))
{
Output.Write("float.NaN");
}
else if (float.IsNegativeInfinity(s))
{
Output.Write("float.NegativeInfinity");
}
else if (float.IsPositiveInfinity(s))
{
Output.Write("float.PositiveInfinity");
}
else
{
Output.Write(s.ToString(CultureInfo.InvariantCulture));
Output.Write('F');
}
}
private void GenerateDoubleValue(double d)
{
if (double.IsNaN(d))
{
Output.Write("double.NaN");
}
else if (double.IsNegativeInfinity(d))
{
Output.Write("double.NegativeInfinity");
}
else if (double.IsPositiveInfinity(d))
{
Output.Write("double.PositiveInfinity");
}
else
{
Output.Write(d.ToString("R", CultureInfo.InvariantCulture));
// always mark a double as being a double in case we have no decimal portion (e.g write 1D instead of 1 which is an int)
Output.Write('D');
}
}
private void GenerateDecimalValue(decimal d)
{
Output.Write(d.ToString(CultureInfo.InvariantCulture));
Output.Write('m');
}
private void OutputVTableModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.VTableMask)
{
case MemberAttributes.New:
Output.Write("new ");
break;
}
}
private void OutputMemberAccessModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.AccessMask)
{
case MemberAttributes.Assembly:
Output.Write("internal ");
break;
case MemberAttributes.FamilyAndAssembly:
Output.Write("internal "); /*FamANDAssem*/
break;
case MemberAttributes.Family:
Output.Write("protected ");
break;
case MemberAttributes.FamilyOrAssembly:
Output.Write("protected internal ");
break;
case MemberAttributes.Private:
Output.Write("private ");
break;
case MemberAttributes.Public:
Output.Write("public ");
break;
}
}
private void OutputMemberScopeModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.ScopeMask)
{
case MemberAttributes.Abstract:
Output.Write("abstract ");
break;
case MemberAttributes.Final:
Output.Write("");
break;
case MemberAttributes.Static:
Output.Write("static ");
break;
case MemberAttributes.Override:
Output.Write("override ");
break;
default:
switch (attributes & MemberAttributes.AccessMask)
{
case MemberAttributes.Family:
case MemberAttributes.Public:
case MemberAttributes.Assembly:
Output.Write("virtual ");
break;
default:
// nothing;
break;
}
break;
}
}
private void OutputOperator(CodeBinaryOperatorType op)
{
switch (op)
{
case CodeBinaryOperatorType.Add:
Output.Write('+');
break;
case CodeBinaryOperatorType.Subtract:
Output.Write('-');
break;
case CodeBinaryOperatorType.Multiply:
Output.Write('*');
break;
case CodeBinaryOperatorType.Divide:
Output.Write('/');
break;
case CodeBinaryOperatorType.Modulus:
Output.Write('%');
break;
case CodeBinaryOperatorType.Assign:
Output.Write('=');
break;
case CodeBinaryOperatorType.IdentityInequality:
Output.Write("!=");
break;
case CodeBinaryOperatorType.IdentityEquality:
Output.Write("==");
break;
case CodeBinaryOperatorType.ValueEquality:
Output.Write("==");
break;
case CodeBinaryOperatorType.BitwiseOr:
Output.Write('|');
break;
case CodeBinaryOperatorType.BitwiseAnd:
Output.Write('&');
break;
case CodeBinaryOperatorType.BooleanOr:
Output.Write("||");
break;
case CodeBinaryOperatorType.BooleanAnd:
Output.Write("&&");
break;
case CodeBinaryOperatorType.LessThan:
Output.Write('<');
break;
case CodeBinaryOperatorType.LessThanOrEqual:
Output.Write("<=");
break;
case CodeBinaryOperatorType.GreaterThan:
Output.Write('>');
break;
case CodeBinaryOperatorType.GreaterThanOrEqual:
Output.Write(">=");
break;
}
}
private void OutputFieldScopeModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.ScopeMask)
{
case MemberAttributes.Final:
break;
case MemberAttributes.Static:
Output.Write("static ");
break;
case MemberAttributes.Const:
Output.Write("const ");
break;
default:
break;
}
}
private void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write('.');
}
OutputIdentifier(e.PropertyName);
}
private void GenerateConstructors(CodeTypeDeclaration e)
{
foreach (CodeTypeMember current in e.Members)
{
if (current is CodeConstructor)
{
_currentMember = current;
if (_options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
CodeConstructor imp = (CodeConstructor)current;
GenerateConstructor(imp, e);
}
}
}
private void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c)
{
if (!(IsCurrentClass || IsCurrentStruct)) return;
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
OutputMemberAccessModifier(e.Attributes);
OutputIdentifier(CurrentTypeName);
Output.Write('(');
OutputParameters(e.Parameters);
Output.Write(')');
CodeExpressionCollection baseArgs = e.BaseConstructorArgs;
CodeExpressionCollection thisArgs = e.ChainedConstructorArgs;
if (baseArgs.Count > 0)
{
Output.WriteLine(" : ");
Indent++;
Indent++;
Output.Write("base(");
OutputExpressionList(baseArgs);
Output.Write(')');
Indent--;
Indent--;
}
if (thisArgs.Count > 0)
{
Output.WriteLine(" : ");
Indent++;
Indent++;
Output.Write("this(");
OutputExpressionList(thisArgs);
Output.Write(')');
Indent--;
Indent--;
}
OutputStartingBrace();
Indent++;
GenerateStatements(e.Statements);
Indent--;
Output.WriteLine('}');
}
private void GenerateTypeConstructor(CodeTypeConstructor e)
{
if (!(IsCurrentClass || IsCurrentStruct)) return;
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
Output.Write("static ");
Output.Write(CurrentTypeName);
Output.Write("()");
OutputStartingBrace();
Indent++;
GenerateStatements(e.Statements);
Indent--;
Output.WriteLine('}');
}
private void GenerateTypeReferenceExpression(CodeTypeReferenceExpression e) =>
OutputType(e.Type);
private void GenerateTypeOfExpression(CodeTypeOfExpression e)
{
Output.Write("typeof(");
OutputType(e.Type);
Output.Write(')');
}
private void GenerateType(CodeTypeDeclaration e)
{
_currentClass = e;
GenerateTypeStart(e);
if (Options.VerbatimOrder)
{
foreach (CodeTypeMember member in e.Members)
GenerateTypeMember(member, e);
}
else
{
GenerateFields(e);
GenerateTypeConstructors(e);
GenerateConstructors(e);
GenerateProperties(e);
GenerateEvents(e);
GenerateMethods(e);
GenerateNestedTypes(e);
}
// Nested types clobber the current class, so reset it.
_currentClass = e;
GenerateTypeEnd(e);
}
private void GenerateTypeStart(CodeTypeDeclaration e)
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
if (IsCurrentDelegate)
{
switch (e.TypeAttributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.Public:
Output.Write("public ");
break;
case TypeAttributes.NotPublic:
default:
break;
}
CodeTypeDelegate del = (CodeTypeDelegate)e;
Output.Write("delegate ");
OutputType(del.ReturnType);
Output.Write(' ');
OutputIdentifier(e.Name);
Output.Write('(');
OutputParameters(del.Parameters);
Output.WriteLine(");");
}
else
{
OutputTypeAttributes(e);
OutputIdentifier(e.Name);
OutputTypeParameters(e.TypeParameters);
bool first = true;
foreach (CodeTypeReference typeRef in e.BaseTypes)
{
if (first)
{
Output.Write(" : ");
first = false;
}
else
{
Output.Write(", ");
}
OutputType(typeRef);
}
OutputTypeParameterConstraints(e.TypeParameters);
OutputStartingBrace();
Indent++;
}
}
private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration declaredType)
{
if (_options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
if (member is CodeTypeDeclaration)
{
((ICodeGenerator)this).GenerateCodeFromType((CodeTypeDeclaration)member, _output.InnerWriter, _options);
// Nested types clobber the current class, so reset it.
_currentClass = declaredType;
// For nested types, comments and line pragmas are handled separately, so return here
return;
}
if (member is CodeMemberField)
GenerateField((CodeMemberField)member);
else if (member is CodeMemberProperty)
GenerateProperty((CodeMemberProperty)member, declaredType);
else if (member is CodeMemberMethod)
{
if (member is CodeConstructor)
{
GenerateConstructor((CodeConstructor)member, declaredType);
}
else if (member is CodeTypeConstructor)
{
GenerateTypeConstructor((CodeTypeConstructor)member);
}
else if (member is CodeEntryPointMethod)
{
GenerateEntryPointMethod((CodeEntryPointMethod)member, declaredType);
}
else
{
GenerateMethod((CodeMemberMethod)member, declaredType);
}
}
else if (member is CodeMemberEvent)
{
GenerateEvent((CodeMemberEvent)member, declaredType);
}
}
private void GenerateTypeConstructors(CodeTypeDeclaration e)
{
foreach (CodeTypeMember current in e.Members)
{
if (current is CodeTypeConstructor)
{
_currentMember = current;
if (_options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
CodeTypeConstructor imp = (CodeTypeConstructor)current;
GenerateTypeConstructor(imp);
}
}
}
private void GenerateNestedTypes(CodeTypeDeclaration e)
{
foreach (CodeTypeMember current in e.Members)
{
if (current is CodeTypeDeclaration)
{
if (_options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
CodeTypeDeclaration currentClass = (CodeTypeDeclaration)current;
((ICodeGenerator)this).GenerateCodeFromType(currentClass, _output.InnerWriter, _options);
}
}
}
private void OutputAttributeArgument(CodeAttributeArgument arg)
{
if (!string.IsNullOrEmpty(arg.Name))
{
OutputIdentifier(arg.Name);
Output.Write('=');
}
((ICodeGenerator)this).GenerateCodeFromExpression(arg.Value, _output.InnerWriter, _options);
}
private void OutputDirection(FieldDirection dir)
{
switch (dir)
{
case FieldDirection.In:
break;
case FieldDirection.Out:
Output.Write("out ");
break;
case FieldDirection.Ref:
Output.Write("ref ");
break;
}
}
private void OutputExpressionList(CodeExpressionCollection expressions)
{
OutputExpressionList(expressions, false /*newlineBetweenItems*/);
}
private void OutputExpressionList(CodeExpressionCollection expressions, bool newlineBetweenItems)
{
bool first = true;
Indent++;
foreach (CodeExpression current in expressions)
{
if (first)
{
first = false;
}
else
{
if (newlineBetweenItems)
ContinueOnNewLine(",");
else
Output.Write(", ");
}
((ICodeGenerator)this).GenerateCodeFromExpression(current, _output.InnerWriter, _options);
}
Indent--;
}
private void OutputParameters(CodeParameterDeclarationExpressionCollection parameters)
{
bool first = true;
bool multiline = parameters.Count > ParameterMultilineThreshold;
if (multiline)
{
Indent += 3;
}
foreach (CodeParameterDeclarationExpression current in parameters)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
if (multiline)
{
ContinueOnNewLine("");
}
GenerateExpression(current);
}
if (multiline)
{
Indent -= 3;
}
}
private void OutputTypeNamePair(CodeTypeReference typeRef, string name)
{
OutputType(typeRef);
Output.Write(' ');
OutputIdentifier(name);
}
private void OutputTypeParameters(CodeTypeParameterCollection typeParameters)
{
if (typeParameters.Count == 0)
{
return;
}
Output.Write('<');
bool first = true;
for (int i = 0; i < typeParameters.Count; i++)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
if (typeParameters[i].CustomAttributes.Count > 0)
{
GenerateAttributes(typeParameters[i].CustomAttributes, null, true);
Output.Write(' ');
}
Output.Write(typeParameters[i].Name);
}
Output.Write('>');
}
private void OutputTypeParameterConstraints(CodeTypeParameterCollection typeParameters)
{
if (typeParameters.Count == 0)
{
return;
}
for (int i = 0; i < typeParameters.Count; i++)
{
// generating something like: "where KeyType: IComparable, IEnumerable"
Output.WriteLine();
Indent++;
bool first = true;
if (typeParameters[i].Constraints.Count > 0)
{
foreach (CodeTypeReference typeRef in typeParameters[i].Constraints)
{
if (first)
{
Output.Write("where ");
Output.Write(typeParameters[i].Name);
Output.Write(" : ");
first = false;
}
else
{
Output.Write(", ");
}
OutputType(typeRef);
}
}
if (typeParameters[i].HasConstructorConstraint)
{
if (first)
{
Output.Write("where ");
Output.Write(typeParameters[i].Name);
Output.Write(" : new()");
}
else
{
Output.Write(", new ()");
}
}
Indent--;
}
}
private void OutputTypeAttributes(CodeTypeDeclaration e)
{
if ((e.Attributes & MemberAttributes.New) != 0)
{
Output.Write("new ");
}
TypeAttributes attributes = e.TypeAttributes;
switch (attributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.Public:
case TypeAttributes.NestedPublic:
Output.Write("public ");
break;
case TypeAttributes.NestedPrivate:
Output.Write("private ");
break;
case TypeAttributes.NestedFamily:
Output.Write("protected ");
break;
case TypeAttributes.NotPublic:
case TypeAttributes.NestedAssembly:
case TypeAttributes.NestedFamANDAssem:
Output.Write("internal ");
break;
case TypeAttributes.NestedFamORAssem:
Output.Write("protected internal ");
break;
}
if (e.IsStruct)
{
if (e.IsPartial)
{
Output.Write("partial ");
}
Output.Write("struct ");
}
else if (e.IsEnum)
{
Output.Write("enum ");
}
else
{
switch (attributes & TypeAttributes.ClassSemanticsMask)
{
case TypeAttributes.Class:
if ((attributes & TypeAttributes.Sealed) == TypeAttributes.Sealed)
{
Output.Write("sealed ");
}
if ((attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract)
{
Output.Write("abstract ");
}
if (e.IsPartial)
{
Output.Write("partial ");
}
Output.Write("class ");
break;
case TypeAttributes.Interface:
if (e.IsPartial)
{
Output.Write("partial ");
}
Output.Write("interface ");
break;
}
}
}
private void GenerateTypeEnd(CodeTypeDeclaration e)
{
if (!IsCurrentDelegate)
{
Indent--;
Output.WriteLine('}');
}
}
private void GenerateDirectionExpression(CodeDirectionExpression e)
{
OutputDirection(e.Direction);
GenerateExpression(e.Expression);
}
private void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes) =>
Output.Write('[');
private void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes) =>
Output.Write(']');
private void GenerateAttributes(CodeAttributeDeclarationCollection attributes) =>
GenerateAttributes(attributes, null, inLine: false);
private void GenerateAttributes(CodeAttributeDeclarationCollection attributes, string prefix) =>
GenerateAttributes(attributes, prefix, inLine: false);
private void GenerateAttributes(CodeAttributeDeclarationCollection attributes, string prefix, bool inLine)
{
if (attributes.Count == 0) return;
bool paramArray = false;
foreach (CodeAttributeDeclaration current in attributes)
{
// we need to convert paramArrayAttribute to params keyword to
// make csharp compiler happy. In addition, params keyword needs to be after
// other attributes.
if (current.Name.Equals("system.paramarrayattribute", StringComparison.OrdinalIgnoreCase))
{
paramArray = true;
continue;
}
GenerateAttributeDeclarationsStart(attributes);
if (prefix != null)
{
Output.Write(prefix);
}
if (current.AttributeType != null)
{
Output.Write(GetTypeOutput(current.AttributeType));
}
Output.Write('(');
bool firstArg = true;
foreach (CodeAttributeArgument arg in current.Arguments)
{
if (firstArg)
{
firstArg = false;
}
else
{
Output.Write(", ");
}
OutputAttributeArgument(arg);
}
Output.Write(')');
GenerateAttributeDeclarationsEnd(attributes);
if (inLine)
{
Output.Write(' ');
}
else
{
Output.WriteLine();
}
}
if (paramArray)
{
if (prefix != null)
{
Output.Write(prefix);
}
Output.Write("params");
if (inLine)
{
Output.Write(' ');
}
else
{
Output.WriteLine();
}
}
}
public bool Supports(GeneratorSupport support) => (support & LanguageSupport) == support;
public bool IsValidIdentifier(string value)
{
// identifiers must be 1 char or longer
//
if (string.IsNullOrEmpty(value))
{
return false;
}
if (value.Length > 512)
{
return false;
}
// identifiers cannot be a keyword, unless they are escaped with an '@'
//
if (value[0] != '@')
{
if (CSharpHelpers.IsKeyword(value))
{
return false;
}
}
else
{
value = value.Substring(1);
}
return CodeGenerator.IsValidLanguageIndependentIdentifier(value);
}
public void ValidateIdentifier(string value)
{
if (!IsValidIdentifier(value))
{
throw new ArgumentException(string.Format(SR.InvalidIdentifier, value));
}
}
public string CreateValidIdentifier(string name)
{
if (CSharpHelpers.IsPrefixTwoUnderscore(name))
{
name = "_" + name;
}
while (CSharpHelpers.IsKeyword(name))
{
name = "_" + name;
}
return name;
}
public string CreateEscapedIdentifier(string name)
{
return CSharpHelpers.CreateEscapedIdentifier(name);
}
// returns the type name without any array declaration.
private string GetBaseTypeOutput(CodeTypeReference typeRef, bool preferBuiltInTypes = true)
{
string s = typeRef.BaseType;
if (preferBuiltInTypes)
{
if (s.Length == 0)
{
return "void";
}
string lowerCaseString = s.ToLower(CultureInfo.InvariantCulture).Trim();
switch (lowerCaseString)
{
case "system.int16":
return "short";
case "system.int32":
return "int";
case "system.int64":
return "long";
case "system.string":
return "string";
case "system.object":
return "object";
case "system.boolean":
return "bool";
case "system.void":
return "void";
case "system.char":
return "char";
case "system.byte":
return "byte";
case "system.uint16":
return "ushort";
case "system.uint32":
return "uint";
case "system.uint64":
return "ulong";
case "system.sbyte":
return "sbyte";
case "system.single":
return "float";
case "system.double":
return "double";
case "system.decimal":
return "decimal";
}
}
// replace + with . for nested classes.
//
var sb = new StringBuilder(s.Length + 10);
if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
{
sb.Append("global::");
}
string baseType = typeRef.BaseType;
int lastIndex = 0;
int currentTypeArgStart = 0;
for (int i = 0; i < baseType.Length; i++)
{
switch (baseType[i])
{
case '+':
case '.':
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
sb.Append('.');
i++;
lastIndex = i;
break;
case '`':
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
i++; // skip the '
int numTypeArgs = 0;
while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
{
numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
i++;
}
GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
currentTypeArgStart += numTypeArgs;
// Arity can be in the middle of a nested type name, so we might have a . or + after it.
// Skip it if so.
if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
{
sb.Append('.');
i++;
}
lastIndex = i;
break;
}
}
if (lastIndex < baseType.Length)
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
return sb.ToString();
}
private string GetTypeArgumentsOutput(CodeTypeReferenceCollection typeArguments)
{
var sb = new StringBuilder(128);
GetTypeArgumentsOutput(typeArguments, 0, typeArguments.Count, sb);
return sb.ToString();
}
private void GetTypeArgumentsOutput(CodeTypeReferenceCollection typeArguments, int start, int length, StringBuilder sb)
{
sb.Append('<');
bool first = true;
for (int i = start; i < start + length; i++)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
// it's possible that we call GetTypeArgumentsOutput with an empty typeArguments collection. This is the case
// for open types, so we want to just output the brackets and commas.
if (i < typeArguments.Count)
sb.Append(GetTypeOutput(typeArguments[i]));
}
sb.Append('>');
}
public string GetTypeOutput(CodeTypeReference typeRef)
{
string s = string.Empty;
CodeTypeReference baseTypeRef = typeRef;
while (baseTypeRef.ArrayElementType != null)
{
baseTypeRef = baseTypeRef.ArrayElementType;
}
s += GetBaseTypeOutput(baseTypeRef);
while (typeRef != null && typeRef.ArrayRank > 0)
{
char[] results = new char[typeRef.ArrayRank + 1];
results[0] = '[';
results[typeRef.ArrayRank] = ']';
for (int i = 1; i < typeRef.ArrayRank; i++)
{
results[i] = ',';
}
s += new string(results);
typeRef = typeRef.ArrayElementType;
}
return s;
}
private void OutputStartingBrace()
{
if (Options.BracingStyle == "C")
{
Output.WriteLine();
Output.WriteLine('{');
}
else
{
Output.WriteLine(" {");
}
}
void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o)
{
bool setLocal = false;
if (_output != null && w != _output.InnerWriter)
{
throw new InvalidOperationException(SR.CodeGenOutputWriter);
}
if (_output == null)
{
setLocal = true;
_options = o ?? new CodeGeneratorOptions();
_output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString);
}
try
{
GenerateType(e);
}
finally
{
if (setLocal)
{
_output = null;
_options = null;
}
}
}
void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o)
{
bool setLocal = false;
if (_output != null && w != _output.InnerWriter)
{
throw new InvalidOperationException(SR.CodeGenOutputWriter);
}
if (_output == null)
{
setLocal = true;
_options = o ?? new CodeGeneratorOptions();
_output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString);
}
try
{
GenerateExpression(e);
}
finally
{
if (setLocal)
{
_output = null;
_options = null;
}
}
}
void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o)
{
bool setLocal = false;
if (_output != null && w != _output.InnerWriter)
throw new InvalidOperationException(SR.CodeGenOutputWriter);
if (_output == null)
{
setLocal = true;
_options = o ?? new CodeGeneratorOptions();
_output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString);
}
try
{
GenerateStatement(e);
}
finally
{
if (setLocal)
{
_output = null;
_options = null;
}
}
}
private static string JoinStringArray(string[] sa, string separator)
{
if (sa == null || sa.Length == 0)
return string.Empty;
if (sa.Length == 1)
return "\"" + sa[0] + "\"";
var sb = new StringBuilder();
for (int i = 0; i < sa.Length - 1; i++)
{
sb.Append('\"');
sb.Append(sa[i]);
sb.Append('\"');
sb.Append(separator);
}
sb.Append('\"');
sb.Append(sa[sa.Length - 1]);
sb.Append('\"');
return sb.ToString();
}
private static readonly char[] s_periodArray = new char[] { '.' };
private ExposedTabStringIndentedTextWriter _output;
private CodeGeneratorOptions _options;
private CodeTypeDeclaration _currentClass;
private CodeTypeMember _currentMember;
private bool _inNestedBinary = false;
private readonly IDictionary<string, string> _provOptions;
private const int ParameterMultilineThreshold = 15;
private const int MaxLineLength = 80;
private const GeneratorSupport LanguageSupport = GeneratorSupport.ArraysOfArrays |
GeneratorSupport.EntryPointMethod |
GeneratorSupport.GotoStatements |
GeneratorSupport.MultidimensionalArrays |
GeneratorSupport.StaticConstructors |
GeneratorSupport.TryCatchStatements |
GeneratorSupport.ReturnTypeAttributes |
GeneratorSupport.AssemblyAttributes |
GeneratorSupport.DeclareValueTypes |
GeneratorSupport.DeclareEnums |
GeneratorSupport.DeclareEvents |
GeneratorSupport.DeclareDelegates |
GeneratorSupport.DeclareInterfaces |
GeneratorSupport.ParameterAttributes |
GeneratorSupport.ReferenceParameters |
GeneratorSupport.ChainedConstructorArguments |
GeneratorSupport.NestedTypes |
GeneratorSupport.MultipleInterfaceMembers |
GeneratorSupport.PublicStaticMembers |
GeneratorSupport.ComplexExpressions |
GeneratorSupport.Win32Resources |
GeneratorSupport.Resources |
GeneratorSupport.PartialTypes |
GeneratorSupport.GenericTypeReference |
GeneratorSupport.GenericTypeDeclaration |
GeneratorSupport.DeclareIndexerProperties;
private static readonly string[][] s_keywords = new string[][] {
null, // 1 character
new string[] { // 2 characters
"as",
"do",
"if",
"in",
"is",
},
new string[] { // 3 characters
"for",
"int",
"new",
"out",
"ref",
"try",
},
new string[] { // 4 characters
"base",
"bool",
"byte",
"case",
"char",
"else",
"enum",
"goto",
"lock",
"long",
"null",
"this",
"true",
"uint",
"void",
},
new string[] { // 5 characters
"break",
"catch",
"class",
"const",
"event",
"false",
"fixed",
"float",
"sbyte",
"short",
"throw",
"ulong",
"using",
"while",
},
new string[] { // 6 characters
"double",
"extern",
"object",
"params",
"public",
"return",
"sealed",
"sizeof",
"static",
"string",
"struct",
"switch",
"typeof",
"unsafe",
"ushort",
},
new string[] { // 7 characters
"checked",
"decimal",
"default",
"finally",
"foreach",
"private",
"virtual",
},
new string[] { // 8 characters
"abstract",
"continue",
"delegate",
"explicit",
"implicit",
"internal",
"operator",
"override",
"readonly",
"volatile",
},
new string[] { // 9 characters
"__arglist",
"__makeref",
"__reftype",
"interface",
"namespace",
"protected",
"unchecked",
},
new string[] { // 10 characters
"__refvalue",
"stackalloc",
},
};
}
}
| 33.68614 | 141 | 0.460525 | [
"BSD-3-Clause"
] | Black-Beard-Sdk/Decompile | src/Black.Beard.Sdk.Decompiler/Microsoft/CSharp/CSharpCodeGenerator.cs | 83,609 | C# |
using System;
using System.Collections;
using DCL.Controllers;
using DCL.Helpers;
using DCL.Models;
using DCL.SettingsCommon;
using UnityEngine;
using AudioSettings = DCL.SettingsCommon.AudioSettings;
namespace DCL.Components
{
public class DCLAudioStream : BaseComponent, IOutOfSceneBoundariesHandler
{
[System.Serializable]
public class Model : BaseModel
{
public string url;
public bool playing = false;
public float volume = 1;
public override BaseModel GetDataFromJSON(string json) { return Utils.SafeFromJson<Model>(json); }
}
private void Awake() { model = new Model(); }
public bool isPlaying { get; private set; } = false;
private float settingsVolume = 0;
private bool isDestroyed = false;
private Model prevModel = new Model();
new public Model GetModel() { return (Model) model; }
public override IEnumerator ApplyChanges(BaseModel newModel)
{
yield return new WaitUntil(() => CommonScriptableObjects.rendererState.Get());
//If the scene creates and destroy the component before our renderer has been turned on bad things happen!
//TODO: Analyze if we can catch this upstream and stop the IEnumerator
if (isDestroyed)
yield break;
Model model = (Model)newModel;
bool forceUpdate = prevModel.volume != model.volume;
settingsVolume = GetCalculatedSettingsVolume(Settings.i.audioSettings.Data);
UpdatePlayingState(forceUpdate);
prevModel = model;
yield return null;
}
private void Start()
{
CommonScriptableObjects.sceneID.OnChange += OnSceneChanged;
CommonScriptableObjects.rendererState.OnChange += OnRendererStateChanged;
Settings.i.audioSettings.OnChanged += OnSettingsChanged;
DataStore.i.virtualAudioMixer.sceneSFXVolume.OnChange += SceneSFXVolume_OnChange;
}
private void OnDestroy()
{
isDestroyed = true;
CommonScriptableObjects.sceneID.OnChange -= OnSceneChanged;
CommonScriptableObjects.rendererState.OnChange -= OnRendererStateChanged;
Settings.i.audioSettings.OnChanged -= OnSettingsChanged;
DataStore.i.virtualAudioMixer.sceneSFXVolume.OnChange -= SceneSFXVolume_OnChange;
StopStreaming();
}
private void UpdatePlayingState(bool forceStateUpdate)
{
if (!gameObject.activeInHierarchy)
{
return;
}
bool canPlayStream = scene.isPersistent || scene.sceneData.id == CommonScriptableObjects.sceneID.Get();
canPlayStream &= CommonScriptableObjects.rendererState;
Model model = (Model) this.model;
bool shouldStopStream = (isPlaying && !model.playing) || (isPlaying && !canPlayStream);
bool shouldStartStream = !isPlaying && canPlayStream && model.playing;
if (shouldStopStream)
{
StopStreaming();
return;
}
if (shouldStartStream)
{
StartStreaming();
return;
}
if (forceStateUpdate)
{
if (isPlaying)
StartStreaming();
else
StopStreaming();
}
}
private void OnSceneChanged(string sceneId, string prevSceneId) { UpdatePlayingState(false); }
private void OnRendererStateChanged(bool isEnable, bool prevState)
{
if (isEnable)
{
UpdatePlayingState(false);
}
}
private void OnSettingsChanged(AudioSettings settings)
{
float newSettingsVolume = GetCalculatedSettingsVolume(settings);
if (Math.Abs(settingsVolume - newSettingsVolume) > Mathf.Epsilon)
{
settingsVolume = newSettingsVolume;
UpdatePlayingState(true);
}
}
private float GetCalculatedSettingsVolume(AudioSettings audioSettings) { return Utils.ToVolumeCurve(DataStore.i.virtualAudioMixer.sceneSFXVolume.Get() * audioSettings.sceneSFXVolume * audioSettings.masterVolume); }
private void SceneSFXVolume_OnChange(float current, float previous) { OnSettingsChanged(Settings.i.audioSettings.Data); }
private void StopStreaming()
{
Model model = (Model) this.model;
isPlaying = false;
Interface.WebInterface.SendAudioStreamEvent(model.url, false, model.volume * settingsVolume);
}
private void StartStreaming()
{
Model model = (Model) this.model;
isPlaying = true;
Interface.WebInterface.SendAudioStreamEvent(model.url, true, model.volume * settingsVolume);
}
public void UpdateOutOfBoundariesState(bool isInsideBoundaries)
{
if (!isPlaying)
return;
if (isInsideBoundaries)
{
StartStreaming();
}
else
{
Model model = (Model) this.model;
//Set volume to 0 (temporary solution until the refactor in #1421)
Interface.WebInterface.SendAudioStreamEvent(model.url, true, 0);
}
}
public override int GetClassId() { return (int) CLASS_ID_COMPONENT.AUDIO_STREAM; }
}
} | 34.950311 | 222 | 0.600675 | [
"Apache-2.0"
] | dcl-glb/unity-renderer | unity-renderer/Assets/Scripts/MainScripts/DCL/Components/Audio/DCLAudioStream.cs | 5,627 | C# |
///===================================================================================================
///
/// Source https://github.com/PeterWaher/IoTGateway/tree/master/Security/Waher.Security.EllipticCurves
/// Owner https://github.com/PeterWaher
///
///===================================================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Security.Cryptography;
namespace Blockcoli.Libra.Net.Crypto
{
/// <summary>
/// Hash method enumeration.
/// </summary>
public enum HashFunctions
{
/// <summary>
/// MD5 Hash function
/// </summary>
MD5,
/// <summary>
/// SHA-1 Hash function
/// </summary>
SHA1,
/// <summary>
/// SHA-256 Hash function
/// </summary>
SHA256,
/// <summary>
/// SHA-384 Hash function
/// </summary>
SHA384,
/// <summary>
/// SHA-512 Hash function
/// </summary>
SHA512
}
/// <summary>
/// Contains methods for simple hash calculations.
/// </summary>
public static class Hashes
{
/// <summary>
/// Converts an array of bytes to a string with their hexadecimal representations (in lower case).
/// </summary>
/// <param name="Data"></param>
/// <returns></returns>
public static string BinaryToString(byte[] Data)
{
StringBuilder Response = new StringBuilder();
foreach (byte b in Data)
Response.Append(b.ToString("x2"));
return Response.ToString();
}
/// <summary>
/// Parses a hex string.
/// </summary>
/// <param name="s">String.</param>
/// <returns>Array of bytes found in the string, or null if not a hex string.</returns>
public static byte[] StringToBinary(string s)
{
List<byte> Bytes = new List<byte>();
int i, c = s.Length;
byte b = 0, b2;
bool First = true;
char ch;
for (i = 0; i < c; i++)
{
ch = s[i];
if (ch >= '0' && ch <= '9')
b2 = (byte)(ch - '0');
else if (ch >= 'a' && ch <= 'f')
b2 = (byte)(ch - 'a' + 10);
else if (ch >= 'A' && ch <= 'F')
b2 = (byte)(ch - 'A' + 10);
else if (ch == ' ' || ch == 160)
continue;
else
return null;
if (First)
{
b = b2;
First = false;
}
else
{
b <<= 4;
b |= b2;
Bytes.Add(b);
First = true;
}
}
if (!First)
return null;
return Bytes.ToArray();
}
/// <summary>
/// Computes a hash of a block of binary data.
/// </summary>
/// <param name="Function">Hash function.</param>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeHashString(HashFunctions Function, byte[] Data)
{
switch (Function)
{
case HashFunctions.MD5:
return ComputeMD5HashString(Data);
case HashFunctions.SHA1:
return ComputeSHA1HashString(Data);
case HashFunctions.SHA256:
return ComputeSHA256HashString(Data);
case HashFunctions.SHA384:
return ComputeSHA384HashString(Data);
case HashFunctions.SHA512:
return ComputeSHA512HashString(Data);
default:
throw new ArgumentException("Unrecognized hash function", nameof(Function));
}
}
/// <summary>
/// Computes a hash of a block of binary data.
/// </summary>
/// <param name="Function">Hash function.</param>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeHashString(HashFunctions Function, Stream Data)
{
switch (Function)
{
case HashFunctions.MD5:
return BinaryToString(ComputeMD5Hash(Data));
case HashFunctions.SHA1:
return BinaryToString(ComputeSHA1Hash(Data));
case HashFunctions.SHA256:
return BinaryToString(ComputeSHA256Hash(Data));
case HashFunctions.SHA384:
return BinaryToString(ComputeSHA384Hash(Data));
case HashFunctions.SHA512:
return BinaryToString(ComputeSHA512Hash(Data));
default:
throw new ArgumentException("Unrecognized hash function", nameof(Function));
}
}
/// <summary>
/// Computes a hash of a block of binary data.
/// </summary>
/// <param name="Function">Hash function.</param>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeHash(HashFunctions Function, byte[] Data)
{
switch (Function)
{
case HashFunctions.MD5:
return ComputeMD5Hash(Data);
case HashFunctions.SHA1:
return ComputeSHA1Hash(Data);
case HashFunctions.SHA256:
return ComputeSHA256Hash(Data);
case HashFunctions.SHA384:
return ComputeSHA384Hash(Data);
case HashFunctions.SHA512:
return ComputeSHA512Hash(Data);
default:
throw new ArgumentException("Unrecognized hash function", nameof(Function));
}
}
/// <summary>
/// Computes a hash of a block of binary data.
/// </summary>
/// <param name="Function">Hash function.</param>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeHash(HashFunctions Function, Stream Data)
{
switch (Function)
{
case HashFunctions.MD5:
return ComputeMD5Hash(Data);
case HashFunctions.SHA1:
return ComputeSHA1Hash(Data);
case HashFunctions.SHA256:
return ComputeSHA256Hash(Data);
case HashFunctions.SHA384:
return ComputeSHA384Hash(Data);
case HashFunctions.SHA512:
return ComputeSHA512Hash(Data);
default:
throw new ArgumentException("Unrecognized hash function", nameof(Function));
}
}
/// <summary>
/// Computes the SHA-1 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA1HashString(byte[] Data)
{
return BinaryToString(ComputeSHA1Hash(Data));
}
/// <summary>
/// Computes the SHA-1 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA1HashString(Stream Data)
{
return BinaryToString(ComputeSHA1Hash(Data));
}
/// <summary>
/// Computes the SHA-1 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA1Hash(byte[] Data)
{
byte[] Result;
using (SHA1 SHA1 = SHA1.Create())
{
Result = SHA1.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the SHA-1 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA1Hash(Stream Data)
{
byte[] Result;
using (SHA1 SHA1 = SHA1.Create())
{
Result = SHA1.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the SHA-256 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA256HashString(byte[] Data)
{
return BinaryToString(ComputeSHA256Hash(Data));
}
/// <summary>
/// Computes the SHA-256 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA256HashString(Stream Data)
{
return BinaryToString(ComputeSHA256Hash(Data));
}
/// <summary>
/// Computes the SHA-256 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA256Hash(byte[] Data)
{
byte[] Result;
using (SHA256 SHA256 = SHA256.Create())
{
Result = SHA256.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the SHA-256 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA256Hash(Stream Data)
{
byte[] Result;
using (SHA256 SHA256 = SHA256.Create())
{
Result = SHA256.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the SHA-384 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA384HashString(byte[] Data)
{
return BinaryToString(ComputeSHA384Hash(Data));
}
/// <summary>
/// Computes the SHA-384 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA384HashString(Stream Data)
{
return BinaryToString(ComputeSHA384Hash(Data));
}
/// <summary>
/// Computes the SHA-384 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA384Hash(byte[] Data)
{
byte[] Result;
using (SHA384 SHA384 = SHA384.Create())
{
Result = SHA384.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the SHA-384 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA384Hash(Stream Data)
{
byte[] Result;
using (SHA384 SHA384 = SHA384.Create())
{
Result = SHA384.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the SHA-512 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA512HashString(byte[] Data)
{
return BinaryToString(ComputeSHA512Hash(Data));
}
/// <summary>
/// Computes the SHA-512 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeSHA512HashString(Stream Data)
{
return BinaryToString(ComputeSHA512Hash(Data));
}
/// <summary>
/// Computes the SHA-512 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA512Hash(byte[] Data)
{
byte[] Result;
using (SHA512 SHA512 = SHA512.Create())
{
Result = SHA512.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the SHA-512 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeSHA512Hash(Stream Data)
{
byte[] Result;
using (SHA512 SHA512 = SHA512.Create())
{
Result = SHA512.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the MD5 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeMD5HashString(byte[] Data)
{
return BinaryToString(ComputeMD5Hash(Data));
}
/// <summary>
/// Computes the MD5 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeMD5HashString(Stream Data)
{
return BinaryToString(ComputeMD5Hash(Data));
}
/// <summary>
/// Computes the MD5 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeMD5Hash(byte[] Data)
{
byte[] Result;
using (MD5 MD5 = MD5.Create())
{
Result = MD5.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the MD5 hash of a block of binary data.
/// </summary>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeMD5Hash(Stream Data)
{
byte[] Result;
using (MD5 MD5 = MD5.Create())
{
Result = MD5.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the HMAC-SHA-1 hash of a block of binary data.
/// </summary>
/// <param name="Key">Binary key.</param>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeHMACSHA1HashString(byte[] Key, byte[] Data)
{
return BinaryToString(ComputeHMACSHA1Hash(Key, Data));
}
/// <summary>
/// Computes the HMAC-SHA-1 hash of a block of binary data.
/// </summary>
/// <param name="Key">Binary key.</param>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeHMACSHA1Hash(byte[] Key, byte[] Data)
{
byte[] Result;
using (HMACSHA1 HMACSHA1 = new HMACSHA1(Key))
{
Result = HMACSHA1.ComputeHash(Data);
}
return Result;
}
/// <summary>
/// Computes the HMAC-SHA-256 hash of a block of binary data.
/// </summary>
/// <param name="Key">Binary key.</param>
/// <param name="Data">Binary data.</param>
/// <returns>String representation of hash.</returns>
public static string ComputeHMACSHA256HashString(byte[] Key, byte[] Data)
{
return BinaryToString(ComputeHMACSHA256Hash(Key, Data));
}
/// <summary>
/// Computes the HMAC-SHA-256 hash of a block of binary data.
/// </summary>
/// <param name="Key">Binary key.</param>
/// <param name="Data">Binary data.</param>
/// <returns>Hash value.</returns>
public static byte[] ComputeHMACSHA256Hash(byte[] Key, byte[] Data)
{
byte[] Result;
using (HMACSHA256 HMACSHA256 = new HMACSHA256(Key))
{
Result = HMACSHA256.ComputeHash(Data);
}
return Result;
}
}
} | 24.638448 | 102 | 0.630709 | [
"MIT"
] | Sakul/libranet | Blockcoli.Libra.Net/Crypto/Hashes.cs | 13,970 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "UNG_022e",
"name": [
"幻象",
"Mirage"
],
"text": [
"1/1。",
"1/1."
],
"cardClass": "PRIEST",
"type": "ENCHANTMENT",
"cost": null,
"rarity": null,
"set": "UNGORO",
"collectible": null,
"dbfId": 42497
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_UNG_022e : SimTemplate
{
}
} | 13.407407 | 36 | 0.527624 | [
"MIT"
] | chi-rei-den/Silverfish | cards/UNGORO/UNG/Sim_UNG_022e.cs | 368 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.