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 |
|---|---|---|---|---|---|---|---|---|
// <copyright file="Program.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
/// <summary>
/// ウィンドウを移動する
/// </summary>
namespace MoveWindow {
using System;
internal class Program {
private static int Main(string[] args) {
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options)) {
if (options.Verbose) {
Console.WriteLine("CommandLine Parse Error!");
}
return 1;
}
NativeMethods.MoveWindowEx(options.WindowTitle, options.X, options.Y, options.Width, options.Height);
return 0;
}
}
} | 26.551724 | 114 | 0.554545 | [
"MIT"
] | alllucky1996/MoveWindow | Program.cs | 792 | C# |
using System;
using System.Collections;
using System.IO;
using System.Net.Http;
namespace Elysium.Internal
{
/// <summary>
/// Responsible for serializing the request and response as JSON and adding the proper JSON
/// response header.
/// </summary>
public class JsonHttpPipeline
{
private readonly IJsonSerializer _serializer;
public JsonHttpPipeline() : this(new NewtonsoftJsonSerializer())
{
}
public JsonHttpPipeline(IJsonSerializer serializer)
{
Ensure.ArgumentNotNull(serializer, nameof(serializer));
_serializer = serializer;
}
public void SerializeRequest(IRequest request)
{
Ensure.ArgumentNotNull(request, nameof(request));
if (!request.Headers.ContainsKey("Accept"))
{
request.Headers["Accept"] = "application/json";
}
if (request.Method == HttpMethod.Get || request.Body == null) return;
if (request.Body is string || request.Body is Stream || request.Body is HttpContent) return;
request.Body = _serializer.Serialize(request.Body);
}
public IApiResponse<T> DeserializeResponse<T>(IResponse response)
{
Ensure.ArgumentNotNull(response, nameof(response));
if (response.ContentType != null && response.ContentType.Equals("application/json", StringComparison.Ordinal))
{
var body = response.Body as string;
// simple json does not support the root node being empty. Will submit a pr but in
// the mean time....
if (!string.IsNullOrEmpty(body) && body != "{}")
{
var typeIsDictionary = typeof(IDictionary).IsAssignableFrom(typeof(T));
var typeIsEnumerable = typeof(IEnumerable).IsAssignableFrom(typeof(T));
var responseIsObject = body.StartsWith("{", StringComparison.Ordinal);
// If we're expecting an array, but we get a single object, just wrap it. This
// supports an api that dynamically changes the return type based on the content.
if (!typeIsDictionary && typeIsEnumerable && responseIsObject)
{
body = "[" + body + "]";
}
var json = _serializer.Deserialize<T>(body);
return new ApiResponse<T>(response, json);
}
}
return new ApiResponse<T>(response);
}
}
} | 37.457143 | 122 | 0.573608 | [
"MIT"
] | ElysiumLabs/Elysium-Client | Source/Elysium.Service.Client/Http/JsonHttpPipeline.cs | 2,624 | C# |
using System;
using CMS.Helpers;
using CMS.UIControls;
public partial class CMSModules_PortalEngine_UI_WebParts_WebPartProperties_properties_frameset : CMSWebPartPropertiesPage
{
protected void Page_Load(object sender, EventArgs e)
{
rowsFrameset.Attributes.Add("rows", "*, " + FooterFrameHeight);
frameContent.Attributes.Add("src", "webpartproperties_properties.aspx" + RequestContext.CurrentQueryString);
frameButtons.Attributes.Add("src", "webpartproperties_buttons.aspx" + RequestContext.CurrentQueryString);
}
} | 35.3125 | 121 | 0.761062 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSModules/PortalEngine/UI/WebParts/WebPartProperties_properties_frameset.aspx.cs | 567 | C# |
// clsWebP, by Jose M. Piñeiro
// Website: https://github.com/JosePineiro/WebP-wapper
// Version: 1.0.0.9 (May 23, 2020)
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WebPWrapper;
#pragma warning disable IDE0007 // Use implicit type
namespace WebPTest
{
public partial class WebPExample : Form
{
#region | Constructors |
public WebPExample()
{
this.InitializeComponent();
}
private void WebPExample_Load(object sender, EventArgs e)
{
try {
//Inform of execution mode
this.Text = Application.ProductName + (IntPtr.Size == 8 ? " x64 v" : " x86 v") + Application.ProductVersion;
//Inform of libWebP version
this.Text += " (libwebp v" + WebP.GetVersion() + ")";
} catch (Exception ex) {
MessageBox.Show(ex.Message + "\r\nIn WebPExample.WebPExample_Load", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region << Events >>
/// <summary>
/// Test for load from file function
/// </summary>
private void ButtonLoad_Click(object sender, EventArgs e)
{
try {
using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
openFileDialog.Filter = "Image files (*.webp, *.png, *.tif, *.tiff)|*.webp;*.png;*.tif;*.tiff";
openFileDialog.FileName = "";
if (openFileDialog.ShowDialog() == DialogResult.OK) {
buttonSave.Enabled = true;
buttonSave.Enabled = true;
string pathFileName = openFileDialog.FileName;
if (Path.GetExtension(pathFileName) == ".webp") {
pictureBox.Image = WebP.Load(pathFileName);
} else {
pictureBox.Image = Image.FromFile(pathFileName);
}
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonLoad_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Test for load thumbnail function
/// </summary>
private void ButtonThumbnail_Click(object sender, EventArgs e)
{
try {
using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
openFileDialog.Filter = "WebP files (*.webp)|*.webp";
openFileDialog.FileName = "";
if (openFileDialog.ShowDialog() == DialogResult.OK) {
string pathFileName = openFileDialog.FileName;
byte[] rawWebP = File.ReadAllBytes(pathFileName);
pictureBox.Image = WebP.GetThumbnailQuality(rawWebP, 200, 150);
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonThumbnail_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Test for advanced decode function
/// </summary>
private void ButtonCropFlip_Click(object sender, EventArgs e)
{
try {
using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
openFileDialog.Filter = "WebP files (*.webp)|*.webp";
openFileDialog.FileName = "";
if (openFileDialog.ShowDialog() == DialogResult.OK) {
string pathFileName = openFileDialog.FileName;
byte[] rawWebP = File.ReadAllBytes(pathFileName);
WebPDecoderOptions decoderOptions = new WebPDecoderOptions
{
use_cropping = 1,
crop_top = 10, //Top beginning of crop area
crop_left = 10, //Left beginning of crop area
crop_height = 250, //Height of crop area
crop_width = 300, //Width of crop area
use_threads = 1, //Use multi-threading
flip = 1 //Flip the image
};
pictureBox.Image = WebP.Decode(rawWebP, decoderOptions);
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonCrop_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Test encode functions
/// </summary>
private void ButtonSave_Click(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
byte[] rawWebP;
try {
if (pictureBox.Image == null) {
MessageBox.Show("Please, load an image first");
}
//get the picture box image
Bitmap bmp = (Bitmap)pictureBox.Image;
//Test simple encode in lossy mode in memory with quality 75
string lossyFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SimpleLossy.webp");
rawWebP = WebP.EncodeLossy(bmp, 75);
File.WriteAllBytes(lossyFileName, rawWebP);
MessageBox.Show("Made " + lossyFileName, "Simple lossy");
//Test simple encode in lossless mode in memory
string simpleLosslessFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SimpleLossless.webp");
rawWebP = WebP.EncodeLossless(bmp);
File.WriteAllBytes(simpleLosslessFileName, rawWebP);
MessageBox.Show("Made " + simpleLosslessFileName, "Simple lossless");
//Test encode in lossy mode in memory with quality 75 and speed 9
string advanceLossyFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AdvanceLossy.webp");
WebPAuxStats lossyStats;
rawWebP = WebP.EncodeLossy(bmp, 71, 9, true, out lossyStats);
ShowCompressionStatistics(lossyStats, bmp);
File.WriteAllBytes(advanceLossyFileName, rawWebP);
MessageBox.Show("Made " + advanceLossyFileName, "Advance lossy");
//Test advance encode lossless mode in memory with speed 9
string losslessFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AdvanceLossless.webp");
rawWebP = WebP.EncodeLossless(bmp, 9);
File.WriteAllBytes(losslessFileName, rawWebP);
MessageBox.Show("Made " + losslessFileName, "Advance lossless");
//Test encode near lossless mode in memory with quality 40 and speed 9
// quality 100: No-loss (bit-stream same as -lossless).
// quality 80: Very very high PSNR (around 54dB) and gets an additional 5-10% size reduction over WebP-lossless image.
// quality 60: Very high PSNR (around 48dB) and gets an additional 20%-25% size reduction over WebP-lossless image.
// quality 40: High PSNR (around 42dB) and gets an additional 30-35% size reduction over WebP-lossless image.
// quality 20 (and below): Moderate PSNR (around 36dB) and gets an additional 40-50% size reduction over WebP-lossless image.
string nearLosslessFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NearLossless.webp");
rawWebP = WebP.EncodeNearLossless(bmp, 40, 9);
File.WriteAllBytes(nearLosslessFileName, rawWebP);
MessageBox.Show("Made " + nearLosslessFileName, "Near lossless");
MessageBox.Show("End of Test");
} catch (Exception ex) {
MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonSave_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Test GetPictureDistortion function
/// </summary>
private void ButtonMeasure_Click(object sender, EventArgs e)
{
try {
if (pictureBox.Image == null) {
MessageBox.Show("Please, load an reference image first");
}
using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
openFileDialog.Filter = "WebP images (*.webp)|*.webp";
openFileDialog.FileName = "";
if (openFileDialog.ShowDialog() == DialogResult.OK) {
Bitmap source;
Bitmap reference;
float[] result;
//Load Bitmaps
source = (Bitmap)pictureBox.Image;
reference = WebP.Load(openFileDialog.FileName);
//Measure PSNR
result = WebP.GetPictureDistortion(source, reference, DistorsionMetric.PeakSignalNoiseRatio);
MessageBox.Show("Red: " + result[0] + "dB.\nGreen: " + result[1] + "dB.\nBlue: " + result[2] + "dB.\nAlpha: " + result[3] + "dB.\nAll: " + result[4] + "dB.", "PSNR");
//Measure SSIM
result = WebP.GetPictureDistortion(source, reference, DistorsionMetric.StructuralSimilarity);
MessageBox.Show("Red: " + result[0] + "dB.\nGreen: " + result[1] + "dB.\nBlue: " + result[2] + "dB.\nAlpha: " + result[3] + "dB.\nAll: " + result[4] + "dB.", "SSIM");
//Measure LSIM
result = WebP.GetPictureDistortion(source, reference, DistorsionMetric.LightweightSimilarity);
MessageBox.Show("Red: " + result[0] + "dB.\nGreen: " + result[1] + "dB.\nBlue: " + result[2] + "dB.\nAlpha: " + result[3] + "dB.\nAll: " + result[4] + "dB.", "LSIM");
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonMeasure_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Test GetInfo function
/// </summary>
private void ButtonInfo_Click(object sender, EventArgs e)
{
try {
using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
openFileDialog.Filter = "WebP images (*.webp)|*.webp";
openFileDialog.FileName = "";
if (openFileDialog.ShowDialog() == DialogResult.OK) {
string pathFileName = openFileDialog.FileName;
byte[] rawWebp = File.ReadAllBytes(pathFileName);
WebPInfo info = WebP.GetInfo(rawWebp);
MessageBox.Show("Width: " + info.Width + "\n" +
"Height: " + info.Height + "\n" +
"Has alpha: " + info.HasAlpha + "\n" +
"Is animation: " + info.IsAnimated + "\n" +
"Format: " + info.Format, "Information");
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message + "\r\nIn WebPExample.buttonInfo_Click", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
private static void ShowCompressionStatistics(WebPAuxStats stats, Bitmap gdiPlusImage)
{
MessageBox.Show("Dimensions: " + gdiPlusImage.Width + " x " + gdiPlusImage.Height + " pixels\n" +
"Output: " + stats.coded_size + " bytes\n" +
"PSNR Y: " + stats.PSNRY + " db\n" +
"PSNR u: " + stats.PSNRU + " db\n" +
"PSNR v: " + stats.PSNRV + " db\n" +
"PSNR ALL: " + stats.PSNRALL + " db\n" +
"Block intra4: " + stats.block_count_intra4 + "\n" +
"Block intra16: " + stats.block_count_intra16 + "\n" +
"Block skipped: " + stats.block_count_skipped + "\n" +
"Header size: " + stats.header_bytes + " bytes\n" +
"Mode-partition: " + stats.mode_partition_0 + " bytes\n" +
"Macro-blocks 0: " + stats.segment_size_segments0 + " residuals bytes\n" +
"Macro-blocks 1: " + stats.segment_size_segments1 + " residuals bytes\n" +
"Macro-blocks 2: " + stats.segment_size_segments2 + " residuals bytes\n" +
"Macro-blocks 3: " + stats.segment_size_segments3 + " residuals bytes\n" +
"Quantizer 0: " + stats.segment_quant_segments0 + " residuals bytes\n" +
"Quantizer 1: " + stats.segment_quant_segments1 + " residuals bytes\n" +
"Quantizer 2: " + stats.segment_quant_segments2 + " residuals bytes\n" +
"Quantizer 3: " + stats.segment_quant_segments3 + " residuals bytes\n" +
"Filter level 0: " + stats.segment_level_segments0 + " residuals bytes\n" +
"Filter level 1: " + stats.segment_level_segments1 + " residuals bytes\n" +
"Filter level 2: " + stats.segment_level_segments2 + " residuals bytes\n" +
"Filter level 3: " + stats.segment_level_segments3 + " residuals bytes\n", "Compression statistics");
}
}
} | 41.992565 | 173 | 0.649965 | [
"MIT"
] | repzilon/WebP-wrapper | WebPTest/WebPExample.cs | 11,299 | C# |
// Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
// Licensed MIT: http://www.opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace DNA.Data
{
/// <summary>
/// The Repository interface
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IRepository<T>: IDisposable
where T : class
{
/// <summary>
/// Get all objects
/// </summary>
/// <returns></returns>
IQueryable<T> All();
IQueryable<T> All(out int total, int index = 0, int size = 50);
/// <summary>
/// Get objects by filter expression.
/// </summary>
/// <param name="predicate">The filter expressions</param>
/// <returns>Returns the IQueryable objects for this filter.</returns>
IQueryable<T> Filter(Expression<Func<T, bool>> predicate);
/// <summary>
/// Get objects by filtering and paging specifications.
/// </summary>
/// <typeparam name="Key"></typeparam>
/// <param name="sortingSelector">The default sorting field selector</param>
/// <param name="filter">The filter expressions</param>
/// <param name="total"></param>
/// <param name="sortby"></param>
/// <param name="index"></param>
/// <param name="size"></param>
/// <returns></returns>
IQueryable<T> Filter<Key>(Expression<Func<T, Key>> sortingSelector, Expression<Func<T, bool>> filter, out int total, SortingOrders sortby = SortingOrders.Asc, int index = 0, int size = 50);
/// <summary>
/// Gets the object(s) is exists in database by specified filter.
/// </summary>
/// <param name="predicate">Specified the filter expression</param>
bool Contains(Expression<Func<T, bool>> predicate);
/// <summary>
/// Get the total objects count.
/// </summary>
int Count();
int Count(Expression<Func<T, bool>> predicate);
/// <summary>
/// Find object by keys.
/// </summary>
/// <param name="keys">Specified the search keys.</param>
T Find(params object[] keys);
/// <summary>
/// Find object by specified expression.
/// </summary>
/// <param name="predicate"></param>
T Find(Expression<Func<T, bool>> predicate);
/// <summary>
/// Create a new object to database.
/// </summary>
/// <param name="t">Specified a new object to create.</param>
T Create(T t);
/// <summary>
/// Delete the object from database.
/// </summary>
/// <param name="t">Specified a existing object to delete.</param>
void Delete(T t);
/// <summary>
/// Delete objects from database by specified filter expression.
/// </summary>
/// <param name="predicate"></param>
int Delete(Expression<Func<T, bool>> predicate);
/// <summary>
/// Update object changes and save to database.
/// </summary>
/// <param name="t">Specified the object to save.</param>
T Update(T t);
/// <summary>
/// Clear all data items.
/// </summary>
/// <returns>Total clear item count</returns>
void Clear();
/// <summary>
/// Save all changes.
/// </summary>
/// <returns></returns>
int Submit();
}
}
| 32.87037 | 197 | 0.552113 | [
"MIT"
] | DotNetAge/DNA.Patterns | src/DNA.Patterns/Data/IRepository.cs | 3,552 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Moq;
using WinForms.Common.Tests;
using Xunit;
namespace System.Windows.Forms.Tests
{
public class MenuItemTests
{
[Fact]
public void MenuItem_Ctor_Default()
{
var menuItem = new MenuItem();
Assert.False(menuItem.BarBreak);
Assert.False(menuItem.Break);
Assert.False(menuItem.Checked);
Assert.False(menuItem.DefaultItem);
Assert.True(menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.False(menuItem.IsParent);
Assert.False(menuItem.MdiList);
Assert.Empty(menuItem.MenuItems);
Assert.Equal(0, menuItem.MergeOrder);
Assert.Equal(MenuMerge.Add, menuItem.MergeType);
Assert.Equal('\0', menuItem.Mnemonic);
Assert.False(menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.False(menuItem.RadioCheck);
Assert.True(menuItem.ShowShortcut);
Assert.Equal(Shortcut.None, menuItem.Shortcut);
Assert.True(menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Empty(menuItem.Text);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public void MenuItem_Ctor_String(string text, string expectedText)
{
var menuItem = new MenuItem(text);
Assert.False(menuItem.BarBreak);
Assert.False(menuItem.Break);
Assert.False(menuItem.Checked);
Assert.False(menuItem.DefaultItem);
Assert.True(menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.False(menuItem.IsParent);
Assert.False(menuItem.MdiList);
Assert.Empty(menuItem.MenuItems);
Assert.Equal(0, menuItem.MergeOrder);
Assert.Equal(MenuMerge.Add, menuItem.MergeType);
Assert.Equal('\0', menuItem.Mnemonic);
Assert.False(menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.False(menuItem.RadioCheck);
Assert.True(menuItem.ShowShortcut);
Assert.Equal(Shortcut.None, menuItem.Shortcut);
Assert.True(menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Equal(expectedText, menuItem.Text);
}
public static IEnumerable<object[]> Ctor_String_EventHandler_TestData()
{
EventHandler onClick = (sender, e) => { };
yield return new object[] { null, null, string.Empty };
yield return new object[] { string.Empty, onClick, string.Empty };
yield return new object[] { "text", onClick, "text" };
}
[Theory]
[MemberData(nameof(Ctor_String_EventHandler_TestData))]
public void MenuItem_Ctor_String_EventHandler(string text, EventHandler onClick, string expectedText)
{
var menuItem = new MenuItem(text, onClick);
Assert.False(menuItem.BarBreak);
Assert.False(menuItem.Break);
Assert.False(menuItem.Checked);
Assert.False(menuItem.DefaultItem);
Assert.True(menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.False(menuItem.IsParent);
Assert.False(menuItem.MdiList);
Assert.Empty(menuItem.MenuItems);
Assert.Equal(0, menuItem.MergeOrder);
Assert.Equal(MenuMerge.Add, menuItem.MergeType);
Assert.Equal('\0', menuItem.Mnemonic);
Assert.False(menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.False(menuItem.RadioCheck);
Assert.True(menuItem.ShowShortcut);
Assert.Equal(Shortcut.None, menuItem.Shortcut);
Assert.True(menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Same(expectedText, menuItem.Text);
}
[Fact]
public void MenuItem_Ctor_String_EventHandler_OnClick()
{
SubMenuItem menuItem = null;
int callCount = 0;
EventHandler onClick = (sender, e) =>
{
Assert.Same(menuItem, sender);
callCount++;
};
menuItem = new SubMenuItem("text", onClick);
menuItem.OnClick(null);
Assert.Equal(1, callCount);
}
public static IEnumerable<object[]> Ctor_String_EventHandler_Shortcut_TestData()
{
EventHandler onClick = (sender, e) => { };
yield return new object[] { null, null, Shortcut.None, string.Empty };
yield return new object[] { string.Empty, onClick, (Shortcut)(Shortcut.None - 1), string.Empty };
yield return new object[] { "text", onClick, Shortcut.CtrlA, "text" };
}
[Theory]
[MemberData(nameof(Ctor_String_EventHandler_Shortcut_TestData))]
public void MenuItem_Ctor_String_EventHandler_Shortcut(string text, EventHandler onClick, Shortcut shortcut, string expectedText)
{
var menuItem = new MenuItem(text, onClick, shortcut);
Assert.False(menuItem.BarBreak);
Assert.False(menuItem.Break);
Assert.False(menuItem.Checked);
Assert.False(menuItem.DefaultItem);
Assert.True(menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.False(menuItem.IsParent);
Assert.False(menuItem.MdiList);
Assert.Empty(menuItem.MenuItems);
Assert.Equal(0, menuItem.MergeOrder);
Assert.Equal(MenuMerge.Add, menuItem.MergeType);
Assert.Equal('\0', menuItem.Mnemonic);
Assert.False(menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.False(menuItem.RadioCheck);
Assert.True(menuItem.ShowShortcut);
Assert.Equal(shortcut, menuItem.Shortcut);
Assert.True(menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Same(expectedText, menuItem.Text);
}
[Fact]
public void MenuItem_Ctor_String_EventHandler_Shortcut_OnClick()
{
SubMenuItem menuItem = null;
int callCount = 0;
EventHandler onClick = (sender, e) =>
{
Assert.Same(menuItem, sender);
callCount++;
};
menuItem = new SubMenuItem("text", onClick, Shortcut.None);
menuItem.OnClick(null);
Assert.Equal(1, callCount);
}
public static IEnumerable<object[]> Ctor_String_MenuItemArray_TestData()
{
yield return new object[] { null, null, false, string.Empty };
yield return new object[] { string.Empty, Array.Empty<MenuItem>(), false, string.Empty };
yield return new object[] { "text", new MenuItem[] { new MenuItem() }, true, "text" };
}
[Theory]
[MemberData(nameof(Ctor_String_MenuItemArray_TestData))]
public void MenuItem_Ctor_String_MenuItemArray(string text, MenuItem[] items, bool expectedIsParent, string expectedText)
{
var menuItem = new MenuItem(text, items);
Assert.False(menuItem.BarBreak);
Assert.False(menuItem.Break);
Assert.False(menuItem.Checked);
Assert.False(menuItem.DefaultItem);
Assert.True(menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.Equal(expectedIsParent, menuItem.IsParent);
Assert.False(menuItem.MdiList);
Assert.Equal(items ?? Array.Empty<MenuItem>(), menuItem.MenuItems.Cast<MenuItem>());
Assert.Equal(0, menuItem.MergeOrder);
Assert.Equal(MenuMerge.Add, menuItem.MergeType);
Assert.Equal('\0', menuItem.Mnemonic);
Assert.False(menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.False(menuItem.RadioCheck);
Assert.True(menuItem.ShowShortcut);
Assert.Equal(Shortcut.None, menuItem.Shortcut);
Assert.True(menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Same(expectedText, menuItem.Text);
}
public static IEnumerable<object[]> Ctor_MergeType_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_TestData()
{
EventHandler onClick = (sender, e) => { };
EventHandler onPopup = (sender, e) => { };
EventHandler onSelect = (sender, e) => { };
yield return new object[] { (MenuMerge)(MenuMerge.Add - 1), -1, (Shortcut)(Shortcut.None - 1), null, null, null, null, null, false, string.Empty };
yield return new object[] { MenuMerge.Add, 0, Shortcut.None, string.Empty, onClick, onPopup, onSelect, Array.Empty<MenuItem>(), false, string.Empty };
yield return new object[] { MenuMerge.MergeItems, 1, Shortcut.CtrlA, "text", onClick, onPopup, onSelect, new MenuItem[] { new MenuItem() }, true, "text" };
}
[Theory]
[MemberData(nameof(Ctor_MergeType_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_TestData))]
public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray(MenuMerge mergeType, int mergeOrder, Shortcut shortcut, string text, EventHandler onClick, EventHandler onPopup, EventHandler onSelect, MenuItem[] items, bool expectedIsParent, string expectedText)
{
var menuItem = new MenuItem(mergeType, mergeOrder, shortcut, text, onClick, onPopup, onSelect, items);
Assert.False(menuItem.BarBreak);
Assert.False(menuItem.Break);
Assert.False(menuItem.Checked);
Assert.False(menuItem.DefaultItem);
Assert.True(menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.Equal(expectedIsParent, menuItem.IsParent);
Assert.False(menuItem.MdiList);
Assert.Equal(items ?? Array.Empty<MenuItem>(), menuItem.MenuItems.Cast<MenuItem>());
Assert.Equal(mergeOrder, menuItem.MergeOrder);
Assert.Equal(mergeType, menuItem.MergeType);
Assert.Equal('\0', menuItem.Mnemonic);
Assert.False(menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.False(menuItem.RadioCheck);
Assert.True(menuItem.ShowShortcut);
Assert.Equal(shortcut, menuItem.Shortcut);
Assert.True(menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Same(expectedText, menuItem.Text);
}
[Fact]
public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_OnClick()
{
SubMenuItem menuItem = null;
int callCount = 0;
EventHandler onClick = (sender, e) =>
{
Assert.Same(menuItem, sender);
callCount++;
};
menuItem = new SubMenuItem(MenuMerge.Add, 0, Shortcut.None, string.Empty, onClick, null, null, Array.Empty<MenuItem>());
menuItem.OnClick(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_OnPopup()
{
SubMenuItem menuItem = null;
int callCount = 0;
EventHandler onPopup = (sender, e) =>
{
Assert.Same(menuItem, sender);
callCount++;
};
menuItem = new SubMenuItem(MenuMerge.Add, 0, Shortcut.None, string.Empty, null, onPopup, null, Array.Empty<MenuItem>());
menuItem.OnPopup(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_Ctor_MenuMerge_Int_Shortcut_String_EventHandler_EventHandler_EventHandler_MenuItemArray_OnSelect()
{
SubMenuItem menuItem = null;
int callCount = 0;
EventHandler onSelect = (sender, e) =>
{
Assert.Same(menuItem, sender);
callCount++;
};
menuItem = new SubMenuItem(MenuMerge.Add, 0, Shortcut.None, string.Empty, null, null, onSelect, Array.Empty<MenuItem>());
menuItem.OnSelect(null);
Assert.Equal(1, callCount);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_BarBreak_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
BarBreak = value
};
Assert.Equal(value, menuItem.BarBreak);
}
[Fact]
public void MenuItem_BarBreak_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.BarBreak);
Assert.Throws<ObjectDisposedException>(() => menuItem.BarBreak = true);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_Break_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
Break = value
};
Assert.Equal(value, menuItem.Break);
}
[Fact]
public void MenuItem_Break_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.Break);
Assert.Throws<ObjectDisposedException>(() => menuItem.Break = true);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_Checked_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
Checked = value
};
Assert.Equal(value, menuItem.Checked);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_Checked_SetWithParent_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem();
var menu = new SubMenu(new MenuItem[] { menuItem });
menuItem.Checked = value;
Assert.Equal(value, menuItem.Checked);
}
[Fact]
public void MenuItem_Checked_SetWithMainMenuParent_ThrowsArgumentException()
{
var menuItem = new MenuItem();
var menu = new MainMenu(new MenuItem[] { menuItem });
Assert.Throws<ArgumentException>("value", () => menuItem.Checked = true);
Assert.False(menuItem.Checked);
menuItem.Checked = false;
Assert.False(menuItem.Checked);
}
[Fact]
public void MenuItem_Checked_SetWithChildren_ThrowsArgumentException()
{
var menuItem = new MenuItem("text", new MenuItem[] { new MenuItem() });
Assert.Throws<ArgumentException>("value", () => menuItem.Checked = true);
Assert.False(menuItem.Checked);
menuItem.Checked = false;
Assert.False(menuItem.Checked);
}
[Fact]
public void MenuItem_Checked_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.Checked);
Assert.Throws<ObjectDisposedException>(() => menuItem.Checked = true);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_DefaultItem_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
DefaultItem = value
};
Assert.Equal(value, menuItem.DefaultItem);
}
[Fact]
public void MenuItem_DefaultItem_SetWithParent_GetReturnsExpected()
{
var menuItem = new MenuItem();
var menu = new SubMenu(new MenuItem[] { menuItem });
menuItem.DefaultItem = true;
Assert.True(menuItem.DefaultItem);
// Set same.
menuItem.DefaultItem = true;
Assert.True(menuItem.DefaultItem);
menuItem.DefaultItem = false;
Assert.False(menuItem.DefaultItem);
// Set same.
menuItem.DefaultItem = false;
Assert.False(menuItem.DefaultItem);
}
[Fact]
public void MenuItem_DefaultItem_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.DefaultItem);
Assert.Throws<ObjectDisposedException>(() => menuItem.DefaultItem = true);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_Enabled_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
Enabled = value
};
Assert.Equal(value, menuItem.Enabled);
}
[Fact]
public void MenuItem_Enabled_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.Enabled);
Assert.Throws<ObjectDisposedException>(() => menuItem.Enabled = true);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void MenuItem_Index_SetWithParent_GetReturnsExpected(int value)
{
var menuItem1 = new MenuItem();
var menuItem2 = new MenuItem();
var menu = new SubMenu(new MenuItem[] { menuItem1, menuItem2 });
menuItem1.Index = value;
Assert.Equal(value, menuItem1.Index);
if (value == 0)
{
Assert.Equal(new MenuItem[] { menuItem1, menuItem2 }, menu.MenuItems.Cast<MenuItem>());
}
else
{
Assert.Equal(new MenuItem[] { menuItem2, menuItem1 }, menu.MenuItems.Cast<MenuItem>());
}
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void MenuItem_Index_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
var menuItem = new MenuItem();
var menu = new SubMenu(new MenuItem[] { menuItem });
Assert.Throws<ArgumentOutOfRangeException>("value", () => menuItem.Index = value);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))]
public void MenuItem_Index_SetWithoutParent_Nop(int value)
{
var menuItem = new MenuItem
{
Index = value
};
Assert.Equal(-1, menuItem.Index);
}
public static IEnumerable<object[]> IsParent_TestData()
{
yield return new object[] { new MenuItem { MdiList = true }, new SubMenu(), true };
yield return new object[] { new MenuItem { MdiList = true }, null, false };
yield return new object[] { new MenuItem { MdiList = false }, new SubMenu(), false };
yield return new object[] { new MenuItem { MdiList = false }, new MenuItem(), false };
yield return new object[] { new MenuItem { MdiList = false }, null, false };
foreach (bool mdiList in new bool[] { true, false })
{
yield return new object[] { new MenuItem { MdiList = mdiList }, new MenuItem(), false };
yield return new object[] { new MenuItem { MdiList = mdiList }, null, false };
yield return new object[] { new MenuItem("text", new MenuItem[] { new MenuItem() }) { MdiList = mdiList }, null, true };
}
var disposedItem = new MenuItem("text", Array.Empty<MenuItem>());
disposedItem.Dispose();
yield return new object[] { disposedItem, new SubMenu(), false };
yield return new object[] { new MenuItem { MdiList = true }, new MainMenu(), true };
var nonMdiForm = new Form { Menu = new MainMenu() };
yield return new object[] { new MenuItem { MdiList = true }, nonMdiForm.Menu, true };
var formWithNoMdiChildren = new Form { Menu = new MainMenu() };
formWithNoMdiChildren.Controls.Add(new MdiClient());
yield return new object[] { new MenuItem { MdiList = true }, formWithNoMdiChildren.Menu, true };
var formWithMdiChildren = new Form { Menu = new MainMenu() };
var client = new MdiClient();
formWithMdiChildren.Controls.Add(client);
client.Controls.Add(new Form { MdiParent = formWithMdiChildren });
yield return new object[] { new MenuItem { MdiList = true }, formWithMdiChildren.Menu, true };
}
[Theory]
[MemberData(nameof(IsParent_TestData))]
public void MenuItem_IsParent_HasParent_ReturnsExpected(MenuItem menuItem, Menu parent, bool expected)
{
parent?.MenuItems.Add(menuItem);
Assert.Equal(expected, menuItem.IsParent);
}
[Fact]
public void MenuItem_IsParent_MdiSeparator_ReturnsFalse()
{
var parentForm = new Form { Menu = new MainMenu() };
var parentFormClient = new MdiClient();
parentForm.Controls.Add(parentFormClient);
parentFormClient.Controls.Add(new Form { MdiParent = parentForm });
var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem() }) { MdiList = true };
var parentMenuItem = new MenuItem("parent", new MenuItem[] { menuItem });
parentForm.Menu.MenuItems.Add(parentMenuItem);
// Has a normal child and a MDI item.
menuItem.OnPopup(null);
Assert.True(menuItem.IsParent);
// Has only MDI items.
menuItem.MenuItems.RemoveAt(0);
Assert.Equal("-", Assert.Single(menuItem.MenuItems.Cast<MenuItem>()).Text);
Assert.True(menuItem.IsParent);
// Parent form does not have MDI forms.
parentForm.IsMdiContainer = false;
Assert.Equal("-", Assert.Single(menuItem.MenuItems.Cast<MenuItem>()).Text);
Assert.False(menuItem.IsParent);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_MdiList_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
MdiList = value
};
Assert.Equal(value, menuItem.MdiList);
}
[Fact]
public void MenuItem_MdiList_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.MdiList);
Assert.Throws<ObjectDisposedException>(() => menuItem.MdiList = true);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetIntTheoryData))]
public void MenuItem_MergeOrder_Set_GetReturnsExpected(int value)
{
var menuItem = new MenuItem
{
MergeOrder = value
};
Assert.Equal(value, menuItem.MergeOrder);
}
[Fact]
public void MenuItem_MergeOrder_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.MergeOrder);
Assert.Throws<ObjectDisposedException>(() => menuItem.MergeOrder = 1);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(MenuMerge))]
public void MenuItem_MergeType_Set_GetReturnsExpected(MenuMerge value)
{
var menuItem = new MenuItem
{
MergeType = value
};
Assert.Equal(value, menuItem.MergeType);
}
[Fact]
public void MenuItem_MergeType_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.MergeType);
Assert.Throws<ObjectDisposedException>(() => menuItem.MergeType = MenuMerge.Add);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(MenuMerge))]
public void MenuItem_MergeType_SetInvalid_ThrowsInvalidEnumArgumentException(MenuMerge value)
{
var menuItem = new MenuItem();
Assert.Throws<InvalidEnumArgumentException>("value", () => menuItem.MergeType = value);
}
[Theory]
[InlineData("", '\0')]
[InlineData("text", '\0')]
[InlineData("&&abc", '\0')]
[InlineData("&abc", 'A')]
[InlineData("&", '\0')]
[InlineData("&&", '\0')]
public void MenuItem_Mnemonic_Get_ReturnsExpected(string text, char expected)
{
var menuItem = new MenuItem(text);
Assert.Equal(expected, menuItem.Mnemonic);
}
[Fact]
public void MenuItem_Mneumonic_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.Mnemonic);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_OwnerDraw_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
OwnerDraw = value
};
Assert.Equal(value, menuItem.OwnerDraw);
}
[Fact]
public void MenuItem_OwnerDraw_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.OwnerDraw);
Assert.Throws<ObjectDisposedException>(() => menuItem.OwnerDraw = true);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_RadioCheck_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
RadioCheck = value
};
Assert.Equal(value, menuItem.RadioCheck);
}
[Fact]
public void MenuItem_RadioCheck_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.RadioCheck);
Assert.Throws<ObjectDisposedException>(() => menuItem.RadioCheck = true);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_ShowShortcut_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
ShowShortcut = value
};
Assert.Equal(value, menuItem.ShowShortcut);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_ShowShortcut_SetCreated_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem();
using (var menu = new SubMenu(new MenuItem[] { menuItem }))
{
menuItem.ShowShortcut = value;
Assert.Equal(value, menuItem.ShowShortcut);
}
}
[Fact]
public void MenuItem_ShowShortcut_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.ShowShortcut);
Assert.Throws<ObjectDisposedException>(() => menuItem.ShowShortcut = true);
}
[Theory]
[InlineData(Shortcut.None)]
[InlineData(Shortcut.Ctrl0)]
public void MenuItem_Shortcut_Set_GetReturnsExpected(Shortcut value)
{
var menuItem = new MenuItem
{
Shortcut = value
};
Assert.Equal(value, menuItem.Shortcut);
}
[Theory]
[InlineData(Shortcut.None)]
[InlineData(Shortcut.Ctrl0)]
public void MenuItem_Shortcut_SetCreated_GetReturnsExpected(Shortcut value)
{
var menuItem = new MenuItem();
using (var menu = new SubMenu(new MenuItem[] { menuItem }))
{
menuItem.Shortcut = value;
Assert.Equal(value, menuItem.Shortcut);
}
}
[Theory]
[InlineData((Shortcut)(Shortcut.None - 1))]
public void MenuItem_Shortcut_SetInvalid_ThrowsInvalidEnumArgumentException(Shortcut value)
{
var menuItem = new MenuItem();
Assert.Throws<InvalidEnumArgumentException>("value", () => menuItem.Shortcut = value);
}
[Fact]
public void MenuItem_Shortcut_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.Shortcut);
Assert.Throws<ObjectDisposedException>(() => menuItem.Shortcut = Shortcut.None);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public void MenuItem_Text_Set_GetReturnsExpected(string value, string expected)
{
var menuItem = new MenuItem
{
Text = value
};
Assert.Equal(expected, menuItem.Text);
// Set same.
menuItem.Text = value;
Assert.Equal(expected, menuItem.Text);
}
[Fact]
public void MenuItem_Text_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.Text);
Assert.Throws<ObjectDisposedException>(() => menuItem.Text = string.Empty);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_Visible_Set_GetReturnsExpected(bool value)
{
var menuItem = new MenuItem
{
Visible = value
};
Assert.Equal(value, menuItem.Visible);
// Set same.
menuItem.Visible = value;
Assert.Equal(value, menuItem.Visible);
// Set different.
menuItem.Visible = !value;
Assert.Equal(!value, menuItem.Visible);
}
[Fact]
public void MenuItem_Visible_SetWithMainMenuParent_GetReturnsExpected()
{
var menuItem = new MenuItem();
var menu = new MainMenu(new MenuItem[] { menuItem });
menuItem.Visible = false;
Assert.False(menuItem.Visible);
menuItem.Visible = true;
Assert.True(menuItem.Visible);
}
[Fact]
public void MenuItem_Visible_SetWithHandle_GetReturnsExpected()
{
var menuItem = new MenuItem();
using (var menu = new SubMenu(new MenuItem[] { menuItem }))
{
Assert.NotEqual(IntPtr.Zero, menu.Handle);
menuItem.Visible = false;
Assert.False(menuItem.Visible);
menuItem.Visible = true;
Assert.True(menuItem.Visible);
}
}
[Fact]
public void MenuItem_Visible_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.Visible);
Assert.Throws<ObjectDisposedException>(() => menuItem.Visible = true);
}
[Fact]
public void MenuItem_MenuID_Get_ReturnsExpected()
{
var menuItem = new SubMenuItem();
Assert.NotEqual(0, menuItem.MenuID);
}
[Fact]
public void MenuItem_MenuID_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.MenuID);
}
[Fact]
public void MenuItem_OnClick_Invoke_Success()
{
var menuItem = new SubMenuItem();
// No handler.
menuItem.OnClick(null);
// Handler.
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.Click += handler;
menuItem.OnClick(null);
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.Click -= handler;
menuItem.OnClick(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_OnClick_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.OnClick(null));
}
[Fact]
public void MenuItem_Click_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
EventHandler handler = (sender, e) => { };
Assert.Throws<ObjectDisposedException>(() => menuItem.Click += handler);
Assert.Throws<ObjectDisposedException>(() => menuItem.Click -= handler);
}
[Fact]
public void MenuItem_OnDrawItem_Invoke_Success()
{
var menuItem = new SubMenuItem();
// No handler.
menuItem.OnDrawItem(null);
// Handler.
int callCount = 0;
DrawItemEventHandler handler = (sender, e) =>
{
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.DrawItem += handler;
menuItem.OnDrawItem(null);
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.DrawItem -= handler;
menuItem.OnDrawItem(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_OnDrawItem_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.OnDrawItem(null));
}
[Fact]
public void MenuItem_DrawItem_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
DrawItemEventHandler handler = (sender, e) => { };
Assert.Throws<ObjectDisposedException>(() => menuItem.DrawItem += handler);
Assert.Throws<ObjectDisposedException>(() => menuItem.DrawItem -= handler);
}
[Fact]
public void MenuItem_OnInitMenuPopup_Invoke_Success()
{
var menuItem = new SubMenuItem();
// No handler.
menuItem.OnInitMenuPopup(null);
// Handler.
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.Popup += handler;
menuItem.OnInitMenuPopup(null);
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.Popup -= handler;
menuItem.OnInitMenuPopup(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_OnInitMenuPopup_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.OnInitMenuPopup(null));
}
[Fact]
public void MenuItem_OnMeasureItem_Invoke_Success()
{
var menuItem = new SubMenuItem();
// No handler.
menuItem.OnMeasureItem(null);
// Handler.
int callCount = 0;
MeasureItemEventHandler handler = (sender, e) =>
{
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.MeasureItem += handler;
menuItem.OnMeasureItem(null);
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.MeasureItem -= handler;
menuItem.OnMeasureItem(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_OnMeasureItem_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.OnMeasureItem(null));
}
[Fact]
public void MenuItem_MeasureItem_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
MeasureItemEventHandler handler = (sender, e) => { };
Assert.Throws<ObjectDisposedException>(() => menuItem.MeasureItem += handler);
Assert.Throws<ObjectDisposedException>(() => menuItem.MeasureItem -= handler);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_OnPopup_Invoke_Success(bool mdiList)
{
var menuItem = new SubMenuItem
{
MdiList = mdiList
};
// No handler.
menuItem.OnPopup(null);
// Handler.
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.Popup += handler;
menuItem.OnPopup(null);
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.Popup -= handler;
menuItem.OnPopup(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_OnPopup_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.OnPopup(null));
}
[Fact]
public void MenuItem_Popup_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
EventHandler handler = (sender, e) => { };
Assert.Throws<ObjectDisposedException>(() => menuItem.Popup += handler);
Assert.Throws<ObjectDisposedException>(() => menuItem.Popup -= handler);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public void MenuItem_OnPopup_InvokeWithChildren_Success(bool mdiList)
{
var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem("text") { MdiList = mdiList } });
// No handler.
menuItem.OnPopup(null);
// Handler.
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.Popup += handler;
menuItem.OnPopup(null);
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.Popup -= handler;
menuItem.OnPopup(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_OnPopup_MdiChildrenWithoutParent_DoesNotAddSeparator()
{
var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true };
menuItem.OnPopup(null);
Assert.Equal(new string[] { "child" }, menuItem.MenuItems.Cast<MenuItem>().Select(m => m.Text));
// Calling OnPopup again should not add duplicate items.
menuItem.OnPopup(null);
Assert.Equal(new string[] { "child" }, menuItem.MenuItems.Cast<MenuItem>().Select(m => m.Text));
}
public static IEnumerable<object[]> OnPopup_MdiChildren_TestData()
{
var formWithNoMdiChildren = new Form { Menu = new MainMenu() };
formWithNoMdiChildren.Controls.Add(new MdiClient());
yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, new MainMenu(), new string[] { "child" } };
yield return new object[] { new SubMenuItem("text") { MdiList = true }, formWithNoMdiChildren.Menu, Array.Empty<string>() };
var formWithNoVisibleMdiChildren = new Form { Menu = new MainMenu() };
var formWithNoVisibleMdiChildrenClient = new MdiClient();
formWithNoVisibleMdiChildren.Controls.Add(formWithNoVisibleMdiChildrenClient);
formWithNoVisibleMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithNoVisibleMdiChildren });
yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithNoVisibleMdiChildren.Menu, new string[] { "child", "-" } };
yield return new object[] { new SubMenuItem("text"), formWithNoVisibleMdiChildren.Menu, Array.Empty<string>() };
var formWithMdiChildren = new Form { Menu = new MainMenu(), Visible = true };
var formWithMdiChildrenClient = new MdiClient();
formWithMdiChildren.Controls.Add(formWithMdiChildrenClient);
formWithMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithMdiChildren, Visible = true, Text = "Form" });
yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithMdiChildren.Menu, new string[] { "child", "-", "&1 Form", "&2 Form" } };
var formWithManyMdiChildren = new Form { Menu = new MainMenu(), Visible = true };
var formWithManyMdiChildrenClient = new MdiClient();
formWithManyMdiChildren.Controls.Add(formWithManyMdiChildrenClient);
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form1" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form2" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form3" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form4" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form5" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form6" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form7" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form8" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form9" });
formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form10" });
yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithManyMdiChildren.Menu, new string[] { "child", "-", "&1 Form1", "&2 Form1", "&3 Form2", "&4 Form2", "&5 Form3", "&6 Form3", "&7 Form4", "&8 Form4", "&9 Form10", "&10 Form10", "&More Windows..." } };
var formWithActiveMdiChildren = new SubForm { Menu = new MainMenu(), Visible = true };
var formWithActiveMdiChildrenClient = new MdiClient();
formWithActiveMdiChildren.Controls.Add(formWithActiveMdiChildrenClient);
var activeForm1 = new Form { MdiParent = formWithActiveMdiChildren, Visible = true, Text = "Form2" };
formWithActiveMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveMdiChildren, Visible = true, Text = "Form1" });
formWithActiveMdiChildrenClient.Controls.Add(activeForm1);
formWithActiveMdiChildren.ActivateMdiChild(activeForm1);
yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithActiveMdiChildren.Menu, new string[] { "child", "-", "&1 Form2", "&2 Form1", "&3 Form1", "&4 Form2" } };
var formWithActiveManyMdiChildren = new SubForm { Menu = new MainMenu(), Visible = true };
var formWithActiveManyMdiChildrenClient = new MdiClient();
formWithActiveManyMdiChildren.Controls.Add(formWithActiveManyMdiChildrenClient);
var activeForm2 = new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form11" };
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form1" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form2" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form3" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form4" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form5" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form6" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form7" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form8" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form9" });
formWithActiveManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithActiveManyMdiChildren, Visible = true, Text = "Form10" });
formWithActiveManyMdiChildrenClient.Controls.Add(activeForm2);
formWithActiveManyMdiChildren.ActivateMdiChild(activeForm2);
yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithActiveManyMdiChildren.Menu, new string[] { "child", "-", "&1 Form11", "&2 Form1", "&3 Form1", "&4 Form2", "&5 Form2", "&6 Form3", "&7 Form3", "&8 Form4", "&9 Form4", "&10 Form11", "&More Windows..." } };
}
[Theory]
[MemberData(nameof(OnPopup_MdiChildren_TestData))]
public void MenuItem_OnPopup_MdiChildren_AddsSeparator(SubMenuItem menuItem, Menu parent, string[] expectedItems)
{
try
{
parent.MenuItems.Add(menuItem);
menuItem.OnPopup(null);
Assert.Equal(expectedItems, menuItem.MenuItems.Cast<MenuItem>().Select(m => m.Text));
// Calling OnPopup again should not add duplicate items.
menuItem.OnPopup(null);
Assert.Equal(expectedItems, menuItem.MenuItems.Cast<MenuItem>().Select(m => m.Text));
}
catch
{
string expected = "Expected: " + string.Join(", ", expectedItems.Select(i => "\"" + i + "\""));
string actual = "Actual: " + string.Join(", ", menuItem.MenuItems.Cast<MenuItem>().Select(m => m.Text).Select(i => "\"" + i + "\""));
throw new Exception(expected + Environment.NewLine + actual);
}
}
[Fact]
public void MenuItem_PerformClick_MdiSeparator_Nop()
{
var parentForm = new Form { Menu = new MainMenu() };
var parentFormClient = new MdiClient();
parentForm.Controls.Add(parentFormClient);
parentFormClient.Controls.Add(new Form { MdiParent = parentForm });
var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem() }) { MdiList = true };
parentForm.Menu.MenuItems.Add(menuItem);
menuItem.OnPopup(null);
MenuItem separator = menuItem.MenuItems[1];
Assert.Equal("-", separator.Text);
separator.PerformClick();
}
[Fact]
public void MenuItem_OnSelect_Invoke_Success()
{
var menuItem = new SubMenuItem();
// No handler.
menuItem.OnSelect(null);
// Handler.
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.Select += handler;
menuItem.OnSelect(null);
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.Select -= handler;
menuItem.OnSelect(null);
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_OnSelect_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.OnSelect(null));
}
[Fact]
public void MenuItem_Select_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new SubMenuItem();
menuItem.Dispose();
EventHandler handler = (sender, e) => { };
Assert.Throws<ObjectDisposedException>(() => menuItem.Select += handler);
Assert.Throws<ObjectDisposedException>(() => menuItem.Select -= handler);
}
[Fact]
public void MenuItem_PerformClick_Invoke_Success()
{
var menuItem = new SubMenuItem();
// No handler.
menuItem.PerformClick();
// Handler.
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Equal(EventArgs.Empty, e);
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.Click += handler;
menuItem.PerformClick();
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.Click -= handler;
menuItem.PerformClick();
Assert.Equal(1, callCount);
}
[Fact]
public void MenuItem_PerformSelect_Invoke_Success()
{
var menuItem = new SubMenuItem();
// No handler.
menuItem.PerformSelect();
// Handler.
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Equal(EventArgs.Empty, e);
Assert.Equal(menuItem, sender);
callCount++;
};
menuItem.Select += handler;
menuItem.PerformSelect();
Assert.Equal(1, callCount);
// Should not call if the handler is removed.
menuItem.Select -= handler;
menuItem.PerformSelect();
Assert.Equal(1, callCount);
}
public static IEnumerable<object[]> CloneMenu_TestData()
{
yield return new object[] { Array.Empty<MenuItem>() };
yield return new object[] { new MenuItem[] { new MenuItem("text") } };
}
[Theory]
[MemberData(nameof(CloneMenu_TestData))]
public void MenuItem_CloneMenu_InvokeNew_Success(MenuItem[] items)
{
var source = new MenuItem("text", items)
{
BarBreak = true,
Break = true,
Checked = items.Length == 0,
Enabled = false,
MdiList = true,
MergeOrder = -1,
MergeType = MenuMerge.Remove,
Name = "name",
OwnerDraw = true,
RadioCheck = true,
ShowShortcut = false,
Shortcut = Shortcut.CtrlA,
Site = Mock.Of<ISite>(),
Tag = "tag",
Visible = false
};
var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) });
MenuItem menuItem = source.CloneMenu();
Assert.NotSame(source, menuItem);
Assert.Equal(source.BarBreak, menuItem.BarBreak);
Assert.Equal(source.Break, menuItem.Break);
Assert.Equal(source.Checked, menuItem.Checked);
Assert.Equal(source.DefaultItem, menuItem.DefaultItem);
Assert.Equal(source.Enabled, menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.Equal(source.IsParent, menuItem.IsParent);
Assert.Equal(source.MdiList, menuItem.MdiList);
MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast<MenuItem>().ToArray());
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(i, menuItem.MenuItems[i].Index);
Assert.Equal(menuItem, menuItem.MenuItems[i].Parent);
}
Assert.Equal(source.MergeOrder, menuItem.MergeOrder);
Assert.Equal(source.MergeType, menuItem.MergeType);
Assert.Equal(source.Mnemonic, menuItem.Mnemonic);
Assert.Equal(source.OwnerDraw, menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.Equal(source.RadioCheck, menuItem.RadioCheck);
Assert.Equal(source.ShowShortcut, menuItem.ShowShortcut);
Assert.Equal(source.Shortcut, menuItem.Shortcut);
Assert.Equal(source.Visible, menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Equal(source.Text, menuItem.Text);
}
[Theory]
[MemberData(nameof(CloneMenu_TestData))]
public void MenuItem_CloneMenu_InvokeExisting_Success(MenuItem[] items)
{
var source = new MenuItem("text", items)
{
BarBreak = true,
Break = true,
Checked = items.Length == 0,
Enabled = false,
MdiList = true,
MergeOrder = -1,
MergeType = MenuMerge.Remove,
OwnerDraw = true,
Site = Mock.Of<ISite>(),
Tag = "tag"
};
var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) });
var menuItem = new SubMenuItem();
menuItem.CloneMenu(source);
Assert.False(menuItem.BarBreak);
Assert.False(menuItem.Break);
Assert.False(menuItem.Checked);
Assert.False(menuItem.DefaultItem);
Assert.True(menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.Equal(source.IsParent, menuItem.IsParent);
Assert.False(menuItem.MdiList);
MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast<MenuItem>().ToArray());
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(i, menuItem.MenuItems[i].Index);
Assert.Equal(menuItem, menuItem.MenuItems[i].Parent);
}
Assert.Equal(0, menuItem.MergeOrder);
Assert.Equal(MenuMerge.Add, menuItem.MergeType);
Assert.Equal('\0', menuItem.Mnemonic);
Assert.False(menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.False(menuItem.RadioCheck);
Assert.True(menuItem.ShowShortcut);
Assert.Equal(Shortcut.None, menuItem.Shortcut);
Assert.True(menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Empty(menuItem.Text);
}
[Fact]
public void MenuItem_CloneMenu_NullMenuSource_ThrowsArgumentNullException()
{
var menu = new SubMenuItem("text");
Assert.Throws<ArgumentNullException>("menuSrc", () => menu.CloneMenu(null));
}
[Theory]
[MemberData(nameof(CloneMenu_TestData))]
public void MenuItem_MergeMenu_InvokeNew_Success(MenuItem[] items)
{
var source = new MenuItem("text", items)
{
BarBreak = true,
Break = true,
Checked = items.Length == 0,
Enabled = false,
MdiList = true,
MergeOrder = -1,
MergeType = MenuMerge.Remove,
Name = "name",
OwnerDraw = true,
RadioCheck = true,
ShowShortcut = false,
Shortcut = Shortcut.CtrlA,
Site = Mock.Of<ISite>(),
Tag = "tag",
Visible = false
};
var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) });
MenuItem menuItem = source.MergeMenu();
Assert.NotSame(source, menuItem);
Assert.Equal(source.BarBreak, menuItem.BarBreak);
Assert.Equal(source.Break, menuItem.Break);
Assert.Equal(source.Checked, menuItem.Checked);
Assert.Equal(source.DefaultItem, menuItem.DefaultItem);
Assert.Equal(source.Enabled, menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.Equal(source.IsParent, menuItem.IsParent);
Assert.Equal(source.MdiList, menuItem.MdiList);
MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast<MenuItem>().ToArray());
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(i, menuItem.MenuItems[i].Index);
Assert.Equal(menuItem, menuItem.MenuItems[i].Parent);
}
Assert.Equal(source.MergeOrder, menuItem.MergeOrder);
Assert.Equal(source.MergeType, menuItem.MergeType);
Assert.Equal(source.Mnemonic, menuItem.Mnemonic);
Assert.Equal(source.OwnerDraw, menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.Equal(source.RadioCheck, menuItem.RadioCheck);
Assert.Equal(source.ShowShortcut, menuItem.ShowShortcut);
Assert.Equal(source.Shortcut, menuItem.Shortcut);
Assert.Equal(source.Visible, menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Equal(source.Text, menuItem.Text);
}
[Theory]
[MemberData(nameof(CloneMenu_TestData))]
public void MenuItem_MergeMenu_InvokeExisting_Success(MenuItem[] items)
{
var source = new MenuItem("text", items)
{
BarBreak = true,
Break = true,
Checked = items.Length == 0,
Enabled = false,
MdiList = true,
MergeOrder = -1,
MergeType = MenuMerge.Remove,
Name = "name",
OwnerDraw = true,
RadioCheck = true,
ShowShortcut = false,
Shortcut = Shortcut.CtrlA,
Site = Mock.Of<ISite>(),
Tag = "tag",
Visible = false
};
var menu = new SubMenu(new MenuItem[] { new MenuItem("parent", new MenuItem[] { source }) });
var menuItem = new MenuItem();
menuItem.MergeMenu(source);
Assert.Equal(source.BarBreak, menuItem.BarBreak);
Assert.Equal(source.Break, menuItem.Break);
Assert.Equal(source.Checked, menuItem.Checked);
Assert.Equal(source.DefaultItem, menuItem.DefaultItem);
Assert.Equal(source.Enabled, menuItem.Enabled);
Assert.Equal(-1, menuItem.Index);
Assert.Equal(source.IsParent, menuItem.IsParent);
Assert.Equal(source.MdiList, menuItem.MdiList);
MenuTests.AssertEqualMenuItems(items, menuItem.MenuItems.Cast<MenuItem>().ToArray());
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(i, menuItem.MenuItems[i].Index);
Assert.Equal(menuItem, menuItem.MenuItems[i].Parent);
}
Assert.Equal(source.MergeOrder, menuItem.MergeOrder);
Assert.Equal(source.MergeType, menuItem.MergeType);
Assert.Equal(source.Mnemonic, menuItem.Mnemonic);
Assert.Equal(source.OwnerDraw, menuItem.OwnerDraw);
Assert.Null(menuItem.Parent);
Assert.Equal(source.RadioCheck, menuItem.RadioCheck);
Assert.Equal(source.ShowShortcut, menuItem.ShowShortcut);
Assert.Equal(source.Shortcut, menuItem.Shortcut);
Assert.Equal(source.Visible, menuItem.Visible);
Assert.Empty(menuItem.Name);
Assert.Null(menuItem.Site);
Assert.Null(menuItem.Container);
Assert.Null(menuItem.Tag);
Assert.Equal(source.Text, menuItem.Text);
}
[Fact]
public void MenuItem_MergeMenu_OnClick_Success()
{
var source = new SubMenuItem();
int sourceCallCount = 0;
source.Click += (sender, e) =>
{
sourceCallCount++;
Assert.Equal(source, sender);
Assert.Equal(EventArgs.Empty, e);
};
SubMenuItem destination = Assert.IsType<SubMenuItem>(source.MergeMenu());
int destinationCallCount = 0;
destination.Click += (sender, e) =>
{
destinationCallCount++;
Assert.Equal(source, sender);
Assert.Equal(EventArgs.Empty, e);
};
destination.OnClick(EventArgs.Empty);
Assert.Equal(1, sourceCallCount);
Assert.Equal(1, destinationCallCount);
source.OnClick(EventArgs.Empty);
Assert.Equal(2, sourceCallCount);
Assert.Equal(2, destinationCallCount);
}
[Fact]
public void MenuItem_MergeMenu_OnDrawItem_Success()
{
var source = new SubMenuItem();
int sourceCallCount = 0;
source.DrawItem += (sender, e) =>
{
sourceCallCount++;
Assert.Equal(source, sender);
Assert.Null(e);
};
SubMenuItem destination = Assert.IsType<SubMenuItem>(source.MergeMenu());
int destinationCallCount = 0;
destination.DrawItem += (sender, e) =>
{
destinationCallCount++;
Assert.Equal(source, sender);
Assert.Null(e);
};
destination.OnDrawItem(null);
Assert.Equal(1, sourceCallCount);
Assert.Equal(1, destinationCallCount);
source.OnDrawItem(null);
Assert.Equal(2, sourceCallCount);
Assert.Equal(2, destinationCallCount);
}
[Fact]
public void MenuItem_MergeMenu_OnMeasureItem_Success()
{
var source = new SubMenuItem();
int sourceCallCount = 0;
source.MeasureItem += (sender, e) =>
{
sourceCallCount++;
Assert.Equal(source, sender);
Assert.Null(e);
};
SubMenuItem destination = Assert.IsType<SubMenuItem>(source.MergeMenu());
int destinationCallCount = 0;
destination.MeasureItem += (sender, e) =>
{
destinationCallCount++;
Assert.Equal(source, sender);
Assert.Null(e);
};
destination.OnMeasureItem(null);
Assert.Equal(1, sourceCallCount);
Assert.Equal(1, destinationCallCount);
source.OnMeasureItem(null);
Assert.Equal(2, sourceCallCount);
Assert.Equal(2, destinationCallCount);
}
[Fact]
public void MenuItem_MergeMenu_OnPopup_Success()
{
var source = new SubMenuItem();
int sourceCallCount = 0;
source.Popup += (sender, e) =>
{
sourceCallCount++;
Assert.Equal(source, sender);
Assert.Equal(EventArgs.Empty, e);
};
SubMenuItem destination = Assert.IsType<SubMenuItem>(source.MergeMenu());
int destinationCallCount = 0;
destination.Popup += (sender, e) =>
{
destinationCallCount++;
Assert.Equal(source, sender);
Assert.Equal(EventArgs.Empty, e);
};
destination.OnPopup(EventArgs.Empty);
Assert.Equal(1, sourceCallCount);
Assert.Equal(1, destinationCallCount);
source.OnPopup(EventArgs.Empty);
Assert.Equal(2, sourceCallCount);
Assert.Equal(2, destinationCallCount);
}
[Fact]
public void MenuItem_MergeMenu_OnSelect_Success()
{
var source = new SubMenuItem();
int sourceCallCount = 0;
source.Select += (sender, e) =>
{
sourceCallCount++;
Assert.Equal(source, sender);
Assert.Equal(EventArgs.Empty, e);
};
SubMenuItem destination = Assert.IsType<SubMenuItem>(source.MergeMenu());
int destinationCallCount = 0;
destination.Select += (sender, e) =>
{
destinationCallCount++;
Assert.Equal(source, sender);
Assert.Equal(EventArgs.Empty, e);
};
destination.OnSelect(EventArgs.Empty);
Assert.Equal(1, sourceCallCount);
Assert.Equal(1, destinationCallCount);
source.OnSelect(EventArgs.Empty);
Assert.Equal(2, sourceCallCount);
Assert.Equal(2, destinationCallCount);
}
[Fact]
public void MenuItem_MergeMenu_NullMenuSource_ThrowsArgumentNullException()
{
var menu = new MenuItem("text");
Assert.Throws<ArgumentNullException>("menuSrc", () => menu.MergeMenu(null));
}
[Fact]
public void MenuItem_MergeMenu_Disposed_ThrowsObjectDisposedException()
{
var menuItem = new MenuItem();
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.MergeMenu());
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))]
public void MenuItem_ToString_Invoke_ReturnsExpected(string text)
{
var menuItem = new MenuItem
{
Text = text
};
Assert.Equal("System.Windows.Forms.MenuItem, Items.Count: 0, Text: " + text, menuItem.ToString());
}
[Fact]
public void MenuItem_Dispose_NoParentOrChildren_Success()
{
var menuItem = new MenuItem("text", Array.Empty<MenuItem>());
menuItem.Dispose();
menuItem.Dispose();
}
[Fact]
public void MenuItem_Dispose_NoParent_Success()
{
var childMenuItem = new MenuItem();
var menuItem = new MenuItem("text", new MenuItem[] { childMenuItem });
menuItem.Dispose();
Assert.Null(childMenuItem.Parent);
Assert.Empty(menuItem.MenuItems);
menuItem.Dispose();
Assert.Empty(menuItem.MenuItems);
}
[Fact]
public void MenuItem_Dispose_HasParent_Success()
{
var childMenuItem = new MenuItem();
var menuItem = new MenuItem("text", new MenuItem[] { childMenuItem });
childMenuItem.Dispose();
Assert.Null(childMenuItem.Parent);
Assert.Empty(menuItem.MenuItems);
childMenuItem.Dispose();
Assert.Empty(menuItem.MenuItems);
}
[Fact]
public void MenuItem_Dispose_HasMenuId_Success()
{
var menuItem = new SubMenuItem();
Assert.NotEqual(0, menuItem.MenuID);
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.MenuID);
menuItem.Dispose();
Assert.Throws<ObjectDisposedException>(() => menuItem.MenuID);
}
public class SubMenuItem : MenuItem
{
public SubMenuItem()
{
}
public SubMenuItem(string text) : base(text)
{
}
public SubMenuItem(string text, EventHandler onClick) : base(text, onClick)
{
}
public SubMenuItem(string text, MenuItem[] items) : base(text, items)
{
}
public SubMenuItem(string text, EventHandler onClick, Shortcut shortcut) : base(text, onClick, shortcut)
{
}
public SubMenuItem(MenuMerge mergeType, int mergeOrder, Shortcut shortcut, string text, EventHandler onClick, EventHandler onPopup, EventHandler onSelect, MenuItem[] items) : base(mergeType, mergeOrder, shortcut, text, onClick, onPopup, onSelect, items)
{
}
public new int MenuID => base.MenuID;
public new void OnClick(EventArgs e) => base.OnClick(e);
public new void OnDrawItem(DrawItemEventArgs e) => base.OnDrawItem(e);
public new void OnInitMenuPopup(EventArgs e) => base.OnInitMenuPopup(e);
public new void OnMeasureItem(MeasureItemEventArgs e) => base.OnMeasureItem(e);
public new void OnPopup(EventArgs e) => base.OnPopup(e);
public new void OnSelect(EventArgs e) => base.OnSelect(e);
public new void CloneMenu(Menu menuSrc) => base.CloneMenu(menuSrc);
}
private class SubMenu : Menu
{
public SubMenu(params MenuItem[] items) : base(items)
{
}
}
private class SubForm : Form
{
public new void ActivateMdiChild(Form form) => base.ActivateMdiChild(form);
}
}
}
| 40.090513 | 337 | 0.579931 | [
"MIT"
] | 15835229565/winforms-1 | src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs | 73,528 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using Zenject;
public class Wall : MonoBehaviour
{
[SerializeField]
private float healthPoints;
[SerializeField]
private Animator cracks;
[SerializeField]
private int lifes;
[SerializeField]
private VideoPlayer collapse;
private float currentHealthPoints;
[Inject]
private GameManager gameManager;
private AudioSource crackingSound;
private void Start ()
{
currentHealthPoints = healthPoints;
crackingSound = GetComponent<AudioSource> ();
}
public void Damage (float damage)
{
if (!gameManager.IsPlaying) return;
currentHealthPoints -= damage;
if (currentHealthPoints <= 0)
Break ();
}
public void Break ()
{
lifes--;
currentHealthPoints = healthPoints;
cracks.SetTrigger ("Crack");
if (lifes == 0)
Collapse ();
crackingSound.Play ();
}
private void Collapse ()
{
collapse.gameObject.SetActive (true);
collapse.Play ();
gameManager.EndGame ();
}
}
| 19.150943 | 47 | 0.731034 | [
"Apache-2.0"
] | halzate93/ar-climbing-wall | Assets/Scripts/Wall.cs | 1,017 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using BeeGame.Terrain.LandGeneration;
namespace BeeGame.Terrain.Chunks
{
/// <summary>
/// Loads the <see cref="Chunk"/>s around the player
/// </summary>
public class LoadChunks : MonoBehaviour
{
#region Data
/// <summary>
/// The world the player is in
/// </summary>
public World world;
/// <summary>
/// List if chunks to build
/// </summary>
private List<ChunkWorldPos> buildList = new List<ChunkWorldPos>();
/// <summary>
/// Positions to make chunks aroud the player
/// /// </summary>
private static ChunkWorldPos[] chunkPositions = new ChunkWorldPos[] { new ChunkWorldPos( 0, 0, 0), new ChunkWorldPos(-1, 0, 0), new ChunkWorldPos( 0, 0, -1), new ChunkWorldPos( 0, 0, 1), new ChunkWorldPos( 1, 0, 0),
new ChunkWorldPos(-1, 0, -1), new ChunkWorldPos(-1, 0, 1), new ChunkWorldPos( 1, 0, -1), new ChunkWorldPos( 1, 0, 1), new ChunkWorldPos(-2, 0, 0),
new ChunkWorldPos( 0, 0, -2), new ChunkWorldPos( 0, 0, 2), new ChunkWorldPos( 2, 0, 0), new ChunkWorldPos(-2, 0, -1), new ChunkWorldPos(-2, 0, 1),
new ChunkWorldPos(-1, 0, -2), new ChunkWorldPos(-1, 0, 2), new ChunkWorldPos( 1, 0, -2), new ChunkWorldPos( 1, 0, 2), new ChunkWorldPos( 2, 0, -1),
new ChunkWorldPos( 2, 0, 1), new ChunkWorldPos(-2, 0, -2), new ChunkWorldPos(-2, 0, 2), new ChunkWorldPos( 2, 0, -2), new ChunkWorldPos( 2, 0, 2),
new ChunkWorldPos(-3, 0, 0), new ChunkWorldPos( 0, 0, -3), new ChunkWorldPos( 0, 0, 3), new ChunkWorldPos( 3, 0, 0), new ChunkWorldPos(-3, 0, -1),
new ChunkWorldPos(-3, 0, 1), new ChunkWorldPos(-1, 0, -3), new ChunkWorldPos(-1, 0, 3), new ChunkWorldPos( 1, 0, -3), new ChunkWorldPos( 1, 0, 3),
new ChunkWorldPos( 3, 0, -1), new ChunkWorldPos( 3, 0, 1), new ChunkWorldPos(-3, 0, -2), new ChunkWorldPos(-3, 0, 2), new ChunkWorldPos(-2, 0, -3),
new ChunkWorldPos(-2, 0, 3), new ChunkWorldPos( 2, 0, -3), new ChunkWorldPos( 2, 0, 3), new ChunkWorldPos( 3, 0, -2), new ChunkWorldPos( 3, 0, 2),
new ChunkWorldPos(-4, 0, 0), new ChunkWorldPos( 0, 0, -4), new ChunkWorldPos( 0, 0, 4), new ChunkWorldPos( 4, 0, 0), new ChunkWorldPos(-4, 0, -1),
new ChunkWorldPos(-4, 0, 1), new ChunkWorldPos(-1, 0, -4), new ChunkWorldPos(-1, 0, 4), new ChunkWorldPos( 1, 0, -4), new ChunkWorldPos( 1, 0, 4),
new ChunkWorldPos( 4, 0, -1), new ChunkWorldPos( 4, 0, 1), new ChunkWorldPos(-3, 0, -3), new ChunkWorldPos(-3, 0, 3), new ChunkWorldPos( 3, 0, -3),
new ChunkWorldPos( 3, 0, 3), new ChunkWorldPos(-4, 0, -2), new ChunkWorldPos(-4, 0, 2), new ChunkWorldPos(-2, 0, -4), new ChunkWorldPos(-2, 0, 4),
new ChunkWorldPos( 2, 0, -4), new ChunkWorldPos( 2, 0, 4), new ChunkWorldPos( 4, 0, -2), new ChunkWorldPos( 4, 0, 2), new ChunkWorldPos(-5, 0, 0),
new ChunkWorldPos(-4, 0, -3), new ChunkWorldPos(-4, 0, 3), new ChunkWorldPos(-3, 0, -4), new ChunkWorldPos(-3, 0, 4), new ChunkWorldPos( 0, 0, -5),
new ChunkWorldPos( 0, 0, 5), new ChunkWorldPos( 3, 0, -4), new ChunkWorldPos( 3, 0, 4), new ChunkWorldPos( 4, 0, -3), new ChunkWorldPos( 4, 0, 3),
new ChunkWorldPos( 5, 0, 0), new ChunkWorldPos(-5, 0, -1), new ChunkWorldPos(-5, 0, 1), new ChunkWorldPos(-1, 0, -5), new ChunkWorldPos(-1, 0, 5),
new ChunkWorldPos( 1, 0, -5), new ChunkWorldPos( 1, 0, 5), new ChunkWorldPos( 5, 0, -1), new ChunkWorldPos( 5, 0, 1), new ChunkWorldPos(-5, 0, -2),
new ChunkWorldPos(-5, 0, 2), new ChunkWorldPos(-2, 0, -5), new ChunkWorldPos(-2, 0, 5), new ChunkWorldPos( 2, 0, -5), new ChunkWorldPos( 2, 0, 5),
new ChunkWorldPos( 5, 0, -2), new ChunkWorldPos( 5, 0, 2), new ChunkWorldPos(-4, 0, -4), new ChunkWorldPos(-4, 0, 4), new ChunkWorldPos( 4, 0, -4),
new ChunkWorldPos( 4, 0, 4), new ChunkWorldPos(-5, 0, -3), new ChunkWorldPos(-5, 0, 3), new ChunkWorldPos(-3, 0, -5), new ChunkWorldPos(-3, 0, 5),
new ChunkWorldPos( 3, 0, -5), new ChunkWorldPos( 3, 0, 5), new ChunkWorldPos( 5, 0, -3), new ChunkWorldPos( 5, 0, 3), new ChunkWorldPos(-6, 0, 0),
new ChunkWorldPos( 0, 0, -6), new ChunkWorldPos( 0, 0, 6), new ChunkWorldPos( 6, 0, 0), new ChunkWorldPos(-6, 0, -1), new ChunkWorldPos(-6, 0, 1),
new ChunkWorldPos(-1, 0, -6), new ChunkWorldPos(-1, 0, 6), new ChunkWorldPos( 1, 0, -6), new ChunkWorldPos( 1, 0, 6), new ChunkWorldPos( 6, 0, -1),
new ChunkWorldPos( 6, 0, 1), new ChunkWorldPos(-6, 0, -2), new ChunkWorldPos(-6, 0, 2), new ChunkWorldPos(-2, 0, -6), new ChunkWorldPos(-2, 0, 6),
new ChunkWorldPos( 2, 0, -6), new ChunkWorldPos( 2, 0, 6), new ChunkWorldPos( 6, 0, -2), new ChunkWorldPos( 6, 0, 2), new ChunkWorldPos(-5, 0, -4),
new ChunkWorldPos(-5, 0, 4), new ChunkWorldPos(-4, 0, -5), new ChunkWorldPos(-4, 0, 5), new ChunkWorldPos( 4, 0, -5), new ChunkWorldPos( 4, 0, 5),
new ChunkWorldPos( 5, 0, -4), new ChunkWorldPos( 5, 0, 4), new ChunkWorldPos(-6, 0, -3), new ChunkWorldPos(-6, 0, 3), new ChunkWorldPos(-3, 0, -6),
new ChunkWorldPos(-3, 0, 6), new ChunkWorldPos( 3, 0, -6), new ChunkWorldPos( 3, 0, 6), new ChunkWorldPos( 6, 0, -3), new ChunkWorldPos( 6, 0, 3),
new ChunkWorldPos(-7, 0, 0), new ChunkWorldPos( 0, 0, -7), new ChunkWorldPos( 0, 0, 7), new ChunkWorldPos( 7, 0, 0), new ChunkWorldPos(-7, 0, -1),
new ChunkWorldPos(-7, 0, 1), new ChunkWorldPos(-5, 0, -5), new ChunkWorldPos(-5, 0, 5), new ChunkWorldPos(-1, 0, -7), new ChunkWorldPos(-1, 0, 7),
new ChunkWorldPos( 1, 0, -7), new ChunkWorldPos( 1, 0, 7), new ChunkWorldPos( 5, 0, -5), new ChunkWorldPos( 5, 0, 5), new ChunkWorldPos( 7, 0, -1),
new ChunkWorldPos( 7, 0, 1), new ChunkWorldPos(-6, 0, -4), new ChunkWorldPos(-6, 0, 4), new ChunkWorldPos(-4, 0, -6), new ChunkWorldPos(-4, 0, 6),
new ChunkWorldPos( 4, 0, -6), new ChunkWorldPos( 4, 0, 6), new ChunkWorldPos( 6, 0, -4), new ChunkWorldPos( 6, 0, 4), new ChunkWorldPos(-7, 0, -2),
new ChunkWorldPos(-7, 0, 2), new ChunkWorldPos(-2, 0, -7), new ChunkWorldPos(-2, 0, 7), new ChunkWorldPos( 2, 0, -7), new ChunkWorldPos( 2, 0, 7),
new ChunkWorldPos( 7, 0, -2), new ChunkWorldPos( 7, 0, 2), new ChunkWorldPos(-7, 0, -3), new ChunkWorldPos(-7, 0, 3), new ChunkWorldPos(-3, 0, -7),
new ChunkWorldPos(-3, 0, 7), new ChunkWorldPos( 3, 0, -7), new ChunkWorldPos( 3, 0, 7), new ChunkWorldPos( 7, 0, -3), new ChunkWorldPos( 7, 0, 3),
new ChunkWorldPos(-6, 0, -5), new ChunkWorldPos(-6, 0, 5), new ChunkWorldPos(-5, 0, -6), new ChunkWorldPos(-5, 0, 6), new ChunkWorldPos( 5, 0, -6),
new ChunkWorldPos( 5, 0, 6), new ChunkWorldPos( 6, 0, -5), new ChunkWorldPos( 6, 0, 5) };
/// <summary>
/// <see cref="Chunk"/>s in a 3x3 radius around the player that should have a collision mesh
/// </summary>
private static ChunkWorldPos[] nearbyChunks = new ChunkWorldPos[] { new ChunkWorldPos(0, 0, 0), new ChunkWorldPos(1, 0, 0), new ChunkWorldPos(-1, 0, 0), new ChunkWorldPos(0, 0, 1), new ChunkWorldPos(0, 0, -1),
new ChunkWorldPos(1, 0, 1), new ChunkWorldPos(1, 0, -1), new ChunkWorldPos(-1, 0, 1), new ChunkWorldPos(-1, 0, -1)};
/// <summary>
/// Timer for chunk removal
/// </summary>
private static int timer = 0;
#endregion
/// <summary>
/// Sets the world
/// </summary>
private void Start()
{
LandGeneration.Terrain.world = world;
}
/// <summary>
/// Builds, Renders, and Remmoves <see cref="Chunk"/>s
/// </summary>
void Update()
{
if (DeleteChunks())
return;
if (!world.chunkHasMadeCollisionMesh)
{
FindChunksToLoad();
LoadAndRenderChunks();
ApplyCollsionMeshToNearbyChunks();
}
//* stops chunks being made and collision meshes being made at the same time
world.chunkHasMadeCollisionMesh = false;
}
/// <summary>
/// Makes a collsion mesh for the <see cref="Chunk"/>s nearest to the player to reduce lag created by PhysX mesh bakeing
/// </summary>
/// <remarks>
/// We dont need to worry about removeing <see cref="Chunk"/> collision meshes as once PhysX has baked then they have minimal performance impact
/// Doing things this wayt also spreads out the PhysX mesh bakeing
/// </remarks>
void ApplyCollsionMeshToNearbyChunks()
{
//* gets the player position in chunk coordinates
ChunkWorldPos playerPos = new ChunkWorldPos(Mathf.FloorToInt(transform.position.x / Chunk.chunkSize) * Chunk.chunkSize, Mathf.FloorToInt(transform.position.y / Chunk.chunkSize) * Chunk.chunkSize, Mathf.FloorToInt(transform.position.z / Chunk.chunkSize) * Chunk.chunkSize);
for (int i = 0; i < nearbyChunks.Length; i++)
{
ChunkWorldPos chunkPos = new ChunkWorldPos(nearbyChunks[i].x * Chunk.chunkSize + playerPos.x, 0, nearbyChunks[i].z * Chunk.chunkSize + playerPos.z);
for (int j = -1; j < 2; j++)
{
Chunk nearbyChunk = world.GetChunk(chunkPos.x, j * Chunk.chunkSize, chunkPos.z);
if (nearbyChunk != null)
nearbyChunk.applyCollisionMesh = true;
}
}
}
/// <summary>
/// Gets the chunks that sould be built and renders then renders them
/// </summary>
void LoadAndRenderChunks()
{
//* if their is somethign in the build list new chunks can be made
if (buildList.Count != 0)
{
//* makes all of the chunks in the build list. Works backwards through the list so that no chunk is missed because chunks are removed from the list as they are made
for (int i = buildList.Count - 1, j = 0; i >= 0 && j < 8; i--, j++)
{
BuildChunk(buildList[0]);
buildList.RemoveAt(0);
}
}
}
/// <summary>
/// Finds the <see cref="Chunk"/>s that should be rendered
/// </summary>
void FindChunksToLoad()
{
if (buildList.Count == 0)
{
//* gets the player position in chunk coordinates
ChunkWorldPos playerPos = new ChunkWorldPos(Mathf.FloorToInt(transform.position.x / Chunk.chunkSize) * Chunk.chunkSize, Mathf.FloorToInt(transform.position.y / Chunk.chunkSize) * Chunk.chunkSize, Mathf.FloorToInt(transform.position.z / Chunk.chunkSize) * Chunk.chunkSize);
//* check all of the chunk positions and if that position does not have a chunk in it make it
for (int i = 0; i < chunkPositions.Length; i++)
{
ChunkWorldPos newChunkPos = new ChunkWorldPos(chunkPositions[i].x * Chunk.chunkSize + playerPos.x, 0, chunkPositions[i].z * Chunk.chunkSize + playerPos.z);
Chunk newChunk = world.GetChunk(newChunkPos.x, newChunkPos.y, newChunkPos.z);
if (newChunk != null && (newChunk.rendered || buildList.Contains(newChunkPos)))
continue;
for (int y = -1; y < 2; y++)
{
for (int x = newChunkPos.x - Chunk.chunkSize; x < newChunkPos.x + Chunk.chunkSize; x += Chunk.chunkSize)
{
for (int z = newChunkPos.z - Chunk.chunkSize; z < newChunkPos.z + Chunk.chunkSize; z += Chunk.chunkSize)
{
buildList.Add(new ChunkWorldPos(x, y * Chunk.chunkSize, z));
}
}
}
return;
}
}
}
/// <summary>
/// Makes a chunk in the given positon if it does not already exist
/// </summary>
/// <param name="pos">hte positon of the new chunk</param>
void BuildChunk(ChunkWorldPos pos)
{
if (world.GetChunk(pos.x, pos.y, pos.z) == null)
world.CreateChunk(pos.x, pos.y, pos.z);
}
/// <summary>
/// Destroys <see cref="Chunk"/>s every 10 calls
/// </summary>
/// <returns>true if <see cref="Chunk"/>s were destroyed</returns>
bool DeleteChunks()
{
//* destroys every 10 call to reduce load on CPU so that chunks are not destroyed and created at the same time
if(timer == 10)
{
timer = 0;
var chunksToDelete = new List<ChunkWorldPos>();
// *go through all of the built chunks and if the chunk is 256 units away it is assumed to be out of sight so is added to the destroy list
foreach (var chunk in world.chunks)
{
float distance = Vector3.Distance(chunk.Value.transform.position, transform.position);
if (distance > 256)
chunksToDelete.Add(chunk.Key);
}
foreach (var chunk in chunksToDelete)
{
world.DestroyChunk(chunk.x, chunk.y, chunk.z);
}
return true;
}
timer++;
return false;
}
}
} | 64.548673 | 288 | 0.529819 | [
"MIT"
] | aliostad/deep-learning-lang-detection | data/train/csharp/49620b56945d2bdacfc06f833e9894d2df81b8f3LoadChunks.cs | 14,590 | C# |
using System.ComponentModel;
namespace AntData.ORM.Enums
{
/// <summary>
/// Sql指令类型
/// </summary>
public enum StatementType
{
/// <summary>
/// Sql语句
/// </summary>
[Description("Sql语句")]
Sql = 0,
/// <summary>
/// 存贮过程
/// </summary>
[Description("存储过程")]
StoredProcedure = 1
}
} | 17.681818 | 30 | 0.465296 | [
"MIT"
] | yuzd/AntData.ORM | AntData/AntData.ORM/DbEngine/Enums/StatementType.cs | 423 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarWeapon : MonoBehaviour
{
[SerializeField] private AutoAttack autoAttack = null;
[SerializeField] private Animator anim = null;
private CarInfo carInfo = null;
public void Init(CarInfo carInfo)
{
this.carInfo = carInfo;
this.autoAttack.Init(carInfo.bullet, carInfo.atkSpd, carInfo.reload, carInfo.atk, SetFireAnimActive);
}
public void SetFireAnimActive(bool active)
{
anim.SetBool("Fire", active);
}
}
| 27.619048 | 110 | 0.681034 | [
"MIT"
] | HEE-SUK/Country_Road | Assets/GameResources/Scripts/Component/CarWeapon.cs | 582 | C# |
namespace Werd.Views
{
//This was fun https://github.com/microsoft/microsoft-ui-xaml/issues/1949#issuecomment-596837959
[Windows.UI.Xaml.Data.Bindable]
public sealed class TagsWebView : ShackWebView { }
}
| 29.857143 | 97 | 0.77512 | [
"MIT"
] | boarder2/Latest-Chatty-8 | Werd/Views/TagsWebView.cs | 211 | C# |
// Authors: Robert M. Scheller, Brian Miranda
// BDA originally programmed by Wei (Vera) Li at University of Missouri-Columbia in 2004.
using System;
using System.Collections.Generic;
using System.Linq;
//using System.Text;
using Landis.Library.Metadata;
using Landis.Utilities;
using Landis.Core;
namespace Landis.Extension.BiomassBDA
{
public static class MetadataHandler
{
public static ExtensionMetadata Extension {get; set;}
public static void InitializeMetadata(int Timestep,
string severityMapFileName,
string srdMapFileName,
string nrdMapFileName,
string logFileName,
IEnumerable<IAgent> manyAgentParameters,
ICore mCore)
{
ScenarioReplicationMetadata scenRep = new ScenarioReplicationMetadata() {
//String outputFolder = OutputPath.ReplaceTemplateVars("", FINISH ME LATER);
//FolderName = System.IO.Directory.GetCurrentDirectory().Split("\\".ToCharArray()).Last(),
RasterOutCellArea = PlugIn.ModelCore.CellArea,
TimeMin = PlugIn.ModelCore.StartTime,
TimeMax = PlugIn.ModelCore.EndTime,
//ProjectionFilePath = "Projection.?" //How do we get projections???
};
Extension = new ExtensionMetadata(mCore){
Name = PlugIn.ExtensionName,
TimeInterval = Timestep, //change this to PlugIn.TimeStep for other extensions
ScenarioReplicationMetadata = scenRep
};
//---------------------------------------
// table outputs:
//---------------------------------------
PlugIn.EventLog = new MetadataTable<EventsLog>(logFileName);
//PlugIn.EventLog = new MetadataTable<EventsLog>("biomass-bda-log.csv");
OutputMetadata tblOut_events = new OutputMetadata()
{
Type = OutputType.Table,
Name = "EventLog",
FilePath = PlugIn.EventLog.FilePath,
Visualize = false,
};
tblOut_events.RetriveFields(typeof(EventsLog));
Extension.OutputMetadatas.Add(tblOut_events);
//PlugIn.PDSILog = new MetadataTable<PDSI_Log>("PDSI_log.csv");
//OutputMetadata tblOut_PDSI = new OutputMetadata()
//{
// Type = OutputType.Table,
// Name = "PDSILog",
// FilePath = PlugIn.PDSILog.FilePath
//};
//tblOut_events.RetriveFields(typeof(PDSI_Log));
//Extension.OutputMetadatas.Add(tblOut_PDSI);
//---------------------------------------
// map outputs:
//---------------------------------------
foreach (IAgent activeAgent in manyAgentParameters)
{
string mapTypePath = MapNames.ReplaceTemplateVarsMetadata(severityMapFileName, activeAgent.AgentName);
OutputMetadata mapOut_Severity = new OutputMetadata()
{
Type = OutputType.Map,
Name = System.String.Format(activeAgent.AgentName + " Outbreak Severity"),
FilePath = @mapTypePath,
Map_DataType = MapDataType.Ordinal,
Map_Unit = FieldUnits.Severity_Rank,
Visualize = true,
};
Extension.OutputMetadatas.Add(mapOut_Severity);
if (srdMapFileName != null)
{
mapTypePath = MapNames.ReplaceTemplateVarsMetadata(srdMapFileName, activeAgent.AgentName);
OutputMetadata mapOut_SRD = new OutputMetadata()
{
Type = OutputType.Map,
Name = "Site Resource Dominance",
FilePath = @mapTypePath,
Map_DataType = MapDataType.Continuous,
Map_Unit = FieldUnits.Percentage,
Visualize = false,
};
Extension.OutputMetadatas.Add(mapOut_SRD);
}
if (nrdMapFileName != null)
{
mapTypePath = MapNames.ReplaceTemplateVarsMetadata(nrdMapFileName, activeAgent.AgentName);
OutputMetadata mapOut_NRD = new OutputMetadata()
{
Type = OutputType.Map,
Name = "Neighborhood Resource Dominance",
FilePath = @mapTypePath,
Map_DataType = MapDataType.Continuous,
Map_Unit = FieldUnits.Percentage,
Visualize = false,
};
Extension.OutputMetadatas.Add(mapOut_NRD);
}
}
//---------------------------------------
MetadataProvider mp = new MetadataProvider(Extension);
mp.WriteMetadataToXMLFile("Metadata", Extension.Name, Extension.Name);
}
}
}
| 40.861538 | 119 | 0.507907 | [
"Apache-2.0"
] | LANDIS-II-Foundation/Extension-Biomass-BDA | src/MetadataHandler.cs | 5,314 | C# |
using System.Collections.Generic;
using GW2Scratch.EVTCAnalytics.Events;
using GW2Scratch.EVTCAnalytics.GameData;
using GW2Scratch.EVTCAnalytics.Model;
using GW2Scratch.EVTCAnalytics.Model.Agents;
using GW2Scratch.EVTCAnalytics.Model.Skills;
using GW2Scratch.EVTCAnalytics.Processing.Encounters;
namespace GW2Scratch.EVTCAnalytics.Processing
{
public class LogProcessorContext
{
public List<Agent> Agents { get; set; }
public Dictionary<ulong, Agent> AgentsByAddress { get; set; }
public Dictionary<int, List<Agent>> AgentsById { get; set; }
public List<Skill> Skills { get; set; }
public List<Event> Events { get; set; }
public LogTime LogStartTime { get; set; }
public LogTime LogEndTime { get; set; }
public Player PointOfView { get; set; }
public string EvtcVersion { get; set; }
public int? GameBuild { get; set; }
public int? GameShardId { get; set; }
public int? GameLanguageId { get; set; }
public int? MapId { get; set; }
public LogType LogType { get; set; }
public GameLanguage GameLanguage { get; set; }
public IEncounterData EncounterData { get; set; }
public bool AwareTimesSet { get; set; }
public bool MastersAssigned { get; set; }
}
} | 37.1875 | 63 | 0.739496 | [
"MIT"
] | jcogilvie/evtc | EVTCAnalytics/Processing/LogProcessorContext.cs | 1,190 | C# |
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace MicroPack.WebApi.Helpers
{
public static class Extensions
{
public static object SetDefaultInstanceProperties(this object instance)
{
var type = instance.GetType();
foreach (var propertyInfo in type.GetProperties())
{
SetValue(propertyInfo, instance);
}
return instance;
}
private static void SetValue(PropertyInfo propertyInfo, object instance)
{
var propertyType = propertyInfo.PropertyType;
if (propertyType == typeof(string))
{
SetDefaultValue(propertyInfo, instance, string.Empty);
return;
}
if (propertyType.Name == "IDictionary`2")
{
return;
}
if (typeof(IEnumerable).IsAssignableFrom(propertyType))
{
SetCollection(propertyInfo, instance);
return;
}
if (propertyType.IsInterface)
{
return;
}
if (propertyType.IsArray)
{
SetCollection(propertyInfo, instance);
return;
}
if (!propertyType.IsClass)
{
return;
}
var propertyInstance = FormatterServices.GetUninitializedObject(propertyInfo.PropertyType);
SetDefaultValue(propertyInfo, instance, propertyInstance);
SetDefaultInstanceProperties(propertyInstance);
}
private static void SetCollection(PropertyInfo propertyInfo, object instance)
{
var elementType = propertyInfo.PropertyType.IsGenericType
? propertyInfo.PropertyType.GenericTypeArguments[0]
: propertyInfo.PropertyType.GetElementType();
if (elementType is null)
{
return;
}
if (typeof(IEnumerable).IsAssignableFrom(elementType))
{
if (elementType == typeof(string))
{
SetDefaultValue(propertyInfo, instance, Array.Empty<string>());
return;
}
return;
}
var array = Array.CreateInstance(elementType, 0);
SetDefaultValue(propertyInfo, instance, array);
}
private static void SetDefaultValue(PropertyInfo propertyInfo, object instance, object value)
{
if (propertyInfo.CanWrite)
{
propertyInfo.SetValue(instance, value);
return;
}
var propertyName = propertyInfo.Name;
var field = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.SingleOrDefault(x => x.Name.StartsWith($"<{propertyName}>"));
field?.SetValue(instance, value);
}
}
} | 30.349515 | 103 | 0.537108 | [
"MIT"
] | meysamhadeli/MicroPack | src/WebApi/Helpers/Extensions.cs | 3,126 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Fabric.Chaos.DataStructures
{
using System.Fabric.Strings;
using System.Globalization;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
using Fabric.Chaos.Common;
using Fabric.Common;
using Threading.Tasks;
using Interop;
using Collections.Generic;
/// <summary>
/// <para>Represents a time range in a 24 hour day in UTC time.</para>
/// </summary>
[DataContract]
[Serializable]
public sealed class ChaosScheduleTimeRangeUtc : ByteSerializable
{
/// <summary>
/// <para>A <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleTimeRangeUtc" /> representing the entire day.</para>
/// </summary>
public static readonly ChaosScheduleTimeRangeUtc WholeDay = new ChaosScheduleTimeRangeUtc(ChaosScheduleTimeUtc.StartOfDay, ChaosScheduleTimeUtc.EndOfDay);
private const string TraceComponent = "Chaos.ChaosScheduleTimeRangeUtc";
internal ChaosScheduleTimeRangeUtc()
{
this.StartTime = new ChaosScheduleTimeUtc();
this.EndTime = new ChaosScheduleTimeUtc();
}
/// <summary>
/// <para>Initializes a new instance of the <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleTimeRangeUtc" /> class by copying another time range.</para>
/// </summary>
/// <param name="other">Another time range to copy.</param>
internal ChaosScheduleTimeRangeUtc(ChaosScheduleTimeRangeUtc other)
{
this.StartTime = new ChaosScheduleTimeUtc(other.StartTime);
this.EndTime = new ChaosScheduleTimeUtc(other.EndTime);
}
/// <summary>
/// <para>Initializes a new instance of the <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleTimeRangeUtc" /> class with a provided start and end time.</para>
/// </summary>
/// <param name="startTime">Start of time range.</param>
/// <param name="endTime">End of time range.</param>
public ChaosScheduleTimeRangeUtc(ChaosScheduleTimeUtc startTime, ChaosScheduleTimeUtc endTime)
{
if (startTime == null)
{
throw new System.ArgumentNullException(
"StartTime",
StringResources.ChaosScheduler_ScheduleJobTimeIsNull);
}
if (endTime == null)
{
throw new System.ArgumentNullException(
"EndTime",
StringResources.ChaosScheduler_ScheduleJobTimeIsNull);
}
this.StartTime = new ChaosScheduleTimeUtc(startTime);
this.EndTime = new ChaosScheduleTimeUtc(endTime);
}
/// <summary>
/// <para>Gets the <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleTimeUtc"/> representing the UTC starting time of the day for a run of Chaos defined by a <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleJob"/>.</para>
/// </summary>
/// <value>
/// <para>The <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleTimeUtc"/> representing the UTC starting time of the day for a run of Chaos defined by a <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleJob"/>.</para>
/// </value>
[DataMember]
public ChaosScheduleTimeUtc StartTime
{
get;
private set;
}
/// <summary>
/// <para>Gets the <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleTimeUtc"/> representing the UTC ending time of the day for a run of Chaos defined by a <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleJob"/>.</para>
/// </summary>
/// <value>
/// <para>The <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleTimeUtc"/> representing the UTC ending time of the day for a run of Chaos defined by a <see cref="System.Fabric.Chaos.DataStructures.ChaosScheduleJob"/>.</para>
/// </value>
[DataMember]
public ChaosScheduleTimeUtc EndTime
{
get;
private set;
}
/// <summary>
/// Gets a string representation of the ChaosScheduleTimeRangeUtc object.
/// </summary>
/// <returns>A string representation of the ChaosScheduleTimeRangeUtc object.</returns>
public override string ToString()
{
var description = new StringBuilder();
description.AppendLine(
string.Format(
CultureInfo.CurrentCulture,
"StartTime: {0}",
this.StartTime.ToString()));
description.AppendLine(
string.Format(
CultureInfo.CurrentCulture,
"EndTime: {0}",
this.EndTime.ToString()));
description.AppendLine();
return description.ToString();
}
#region ByteSerializable
/// <summary>
/// Reads the state of this object from byte array.
/// </summary>
/// <param name="br">A BinaryReader object</param>
/// <exception cref="EndOfStreamException">The end of the stream is reached. </exception>
/// <exception cref="IOException">An I/O error occurs. </exception>
public override void Read(BinaryReader br)
{
decimal objectVersion = br.ReadDecimal();
if (objectVersion >= ChaosConstants.ApiVersion62)
{
this.StartTime = new ChaosScheduleTimeUtc(0, 0);
this.StartTime.Read(br);
this.EndTime = new ChaosScheduleTimeUtc(0, 0);
this.EndTime.Read(br);
}
else
{
TestabilityTrace.TraceSource.WriteError(TraceComponent, "Attempting to read a version of object below lowest version. Saw {0}. Expected >=6.2", objectVersion);
ReleaseAssert.Fail("Failed to read byte serialization of ChaosScheduleTimeRangeUtc");
}
}
/// <summary>
/// Writes the state of this object into a byte array.
/// </summary>
/// <param name="bw">A BinaryWriter object.</param>
/// <exception cref="IOException">An I/O error occurs. </exception>
public override void Write(BinaryWriter bw)
{
bw.Write(ChaosConstants.ApiVersionCurrent);
// Api Version >= 6.2
this.StartTime.Write(bw);
this.EndTime.Write(bw);
}
#endregion
#region Interop Helpers
internal static unsafe ChaosScheduleTimeRangeUtc FromNative(IntPtr pointer)
{
var nativeTimeRange = *(NativeTypes.FABRIC_CHAOS_SCHEDULE_TIME_RANGE_UTC*)pointer;
var startTime = ChaosScheduleTimeUtc.FromNative(nativeTimeRange.StartTime);
var endTime = ChaosScheduleTimeUtc.FromNative(nativeTimeRange.EndTime);
return new ChaosScheduleTimeRangeUtc(startTime, endTime);
}
internal IntPtr ToNative(PinCollection pinCollection)
{
var nativeTimeRange = new NativeTypes.FABRIC_CHAOS_SCHEDULE_TIME_RANGE_UTC
{
StartTime = this.StartTime.ToNative(pinCollection),
EndTime = this.EndTime.ToNative(pinCollection),
};
return pinCollection.AddBlittable(nativeTimeRange);
}
internal static unsafe IntPtr ToNativeList(PinCollection pinCollection, List<ChaosScheduleTimeRangeUtc> times)
{
var timesArray = new NativeTypes.FABRIC_CHAOS_SCHEDULE_TIME_RANGE_UTC[times.Count];
for (int i=0; i<times.Count; i++)
{
timesArray[i].StartTime = times[i].StartTime.ToNative(pinCollection);
timesArray[i].EndTime = times[i].EndTime.ToNative(pinCollection);
}
var nativeTimeRangeList = new NativeTypes.FABRIC_CHAOS_SCHEDULE_TIME_RANGE_UTC_LIST
{
Count = (uint)times.Count,
Items = pinCollection.AddBlittable(timesArray)
};
return pinCollection.AddBlittable(nativeTimeRangeList);
}
#endregion
}
} | 41.214634 | 248 | 0.606581 | [
"MIT"
] | AlkisFortuneFish/service-fabric | src/prod/src/managed/Api/src/System/Fabric/Chaos/DataStructures/ChaosScheduleTimeRangeUtc.cs | 8,449 | C# |
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
namespace VsctCompletion.Completion.Providers
{
public class EditorProvider : ICompletionProvider
{
private static List<CompletionItem> _items;
public IEnumerable<CompletionItem> GetCompletions(XmlDocument doc, XPathNavigator navigator, Func<string, CompletionItem> CreateCompletionItem)
{
if (_items == null)
{
_items = new List<CompletionItem>
{
CreateCompletionItem("GUID_TextEditorFactory"),
CreateCompletionItem("guidVSStd97"),
CreateCompletionItem("guidVSStd2K"),
};
}
return _items;
}
}
}
| 29.758621 | 151 | 0.628042 | [
"Apache-2.0"
] | PonomarevDmitry/VsctIntellisense | src/Completion/Providers/EditorProvider.cs | 865 | C# |
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/
* Copyright : Copyright © Nequeo Pty Ltd 2012 http://www.nequeo.com.au/
*
* File :
* Purpose :
*
*/
#region Nequeo Pty Ltd License
/*
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
namespace Nequeo.Net.Core.Messaging
{
using System.Diagnostics.Contracts;
using System.Net;
/// <summary>
/// An interface that allows direct request messages to capture the details of the HTTP request they arrived on.
/// </summary>
[ContractClass(typeof(IHttpDirectRequestContract))]
public interface IHttpDirectRequest : IMessage {
/// <summary>
/// Gets the HTTP headers of the request.
/// </summary>
/// <value>May be an empty collection, but must not be <c>null</c>.</value>
WebHeaderCollection Headers { get; }
}
}
| 36.211538 | 113 | 0.71641 | [
"MIT"
] | nequeo/sockets | Nequeo.Net.Core/Nequeo.Net.Core/Core/Messaging/IHttpDirectRequest.cs | 1,886 | C# |
#pragma checksum "..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "169E11558BAA77EFC86FE08A9DB1DAA85C7BBE6D"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using CoordinateTransformations;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace CoordinateTransformations {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
#line 5 "..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
CoordinateTransformations.App app = new CoordinateTransformations.App();
app.InitializeComponent();
app.Run();
}
}
}
| 32.507042 | 118 | 0.625217 | [
"MIT"
] | MsSuomka/CoordinateTransformations | CoordinateTransformations/CoordinateTransformations/obj/Debug/App.g.cs | 2,310 | 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 Microsoft.DotNet.Darc.Helpers;
using Microsoft.DotNet.Darc.Options;
using Microsoft.DotNet.DarcLib;
using Microsoft.DotNet.Maestro.Client;
using Microsoft.DotNet.Maestro.Client.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.DotNet.Darc.Operations
{
internal class GetLatestBuildOperation : Operation
{
GetLatestBuildCommandLineOptions _options;
public GetLatestBuildOperation(GetLatestBuildCommandLineOptions options)
: base(options)
{
_options = options;
}
/// <summary>
/// Gets the latest build for a repo
/// </summary>
/// <returns>Process exit code.</returns>
public override async Task<int> ExecuteAsync()
{
try
{
IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);
// Calculate out possible repos based on the input strings.
// Today the DB has no way of searching for builds by substring, so for now
// grab source/targets repos of subscriptions matched on substring,
// and then add the explicit repo from the options.
// Then search channels by substring
// Then run GetLatestBuild for each permutation.
var subscriptions = await remote.GetSubscriptionsAsync();
var possibleRepos = subscriptions
.SelectMany(subscription => new List<string> { subscription.SourceRepository, subscription.TargetRepository })
.Where(r => r.Contains(_options.Repo, StringComparison.OrdinalIgnoreCase))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
possibleRepos.Add(_options.Repo);
var channels = (await remote.GetChannelsAsync())
.Where(c => string.IsNullOrEmpty(_options.Channel) || c.Name.Contains(_options.Channel, StringComparison.OrdinalIgnoreCase));
if (!channels.Any())
{
Console.WriteLine($"Could not find a channel with name containing '{_options.Channel}'");
return Constants.ErrorCode;
}
bool foundBuilds = false;
foreach (string possibleRepo in possibleRepos)
{
foreach (Channel channel in channels)
{
Build latestBuild = await remote.GetLatestBuildAsync(possibleRepo, channel.Id);
if (latestBuild != null)
{
if (foundBuilds)
{
Console.WriteLine();
}
foundBuilds = true;
Console.Write(UxHelpers.GetTextBuildDescription(latestBuild));
}
}
}
if (!foundBuilds)
{
Console.WriteLine("No latest build found matching the specified criteria");
return Constants.ErrorCode;
}
return Constants.SuccessCode;
}
catch (AuthenticationException e)
{
Console.WriteLine(e.Message);
return Constants.ErrorCode;
}
catch (Exception e)
{
Logger.LogError(e, "Error: Failed to retrieve latest build.");
return Constants.ErrorCode;
}
}
}
}
| 39.464646 | 145 | 0.557973 | [
"MIT"
] | AlitzelMendez/arcade-services | src/Microsoft.DotNet.Darc/src/Darc/Operations/GetLatestBuildOperation.cs | 3,907 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace intro1_proper_logging
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ConsoleLifetimeOptions>(opts =>
{
opts.SuppressStatusMessages = false;
});
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 31.112903 | 143 | 0.60394 | [
"Apache-2.0"
] | reyou/Ggg.Csharp | apps/apps-web/andrewlock.net/series/exploring-asp-net-core-3/part6-structured-logging/intro1-proper-logging/Startup.cs | 1,929 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaswordKeeperMVVM.Models
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
List<MyNote> MyTasks { get; set; }
}
}
| 19.6875 | 42 | 0.660317 | [
"MIT"
] | Falka-WPF/Password_Keeper-MVVM | PaswordKeeperMVVM/Models/Category.cs | 317 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Flurl.Http
{
/// <summary>
/// Extension methods off HttpRequestMessage.
/// </summary>
public static class HttpRequestMessageExtensions
{
/// <summary>
/// Set a header on this HttpRequestMessage (default), or its Content property if it's a known content-level header.
/// No validation. Overwrites any existing value(s) for the header.
/// </summary>
/// <param name="request">The HttpRequestMessage.</param>
/// <param name="name">The header name.</param>
/// <param name="value">The header value.</param>
/// <param name="createContentIfNecessary">If it's a content-level header and there is no content, this determines whether to create an empty HttpContent or just ignore the header.</param>
public static void SetHeader(this HttpRequestMessage request, string name, object value, bool createContentIfNecessary = true) {
new HttpMessage(request).SetHeader(name, value, createContentIfNecessary);
}
/// <summary>
/// Gets the value of a header on this HttpRequestMessage (default), or its Content property.
/// Returns null if the header doesn't exist.
/// </summary>
/// <param name="request">The HttpRequestMessage.</param>
/// <param name="name">The header name.</param>
/// <returns>The header value.</returns>
public static string GetHeaderValue(this HttpRequestMessage request, string name) {
return new HttpMessage(request).GetHeaderValue(name);
}
/// <summary>
/// Associate an HttpCall object with this request
/// </summary>
internal static void SetHttpCall(this HttpRequestMessage request, HttpCall call) {
if (request?.Properties != null)
request.Properties["FlurlHttpCall"] = call;
}
/// <summary>
/// Get the HttpCall associated with this request, if any.
/// </summary>
internal static HttpCall GetHttpCall(this HttpRequestMessage request) {
if (request?.Properties != null && request.Properties.TryGetValue("FlurlHttpCall", out var obj) && obj is HttpCall call)
return call;
return null;
}
}
}
| 40.071429 | 193 | 0.692513 | [
"MIT"
] | yang-xiaodong/Flurl | src/Flurl.Http/HttpRequestMessageExtensions.cs | 2,246 | C# |
/*
// <copyright>
// dotNetRDF is free and open source software licensed under the MIT License
// -------------------------------------------------------------------------
//
// Copyright (c) 2009-2017 dotNetRDF Project (http://dotnetrdf.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using VDS.RDF.Configuration;
using VDS.RDF.Parsing;
using VDS.RDF.Parsing.Handlers;
using VDS.RDF.Query;
using VDS.RDF.Storage.Management;
using VDS.RDF.Update;
using VDS.RDF.Writing.Formatting;
namespace VDS.RDF.Storage
{
/// <summary>
/// Controls how the <see cref="SparqlConnector">SparqlConnector</see> loads Graphs from the Endpoint
/// </summary>
public enum SparqlConnectorLoadMethod
{
/// <summary>
/// Graphs are loaded by issuing a DESCRIBE query using the Graph URI
/// </summary>
Describe,
/// <summary>
/// Graphs are loaded by issuing a CONSTRUCT FROM query using the Graph URI
/// </summary>
Construct
}
/// <summary>
/// Class for connecting to any SPARQL Endpoint as a read-only Store
/// </summary>
/// <remarks>
/// <para>
/// This class is effectively a read-only wrapper around a <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> using it with it's default settings, if you only need to query an endpoint and require more control over the settings used to access the endpoint you should use that class directly or use the constructors which allow you to provide your own pre-configure <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> instance
/// </para>
/// <para>
/// Unlike other HTTP based connectors this connector does not derive from <see cref="BaseAsyncHttpConnector">BaseHttpConnector</see> - if you need to specify proxy information you should do so on the SPARQL Endpoint you are wrapping either by providing a <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> instance pre-configured with the proxy settings or by accessing the endpoint via the <see cref="SparqlConnector.Endpoint">Endpoint</see> property and programmatically adding the settings.
/// </para>
/// </remarks>
public class SparqlConnector
: IQueryableStorage, IConfigurationSerializable
{
/// <summary>
/// Underlying SPARQL query endpoint
/// </summary>
protected SparqlRemoteEndpoint _endpoint;
/// <summary>
/// Method for loading graphs
/// </summary>
protected SparqlConnectorLoadMethod _mode = SparqlConnectorLoadMethod.Construct;
/// <summary>
/// Whether to skip local parsing
/// </summary>
protected bool _skipLocalParsing = false;
/// <summary>
/// Timeout for endpoints
/// </summary>
protected int _timeout;
/// <summary>
/// Creates a new SPARQL Connector which uses the given SPARQL Endpoint
/// </summary>
/// <param name="endpoint">Endpoint</param>
public SparqlConnector(SparqlRemoteEndpoint endpoint)
{
if (endpoint == null) throw new ArgumentNullException("endpoint", "A valid Endpoint must be specified");
_endpoint = endpoint;
_timeout = endpoint.Timeout;
}
/// <summary>
/// Creates a new SPARQL Connector which uses the given SPARQL Endpoint
/// </summary>
/// <param name="endpoint">Endpoint</param>
/// <param name="mode">Load Method to use</param>
public SparqlConnector(SparqlRemoteEndpoint endpoint, SparqlConnectorLoadMethod mode)
: this(endpoint)
{
_mode = mode;
}
/// <summary>
/// Creates a new SPARQL Connector which uses the given SPARQL Endpoint
/// </summary>
/// <param name="endpointUri">Endpoint URI</param>
public SparqlConnector(Uri endpointUri)
: this(new SparqlRemoteEndpoint(endpointUri)) { }
/// <summary>
/// Creates a new SPARQL Connector which uses the given SPARQL Endpoint
/// </summary>
/// <param name="endpointUri">Endpoint URI</param>
/// <param name="mode">Load Method to use</param>
public SparqlConnector(Uri endpointUri, SparqlConnectorLoadMethod mode)
: this(new SparqlRemoteEndpoint(endpointUri), mode) { }
/// <summary>
/// Gets the parent server (if any)
/// </summary>
public IStorageServer ParentServer
{
get
{
return null;
}
}
/// <summary>
/// Controls whether the Query will be parsed locally to accurately determine its Query Type for processing the response
/// </summary>
/// <remarks>
/// If the endpoint you are connecting to provides extensions to SPARQL syntax which are not permitted by the libraries parser then you may wish to enable this option as otherwise you will not be able to execute such queries
/// </remarks>
[Description("Determines whether queries are parsed locally before being sent to the remote endpoint. Should be disabled if the remote endpoint supports non-standard extensions that won't parse locally.")]
public bool SkipLocalParsing
{
get
{
return _skipLocalParsing;
}
set
{
_skipLocalParsing = value;
}
}
/// <summary>
/// Gets/Sets the HTTP Timeout in milliseconds used for communicating with the SPARQL Endpoint
/// </summary>
public virtual int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
_endpoint.Timeout = value;
}
}
/// <summary>
/// Gets the underlying <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> which this class is a wrapper around
/// </summary>
[Description("The Remote Endpoint to which queries are sent using HTTP."),TypeConverter(typeof(ExpandableObjectConverter))]
public SparqlRemoteEndpoint Endpoint
{
get
{
return _endpoint;
}
}
/// <summary>
/// Makes a Query against the SPARQL Endpoint
/// </summary>
/// <param name="sparqlQuery">SPARQL Query</param>
/// <returns></returns>
public object Query(String sparqlQuery)
{
Graph g = new Graph();
SparqlResultSet results = new SparqlResultSet();
Query(new GraphHandler(g), new ResultSetHandler(results), sparqlQuery);
if (results.ResultsType != SparqlResultsType.Unknown)
{
return results;
}
else
{
return g;
}
}
/// <summary>
/// Makes a Query against the SPARQL Endpoint processing the results with an appropriate handler from those provided
/// </summary>
/// <param name="rdfHandler">RDF Handler</param>
/// <param name="resultsHandler">Results Handler</param>
/// <param name="sparqlQuery">SPARQL Query</param>
/// <returns></returns>
public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
{
if (!_skipLocalParsing)
{
// Parse the query locally to validate it and so we can decide what to do
// when we receive the Response more easily as we'll know the query type
// This also saves us wasting a HttpWebRequest on a malformed query
SparqlQueryParser qparser = new SparqlQueryParser();
SparqlQuery q = qparser.ParseFromString(sparqlQuery);
switch (q.QueryType)
{
case SparqlQueryType.Ask:
case SparqlQueryType.Select:
case SparqlQueryType.SelectAll:
case SparqlQueryType.SelectAllDistinct:
case SparqlQueryType.SelectAllReduced:
case SparqlQueryType.SelectDistinct:
case SparqlQueryType.SelectReduced:
// Some kind of Sparql Result Set
_endpoint.QueryWithResultSet(resultsHandler, sparqlQuery);
break;
case SparqlQueryType.Construct:
case SparqlQueryType.Describe:
case SparqlQueryType.DescribeAll:
// Some kind of Graph
_endpoint.QueryWithResultGraph(rdfHandler, sparqlQuery);
break;
case SparqlQueryType.Unknown:
default:
// Error
throw new RdfQueryException("Unknown Query Type was used, unable to determine how to process the response");
}
}
else
{
// If we're skipping local parsing then we'll need to just make a raw query and process the response
using (HttpWebResponse response = _endpoint.QueryRaw(sparqlQuery))
{
try
{
// Is the Content Type referring to a Sparql Result Set format?
ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
sparqlParser.Load(resultsHandler, new StreamReader(response.GetResponseStream()));
response.Close();
}
catch (RdfParserSelectionException)
{
// If we get a Parser Selection exception then the Content Type isn't valid for a Sparql Result Set
// Is the Content Type referring to a RDF format?
IRdfReader rdfParser = MimeTypesHelper.GetParser(response.ContentType);
rdfParser.Load(rdfHandler, new StreamReader(response.GetResponseStream()));
response.Close();
}
}
}
}
/// <summary>
/// Loads a Graph from the SPARQL Endpoint
/// </summary>
/// <param name="g">Graph to load into</param>
/// <param name="graphUri">URI of the Graph to load</param>
public virtual void LoadGraph(IGraph g, Uri graphUri)
{
LoadGraph(g, graphUri.ToSafeString());
}
/// <summary>
/// Loads a Graph from the SPARQL Endpoint
/// </summary>
/// <param name="handler">RDF Handler</param>
/// <param name="graphUri">URI of the Graph to load</param>
public virtual void LoadGraph(IRdfHandler handler, Uri graphUri)
{
LoadGraph(handler, graphUri.ToSafeString());
}
/// <summary>
/// Loads a Graph from the SPARQL Endpoint
/// </summary>
/// <param name="g">Graph to load into</param>
/// <param name="graphUri">URI of the Graph to load</param>
public virtual void LoadGraph(IGraph g, String graphUri)
{
if (g.IsEmpty && graphUri != null && !graphUri.Equals(String.Empty))
{
g.BaseUri = UriFactory.Create(graphUri);
}
LoadGraph(new GraphHandler(g), graphUri.ToSafeString());
}
/// <summary>
/// Loads a Graph from the SPARQL Endpoint
/// </summary>
/// <param name="handler">RDF Handler</param>
/// <param name="graphUri">URI of the Graph to load</param>
public virtual void LoadGraph(IRdfHandler handler, String graphUri)
{
String query;
if (graphUri.Equals(String.Empty))
{
if (_mode == SparqlConnectorLoadMethod.Describe)
{
throw new RdfStorageException("Cannot retrieve the Default Graph when the Load Method is Describe");
}
else
{
query = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}";
}
}
else
{
switch (_mode)
{
case SparqlConnectorLoadMethod.Describe:
query = "DESCRIBE <" + graphUri.Replace(">", "\\>") + ">";
break;
case SparqlConnectorLoadMethod.Construct:
default:
query = "CONSTRUCT {?s ?p ?o} FROM <" + graphUri.Replace(">", "\\>") + "> WHERE {?s ?p ?o}";
break;
}
}
_endpoint.QueryWithResultGraph(handler, query);
}
/// <summary>
/// Throws an error since this Manager is read-only
/// </summary>
/// <param name="g">Graph to save</param>
/// <exception cref="RdfStorageException">Always thrown since this Manager provides a read-only connection</exception>
public virtual void SaveGraph(IGraph g)
{
throw new RdfStorageException("The SparqlConnector provides a read-only connection");
}
/// <summary>
/// Gets the IO Behaviour of SPARQL Connections
/// </summary>
public virtual IOBehaviour IOBehaviour
{
get
{
return IOBehaviour.ReadOnlyGraphStore;
}
}
/// <summary>
/// Throws an error since this Manager is read-only
/// </summary>
/// <param name="graphUri">Graph URI</param>
/// <param name="additions">Triples to be added</param>
/// <param name="removals">Triples to be removed</param>
public virtual void UpdateGraph(Uri graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals)
{
throw new RdfStorageException("The SparqlConnector provides a read-only connection");
}
/// <summary>
/// Throws an error since this Manager is read-only
/// </summary>
/// <param name="graphUri">Graph URI</param>
/// <param name="additions">Triples to be added</param>
/// <param name="removals">Triples to be removed</param>
public virtual void UpdateGraph(String graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals)
{
throw new RdfStorageException("The SparqlConnector provides a read-only connection");
}
/// <summary>
/// Returns that Updates are not supported since this connection is read-only
/// </summary>
public virtual bool UpdateSupported
{
get
{
return false;
}
}
/// <summary>
/// Throws an exception as this connector provides a read-only connection
/// </summary>
/// <param name="graphUri">URI of this Graph to delete</param>
/// <exception cref="RdfStorageException">Thrown since this connection is read-only so you cannot delete graphs using it</exception>
public virtual void DeleteGraph(Uri graphUri)
{
throw new RdfStorageException("The SparqlConnector provides a read-only connection");
}
/// <summary>
/// Throws an exception as this connector provides a read-only connection
/// </summary>
/// <param name="graphUri">URI of this Graph to delete</param>
/// <exception cref="RdfStorageException">Thrown since this connection is read-only so you cannot delete graphs using it</exception>
public virtual void DeleteGraph(String graphUri)
{
throw new RdfStorageException("The SparqlConnector provides a read-only connection");
}
/// <summary>
/// Returns that deleting graphs is not supported
/// </summary>
public virtual bool DeleteSupported
{
get
{
return false;
}
}
/// <summary>
/// Lists the Graphs in the Store
/// </summary>
/// <returns></returns>
public virtual IEnumerable<Uri> ListGraphs()
{
try
{
// Technically the ?s ?p ?o is unecessary here but we may not get the right results if we don't include this because some stores
// won't interpret GRAPH ?g { } correctly
Object results = Query("SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }");
if (results is SparqlResultSet)
{
List<Uri> graphs = new List<Uri>();
foreach (SparqlResult r in ((SparqlResultSet)results))
{
if (r.HasValue("g"))
{
INode temp = r["g"];
if (temp.NodeType == NodeType.Uri)
{
graphs.Add(((IUriNode)temp).Uri);
}
}
}
return graphs;
}
else
{
return Enumerable.Empty<Uri>();
}
}
catch (Exception ex)
{
throw StorageHelper.HandleError(ex, "listing Graphs from");
}
}
/// <summary>
/// Returns that listing graphs is supported
/// </summary>
public virtual bool ListGraphsSupported
{
get
{
return true;
}
}
/// <summary>
/// Returns that the Connection is ready
/// </summary>
public virtual bool IsReady
{
get
{
return true;
}
}
/// <summary>
/// Returns that the Connection is read-only
/// </summary>
public virtual bool IsReadOnly
{
get
{
return true;
}
}
/// <summary>
/// Disposes of the Connection
/// </summary>
public void Dispose()
{
// Nothing to do
}
/// <summary>
/// Gets a String which gives details of the Connection
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "[SPARQL Query] " + _endpoint.Uri.AbsoluteUri;
}
/// <summary>
/// Serializes the connection's configuration
/// </summary>
/// <param name="context">Configuration Serialization Context</param>
public virtual void SerializeConfiguration(ConfigurationSerializationContext context)
{
INode manager = context.NextSubject;
INode rdfType = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType));
INode rdfsLabel = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "label"));
INode dnrType = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyType));
INode genericManager = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.ClassStorageProvider));
INode loadMode = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyLoadMode));
INode skipParsing = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertySkipParsing));
// Basic information
context.Graph.Assert(new Triple(manager, rdfType, genericManager));
context.Graph.Assert(new Triple(manager, rdfsLabel, context.Graph.CreateLiteralNode(ToString())));
context.Graph.Assert(new Triple(manager, dnrType, context.Graph.CreateLiteralNode(GetType().FullName)));
// Serialize Load Mode
context.Graph.Assert(new Triple(manager, loadMode, context.Graph.CreateLiteralNode(_mode.ToString())));
context.Graph.Assert(new Triple(manager, skipParsing, _skipLocalParsing.ToLiteral(context.Graph)));
// Query Endpoint
if (_endpoint is IConfigurationSerializable)
{
// Use the indirect serialization method
// Serialize the Endpoints Configuration
INode endpoint = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryEndpoint));
INode endpointObj = context.Graph.CreateBlankNode();
context.NextSubject = endpointObj;
((IConfigurationSerializable)_endpoint).SerializeConfiguration(context);
// Link that serialization to our serialization
context.Graph.Assert(new Triple(manager, endpoint, endpointObj));
}
else
{
// Use the direct serialization method
INode endpointUri = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryEndpointUri));
INode defGraphUri = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyDefaultGraphUri));
INode namedGraphUri = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyNamedGraphUri));
context.Graph.Assert(new Triple(manager, endpointUri, context.Graph.CreateLiteralNode(_endpoint.Uri.AbsoluteUri)));
foreach (String u in _endpoint.DefaultGraphs)
{
context.Graph.Assert(new Triple(manager, defGraphUri, context.Graph.CreateUriNode(UriFactory.Create(u))));
}
foreach (String u in _endpoint.NamedGraphs)
{
context.Graph.Assert(new Triple(manager, namedGraphUri, context.Graph.CreateUriNode(UriFactory.Create(u))));
}
}
}
}
/// <summary>
/// Class for connecting to any SPARQL server that provides both a query and update endpoint
/// </summary>
/// <remarks>
/// <para>
/// This class is a wrapper around a <see cref="SparqlRemoteEndpoint"/> and a <see cref="SparqlRemoteUpdateEndpoint"/>. The former is used for the query functionality while the latter is used for the update functionality. As updates happen via SPARQL the behaviour with respects to adding and removing blank nodes will be somewhat up to the underlying SPARQL implementation. This connector is <strong>not</strong> able to carry out <see cref="IStorageProvider.UpdateGraph(Uri,IEnumerable{Triple},IEnumerable{Triple})"/> operations which attempt to delete blank nodes and cannot guarantee that added blank nodes bear any relation to existing blank nodes in the store.
/// </para>
/// <para>
/// Unlike other HTTP based connectors this connector does not derive from <see cref="BaseAsyncHttpConnector">BaseHttpConnector</see> - if you need to specify proxy information you should do so on the SPARQL Endpoint you are wrapping either by providing endpoint instance pre-configured with the proxy settings or by accessing the endpoint via the <see cref="ReadWriteSparqlConnector">Endpoint</see> and <see cref="ReadWriteSparqlConnector.UpdateEndpoint">UpdateEndpoint</see> properties and programmatically adding the settings.
/// </para>
/// </remarks>
public class ReadWriteSparqlConnector
: SparqlConnector, IUpdateableStorage
{
private readonly SparqlFormatter _formatter = new SparqlFormatter();
private readonly SparqlRemoteUpdateEndpoint _updateEndpoint;
/// <summary>
/// Creates a new connection
/// </summary>
/// <param name="queryEndpoint">Query Endpoint</param>
/// <param name="updateEndpoint">Update Endpoint</param>
/// <param name="mode">Method for loading graphs</param>
public ReadWriteSparqlConnector(SparqlRemoteEndpoint queryEndpoint, SparqlRemoteUpdateEndpoint updateEndpoint, SparqlConnectorLoadMethod mode)
: base(queryEndpoint, mode)
{
_updateEndpoint = updateEndpoint ?? throw new ArgumentNullException(nameof(updateEndpoint), "Update Endpoint cannot be null, if you require a read-only SPARQL connector use the base class SparqlConnector instead");
}
/// <summary>
/// Creates a new connection
/// </summary>
/// <param name="queryEndpoint">Query Endpoint</param>
/// <param name="updateEndpoint">Update Endpoint</param>
public ReadWriteSparqlConnector(SparqlRemoteEndpoint queryEndpoint, SparqlRemoteUpdateEndpoint updateEndpoint)
: this(queryEndpoint, updateEndpoint, SparqlConnectorLoadMethod.Construct) { }
/// <summary>
/// Creates a new connection
/// </summary>
/// <param name="queryEndpoint">Query Endpoint</param>
/// <param name="updateEndpoint">Update Endpoint</param>
/// <param name="mode">Method for loading graphs</param>
public ReadWriteSparqlConnector(Uri queryEndpoint, Uri updateEndpoint, SparqlConnectorLoadMethod mode)
: this(new SparqlRemoteEndpoint(queryEndpoint), new SparqlRemoteUpdateEndpoint(updateEndpoint), mode) { }
/// <summary>
/// Creates a new connection
/// </summary>
/// <param name="queryEndpoint">Query Endpoint</param>
/// <param name="updateEndpoint">Update Endpoint</param>
public ReadWriteSparqlConnector(Uri queryEndpoint, Uri updateEndpoint)
: this(queryEndpoint, updateEndpoint, SparqlConnectorLoadMethod.Construct) { }
/// <summary>
/// Gets the underlying <see cref="SparqlRemoteUpdateEndpoint">SparqlRemoteUpdateEndpoint</see> which this class is a wrapper around
/// </summary>
[Description("The Remote Update Endpoint to which queries are sent using HTTP."), TypeConverter(typeof(ExpandableObjectConverter))]
public SparqlRemoteUpdateEndpoint UpdateEndpoint
{
get
{
return _updateEndpoint;
}
}
/// <summary>
/// Gets/Sets the HTTP Timeout in milliseconds used for communicating with the SPARQL Endpoint
/// </summary>
public override int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
_endpoint.Timeout = value;
_updateEndpoint.Timeout = value;
}
}
/// <summary>
/// Gets that deleting graphs is supported
/// </summary>
public override bool DeleteSupported
{
get
{
return true;
}
}
/// <summary>
/// Gets that the store is not read-only
/// </summary>
public override bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Gets the IO behaviour for the store
/// </summary>
public override IOBehaviour IOBehaviour
{
get
{
return IOBehaviour.IsQuadStore | IOBehaviour.HasDefaultGraph | IOBehaviour.HasNamedGraphs | IOBehaviour.CanUpdateTriples | IOBehaviour.OverwriteTriples | IOBehaviour.OverwriteDefault | IOBehaviour.OverwriteNamed;
}
}
/// <summary>
/// Gets that triple level updates are supported, see the remarks section of the <see cref="ReadWriteSparqlConnector"/> for exactly what is and isn't supported
/// </summary>
public override bool UpdateSupported
{
get
{
return true;
}
}
/// <summary>
/// Deletes a graph from the store
/// </summary>
/// <param name="graphUri">URI of the graph to delete</param>
public override void DeleteGraph(string graphUri)
{
DeleteGraph(graphUri.ToSafeUri());
}
/// <summary>
/// Deletes a graph from the store
/// </summary>
/// <param name="graphUri">URI of the graph to delete</param>
public override void DeleteGraph(Uri graphUri)
{
if (graphUri == null)
{
Update("DROP DEFAULT");
}
else
{
Update("DROP GRAPH <" + _formatter.FormatUri(graphUri) + ">");
}
}
/// <summary>
/// Saves a graph to the store
/// </summary>
/// <param name="g">Graph to save</param>
public override void SaveGraph(IGraph g)
{
StringBuilder updates = new StringBuilder();
// Saving a Graph ovewrites a previous graph so start with a CLEAR SILENT GRAPH
if (g.BaseUri == null)
{
updates.AppendLine("CLEAR SILENT DEFAULT;");
}
else
{
updates.AppendLine("CLEAR SILENT GRAPH <" + _formatter.FormatUri(g.BaseUri) + ">;");
}
// Insert preamble
// Note that we use INSERT { } WHERE { } rather than INSERT DATA { } so we can insert blank nodes
if (g.BaseUri != null)
{
updates.AppendLine("WITH <" + _formatter.FormatUri(g.BaseUri) + ">");
}
updates.AppendLine("INSERT");
updates.AppendLine("{");
// Serialize triples
foreach (Triple t in g.Triples)
{
updates.AppendLine(" " + _formatter.Format(t));
}
// End
updates.AppendLine("} WHERE { }");
// Save the graph
Update(updates.ToString());
}
/// <summary>
/// Updates a graph in the store
/// </summary>
/// <param name="graphUri">URI of the graph to update</param>
/// <param name="additions">Triples to add</param>
/// <param name="removals">Triples to remove</param>
public override void UpdateGraph(string graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals)
{
UpdateGraph(graphUri.ToSafeUri(), additions, removals);
}
/// <summary>
/// Updates a graph in the store
/// </summary>
/// <param name="graphUri">URI of the graph to update</param>
/// <param name="additions">Triples to add</param>
/// <param name="removals">Triples to remove</param>
public override void UpdateGraph(Uri graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals)
{
StringBuilder updates = new StringBuilder();
if (additions != null)
{
if (additions.Any())
{
// Insert preamble
// Note that we use INSERT { } WHERE { } rather than INSERT DATA { } so we can insert blank nodes
if (graphUri != null)
{
updates.AppendLine("WITH <" + _formatter.FormatUri(graphUri) + ">");
}
updates.AppendLine("INSERT");
updates.AppendLine("{");
// Serialize triples
foreach (Triple t in additions)
{
updates.AppendLine(" " + _formatter.Format(t));
}
// End
updates.AppendLine("} WHERE { }");
if (removals != null && removals.Any()) updates.AppendLine(";");
}
}
if (removals != null)
{
if (removals.Any())
{
// Insert preamble
// Note that we use DELETE DATA { } for deletes so we don't support deleting blank nodes
updates.AppendLine("DELETE DATA");
updates.AppendLine("{");
if (graphUri != null)
{
updates.AppendLine("GRAPH <" + _formatter.FormatUri(graphUri) + "> {");
}
// Serialize triples
foreach (Triple t in removals)
{
if (!t.IsGroundTriple) throw new RdfStorageException("The ReadWriteSparqlConnector does not support the deletion of blank node containing triples");
updates.AppendLine(" " + _formatter.Format(t));
}
// End
if (graphUri != null) updates.AppendLine(" }");
updates.AppendLine("}");
}
}
// Make an update if necessary
if (updates.Length > 0)
{
Update(updates.ToString());
}
}
/// <summary>
/// Makes a SPARQL Update against the store
/// </summary>
/// <param name="sparqlUpdate">SPARQL Update</param>
public void Update(string sparqlUpdate)
{
if (!_skipLocalParsing)
{
// Parse the update locally to validate it
// This also saves us wasting a HttpWebRequest on a malformed update
SparqlUpdateParser uparser = new SparqlUpdateParser();
uparser.ParseFromString(sparqlUpdate);
_updateEndpoint.Update(sparqlUpdate);
}
else
{
// If we're skipping local parsing then we'll need to just make a raw update
_updateEndpoint.Update(sparqlUpdate);
}
}
/// <summary>
/// Gets a String which gives details of the Connection
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "[SPARQL Query & Update] Query: " + _endpoint.Uri.AbsoluteUri + " Update: " + _updateEndpoint.Uri.AbsoluteUri;
}
/// <summary>
/// Serializes the connection's configuration
/// </summary>
/// <param name="context">Configuration Serialization Context</param>
public override void SerializeConfiguration(ConfigurationSerializationContext context)
{
// Call base SerializeConfiguration() first
INode manager = context.NextSubject;
context.NextSubject = manager;
base.SerializeConfiguration(context);
context.NextSubject = manager;
if (_updateEndpoint is IConfigurationSerializable)
{
// Use the indirect serialization method
// Serialize the Endpoints Configuration
INode endpoint = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUpdateEndpoint));
INode endpointObj = context.Graph.CreateBlankNode();
context.NextSubject = endpointObj;
((IConfigurationSerializable)_updateEndpoint).SerializeConfiguration(context);
// Link that serialization to our serialization
context.Graph.Assert(new Triple(manager, endpoint, endpointObj));
}
else
{
// Use the direct serialization method
INode endpointUri = context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUpdateEndpointUri));
context.Graph.Assert(new Triple(manager, endpointUri, context.Graph.CreateLiteralNode(_endpoint.Uri.AbsoluteUri)));
}
}
}
}
| 40.853231 | 673 | 0.569667 | [
"MIT"
] | DFihnn/dotnetrdf | Libraries/dotNetRDF/Storage/SparqlConnector.cs | 37,299 | C# |
using System;
using CMS.Base;
using CMS.Base.Web.UI;
using CMS.FormEngine.Web.UI;
using CMS.Globalization;
using CMS.Helpers;
using CMS.MacroEngine;
using CMS.Membership;
using CMS.Modules;
using CMS.SiteProvider;
using TimeZoneInfo = CMS.Globalization.TimeZoneInfo;
public partial class CMSFormControls_Macros_ConditionBuilder : FormEngineUserControl
{
#region "Properties"
/// <summary>
/// Gets ors sets value if the displayed text is User-Friendly representation of a macro.
/// </summary>
private string EditorValue
{
get
{
if (string.IsNullOrEmpty(hdnValue.Value))
{
return txtMacro.Text;
}
return hdnValue.Value;
}
}
/// <summary>
/// Indicates whether builder has more lines.
/// </summary>
public bool SingleLineMode
{
get
{
return ValidationHelper.GetBoolean(GetValue("SingleLineMode"), true);
}
set
{
SetValue("SingleLineMode", value);
txtMacro.SingleLineMode = value;
}
}
/// <summary>
/// Determines whether the global rules are shown among with the specific rules defined in the RuleCategoryNames property.
/// </summary>
public bool ShowGlobalRules
{
get
{
return ValidationHelper.GetBoolean(GetValue("ShowGlobalRules"), true);
}
set
{
SetValue("ShowGlobalRules", value);
}
}
/// <summary>
/// Gets or sets macro resolver name which should be used for macro editor (if no name is given, MacroResolver.Current is used).
/// </summary>
public override string ResolverName
{
get
{
return ValidationHelper.GetString(GetValue("ResolverName"), "");
}
set
{
SetValue("ResolverName", value);
}
}
/// <summary>
/// Gets or sets name(s) of the Macro rule category(ies) which should be displayed in Rule designer. Items should be separated by semicolon.
/// </summary>
public string RuleCategoryNames
{
get
{
return ValidationHelper.GetString(GetValue("RuleCategoryNames"), "");
}
set
{
SetValue("RuleCategoryNames", value);
}
}
/// <summary>
/// Determines which rules to display. 0 means all rules, 1 means only rules which does not require context, 2 only rules which require context.
/// </summary>
public int DisplayRuleType
{
get
{
return ValidationHelper.GetInteger(GetValue("DisplayRuleType"), 0);
}
set
{
SetValue("DisplayRuleType", value);
}
}
/// <summary>
/// Gets or sets he maximum width of conditional builder in pixels.
/// 0 mean unlimited and default value is 600px.
/// </summary>
public int MaxWidth
{
get
{
return ValidationHelper.GetInteger(GetValue("MaxWidth"), 600);
}
set
{
SetValue("MaxWidth", value);
}
}
/// <summary>
/// Gets or sets the enabled state of the control.
/// </summary>
public override bool Enabled
{
get
{
return txtMacro.Editor.Enabled;
}
set
{
txtMacro.Editor.Enabled = value;
btnEdit.Enabled = value;
btnClear.Enabled = value;
}
}
/// <summary>
/// Determines if value will be signed and wrapped in macro brackets.
/// </summary>
public bool AddDataMacroBrackets
{
get
{
return ValidationHelper.GetBoolean(GetValue("AddDataMacroBrackets"), true);
}
set
{
SetValue("AddDataMacroBrackets", value);
}
}
/// <summary>
/// Gets or sets the text which is displayed by default when there is no rule defined.
/// </summary>
public string DefaultConditionText
{
get
{
return ValidationHelper.GetString(GetValue("DefaultConditionText"), "");
}
set
{
SetValue("DefaultConditionText", value);
}
}
/// <summary>
/// Gets or sets field value.
/// </summary>
public override object Value
{
get
{
string val = MacroProcessor.RemoveDataMacroBrackets(EditorValue.Trim());
if (!string.IsNullOrEmpty(val))
{
if (AddDataMacroBrackets)
{
if (!(MacroStaticSettings.AllowOnlySimpleMacros || MacroSecurityProcessor.IsSimpleMacro(val)))
{
val = MacroSecurityProcessor.AddMacroSecurityParams(val, MacroIdentityOption.FromUserInfo(MembershipContext.AuthenticatedUser));
}
val = "{%" + val + "%}";
}
return val;
}
return string.Empty;
}
set
{
string val = MacroProcessor.RemoveDataMacroBrackets(ValidationHelper.GetString(value, ""));
MacroIdentityOption identityOption;
val = MacroSecurityProcessor.RemoveMacroSecurityParams(val, out identityOption);
hdnValue.Value = MacroProcessor.RemoveDataMacroBrackets(val.Trim());
RefreshText();
}
}
/// <summary>
/// If true, auto completion is shown above the editor, otherwise it is below (default position is below).
/// </summary>
public bool ShowAutoCompletionAbove
{
get
{
return ValidationHelper.GetBoolean(GetValue("ShowAutoCompletionAbove"), false);
}
set
{
SetValue("ShowAutoCompletionAbove", value);
txtMacro.ShowAutoCompletionAbove = value;
}
}
/// <summary>
/// Gets ClientID of the textbox with emailinput.
/// </summary>
public override string ValueElementID
{
get
{
return txtMacro.ClientID;
}
}
/// <summary>
/// Gets or sets the left offset of the autocomplete control (to position it correctly).
/// </summary>
public int LeftOffset
{
get
{
return txtMacro.LeftOffset;
}
set
{
txtMacro.LeftOffset = value;
}
}
/// <summary>
/// Gets or sets the top offset of the autocomplete control (to position it correctly).
/// </summary>
public int TopOffset
{
get
{
return txtMacro.TopOffset;
}
set
{
txtMacro.TopOffset = value;
}
}
/// <summary>
/// Client ID of primary input control.
/// </summary>
public override string InputClientID
{
get
{
if (pnlRule.Visible)
{
return pnlRule.ClientID;
}
else
{
return txtMacro.Editor.ClientID;
}
}
}
#endregion
/// <summary>
/// Page load.
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
// Set control style and css class
if (!string.IsNullOrEmpty(ControlStyle))
{
txtMacro.Editor.Attributes.Add("style", ControlStyle);
}
if (!string.IsNullOrEmpty(CssClass))
{
txtMacro.Editor.CssClass = CssClass;
}
txtMacro.ShowAutoCompletionAbove = ShowAutoCompletionAbove;
txtMacro.Editor.UseSmallFonts = true;
txtMacro.MixedMode = false;
MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(ResolverName);
if (resolver != null)
{
resolver.Settings.VirtualMode = true;
txtMacro.Resolver = resolver;
}
var ed = txtMacro.Editor;
ed.ShowToolbar = false;
ed.ShowLineNumbers = false;
ed.DynamicHeight = false;
string script = @"
function InsertMacroCondition" + ClientID + @"(text) {
var hidden = document.getElementById('" + hdnValue.ClientID + @"');
hidden.value = text;
" + ControlsHelper.GetPostBackEventReference(btnRefresh) + @";
}";
ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "InsertMacroCondition" + ClientID, script, true);
ScriptHelper.RegisterDialogScript(Page);
btnEdit.Click += btnEdit_Click;
btnRefresh.Click += btnRefresh_Click;
if (txtMacro.ReadOnly)
{
txtMacro.Editor.Language = LanguageEnum.Text;
}
if (MaxWidth > 0)
{
pnlConditionBuilder.Attributes["style"] += " max-width: " + MaxWidth + "px;";
}
txtMacro.DataBind();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
btnEdit.ToolTip = GetString("macrodesigner.edit");
if (!btnEdit.Enabled)
{
btnEdit.AddCssClass("ButtonDisabled");
}
btnClear.ToolTip = GetString("macrodesigner.clearcondition");
if (btnClear.Enabled)
{
btnClear.Attributes.Add("onclick", "if (confirm(" + ScriptHelper.GetString(GetString("macrodesigner.clearconditionconfirm")) + ")) { InsertMacroCondition" + ClientID + "(''); } return false;");
}
else
{
btnClear.AddCssClass("ButtonDisabled");
}
if (!Enabled)
{
// Disable the textbox
pnlRule.Attributes["disabled"] = "disabled";
}
}
protected void btnRefresh_Click(object sender, EventArgs e)
{
RefreshText();
}
private void RefreshText()
{
string hdnValueTrim = hdnValue.Value.Trim();
if (hdnValueTrim.StartsWithCSafe("rule(", true))
{
// Empty rule designer condition is not considered as rule conditions
if (hdnValueTrim.EqualsCSafe("Rule(\"\", \"<rules></rules>\")", true))
{
hdnValue.Value = "";
}
else
{
try
{
string ruleText = MacroRuleTree.GetRuleText(hdnValueTrim, true, true, TimeZoneTransformation);
// Display rule text
ltlMacro.Text = ruleText;
txtMacro.Visible = false;
pnlRule.Visible = true;
pnlUpdate.Update();
return;
}
catch
{
// If failed to parse the rule, extract the condition
MacroExpression xml = MacroExpression.ExtractParameter(hdnValueTrim, "rule", 0);
if (xml != null)
{
MacroIdentityOption identityOption;
hdnValue.Value = MacroSecurityProcessor.RemoveMacroSecurityParams(ValidationHelper.GetString(xml.Value, ""), out identityOption);
}
}
}
}
if (string.IsNullOrEmpty(hdnValue.Value) && !string.IsNullOrEmpty(DefaultConditionText))
{
ltlMacro.Text = DefaultConditionText;
txtMacro.Text = "";
txtMacro.Visible = false;
pnlRule.Visible = true;
}
else
{
txtMacro.Text = hdnValue.Value;
hdnValue.Value = null;
txtMacro.Visible = true;
pnlRule.Visible = false;
}
pnlUpdate.Update();
}
/// <summary>
/// Displays correct timezone for the rule parameter values.
/// </summary>
/// <param name="o">Parameter values</param>
private object TimeZoneTransformation(object o)
{
if (o is DateTime)
{
DateTime dt = (DateTime)o;
TimeZoneInfo usedTimeZone;
return TimeZoneHelper.GetCurrentTimeZoneDateTimeString(dt, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite, out usedTimeZone);
}
return o;
}
protected void btnEdit_Click(object sender, EventArgs e)
{
var controlHash = GetHashCode();
SessionHelper.SetValue("ConditionBuilderCondition_" + controlHash, EditorValue);
string dialogUrl = String.Format("{0}?clientid={1}&controlHash={2}&module={3}&ruletype={4}&showglobal={5}", ApplicationUrlHelper.ResolveDialogUrl("~/CMSFormControls/Macros/ConditionBuilder.aspx"), ClientID, controlHash, RuleCategoryNames, DisplayRuleType, ShowGlobalRules ? "1" : "0");
if (!string.IsNullOrEmpty(ResolverName))
{
SessionHelper.SetValue("ConditionBuilderResolver_" + controlHash, ResolverName);
}
if (!string.IsNullOrEmpty(DefaultConditionText))
{
SessionHelper.SetValue("ConditionBuilderDefaultText_" + controlHash, DefaultConditionText);
}
ScriptHelper.RegisterStartupScript(Page, typeof(string), "ConditionBuilderDialog", "modalDialog('" + dialogUrl + "', 'editmacrocondition', '95%', 700);", true);
}
} | 27.394191 | 293 | 0.559224 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSFormControls/Macros/ConditionBuilder.ascx.cs | 13,206 | 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("AbstractFactory")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AbstractFactory")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("be13a351-c364-46ef-8c4a-11eb67a30dcc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.783784 | 84 | 0.748927 | [
"MIT"
] | john29917958/Design-Pattern-Study | AbstractFactory/CSharp/AbstractFactory/AbstractFactory/Properties/AssemblyInfo.cs | 1,401 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//
// <summary>
// The all transient strategy.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace LoMo.TransientFaultHandling
{
using System;
using Microsoft.Practices.TransientFaultHandling;
/// <summary>
/// The all transient strategy.
/// </summary>
public class AllTransientStrategy : ITransientErrorDetectionStrategy
{
#region Public Methods and Operators
/// <summary>
/// Transient error detection - returns true always.
/// </summary>
/// <param name="ex">
/// The ex.
/// </param>
/// <returns> Always true </returns>
public bool IsTransient(Exception ex)
{
return true;
}
#endregion
}
} | 27.216216 | 119 | 0.536246 | [
"MIT"
] | BOONRewardsInc/rewards | Common/LoMo.TransientFaultHandling/AllTransientStrategy.cs | 1,007 | C# |
using System.Collections.Generic;
using commercetools.Common;
using Newtonsoft.Json;
namespace commercetools.Products
{
/// <summary>
/// An implementation of PagedQueryResult that provides access to the results as a List of Product objects.
/// </summary>
/// <see href="http://dev.commercetools.com/http-api.html#pagedqueryresult"/>
public class ProductQueryResult : PagedQueryResult
{
#region Properties
/// <summary>
/// Results
/// </summary>
[JsonProperty(PropertyName = "results")]
public List<Product> Results { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Initializes this instance with JSON data from an API response.
/// </summary>
/// <param name="data">JSON object</param>
public ProductQueryResult(dynamic data = null)
: base((object)data)
{
if (data == null)
{
return;
}
this.Offset = data.offset;
this.Count = data.count;
this.Total = data.total;
this.Results = Helper.GetListFromJsonArray<Product>(data.results);
}
#endregion
}
}
| 26.041667 | 111 | 0.576 | [
"MIT"
] | DavidDeVries/commercetools-dotnet-sdk | commercetools.NET/Products/ProductQueryResult.cs | 1,252 | C# |
using System;
using Handelabra;
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
using System.Collections;
namespace Memes.JustAField
{
public class VeryTallGrassCardController: CardController
{
public VeryTallGrassCardController(Card card, TurnTakerController turnTakerController)
: base(card, turnTakerController)
{
}
public override void AddTriggers()
{
// When this card is destroyed, play a Tall Grass from the environment trash.
this.AddWhenDestroyedTrigger(new Func<DestroyCardAction, IEnumerator>(this.OnDestroyResponse), TriggerType.PlayCard);
}
private IEnumerator OnDestroyResponse(DestroyCardAction dca)
{
// Play a Tall Grass from the environment trash.
var environmentPlayArea = new MoveCardDestination(this.TurnTaker.PlayArea);
var coroutine = this.GameController.SelectCardsFromLocationAndMoveThem(
this.DecisionMaker,
this.TurnTaker.Trash,
1,
1,
new LinqCardCriteria((Card c) => c.Identifier == "TallGrass" && c.IsInTrash),
environmentPlayArea.ToEnumerable<MoveCardDestination>(),
isPutIntoPlay: false,
playIfMovingToPlayArea: true,
shuffleAfterwards: false,
optional: false,
autoDecideCard: true,
allowAutoDecide: true,
selectionType: SelectionType.MoveCardToPlayArea,
cardSource: this.GetCardSource());
if (this.UseUnityCoroutines)
{
yield return this.GameController.StartCoroutine(coroutine);
}
else
{
this.GameController.ExhaustCoroutine(coroutine);
}
}
}
} | 35 | 120 | 0.641758 | [
"MIT"
] | FullPointerException/sotm-memes | MemesMod/JustAField/VeryTallGrassCardController.cs | 1,820 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
Type: Module
**
==============================================================*/
using global::System;
using global::System.Collections.Generic;
namespace System.Reflection
{
public abstract class Module
{
protected Module()
{
}
public virtual Assembly Assembly
{
get
{
throw NotImplemented.ByDesign;
}
}
public virtual IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
throw NotImplemented.ByDesign;
}
}
public virtual string FullyQualifiedName
{
get
{
throw NotImplemented.ByDesign;
}
}
public virtual String Name
{
get
{
throw NotImplemented.ByDesign;
}
}
// Equals() and GetHashCode() implement reference equality for compatibility with desktop.
// Unfortunately, this means that implementors who don't unify instances will be on the hook
// to override these implementations to test for semantic equivalence.
public override bool Equals(Object o)
{
return base.Equals(o);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public virtual Type GetType(String name, bool throwOnError, bool ignoreCase)
{
throw NotImplemented.ByDesign;
}
public override String ToString()
{
throw NotImplemented.ByDesign;
}
}
}
| 23.772152 | 101 | 0.511182 | [
"MIT"
] | ZZHGit/corert | src/System.Private.Reflection/src/System/Reflection/Module.cs | 1,878 | C# |
using System.Collections.Generic;
public class Tires
{
public Dictionary<double, int> tire;
public Tires()
{
this.tire = new Dictionary<double, int>();
}
} | 16.545455 | 50 | 0.631868 | [
"MIT"
] | sevdalin/Software-University-SoftUni | C-sharp-Web-Developer/C# OOP Basics/01. DefiningClasses/06. RawData/Tires.cs | 184 | C# |
namespace MailChimp.Api.Net.Domain.Lists
{
public class Contact
{
public string company { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public string country { get; set; }
public string phone { get; set; }
}
}
| 28.4 | 44 | 0.57277 | [
"MIT"
] | kinamarie016/MailChimp.Api.Net-master | MailChimp.Api.Net/Domain/Lists/Contact.cs | 428 | C# |
//
// https://docs.microsoft.com/fr-fr/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-implemenation-entity-framework-core
//
using DataMonitoring.DAL;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace DataMonitoring.Business
{
public class UnitOfWork : IUnitOfWork , IDisposable
{
protected readonly DbContext Context;
private IWidgetRepository _widgetRepository;
private ITimeManagementRepository _timeManagementRepository;
private IDashboardRepository _dashboardRepository;
private MonitorBusiness _monitorBusiness;
private IndicatorQueryBusiness _indicatorQueryBusiness;
private IndicatorDefinitionBusiness _indicatorDefinitionBusiness;
private ConfigurationBusiness _configurationBusiness;
private WidgetBusiness _widgetBusiness;
private DashboardBusiness _dashboardBusiness;
private TimeManagementBusiness _timeManagementBusiness;
public UnitOfWork() : this(new DataMonitoringDbContext())
{}
public UnitOfWork(DataMonitoringDbContext dataMonitorContext)
{
Context = dataMonitorContext;
}
public IRepository<TEntity> Repository<TEntity>() where TEntity : class
{
return new Repository<TEntity>(Context);
}
public IDashboardRepository DashboardRepository
{
get
{
return _dashboardRepository = _dashboardRepository ?? new DashboardRepository(Context);
}
}
public IWidgetRepository WidgetRepository
{
get
{
return _widgetRepository = _widgetRepository ?? new WidgetRepository(Context);
}
}
public ITimeManagementRepository TimeManagementRepository
{
get
{
return _timeManagementRepository = _timeManagementRepository ?? new TimeManagementRepository( Context );
}
}
public MonitorBusiness MonitorBusiness
{
get
{
return _monitorBusiness = _monitorBusiness ?? new MonitorBusiness((DataMonitoringDbContext)Context);
}
}
public IndicatorQueryBusiness IndicatorQueryBusiness
{
get
{
return _indicatorQueryBusiness = _indicatorQueryBusiness ?? new IndicatorQueryBusiness((DataMonitoringDbContext)Context);
}
}
public IndicatorDefinitionBusiness IndicatorDefinitionBusiness
{
get
{
return _indicatorDefinitionBusiness = _indicatorDefinitionBusiness ?? new IndicatorDefinitionBusiness((DataMonitoringDbContext)Context);
}
}
public WidgetBusiness WidgetBusiness
{
get
{
return _widgetBusiness = _widgetBusiness ?? new WidgetBusiness((DataMonitoringDbContext)Context);
}
}
public DashboardBusiness DashboardBusiness
{
get
{
return _dashboardBusiness = _dashboardBusiness ?? new DashboardBusiness((DataMonitoringDbContext)Context);
}
}
public TimeManagementBusiness TimeManagementBusiness
{
get
{
return _timeManagementBusiness = _timeManagementBusiness ?? new TimeManagementBusiness( (DataMonitoringDbContext)Context );
}
}
public ConfigurationBusiness ConfigurationBusiness
{
get
{
return _configurationBusiness = _configurationBusiness ?? new ConfigurationBusiness( (DataMonitoringDbContext)Context );
}
}
public int Save()
{
return Context.SaveChanges();
}
public async Task<int> SaveAsync()
{
return await Context.SaveChangesAsync();
}
public void Dispose()
{
Context.Dispose();
}
public IDatabaseTransaction BeginTransaction()
{
return new EntityDatabaseTransaction(Context);
}
}
}
| 30.432624 | 169 | 0.622233 | [
"MIT"
] | SoDevLog/DataMonitoring | DataMonitoring.Business/UnitOfWork.cs | 4,293 | C# |
using Ahegao.Models;
using Ahegao.SitesParsers;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Ahegao.Data
{
/// <summary>
/// Class to access the Sites database
/// </summary>
public class SiteContext : DbContext
{
private DbSet<Site> Sites { get; set; }
public SiteContext(DbContextOptions<SiteContext> options) : base(options) { }
/// <summary>
/// Get all the sites from the database asynchronously
/// </summary>
/// <returns>The list of retieved sites</returns>
public async Task<IList<Site>> GetAllAsync()
{
return await Sites.ToListAsync();
}
/// <summary>
/// Convert the site Id to the ISite Type
/// </summary>
/// <param name="id">Id of the site</param>
/// <returns>The Type T to use in the HentaiParser<T></returns>
public Type IdToType(int id)
{
return id switch
{
1 => typeof(Nhentai),
2 => typeof(Tsumino),
3 => typeof(Hentai2Read),
4 => typeof(HentaiNexus),
_ => typeof(Nhentai),
};
}
}
}
| 27.782609 | 85 | 0.552426 | [
"Apache-2.0"
] | Julien-Torrent/Ahegao | Ahegao/Data/SiteContext.cs | 1,280 | C# |
// Tests anonymous types
using System;
using System.Collections;
namespace anontype01
{
public class Test
{
static int Test1()
{
var v = new { Foo = "Bar", Baz = 42 };
if (v.Foo != "Bar")
return 1;
if (v.Baz != 42)
return 2;
return 0;
}
static void Main()
{
Console.WriteLine(Test1());
Console.WriteLine("<%END%>");
}
}
}
| 19.730769 | 51 | 0.409357 | [
"MIT"
] | GrapeCity/pagefx | tests/Simple/mcs/gtest-anontype-01.cs | 513 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Bdd.Tests
{
public class TestPriorityOrderer : ITestCaseOrderer
{
public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases)
where TTestCase : ITestCase
{
var sortedMethods = new SortedDictionary<int, List<TTestCase>>();
foreach (TTestCase testCase in testCases)
{
int priority = 0;
foreach (IAttributeInfo attr in testCase.TestMethod.Method.GetCustomAttributes(
(typeof(TestPriorityAttribute).AssemblyQualifiedName)))
priority = attr.GetNamedArgument<int>("Priority");
GetOrCreate(sortedMethods, priority).Add(testCase);
}
foreach (var list in sortedMethods.Keys.Select(priority => sortedMethods[priority]))
{
list.Sort((x, y) =>
StringComparer.OrdinalIgnoreCase.Compare(x.TestMethod.Method.Name, y.TestMethod.Method.Name));
foreach (TTestCase testCase in list)
yield return testCase;
}
}
static TValue GetOrCreate<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey key) where TValue : new()
{
TValue result;
if (dictionary.TryGetValue(key, out result)) return result;
result = new TValue();
dictionary[key] = result;
return result;
}
}
} | 32.9375 | 116 | 0.600253 | [
"MIT"
] | monkieboy/Testify | Bdd.Tests/TestPriorityOrderer.cs | 1,581 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Yunjing.V20180228.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeWeeklyReportsRequest : AbstractModel
{
/// <summary>
/// 返回数量,默认为10,最大值为100。
/// </summary>
[JsonProperty("Limit")]
public ulong? Limit{ get; set; }
/// <summary>
/// 偏移量,默认为0。
/// </summary>
[JsonProperty("Offset")]
public ulong? Offset{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Limit", this.Limit);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
}
}
}
| 29.176471 | 83 | 0.633065 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Yunjing/V20180228/Models/DescribeWeeklyReportsRequest.cs | 1,554 | C# |
using System;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Core.Domain
{
/// <summary>
/// ZhimaCreditScoreBriefGetModel Data Structure.
/// </summary>
[Serializable]
public class ZhimaCreditScoreBriefGetModel : AopObject
{
/// <summary>
/// 350~950之间 业务判断的准入标准 建议业务确定一个稳定的判断标准 频繁的变更该标准可能导致接口被停用
/// </summary>
[XmlElement("admittance_score")]
public long AdmittanceScore { get; set; }
/// <summary>
/// 对应的证件号(未脱敏)或支付宝uid
/// </summary>
[XmlElement("cert_no")]
public string CertNo { get; set; }
/// <summary>
/// 证件类型 目前支持三种IDENTITY_CARD(身份证),PASSPORT(护照),ALIPAY_USER_ID(支付宝uid)
/// </summary>
[XmlElement("cert_type")]
public string CertType { get; set; }
/// <summary>
/// 芝麻平台服务商模式下的二级商户标识,如果是直连商户调用该接口,不需要设置
/// </summary>
[XmlElement("linked_merchant_id")]
public string LinkedMerchantId { get; set; }
/// <summary>
/// 用户姓名 当证件类型为ALIPAY_USER_ID时不需要传入
/// </summary>
[XmlElement("name")]
public string Name { get; set; }
/// <summary>
/// 产品码,直接使用[示例]给出的值
/// </summary>
[XmlElement("product_code")]
public string ProductCode { get; set; }
/// <summary>
/// 商户请求的唯一标志,64位长度的字母数字下划线组合。该标识作为对账的关键信息,商户要保证其唯一性,对于用户使用相同transaction_id的查询,芝麻在一天(86400秒)内返回首次查询数据,超过有效期的查询即为无效并返回异常,有效期内的重复查询不重新计费
/// </summary>
[XmlElement("transaction_id")]
public string TransactionId { get; set; }
}
}
| 29.345455 | 142 | 0.5886 | [
"MIT"
] | leixf2005/Alipay.AopSdk.Core | Alipay.AopSdk.Core/Domain/ZhimaCreditScoreBriefGetModel.cs | 2,118 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.DynamoDBv2.Model
{
///<summary>
/// DynamoDB exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class ResourceInUseException : AmazonDynamoDBException
{
/// <summary>
/// Constructs a new ResourceInUseException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ResourceInUseException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ResourceInUseException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ResourceInUseException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ResourceInUseException
/// </summary>
/// <param name="innerException"></param>
public ResourceInUseException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ResourceInUseException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ResourceInUseException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ResourceInUseException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ResourceInUseException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the ResourceInUseException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected ResourceInUseException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 42.731959 | 178 | 0.646803 | [
"Apache-2.0"
] | AltairMartinez/aws-sdk-unity-net | src/Services/DynamoDBv2/Generated/Model/ResourceInUseException.cs | 4,145 | C# |
using EventBus.Messages.Common;
using MassTransit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Ordering.API.EventBusConsumer;
using Ordering.Application;
using Ordering.Infrastructure;
namespace Ordering.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationServices();
services.AddInfrastructureServices(Configuration);
// General Configuration
services.AddAutoMapper(typeof(Startup));
services.AddScoped<BasketCheckoutConsumer>();
//to register mass transit connection
services.AddMassTransit(config =>
{
//we will consume from basket thus we need the line below
config.AddConsumer<BasketCheckoutConsumer>();
config.UsingRabbitMq((ctx, cfg) =>
{
cfg.Host(Configuration["EventBusSettings:HostAddress"]);
// amqp protocol is the queue protocol of Rabbit MQ
cfg.ReceiveEndpoint(EventBusConstants.BasketCheckoutQueue, c => {
c.ConfigureConsumer<BasketCheckoutConsumer>(ctx);
});
});
});
services.AddMassTransitHostedService();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Ordering.API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ordering.API v1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
} | 32.864198 | 106 | 0.596544 | [
"MIT"
] | erolsonmez95/AspnetMicroservices | src/Services/Ordering/Ordering.API/Startup.cs | 2,662 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
// See the LICENSE.md file in the project root for full license information.
#if STRIDE_UI_WINFORMS || STRIDE_UI_WPF
using System;
using System.Windows.Forms;
namespace Stride.Games
{
/// <summary>
/// Represents a <see cref="GameContext"/> that can be used for rendering to an existing WinForms <see cref="Control"/>.
/// </summary>
public class GameContextWinforms : GameContext<Control>
{
/// <inheritDoc/>
/// <param name="isUserManagingRun">A value indicating if the user will manage the event processing of <paramref name="control"/>.</param>
public GameContextWinforms(Control control, int requestedWidth = 0, int requestedHeight = 0, bool isUserManagingRun = false)
: base(control ?? CreateForm(), requestedWidth, requestedHeight, isUserManagingRun)
{
ContextType = AppContextType.Desktop;
}
private static Form CreateForm()
{
#if !STRIDE_GRAPHICS_API_NULL
return new GameForm();
#else
// Not Reachable.
return null;
#endif
}
}
}
#endif
| 34.85 | 146 | 0.672884 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Games/GameContextWinforms.cs | 1,394 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.FaceAnalysis;
using Windows.Media.MediaProperties;
using Windows.System.Threading;
namespace FaceTheremin
{
public class FaceMatrix
{
private readonly int _rowsCount;
private readonly int _columnsCount;
// FaceTracker detects faces
private readonly FaceTracker _faceTracker;
// MediaCapture provides source for streaming element and frames for face detection
private readonly MediaCapture _mediaCapture;
// Time interval between two separate face detections (8.33 fps)
private readonly TimeSpan _frameProcessingTimerInterval = TimeSpan.FromMilliseconds(120);
// The cells which had faces on a previous frame
private readonly List<Cell> _previousFrameCells = new List<Cell>();
private readonly VideoFrame _previewFrame;
public event EventHandler<FaceMatrixFrameEventArgs> Frame;
private FaceMatrix(FaceTracker faceTracker, MediaCapture mediaCapture, int rowsCount, int columnsCount)
{
_faceTracker = faceTracker;
_mediaCapture = mediaCapture;
// get properties of the stream, we need them to get width/height for face detection
var videoProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
_previewFrame = new VideoFrame(BitmapPixelFormat.Nv12, (int)videoProperties.Width, (int)videoProperties.Height);
_rowsCount = rowsCount;
_columnsCount = columnsCount;
}
public static async Task<FaceMatrix> CreateAsync(MediaCapture mediaCapture, int rowsCount, int columnsCount)
{
var faceTracker = await FaceTracker.CreateAsync();
var faceMatrix = new FaceMatrix(faceTracker, mediaCapture, rowsCount, columnsCount);
faceMatrix.StartRecognitionLoop();
return faceMatrix;
}
private void StartRecognitionLoop()
{
ThreadPoolTimer.CreateTimer(ProcessCurrentVideoFrameAsync, _frameProcessingTimerInterval);
}
/// <summary>
/// Detect faces and process them
/// </summary>
/// <param name="timer"></param>
private async void ProcessCurrentVideoFrameAsync(ThreadPoolTimer timer)
{
// fill the frame
await _mediaCapture.GetPreviewFrameAsync(_previewFrame);
// collection for faces
IList<DetectedFace> faces;
if (FaceDetector.IsBitmapPixelFormatSupported(_previewFrame.SoftwareBitmap.BitmapPixelFormat))
{
// get detected faces on the frame
faces = await _faceTracker.ProcessNextFrameAsync(_previewFrame);
}
else
{
throw new NotSupportedException($"PixelFormat {BitmapPixelFormat.Nv12} is not supported by FaceDetector.");
}
// get the size of frame webcam provided, we need it to scale image on the screen
var previewFrameSize = new Size(_previewFrame.SoftwareBitmap.PixelWidth, _previewFrame.SoftwareBitmap.PixelHeight);
ProcessFrameFaces(previewFrameSize, faces);
// arrange the next processing time
ThreadPoolTimer.CreateTimer(ProcessCurrentVideoFrameAsync, _frameProcessingTimerInterval);
}
/// <summary>
/// Color the cells with faces and play sounds for them
/// </summary>
/// <param name="previewFrameSize">Webcam resolution</param>
/// <param name="faces"></param>
private void ProcessFrameFaces(Size previewFrameSize, IList<DetectedFace> faces)
{
// get cells with faces
var cells = faces.Select(x => CreateFaceCell(previewFrameSize, x)).ToArray();
// exclude cells were on the previous frame
var newCells = cells.Except(_previousFrameCells).ToArray();
OnFrame(new FaceMatrixFrameEventArgs
{
PreviewFrameSize = previewFrameSize,
DetectedFaces = faces.ToArray(),
PreviousFaceCells = _previousFrameCells.ToArray(),
NewFaceCells = newCells.ToArray()
});
// remember current cells with faces for next frame processing
_previousFrameCells.Clear();
_previousFrameCells.AddRange(cells);
}
/// <summary>
/// Get the cell for a face
/// </summary>
/// <param name="previewFrameSize">Webcam resolution</param>
/// <param name="face">Detected face</param>
/// <returns>Cell</returns>
private Cell CreateFaceCell(Size previewFrameSize, DetectedFace face)
{
var cellX = (face.FaceBox.X + face.FaceBox.Width / 2) / (uint)(previewFrameSize.Width / _columnsCount);
var cellY = (face.FaceBox.Y + face.FaceBox.Height / 2) / (uint)(previewFrameSize.Height / _rowsCount);
return new Cell((int)cellX, (int)cellY);
}
protected virtual void OnFrame(FaceMatrixFrameEventArgs e)
{
Frame?.Invoke(this, e);
}
}
public class FaceMatrixFrameEventArgs : EventArgs
{
public Size PreviewFrameSize { get; set; }
public IList<DetectedFace> DetectedFaces { get; set; }
public IList<Cell> PreviousFaceCells { get; set; }
public IList<Cell> NewFaceCells { get; set; }
}
} | 40.207792 | 152 | 0.637274 | [
"MIT"
] | 9112Michael/Coding4Fun | FaceTheremin/FaceTheremin/FaceTheremin/FaceMatrix.cs | 6,192 | C# |
using System.Collections.Generic;
namespace WK.Info.Services
{
public class WaniKaniUserInformation
{
public int Level { get; set; }
public string Title { get; set; }
public string Username { get; set; }
}
public class WaniKaniVocab
{
public int Level { get; set; }
public string Character { get; set; }
public string Kana { get; set; }
public string Meaning { get; set; }
}
public class WaniKaniVocabModelRequestedInformation
{
public List<WaniKaniVocab> General { get; set; }
}
public class WaniKaniVocabModel
{
public WaniKaniUserInformation UserInformation { get; set; }
public WaniKaniVocabModelRequestedInformation RequestedInformation { get; set; }
}
public class WaniKaniKanji
{
public int Level { get; set; }
public string Character { get; set; }
public string Meaning { get; set; }
public string Onyomi { get; set; }
public string Kunyomi { get; set; }
public string ImportantReading { get; set; }
public string Nanori { get; set; }
}
public class WaniKaniKanjiModel
{
public WaniKaniUserInformation UserInformation { get; set; }
public List<WaniKaniKanji> RequestedInformation { get; set; }
}
}
| 24.354167 | 82 | 0.716852 | [
"MIT"
] | luffyuzumaki/WK.Info | WK.Info/Services/Models/WaniKani.cs | 1,171 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Clare.ECommerce.Authorization.Users;
namespace Clare.ECommerce.Users.Dto
{
[AutoMapFrom(typeof(User))]
public class UserDto : EntityDto<long>
{
[Required]
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[Required]
[EmailAddress]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
public bool IsActive { get; set; }
public string FullName { get; set; }
public DateTime? LastLoginTime { get; set; }
public DateTime CreationTime { get; set; }
public string[] RoleNames { get; set; }
}
}
| 25.853659 | 57 | 0.653774 | [
"MIT"
] | clarechan95/ECommerce | aspnet-core/src/Clare.ECommerce.Application/Users/Dto/UserDto.cs | 1,060 | C# |
namespace SMS.Data
{
public class DatabaseConfiguration
{
// ReSharper disable once InconsistentNaming
public const string ConnectionString =
@"Server=.;Database=Sms;User Id = sa; Password=SoftUn!2021;";
}
}
| 24.9 | 73 | 0.650602 | [
"MIT"
] | mirakis97/C-Web | C#Web Basics/Exams/SMS Stamo Solution/SMS/Data/DatabaseConfiguration.cs | 251 | C# |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V8.Common;
using Google.Ads.GoogleAds.V8.Enums;
using Google.Ads.GoogleAds.V8.Errors;
using Google.Ads.GoogleAds.V8.Resources;
using Google.Ads.GoogleAds.V8.Services;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V8.Enums.LeadFormCallToActionTypeEnum.Types;
using static Google.Ads.GoogleAds.V8.Enums.LeadFormFieldUserInputTypeEnum.Types;
using static Google.Ads.GoogleAds.V8.Enums.LeadFormPostSubmitCallToActionTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V8
{
/// <summary>
/// This code example creates a lead form and a lead form extension for a campaign. Run
/// AddCampaigns.cs to create a campaign.
/// </summary>
public class AddLeadFormExtension : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddLeadFormExtension"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the campaign to which lead form extensions are added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"ID of the campaign to which lead form extensions are added.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// ID of the campaign to which lead form extensions are added.
options.CampaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
return 0;
});
AddLeadFormExtension codeExample = new AddLeadFormExtension();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example creates a lead form and a lead form extension for a campaign. " +
"Run AddCampaigns.cs to create a campaign.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">
/// ID of the campaign to which lead form extensions are added.
/// </param>
public void Run(GoogleAdsClient client, long customerId, long campaignId)
{
try
{
// Create a lead form asset.
string leadFormAssetResourceName = CreateLeadFormAsset(client, customerId);
// Create a lead form extension for the campaign.
CreateLeadFormExtension(client, customerId, campaignId, leadFormAssetResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the lead form extension.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">
/// ID of the campaign to which lead form extensions are added.
/// </param>
/// <param name="leadFormAssetResourceName">The lead form asset resource name.</param>
// [START add_lead_form_extension_1]
private void CreateLeadFormExtension(GoogleAdsClient client, long customerId,
long campaignId, string leadFormAssetResourceName)
{
CampaignAssetServiceClient campaignAssetService = client.GetService(
Services.V8.CampaignAssetService);
// Creates the campaign asset for the lead form.
CampaignAsset campaignAsset = new CampaignAsset()
{
Asset = leadFormAssetResourceName,
FieldType = AssetFieldTypeEnum.Types.AssetFieldType.LeadForm,
Campaign = ResourceNames.Campaign(customerId, campaignId),
};
CampaignAssetOperation operation = new CampaignAssetOperation()
{
Create = campaignAsset
};
MutateCampaignAssetsResponse response = campaignAssetService.MutateCampaignAssets(
customerId.ToString(), new[] { operation });
foreach (MutateCampaignAssetResult result in response.Results)
{
Console.WriteLine("Created campaign asset with resource name =" +
$" '{result.ResourceName}' for campaign ID {campaignId}.");
}
}
// [END add_lead_form_extension_1]
/// <summary>
/// Creates the lead form asset.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <returns>The lead form asset resource name.</returns>
// [START add_lead_form_extension]
private string CreateLeadFormAsset(GoogleAdsClient client, long customerId)
{
AssetServiceClient assetService = client.GetService(Services.V8.AssetService);
// Creates the lead form asset.
Asset leadFormAsset = new Asset()
{
Name = $"Interplanetary Cruise #{ExampleUtilities.GetRandomString()} Lead Form",
LeadFormAsset = new LeadFormAsset()
{
// Specify the details of the extension that the users will see.
CallToActionType = LeadFormCallToActionType.BookNow,
CallToActionDescription = "Latest trip to Jupiter!",
// Define the form details.
BusinessName = "Interplanetary Cruise",
Headline = "Trip to Jupiter",
Description = "Our latest trip to Jupiter is now open for booking.",
PrivacyPolicyUrl = "http://example.com/privacy",
// Define the fields to be displayed to the user.
Fields = {
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.FullName,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.Email,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PhoneNumber,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PreferredContactTime,
SingleChoiceAnswers = new LeadFormSingleChoiceAnswers()
{
Answers = { "Before 9 AM", "Any time", "After 5 PM" }
}
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.TravelBudget,
},
},
// Optional: You can also specify a background image asset. To upload an asset,
// see Misc/UploadImageAsset.cs. BackgroundImageAsset =
// "INSERT_IMAGE_ASSET_HERE",
// Optional: Define the response page after the user signs up on the form.
PostSubmitHeadline = "Thanks for signing up!",
PostSubmitDescription = "We will reach out to you shortly. Visit our website " +
"to see past trip details.",
PostSubmitCallToActionType = LeadFormPostSubmitCallToActionType.VisitSite,
// Optional: Display a custom disclosure that displays along with the Google
// disclaimer on the form.
CustomDisclosure = "Trip may get cancelled due to meteor shower.",
// Optional: Define a delivery method for the form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
DeliveryMethods =
{
new LeadFormDeliveryMethod()
{
Webhook = new WebhookDelivery()
{
AdvertiserWebhookUrl = "http://example.com/webhook",
GoogleSecret = "interplanetary google secret",
PayloadSchemaVersion = 3L
}
}
},
},
FinalUrls = { "http://example.com/jupiter" }
};
// Creates the operation.
AssetOperation operation = new AssetOperation()
{
Create = leadFormAsset,
};
// Makes the API call.
MutateAssetsResponse response = assetService.MutateAssets(customerId.ToString(),
new[] { operation });
string leadFormAssetResourceName = response.Results[0].ResourceName;
// Displays the result.
Console.WriteLine($"Asset with resource name = '{leadFormAssetResourceName}' " +
"was created.");
return leadFormAssetResourceName;
}
// [END add_lead_form_extension]
}
}
| 43.520599 | 100 | 0.554819 | [
"Apache-2.0"
] | deni-skaraudio/google-ads-dotnet | examples/Extensions/AddLeadFormExtension.cs | 11,620 | 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/d3d11.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public partial struct D3D11_FEATURE_DATA_D3D11_OPTIONS3
{
[NativeTypeName("BOOL")]
public int VPAndRTArrayIndexFromAnyShaderFeedingRasterizer;
}
}
| 34.785714 | 145 | 0.753593 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/d3d11/D3D11_FEATURE_DATA_D3D11_OPTIONS3.cs | 489 | C# |
// Copyright (c) 2020 Flucto Team and others. Licensed under the MIT Licence.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using flucto.Extensions.TypeExtensions;
using flucto.Graphics.Containers;
namespace flucto.Allocation
{
/// <summary>
/// Helper class that provides methods to merge dependencies of objects and inject dependencies into objects.
/// The process of merging/injecting dependencies into objects happens in a "bottom-up" manner from least derived to most derived.
/// E.g. Drawable -> CompositeDrawable -> Toolbar, etc...
/// </summary>
/// <remarks>
/// Injection of dependencies is ordered into two processes:
/// <para>1) Inject into properties marked with <see cref="ResolvedAttribute"/>.</para>
/// 2) Invoke methods marked with <see cref="BackgroundDependencyLoaderAttribute"/>.
/// </remarks>
internal class DependencyActivator
{
private static readonly ConcurrentDictionary<Type, DependencyActivator> activator_cache = new ConcurrentDictionary<Type, DependencyActivator>();
private readonly List<InjectDependencyDelegate> injectionActivators = new List<InjectDependencyDelegate>();
private readonly List<CacheDependencyDelegate> buildCacheActivators = new List<CacheDependencyDelegate>();
private readonly DependencyActivator baseActivator;
private DependencyActivator(Type type)
{
injectionActivators.Add(ResolvedAttribute.CreateActivator(type));
injectionActivators.Add(BackgroundDependencyLoaderAttribute.CreateActivator(type));
buildCacheActivators.Add(CachedAttribute.CreateActivator(type));
if (type.BaseType != typeof(object))
baseActivator = getActivator(type.BaseType);
activator_cache[type] = this;
}
/// <summary>
/// Injects dependencies from a <see cref="DependencyContainer"/> into an object.
/// </summary>
/// <param name="obj">The object to inject the dependencies into.</param>
/// <param name="dependencies">The dependencies to use for injection.</param>
public static void Activate(object obj, IReadOnlyDependencyContainer dependencies)
=> getActivator(obj.GetType()).activate(obj, dependencies);
/// <summary>
/// Merges existing dependencies with new dependencies from an object into a new <see cref="IReadOnlyDependencyContainer"/>.
/// </summary>
/// <param name="obj">The object whose dependencies should be merged into the dependencies provided by <paramref name="dependencies"/>.</param>
/// <param name="dependencies">The existing dependencies.</param>
/// <param name="info">Extra information to identify parameters of <paramref name="obj"/> in the cache with.</param>
/// <returns>A new <see cref="IReadOnlyDependencyContainer"/> if <paramref name="obj"/> provides any dependencies, otherwise <paramref name="dependencies"/>.</returns>
public static IReadOnlyDependencyContainer MergeDependencies(object obj, IReadOnlyDependencyContainer dependencies, CacheInfo info = default)
=> getActivator(obj.GetType()).mergeDependencies(obj, dependencies, info);
private static DependencyActivator getActivator(Type type)
{
if (!activator_cache.TryGetValue(type, out var existing))
return activator_cache[type] = new DependencyActivator(type);
return existing;
}
private void activate(object obj, IReadOnlyDependencyContainer dependencies)
{
baseActivator?.activate(obj, dependencies);
foreach (var a in injectionActivators)
a(obj, dependencies);
}
private IReadOnlyDependencyContainer mergeDependencies(object obj, IReadOnlyDependencyContainer dependencies, CacheInfo info)
{
dependencies = baseActivator?.mergeDependencies(obj, dependencies, info) ?? dependencies;
foreach (var a in buildCacheActivators)
dependencies = a(obj, dependencies, info);
return dependencies;
}
}
/// <summary>
/// Occurs when multiple <see cref="BackgroundDependencyLoaderAttribute"/>s exist in one object.
/// </summary>
public class MultipleDependencyLoaderMethodsException : Exception
{
public MultipleDependencyLoaderMethodsException(Type type)
: base($"The type {type.ReadableName()} has more than one method marked with a {nameof(BackgroundDependencyLoaderAttribute)}."
+ "Any given type may only have one such method.")
{
}
}
/// <summary>
/// Occurs when an object requests the resolution of a dependency, but the dependency doesn't exist.
/// This is caused by the dependency not being registered by parent <see cref="CompositeDrawable"/> through
/// <see cref="CompositeDrawable.CreateChildDependencies"/> or <see cref="CachedAttribute"/>.
/// </summary>
public class DependencyNotRegisteredException : Exception
{
public DependencyNotRegisteredException(Type type, Type requestedType)
: base($"The type {type.ReadableName()} has a dependency on {requestedType.ReadableName()}, but the dependency is not registered.")
{
}
}
/// <summary>
/// Occurs when a dependency-related operation occurred on a member with an unacceptable access modifier.
/// </summary>
public abstract class AccessModifierNotAllowedForMemberException : InvalidOperationException
{
protected AccessModifierNotAllowedForMemberException(AccessModifier modifier, MemberInfo member, string description)
: base($"The access modifier(s) [ {modifier.ToString()} ] are not allowed on \"{member.DeclaringType.ReadableName()}.{member.Name}\". {description}")
{
}
}
/// <summary>
/// Occurs when attempting to cache a non-private and non-readonly field with an attached <see cref="CachedAttribute"/>.
/// </summary>
public class AccessModifierNotAllowedForCachedValueException : AccessModifierNotAllowedForMemberException
{
public AccessModifierNotAllowedForCachedValueException(AccessModifier modifier, MemberInfo member)
: base(modifier, member, $"A field with an attached {nameof(CachedAttribute)} must be private, readonly,"
+ " or be an auto-property with a getter and private (or non-existing) setter.")
{
}
}
/// <summary>
/// Occurs when a method with an attached <see cref="BackgroundDependencyLoaderAttribute"/> isn't private.
/// </summary>
public class AccessModifierNotAllowedForLoaderMethodException : AccessModifierNotAllowedForMemberException
{
public AccessModifierNotAllowedForLoaderMethodException(AccessModifier modifier, MemberInfo member)
: base(modifier, member, $"A method with an attached {nameof(BackgroundDependencyLoaderAttribute)} must be private.")
{
}
}
/// <summary>
/// Occurs when the setter of a property with an attached <see cref="ResolvedAttribute"/> isn't private.
/// </summary>
public class AccessModifierNotAllowedForPropertySetterException : AccessModifierNotAllowedForMemberException
{
public AccessModifierNotAllowedForPropertySetterException(AccessModifier modifier, MemberInfo member)
: base(modifier, member, $"A property with an attached {nameof(ResolvedAttribute)} must have a private setter.")
{
}
}
internal delegate void InjectDependencyDelegate(object target, IReadOnlyDependencyContainer dependencies);
internal delegate IReadOnlyDependencyContainer CacheDependencyDelegate(object target, IReadOnlyDependencyContainer existingDependencies, CacheInfo info);
}
| 49.711656 | 175 | 0.700605 | [
"MIT"
] | flucto/flucto | flucto/Allocation/DependencyActivator.cs | 8,103 | 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 securityhub-2018-10-26.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.SecurityHub.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for AwsEc2NetworkInterfaceIpV6AddressDetail Object
/// </summary>
public class AwsEc2NetworkInterfaceIpV6AddressDetailUnmarshaller : IUnmarshaller<AwsEc2NetworkInterfaceIpV6AddressDetail, XmlUnmarshallerContext>, IUnmarshaller<AwsEc2NetworkInterfaceIpV6AddressDetail, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
AwsEc2NetworkInterfaceIpV6AddressDetail IUnmarshaller<AwsEc2NetworkInterfaceIpV6AddressDetail, 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 AwsEc2NetworkInterfaceIpV6AddressDetail Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
AwsEc2NetworkInterfaceIpV6AddressDetail unmarshalledObject = new AwsEc2NetworkInterfaceIpV6AddressDetail();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("IpV6Address", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.IpV6Address = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static AwsEc2NetworkInterfaceIpV6AddressDetailUnmarshaller _instance = new AwsEc2NetworkInterfaceIpV6AddressDetailUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static AwsEc2NetworkInterfaceIpV6AddressDetailUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.815217 | 230 | 0.673162 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/AwsEc2NetworkInterfaceIpV6AddressDetailUnmarshaller.cs | 3,387 | 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 Xunit;
namespace System.Globalization.Tests
{
public static class CalendarHelpers
{
public enum DataType
{
Year = 1,
Month = 2,
Day = 8
}
public static Calendar[] s_calendars = new Calendar[]
{
new ThaiBuddhistCalendar(),
new JapaneseCalendar(),
new KoreanCalendar(),
new TaiwanCalendar(),
new GregorianCalendar(GregorianCalendarTypes.Arabic),
new GregorianCalendar(GregorianCalendarTypes.Localized),
new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench),
new GregorianCalendar(GregorianCalendarTypes.TransliteratedEnglish),
new GregorianCalendar(GregorianCalendarTypes.TransliteratedFrench),
new GregorianCalendar(GregorianCalendarTypes.USEnglish),
new HijriCalendar(),
new HebrewCalendar(),
new JulianCalendar(),
new TaiwanLunisolarCalendar(),
new ChineseLunisolarCalendar(),
new KoreanLunisolarCalendar(),
new PersianCalendar(),
new JapaneseLunisolarCalendar(),
new UmAlQuraCalendar()
};
private static int MinEra(Calendar calendar) => calendar.GetEra(calendar.MinSupportedDateTime);
private static int MaxEra(Calendar calendar) => calendar.GetEra(calendar.MaxSupportedDateTime);
private static int MaxCalendarYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[0] || era == 0)
{
return calendar.GetYear(calendar.MaxSupportedDateTime);
}
return calendar.GetYear(calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era + 1).AddDays(-1)) + 1;
}
private static int MaxGregorianYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[0] || era == 0)
{
return calendar.MaxSupportedDateTime.Year;
}
return (calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era + 1).AddDays(-1)).Year;
}
private static int MinGregorianYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[eras.Length - 1] || era == 0)
{
return calendar.MinSupportedDateTime.Year;
}
return calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era).Year;
}
private static int MinCalendarYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[eras.Length - 1] || era == 0)
{
return calendar.GetYear(calendar.MinSupportedDateTime);
}
return calendar.GetYear(calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era));
}
public static IEnumerable<object[]> Calendars_TestData()
{
foreach (Calendar calendar in s_calendars)
{
yield return new object[] { calendar };
}
}
public static IEnumerable<object[]> Year_Month_Day_Era_TestData(DataType type, bool ignoreJapaneseLunisolarCalendar)
{
int month = 1;
int day = 1;
foreach (Calendar calendar in s_calendars)
{
if (ignoreJapaneseLunisolarCalendar && calendar is JapaneseLunisolarCalendar)
{
// desktop has a bug in JapaneseLunisolarCalendar which is fixed in .Net Core.
// in case of a new era starts in the middle of a month which means part of the month will belong to one
// era and the rest will belong to the new era. When calculating the calendar year number for dates which
// in the rest of the month and exist in the new started era, we should still use the old era info instead
// of the new era info because the rest of the month still belong to the year of last era.
// https://github.com/dotnet/coreclr/pull/3662
continue;
}
foreach (int era in calendar.Eras)
{
int year = MaxCalendarYearInEra(calendar, era) - 2;
// Year is invalid
yield return new object[] { calendar, -1, month, day, era, "year" };
yield return new object[] { calendar, 0, month, day, era, "year" };
yield return new object[] { calendar, MaxCalendarYearInEra(calendar, era) + 1, month, day, era, "year" };
if ((type & DataType.Month) != 0)
{
// Month is invalid
yield return new object[] { calendar, year, -1, day, era, "month" };
yield return new object[] { calendar, year, 0, day, era, "month" };
yield return new object[] { calendar, year, calendar.GetMonthsInYear(year, era) + 1, day, era, "month" };
}
if ((type & DataType.Day) != 0)
{
// Day is invalid
yield return new object[] { calendar, year, month, -1, era, "day" };
yield return new object[] { calendar, year, month, 0, era, "day" };
yield return new object[] { calendar, year, month, calendar.GetDaysInMonth(year, month, era) + 1, era, "day" };
}
}
// Year is invalid
yield return new object[] { calendar, MinCalendarYearInEra(calendar, MinEra(calendar)) - 1, month, day, MinEra(calendar), "year" };
// Era is invalid
yield return new object[] { calendar, calendar.GetYear(calendar.MaxSupportedDateTime), month, day, MinEra(calendar) - 2, "era" };
yield return new object[] { calendar, calendar.GetYear(calendar.MaxSupportedDateTime), month, day, MaxEra(calendar) + 1, "era" };
}
}
public static IEnumerable<object[]> DateTime_TestData()
{
foreach (Calendar calendar in s_calendars)
{
DateTime minDate = calendar.MinSupportedDateTime;
if (minDate != DateTime.MinValue)
{
yield return new object[] { calendar, minDate.AddDays(-1) };
}
DateTime maxDate = calendar.MaxSupportedDateTime;
if (maxDate != DateTime.MaxValue)
{
yield return new object[] { calendar, maxDate.AddDays(1) };
}
}
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year, false)]
public static void GetDaysInYear_Invalid(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.GetDaysInYear(year, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year, false)]
public static void GetMonthsInYear_Invalid(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.GetMonthsInYear(year, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year | DataType.Month, true)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public static void GetDaysInMonth_Invalid_net46(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.GetDaysInMonth(year, month, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year | DataType.Month, false)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void GetDaysInMonth_Invalid_netcore(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.GetDaysInMonth(year, month, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year | DataType.Month | DataType.Day, false)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void IsLeapDay_Invalid_netcore(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.IsLeapDay(year, month, day, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year | DataType.Month | DataType.Day, true)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public static void IsLeapDay_Invalid_net46(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.IsLeapDay(year, month, day, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year | DataType.Month, false)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void IsLeapMonth_Invalid_netcore(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.IsLeapMonth(year, month, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year | DataType.Month, true)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public static void IsLeapMonth_Invalid_net46(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.IsLeapMonth(year, month, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year, false)]
public static void IsLeapYear_Invalid(Calendar calendar, int year, int month, int day, int era, string exceptionParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(exceptionParamName, () => calendar.IsLeapYear(year, era));
}
[Theory]
[MemberData(nameof(Year_Month_Day_Era_TestData), DataType.Year, false)]
public static void GetLeapMonth_Invalid(Calendar calendar, int year, int month, int day, int era, string expectedParamName)
{
Assert.Throws<ArgumentOutOfRangeException>(expectedParamName, () => calendar.GetLeapMonth(year, era));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void AddYears_Invalid(Calendar calendar)
{
Assert.ThrowsAny<ArgumentException>(() => calendar.AddYears(calendar.MaxSupportedDateTime, 1));
Assert.ThrowsAny<ArgumentException>(() => calendar.AddYears(calendar.MinSupportedDateTime, -1));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void AddMonths_Invalid(Calendar calendar)
{
Assert.ThrowsAny<ArgumentException>(() => calendar.AddMonths(calendar.MaxSupportedDateTime, 1));
Assert.ThrowsAny<ArgumentException>(() => calendar.AddMonths(calendar.MinSupportedDateTime, -1)); // JapaneseCalendar throws ArgumentException
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, -120001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, 120001));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void AddDays_Invalid(Calendar calendar)
{
Assert.Throws<ArgumentException>(() => calendar.AddDays(calendar.MaxSupportedDateTime, 1));
Assert.Throws<ArgumentException>(() => calendar.AddDays(calendar.MinSupportedDateTime, -1));
Assert.Throws<ArgumentException>(() => calendar.AddDays(DateTime.Now, -120001 * 30));
Assert.Throws<ArgumentException>(() => calendar.AddDays(DateTime.Now, 120001 * 30));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void AddHours_Invalid(Calendar calendar)
{
Assert.Throws<ArgumentException>(() => calendar.AddHours(calendar.MaxSupportedDateTime, 1));
Assert.Throws<ArgumentException>(() => calendar.AddHours(calendar.MinSupportedDateTime, -1));
Assert.Throws<ArgumentException>(() => calendar.AddHours(DateTime.Now, -120001 * 30 * 24));
Assert.Throws<ArgumentException>(() => calendar.AddHours(DateTime.Now, 120001 * 30 * 24));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void AddMinutes_Invalid(Calendar calendar)
{
Assert.Throws<ArgumentException>(() => calendar.AddMinutes(calendar.MaxSupportedDateTime, 1));
Assert.Throws<ArgumentException>(() => calendar.AddMinutes(calendar.MinSupportedDateTime, -1));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void AddSeconds_Invalid(Calendar calendar)
{
Assert.Throws<ArgumentException>(() => calendar.AddSeconds(calendar.MaxSupportedDateTime, 1));
Assert.Throws<ArgumentException>(() => calendar.AddSeconds(calendar.MinSupportedDateTime, -1));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void AddMilliseconds_Invalid(Calendar calendar)
{
Assert.Throws<ArgumentException>(() => calendar.AddMilliseconds(calendar.MaxSupportedDateTime, 1));
Assert.Throws<ArgumentException>(() => calendar.AddMilliseconds(calendar.MinSupportedDateTime, -1));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void GetWeekOfYear_Invalid(Calendar calendar)
{
// Rule is outside supported range
AssertExtensions.Throws<ArgumentOutOfRangeException>("rule", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstDay - 1, DayOfWeek.Saturday));
AssertExtensions.Throws<ArgumentOutOfRangeException>("rule", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstFourDayWeek + 1, DayOfWeek.Saturday));
// FirstDayOfWeek is outside supported range
AssertExtensions.Throws<ArgumentOutOfRangeException>("firstDayOfWeek", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday - 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("firstDayOfWeek", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstDay, DayOfWeek.Saturday + 1));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void ToDateTime_Invalid(Calendar calendar)
{
int month = 1;
int day = 1;
int hour = 1;
int minute = 1;
int second = 1;
int millisecond = 1;
foreach (int era in calendar.Eras)
{
int year = MaxCalendarYearInEra(calendar, era) - 2;
// Year is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(-1, month, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(0, month, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(MaxCalendarYearInEra(calendar, era) + 1, month, day, hour, minute, second, millisecond, era));
// Month is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, -1, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, 0, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, calendar.GetMonthsInYear(year, era) + 1, day, hour, minute, second, millisecond, era));
// Day is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, -1, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, 0, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, calendar.GetDaysInMonth(year, month, era) + 1, minute, second, millisecond, era));
// Hour is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, -1, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, 60, minute, second, millisecond, era));
// Minute is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, -1, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, 60, second, millisecond, era));
// Second is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, -1, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, 60, millisecond, era));
// Millisecond is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, second, -1, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, second, 1000, era));
}
// Year is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(MinCalendarYearInEra(calendar, MinEra(calendar)) - 1, month, day, hour, minute, second, millisecond, MinEra(calendar)));
// Era is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(calendar.GetYear(calendar.MaxSupportedDateTime), month, day, hour, minute, second, millisecond, MinEra(calendar) - 2));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(calendar.GetYear(calendar.MaxSupportedDateTime), month, day, hour, minute, second, millisecond, MaxEra(calendar) + 1));
// New date is out of range
DateTime minDateTime = calendar.MinSupportedDateTime;
int minEra = calendar.GetEra(minDateTime);
int minYear = calendar.GetYear(minDateTime);
DateTime maxDateTime = calendar.MaxSupportedDateTime;
int maxEra = calendar.GetEra(maxDateTime);
int maxYear = calendar.GetYear(maxDateTime);
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(minYear - 1, minDateTime.Month, minDateTime.Day, minDateTime.Hour, minDateTime.Minute, minDateTime.Second, minDateTime.Millisecond, minEra));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(maxYear + 1, maxDateTime.Month, maxDateTime.Day, maxDateTime.Hour, maxDateTime.Minute, maxDateTime.Second, maxDateTime.Millisecond, maxEra));
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void ToFourDigitYear_Invalid(Calendar calendar)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => calendar.ToFourDigitYear(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => calendar.ToFourDigitYear(MaxCalendarYearInEra(calendar, MaxEra(calendar)) + 1));
if (!(calendar is JapaneseLunisolarCalendar))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => calendar.ToFourDigitYear(MinCalendarYearInEra(calendar, MinEra(calendar)) - 2));
}
}
[Theory]
[MemberData(nameof(Calendars_TestData))]
public static void TwoDigitYearMax_Invalid(Calendar calendar)
{
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.TwoDigitYearMax = 98);
int max = Math.Max(MaxGregorianYearInEra(calendar, MaxEra(calendar)), MaxCalendarYearInEra(calendar, MaxEra(calendar)));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.TwoDigitYearMax = max + 1);
}
[Theory]
[MemberData(nameof(DateTime_TestData))]
public static void GetEra_Invalid(Calendar calendar, DateTime dt)
{
// JapaneseCalendar throws on Unix (ICU), but not on Windows
if ((calendar is JapaneseCalendar && PlatformDetection.IsWindows) || calendar is HebrewCalendar || calendar is TaiwanLunisolarCalendar || calendar is JapaneseLunisolarCalendar)
{
calendar.GetEra(dt);
}
else
{
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.GetEra(dt));
}
}
[Theory]
[MemberData(nameof(DateTime_TestData))]
public static void GetYear_Invalid(Calendar calendar, DateTime dt)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetYear(dt));
}
[Theory]
[MemberData(nameof(DateTime_TestData))]
public static void GetMonth_Invalid(Calendar calendar, DateTime dt)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetMonth(dt));
}
[Theory]
[MemberData(nameof(DateTime_TestData))]
public static void GetDayOfYear_Invalid(Calendar calendar, DateTime dt)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetDayOfYear(dt));
}
[Theory]
[MemberData(nameof(DateTime_TestData))]
public static void GetDayOfMonth_Invalid(Calendar calendar, DateTime dt)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetDayOfMonth(dt));
}
[Theory]
[MemberData(nameof(DateTime_TestData))]
public static void GetDayOfWeek_Invalid(Calendar calendar, DateTime dt)
{
if (calendar is HijriCalendar || calendar is UmAlQuraCalendar || calendar is PersianCalendar || calendar is HebrewCalendar)
{
calendar.GetDayOfWeek(dt);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetDayOfWeek(dt));
}
}
}
}
| 51.974194 | 222 | 0.631124 | [
"MIT"
] | ERROR-FAILS-NewData-News/corefx | src/System.Globalization.Calendars/tests/CalendarHelpers.cs | 24,168 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Teguh.Identity.Codegen.Migrations
{
public partial class InitiateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 42.458716 | 108 | 0.490601 | [
"MIT"
] | teguhmurdianto/teguh-identity-codegenerator-demo | Teguh.Identity.Codegen/Migrations/20210215110325_InitiateIdentitySchema.cs | 9,258 | C# |
// Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
using System.Collections.Generic;
public class TanksAndZombiesTarget : TargetRules
{
public TanksAndZombiesTarget(TargetInfo Target) : base(Target)
{
Type = TargetType.Game;
ExtraModuleNames.AddRange( new string[] { "TanksAndZombies" } );
}
}
| 23.666667 | 78 | 0.771831 | [
"MIT"
] | bawboc/TanksAndZombies | Source/TanksAndZombies.Target.cs | 355 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Eru.Server.Dtos
{
public class CommentCreateInDto
{
[DefaultValue(null)] public Guid? ParentId { get; set; } = null;
[Required]
public Guid PostId { get; set; }
[Required]
public int StatusId { get; set; }
[DefaultValue(null)] public int? CategoryId { get; set; } = null;
[Required] public string Content { get; set; }
[Required] public Guid UserId { get; set; }
}
}
| 25.52 | 73 | 0.641066 | [
"MIT"
] | lonelyhentai/workspace | database/comp3010/exp3/Eru.Server/Dtos/CommentCreateInDto.cs | 640 | C# |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Garmin Canada Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2020 Garmin Canada Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 21.38Release
// Tag = production/akw/21.38.00-0-g0d69e49
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Linq;
namespace Dynastream.Fit
{
/// <summary>
/// Implements the Hr profile message.
/// </summary>
public class HrMesg : Mesg
{
#region Fields
#endregion
/// <summary>
/// Field Numbers for <see cref="HrMesg"/>
/// </summary>
public sealed class FieldDefNum
{
public const byte Timestamp = 253;
public const byte FractionalTimestamp = 0;
public const byte Time256 = 1;
public const byte FilteredBpm = 6;
public const byte EventTimestamp = 9;
public const byte EventTimestamp12 = 10;
public const byte Invalid = Fit.FieldNumInvalid;
}
#region Constructors
public HrMesg() : base(Profile.GetMesg(MesgNum.Hr))
{
}
public HrMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
Object val = GetFieldValue(253, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return TimestampToDateTime(Convert.ToUInt32(val));
}
/// <summary>
/// Set Timestamp field</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the FractionalTimestamp field
/// Units: s</summary>
/// <returns>Returns nullable float representing the FractionalTimestamp field</returns>
public float? GetFractionalTimestamp()
{
Object val = GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToSingle(val));
}
/// <summary>
/// Set FractionalTimestamp field
/// Units: s</summary>
/// <param name="fractionalTimestamp_">Nullable field value to be set</param>
public void SetFractionalTimestamp(float? fractionalTimestamp_)
{
SetFieldValue(0, 0, fractionalTimestamp_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Time256 field
/// Units: s</summary>
/// <returns>Returns nullable float representing the Time256 field</returns>
public float? GetTime256()
{
Object val = GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToSingle(val));
}
/// <summary>
/// Set Time256 field
/// Units: s</summary>
/// <param name="time256_">Nullable field value to be set</param>
public void SetTime256(float? time256_)
{
SetFieldValue(1, 0, time256_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field FilteredBpm</returns>
public int GetNumFilteredBpm()
{
return GetNumFieldValues(6, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the FilteredBpm field
/// Units: bpm</summary>
/// <param name="index">0 based index of FilteredBpm element to retrieve</param>
/// <returns>Returns nullable byte representing the FilteredBpm field</returns>
public byte? GetFilteredBpm(int index)
{
Object val = GetFieldValue(6, index, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set FilteredBpm field
/// Units: bpm</summary>
/// <param name="index">0 based index of filtered_bpm</param>
/// <param name="filteredBpm_">Nullable field value to be set</param>
public void SetFilteredBpm(int index, byte? filteredBpm_)
{
SetFieldValue(6, index, filteredBpm_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field EventTimestamp</returns>
public int GetNumEventTimestamp()
{
return GetNumFieldValues(9, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the EventTimestamp field
/// Units: s</summary>
/// <param name="index">0 based index of EventTimestamp element to retrieve</param>
/// <returns>Returns nullable float representing the EventTimestamp field</returns>
public float? GetEventTimestamp(int index)
{
Object val = GetFieldValue(9, index, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToSingle(val));
}
/// <summary>
/// Set EventTimestamp field
/// Units: s</summary>
/// <param name="index">0 based index of event_timestamp</param>
/// <param name="eventTimestamp_">Nullable field value to be set</param>
public void SetEventTimestamp(int index, float? eventTimestamp_)
{
SetFieldValue(9, index, eventTimestamp_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field EventTimestamp12</returns>
public int GetNumEventTimestamp12()
{
return GetNumFieldValues(10, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the EventTimestamp12 field</summary>
/// <param name="index">0 based index of EventTimestamp12 element to retrieve</param>
/// <returns>Returns nullable byte representing the EventTimestamp12 field</returns>
public byte? GetEventTimestamp12(int index)
{
Object val = GetFieldValue(10, index, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set EventTimestamp12 field</summary>
/// <param name="index">0 based index of event_timestamp_12</param>
/// <param name="eventTimestamp12_">Nullable field value to be set</param>
public void SetEventTimestamp12(int index, byte? eventTimestamp12_)
{
SetFieldValue(10, index, eventTimestamp12_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| 32.862348 | 96 | 0.56856 | [
"MIT"
] | gcaufield/FitFileTools | Dynastream.Fit/Fit/Profile/Mesgs/HrMesg.cs | 8,117 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Grafeas.V1.Snippets
{
using Grafeas.V1;
public sealed partial class GeneratedGrafeasClientStandaloneSnippets
{
/// <summary>Snippet for GetOccurrence</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetOccurrenceRequestObject()
{
// Create client
GrafeasClient grafeasClient = GrafeasClient.Create();
// Initialize request argument(s)
GetOccurrenceRequest request = new GetOccurrenceRequest
{
OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"),
};
// Make the request
Occurrence response = grafeasClient.GetOccurrence(request);
}
}
}
| 36.595238 | 99 | 0.670787 | [
"Apache-2.0"
] | googleapis/googleapis-gen | grafeas/v1/google-cloud-grafeas-v1-csharp/Grafeas.V1.StandaloneSnippets/GrafeasClient.GetOccurrenceRequestObjectSnippet.g.cs | 1,537 | 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.Threading;
using System.ComponentModel;
using System.ComponentModel.Design;
namespace System.Timers
{
/// <summary>
/// Handles recurring events in an application.
/// </summary>
[DefaultProperty("Interval"), DefaultEvent("Elapsed")]
public partial class Timer : Component, ISupportInitialize
{
private double _interval;
private bool _enabled;
private bool _initializing;
private bool _delayedEnable;
private ElapsedEventHandler _onIntervalElapsed;
private bool _autoReset;
private bool _tickImmediately;
private ISynchronizeInvoke _synchronizingObject;
private bool _disposed;
private Threading.Timer _timer;
private readonly TimerCallback _callback;
private object _cookie;
/// <summary>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.
/// </summary>
public Timer() : base()
{
_interval = 100;
_enabled = false;
_autoReset = true;
_tickImmediately = false;
_initializing = false;
_delayedEnable = false;
_callback = new TimerCallback(MyTimerCallback);
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </summary>
public Timer(double interval) : this()
{
if (interval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
}
double roundedInterval = Math.Ceiling(interval);
if (roundedInterval > int.MaxValue || roundedInterval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
}
_interval = (int)roundedInterval;
}
/// <summary>
/// Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed, when Enabled is set to true.
/// </summary>
[TimersDescription(nameof(SR.TimerAutoReset), null), DefaultValue(true)]
public bool AutoReset
{
get => _autoReset;
set
{
if (DesignMode)
{
_autoReset = value;
}
else if (_autoReset != value)
{
_autoReset = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the Timer raises the Tick event immediately upon start,
/// when Enabled is set to true.
/// </summary>
[TimersDescription(nameof(SR.TimerTickImmediately), null), DefaultValue(false)]
public bool TickImmediately
{
get => _tickImmediately;
set
{
if (DesignMode)
{
_tickImmediately = value;
}
else if (_tickImmediately != value)
{
_tickImmediately = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able to raise events at a defined interval.
/// The default value by design is false, don't change it.
/// </summary>
[TimersDescription(nameof(SR.TimerEnabled), null), DefaultValue(false)]
public bool Enabled
{
get => _enabled;
set
{
if (DesignMode)
{
_delayedEnable = value;
_enabled = value;
}
else if (_initializing)
{
_delayedEnable = value;
}
else if (_enabled != value)
{
if (!value)
{
if (_timer != null)
{
_cookie = null;
_timer.Dispose();
_timer = null;
}
_enabled = value;
}
else
{
_enabled = value;
if (_timer == null)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
int i = (int)Math.Ceiling(_interval);
_cookie = new object();
_timer = new Threading.Timer(_callback, _cookie, Timeout.Infinite, Timeout.Infinite);
_timer.Change(_tickImmediately ? 0 : i, _autoReset ? i : Timeout.Infinite);
}
else
{
UpdateTimer();
}
}
}
}
}
private void UpdateTimer()
{
int i = (int)Math.Ceiling(_interval);
_timer.Change(_tickImmediately ? 0 : i, _autoReset ? i : Timeout.Infinite);
}
/// <summary>
/// Gets or sets the interval on which to raise events.
/// </summary>
[TimersDescription(nameof(SR.TimerInterval), null), DefaultValue(100d)]
public double Interval
{
get => _interval;
set
{
if (value <= 0)
{
throw new ArgumentException(SR.Format(SR.TimerInvalidInterval, value, 0));
}
_interval = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
/// <summary>
/// Occurs when the <see cref='System.Timers.Timer.Interval'/> has
/// elapsed.
/// </summary>
[TimersDescription(nameof(SR.TimerIntervalElapsed), null)]
public event ElapsedEventHandler Elapsed
{
add => _onIntervalElapsed += value;
remove => _onIntervalElapsed -= value;
}
/// <summary>
/// Sets the enable property in design mode to true by default.
/// </summary>
public override ISite Site
{
get => base.Site;
set
{
base.Site = value;
if (DesignMode)
{
_enabled = true;
}
}
}
/// <summary>
/// Gets or sets the object used to marshal event-handler calls that are issued when
/// an interval has elapsed.
/// </summary>
[DefaultValue(null), TimersDescription(nameof(SR.TimerSynchronizingObject), null)]
public ISynchronizeInvoke SynchronizingObject
{
get
{
if (_synchronizingObject == null && DesignMode)
{
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
object baseComponent = host?.RootComponent;
if (baseComponent != null && baseComponent is ISynchronizeInvoke)
{
_synchronizingObject = (ISynchronizeInvoke)baseComponent;
}
}
return _synchronizingObject;
}
set => _synchronizingObject = value;
}
/// <summary>
/// Notifies the object that initialization is beginning and tells it to stand by.
/// </summary>
public void BeginInit()
{
Close();
_initializing = true;
}
/// <summary>
/// Disposes of the resources (other than memory) used by
/// the <see cref='System.Timers.Timer'/>.
/// </summary>
public void Close()
{
_initializing = false;
_delayedEnable = false;
_enabled = false;
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
}
protected override void Dispose(bool disposing)
{
Close();
_disposed = true;
base.Dispose(disposing);
}
/// <summary>
/// Notifies the object that initialization is complete.
/// </summary>
public void EndInit()
{
_initializing = false;
Enabled = _delayedEnable;
}
/// <summary>
/// Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.
/// </summary>
public void Start() => Enabled = true;
/// <summary>
/// Stops the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='false'/>.
/// </summary>
public void Stop()
{
Enabled = false;
}
private void MyTimerCallback(object state)
{
// System.Threading.Timer will not cancel the work item queued before the timer is stopped.
// We don't want to handle the callback after a timer is stopped.
if (state != _cookie)
{
return;
}
if (!_autoReset)
{
_enabled = false;
}
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(DateTime.Now);
try
{
// To avoid race between remove handler and raising the event
ElapsedEventHandler intervalElapsed = _onIntervalElapsed;
if (intervalElapsed != null)
{
if (SynchronizingObject != null && SynchronizingObject.InvokeRequired)
SynchronizingObject.BeginInvoke(intervalElapsed, new object[] { this, elapsedEventArgs });
else
intervalElapsed(this, elapsedEventArgs);
}
}
catch
{
}
}
}
}
| 32.420896 | 175 | 0.475555 | [
"MIT"
] | jez9999/runtime | src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs | 10,861 | C# |
// 为模型“J:\Project\Personal\语音对讲机\pmessage\02-Src\IM后台源码\LiveVideoSDKNew\LiveVideoSDK\VIMS.LiveVideoSDK\VIMS.LiveVideoSDK.Bll\Entity\DBEntities.edmx”启用了 T4 代码生成。
// 要启用旧代码生成功能,请将“代码生成策略”设计器属性的值
// 更改为“旧的 ObjectContext”。当在设计器中打开该模型时,此属性会出现在
// “属性”窗口中。
// 如果没有生成任何上下文和实体类,可能是因为您创建了空模型但是
// 尚未选择要使用的实体框架版本。要为您的模型生成一个上下文类和实体
// 类,请在设计器中打开该模型,右键单击设计器图面,然后
// 选择“从数据库更新模型...”、“从模型生成数据库...”或“添加代码生成
// 项...”。 | 40.3 | 161 | 0.769231 | [
"MIT"
] | zengfanmao/mpds | LiveVideoSDK/VIMS.LiveVideoSDK/VIMS.LiveVideoSDK.Bll/Entity/DBEntities.Designer.cs | 821 | C# |
using System.Collections.Generic;
namespace Eshava.Transition.Models
{
public class DataProperty
{
public IEnumerable<string> MappingProperties { get; set; }
public IEnumerable<DataProperty> DataProperties { get; set; }
public string PropertyTarget { get; set; }
public string PropertySource { get; set; }
/// <summary>
/// Configured value, whether is used if PropertySource is not set
/// HasMapping has to be true
/// </summary>
public string MappedValue { get; set; }
public bool HasMapping { get; set; }
/// <summary>
/// Configured key/value pair list to translate incoming values
/// HasMapping has to be false
/// </summary>
public IEnumerable<MappingPair> ValueMappings { get; set; }
/// <summary>
/// Optional
/// Fallback: InvariantCulture
/// </summary>
public string CultureCode { get; set; }
public bool IsSameDataRecord { get; set; } /* Export */
public string ConditionalPropertyName { get; set; } /* Export */
public string ConditionalPropertyValue { get; set; } /* Export */
public bool SplitExportResult { get; set; } /* Export */
#region json
public bool ExportAsString { get; set; } /* Export */
#endregion
#region edi
public int PositionEDI { get; set; }
public int LengthEDI { get; set; }
public int LineIndexEDI { get; set; }
public bool CanRepeatEDI { get; set; }
#endregion
#region csv
public bool HasSurroundingQuotationMarksCSV { get; set; }
public int StartRowIndexCSV { get; set; }
public bool HasColumnNamesCSV { get; set; }
public char SeparatorCSVColumn { get; set; }
public int PropertySourceIndexCSV { get; set; } /* Export */
#endregion
#region xml
public IEnumerable<AdditionalPropertyData> AdditionalPropertyData { get; set; } /* Export */
public bool IsAttribute { get; set; }
public bool SurroundWithCData { get; set; } /* Export */
#endregion
}
} | 32.7 | 105 | 0.665647 | [
"MIT"
] | eshava/transition | Eshava.Transition/Models/DataProperty.cs | 1,964 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.34209
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace MsgPack.Serialization.GeneratedSerializers.ArrayBased {
[System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public class System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer : MsgPack.Serialization.CollectionSerializers.CollectionMessagePackSerializer<System.Collections.ObjectModel.ObservableCollection<MsgPack.MessagePackObject[]>, MsgPack.MessagePackObject[]> {
public System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer(MsgPack.Serialization.SerializationContext context) :
base(context, System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.RestoreSchema()) {
}
protected override System.Collections.ObjectModel.ObservableCollection<MsgPack.MessagePackObject[]> CreateInstance(int initialCapacity) {
System.Collections.ObjectModel.ObservableCollection<MsgPack.MessagePackObject[]> collection = default(System.Collections.ObjectModel.ObservableCollection<MsgPack.MessagePackObject[]>);
collection = new System.Collections.ObjectModel.ObservableCollection<MsgPack.MessagePackObject[]>();
return collection;
}
private static MsgPack.Serialization.PolymorphismSchema RestoreSchema() {
MsgPack.Serialization.PolymorphismSchema schema = default(MsgPack.Serialization.PolymorphismSchema);
schema = null;
return schema;
}
private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse)
{
if (condition) {
return whenTrue;
}
else {
return whenFalse;
}
}
}
}
| 50.688889 | 303 | 0.673389 | [
"Apache-2.0"
] | sosan/msgpack-cli | test/MsgPack.UnitTest/gen/array/System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs | 2,455 | C# |
namespace System.IO.BACnet
{
/*Network Layer Message Type */
/*If Bit 7 of the control octet described in 6.2.2 is 1, */
/* a message type octet shall be present as shown in Figure 6-1. */
/* The following message types are indicated: */
public enum BacnetNetworkMessageTypes : byte
{
NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK = 0,
NETWORK_MESSAGE_I_AM_ROUTER_TO_NETWORK = 1,
NETWORK_MESSAGE_I_COULD_BE_ROUTER_TO_NETWORK = 2,
NETWORK_MESSAGE_REJECT_MESSAGE_TO_NETWORK = 3,
NETWORK_MESSAGE_ROUTER_BUSY_TO_NETWORK = 4,
NETWORK_MESSAGE_ROUTER_AVAILABLE_TO_NETWORK = 5,
NETWORK_MESSAGE_INIT_RT_TABLE = 6,
NETWORK_MESSAGE_INIT_RT_TABLE_ACK = 7,
NETWORK_MESSAGE_ESTABLISH_CONNECTION_TO_NETWORK = 8,
NETWORK_MESSAGE_DISCONNECT_CONNECTION_TO_NETWORK = 9,
/* X'0A' to X'7F': Reserved for use by ASHRAE, */
/* X'80' to X'FF': Available for vendor proprietary messages */
}
} | 40.681818 | 68 | 0.776536 | [
"MIT"
] | vberkaltun/BACnet | Base/BacnetNetworkMessageTypes.cs | 897 | C# |
using Klei.AI;
public class ToPercentAttributeFormatter : StandardAttributeFormatter
{
public float max = 1f;
public ToPercentAttributeFormatter(float max, GameUtil.TimeSlice deltaTimeSlice = GameUtil.TimeSlice.None)
: base(GameUtil.UnitClass.Percent, deltaTimeSlice)
{
this.max = max;
}
public override string GetFormattedAttribute(AttributeInstance instance)
{
return GetFormattedValue(instance.GetTotalDisplayValue(), base.DeltaTimeSlice);
}
public override string GetFormattedModifier(AttributeModifier modifier)
{
return GetFormattedValue(modifier.Value, base.DeltaTimeSlice);
}
public override string GetFormattedValue(float value, GameUtil.TimeSlice timeSlice)
{
return GameUtil.GetFormattedPercent(value / max * 100f, timeSlice);
}
}
| 27.5 | 107 | 0.801299 | [
"MIT"
] | undancer/oni-data | Managed/main/ToPercentAttributeFormatter.cs | 770 | C# |
using System;
using System.Data.SqlClient;
using EasyADO.NET;
using NUnit.Framework;
namespace Tests.Unit_Tests.FindTests
{
[TestFixture]
public class FindColumnsByPredicateTests : BaseTestFixture
{
[SetUp]
public void Init()
{
_easyAdoNet = new EasyAdoNet(ConnectionString);
}
[TestCase("Persons", "WHERE Name = 'Maksym'", new[] {"Name", "Surname"})]
[TestCase("Roles", "WHERE Name = 'Admin'", new[] {"Name"})]
public void When_Find_Has_Rows(string tableName, string predicate, params string[] columns)
{
var result = _easyAdoNet.Find(tableName, predicate, columns);
Assert.IsTrue(result.HasRows);
}
[TestCase("Persons", "WHERE Name = 'NotExists'", new[] {"Name", "Surname"})]
[TestCase("Roles", "WHERE Name = 'NotExists'", new[] {"Name"})]
public void When_Find_HasNot_Rows(string tableName, string predicate, params string[] columns)
{
var result = _easyAdoNet.Find(tableName, predicate, columns);
Assert.IsFalse(result.HasRows);
}
[TestCase("NotExistent", "WHERE Name = 'NotExists'", new[] {"NotExists"})]
[TestCase("Persons", "", new[] {"NotExists"})]
[TestCase("Persons", "WHERE Name = 'NotExists'")]
public void When_Find_Throws_ArgumentException(string tableName, string predicate, params string[] columns)
{
Assert.Throws<ArgumentException>(() => _easyAdoNet.Find(tableName, predicate, columns));
}
[TestCase(null, "WHERE Name = 'NotExists'", new[] {"NotExists"})]
[TestCase("Persons", null, new[] {"NotExists"})]
[TestCase("Persons", "WHERE Name = 'NotExists'", null)]
public void When_Find_Throws_ArgumentNullException(string tableName, string predicate, params string[] columns)
{
Assert.Throws<ArgumentNullException>(() => _easyAdoNet.Find(tableName, predicate, columns));
}
[TestCase("Persons", "WHERE NotExists = 'NotExists'", new[] {"Name"})]
[TestCase("Roles", "WHERE Name = 'NotExists'", new[] {"NotExists"})]
public void When_Find_Throws_SqlException(string tableName, string predicate, params string[] columns)
{
Assert.Throws<SqlException>(() => _easyAdoNet.Find(tableName, predicate, columns));
}
private EasyAdoNet _easyAdoNet;
}
} | 40.516667 | 119 | 0.622378 | [
"MIT"
] | lemichello/EasyADO.NET | Tests/Unit Tests/FindTests/FindColumnsByPredicateTests.cs | 2,431 | C# |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Collections.Generic;
using Quartz.Impl.Matchers;
using Quartz.Spi;
namespace Quartz
{
/// <summary>
/// This is the main interface of a Quartz Scheduler.
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="IScheduler"/> maintains a registry of
/// <see cref="IJobDetail"/>s and <see cref="ITrigger"/>s. Once
/// registered, the <see cref="IScheduler"/> is responsible for executing
/// <see cref="IJob"/> s when their associated <see cref="ITrigger"/> s
/// fire (when their scheduled time arrives).
/// </para>
/// <para>
/// <see cref="IScheduler"/> instances are produced by a
/// <see cref="ISchedulerFactory"/>. A scheduler that has already been
/// created/initialized can be found and used through the same factory that
/// produced it. After a <see cref="IScheduler"/> has been created, it is in
/// "stand-by" mode, and must have its <see cref="IScheduler.Start"/> method
/// called before it will fire any <see cref="IJob"/>s.
/// </para>
/// <para>
/// <see cref="IJob"/> s are to be created by the 'client program', by
/// defining a class that implements the <see cref="IJob"/> interface.
/// <see cref="IJobDetail"/> objects are then created (also by the client) to
/// define a individual instances of the <see cref="IJob"/>.
/// <see cref="IJobDetail"/> instances can then be registered with the
/// <see cref="IScheduler"/> via the %IScheduler.ScheduleJob(JobDetail,
/// Trigger)% or %IScheduler.AddJob(JobDetail, bool)% method.
/// </para>
/// <para>
/// <see cref="ITrigger"/> s can then be defined to fire individual
/// <see cref="IJob"/> instances based on given schedules.
/// <see cref="ISimpleTrigger"/> s are most useful for one-time firings, or
/// firing at an exact moment in time, with N repeats with a given delay between
/// them. <see cref="ICronTrigger"/> s allow scheduling based on time of day,
/// day of week, day of month, and month of year.
/// </para>
/// <para>
/// <see cref="IJob"/> s and <see cref="ITrigger"/> s have a name and
/// group associated with them, which should uniquely identify them within a single
/// <see cref="IScheduler"/>. The 'group' feature may be useful for creating
/// logical groupings or categorizations of <see cref="IJob"/>s and
/// <see cref="ITrigger"/>s. If you don't have need for assigning a group to a
/// given <see cref="IJob"/>s of <see cref="ITrigger"/>s, then you can use
/// the <see cref="SchedulerConstants.DefaultGroup"/> constant defined on
/// this interface.
/// </para>
/// <para>
/// Stored <see cref="IJob"/> s can also be 'manually' triggered through the
/// use of the %IScheduler.TriggerJob(string, string)% function.
/// </para>
/// <para>
/// Client programs may also be interested in the 'listener' interfaces that are
/// available from Quartz. The <see cref="IJobListener"/> interface provides
/// notifications of <see cref="IJob"/> executions. The
/// <see cref="ITriggerListener"/> interface provides notifications of
/// <see cref="ITrigger"/> firings. The <see cref="ISchedulerListener"/>
/// interface provides notifications of <see cref="IScheduler"/> events and
/// errors. Listeners can be associated with local schedulers through the
/// <see cref="IListenerManager" /> interface.
/// </para>
/// <para>
/// The setup/configuration of a <see cref="IScheduler"/> instance is very
/// customizable. Please consult the documentation distributed with Quartz.
/// </para>
/// </remarks>
/// <seealso cref="IJob"/>
/// <seealso cref="IJobDetail"/>
/// <seealso cref="ITrigger"/>
/// <seealso cref="IJobListener"/>
/// <seealso cref="ITriggerListener"/>
/// <seealso cref="ISchedulerListener"/>
/// <author>Marko Lahma (.NET)</author>
public interface IScheduler
{
/// <summary>
/// returns true if the given JobGroup
/// is paused
/// </summary>
/// <param name="groupName"></param>
/// <returns></returns>
bool IsJobGroupPaused(string groupName);
/// <summary>
/// returns true if the given TriggerGroup
/// is paused
/// </summary>
/// <param name="groupName"></param>
/// <returns></returns>
bool IsTriggerGroupPaused(string groupName);
/// <summary>
/// Returns the name of the <see cref="IScheduler" />.
/// </summary>
string SchedulerName { get; }
/// <summary>
/// Returns the instance Id of the <see cref="IScheduler" />.
/// </summary>
string SchedulerInstanceId { get; }
/// <summary>
/// Returns the <see cref="SchedulerContext" /> of the <see cref="IScheduler" />.
/// </summary>
SchedulerContext Context { get; }
/// <summary>
/// Reports whether the <see cref="IScheduler" /> is in stand-by mode.
/// </summary>
/// <seealso cref="Standby()" />
/// <seealso cref="Start()" />
bool InStandbyMode { get; }
/// <summary>
/// Reports whether the <see cref="IScheduler" /> has been Shutdown.
/// </summary>
bool IsShutdown { get; }
/// <summary>
/// Get a <see cref="SchedulerMetaData" /> object describing the settings
/// and capabilities of the scheduler instance.
/// </summary>
/// <remarks>
/// Note that the data returned is an 'instantaneous' snap-shot, and that as
/// soon as it's returned, the meta data values may be different.
/// </remarks>
SchedulerMetaData GetMetaData();
/// <summary>
/// Return a list of <see cref="IJobExecutionContext" /> objects that
/// represent all currently executing Jobs in this Scheduler instance.
/// </summary>
/// <remarks>
/// <para>
/// This method is not cluster aware. That is, it will only return Jobs
/// currently executing in this Scheduler instance, not across the entire
/// cluster.
/// </para>
/// <para>
/// Note that the list returned is an 'instantaneous' snap-shot, and that as
/// soon as it's returned, the true list of executing jobs may be different.
/// Also please read the doc associated with <see cref="IJobExecutionContext" />-
/// especially if you're using remoting.
/// </para>
/// </remarks>
/// <seealso cref="IJobExecutionContext" />
IList<IJobExecutionContext> GetCurrentlyExecutingJobs();
/// <summary>
/// Set the <see cref="JobFactory" /> that will be responsible for producing
/// instances of <see cref="IJob" /> classes.
/// </summary>
/// <remarks>
/// JobFactories may be of use to those wishing to have their application
/// produce <see cref="IJob" /> instances via some special mechanism, such as to
/// give the opportunity for dependency injection.
/// </remarks>
/// <seealso cref="IJobFactory" />
IJobFactory JobFactory { set; }
/// <summary>
/// Get a reference to the scheduler's <see cref="IListenerManager" />,
/// through which listeners may be registered.
/// </summary>
/// <returns>the scheduler's <see cref="IListenerManager" /></returns>
/// <seealso cref="ListenerManager" />
/// <seealso cref="IJobListener" />
/// <seealso cref="ITriggerListener" />
/// <seealso cref="ISchedulerListener" />
IListenerManager ListenerManager { get; }
/// <summary>
/// Get the names of all known <see cref="IJobDetail" /> groups.
/// </summary>
IList<string> GetJobGroupNames();
/// <summary>
/// Get the names of all known <see cref="ITrigger" /> groups.
/// </summary>
IList<string> GetTriggerGroupNames();
/// <summary>
/// Get the names of all <see cref="ITrigger" /> groups that are paused.
/// </summary>
Collection.ISet<string> GetPausedTriggerGroups();
/// <summary>
/// Starts the <see cref="IScheduler" />'s threads that fire <see cref="ITrigger" />s.
/// When a scheduler is first created it is in "stand-by" mode, and will not
/// fire triggers. The scheduler can also be put into stand-by mode by
/// calling the <see cref="Standby" /> method.
/// </summary>
/// <remarks>
/// The misfire/recovery process will be started, if it is the initial call
/// to this method on this scheduler instance.
/// </remarks>
/// <seealso cref="StartDelayed(TimeSpan)"/>
/// <seealso cref="Standby"/>
/// <seealso cref="Shutdown(bool)"/>
void Start();
/// <summary>
/// Calls <see cref="Start" /> after the indicated delay.
/// (This call does not block). This can be useful within applications that
/// have initializers that create the scheduler immediately, before the
/// resources needed by the executing jobs have been fully initialized.
/// </summary>
/// <seealso cref="Start"/>
/// <seealso cref="Standby"/>
/// <seealso cref="Shutdown(bool)"/>
void StartDelayed(TimeSpan delay);
/// <summary>
/// Whether the scheduler has been started.
/// </summary>
/// <remarks>
/// Note: This only reflects whether <see cref="Start" /> has ever
/// been called on this Scheduler, so it will return <see langword="true" /> even
/// if the <see cref="IScheduler" /> is currently in standby mode or has been
/// since shutdown.
/// </remarks>
/// <seealso cref="Start" />
/// <seealso cref="IsShutdown" />
/// <seealso cref="InStandbyMode" />
bool IsStarted { get; }
/// <summary>
/// Temporarily halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s.
/// </summary>
/// <remarks>
/// <para>
/// When <see cref="Start" /> is called (to bring the scheduler out of
/// stand-by mode), trigger misfire instructions will NOT be applied
/// during the execution of the <see cref="Start" /> method - any misfires
/// will be detected immediately afterward (by the <see cref="IJobStore" />'s
/// normal process).
/// </para>
/// <para>
/// The scheduler is not destroyed, and can be re-started at any time.
/// </para>
/// </remarks>
/// <seealso cref="Start()"/>
/// <seealso cref="PauseAll()"/>
void Standby();
/// <summary>
/// Halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s,
/// and cleans up all resources associated with the Scheduler. Equivalent to Shutdown(false).
/// </summary>
/// <remarks>
/// The scheduler cannot be re-started.
/// </remarks>
/// <seealso cref="Shutdown(bool)" />
void Shutdown();
/// <summary>
/// Halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s,
/// and cleans up all resources associated with the Scheduler.
/// </summary>
/// <remarks>
/// The scheduler cannot be re-started.
/// </remarks>
/// <param name="waitForJobsToComplete">
/// if <see langword="true" /> the scheduler will not allow this method
/// to return until all currently executing jobs have completed.
/// </param>
/// <seealso cref="Shutdown()" />
void Shutdown(bool waitForJobsToComplete);
/// <summary>
/// Add the given <see cref="IJobDetail" /> to the
/// Scheduler, and associate the given <see cref="ITrigger" /> with
/// it.
/// </summary>
/// <remarks>
/// If the given Trigger does not reference any <see cref="IJob" />, then it
/// will be set to reference the Job passed with it into this method.
/// </remarks>
DateTimeOffset ScheduleJob(IJobDetail jobDetail, ITrigger trigger);
/// <summary>
/// Schedule the given <see cref="ITrigger" /> with the
/// <see cref="IJob" /> identified by the <see cref="ITrigger" />'s settings.
/// </summary>
DateTimeOffset ScheduleJob(ITrigger trigger);
/// <summary>
/// Schedule all of the given jobs with the related set of triggers.
/// </summary>
/// <remarks>
/// <para>If any of the given jobs or triggers already exist (or more
/// specifically, if the keys are not unique) and the replace
/// parameter is not set to true then an exception will be thrown.</para>
/// </remarks>
void ScheduleJobs(IDictionary<IJobDetail, Collection.ISet<ITrigger>> triggersAndJobs, bool replace);
/// <summary>
/// Schedule the given job with the related set of triggers.
/// </summary>
/// <remarks>
/// If any of the given job or triggers already exist (or more
/// specifically, if the keys are not unique) and the replace
/// parameter is not set to true then an exception will be thrown.
/// </remarks>
/// <param name="jobDetail"></param>
/// <param name="triggersForJob"></param>
/// <param name="replace"></param>
void ScheduleJob(IJobDetail jobDetail, Collection.ISet<ITrigger> triggersForJob, bool replace);
/// <summary>
/// Remove the indicated <see cref="ITrigger" /> from the scheduler.
/// <para>If the related job does not have any other triggers, and the job is
/// not durable, then the job will also be deleted.</para>
/// </summary>
bool UnscheduleJob(TriggerKey triggerKey);
/// <summary>
/// Remove all of the indicated <see cref="ITrigger" />s from the scheduler.
/// </summary>
/// <remarks>
/// <para>If the related job does not have any other triggers, and the job is
/// not durable, then the job will also be deleted.</para>
/// Note that while this bulk operation is likely more efficient than
/// invoking <see cref="UnscheduleJob(TriggerKey)" /> several
/// times, it may have the adverse affect of holding data locks for a
/// single long duration of time (rather than lots of small durations
/// of time).
/// </remarks>
bool UnscheduleJobs(IList<TriggerKey> triggerKeys);
/// <summary>
/// Remove (delete) the <see cref="ITrigger" /> with the
/// given key, and store the new given one - which must be associated
/// with the same job (the new trigger must have the job name & group specified)
/// - however, the new trigger need not have the same name as the old trigger.
/// </summary>
/// <param name="triggerKey">The <see cref="ITrigger" /> to be replaced.</param>
/// <param name="newTrigger">
/// The new <see cref="ITrigger" /> to be stored.
/// </param>
/// <returns>
/// <see langword="null" /> if a <see cref="ITrigger" /> with the given
/// name and group was not found and removed from the store (and the
/// new trigger is therefore not stored), otherwise
/// the first fire time of the newly scheduled trigger.
/// </returns>
DateTimeOffset? RescheduleJob(TriggerKey triggerKey, ITrigger newTrigger);
/// <summary>
/// Add the given <see cref="IJob" /> to the Scheduler - with no associated
/// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until
/// it is scheduled with a <see cref="ITrigger" />, or <see cref="TriggerJob(Quartz.JobKey)" />
/// is called for it.
/// </summary>
/// <remarks>
/// The <see cref="IJob" /> must by definition be 'durable', if it is not,
/// SchedulerException will be thrown.
/// </remarks>
void AddJob(IJobDetail jobDetail, bool replace);
/// <summary>
/// Add the given <see cref="IJob" /> to the Scheduler - with no associated
/// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until
/// it is scheduled with a <see cref="ITrigger" />, or <see cref="TriggerJob(Quartz.JobKey)" />
/// is called for it.
/// </summary>
/// <remarks>
/// With the <paramref name="storeNonDurableWhileAwaitingScheduling"/> parameter
/// set to <code>true</code>, a non-durable job can be stored. Once it is
/// scheduled, it will resume normal non-durable behavior (i.e. be deleted
/// once there are no remaining associated triggers).
/// </remarks>
void AddJob(IJobDetail jobDetail, bool replace, bool storeNonDurableWhileAwaitingScheduling);
/// <summary>
/// Delete the identified <see cref="IJob" /> from the Scheduler - and any
/// associated <see cref="ITrigger" />s.
/// </summary>
/// <returns> true if the Job was found and deleted.</returns>
bool DeleteJob(JobKey jobKey);
/// <summary>
/// Delete the identified jobs from the Scheduler - and any
/// associated <see cref="ITrigger" />s.
/// </summary>
/// <remarks>
/// <para>Note that while this bulk operation is likely more efficient than
/// invoking <see cref="DeleteJob(JobKey)" /> several
/// times, it may have the adverse affect of holding data locks for a
/// single long duration of time (rather than lots of small durations
/// of time).</para>
/// </remarks>
/// <returns>
/// true if all of the Jobs were found and deleted, false if
/// one or more were not deleted.
/// </returns>
bool DeleteJobs(IList<JobKey> jobKeys);
/// <summary>
/// Trigger the identified <see cref="IJobDetail" />
/// (Execute it now).
/// </summary>
void TriggerJob(JobKey jobKey);
/// <summary>
/// Trigger the identified <see cref="IJobDetail" /> (Execute it now).
/// </summary>
/// <param name="data">
/// the (possibly <see langword="null" />) JobDataMap to be
/// associated with the trigger that fires the job immediately.
/// </param>
/// <param name="jobKey">
/// The <see cref="JobKey"/> of the <see cref="IJob" /> to be executed.
/// </param>
void TriggerJob(JobKey jobKey, JobDataMap data);
/// <summary>
/// Pause the <see cref="IJobDetail" /> with the given
/// key - by pausing all of its current <see cref="ITrigger" />s.
/// </summary>
void PauseJob(JobKey jobKey);
/// <summary>
/// Pause all of the <see cref="IJobDetail" />s in the
/// matching groups - by pausing all of their <see cref="ITrigger" />s.
/// </summary>
/// <remarks>
/// <para>
/// The Scheduler will "remember" that the groups are paused, and impose the
/// pause on any new jobs that are added to any of those groups until it is resumed.
/// </para>
/// <para>NOTE: There is a limitation that only exactly matched groups
/// can be remembered as paused. For example, if there are pre-existing
/// job in groups "aaa" and "bbb" and a matcher is given to pause
/// groups that start with "a" then the group "aaa" will be remembered
/// as paused and any subsequently added jobs in group "aaa" will be paused,
/// however if a job is added to group "axx" it will not be paused,
/// as "axx" wasn't known at the time the "group starts with a" matcher
/// was applied. HOWEVER, if there are pre-existing groups "aaa" and
/// "bbb" and a matcher is given to pause the group "axx" (with a
/// group equals matcher) then no jobs will be paused, but it will be
/// remembered that group "axx" is paused and later when a job is added
/// in that group, it will become paused.</para>
/// </remarks>
/// <seealso cref="ResumeJobs" />
void PauseJobs(GroupMatcher<JobKey> matcher);
/// <summary>
/// Pause the <see cref="ITrigger" /> with the given key.
/// </summary>
void PauseTrigger(TriggerKey triggerKey);
/// <summary>
/// Pause all of the <see cref="ITrigger" />s in the groups matching.
/// </summary>
/// <remarks>
/// <para>
/// The Scheduler will "remember" all the groups paused, and impose the
/// pause on any new triggers that are added to any of those groups until it is resumed.
/// </para>
/// <para>NOTE: There is a limitation that only exactly matched groups
/// can be remembered as paused. For example, if there are pre-existing
/// triggers in groups "aaa" and "bbb" and a matcher is given to pause
/// groups that start with "a" then the group "aaa" will be remembered as
/// paused and any subsequently added triggers in that group be paused,
/// however if a trigger is added to group "axx" it will not be paused,
/// as "axx" wasn't known at the time the "group starts with a" matcher
/// was applied. HOWEVER, if there are pre-existing groups "aaa" and
/// "bbb" and a matcher is given to pause the group "axx" (with a
/// group equals matcher) then no triggers will be paused, but it will be
/// remembered that group "axx" is paused and later when a trigger is added
/// in that group, it will become paused.</para>
/// </remarks>
/// <seealso cref="ResumeTriggers" />
void PauseTriggers(GroupMatcher<TriggerKey> matcher);
/// <summary>
/// Resume (un-pause) the <see cref="IJobDetail" /> with
/// the given key.
/// </summary>
/// <remarks>
/// If any of the <see cref="IJob" />'s<see cref="ITrigger" /> s missed one
/// or more fire-times, then the <see cref="ITrigger" />'s misfire
/// instruction will be applied.
/// </remarks>
void ResumeJob(JobKey jobKey);
/// <summary>
/// Resume (un-pause) all of the <see cref="IJobDetail" />s
/// in matching groups.
/// </summary>
/// <remarks>
/// If any of the <see cref="IJob" /> s had <see cref="ITrigger" /> s that
/// missed one or more fire-times, then the <see cref="ITrigger" />'s
/// misfire instruction will be applied.
/// </remarks>
/// <seealso cref="PauseJobs" />
void ResumeJobs(GroupMatcher<JobKey> matcher);
/// <summary>
/// Resume (un-pause) the <see cref="ITrigger" /> with the given
/// key.
/// </summary>
/// <remarks>
/// If the <see cref="ITrigger" /> missed one or more fire-times, then the
/// <see cref="ITrigger" />'s misfire instruction will be applied.
/// </remarks>
void ResumeTrigger(TriggerKey triggerKey);
/// <summary>
/// Resume (un-pause) all of the <see cref="ITrigger" />s in matching groups.
/// </summary>
/// <remarks>
/// If any <see cref="ITrigger" /> missed one or more fire-times, then the
/// <see cref="ITrigger" />'s misfire instruction will be applied.
/// </remarks>
/// <seealso cref="PauseTriggers" />
void ResumeTriggers(GroupMatcher<TriggerKey> matcher);
/// <summary>
/// Pause all triggers - similar to calling <see cref="PauseTriggers" />
/// on every group, however, after using this method <see cref="ResumeAll()" />
/// must be called to clear the scheduler's state of 'remembering' that all
/// new triggers will be paused as they are added.
/// </summary>
/// <remarks>
/// When <see cref="ResumeAll()" /> is called (to un-pause), trigger misfire
/// instructions WILL be applied.
/// </remarks>
/// <seealso cref="ResumeAll()" />
/// <seealso cref="PauseTriggers" />
/// <seealso cref="Standby()" />
void PauseAll();
/// <summary>
/// Resume (un-pause) all triggers - similar to calling
/// <see cref="ResumeTriggers" /> on every group.
/// </summary>
/// <remarks>
/// If any <see cref="ITrigger" /> missed one or more fire-times, then the
/// <see cref="ITrigger" />'s misfire instruction will be applied.
/// </remarks>
/// <seealso cref="PauseAll()" />
void ResumeAll();
/// <summary>
/// Get the keys of all the <see cref="IJobDetail" />s in the matching groups.
/// </summary>
Collection.ISet<JobKey> GetJobKeys(GroupMatcher<JobKey> matcher);
/// <summary>
/// Get all <see cref="ITrigger" /> s that are associated with the
/// identified <see cref="IJobDetail" />.
/// </summary>
/// <remarks>
/// The returned Trigger objects will be snap-shots of the actual stored
/// triggers. If you wish to modify a trigger, you must re-store the
/// trigger afterward (e.g. see <see cref="RescheduleJob(TriggerKey, ITrigger)" />).
/// </remarks>
IList<ITrigger> GetTriggersOfJob(JobKey jobKey);
/// <summary>
/// Get the names of all the <see cref="ITrigger" />s in the given
/// groups.
/// </summary>
Collection.ISet<TriggerKey> GetTriggerKeys(GroupMatcher<TriggerKey> matcher);
/// <summary>
/// Get the <see cref="IJobDetail" /> for the <see cref="IJob" />
/// instance with the given key .
/// </summary>
/// <remarks>
/// The returned JobDetail object will be a snap-shot of the actual stored
/// JobDetail. If you wish to modify the JobDetail, you must re-store the
/// JobDetail afterward (e.g. see <see cref="AddJob(IJobDetail, bool)" />).
/// </remarks>
IJobDetail GetJobDetail(JobKey jobKey);
/// <summary>
/// Get the <see cref="ITrigger" /> instance with the given key.
/// </summary>
/// <remarks>
/// The returned Trigger object will be a snap-shot of the actual stored
/// trigger. If you wish to modify the trigger, you must re-store the
/// trigger afterward (e.g. see <see cref="RescheduleJob(TriggerKey, ITrigger)" />).
/// </remarks>
ITrigger GetTrigger(TriggerKey triggerKey);
/// <summary>
/// Get the current state of the identified <see cref="ITrigger" />.
/// </summary>
/// <seealso cref="TriggerState.Normal" />
/// <seealso cref="TriggerState.Paused" />
/// <seealso cref="TriggerState.Complete" />
/// <seealso cref="TriggerState.Blocked" />
/// <seealso cref="TriggerState.Error" />
/// <seealso cref="TriggerState.None" />
TriggerState GetTriggerState(TriggerKey triggerKey);
/// <summary>
/// Add (register) the given <see cref="ICalendar" /> to the Scheduler.
/// </summary>
/// <param name="calName">Name of the calendar.</param>
/// <param name="calendar">The calendar.</param>
/// <param name="replace">if set to <c>true</c> [replace].</param>
/// <param name="updateTriggers">whether or not to update existing triggers that
/// referenced the already existing calendar so that they are 'correct'
/// based on the new trigger.</param>
void AddCalendar(string calName, ICalendar calendar, bool replace, bool updateTriggers);
/// <summary>
/// Delete the identified <see cref="ICalendar" /> from the Scheduler.
/// </summary>
/// <remarks>
/// If removal of the <code>Calendar</code> would result in
/// <see cref="ITrigger" />s pointing to non-existent calendars, then a
/// <see cref="SchedulerException" /> will be thrown.
/// </remarks>
/// <param name="calName">Name of the calendar.</param>
/// <returns>true if the Calendar was found and deleted.</returns>
bool DeleteCalendar(string calName);
/// <summary>
/// Get the <see cref="ICalendar" /> instance with the given name.
/// </summary>
ICalendar GetCalendar(string calName);
/// <summary>
/// Get the names of all registered <see cref="ICalendar" />.
/// </summary>
IList<string> GetCalendarNames();
/// <summary>
/// Request the interruption, within this Scheduler instance, of all
/// currently executing instances of the identified <see cref="IJob" />, which
/// must be an implementor of the <see cref="IInterruptableJob" /> interface.
/// </summary>
/// <remarks>
/// <para>
/// If more than one instance of the identified job is currently executing,
/// the <see cref="IInterruptableJob.Interrupt" /> method will be called on
/// each instance. However, there is a limitation that in the case that
/// <see cref="Interrupt(JobKey)" /> on one instances throws an exception, all
/// remaining instances (that have not yet been interrupted) will not have
/// their <see cref="Interrupt(JobKey)" /> method called.
/// </para>
///
/// <para>
/// If you wish to interrupt a specific instance of a job (when more than
/// one is executing) you can do so by calling
/// <see cref="GetCurrentlyExecutingJobs" /> to obtain a handle
/// to the job instance, and then invoke <see cref="Interrupt(JobKey)" /> on it
/// yourself.
/// </para>
/// <para>
/// This method is not cluster aware. That is, it will only interrupt
/// instances of the identified InterruptableJob currently executing in this
/// Scheduler instance, not across the entire cluster.
/// </para>
/// </remarks>
/// <returns>
/// true is at least one instance of the identified job was found and interrupted.
/// </returns>
/// <seealso cref="IInterruptableJob" />
/// <seealso cref="GetCurrentlyExecutingJobs" />
bool Interrupt(JobKey jobKey);
/// <summary>
/// Request the interruption, within this Scheduler instance, of the
/// identified executing job instance, which
/// must be an implementor of the <see cref="IInterruptableJob" /> interface.
/// </summary>
/// <remarks>
/// This method is not cluster aware. That is, it will only interrupt
/// instances of the identified InterruptableJob currently executing in this
/// Scheduler instance, not across the entire cluster.
/// </remarks>
/// <seealso cref="IInterruptableJob.Interrupt()" />
/// <seealso cref="GetCurrentlyExecutingJobs()" />
/// <seealso cref="IJobExecutionContext.FireInstanceId" />
/// <seealso cref="Interrupt(JobKey)" />
/// <param nane="fireInstanceId">
/// the unique identifier of the job instance to be interrupted (see <see cref="IJobExecutionContext.FireInstanceId" />
/// </param>
/// <param name="fireInstanceId"> </param>
/// <returns>true if the identified job instance was found and interrupted.</returns>
bool Interrupt(string fireInstanceId);
/// <summary>
/// Determine whether a <see cref="IJob" /> with the given identifier already
/// exists within the scheduler.
/// </summary>
/// <param name="jobKey">the identifier to check for</param>
/// <returns>true if a Job exists with the given identifier</returns>
bool CheckExists(JobKey jobKey);
/// <summary>
/// Determine whether a <see cref="ITrigger" /> with the given identifier already
/// exists within the scheduler.
/// </summary>
/// <param name="triggerKey">the identifier to check for</param>
/// <returns>true if a Trigger exists with the given identifier</returns>
bool CheckExists(TriggerKey triggerKey);
/// <summary>
/// Clears (deletes!) all scheduling data - all <see cref="IJob"/>s, <see cref="ITrigger" />s
/// <see cref="ICalendar"/>s.
/// </summary>
void Clear();
}
} | 45.97973 | 128 | 0.580838 | [
"Apache-2.0"
] | Despair/quartznet | src/Quartz/IScheduler.cs | 34,025 | C# |
using FreeSql;
using FreeSql.Internal;
using Microsoft.Extensions.DependencyInjection;
using Nps.Application.SysLog.Dtos;
using Nps.Application.SysLog.Services;
using Nps.Core.Aop.Attributes;
using Nps.Core.Entities;
using Nps.Infrastructure;
using Nps.Infrastructure.IdGenerators;
using Nps.Data.FreeSql;
using Serilog;
using StackExchange.Profiling;
using System;
using System.Threading.Tasks;
namespace Nps.Api.Extension.Service
{
/// <summary>
/// IServiceCollection扩展-FreeSqlORM
/// </summary>
public static partial class FreeSqlExtension
{
/// <summary>
/// 注入FreeSql
/// </summary>
/// <param name="services">IServiceCollection</param>
public static void AddFreeSql(this IServiceCollection services)
{
Log.Logger.Information("Initialize FreeSql Start;");
//获取数据库类型及其连接字符串
var dataTypeValue = NpsEnvironment.NPS_DB_DATETYPE;
var dataTypeConnectionString = NpsEnvironment.NPS_DB_MASTERCONNECTSTRING;
if (Enum.TryParse(dataTypeValue, out DataType dataType))
{
if (!Enum.IsDefined(typeof(DataType), dataType))
{
Log.Error($"数据库配置DataType:{dataType}无效");
}
if (dataTypeConnectionString.IsNullOrWhiteSpace())
{
Log.Error($"数据库配置ConnectionStrings:{dataType}连接字符串无效");
}
}
else
{
Log.Error($"数据库配置DataType:{dataTypeValue}无效");
}
//创建建造器
var builder = new FreeSqlBuilder()
.UseConnectionString(dataType, dataTypeConnectionString)
.UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower)
//设置是否自动同步表结构,开发环境必备
.UseAutoSyncStructure(NpsEnvironment.NPS_DB_SYNCSTRUCTURE.ToBooleanOrDefault(false))
.UseNoneCommandParameter(true)
.UseMonitorCommand(cmd => { }, (cmd, traceLog) =>
{//监听所有命令
Log.Logger.Debug($"MonitorCommand:{traceLog};");
});
//生成数据库操作对象
IFreeSql freeSql = builder.Build();
//开启联级保存功能(默认为关闭)
freeSql.SetDbContextOptions(opts => opts.EnableAddOrUpdateNavigateList = true);
//加载过滤器,设置全局软删除为false
freeSql.GlobalFilter.Apply<ISoftDelete>("IsDeleted", a => a.IsDeleted == false);
//监听CURD操作
freeSql.Aop.CurdAfter += (s, e) =>
{
//Task.Run(() =>//写法一
Parallel.For(0, 1, a =>//写法二
{
//添加MiniProfiler监控SQL性能
MiniProfiler.Current.CustomTiming("SQL:", $"【SQL语句】:{e.Sql},耗时:{e.ElapsedMilliseconds}毫秒");
//若实体中不含DisableSqlCurd标记,则将记录写入至数据库
if (e.EntityType.GetCustomAttribute<DisableSqlCurdAttribute>(false) == null)
{
//获取ISqlCurdService对象,在获取之前需要注入
var sqlCurdService = services.BuildServiceProvider().GetRequiredService<ISqlCurdService>();
sqlCurdService.Create(new SqlCurdAddInput
{
FullName = e.EntityType.FullName,
ExecuteMilliseconds = e.ElapsedMilliseconds,
Sql = e.Sql
});
}
});
};
//获取IdGenerator对象,在获取之前需要注入
var longGenerator = services.BuildServiceProvider().GetRequiredService<ILongIdGenerator>();
var guidGenerator = services.BuildServiceProvider().GetRequiredService<IGuidGenerator>();
//审计Curd
freeSql.Aop.AuditValue += (s, e) =>
{
if (e.Column.CsType == typeof(long))
{
if (e.Property.GetCustomAttribute<IdGeneratorAttribute>(false) != null)
{
if (e.Value?.ToString() == "0")
{//当主键为long类型且拥有Id自生成标记且值为0时,主键列不能设置自增属性
e.Value = longGenerator?.Create();
}
}
}
else if (e.Column.CsType == typeof(Guid))
{
if (e.Property.GetCustomAttribute<IdGeneratorAttribute>(false) != null)
{
if (e.Value?.ToString() == "00000000-0000-0000-0000-000000000000")
{//当主键为Guid类型且拥有Id自生成标记且值全为0时
e.Value = guidGenerator?.Create();
}
}
}
};
//注入IOC框架
services.AddSingleton(freeSql);
//注入仓储
services.AddFreeRepository();
//注入工作单元
services.AddScoped<UnitOfWorkManager>();
//注入SQLCurd语句写入服务
services.AddScoped<ISqlCurdService, SqlCurdService>();
//连接数据库
try
{
using var masterPool = freeSql.Ado.MasterPool.Get();
}
catch (Exception ex)
{
Log.Logger.Error(ex + ex.StackTrace + ex.Message + ex.InnerException);
return;
}
//同步表结构及初始化数据
try
{
//注意:只有当CURD到此表时,才会自动生成表结构。
//如需系统运行时迁移表结构,请使用SyncStructure方法
//在运行时直接生成表结构
if (NpsEnvironment.NPS_DB_SYNCSTRUCTURE.ToBooleanOrDefault(false))
{
freeSql.CodeFirst
.ConfigEntity()
.SeedData(NpsEnvironment.NPS_DB_SYNCDATA.ToBooleanOrDefault(false))//初始化部分数据
.SyncStructure(FreeSqlEntitySyncStructure.FindIEntities(new string[] { "Nps.Data" }));
}
}
catch (Exception ex)
{
Log.Logger.Error(ex + ex.StackTrace + ex.Message + ex.InnerException);
return;
}
Log.Logger.Information("Initialize FreeSql End;");
}
}
} | 38.208589 | 115 | 0.516859 | [
"Apache-2.0"
] | io2020/io_nps_server | src/Nps.Api.Extension/Service/FreeSqlExtension.cs | 6,894 | C# |
using cloudscribe.Core.Models;
using cloudscribe.UserProperties.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using sourceDev.WebApp.Components;
using System;
namespace Microsoft.Extensions.DependencyInjection
{
public static class CloudscribeFeatures
{
public static IServiceCollection SetupDataStorage(
this IServiceCollection services,
IConfiguration config
)
{
services.AddScoped<cloudscribe.Core.Models.Setup.ISetupTask, cloudscribe.Core.Web.Components.EnsureInitialDataSetupTask>();
var storage = config["DevOptions:DbPlatform"];
var efProvider = config["DevOptions:EFProvider"];
var useMiniProfiler = config.GetValue<bool>("DevOptions:EnableMiniProfiler");
switch (storage)
{
case "NoDb":
var useSingletons = true;
services.AddCloudscribeCoreNoDbStorage(useSingletons);
services.AddCloudscribeLoggingNoDbStorage(config);
services.AddCloudscribeKvpNoDbStorage();
if(useMiniProfiler)
{
services.AddMiniProfiler();
}
break;
case "ef":
default:
if (useMiniProfiler)
{
services.AddMiniProfiler()
.AddEntityFramework();
}
switch (efProvider)
{
case "sqlite":
var slConnection = config.GetConnectionString("SQLiteEntityFrameworkConnectionString");
services.AddCloudscribeCoreEFStorageSQLite(slConnection);
services.AddCloudscribeLoggingEFStorageSQLite(slConnection);
services.AddCloudscribeKvpEFStorageSQLite(slConnection);
break;
case "pgsql-old":
var pgConnection = config.GetConnectionString("PostgreSqlEntityFrameworkConnectionString");
services.AddCloudscribeCoreEFStoragePostgreSql(pgConnection);
services.AddCloudscribeLoggingEFStoragePostgreSql(pgConnection);
services.AddCloudscribeKvpEFStoragePostgreSql(pgConnection);
break;
case "pgsql":
var pgsConnection = config.GetConnectionString("PostgreSqlConnectionString");
services.AddCloudscribeCorePostgreSqlStorage(pgsConnection);
services.AddCloudscribeLoggingPostgreSqlStorage(pgsConnection);
services.AddCloudscribeKvpPostgreSqlStorage(pgsConnection);
break;
case "MySql":
var mysqlConnection = config.GetConnectionString("MySqlEntityFrameworkConnectionString");
services.AddCloudscribeCoreEFStorageMySql(mysqlConnection);
services.AddCloudscribeLoggingEFStorageMySQL(mysqlConnection);
services.AddCloudscribeKvpEFStorageMySql(mysqlConnection);
break;
case "MSSQL":
default:
var connectionString = config.GetConnectionString("EntityFrameworkConnectionString");
// this shows all the params with default values
// only connectionstring is required to be passed in
services.AddCloudscribeCoreEFStorageMSSQL(
connectionString: connectionString,
maxConnectionRetryCount: 0,
maxConnectionRetryDelaySeconds: 30,
transientSqlErrorNumbersToAdd: null,
useSql2008Compatibility: false);
//services.AddCloudscribeCoreEFStorageMSSQL(
// connectionString: connectionString,
// useSql2008Compatibility: true);
services.AddCloudscribeLoggingEFStorageMSSQL(connectionString);
services.AddCloudscribeKvpEFStorageMSSQL(connectionString);
break;
}
break;
}
return services;
}
public static IServiceCollection SetupCloudscribeFeatures(
this IServiceCollection services,
IConfiguration config
)
{
services.AddScoped<cloudscribe.Versioning.IVersionProvider, cloudscribe.Web.StaticFiles.VersionProvider>();
/* optional and only needed if you are using cloudscribe Logging */
services.AddCloudscribeLogging();
services.Configure<ProfilePropertySetContainer>(config.GetSection("ProfilePropertySetContainer"));
services.AddCloudscribeKvpUserProperties();
/* these are optional and only needed if using cloudscribe Setup */
//services.Configure<SetupOptions>(Configuration.GetSection("SetupOptions"));
//services.AddScoped<SetupManager, SetupManager>();
//services.AddScoped<IVersionProvider, SetupVersionProvider>();
//services.AddScoped<IVersionProvider, CloudscribeLoggingVersionProvider>();
/* end cloudscribe Setup */
//services.AddScoped<cloudscribe.Core.Web.ExtensionPoints.IHandleCustomRegistration, sourceDev.WebApp.Components.CustomRegistrationHandler>();
//services.AddCloudscribeCore(Configuration);
services.AddCloudscribeCoreMvc(config);
services.AddScoped<IGuardNeededRoles, DemoRoleGuard>();
var useWindowsCompatLdap = config.GetValue<bool>("DevOptions:UseWindowsCompatLdap");
if(useWindowsCompatLdap)
{
services.AddCloudscribeLdapWindowsSupport(config);
}
else
{
services.AddCloudscribeLdapSupport(config);
}
// this was just for testing expired password reset token
//services.Configure<DataProtectionTokenProviderOptions>(options =>
// options.TokenLifespan = TimeSpan.FromMinutes(3));
return services;
}
}
}
| 41.833333 | 154 | 0.563671 | [
"Apache-2.0"
] | maziesmith/cloudscribe | src/sourceDev.WebApp/Configuration/CloudscribeFeatures.cs | 6,779 | C# |
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using NHSD.GPIT.BuyingCatalogue.EntityFramework.Catalogue.Models;
using NHSD.GPIT.BuyingCatalogue.ServiceContracts.Solutions.Models;
using NHSD.GPIT.BuyingCatalogue.Test.Framework.AutoFixtureCustomisations;
using NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Solutions.Models;
using Xunit;
namespace NHSD.GPIT.BuyingCatalogue.WebApp.UnitTests.Areas.Solutions.Models
{
public static class SolutionSupplierDetailsModelTests
{
[Fact]
public static void Class_Inherits_SolutionDisplayBaseModel()
{
typeof(SolutionSupplierDetailsModel)
.Should()
.BeAssignableTo<SolutionDisplayBaseModel>();
}
[Theory]
[CommonAutoData]
public static void Constructor_PopulatesAllProperties(Solution solution)
{
var catalogueItem = solution.CatalogueItem;
var model = new SolutionSupplierDetailsModel(catalogueItem, new CatalogueItemContentStatus());
model.Name.Should().Be(catalogueItem.Supplier.Name);
model.Url.Should().Be(catalogueItem.Supplier.SupplierUrl);
model.Summary.Should().Be(catalogueItem.Supplier.Summary);
model.Contacts.Any().Should().BeTrue();
}
[Theory]
[CommonAutoData]
public static void HasContacts_ValidContacts_ReturnsTrue(SolutionSupplierDetailsModel model)
{
model.Contacts.Any(c => c != null).Should().BeTrue();
model.HasContacts().Should().BeTrue();
}
[Fact]
public static void HasContacts_NullContacts_ReturnsFalse()
{
var model = new SolutionSupplierDetailsModel
{
Contacts = new List<SupplierContactViewModel> { null, null, },
};
model.HasContacts().Should().BeFalse();
}
[Fact]
public static void HasContacts_EmptyContacts_ReturnsFalse()
{
var model = new SolutionSupplierDetailsModel
{
Contacts = new List<SupplierContactViewModel>(),
};
model.HasContacts().Should().BeFalse();
}
[Fact]
public static void HasContacts_NullCollection_ReturnsFalse()
{
var model = new SolutionSupplierDetailsModel
{
Contacts = null,
};
model.HasContacts().Should().BeFalse();
}
}
}
| 32.141026 | 106 | 0.630235 | [
"MIT"
] | nhs-digital-gp-it-futures/GPITBuyingCatalogue | tests/NHSD.GPIT.BuyingCatalogue.WebApp.UnitTests/Areas/Solutions/Models/SolutionSupplierDetailsModelTests.cs | 2,509 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.DotNet.XUnitExtensions;
using Test.Cryptography;
using Xunit;
using Xunit.Abstractions;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public class CertTests
{
private const string PrivateKeySectionHeader = "[Private Key]";
private const string PublicKeySectionHeader = "[Public Key]";
private readonly ITestOutputHelper _log;
public CertTests(ITestOutputHelper output)
{
_log = output;
}
[Fact]
public static void X509CertTest()
{
string certSubject = @"CN=Microsoft Corporate Root Authority, OU=ITG, O=Microsoft, L=Redmond, S=WA, C=US, E=pkit@microsoft.com";
string certSubjectObsolete = @"E=pkit@microsoft.com, C=US, S=WA, L=Redmond, O=Microsoft, OU=ITG, CN=Microsoft Corporate Root Authority";
using (X509Certificate cert = new X509Certificate(Path.Combine("TestData", "microsoft.cer")))
{
Assert.Equal(certSubject, cert.Subject);
Assert.Equal(certSubject, cert.Issuer);
#pragma warning disable CS0618 // Type or member is obsolete
Assert.Equal(certSubjectObsolete, cert.GetName());
Assert.Equal(certSubjectObsolete, cert.GetIssuerName());
#pragma warning restore CS0618
int snlen = cert.GetSerialNumber().Length;
Assert.Equal(16, snlen);
byte[] serialNumber = new byte[snlen];
Buffer.BlockCopy(cert.GetSerialNumber(), 0,
serialNumber, 0,
snlen);
Assert.Equal(0xF6, serialNumber[0]);
Assert.Equal(0xB3, serialNumber[snlen / 2]);
Assert.Equal(0x2A, serialNumber[snlen - 1]);
Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm());
int pklen = cert.GetPublicKey().Length;
Assert.Equal(270, pklen);
byte[] publicKey = new byte[pklen];
Buffer.BlockCopy(cert.GetPublicKey(), 0,
publicKey, 0,
pklen);
Assert.Equal(0x30, publicKey[0]);
Assert.Equal(0xB6, publicKey[9]);
Assert.Equal(1, publicKey[pklen - 1]);
}
}
[Fact]
public static void X509Cert2Test()
{
string certName = @"E=admin@digsigtrust.com, CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US";
DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
{
Assert.Equal(certName, cert2.IssuerName.Name);
Assert.Equal(certName, cert2.SubjectName.Name);
Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true));
PublicKey pubKey = cert2.PublicKey;
Assert.Equal("RSA", pubKey.Oid.FriendlyName);
Assert.Equal(notAfter, cert2.NotAfter);
Assert.Equal(notBefore, cert2.NotBefore);
Assert.Equal(notAfter.ToString(), cert2.GetExpirationDateString());
Assert.Equal(notBefore.ToString(), cert2.GetEffectiveDateString());
Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber);
Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value);
Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint);
Assert.Equal(3, cert2.Version);
}
}
[ActiveIssue(29779)]
[ConditionalFact]
[OuterLoop("May require using the network, to download CRLs and intermediates")]
public void TestVerify()
{
bool success;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
{
// Fails because expired (NotAfter = 10/16/2016)
Assert.False(microsoftDotCom.Verify(), "MicrosoftDotComSslCertBytes");
}
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
{
// NotAfter=10/31/2023
success = microsoftDotComIssuer.Verify();
if (!success)
{
LogVerifyErrors(microsoftDotComIssuer, "MicrosoftDotComIssuerBytes");
}
Assert.True(success, "MicrosoftDotComIssuerBytes");
}
// High Sierra fails to build a chain for a self-signed certificate with revocation enabled.
// https://github.com/dotnet/corefx/issues/21875
if (!PlatformDetection.IsMacOsHighSierraOrHigher)
{
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
// NotAfter=7/17/2036
success = microsoftDotComRoot.Verify();
if (!success)
{
LogVerifyErrors(microsoftDotComRoot, "MicrosoftDotComRootBytes");
}
Assert.True(success, "MicrosoftDotComRootBytes");
}
}
}
private void LogVerifyErrors(X509Certificate2 cert, string testName)
{
// Emulate cert.Verify() implementation in order to capture and log errors.
try
{
using (var chain = new X509Chain())
{
if (!chain.Build(cert))
{
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
_log.WriteLine(string.Format($"X509Certificate2.Verify error: {testName}, {chainStatus.Status}, {chainStatus.StatusInformation}"));
}
}
else
{
_log.WriteLine(string.Format($"X509Certificate2.Verify expected error; received none: {testName}"));
}
}
}
catch (Exception e)
{
_log.WriteLine($"X509Certificate2.Verify exception: {testName}, {e}");
}
}
[Fact]
public static void X509CertEmptyToString()
{
using (var c = new X509Certificate())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate";
Assert.Equal(expectedResult, c.ToString());
Assert.Equal(expectedResult, c.ToString(false));
Assert.Equal(expectedResult, c.ToString(true));
}
}
[Fact]
public static void X509Cert2EmptyToString()
{
using (var c2 = new X509Certificate2())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate2";
Assert.Equal(expectedResult, c2.ToString());
Assert.Equal(expectedResult, c2.ToString(false));
Assert.Equal(expectedResult, c2.ToString(true));
}
}
[Fact]
public static void X509Cert2ToStringVerbose()
{
using (X509Store store = new X509Store("My", StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 c in store.Certificates)
{
Assert.False(string.IsNullOrWhiteSpace(c.ToString(true)));
c.Dispose();
}
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void X509Certificate2ToStringVerbose_WithPrivateKey(X509KeyStorageFlags keyStorageFlags)
{
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
string certToString = cert.ToString(true);
Assert.Contains(PrivateKeySectionHeader, certToString);
Assert.Contains(PublicKeySectionHeader, certToString);
}
}
[Fact]
public static void X509Certificate2ToStringVerbose_NoPrivateKey()
{
using (var cert = new X509Certificate2(TestData.MsCertificatePemBytes))
{
string certToString = cert.ToString(true);
Assert.DoesNotContain(PrivateKeySectionHeader, certToString);
Assert.Contains(PublicKeySectionHeader, certToString);
}
}
[Fact]
public static void X509Cert2CreateFromEmptyPfx()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.EmptyPfx));
}
[Fact]
public static void X509Cert2CreateFromPfxFile()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "DummyTcpServer.pfx")))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
public static void X509Cert2CreateFromPfxWithPassword()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.pfx"), "test"))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
public static void X509Certificate2FromPkcs7DerFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7b")));
}
[Fact]
public static void X509Certificate2FromPkcs7PemFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7c")));
}
[Fact]
public static void X509Certificate2FromPkcs7DerBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SingleDerBytes));
}
[Fact]
public static void X509Certificate2FromPkcs7PemBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SinglePemBytes));
}
[Fact]
public static void UseAfterDispose()
{
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
IntPtr h = c.Handle;
// Do a couple of things that would only be true on a valid certificate, as a precondition.
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
c.Dispose();
// For compat reasons, Dispose() acts like the now-defunct Reset() method rather than
// causing ObjectDisposedExceptions.
h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
// State held on X509Certificate
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString());
#if HAVE_THUMBPRINT_OVERLOADS
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash(HashAlgorithmName.SHA256));
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString(HashAlgorithmName.SHA256));
#endif
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => c.Subject);
Assert.ThrowsAny<CryptographicException>(() => c.NotBefore);
Assert.ThrowsAny<CryptographicException>(() => c.NotAfter);
#if HAVE_THUMBPRINT_OVERLOADS
Assert.ThrowsAny<CryptographicException>(
() => c.TryGetCertHash(HashAlgorithmName.SHA256, Array.Empty<byte>(), out _));
#endif
// State held on X509Certificate2
Assert.ThrowsAny<CryptographicException>(() => c.RawData);
Assert.ThrowsAny<CryptographicException>(() => c.SignatureAlgorithm);
Assert.ThrowsAny<CryptographicException>(() => c.Version);
Assert.ThrowsAny<CryptographicException>(() => c.SubjectName);
Assert.ThrowsAny<CryptographicException>(() => c.IssuerName);
Assert.ThrowsAny<CryptographicException>(() => c.PublicKey);
Assert.ThrowsAny<CryptographicException>(() => c.Extensions);
Assert.ThrowsAny<CryptographicException>(() => c.PrivateKey);
}
}
[Fact]
public static void ExportPublicKeyAsPkcs12()
{
using (X509Certificate2 publicOnly = new X509Certificate2(TestData.MsCertificate))
{
// Pre-condition: There's no private key
Assert.False(publicOnly.HasPrivateKey);
// macOS 10.12 (Sierra) fails to create a PKCS#12 blob if it has no private keys within it.
bool shouldThrow = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
try
{
byte[] pkcs12Bytes = publicOnly.Export(X509ContentType.Pkcs12);
Assert.False(shouldThrow, "PKCS#12 export of a public-only certificate threw as expected");
// Read it back as a collection, there should be only one cert, and it should
// be equal to the one we started with.
using (ImportedCollection ic = Cert.Import(pkcs12Bytes))
{
X509Certificate2Collection fromPfx = ic.Collection;
Assert.Equal(1, fromPfx.Count);
Assert.Equal(publicOnly, fromPfx[0]);
}
}
catch (CryptographicException)
{
if (!shouldThrow)
{
throw;
}
}
}
}
[Fact]
public static void X509Certificate2WithT61String()
{
string certSubject = @"E=mabaul@microsoft.com, OU=Engineering, O=Xamarin, S=Massachusetts, C=US, CN=test-server.local";
using (var cert = new X509Certificate2(TestData.T61StringCertificate))
{
Assert.Equal(certSubject, cert.Subject);
Assert.Equal(certSubject, cert.Issuer);
Assert.Equal("9E7A5CCC9F951A8700", cert.GetSerialNumber().ByteArrayToHex());
Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm());
Assert.Equal(74, cert.GetPublicKey().Length);
Assert.Equal("test-server.local", cert.GetNameInfo(X509NameType.SimpleName, false));
Assert.Equal("mabaul@microsoft.com", cert.GetNameInfo(X509NameType.EmailName, false));
}
}
public static IEnumerable<object> StorageFlags => CollectionImportTests.StorageFlags;
}
}
| 41.384224 | 159 | 0.571323 | [
"MIT"
] | Fasjeit/corefx | src/System.Security.Cryptography.X509Certificates/tests/CertTests.cs | 16,264 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
using System.Reactive.Linq;
namespace Lpp
{
public static class UtilityExtensions
{
public static TValue ValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue ))
{
//Contract.Requires( dictionary != null );
TValue res;
return dictionary.TryGetValue(key, out res) ? res : defaultValue;
}
public static string MemberName<T>(this Expression<T> expr)
{
//Contract.Requires( expr != null );
return expr.Body.MemberName();
}
public static IDictionary<string, object> CallParameters<T>(this Expression<T> expr)
{
//Contract.Requires( expr != null );
//Contract.Ensures( Contract.Result<IDictionary<string,object>>() != null );
return expr.Body.CallParameters();
}
public static IDictionary<string, object> CallParameters(this Expression expr)
{
//Contract.Requires( expr != null );
//Contract.Ensures( Contract.Result<IDictionary<string, object>>() != null );
switch (expr.NodeType)
{
case ExpressionType.Call:
{
var mce = expr as MethodCallExpression;
return
mce.Arguments
.Zip(mce.Method.GetParameters(), (a, p) => new { param = p, value = a.Eval() })
//.SelectMany( x =>
// ( x.param.ParameterType.IsPrimitive || x.param.ParameterType == typeof( string ) ) ?
// EnumerableEx.Return( new { x.param.Name, x.value } ) :
// TypeDescriptor.GetProperties( x.value ).Cast<PropertyDescriptor>()
// .Select( p => new { p.Name, value = p.GetValue( x.value ) } ) )
.ToDictionary(x => x.param.Name, x => x.value);
}
case ExpressionType.Convert: return (expr as UnaryExpression).Operand.CallParameters();
default: throw new InvalidOperationException("Unsupported expression type: " + expr.NodeType);
}
}
public static object Eval(this Expression expression)
{
return
Expression.Lambda<Func<object>>(
Expression.Convert(expression, typeof(object))
)
.Compile()
();
}
public static string MemberName(this Expression expr)
{
switch (expr.NodeType)
{
case ExpressionType.MemberAccess: return (expr as MemberExpression).Member.Name;
case ExpressionType.Call: return (expr as MethodCallExpression).Method.Name;
case ExpressionType.Convert: return (expr as UnaryExpression).Operand.MemberName();
default: return null;
//throw new InvalidOperationException( "Unsupported expression type: " + expr.NodeType );
}
}
public static void Raise(this EventHandler e, object sender = null)
{
if (e != null) e(sender, EventArgs.Empty);
}
public static void Raise<T>(this EventHandler<T> e, object sender, T args) where T : EventArgs
{
if (e != null) e(sender, args);
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
public static ISet<T> ToSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
public static IDictionary<TKey, TValue> Merge<TKey, TValue>(this IDictionary<TKey, TValue> a, IDictionary<TKey, TValue> b)
{
if (a == null) return b;
if (b == null) return a;
var res = new SortedList<TKey, TValue>(a);
foreach (var k in b) res[k.Key] = k.Value;
return res;
}
public static IDictionary<T, V> MapValues<T, U, V>(this IDictionary<T, U> d, Func<U, V> selector)
{
//Contract.Requires( d != null );
//Contract.Requires( selector != null );
return d.ToDictionary(x => x.Key, x => selector(x.Value));
}
public static IDictionary<V, U> MapKeys<T, U, V>(this IDictionary<T, U> d, Func<T, V> selector)
{
//Contract.Requires( d != null );
//Contract.Requires( selector != null );
return d.ToDictionary(x => selector(x.Key), x => x.Value);
}
public static bool NullOrEmpty<T>(this IEnumerable<T> s) { return s == null || !s.Any(); }
public static bool NullOrSpace(this string s) { return string.IsNullOrWhiteSpace(s); }
public static ILookup<T, U> ToLookup<X, T, U>(this IEnumerable<X> source, Func<X, T> selectKey, Func<X, IEnumerable<U>> selectValues)
{
//Contract.Requires(source != null);
//Contract.Requires( selectKey != null );
//Contract.Requires( selectValues != null );
return source
.SelectMany(x => selectValues(x).EmptyIfNull().Select(value => new { key = selectKey(x), value }))
.ToLookup(x => x.key, x => x.value);
}
public static T If<T>(this T source, bool condition, Func<T, T> then)
{
//Contract.Requires( then != null );
return condition ? then(source) : source;
}
public static U If<T, U>(this T source, bool condition, Func<T, U> then, Func<T, U> fnElse)
{
//Contract.Requires( then != null );
//Contract.Requires( fnElse != null );
return (condition ? then : fnElse)(source);
}
public static void CallDispose(this IDisposable d)
{
if (d != null) d.Dispose();
}
public static ILookup<TKey, TValue> Merge<TKey, TValue>(this ILookup<TKey, TValue> a, IEnumerable<ILookup<TKey, TValue>> bs)
{
//Contract.Requires( a != null );
//Contract.Requires( bs != null );
//Contract.Ensures( Contract.Result<ILookup<TKey, TValue>>() != null );
return flatten(a).Concat(bs.SelectMany(flatten)).ToLookup(k => k.Key, k => k.Value);
}
public static ILookup<TKey, TValue> Merge<TKey, TValue>(this ILookup<TKey, TValue> a, ILookup<TKey, TValue> b)
{
//Contract.Requires( a != null );
//Contract.Requires( b != null );
//Contract.Ensures( Contract.Result<ILookup<TKey, TValue>>() != null );
return a.Merge(EnumerableEx.Return(b));
}
static IEnumerable<KeyValuePair<TKey, TValue>> flatten<TKey, TValue>(ILookup<TKey, TValue> l)
{
return from k in l
from v in k
select new KeyValuePair<TKey, TValue>(k.Key, v);
}
public static string ToQueryString(this System.Collections.Specialized.NameValueCollection values)
{
if (values == null && values.Count == 0)
{
return string.Empty;
}
var sb = new StringBuilder();
for (int i = 0; i < values.Count; i++)
{
string text = values.GetKey(i);
{
text = System.Web.HttpUtility.UrlEncode(text);
string key = (!string.IsNullOrEmpty(text)) ? (text + "=") : string.Empty;
string[] vals = values.GetValues(i);
if (sb.Length > 0)
sb.Append('&');
if (vals == null || vals.Length == 0)
sb.Append(key);
else
{
if (vals.Length == 1)
{
sb.Append(key);
sb.Append(System.Web.HttpUtility.UrlEncode(vals[0]));
}
else
{
for (int j = 0; j < vals.Length; j++)
{
if (j > 0)
sb.Append('&');
sb.Append(key);
sb.Append(System.Web.HttpUtility.UrlEncode(vals[j]));
}
}
}
}
}
if (sb.Length > 0)
{
sb.Insert(0, "?");
}
return sb.ToString();
}
}
} | 38.127119 | 150 | 0.50489 | [
"Apache-2.0"
] | Missouri-BMI/popmednet | Lpp.Adapters/Lpp.Dns.DataMart.Client/Lib/Utils/UtilityExtensions.cs | 9,000 | C# |
/*
* TeamCity REST API
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 2018.1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using TeamCity.Api;
using TeamCity.Model;
using TeamCity.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace TeamCity.Test
{
/// <summary>
/// Class for testing PropertiesDto
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class PropertiesDtoTests
{
// TODO uncomment below to declare an instance variable for PropertiesDto
//private PropertiesDto instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of PropertiesDto
//instance = new PropertiesDto();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of PropertiesDto
/// </summary>
[Test]
public void PropertiesDtoInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" PropertiesDto
//Assert.IsInstanceOfType<PropertiesDto> (instance, "variable 'instance' is a PropertiesDto");
}
/// <summary>
/// Test the property 'Count'
/// </summary>
[Test]
public void CountTest()
{
// TODO unit test for the property 'Count'
}
/// <summary>
/// Test the property 'Href'
/// </summary>
[Test]
public void HrefTest()
{
// TODO unit test for the property 'Href'
}
/// <summary>
/// Test the property 'Property'
/// </summary>
[Test]
public void PropertyTest()
{
// TODO unit test for the property 'Property'
}
}
}
| 24.010309 | 106 | 0.565049 | [
"MIT"
] | NikolayPianikov/teamcity.client | generated/src/TeamCity.Test/Model/PropertiesDtoTests.cs | 2,329 | 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.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.polardb.Transform;
using Aliyun.Acs.polardb.Transform.V20170801;
namespace Aliyun.Acs.polardb.Model.V20170801
{
public class CreateAccountRequest : RpcAcsRequest<CreateAccountResponse>
{
public CreateAccountRequest()
: base("polardb", "2017-08-01", "CreateAccount", "polardb", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.polardb.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.polardb.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private long? resourceOwnerId;
private string accountType;
private string accountDescription;
private string accountPrivilege;
private string accountName;
private string resourceOwnerAccount;
private string dBClusterId;
private string ownerAccount;
private long? ownerId;
private string accountPassword;
private string dBName;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string AccountType
{
get
{
return accountType;
}
set
{
accountType = value;
DictionaryUtil.Add(QueryParameters, "AccountType", value);
}
}
public string AccountDescription
{
get
{
return accountDescription;
}
set
{
accountDescription = value;
DictionaryUtil.Add(QueryParameters, "AccountDescription", value);
}
}
public string AccountPrivilege
{
get
{
return accountPrivilege;
}
set
{
accountPrivilege = value;
DictionaryUtil.Add(QueryParameters, "AccountPrivilege", value);
}
}
public string AccountName
{
get
{
return accountName;
}
set
{
accountName = value;
DictionaryUtil.Add(QueryParameters, "AccountName", value);
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string DBClusterId
{
get
{
return dBClusterId;
}
set
{
dBClusterId = value;
DictionaryUtil.Add(QueryParameters, "DBClusterId", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string AccountPassword
{
get
{
return accountPassword;
}
set
{
accountPassword = value;
DictionaryUtil.Add(QueryParameters, "AccountPassword", value);
}
}
public string DBName
{
get
{
return dBName;
}
set
{
dBName = value;
DictionaryUtil.Add(QueryParameters, "DBName", value);
}
}
public override CreateAccountResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return CreateAccountResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 21.672897 | 137 | 0.649633 | [
"Apache-2.0"
] | chys0404/aliyun-openapi-net-sdk | aliyun-net-sdk-polardb/Polardb/Model/V20170801/CreateAccountRequest.cs | 4,638 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleETrade.SampleETradePublic
File: MyTradesWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleETrade
{
public partial class MyTradesWindow
{
public MyTradesWindow()
{
InitializeComponent();
}
}
} | 32.28 | 92 | 0.60347 | [
"Apache-2.0"
] | 1M15M3/StockSharp | Samples/ETrade/SampleETrade/MyTradesWindow.xaml.cs | 809 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IMethodCollectionPage.cs.tt
namespace Microsoft.Graph
{
using System.Text.Json.Serialization;
/// <summary>
/// The interface IGroupPolicyConfigurationAssignCollectionPage.
/// </summary>
[InterfaceConverter(typeof(InterfaceConverter<GroupPolicyConfigurationAssignCollectionPage>))]
public interface IGroupPolicyConfigurationAssignCollectionPage : ICollectionPage<GroupPolicyConfigurationAssignment>
{
/// <summary>
/// Gets the next page <see cref="IGroupPolicyConfigurationAssignRequest"/> instance.
/// </summary>
IGroupPolicyConfigurationAssignRequest NextPageRequest { get; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString);
}
}
| 41.354839 | 153 | 0.634165 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IGroupPolicyConfigurationAssignCollectionPage.cs | 1,282 | C# |
using System;
using System.Collections;
using Addler.Runtime.Core;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
namespace Addler.Tests.Core
{
[PrebuildSetup(typeof(PrePostBuildProcess))]
[PostBuildCleanup(typeof(PrePostBuildProcess))]
public class AddressablesPreloaderTest
{
[UnityTest]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor)]
public IEnumerator PreloadAsync_CanPreload()
{
var preloader = new AddressablesPreloader();
var referenceCounter = new ReferenceCounter(TestStrings.TestPrefabPath);
yield return preloader.PreloadAsync(TestStrings.TestPrefabAddress).AsIEnumerator();
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(1));
var prefab = preloader.Get<GameObject>(TestStrings.TestPrefabAddress);
Assert.That(prefab, Is.EqualTo(AssetDatabase.LoadAssetAtPath<GameObject>(TestStrings.TestPrefabPath)));
preloader.Dispose();
// The handle is completely discarded in the next frame so wait a frame.
yield return null;
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(0));
}
[UnityTest]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor)]
public IEnumerator PreloadAsync_Disposed_ObjectDisposedException()
{
var preloader = new AddressablesPreloader();
var referenceCounter = new ReferenceCounter(TestStrings.TestPrefabPath);
preloader.Dispose();
Exception ex = null;
try
{
preloader.PreloadAsync(TestStrings.TestPrefabAddress).Wait();
}
catch (AggregateException e)
{
ex = e.InnerException;
preloader.Dispose();
}
Assert.That(ex, Is.TypeOf<ObjectDisposedException>());
// The handle is completely discarded in the next frame so wait a frame.
yield return null;
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(0));
}
[Test]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor)]
public void PreloadAsync_KeysIsNull_ArgumentNullException()
{
var preloader = new AddressablesPreloader();
Exception ex = null;
try
{
preloader.PreloadAsync(null).Wait();
}
catch (AggregateException e)
{
ex = e.InnerException;
preloader.Dispose();
}
Assert.That(ex, Is.TypeOf<ArgumentNullException>());
}
[Test]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor)]
public void PreloadAsync_KeysIsEmpty_ArgumentException()
{
var preloader = new AddressablesPreloader();
Exception ex = null;
try
{
preloader.PreloadAsync().Wait();
}
catch (AggregateException e)
{
ex = e.InnerException;
preloader.Dispose();
}
Assert.That(ex, Is.TypeOf<ArgumentException>());
}
[UnityTest]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor)]
public IEnumerator Get_CanGet()
{
var preloader = new AddressablesPreloader();
var referenceCounter = new ReferenceCounter(TestStrings.TestPrefabPath);
yield return preloader.PreloadAsync(TestStrings.TestPrefabAddress).AsIEnumerator();
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(1));
var prefab = preloader.Get<GameObject>(TestStrings.TestPrefabAddress);
Assert.That(prefab, Is.EqualTo(AssetDatabase.LoadAssetAtPath<GameObject>(TestStrings.TestPrefabPath)));
preloader.Dispose();
// The handle is completely discarded in the next frame so wait a frame.
yield return null;
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(0));
}
[UnityTest]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor)]
public IEnumerator Get_Disposed_ObjectDisposedException()
{
var preloader = new AddressablesPreloader();
var referenceCounter = new ReferenceCounter(TestStrings.TestPrefabPath);
yield return preloader.PreloadAsync(TestStrings.TestPrefabAddress).AsIEnumerator();
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(1));
preloader.Dispose();
Assert.Throws<ObjectDisposedException>(() => { preloader.Get<GameObject>(TestStrings.TestPrefabAddress); });
// The handle is completely discarded in the next frame so wait a frame.
yield return null;
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(0));
}
[UnityTest]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor)]
public IEnumerator Get_NotPreloaded_InvalidOperationException()
{
var preloader = new AddressablesPreloader();
var referenceCounter = new ReferenceCounter(TestStrings.TestPrefabPath);
Assert.Throws<InvalidOperationException>(() =>
{
try
{
preloader.Get<GameObject>(TestStrings.TestPrefabAddress);
}
finally
{
preloader.Dispose();
}
});
// The handle is completely discarded in the next frame so wait a frame.
yield return null;
Assert.That(referenceCounter.ReferenceCount, Is.EqualTo(0));
}
}
} | 39.039474 | 120 | 0.619481 | [
"MIT"
] | Haruma-K/Addler | Packages/com.harumak.addler/Tests/Core/AddressablesPreloaderTest.cs | 5,936 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using RestSharp;
using BtseApi.Client.DataClasses.Futures;
using BtseApi.Client.ApiSettings;
using BtseApi.Client.Helpers;
namespace BtseApi.Client.Operations.Futures.Trading
{
public static class ClosePosition
{
private static string urlPath = "/api/v2.1/order/close_position";
/// <summary>
/// Closes a user's position for the particular market as specified by symbol.
/// If type is specified as LIMIT, then price is mandatory.
/// When type is MARKET, it closes the position at market price.
/// </summary>
public static string Execute(ClosePositionForm info)
{
var client = Helper.GetClient(urlPath);
var request = new RestRequest(Method.POST);
var options = new JsonSerializerOptions();
options.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
var body = JsonSerializer.Serialize(info, options);
request.AddJsonBody(body);
Helper.AddRequestAuth(request, urlPath, body);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
IRestResponse response = client.Execute(request);
return response.Content;
}
/// <summary>
/// Closes a user's position for the particular market as specified by symbol.
/// If type is specified as LIMIT, then price is mandatory.
/// When type is MARKET, it closes the position at market price.
/// </summary>
public static List<OrderResponse> ExecuteObj(
ClosePositionForm info)
{
var json = Execute(info);
var result =
JsonSerializer.Deserialize<List<OrderResponse>>(json,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
return result;
}
}
}
| 32.384615 | 112 | 0.644181 | [
"MIT"
] | yuriysokha/BTSEClient.Net | BTSEClient/BtseApi.Client/Operations/Futures/Trading/ClosePosition.cs | 2,107 | C# |
//-----------------------------------------------------------------------
// <copyright file="DiveraStatus.cs" company="Moritz Jökel">
// Copyright (c) Moritz Jökel. All Rights Reserved.
// Licensed under Creative Commons Zero v1.0 Universal
// </copyright>
//-----------------------------------------------------------------------
namespace DiveraFMSConnect.Models
{
using Newtonsoft.Json;
/// <summary>
/// Repräsentiert einen Fahrzeugstatus aus Divera.
/// </summary>
public class DiveraStatus
{
/// <summary>
/// Holt oder setzt den Fahrzeugstatus.
/// </summary>
public int Status { get; set; }
/// <summary>
/// Holt oder setzt die Fahrzeugstatus-ID.
/// </summary>
[JsonProperty("status_id")]
public int StatusId { get; set; }
/// <summary>
/// Holt oder setzt den Zeitstempel des Fahrzeugstatus als UNIX-Timestamp.
/// </summary>
[JsonProperty("status_ts")]
public int StatusTimestamp { get; set; }
/// <summary>
/// Holt oder setzt die Bemerkung zum Fahrzeugstatus.
/// </summary>
[JsonProperty("status_note")]
public string StatusNote { get; set; }
/// <summary>
/// Holt oder setzt den Breitengrad der Fahrzeugposition.
/// </summary>
[JsonProperty("lat")]
public decimal Latitude { get; set; }
/// <summary>
/// Holt oder setzt den Längengrad der Fahrzeugposition.
/// </summary>
[JsonProperty("lng")]
public decimal Longitude { get; set; }
}
}
| 30.811321 | 82 | 0.523576 | [
"CC0-1.0"
] | MrzJkl/DiveraFMSConnect | DiveraFMSConnect/Models/DiveraStatus.cs | 1,639 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SharpFlappyBird")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xavier Flix")]
[assembly: AssemblyProduct("SharpFlappyBird")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("14a8d749-7532-4b4f-8ce5-62be6e01b436")]
// 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("2021.6.18.863")]
[assembly: AssemblyFileVersion("2021.6.18.861")]
| 38.388889 | 84 | 0.748915 | [
"MIT"
] | morphx666/SharpFlappyBird | SharpFlappyBird(WinForms)/Properties/AssemblyInfo.cs | 1,385 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudfront-2014-11-06.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.CloudFront.Model
{
///<summary>
/// CloudFront exception
/// </summary>
public class InvalidGeoRestrictionParameterException : AmazonCloudFrontException
{
/// <summary>
/// Constructs a new InvalidGeoRestrictionParameterException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidGeoRestrictionParameterException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidGeoRestrictionParameterException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidGeoRestrictionParameterException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidGeoRestrictionParameterException
/// </summary>
/// <param name="innerException"></param>
public InvalidGeoRestrictionParameterException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidGeoRestrictionParameterException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidGeoRestrictionParameterException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidGeoRestrictionParameterException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidGeoRestrictionParameterException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
}
} | 41.151899 | 181 | 0.650261 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/CloudFront/Generated/Model/InvalidGeoRestrictionParameterException.cs | 3,251 | 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
#if MS_IO_REDIST
using System;
using System.IO;
namespace Microsoft.IO
#else
namespace System.IO
#endif
{
// Provides methods for processing file system strings in a cross-platform manner.
// Most of the methods don't do a complete parsing (such as examining a UNC hostname),
// but they will handle most string operations.
public static partial class Path
{
// Public static readonly variant of the separators. The Path implementation itself is using
// internal const variant of the separators for better performance.
public static readonly char DirectorySeparatorChar = PathInternal.DirectorySeparatorChar;
public static readonly char AltDirectorySeparatorChar = PathInternal.AltDirectorySeparatorChar;
public static readonly char VolumeSeparatorChar = PathInternal.VolumeSeparatorChar;
public static readonly char PathSeparator = PathInternal.PathSeparator;
// For generating random file names
// 8 random bytes provides 12 chars in our encoding for the 8.3 name.
private const int KeyLength = 8;
[Obsolete("Path.InvalidPathChars has been deprecated. Use GetInvalidPathChars or GetInvalidFileNameChars instead.")]
public static readonly char[] InvalidPathChars = GetInvalidPathChars();
// Changes the extension of a file path. The path parameter
// specifies a file path, and the extension parameter
// specifies a file extension (with a leading period, such as
// ".exe" or ".cs").
//
// The function returns a file path with the same root, directory, and base
// name parts as path, but with the file extension changed to
// the specified extension. If path is null, the function
// returns null. If path does not contain a file extension,
// the new file extension is appended to the path. If extension
// is null, any existing extension is removed from path.
[return: NotNullIfNotNull("path")]
public static string? ChangeExtension(string? path, string? extension)
{
if (path == null)
return null;
int subLength = path.Length;
if (subLength == 0)
return string.Empty;
for (int i = path.Length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == '.')
{
subLength = i;
break;
}
if (PathInternal.IsDirectorySeparator(ch))
{
break;
}
}
if (extension == null)
{
return path.Substring(0, subLength);
}
ReadOnlySpan<char> subpath = path.AsSpan(0, subLength);
#if MS_IO_REDIST
return extension.Length != 0 && extension[0] == '.' ?
StringExtensions.Concat(subpath, extension.AsSpan()) :
StringExtensions.Concat(subpath, ".".AsSpan(), extension.AsSpan());
#else
return extension.StartsWith('.') ?
string.Concat(subpath, extension) :
string.Concat(subpath, ".", extension);
#endif
}
/// <summary>
/// Returns the directory portion of a file path. This method effectively
/// removes the last segment of the given file path, i.e. it returns a
/// string consisting of all characters up to but not including the last
/// backslash ("\") in the file path. The returned value is null if the
/// specified path is null, empty, or a root (such as "\", "C:", or
/// "\\server\share").
/// </summary>
/// <remarks>
/// Directory separators are normalized in the returned string.
/// </remarks>
public static string? GetDirectoryName(string? path)
{
if (path == null || PathInternal.IsEffectivelyEmpty(path.AsSpan()))
return null;
int end = GetDirectoryNameOffset(path.AsSpan());
return end >= 0 ? PathInternal.NormalizeDirectorySeparators(path.Substring(0, end)) : null;
}
/// <summary>
/// Returns the directory portion of a file path. The returned value is empty
/// if the specified path is null, empty, or a root (such as "\", "C:", or
/// "\\server\share").
/// </summary>
/// <remarks>
/// Unlike the string overload, this method will not normalize directory separators.
/// </remarks>
public static ReadOnlySpan<char> GetDirectoryName(ReadOnlySpan<char> path)
{
if (PathInternal.IsEffectivelyEmpty(path))
return ReadOnlySpan<char>.Empty;
int end = GetDirectoryNameOffset(path);
return end >= 0 ? path.Slice(0, end) : ReadOnlySpan<char>.Empty;
}
internal static int GetDirectoryNameOffset(ReadOnlySpan<char> path)
{
int rootLength = PathInternal.GetRootLength(path);
int end = path.Length;
if (end <= rootLength)
return -1;
while (end > rootLength && !PathInternal.IsDirectorySeparator(path[--end])) ;
// Trim off any remaining separators (to deal with C:\foo\\bar)
while (end > rootLength && PathInternal.IsDirectorySeparator(path[end - 1]))
end--;
return end;
}
/// <summary>
/// Returns the extension of the given path. The returned value includes the period (".") character of the
/// extension except when you have a terminal period when you get string.Empty, such as ".exe" or ".cpp".
/// The returned value is null if the given path is null or empty if the given path does not include an
/// extension.
/// </summary>
[return: NotNullIfNotNull("path")]
public static string? GetExtension(string? path)
{
if (path == null)
return null;
return GetExtension(path.AsSpan()).ToString();
}
/// <summary>
/// Returns the extension of the given path.
/// </summary>
/// <remarks>
/// The returned value is an empty ReadOnlySpan if the given path does not include an extension.
/// </remarks>
public static ReadOnlySpan<char> GetExtension(ReadOnlySpan<char> path)
{
int length = path.Length;
for (int i = length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == '.')
{
if (i != length - 1)
return path.Slice(i, length - i);
else
return ReadOnlySpan<char>.Empty;
}
if (PathInternal.IsDirectorySeparator(ch))
break;
}
return ReadOnlySpan<char>.Empty;
}
/// <summary>
/// Returns the name and extension parts of the given path. The resulting string contains
/// the characters of path that follow the last separator in path. The resulting string is
/// null if path is null.
/// </summary>
[return: NotNullIfNotNull("path")]
public static string? GetFileName(string? path)
{
if (path == null)
return null;
ReadOnlySpan<char> result = GetFileName(path.AsSpan());
if (path.Length == result.Length)
return path;
return result.ToString();
}
/// <summary>
/// The returned ReadOnlySpan contains the characters of the path that follows the last separator in path.
/// </summary>
public static ReadOnlySpan<char> GetFileName(ReadOnlySpan<char> path)
{
int root = GetPathRoot(path).Length;
// We don't want to cut off "C:\file.txt:stream" (i.e. should be "file.txt:stream")
// but we *do* want "C:Foo" => "Foo". This necessitates checking for the root.
for (int i = path.Length; --i >= 0;)
{
if (i < root || PathInternal.IsDirectorySeparator(path[i]))
return path.Slice(i + 1, path.Length - i - 1);
}
return path;
}
[return: NotNullIfNotNull("path")]
public static string? GetFileNameWithoutExtension(string? path)
{
if (path == null)
return null;
ReadOnlySpan<char> result = GetFileNameWithoutExtension(path.AsSpan());
if (path.Length == result.Length)
return path;
return result.ToString();
}
/// <summary>
/// Returns the characters between the last separator and last (.) in the path.
/// </summary>
public static ReadOnlySpan<char> GetFileNameWithoutExtension(ReadOnlySpan<char> path)
{
ReadOnlySpan<char> fileName = GetFileName(path);
int lastPeriod = fileName.LastIndexOf('.');
return lastPeriod == -1 ?
fileName : // No extension was found
fileName.Slice(0, lastPeriod);
}
/// <summary>
/// Returns a cryptographically strong random 8.3 string that can be
/// used as either a folder name or a file name.
/// </summary>
public static unsafe string GetRandomFileName()
{
byte* pKey = stackalloc byte[KeyLength];
Interop.GetRandomBytes(pKey, KeyLength);
#if MS_IO_REDIST
return StringExtensions.Create(
#else
return string.Create(
#endif
12, (IntPtr)pKey, (span, key) => // 12 == 8 + 1 (for period) + 3
Populate83FileNameFromRandomBytes((byte*)key, KeyLength, span));
}
/// <summary>
/// Returns true if the path is fixed to a specific drive or UNC path. This method does no
/// validation of the path (URIs will be returned as relative as a result).
/// Returns false if the path specified is relative to the current drive or working directory.
/// </summary>
/// <remarks>
/// Handles paths that use the alternate directory separator. It is a frequent mistake to
/// assume that rooted paths <see cref="Path.IsPathRooted(string)"/> are not relative. This isn't the case.
/// "C:a" is drive relative- meaning that it will be resolved against the current directory
/// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
/// will not be used to modify the path).
/// </remarks>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="path"/> is null.
/// </exception>
public static bool IsPathFullyQualified(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
return IsPathFullyQualified(path.AsSpan());
}
public static bool IsPathFullyQualified(ReadOnlySpan<char> path)
{
return !PathInternal.IsPartiallyQualified(path);
}
/// <summary>
/// Tests if a path's file name includes a file extension. A trailing period
/// is not considered an extension.
/// </summary>
public static bool HasExtension([NotNullWhen(true)] string? path)
{
if (path != null)
{
return HasExtension(path.AsSpan());
}
return false;
}
public static bool HasExtension(ReadOnlySpan<char> path)
{
for (int i = path.Length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == '.')
{
return i != path.Length - 1;
}
if (PathInternal.IsDirectorySeparator(ch))
break;
}
return false;
}
public static string Combine(string path1, string path2)
{
if (path1 == null || path2 == null)
throw new ArgumentNullException((path1 == null) ? nameof(path1) : nameof(path2));
return CombineInternal(path1, path2);
}
public static string Combine(string path1, string path2, string path3)
{
if (path1 == null || path2 == null || path3 == null)
throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : nameof(path3));
return CombineInternal(path1, path2, path3);
}
public static string Combine(string path1, string path2, string path3, string path4)
{
if (path1 == null || path2 == null || path3 == null || path4 == null)
throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : (path3 == null) ? nameof(path3) : nameof(path4));
return CombineInternal(path1, path2, path3, path4);
}
public static string Combine(params string[] paths)
{
if (paths == null)
{
throw new ArgumentNullException(nameof(paths));
}
int maxSize = 0;
int firstComponent = 0;
// We have two passes, the first calculates how large a buffer to allocate and does some precondition
// checks on the paths passed in. The second actually does the combination.
for (int i = 0; i < paths.Length; i++)
{
if (paths[i] == null)
{
throw new ArgumentNullException(nameof(paths));
}
if (paths[i].Length == 0)
{
continue;
}
if (IsPathRooted(paths[i]))
{
firstComponent = i;
maxSize = paths[i].Length;
}
else
{
maxSize += paths[i].Length;
}
char ch = paths[i][paths[i].Length - 1];
if (!PathInternal.IsDirectorySeparator(ch))
maxSize++;
}
var builder = new ValueStringBuilder(stackalloc char[260]); // MaxShortPath on Windows
builder.EnsureCapacity(maxSize);
for (int i = firstComponent; i < paths.Length; i++)
{
if (paths[i].Length == 0)
{
continue;
}
if (builder.Length == 0)
{
builder.Append(paths[i]);
}
else
{
char ch = builder[builder.Length - 1];
if (!PathInternal.IsDirectorySeparator(ch))
{
builder.Append(PathInternal.DirectorySeparatorChar);
}
builder.Append(paths[i]);
}
}
return builder.ToString();
}
// Unlike Combine(), Join() methods do not consider rooting. They simply combine paths, ensuring that there
// is a directory separator between them.
public static string Join(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2)
{
if (path1.Length == 0)
return path2.ToString();
if (path2.Length == 0)
return path1.ToString();
return JoinInternal(path1, path2);
}
public static string Join(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, ReadOnlySpan<char> path3)
{
if (path1.Length == 0)
return Join(path2, path3);
if (path2.Length == 0)
return Join(path1, path3);
if (path3.Length == 0)
return Join(path1, path2);
return JoinInternal(path1, path2, path3);
}
public static string Join(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, ReadOnlySpan<char> path3, ReadOnlySpan<char> path4)
{
if (path1.Length == 0)
return Join(path2, path3, path4);
if (path2.Length == 0)
return Join(path1, path3, path4);
if (path3.Length == 0)
return Join(path1, path2, path4);
if (path4.Length == 0)
return Join(path1, path2, path3);
return JoinInternal(path1, path2, path3, path4);
}
public static string Join(string? path1, string? path2)
{
return Join(path1.AsSpan(), path2.AsSpan());
}
public static string Join(string? path1, string? path2, string? path3)
{
return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan());
}
public static string Join(string? path1, string? path2, string? path3, string? path4)
{
return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan(), path4.AsSpan());
}
public static string Join(params string?[] paths)
{
if (paths == null)
{
throw new ArgumentNullException(nameof(paths));
}
if (paths.Length == 0)
{
return string.Empty;
}
int maxSize = 0;
foreach (string? path in paths)
{
maxSize += path?.Length ?? 0;
}
maxSize += paths.Length - 1;
var builder = new ValueStringBuilder(stackalloc char[260]); // MaxShortPath on Windows
builder.EnsureCapacity(maxSize);
for (int i = 0; i < paths.Length; i++)
{
string? path = paths[i];
if (string.IsNullOrEmpty(path))
{
continue;
}
if (builder.Length == 0)
{
builder.Append(path);
}
else
{
if (!PathInternal.IsDirectorySeparator(builder[builder.Length - 1]) && !PathInternal.IsDirectorySeparator(path[0]))
{
builder.Append(PathInternal.DirectorySeparatorChar);
}
builder.Append(path);
}
}
return builder.ToString();
}
public static bool TryJoin(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, Span<char> destination, out int charsWritten)
{
charsWritten = 0;
if (path1.Length == 0 && path2.Length == 0)
return true;
if (path1.Length == 0 || path2.Length == 0)
{
ref ReadOnlySpan<char> pathToUse = ref path1.Length == 0 ? ref path2 : ref path1;
if (destination.Length < pathToUse.Length)
{
return false;
}
pathToUse.CopyTo(destination);
charsWritten = pathToUse.Length;
return true;
}
bool needsSeparator = !(EndsInDirectorySeparator(path1) || PathInternal.StartsWithDirectorySeparator(path2));
int charsNeeded = path1.Length + path2.Length + (needsSeparator ? 1 : 0);
if (destination.Length < charsNeeded)
return false;
path1.CopyTo(destination);
if (needsSeparator)
destination[path1.Length] = DirectorySeparatorChar;
path2.CopyTo(destination.Slice(path1.Length + (needsSeparator ? 1 : 0)));
charsWritten = charsNeeded;
return true;
}
public static bool TryJoin(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, ReadOnlySpan<char> path3, Span<char> destination, out int charsWritten)
{
charsWritten = 0;
if (path1.Length == 0 && path2.Length == 0 && path3.Length == 0)
return true;
if (path1.Length == 0)
return TryJoin(path2, path3, destination, out charsWritten);
if (path2.Length == 0)
return TryJoin(path1, path3, destination, out charsWritten);
if (path3.Length == 0)
return TryJoin(path1, path2, destination, out charsWritten);
int neededSeparators = EndsInDirectorySeparator(path1) || PathInternal.StartsWithDirectorySeparator(path2) ? 0 : 1;
bool needsSecondSeparator = !(EndsInDirectorySeparator(path2) || PathInternal.StartsWithDirectorySeparator(path3));
if (needsSecondSeparator)
neededSeparators++;
int charsNeeded = path1.Length + path2.Length + path3.Length + neededSeparators;
if (destination.Length < charsNeeded)
return false;
bool result = TryJoin(path1, path2, destination, out charsWritten);
Debug.Assert(result, "should never fail joining first two paths");
if (needsSecondSeparator)
destination[charsWritten++] = DirectorySeparatorChar;
path3.CopyTo(destination.Slice(charsWritten));
charsWritten += path3.Length;
return true;
}
private static string CombineInternal(string first, string second)
{
if (string.IsNullOrEmpty(first))
return second;
if (string.IsNullOrEmpty(second))
return first;
if (IsPathRooted(second.AsSpan()))
return second;
return JoinInternal(first.AsSpan(), second.AsSpan());
}
private static string CombineInternal(string first, string second, string third)
{
if (string.IsNullOrEmpty(first))
return CombineInternal(second, third);
if (string.IsNullOrEmpty(second))
return CombineInternal(first, third);
if (string.IsNullOrEmpty(third))
return CombineInternal(first, second);
if (IsPathRooted(third.AsSpan()))
return third;
if (IsPathRooted(second.AsSpan()))
return CombineInternal(second, third);
return JoinInternal(first.AsSpan(), second.AsSpan(), third.AsSpan());
}
private static string CombineInternal(string first, string second, string third, string fourth)
{
if (string.IsNullOrEmpty(first))
return CombineInternal(second, third, fourth);
if (string.IsNullOrEmpty(second))
return CombineInternal(first, third, fourth);
if (string.IsNullOrEmpty(third))
return CombineInternal(first, second, fourth);
if (string.IsNullOrEmpty(fourth))
return CombineInternal(first, second, third);
if (IsPathRooted(fourth.AsSpan()))
return fourth;
if (IsPathRooted(third.AsSpan()))
return CombineInternal(third, fourth);
if (IsPathRooted(second.AsSpan()))
return CombineInternal(second, third, fourth);
return JoinInternal(first.AsSpan(), second.AsSpan(), third.AsSpan(), fourth.AsSpan());
}
private static unsafe string JoinInternal(ReadOnlySpan<char> first, ReadOnlySpan<char> second)
{
Debug.Assert(first.Length > 0 && second.Length > 0, "should have dealt with empty paths");
bool hasSeparator = PathInternal.IsDirectorySeparator(first[first.Length - 1])
|| PathInternal.IsDirectorySeparator(second[0]);
#if !MS_IO_REDIST
return hasSeparator ?
string.Concat(first, second) :
string.Concat(first, PathInternal.DirectorySeparatorCharAsString, second);
#else
fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second))
{
return StringExtensions.Create(
first.Length + second.Length + (hasSeparator ? 0 : 1),
(First: (IntPtr)f, FirstLength: first.Length, Second: (IntPtr)s, SecondLength: second.Length),
static (destination, state) =>
{
new Span<char>((char*)state.First, state.FirstLength).CopyTo(destination);
if (destination.Length != (state.FirstLength + state.SecondLength))
destination[state.FirstLength] = PathInternal.DirectorySeparatorChar;
new Span<char>((char*)state.Second, state.SecondLength).CopyTo(destination.Slice(destination.Length - state.SecondLength));
});
}
#endif
}
private unsafe readonly struct Join3Payload
{
public Join3Payload(char* first, int firstLength, char* second, int secondLength, char* third, int thirdLength, byte separators)
{
First = first;
FirstLength = firstLength;
Second = second;
SecondLength = secondLength;
Third = third;
ThirdLength = thirdLength;
Separators = separators;
}
public readonly char* First;
public readonly int FirstLength;
public readonly char* Second;
public readonly int SecondLength;
public readonly char* Third;
public readonly int ThirdLength;
public readonly byte Separators;
}
private static unsafe string JoinInternal(ReadOnlySpan<char> first, ReadOnlySpan<char> second, ReadOnlySpan<char> third)
{
Debug.Assert(first.Length > 0 && second.Length > 0 && third.Length > 0, "should have dealt with empty paths");
byte firstNeedsSeparator = PathInternal.IsDirectorySeparator(first[first.Length - 1])
|| PathInternal.IsDirectorySeparator(second[0]) ? (byte)0 : (byte)1;
byte secondNeedsSeparator = PathInternal.IsDirectorySeparator(second[second.Length - 1])
|| PathInternal.IsDirectorySeparator(third[0]) ? (byte)0 : (byte)1;
fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second), t = &MemoryMarshal.GetReference(third))
{
var payload = new Join3Payload(
f, first.Length, s, second.Length, t, third.Length,
(byte)(firstNeedsSeparator | secondNeedsSeparator << 1));
#if MS_IO_REDIST
return StringExtensions.Create(
#else
return string.Create(
#endif
first.Length + second.Length + third.Length + firstNeedsSeparator + secondNeedsSeparator,
(IntPtr)(&payload),
static (destination, statePtr) =>
{
ref Join3Payload state = ref *(Join3Payload*)statePtr;
new Span<char>(state.First, state.FirstLength).CopyTo(destination);
if ((state.Separators & 0b1) != 0)
destination[state.FirstLength] = PathInternal.DirectorySeparatorChar;
new Span<char>(state.Second, state.SecondLength).CopyTo(destination.Slice(state.FirstLength + (state.Separators & 0b1)));
if ((state.Separators & 0b10) != 0)
destination[destination.Length - state.ThirdLength - 1] = PathInternal.DirectorySeparatorChar;
new Span<char>(state.Third, state.ThirdLength).CopyTo(destination.Slice(destination.Length - state.ThirdLength));
});
}
}
private unsafe readonly struct Join4Payload
{
public Join4Payload(char* first, int firstLength, char* second, int secondLength, char* third, int thirdLength, char* fourth, int fourthLength, byte separators)
{
First = first;
FirstLength = firstLength;
Second = second;
SecondLength = secondLength;
Third = third;
ThirdLength = thirdLength;
Fourth = fourth;
FourthLength = fourthLength;
Separators = separators;
}
public readonly char* First;
public readonly int FirstLength;
public readonly char* Second;
public readonly int SecondLength;
public readonly char* Third;
public readonly int ThirdLength;
public readonly char* Fourth;
public readonly int FourthLength;
public readonly byte Separators;
}
private static unsafe string JoinInternal(ReadOnlySpan<char> first, ReadOnlySpan<char> second, ReadOnlySpan<char> third, ReadOnlySpan<char> fourth)
{
Debug.Assert(first.Length > 0 && second.Length > 0 && third.Length > 0 && fourth.Length > 0, "should have dealt with empty paths");
byte firstNeedsSeparator = PathInternal.IsDirectorySeparator(first[first.Length - 1])
|| PathInternal.IsDirectorySeparator(second[0]) ? (byte)0 : (byte)1;
byte secondNeedsSeparator = PathInternal.IsDirectorySeparator(second[second.Length - 1])
|| PathInternal.IsDirectorySeparator(third[0]) ? (byte)0 : (byte)1;
byte thirdNeedsSeparator = PathInternal.IsDirectorySeparator(third[third.Length - 1])
|| PathInternal.IsDirectorySeparator(fourth[0]) ? (byte)0 : (byte)1;
fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second), t = &MemoryMarshal.GetReference(third), u = &MemoryMarshal.GetReference(fourth))
{
var payload = new Join4Payload(
f, first.Length, s, second.Length, t, third.Length, u, fourth.Length,
(byte)(firstNeedsSeparator | secondNeedsSeparator << 1 | thirdNeedsSeparator << 2));
#if MS_IO_REDIST
return StringExtensions.Create(
#else
return string.Create(
#endif
first.Length + second.Length + third.Length + fourth.Length + firstNeedsSeparator + secondNeedsSeparator + thirdNeedsSeparator,
(IntPtr)(&payload),
static (destination, statePtr) =>
{
ref Join4Payload state = ref *(Join4Payload*)statePtr;
new Span<char>(state.First, state.FirstLength).CopyTo(destination);
int insertionPoint = state.FirstLength;
if ((state.Separators & 0b1) != 0)
destination[insertionPoint++] = PathInternal.DirectorySeparatorChar;
new Span<char>(state.Second, state.SecondLength).CopyTo(destination.Slice(insertionPoint));
insertionPoint += state.SecondLength;
if ((state.Separators & 0b10) != 0)
destination[insertionPoint++] = PathInternal.DirectorySeparatorChar;
new Span<char>(state.Third, state.ThirdLength).CopyTo(destination.Slice(insertionPoint));
insertionPoint += state.ThirdLength;
if ((state.Separators & 0b100) != 0)
destination[insertionPoint++] = PathInternal.DirectorySeparatorChar;
new Span<char>(state.Fourth, state.FourthLength).CopyTo(destination.Slice(insertionPoint));
});
}
}
private static ReadOnlySpan<byte> Base32Char => new byte[32] { // uses C# compiler's optimization for static byte[] data
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h',
(byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p',
(byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x',
(byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5' };
private static unsafe void Populate83FileNameFromRandomBytes(byte* bytes, int byteCount, Span<char> chars)
{
// This method requires bytes of length 8 and chars of length 12.
Debug.Assert(bytes != null);
Debug.Assert(byteCount == 8, $"Unexpected {nameof(byteCount)}");
Debug.Assert(chars.Length == 12, $"Unexpected {nameof(chars)}.Length");
byte b0 = bytes[0];
byte b1 = bytes[1];
byte b2 = bytes[2];
byte b3 = bytes[3];
byte b4 = bytes[4];
// write to chars[11] first in order to eliminate redundant bounds checks
chars[11] = (char)Base32Char[bytes[7] & 0x1F];
// Consume the 5 Least significant bits of the first 5 bytes
chars[0] = (char)Base32Char[b0 & 0x1F];
chars[1] = (char)Base32Char[b1 & 0x1F];
chars[2] = (char)Base32Char[b2 & 0x1F];
chars[3] = (char)Base32Char[b3 & 0x1F];
chars[4] = (char)Base32Char[b4 & 0x1F];
// Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4
chars[5] = (char)Base32Char[
((b0 & 0xE0) >> 5) |
((b3 & 0x60) >> 2)];
chars[6] = (char)Base32Char[
((b1 & 0xE0) >> 5) |
((b4 & 0x60) >> 2)];
// Consume 3 MSB bits of b2, 1 MSB bit of b3, b4
b2 >>= 5;
Debug.Assert((b2 & 0xF8) == 0, "Unexpected set bits");
if ((b3 & 0x80) != 0)
b2 |= 0x08;
if ((b4 & 0x80) != 0)
b2 |= 0x10;
chars[7] = (char)Base32Char[b2];
// Set the file extension separator
chars[8] = '.';
// Consume the 5 Least significant bits of the remaining 3 bytes
chars[9] = (char)Base32Char[bytes[5] & 0x1F];
chars[10] = (char)Base32Char[bytes[6] & 0x1F];
}
/// <summary>
/// Create a relative path from one path to another. Paths will be resolved before calculating the difference.
/// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix).
/// </summary>
/// <param name="relativeTo">The source path the output should be relative to. This path is always considered to be a directory.</param>
/// <param name="path">The destination path.</param>
/// <returns>The relative path or <paramref name="path"/> if the paths don't share the same root.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="relativeTo"/> or <paramref name="path"/> is <c>null</c> or an empty string.</exception>
public static string GetRelativePath(string relativeTo, string path)
{
return GetRelativePath(relativeTo, path, PathInternal.StringComparison);
}
private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType)
{
if (relativeTo == null)
throw new ArgumentNullException(nameof(relativeTo));
if (PathInternal.IsEffectivelyEmpty(relativeTo.AsSpan()))
throw new ArgumentException(SR.Arg_PathEmpty, nameof(relativeTo));
if (path == null)
throw new ArgumentNullException(nameof(path));
if (PathInternal.IsEffectivelyEmpty(path.AsSpan()))
throw new ArgumentException(SR.Arg_PathEmpty, nameof(path));
Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase);
relativeTo = GetFullPath(relativeTo);
path = GetFullPath(path);
// Need to check if the roots are different- if they are we need to return the "to" path.
if (!PathInternal.AreRootsEqual(relativeTo, path, comparisonType))
return path;
int commonLength = PathInternal.GetCommonPathLength(relativeTo, path, ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase);
// If there is nothing in common they can't share the same root, return the "to" path as is.
if (commonLength == 0)
return path;
// Trailing separators aren't significant for comparison
int relativeToLength = relativeTo.Length;
if (EndsInDirectorySeparator(relativeTo.AsSpan()))
relativeToLength--;
bool pathEndsInSeparator = EndsInDirectorySeparator(path.AsSpan());
int pathLength = path.Length;
if (pathEndsInSeparator)
pathLength--;
// If we have effectively the same path, return "."
if (relativeToLength == pathLength && commonLength >= relativeToLength) return ".";
// We have the same root, we need to calculate the difference now using the
// common Length and Segment count past the length.
//
// Some examples:
//
// C:\Foo C:\Bar L3, S1 -> ..\Bar
// C:\Foo C:\Foo\Bar L6, S0 -> Bar
// C:\Foo\Bar C:\Bar\Bar L3, S2 -> ..\..\Bar\Bar
// C:\Foo\Foo C:\Foo\Bar L7, S1 -> ..\Bar
var sb = new ValueStringBuilder(stackalloc char[260]);
sb.EnsureCapacity(Math.Max(relativeTo.Length, path.Length));
// Add parent segments for segments past the common on the "from" path
if (commonLength < relativeToLength)
{
sb.Append("..");
for (int i = commonLength + 1; i < relativeToLength; i++)
{
if (PathInternal.IsDirectorySeparator(relativeTo[i]))
{
sb.Append(DirectorySeparatorChar);
sb.Append("..");
}
}
}
else if (PathInternal.IsDirectorySeparator(path[commonLength]))
{
// No parent segments and we need to eat the initial separator
// (C:\Foo C:\Foo\Bar case)
commonLength++;
}
// Now add the rest of the "to" path, adding back the trailing separator
int differenceLength = pathLength - commonLength;
if (pathEndsInSeparator)
differenceLength++;
if (differenceLength > 0)
{
if (sb.Length > 0)
{
sb.Append(DirectorySeparatorChar);
}
sb.Append(path.AsSpan(commonLength, differenceLength));
}
return sb.ToString();
}
/// <summary>
/// Trims one trailing directory separator beyond the root of the path.
/// </summary>
public static string TrimEndingDirectorySeparator(string path) => PathInternal.TrimEndingDirectorySeparator(path);
/// <summary>
/// Trims one trailing directory separator beyond the root of the path.
/// </summary>
public static ReadOnlySpan<char> TrimEndingDirectorySeparator(ReadOnlySpan<char> path) => PathInternal.TrimEndingDirectorySeparator(path);
/// <summary>
/// Returns true if the path ends in a directory separator.
/// </summary>
public static bool EndsInDirectorySeparator(ReadOnlySpan<char> path) => PathInternal.EndsInDirectorySeparator(path);
/// <summary>
/// Returns true if the path ends in a directory separator.
/// </summary>
public static bool EndsInDirectorySeparator(string path) => PathInternal.EndsInDirectorySeparator(path);
}
}
| 41.249745 | 186 | 0.555157 | [
"MIT"
] | 3DCloud/runtime | src/libraries/System.Private.CoreLib/src/System/IO/Path.cs | 40,466 | C# |
using System;
namespace ADFSEmailMFA
{
class PINGenerator
{
public static string EncryptedPIN = GetEncryptedPIN();
public static string DecryptedPIN = GetDecryptedPIN();
private static string GetEncryptedPIN()
{
string EncryptedText = cryptoHelper.AESThenHMAC.SimpleEncryptWithPassword(GetPin, EmailAuthenticationProvider.AuthProviderSettings.pinEncryptionKey);
return EncryptedText;
}
private static string GetDecryptedPIN()
{
string DecryptedText = cryptoHelper.AESThenHMAC.SimpleDecryptWithPassword(EncryptedPIN, EmailAuthenticationProvider.AuthProviderSettings.pinEncryptionKey);
return DecryptedText;
}
private static string GetPin
{
get
{
Random Random = new Random();
string RandomPinNumber = Random.Next(100000, 999999).ToString();
return RandomPinNumber;
}
}
}
}
| 30.575758 | 167 | 0.638256 | [
"MIT"
] | meowingtons/ADFSMFA | ADFSEmailMFA/PINGenerator.cs | 1,011 | C# |
// Copyright (c) FCChan. All rights reserved.
//
// Licensed under the MIT license.
namespace FC.Manager.Server.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord.WebSocket;
using FC.Bot.Services;
using FC.Manager.Server.RPC;
public class GuildService : ServiceBase
{
[RPC]
public bool IsInGuild(ulong guildId)
{
SocketGuild guild = DiscordService.DiscordClient.GetGuild(guildId);
return guild != null;
}
[GuildRpc]
public List<Channel> GetChannels(ulong guildId)
{
SocketGuild guild = DiscordService.DiscordClient.GetGuild(guildId);
if (guild == null)
throw new Exception("Unable to access guild");
List<Channel> results = new List<Channel>();
foreach (SocketGuildChannel guildChannel in guild.Channels)
{
Channel.Types type = Channel.Types.Unknown;
if (guildChannel is SocketTextChannel)
type = Channel.Types.Text;
if (guildChannel is SocketVoiceChannel)
type = Channel.Types.Voice;
results.Add(new Channel(guildChannel.Id, guildChannel.Name, type));
}
return results;
}
[GuildRpc]
public List<Role> GetRoles(ulong guildId)
{
SocketGuild guild = DiscordService.DiscordClient.GetGuild(guildId);
if (guild == null)
throw new Exception("Unable to access guild");
List<Role> results = new List<Role>();
foreach (SocketRole guildRole in guild.Roles)
{
results.Add(new Role(guildRole.Id, guildRole.Name));
}
return results;
}
[GuildRpc]
public List<GuildUser> GetGuildUsers(ulong guildId)
{
SocketGuild guild = DiscordService.DiscordClient.GetGuild(guildId);
if (guild == null)
throw new Exception("Unable to access guild");
// Get the guild users
IReadOnlyCollection<Discord.IGuildUser> guildUsers = guild.GetUsersAsync().ToEnumerable().FirstOrDefault();
// Get database users
List<User> users = UserService.GetAllUsersForGuild(guildId).Result;
List<GuildUser> results = new List<GuildUser>();
foreach (User guildUser in users)
{
string username = "Unknown";
Discord.IGuildUser user = guildUsers.FirstOrDefault(x => x.Id == guildUser.DiscordUserId);
if (user != null)
username = user.Nickname ?? user.Username;
results.Add(new GuildUser(guildUser.DiscordUserId, username, guildUser.TotalKupoNutsCurrent, guildUser.TotalXPCurrent, guildUser.Level, guildUser.Reputation));
}
return results;
}
[GuildRpc]
public async Task<GuildSettings> GetSettings(ulong guildId)
{
return await SettingsService.GetSettings<GuildSettings>(guildId);
}
[GuildRpc]
public async Task SetSettings(ulong guildId, GuildSettings settings)
{
settings.Guild = guildId;
await SettingsService.SaveSettings(settings);
}
[GuildRpc]
public async Task<List<string>> GetTimezonesFromSettings(ulong guildId)
{
GuildSettings settings = await SettingsService.GetSettings<GuildSettings>(guildId);
return settings.TimeZone;
}
[GuildRpc]
public void ResetGuildUserNuts(ulong guildId)
{
// Get database users
List<User> users = UserService.GetAllUsersForGuild(guildId).Result;
foreach (User u in users)
u.ClearTotalKupoNuts();
return;
}
}
}
| 25.527559 | 163 | 0.72116 | [
"MIT"
] | twobe7/KupoNutsBot | FC.Manager.Server/Services/GuildService.cs | 3,244 | C# |
namespace Melanchall.DryWetMidi.MusicTheory
{
/// <summary>
/// Represents a chord's quality.
/// </summary>
public enum ChordQuality
{
/// <summary>
/// Major chord.
/// </summary>
Major,
/// <summary>
/// Minor chord.
/// </summary>
Minor,
/// <summary>
/// Augmented chord.
/// </summary>
Augmented,
/// <summary>
/// Diminished chord.
/// </summary>
Diminished
}
}
| 18.103448 | 44 | 0.445714 | [
"MIT"
] | EnableIrelandAT/Coimbra | ProjectCoimbra.UWP/Melanchall.DryWetMidi.UWP/MusicTheory/Chord/ChordQuality.cs | 527 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the globalaccelerator-2018-08-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GlobalAccelerator.Model
{
/// <summary>
/// This is the response object from the AdvertiseByoipCidr operation.
/// </summary>
public partial class AdvertiseByoipCidrResponse : AmazonWebServiceResponse
{
private ByoipCidr _byoipCidr;
/// <summary>
/// Gets and sets the property ByoipCidr.
/// <para>
/// Information about the address range.
/// </para>
/// </summary>
public ByoipCidr ByoipCidr
{
get { return this._byoipCidr; }
set { this._byoipCidr = value; }
}
// Check to see if ByoipCidr property is set
internal bool IsSetByoipCidr()
{
return this._byoipCidr != null;
}
}
} | 29.350877 | 115 | 0.665272 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/GlobalAccelerator/Generated/Model/AdvertiseByoipCidrResponse.cs | 1,673 | C# |
//-----------------------------------------------------------------------
// <copyright file="DistributedPubSubMessageSerializer.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.IO.Compression;
using System.Linq;
using Akka.Actor;
using Akka.Cluster.PubSub.Serializers.Proto;
using Akka.Cluster.Tools.PublishSubscribe.Internal;
using Akka.Serialization;
using Google.ProtocolBuffers;
using Address = Akka.Cluster.PubSub.Serializers.Proto.Address;
using Delta = Akka.Cluster.Tools.PublishSubscribe.Internal.Delta;
using Status = Akka.Cluster.PubSub.Serializers.Proto.Status;
namespace Akka.Cluster.Tools.PublishSubscribe.Serialization
{
/**
* Protobuf serializer of DistributedPubSubMediator messages.
*/
/// <summary>
/// TBD
/// </summary>
public class DistributedPubSubMessageSerializer : SerializerWithStringManifest
{
/// <summary>
/// TBD
/// </summary>
public const int BufferSize = 1024 * 4;
/// <summary>
/// TBD
/// </summary>
public const string StatusManifest = "A";
/// <summary>
/// TBD
/// </summary>
public const string DeltaManifest = "B";
/// <summary>
/// TBD
/// </summary>
public const string SendManifest = "C";
/// <summary>
/// TBD
/// </summary>
public const string SendToAllManifest = "D";
/// <summary>
/// TBD
/// </summary>
public const string PublishManifest = "E";
private readonly IDictionary<string, Func<byte[], object>> _fromBinaryMap;
private readonly int _identifier;
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
public DistributedPubSubMessageSerializer(ExtendedActorSystem system) : base(system)
{
_identifier = SerializerIdentifierHelper.GetSerializerIdentifierFromConfig(this.GetType(), system);
_fromBinaryMap = new Dictionary<string, Func<byte[], object>>
{
{StatusManifest, StatusFromBinary},
{DeltaManifest, DeltaFromBinary},
{SendManifest, SendFromBinary},
{SendToAllManifest, SendToAllFromBinary},
{PublishManifest, PublishFromBinary}
};
}
/// <summary>
/// TBD
/// </summary>
public override int Identifier { get { return _identifier; } }
/// <summary>
/// TBD
/// </summary>
/// <param name="obj">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public override byte[] ToBinary(object obj)
{
if (obj is Internal.Status) return Compress(StatusToProto(obj as Internal.Status));
if (obj is Internal.Delta) return Compress(DeltaToProto(obj as Internal.Delta));
if (obj is Send) return SendToProto(obj as Send).ToByteArray();
if (obj is SendToAll) return SendToAllToProto(obj as SendToAll).ToByteArray();
if (obj is Publish) return PublishToProto(obj as Publish).ToByteArray();
throw new ArgumentException(string.Format("Can't serialize object of type {0} with {1}", obj.GetType(), GetType()));
}
/// <summary>
/// TBD
/// </summary>
/// <param name="bytes">TBD</param>
/// <param name="manifestString">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public override object FromBinary(byte[] bytes, string manifestString)
{
Func<byte[], object> deserializer;
if (_fromBinaryMap.TryGetValue(manifestString, out deserializer))
{
return deserializer(bytes);
}
throw new ArgumentException(string.Format("Unimplemented deserialization of message with manifest [{0}] in serializer {1}", manifestString, GetType()));
}
/// <summary>
/// TBD
/// </summary>
/// <param name="o">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public override string Manifest(object o)
{
if (o is Internal.Status) return StatusManifest;
if (o is Internal.Delta) return DeltaManifest;
if (o is Send) return SendManifest;
if (o is SendToAll) return SendToAllManifest;
if (o is Publish) return PublishManifest;
throw new ArgumentException(string.Format("Serializer {0} cannot serialize message of type {1}", this.GetType(), o.GetType()));
}
private byte[] Compress(IMessageLite message)
{
using (var bos = new MemoryStream(BufferSize))
using (var gzipStream = new GZipStream(bos, CompressionMode.Compress))
{
message.WriteTo(gzipStream);
gzipStream.Dispose();
return bos.ToArray();
}
}
private byte[] Decompress(byte[] bytes)
{
using (var input = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress))
using (var output = new MemoryStream())
{
var buffer = new byte[BufferSize];
var bytesRead = input.Read(buffer, 0, BufferSize);
while (bytesRead > 0)
{
output.Write(buffer, 0, bytesRead);
bytesRead = input.Read(buffer, 0, BufferSize);
}
return output.ToArray();
}
}
private Address.Builder AddressToProto(Actor.Address address)
{
if (string.IsNullOrEmpty(address.Host) || !address.Port.HasValue)
throw new ArgumentException(string.Format("Address [{0}] could not be serialized: host or port missing", address));
return Address.CreateBuilder()
.SetSystem(address.System)
.SetHostname(address.Host)
.SetPort((uint)address.Port.Value)
.SetProtocol(address.Protocol);
}
private Actor.Address AddressFromProto(Address address)
{
return new Actor.Address(address.Protocol, address.System, address.Hostname, (int)address.Port);
}
private Akka.Cluster.PubSub.Serializers.Proto.Delta DeltaToProto(Delta delta)
{
var buckets = delta.Buckets.Select(b =>
{
var entries = b.Content.Select(c =>
{
var bb = Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.CreateBuilder()
.SetKey(c.Key).SetVersion(c.Value.Version);
if (c.Value.Ref != null)
{
bb.SetRef(Akka.Serialization.Serialization.SerializedActorPath(c.Value.Ref));
}
return bb.Build();
});
return Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.CreateBuilder()
.SetOwner(AddressToProto(b.Owner))
.SetVersion(b.Version)
.AddRangeContent(entries)
.Build();
}).ToArray();
return Akka.Cluster.PubSub.Serializers.Proto.Delta.CreateBuilder()
.AddRangeBuckets(buckets)
.Build();
}
private Delta DeltaFromBinary(byte[] binary)
{
return DeltaFromProto(Akka.Cluster.PubSub.Serializers.Proto.Delta.ParseFrom(Decompress(binary)));
}
private Delta DeltaFromProto(Akka.Cluster.PubSub.Serializers.Proto.Delta delta)
{
return new Delta(delta.BucketsList.Select(b =>
{
var content = b.ContentList.Aggregate(ImmutableDictionary<string, ValueHolder>.Empty, (map, entry) =>
map.Add(entry.Key, new ValueHolder(entry.Version, entry.HasRef ? ResolveActorRef(entry.Ref) : null)));
return new Bucket(AddressFromProto(b.Owner), b.Version, content);
}).ToArray());
}
private IActorRef ResolveActorRef(string path)
{
return system.Provider.ResolveActorRef(path);
}
private Status StatusToProto(Internal.Status status)
{
var versions = status.Versions.Select(v =>
Status.Types.Version.CreateBuilder()
.SetAddress(AddressToProto(v.Key))
.SetTimestamp(v.Value)
.Build())
.ToArray();
return Status.CreateBuilder()
.AddRangeVersions(versions)
.SetReplyToStatus(status.IsReplyToStatus)
.Build();
}
private Internal.Status StatusFromBinary(byte[] binary)
{
return StatusFromProto(Status.ParseFrom(Decompress(binary)));
}
private Internal.Status StatusFromProto(Status status)
{
var isReplyToStatus = status.HasReplyToStatus ? status.ReplyToStatus : false;
return new Internal.Status(status.VersionsList
.ToDictionary(
v => AddressFromProto(v.Address),
v => v.Timestamp), isReplyToStatus);
}
private Akka.Cluster.PubSub.Serializers.Proto.Send SendToProto(Send send)
{
return Akka.Cluster.PubSub.Serializers.Proto.Send.CreateBuilder()
.SetPath(send.Path)
.SetLocalAffinity(send.LocalAffinity)
.SetPayload(PayloadToProto(send.Message))
.Build();
}
private Send SendFromBinary(byte[] binary)
{
return SendFromProto(Akka.Cluster.PubSub.Serializers.Proto.Send.ParseFrom(binary));
}
private Send SendFromProto(Akka.Cluster.PubSub.Serializers.Proto.Send send)
{
return new Send(send.Path, PayloadFromProto(send.Payload), send.LocalAffinity);
}
private Akka.Cluster.PubSub.Serializers.Proto.SendToAll SendToAllToProto(SendToAll sendToAll)
{
return Akka.Cluster.PubSub.Serializers.Proto.SendToAll.CreateBuilder()
.SetPath(sendToAll.Path)
.SetAllButSelf(sendToAll.ExcludeSelf)
.SetPayload(PayloadToProto(sendToAll.Message))
.Build();
}
private SendToAll SendToAllFromBinary(byte[] binary)
{
return SendToAllFromProto(Akka.Cluster.PubSub.Serializers.Proto.SendToAll.ParseFrom(binary));
}
private SendToAll SendToAllFromProto(Akka.Cluster.PubSub.Serializers.Proto.SendToAll send)
{
return new SendToAll(send.Path, PayloadFromProto(send.Payload), send.AllButSelf);
}
private Akka.Cluster.PubSub.Serializers.Proto.Publish PublishToProto(Publish publish)
{
return Akka.Cluster.PubSub.Serializers.Proto.Publish.CreateBuilder()
.SetTopic(publish.Topic)
.SetPayload(PayloadToProto(publish.Message))
.Build();
}
private Publish PublishFromBinary(byte[] binary)
{
return PublishFromProto(Akka.Cluster.PubSub.Serializers.Proto.Publish.ParseFrom(binary));
}
private Publish PublishFromProto(Akka.Cluster.PubSub.Serializers.Proto.Publish publish)
{
return new Publish(publish.Topic, PayloadFromProto(publish.Payload));
}
private Payload PayloadToProto(object message)
{
var serializer = system.Serialization.FindSerializerFor(message);
var builder = Payload.CreateBuilder()
.SetEnclosedMessage(ByteString.CopyFrom(serializer.ToBinary(message)))
.SetSerializerId(serializer.Identifier);
SerializerWithStringManifest serializerWithManifest;
if ((serializerWithManifest = serializer as SerializerWithStringManifest) != null)
{
var manifest = serializerWithManifest.Manifest(message);
if (!string.IsNullOrEmpty(manifest))
builder.SetMessageManifest(ByteString.CopyFromUtf8(manifest));
}
else
{
if (serializer.IncludeManifest)
builder.SetMessageManifest(ByteString.CopyFromUtf8(TypeQualifiedNameForManifest(message.GetType())));
}
return builder.Build();
}
private object PayloadFromProto(Payload payload)
{
var type = payload.HasMessageManifest ? Type.GetType(payload.MessageManifest.ToStringUtf8()) : null;
return system.Serialization.Deserialize(
payload.EnclosedMessage.ToByteArray(),
payload.SerializerId,
type);
}
}
} | 38.869186 | 164 | 0.58223 | [
"Apache-2.0"
] | corefan/akka.net | src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Serialization/DistributedPubSubMessageSerializer.cs | 13,373 | 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.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class OverloadResolution
{
public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// We can do a table lookup for well-known problems in overload resolution.
BinaryOperatorOverloadResolution_EasyOut(kind, left, right, result);
if (result.Results.Count > 0)
{
return;
}
BinaryOperatorOverloadResolution_NoEasyOut(kind, left, right, result, ref useSiteDiagnostics);
}
internal void BinaryOperatorOverloadResolution_EasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(result.Results.Count == 0);
// SPEC: An operation of the form x&&y or x||y is processed by applying overload resolution
// SPEC: as if the operation was written x&y or x|y.
// SPEC VIOLATION: For compatibility with Dev11, do not apply this rule to built-in conversions.
BinaryOperatorKind underlyingKind = kind & ~BinaryOperatorKind.Logical;
BinaryOperatorEasyOut(underlyingKind, left, right, result);
}
internal void BinaryOperatorOverloadResolution_NoEasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(result.Results.Count == 0);
// The following is a slight rewording of the specification to emphasize that not all
// operands of a binary operation need to have a type.
// SPEC: An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
// SPEC: The set of candidate user-defined operators provided by the types (if any) of x and y for the
// SPEC operation operator op(x, y) is determined.
TypeSymbol leftOperatorSourceOpt = left.Type?.StrippedType();
TypeSymbol rightOperatorSourceOpt = right.Type?.StrippedType();
bool leftSourceIsInterface = leftOperatorSourceOpt?.IsInterfaceType() == true;
bool rightSourceIsInterface = rightOperatorSourceOpt?.IsInterfaceType() == true;
// The following is a slight rewording of the specification to emphasize that not all
// operands of a binary operation need to have a type.
// TODO (tomat): The spec needs to be updated to use identity conversion instead of type equality.
// Spec 7.3.4 Binary operator overload resolution:
// An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
// The set of candidate user-defined operators provided by the types (if any) of x and y for the
// operation operator op(x, y) is determined. The set consists of the union of the candidate operators
// provided by the type of x (if any) and the candidate operators provided by the type of y (if any),
// each determined using the rules of 7.3.5. Candidate operators only occur in the combined set once.
// From https://github.com/dotnet/csharplang/blob/master/meetings/2017/LDM-2017-06-27.md:
// - We only even look for operator implementations in interfaces if one of the operands has a type that is
// an interface or a type parameter with a non-empty effective base interface list.
// - We should look at operators from classes first, in order to avoid breaking changes.
// Only if there are no applicable user-defined operators from classes will we look in interfaces.
// If there aren't any there either, we go to built-ins.
// - If we find an applicable candidate in an interface, that candidate shadows all applicable operators in
// base interfaces: we stop looking.
bool hadApplicableCandidates = false;
// In order to preserve backward compatibility, at first we ignore interface sources.
if ((object)leftOperatorSourceOpt != null && !leftSourceIsInterface)
{
hadApplicableCandidates = GetUserDefinedOperators(kind, leftOperatorSourceOpt, left, right, result.Results, ref useSiteDiagnostics);
if (!hadApplicableCandidates)
{
result.Results.Clear();
}
}
if ((object)rightOperatorSourceOpt != null && !rightSourceIsInterface && !rightOperatorSourceOpt.Equals(leftOperatorSourceOpt))
{
var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
if (GetUserDefinedOperators(kind, rightOperatorSourceOpt, left, right, rightOperators, ref useSiteDiagnostics))
{
hadApplicableCandidates = true;
AddDistinctOperators(result.Results, rightOperators);
}
rightOperators.Free();
}
Debug.Assert((result.Results.Count == 0) != hadApplicableCandidates);
// If there are no applicable candidates in classes / stuctures, try with interface sources.
// From https://github.com/dotnet/csharplang/blob/master/meetings/2017/LDM-2017-06-27.md:
// We do not allow == and != and. Otherwise, there'd be no way to override Equals and GetHashCode,
// so you couldn't do == and != in a recommended way.
if (!hadApplicableCandidates &&
kind != BinaryOperatorKind.Equal && kind != BinaryOperatorKind.NotEqual)
{
result.Results.Clear();
string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
var lookedInInterfaces = PooledDictionary<TypeSymbol, bool>.GetInstance();
hadApplicableCandidates = GetUserDefinedBinaryOperatorsFromInterfaces(kind, name,
leftOperatorSourceOpt, leftSourceIsInterface, left, right, ref useSiteDiagnostics, lookedInInterfaces, result.Results);
if (!hadApplicableCandidates)
{
result.Results.Clear();
}
if ((object)rightOperatorSourceOpt != null && !rightOperatorSourceOpt.Equals(leftOperatorSourceOpt))
{
var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
if (GetUserDefinedBinaryOperatorsFromInterfaces(kind, name,
rightOperatorSourceOpt, rightSourceIsInterface, left, right, ref useSiteDiagnostics, lookedInInterfaces, rightOperators))
{
hadApplicableCandidates = true;
AddDistinctOperators(result.Results, rightOperators);
}
rightOperators.Free();
}
lookedInInterfaces.Free();
}
// SPEC: If the set of candidate user-defined operators is not empty, then this becomes the set of candidate
// SPEC: operators for the operation. Otherwise, the predefined binary operator op implementations, including
// SPEC: their lifted forms, become the set of candidate operators for the operation.
// Note that the native compiler has a bug in its binary operator overload resolution involving
// lifted built-in operators. The spec says that we should add the lifted and unlifted operators
// to a candidate set, eliminate the inapplicable operators, and then choose the best of what is left.
// The lifted operator is defined as, say int? + int? --> int?. That is not what the native compiler
// does. The native compiler, rather, effectively says that there are *three* lifted operators:
// int? + int? --> int?, int + int? --> int? and int? + int --> int?, and it chooses the best operator
// amongst those choices.
//
// This is a subtle difference; most of the time all it means is that we generate better code because we
// skip an unnecessary operand conversion to int? when adding int to int?. But some of the time it
// means that a different user-defined conversion is chosen than the one you would expect, if the
// operand has a user-defined conversion to both int and int?.
//
// Roslyn matches the specification and takes the break from the native compiler.
Debug.Assert((result.Results.Count == 0) != hadApplicableCandidates);
if (!hadApplicableCandidates)
{
result.Results.Clear();
GetAllBuiltInOperators(kind, left, right, result.Results, ref useSiteDiagnostics);
}
// SPEC: The overload resolution rules of 7.5.3 are applied to the set of candidate operators to select the best
// SPEC: operator with respect to the argument list (x, y), and this operator becomes the result of the overload
// SPEC: resolution process. If overload resolution fails to select a single best operator, a binding-time
// SPEC: error occurs.
BinaryOperatorOverloadResolution(left, right, result, ref useSiteDiagnostics);
}
private bool GetUserDefinedBinaryOperatorsFromInterfaces(BinaryOperatorKind kind, string name,
TypeSymbol operatorSourceOpt, bool sourceIsInterface,
BoundExpression left, BoundExpression right, ref HashSet<DiagnosticInfo> useSiteDiagnostics,
Dictionary<TypeSymbol, bool> lookedInInterfaces, ArrayBuilder<BinaryOperatorAnalysisResult> candidates)
{
Debug.Assert(candidates.Count == 0);
if ((object)operatorSourceOpt == null)
{
return false;
}
bool hadUserDefinedCandidateFromInterfaces = false;
ImmutableArray<NamedTypeSymbol> interfaces = default;
if (sourceIsInterface)
{
if (!lookedInInterfaces.TryGetValue(operatorSourceOpt, out _))
{
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
GetUserDefinedBinaryOperatorsFromType((NamedTypeSymbol)operatorSourceOpt, kind, name, operators);
hadUserDefinedCandidateFromInterfaces = CandidateOperators(operators, left, right, candidates, ref useSiteDiagnostics);
operators.Free();
Debug.Assert(hadUserDefinedCandidateFromInterfaces == candidates.Any(r => r.IsValid));
lookedInInterfaces.Add(operatorSourceOpt, hadUserDefinedCandidateFromInterfaces);
if (!hadUserDefinedCandidateFromInterfaces)
{
candidates.Clear();
interfaces = operatorSourceOpt.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
}
}
}
else if (operatorSourceOpt.IsTypeParameter())
{
interfaces = ((TypeParameterSymbol)operatorSourceOpt).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
}
if (!interfaces.IsDefaultOrEmpty)
{
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
var results = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
var shadowedInterfaces = PooledHashSet<NamedTypeSymbol>.GetInstance();
foreach (NamedTypeSymbol @interface in interfaces)
{
if (!@interface.IsInterface)
{
// this code could be reachable in error situations
continue;
}
if (shadowedInterfaces.Contains(@interface))
{
// this interface is "shadowed" by a derived interface
continue;
}
if (lookedInInterfaces.TryGetValue(@interface, out bool hadUserDefinedCandidate))
{
if (hadUserDefinedCandidate)
{
// this interface "shadows" all its base interfaces
shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics));
}
// no need to perform another lookup in this interface
continue;
}
operators.Clear();
results.Clear();
GetUserDefinedBinaryOperatorsFromType(@interface, kind, name, operators);
hadUserDefinedCandidate = CandidateOperators(operators, left, right, results, ref useSiteDiagnostics);
Debug.Assert(hadUserDefinedCandidate == results.Any(r => r.IsValid));
lookedInInterfaces.Add(@interface, hadUserDefinedCandidate);
if (hadUserDefinedCandidate)
{
hadUserDefinedCandidateFromInterfaces = true;
candidates.AddRange(results);
// this interface "shadows" all its base interfaces
shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics));
}
}
operators.Free();
results.Free();
shadowedInterfaces.Free();
}
return hadUserDefinedCandidateFromInterfaces;
}
private void AddDelegateOperation(BinaryOperatorKind kind, TypeSymbol delegateType,
ArrayBuilder<BinaryOperatorSignature> operators)
{
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
break;
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
default:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, delegateType));
break;
}
}
private void GetDelegateOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right,
ArrayBuilder<BinaryOperatorSignature> operators, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
switch (kind)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.RightShift:
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
return;
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
break;
default:
// Unhandled bin op kind in get delegate operation
throw ExceptionUtilities.UnexpectedValue(kind);
}
var leftType = left.Type;
var leftDelegate = (object)leftType != null && leftType.IsDelegateType();
var rightType = right.Type;
var rightDelegate = (object)rightType != null && rightType.IsDelegateType();
// If no operands have delegate types then add nothing.
if (!leftDelegate && !rightDelegate)
{
// Even though neither left nor right type is a delegate type,
// both types might have implicit conversions to System.Delegate type.
// Spec 7.10.8: Delegate equality operators:
// Every delegate type implicitly provides the following predefined comparison operators:
// bool operator ==(System.Delegate x, System.Delegate y)
// bool operator !=(System.Delegate x, System.Delegate y)
switch (OperatorKindExtensions.Operator(kind))
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
TypeSymbol systemDelegateType = _binder.GetSpecialType(SpecialType.System_Delegate, _binder.Compilation.DeclarationDiagnostics, left.Syntax);
if (Conversions.ClassifyImplicitConversionFromExpression(left, systemDelegateType, ref useSiteDiagnostics).IsValid &&
Conversions.ClassifyImplicitConversionFromExpression(right, systemDelegateType, ref useSiteDiagnostics).IsValid)
{
AddDelegateOperation(kind, systemDelegateType, operators);
}
break;
}
return;
}
// We might have a situation like
//
// Func<string> + Func<object>
//
// in which case overload resolution should consider both
//
// Func<string> + Func<string>
// Func<object> + Func<object>
//
// are candidates (and it will pick Func<object>). Similarly,
// we might have something like:
//
// Func<object> + Func<dynamic>
//
// in which case neither candidate is better than the other,
// resulting in an error.
//
// We could as an optimization say that if you are adding two completely
// dissimilar delegate types D1 and D2, that neither is added to the candidate
// set because neither can possibly be applicable, but let's not go there.
// Let's just add them to the set and let overload resolution (and the
// error recovery heuristics) have at the real candidate set.
//
// However, we will take a spec violation for this scenario:
//
// SPEC VIOLATION:
//
// Technically the spec implies that we ought to be able to compare
//
// Func<int> x = whatever;
// bool y = x == ()=>1;
//
// The native compiler does not allow this. I see no
// reason why we ought to allow this. However, a good question is whether
// the violation ought to be here, where we are determining the operator
// candidate set, or in overload resolution where we are determining applicability.
// In the native compiler we did it during candidate set determination,
// so let's stick with that.
if (leftDelegate && rightDelegate)
{
// They are both delegate types. Add them both if they are different types.
AddDelegateOperation(kind, leftType, operators);
// There is no reason why we can't compare instances of delegate types that are identity convertible.
// We can't perform + or - operation on them since it is not clear what the return type of such operation should be.
bool useIdentityConversion = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
if (!(useIdentityConversion ? Conversions.HasIdentityConversion(leftType, rightType) : leftType.Equals(rightType)))
{
AddDelegateOperation(kind, rightType, operators);
}
return;
}
// One of them is a delegate, the other is not.
TypeSymbol delegateType = leftDelegate ? leftType : rightType;
BoundExpression nonDelegate = leftDelegate ? right : left;
if ((kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual)
&& nonDelegate.Kind == BoundKind.UnboundLambda)
{
return;
}
AddDelegateOperation(kind, delegateType, operators);
}
private void GetEnumOperation(BinaryOperatorKind kind, TypeSymbol enumType, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> operators)
{
Debug.Assert((object)enumType != null);
AssertNotChecked(kind);
if (!enumType.IsValidEnumType())
{
return;
}
var underlying = enumType.GetEnumUnderlyingType();
Debug.Assert((object)underlying != null);
Debug.Assert(underlying.SpecialType != SpecialType.None);
var nullable = Compilation.GetSpecialType(SpecialType.System_Nullable_T);
var nullableEnum = nullable.Construct(enumType);
var nullableUnderlying = nullable.Construct(underlying);
switch (kind)
{
case BinaryOperatorKind.Addition:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingAddition, enumType, underlying, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumAddition, underlying, enumType, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingAddition, nullableEnum, nullableUnderlying, nullableEnum));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumAddition, nullableUnderlying, nullableEnum, nullableEnum));
break;
case BinaryOperatorKind.Subtraction:
if (Strict)
{
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum));
}
else
{
// SPEC VIOLATION:
// The native compiler has bugs in overload resolution involving binary operator- for enums,
// which we duplicate by hardcoding Priority values among the operators. When present on both
// methods being compared during overload resolution, Priority values are used to decide between
// two candidates (instead of the usual language-specified rules).
bool isExactSubtraction = TypeSymbol.Equals(right.Type?.StrippedType(), underlying, TypeCompareKind.ConsiderEverything2);
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying)
{ Priority = 2 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType)
{ Priority = isExactSubtraction ? 1 : 3 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying)
{ Priority = 12 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum)
{ Priority = isExactSubtraction ? 11 : 13 });
// Due to a bug, the native compiler allows "underlying - enum", so Roslyn does as well.
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumSubtraction, underlying, enumType, enumType)
{ Priority = 4 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumSubtraction, nullableUnderlying, nullableEnum, nullableEnum)
{ Priority = 14 });
}
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
var boolean = Compilation.GetSpecialType(SpecialType.System_Boolean);
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, boolean));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, boolean));
break;
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, enumType));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, nullableEnum));
break;
}
}
private void GetPointerArithmeticOperators(
BinaryOperatorKind kind,
PointerTypeSymbol pointerType,
ArrayBuilder<BinaryOperatorSignature> operators)
{
Debug.Assert((object)pointerType != null);
AssertNotChecked(kind);
switch (kind)
{
case BinaryOperatorKind.Addition:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.IntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UIntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.ULongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType, pointerType));
break;
case BinaryOperatorKind.Subtraction:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerSubtraction, pointerType, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64)));
break;
}
}
private void GetPointerComparisonOperators(
BinaryOperatorKind kind,
ArrayBuilder<BinaryOperatorSignature> operators)
{
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
var voidPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(Compilation.GetSpecialType(SpecialType.System_Void)));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Pointer, voidPointerType, voidPointerType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
break;
}
}
private void GetEnumOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> results)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
// First take some easy outs:
switch (kind)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.RightShift:
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
return;
}
var leftType = left.Type;
if ((object)leftType != null)
{
leftType = leftType.StrippedType();
}
var rightType = right.Type;
if ((object)rightType != null)
{
rightType = rightType.StrippedType();
}
bool useIdentityConversion;
switch (kind)
{
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
// These operations are ambiguous on non-equal identity-convertible types -
// it's not clear what the resulting type of the operation should be:
// C<?>.E operator +(C<dynamic>.E x, C<object>.E y)
useIdentityConversion = false;
break;
case BinaryOperatorKind.Addition:
// Addition only accepts a single enum type, so operations on non-equal identity-convertible types are not ambiguous.
// E operator +(E x, U y)
// E operator +(U x, E y)
useIdentityConversion = true;
break;
case BinaryOperatorKind.Subtraction:
// Subtraction either returns underlying type or only accept a single enum type, so operations on non-equal identity-convertible types are not ambiguous.
// U operator –(E x, E y)
// E operator –(E x, U y)
useIdentityConversion = true;
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
// Relational operations return Boolean, so operations on non-equal identity-convertible types are not ambiguous.
// Boolean operator op(C<dynamic>.E, C<object>.E)
useIdentityConversion = true;
break;
default:
// Unhandled bin op kind in get enum operations
throw ExceptionUtilities.UnexpectedValue(kind);
}
if ((object)leftType != null)
{
GetEnumOperation(kind, leftType, left, right, results);
}
if ((object)rightType != null && ((object)leftType == null || !(useIdentityConversion ? Conversions.HasIdentityConversion(rightType, leftType) : rightType.Equals(leftType))))
{
GetEnumOperation(kind, rightType, left, right, results);
}
}
private void GetPointerOperators(
BinaryOperatorKind kind,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorSignature> results)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
var leftType = left.Type as PointerTypeSymbol;
var rightType = right.Type as PointerTypeSymbol;
if ((object)leftType != null)
{
GetPointerArithmeticOperators(kind, leftType, results);
}
// The only arithmetic operator that is applicable on two distinct pointer types is
// long operator –(T* x, T* y)
// This operator returns long and so it's not ambiguous to apply it on T1 and T2 that are identity convertible to each other.
if ((object)rightType != null && ((object)leftType == null || !Conversions.HasIdentityConversion(rightType, leftType)))
{
GetPointerArithmeticOperators(kind, rightType, results);
}
if ((object)leftType != null || (object)rightType != null)
{
// The pointer comparison operators are all "void* OP void*".
GetPointerComparisonOperators(kind, results);
}
}
private void GetAllBuiltInOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorAnalysisResult> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// Strip the "checked" off; the checked-ness of the context does not affect which built-in operators
// are applicable.
kind = kind.OperatorWithLogical();
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
if (isEquality && useOnlyReferenceEquality(Conversions, left, right, ref useSiteDiagnostics))
{
// As a special case, if the reference equality operator is applicable (and it
// is not a string or delegate) we do not check any other operators. This patches
// what is otherwise a flaw in the language specification. See 11426.
GetReferenceEquality(kind, operators);
}
else
{
this.Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, operators, skipNativeIntegerOperators: !left.Type.IsNativeIntegerOrNullableNativeIntegerType() && !right.Type.IsNativeIntegerOrNullableNativeIntegerType());
// SPEC 7.3.4: For predefined enum and delegate operators, the only operators
// considered are those defined by an enum or delegate type that is the binding
//-time type of one of the operands.
GetDelegateOperations(kind, left, right, operators, ref useSiteDiagnostics);
GetEnumOperations(kind, left, right, operators);
// We similarly limit pointer operator candidates considered.
GetPointerOperators(kind, left, right, operators);
}
CandidateOperators(operators, left, right, results, ref useSiteDiagnostics);
operators.Free();
static bool useOnlyReferenceEquality(Conversions conversions, BoundExpression left, BoundExpression right, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// We consider the `null` literal, but not the `default` literal, since the latter does not require a reference equality
return
BuiltInOperators.IsValidObjectEquality(conversions, left.Type, left.IsLiteralNull(), leftIsDefault: false, right.Type, right.IsLiteralNull(), rightIsDefault: false, ref useSiteDiagnostics) &&
((object)left.Type == null || (!left.Type.IsDelegateType() && left.Type.SpecialType != SpecialType.System_String && left.Type.SpecialType != SpecialType.System_Delegate)) &&
((object)right.Type == null || (!right.Type.IsDelegateType() && right.Type.SpecialType != SpecialType.System_String && right.Type.SpecialType != SpecialType.System_Delegate));
}
}
private void GetReferenceEquality(BinaryOperatorKind kind, ArrayBuilder<BinaryOperatorSignature> operators)
{
var @object = Compilation.GetSpecialType(SpecialType.System_Object);
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Object, @object, @object, Compilation.GetSpecialType(SpecialType.System_Boolean)));
}
private bool CandidateOperators(
ArrayBuilder<BinaryOperatorSignature> operators,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> results,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
bool hadApplicableCandidate = false;
foreach (var op in operators)
{
var convLeft = Conversions.ClassifyConversionFromExpression(left, op.LeftType, ref useSiteDiagnostics);
var convRight = Conversions.ClassifyConversionFromExpression(right, op.RightType, ref useSiteDiagnostics);
if (convLeft.IsImplicit && convRight.IsImplicit)
{
results.Add(BinaryOperatorAnalysisResult.Applicable(op, convLeft, convRight));
hadApplicableCandidate = true;
}
else
{
results.Add(BinaryOperatorAnalysisResult.Inapplicable(op, convLeft, convRight));
}
}
return hadApplicableCandidate;
}
private static void AddDistinctOperators(ArrayBuilder<BinaryOperatorAnalysisResult> result, ArrayBuilder<BinaryOperatorAnalysisResult> additionalOperators)
{
int initialCount = result.Count;
foreach (var op in additionalOperators)
{
bool equivalentToExisting = false;
for (int i = 0; i < initialCount; i++)
{
var existingSignature = result[i].Signature;
Debug.Assert(op.Signature.Kind.Operator() == existingSignature.Kind.Operator());
// Return types must match exactly, parameters might match modulo identity conversion.
if (op.Signature.Kind == existingSignature.Kind && // Easy out
equalsIgnoringNullable(op.Signature.ReturnType, existingSignature.ReturnType) &&
equalsIgnoringNullableAndDynamic(op.Signature.LeftType, existingSignature.LeftType) &&
equalsIgnoringNullableAndDynamic(op.Signature.RightType, existingSignature.RightType) &&
equalsIgnoringNullableAndDynamic(op.Signature.Method.ContainingType, existingSignature.Method.ContainingType))
{
equivalentToExisting = true;
break;
}
}
if (!equivalentToExisting)
{
result.Add(op);
}
}
static bool equalsIgnoringNullable(TypeSymbol a, TypeSymbol b) => a.Equals(b, TypeCompareKind.AllNullableIgnoreOptions);
static bool equalsIgnoringNullableAndDynamic(TypeSymbol a, TypeSymbol b) => a.Equals(b, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreDynamic);
}
private bool GetUserDefinedOperators(
BinaryOperatorKind kind,
TypeSymbol type0,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> results,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
Debug.Assert(results.Count == 0);
if ((object)type0 == null || OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0))
{
return false;
}
// Spec 7.3.5 Candidate user-defined operators
// SPEC: Given a type T and an operation operator op(A), where op is an overloadable
// SPEC: operator and A is an argument list, the set of candidate user-defined operators
// SPEC: provided by T for operator op(A) is determined as follows:
// SPEC: Determine the type T0. If T is a nullable type, T0 is its underlying type,
// SPEC: otherwise T0 is equal to T.
// (The caller has already passed in the stripped type.)
// SPEC: For all operator op declarations in T0 and all lifted forms of such operators,
// SPEC: if at least one operator is applicable (7.5.3.1) with respect to the argument
// SPEC: list A, then the set of candidate operators consists of all such applicable
// SPEC: operators in T0. Otherwise, if T0 is object, the set of candidate operators is empty.
// SPEC: Otherwise, the set of candidate operators provided by T0 is the set of candidate
// SPEC: operators provided by the direct base class of T0, or the effective base class of
// SPEC: T0 if T0 is a type parameter.
string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
bool hadApplicableCandidates = false;
NamedTypeSymbol current = type0 as NamedTypeSymbol;
if ((object)current == null)
{
current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
}
if ((object)current == null && type0.IsTypeParameter())
{
current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteDiagnostics);
}
for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
{
operators.Clear();
GetUserDefinedBinaryOperatorsFromType(current, kind, name, operators);
results.Clear();
if (CandidateOperators(operators, left, right, results, ref useSiteDiagnostics))
{
hadApplicableCandidates = true;
break;
}
}
operators.Free();
Debug.Assert(hadApplicableCandidates == results.Any(r => r.IsValid));
return hadApplicableCandidates;
}
private void GetUserDefinedBinaryOperatorsFromType(
NamedTypeSymbol type,
BinaryOperatorKind kind,
string name,
ArrayBuilder<BinaryOperatorSignature> operators)
{
foreach (MethodSymbol op in type.GetOperators(name))
{
// If we're in error recovery, we might have bad operators. Just ignore it.
if (op.ParameterCount != 2 || op.ReturnsVoid)
{
continue;
}
TypeSymbol leftOperandType = op.GetParameterType(0);
TypeSymbol rightOperandType = op.GetParameterType(1);
TypeSymbol resultType = op.ReturnType;
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, op));
LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind);
if (lifting == LiftingResult.LiftOperandsAndResult)
{
operators.Add(new BinaryOperatorSignature(
BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
MakeNullable(leftOperandType), MakeNullable(rightOperandType), MakeNullable(resultType), op));
}
else if (lifting == LiftingResult.LiftOperandsButNotResult)
{
operators.Add(new BinaryOperatorSignature(
BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
MakeNullable(leftOperandType), MakeNullable(rightOperandType), resultType, op));
}
}
}
private enum LiftingResult
{
NotLifted,
LiftOperandsAndResult,
LiftOperandsButNotResult
}
private static LiftingResult UserDefinedBinaryOperatorCanBeLifted(TypeSymbol left, TypeSymbol right, TypeSymbol result, BinaryOperatorKind kind)
{
// SPEC: For the binary operators + - * / % & | ^ << >> a lifted form of the
// SPEC: operator exists if the operand and result types are all non-nullable
// SPEC: value types. The lifted form is constructed by adding a single ?
// SPEC: modifier to each operand and result type.
//
// SPEC: For the equality operators == != a lifted form of the operator exists
// SPEC: if the operand types are both non-nullable value types and if the
// SPEC: result type is bool. The lifted form is constructed by adding
// SPEC: a single ? modifier to each operand type.
//
// SPEC: For the relational operators > < >= <= a lifted form of the
// SPEC: operator exists if the operand types are both non-nullable value
// SPEC: types and if the result type is bool. The lifted form is
// SPEC: constructed by adding a single ? modifier to each operand type.
if (!left.IsValueType ||
left.IsNullableType() ||
!right.IsValueType ||
right.IsNullableType())
{
return LiftingResult.NotLifted;
}
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
// Spec violation: can't lift unless the types match.
// The spec doesn't require this, but dev11 does and it reduces ambiguity in some cases.
if (!TypeSymbol.Equals(left, right, TypeCompareKind.ConsiderEverything2)) return LiftingResult.NotLifted;
goto case BinaryOperatorKind.GreaterThan;
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
return result.SpecialType == SpecialType.System_Boolean ?
LiftingResult.LiftOperandsButNotResult :
LiftingResult.NotLifted;
default:
return result.IsValueType && !result.IsNullableType() ?
LiftingResult.LiftOperandsAndResult :
LiftingResult.NotLifted;
}
}
// Takes a list of candidates and mutates the list to throw out the ones that are worse than
// another applicable candidate.
private void BinaryOperatorOverloadResolution(
BoundExpression left,
BoundExpression right,
BinaryOperatorOverloadResolutionResult result,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// SPEC: Given the set of applicable candidate function members, the best function member in that set is located.
// SPEC: If the set contains only one function member, then that function member is the best function member.
if (result.SingleValid())
{
return;
}
// SPEC: Otherwise, the best function member is the one function member that is better than all other function
// SPEC: members with respect to the given argument list, provided that each function member is compared to all
// SPEC: other function members using the rules in 7.5.3.2. If there is not exactly one function member that is
// SPEC: better than all other function members, then the function member invocation is ambiguous and a binding-time
// SPEC: error occurs.
var candidates = result.Results;
// Try to find a single best candidate
int bestIndex = GetTheBestCandidateIndex(left, right, candidates, ref useSiteDiagnostics);
if (bestIndex != -1)
{
// Mark all other candidates as worse
for (int index = 0; index < candidates.Count; ++index)
{
if (candidates[index].Kind != OperatorAnalysisResultKind.Inapplicable && index != bestIndex)
{
candidates[index] = candidates[index].Worse();
}
}
return;
}
for (int i = 1; i < candidates.Count; ++i)
{
if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable)
{
continue;
}
// Is this applicable operator better than every other applicable method?
for (int j = 0; j < i; ++j)
{
if (candidates[j].Kind == OperatorAnalysisResultKind.Inapplicable)
{
continue;
}
var better = BetterOperator(candidates[i].Signature, candidates[j].Signature, left, right, ref useSiteDiagnostics);
if (better == BetterResult.Left)
{
candidates[j] = candidates[j].Worse();
}
else if (better == BetterResult.Right)
{
candidates[i] = candidates[i].Worse();
}
}
}
}
private int GetTheBestCandidateIndex(
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> candidates,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
int currentBestIndex = -1;
for (int index = 0; index < candidates.Count; index++)
{
if (candidates[index].Kind != OperatorAnalysisResultKind.Applicable)
{
continue;
}
// Assume that the current candidate is the best if we don't have any
if (currentBestIndex == -1)
{
currentBestIndex = index;
}
else
{
var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteDiagnostics);
if (better == BetterResult.Right)
{
// The current best is worse
currentBestIndex = index;
}
else if (better != BetterResult.Left)
{
// The current best is not better
currentBestIndex = -1;
}
}
}
// Make sure that every candidate up to the current best is worse
for (int index = 0; index < currentBestIndex; index++)
{
if (candidates[index].Kind == OperatorAnalysisResultKind.Inapplicable)
{
continue;
}
var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteDiagnostics);
if (better != BetterResult.Left)
{
// The current best is not better
return -1;
}
}
return currentBestIndex;
}
private BetterResult BetterOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, BoundExpression left, BoundExpression right, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// We use Priority as a tie-breaker to help match native compiler bugs.
Debug.Assert(op1.Priority.HasValue == op2.Priority.HasValue);
if (op1.Priority.HasValue && op1.Priority.GetValueOrDefault() != op2.Priority.GetValueOrDefault())
{
return (op1.Priority.GetValueOrDefault() < op2.Priority.GetValueOrDefault()) ? BetterResult.Left : BetterResult.Right;
}
BetterResult leftBetter = BetterConversionFromExpression(left, op1.LeftType, op2.LeftType, ref useSiteDiagnostics);
BetterResult rightBetter = BetterConversionFromExpression(right, op1.RightType, op2.RightType, ref useSiteDiagnostics);
// SPEC: Mp is defined to be a better function member than Mq if:
// SPEC: * For each argument, the implicit conversion from Ex to Qx is not better than
// SPEC: the implicit conversion from Ex to Px, and
// SPEC: * For at least one argument, the conversion from Ex to Px is better than the
// SPEC: conversion from Ex to Qx.
// If that is hard to follow, consult this handy chart:
// op1.Left vs op2.Left op1.Right vs op2.Right result
// -----------------------------------------------------------
// op1 better op1 better op1 better
// op1 better neither better op1 better
// op1 better op2 better neither better
// neither better op1 better op1 better
// neither better neither better neither better
// neither better op2 better op2 better
// op2 better op1 better neither better
// op2 better neither better op2 better
// op2 better op2 better op2 better
if (leftBetter == BetterResult.Left && rightBetter != BetterResult.Right ||
leftBetter != BetterResult.Right && rightBetter == BetterResult.Left)
{
return BetterResult.Left;
}
if (leftBetter == BetterResult.Right && rightBetter != BetterResult.Left ||
leftBetter != BetterResult.Left && rightBetter == BetterResult.Right)
{
return BetterResult.Right;
}
// There was no better member on the basis of conversions. Go to the tiebreaking round.
// SPEC: In case the parameter type sequences P1, P2 and Q1, Q2 are equivalent -- that is, every Pi
// SPEC: has an identity conversion to the corresponding Qi -- the following tie-breaking rules
// SPEC: are applied:
if (Conversions.HasIdentityConversion(op1.LeftType, op2.LeftType) &&
Conversions.HasIdentityConversion(op1.RightType, op2.RightType))
{
// NOTE: The native compiler does not follow these rules; effectively, the native
// compiler checks for liftedness first, and then for specificity. For example:
// struct S<T> where T : struct {
// public static bool operator +(S<T> x, int y) { return true; }
// public static bool? operator +(S<T>? x, int? y) { return false; }
// }
//
// bool? b = new S<int>?() + new int?();
//
// should reason as follows: the two applicable operators are the lifted
// form of the first operator and the unlifted second operator. The
// lifted form of the first operator is *more specific* because int?
// is more specific than T?. Therefore it should win. In fact the
// native compiler chooses the second operator, because it is unlifted.
//
// Roslyn follows the spec rules; if we decide to change the spec to match
// the native compiler, or decide to change Roslyn to match the native
// compiler, we should change the order of the checks here.
// SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq.
BetterResult result = MoreSpecificOperator(op1, op2, ref useSiteDiagnostics);
if (result == BetterResult.Left || result == BetterResult.Right)
{
return result;
}
// SPEC: If one member is a non-lifted operator and the other is a lifted operator,
// SPEC: the non-lifted one is better.
bool lifted1 = op1.Kind.IsLifted();
bool lifted2 = op2.Kind.IsLifted();
if (lifted1 && !lifted2)
{
return BetterResult.Right;
}
else if (!lifted1 && lifted2)
{
return BetterResult.Left;
}
}
// Always prefer operators with val parameters over operators with in parameters:
BetterResult valOverInPreference;
if (op1.LeftRefKind == RefKind.None && op2.LeftRefKind == RefKind.In)
{
valOverInPreference = BetterResult.Left;
}
else if (op2.LeftRefKind == RefKind.None && op1.LeftRefKind == RefKind.In)
{
valOverInPreference = BetterResult.Right;
}
else
{
valOverInPreference = BetterResult.Neither;
}
if (op1.RightRefKind == RefKind.None && op2.RightRefKind == RefKind.In)
{
if (valOverInPreference == BetterResult.Right)
{
return BetterResult.Neither;
}
else
{
valOverInPreference = BetterResult.Left;
}
}
else if (op2.RightRefKind == RefKind.None && op1.RightRefKind == RefKind.In)
{
if (valOverInPreference == BetterResult.Left)
{
return BetterResult.Neither;
}
else
{
valOverInPreference = BetterResult.Right;
}
}
return valOverInPreference;
}
private BetterResult MoreSpecificOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
TypeSymbol op1Left, op1Right, op2Left, op2Right;
if ((object)op1.Method != null)
{
var p = op1.Method.OriginalDefinition.GetParameters();
op1Left = p[0].Type;
op1Right = p[1].Type;
if (op1.Kind.IsLifted())
{
op1Left = MakeNullable(op1Left);
op1Right = MakeNullable(op1Right);
}
}
else
{
op1Left = op1.LeftType;
op1Right = op1.RightType;
}
if ((object)op2.Method != null)
{
var p = op2.Method.OriginalDefinition.GetParameters();
op2Left = p[0].Type;
op2Right = p[1].Type;
if (op2.Kind.IsLifted())
{
op2Left = MakeNullable(op2Left);
op2Right = MakeNullable(op2Right);
}
}
else
{
op2Left = op2.LeftType;
op2Right = op2.RightType;
}
var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance();
var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance();
uninst1.Add(op1Left);
uninst1.Add(op1Right);
uninst2.Add(op2Left);
uninst2.Add(op2Right);
BetterResult result = MoreSpecificType(uninst1, uninst2, ref useSiteDiagnostics);
uninst1.Free();
uninst2.Free();
return result;
}
[Conditional("DEBUG")]
private static void AssertNotChecked(BinaryOperatorKind kind)
{
Debug.Assert((kind & ~BinaryOperatorKind.Checked) == kind, "Did not expect operator to be checked. Consider using .Operator() to mask.");
}
}
}
| 51.140924 | 238 | 0.594352 | [
"MIT"
] | BertanAygun/roslyn | src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolution.cs | 64,241 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class W3Effect_Mutation4 : CBaseGameplayEffect
{
[Ordinal(1)] [RED("bonusPerPoint")] public CFloat BonusPerPoint { get; set;}
[Ordinal(2)] [RED("dotDuration")] public CFloat DotDuration { get; set;}
public W3Effect_Mutation4(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3Effect_Mutation4(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 33.518519 | 130 | 0.730387 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/W3Effect_Mutation4.cs | 905 | C# |
namespace SKIT.FlurlHttpClient.Wechat.Api.Models
{
/// <summary>
/// <para>表示 [POST] /cgi-bin/media/uploadimg 接口的请求。</para>
/// </summary>
public class CgibinMediaUploadImageRequest : WechatApiRequest, IMapResponse<CgibinMediaUploadImageRequest, CgibinMediaUploadImageResponse>
{
/// <summary>
/// 获取或设置图片文件字节数组。
/// </summary>
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public byte[] FileBytes { get; set; } = new byte[0];
/// <summary>
/// 获取或设置图片文件名。如果不指定将由系统自动生成。
/// </summary>
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public string? FileName { get; set; }
/// <summary>
/// 获取或设置图片文件 Conent-Type。如果不指定将由系统自动生成。
/// </summary>
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public string? FileContentType { get; set; }
}
}
| 32.9 | 142 | 0.616008 | [
"MIT"
] | vst-h/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinMedia/CgibinMediaUploadImageRequest.cs | 1,131 | 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.V20190801
{
/// <summary>
/// Hybrid Connection for an App Service app.
/// </summary>
[AzureNativeResourceType("azure-native:web/v20190801:WebAppRelayServiceConnectionSlot")]
public partial class WebAppRelayServiceConnectionSlot : Pulumi.CustomResource
{
[Output("biztalkUri")]
public Output<string?> BiztalkUri { get; private set; } = null!;
[Output("entityConnectionString")]
public Output<string?> EntityConnectionString { get; private set; } = null!;
[Output("entityName")]
public Output<string?> EntityName { get; private set; } = null!;
[Output("hostname")]
public Output<string?> Hostname { get; private set; } = null!;
/// <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!;
[Output("port")]
public Output<int?> Port { get; private set; } = null!;
[Output("resourceConnectionString")]
public Output<string?> ResourceConnectionString { get; private set; } = null!;
[Output("resourceType")]
public Output<string?> ResourceType { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a WebAppRelayServiceConnectionSlot 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 WebAppRelayServiceConnectionSlot(string name, WebAppRelayServiceConnectionSlotArgs args, CustomResourceOptions? options = null)
: base("azure-native:web/v20190801:WebAppRelayServiceConnectionSlot", name, args ?? new WebAppRelayServiceConnectionSlotArgs(), MakeResourceOptions(options, ""))
{
}
private WebAppRelayServiceConnectionSlot(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:web/v20190801:WebAppRelayServiceConnectionSlot", 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/v20190801:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20150801:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20150801:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20160801:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20160801:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20180201:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20180201:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20181101:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20181101:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20200601:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20200601:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20200901:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20200901:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20201001:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20201001:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-native:web/v20201201:WebAppRelayServiceConnectionSlot"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20201201:WebAppRelayServiceConnectionSlot"},
},
};
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 WebAppRelayServiceConnectionSlot 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 WebAppRelayServiceConnectionSlot Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new WebAppRelayServiceConnectionSlot(name, id, options);
}
}
public sealed class WebAppRelayServiceConnectionSlotArgs : Pulumi.ResourceArgs
{
[Input("biztalkUri")]
public Input<string>? BiztalkUri { get; set; }
[Input("entityConnectionString")]
public Input<string>? EntityConnectionString { get; set; }
[Input("entityName")]
public Input<string>? EntityName { get; set; }
[Input("hostname")]
public Input<string>? Hostname { get; set; }
/// <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("port")]
public Input<int>? Port { get; set; }
[Input("resourceConnectionString")]
public Input<string>? ResourceConnectionString { get; set; }
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("resourceType")]
public Input<string>? ResourceType { get; set; }
/// <summary>
/// Name of the deployment slot. If a slot is not specified, the API will create or update a hybrid connection for the production slot.
/// </summary>
[Input("slot", required: true)]
public Input<string> Slot { get; set; } = null!;
public WebAppRelayServiceConnectionSlotArgs()
{
}
}
}
| 45.758621 | 173 | 0.624592 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/Web/V20190801/WebAppRelayServiceConnectionSlot.cs | 7,962 | C# |
/*
*Ваши права на использование кода регулируются данной лицензией http://o-s-a.net/doc/license_simple_engine.pdf
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows.Forms.Integration;
using System.Windows.Shapes;
using OsEngine.Charts;
using OsEngine.Entity;
using OsEngine.Logging;
using OsEngine.Market.Servers;
using OsEngine.Market.Servers.Finam;
namespace OsEngine.OsData
{
/// <summary>
/// сет хранения данных
/// </summary>
public class OsDataSet
{
// регулируемые настройки
/// <summary>
/// включен ли к сохранению 1 секундный ТаймФрейм
/// </summary>
public bool Tf1SecondIsOn;
/// <summary>
/// включен ли к сохранению 2ух секундный ТаймФрейм
/// </summary>
public bool Tf2SecondIsOn;
/// <summary>
/// включен ли к сохранению пяти секундный ТаймФрейм
/// </summary>
public bool Tf5SecondIsOn;
/// <summary>
/// включен ли к сохранению 10 секундный ТаймФрейм
/// </summary>
public bool Tf10SecondIsOn;
/// <summary>
/// включен ли к сохранению 15 секундный ТаймФрейм
/// </summary>
public bool Tf15SecondIsOn;
/// <summary>
/// включен ли к сохранению 20 секундный ТаймФрейм
/// </summary>
public bool Tf20SecondIsOn;
/// <summary>
/// включен ли к сохранению 30 секундный ТаймФрейм
/// </summary>
public bool Tf30SecondIsOn;
/// <summary>
/// включен ли к сохранению 1 минутный ТаймФрейм
/// </summary>
public bool Tf1MinuteIsOn;
/// <summary>
/// включен ли к сохранению 2 минутный ТаймФрейм
/// </summary>
public bool Tf2MinuteIsOn;
/// <summary>
/// включен ли к сохранению 5 минутный ТаймФрейм
/// </summary>
public bool Tf5MinuteIsOn;
/// <summary>
/// включен ли к сохранению 10 минутный ТаймФрейм
/// </summary>
public bool Tf10MinuteIsOn;
/// <summary>
/// включен ли к сохранению 15 минутный ТаймФрейм
/// </summary>
public bool Tf15MinuteIsOn;
/// <summary>
/// включен ли к сохранению 30 минутный ТаймФрейм
/// </summary>
public bool Tf30MinuteIsOn;
/// <summary>
/// включен ли к сохранению 1 часовой ТаймФрейм
/// </summary>
public bool Tf1HourIsOn;
/// <summary>
/// включен ли к сохранению 2 часовой ТаймФрейм
/// </summary>
public bool Tf2HourIsOn;
/// <summary>
/// включен ли к сохранению тиковый ТаймФрейм
/// </summary>
public bool TfTickIsOn;
/// <summary>
/// включен ли к сохранению стакан
/// </summary>
public bool TfMarketDepthIsOn;
/// <summary>
/// глубина сохранения стакана
/// </summary>
public int MarketDepthDepth;
/// <summary>
/// тип создания свечек - из стакана или из тиков
/// </summary>
public CandleSeriesCreateDataType CandleCreateType;
/// <summary>
/// уникальное имя сета
/// </summary>
public string SetName;
/// <summary>
/// источник сета
/// </summary>
public ServerType Source;
/// <summary>
/// время старта скачивания
/// </summary>
public DateTime TimeStart;
/// <summary>
/// время завершения
/// </summary>
public DateTime TimeEnd;
/// <summary>
/// имена бумаг на которые мы подписаны
/// </summary>
public List<string> SecuritiesNames;
/// <summary>
/// нужно ли обновлять данные автоматически
/// </summary>
public bool NeadToUpdate;
/// <summary>
/// нужно ли загрузить данные в боевые сервера
/// </summary>
public bool NeadToLoadDataInServers;
// сервис
/// <summary>
/// конструктор
/// </summary>
public OsDataSet(string nameUniq, System.Windows.Controls.ComboBox comboBoxSecurity,
System.Windows.Controls.ComboBox comboBoxTimeFrame)
{
SetName = nameUniq;
_regime = DataSetState.Off;
Tf1SecondIsOn = true;
Tf2SecondIsOn = true;
Tf5SecondIsOn = true;
Tf10SecondIsOn = true;
Tf15SecondIsOn = true;
Tf20SecondIsOn = true;
Tf30SecondIsOn = true;
Tf1MinuteIsOn = true;
Tf2MinuteIsOn = true;
Tf5MinuteIsOn = true;
Tf10MinuteIsOn = true;
Tf15MinuteIsOn = true;
Tf30MinuteIsOn = true;
Tf1HourIsOn = true;
Tf2HourIsOn = true;
TfTickIsOn = true;
TfMarketDepthIsOn = true;
Source = ServerType.Unknown;
SecuritiesNames = new List<string>();
TimeStart = DateTime.Now;
TimeEnd = DateTime.Now.AddDays(5);
MarketDepthDepth = 5;
Load();
Thread worker = new Thread(WorkerArea);
worker.IsBackground = true;
worker.Start();
_chartMaster = new ChartMaster(nameUniq);
_chartMaster.StopPaint();
_comboBoxSecurity = comboBoxSecurity;
_comboBoxTimeFrame = comboBoxTimeFrame;
_comboBoxSecurity.SelectionChanged += _comboBoxSecurity_SelectionChanged;
_comboBoxTimeFrame.SelectionChanged += _comboBoxTimeFrame_SelectionChanged;
}
/// <summary>
/// сохранить настройки
/// </summary>
public void Save()
{
try
{
if (!Directory.Exists("Data\\" + SetName))
{
Directory.CreateDirectory("Data\\" + SetName);
}
using (StreamWriter writer = new StreamWriter("Data\\" + SetName + @"\\Settings.txt", false))
{
writer.WriteLine(_regime);
writer.WriteLine(Tf1SecondIsOn);
writer.WriteLine(Tf2SecondIsOn);
writer.WriteLine(Tf5SecondIsOn);
writer.WriteLine(Tf10SecondIsOn);
writer.WriteLine(Tf15SecondIsOn);
writer.WriteLine(Tf20SecondIsOn);
writer.WriteLine(Tf30SecondIsOn);
writer.WriteLine(Tf1MinuteIsOn);
writer.WriteLine(Tf2MinuteIsOn);
writer.WriteLine(Tf5MinuteIsOn);
writer.WriteLine(Tf10MinuteIsOn);
writer.WriteLine(Tf15MinuteIsOn);
writer.WriteLine(Tf30MinuteIsOn);
writer.WriteLine(Tf1HourIsOn);
writer.WriteLine(Tf2HourIsOn);
writer.WriteLine(TfTickIsOn);
writer.WriteLine(TfMarketDepthIsOn);
writer.WriteLine(Source);
writer.WriteLine(TimeStart);
writer.WriteLine(TimeEnd);
writer.WriteLine(_selectedTf);
writer.WriteLine(_selectedSecurity);
string securities = "";
for (int i = 0; SecuritiesNames != null && i < SecuritiesNames.Count; i++)
{
securities += SecuritiesNames[i] + "*";
}
writer.WriteLine(securities);
writer.WriteLine(CandleCreateType);
writer.WriteLine(MarketDepthDepth);
writer.WriteLine(NeadToUpdate);
writer.WriteLine(NeadToLoadDataInServers);
writer.Close();
}
}
catch (Exception)
{
// ignored
}
}
/// <summary>
/// загрузить настройки
/// </summary>
private void Load()
{
if (!File.Exists("Data\\" + SetName + @"\\Settings.txt"))
{
return;
}
try
{
using (StreamReader reader = new StreamReader("Data\\" + SetName + @"\\Settings.txt"))
{
Enum.TryParse(reader.ReadLine(), out _regime);
Tf1SecondIsOn = Convert.ToBoolean(reader.ReadLine());
Tf2SecondIsOn = Convert.ToBoolean(reader.ReadLine());
Tf5SecondIsOn = Convert.ToBoolean(reader.ReadLine());
Tf10SecondIsOn = Convert.ToBoolean(reader.ReadLine());
Tf15SecondIsOn = Convert.ToBoolean(reader.ReadLine());
Tf20SecondIsOn = Convert.ToBoolean(reader.ReadLine());
Tf30SecondIsOn = Convert.ToBoolean(reader.ReadLine());
Tf1MinuteIsOn = Convert.ToBoolean(reader.ReadLine());
Tf2MinuteIsOn = Convert.ToBoolean(reader.ReadLine());
Tf5MinuteIsOn = Convert.ToBoolean(reader.ReadLine());
Tf10MinuteIsOn = Convert.ToBoolean(reader.ReadLine());
Tf15MinuteIsOn = Convert.ToBoolean(reader.ReadLine());
Tf30MinuteIsOn = Convert.ToBoolean(reader.ReadLine());
Tf1HourIsOn = Convert.ToBoolean(reader.ReadLine());
Tf2HourIsOn = Convert.ToBoolean(reader.ReadLine());
TfTickIsOn = Convert.ToBoolean(reader.ReadLine());
TfMarketDepthIsOn = Convert.ToBoolean(reader.ReadLine());
Enum.TryParse(reader.ReadLine(), out Source);
TimeStart = Convert.ToDateTime(reader.ReadLine());
TimeEnd = Convert.ToDateTime(reader.ReadLine());
Enum.TryParse(reader.ReadLine(), out _selectedTf);
_selectedSecurity = reader.ReadLine();
string[] securities = reader.ReadLine().Split('*');
if (securities.Length != 0)
{
SecuritiesNames = securities.ToList();
SecuritiesNames.RemoveAt(SecuritiesNames.Count - 1);
}
Enum.TryParse(reader.ReadLine(), out CandleCreateType);
MarketDepthDepth = Convert.ToInt32(reader.ReadLine());
NeadToUpdate = Convert.ToBoolean(reader.ReadLine());
NeadToLoadDataInServers = Convert.ToBoolean(reader.ReadLine());
reader.Close();
}
}
catch (Exception)
{
// ignored
}
}
/// <summary>
/// удалить настройки
/// </summary>
public void Delete()
{
if (File.Exists("Data\\" + SetName + @"\\Settings.txt"))
{
File.Delete("Data\\" + SetName + @"\\Settings.txt");
}
if (Directory.Exists("Data\\" + SetName))
{
try
{
DirectoryInfo info = new DirectoryInfo("Data\\" + SetName);
info.Delete(true);
}
catch (Exception)
{
// ignore
}
}
}
/// <summary>
/// показать окно настроек
/// </summary>
public void ShowDialog()
{
OsDataSetUi ui = new OsDataSetUi(this);
ui.ShowDialog();
ReBuildComboBox();
}
/// <summary>
/// режим работы
/// </summary>
public DataSetState Regime
{
set { _regime = value; }
get { return _regime; }
}
private DataSetState _regime;
// управление
/// <summary>
/// подключить новый инструмент
/// </summary>
public void AddNewSecurity()
{
IServer myServer = ServerMaster.GetServers().Find(server => server.ServerType == Source);
if (myServer == null)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent("Источник не настроен", LogMessageType.System);
}
return;
}
List<Security> securities = myServer.Securities;
if (securities == null || securities.Count
== 0)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent("В источнике нет доступных бумаг", LogMessageType.System);
}
return;
}
NewSecurityUi ui = new NewSecurityUi(securities);
ui.ShowDialog();
if (ui.SelectedSecurity != null)
{
if (SecuritiesNames == null)
{
SecuritiesNames = new List<string>();
}
if (SecuritiesNames.Find(s => s == ui.SelectedSecurity.Name) == null)
{
SecuritiesNames.Add(ui.SelectedSecurity.Name);
}
}
Save();
ReBuildComboBox();
}
/// <summary>
/// удалить инструмент для скачивания
/// </summary>
/// <param name="index">индекс инструмента в массиве</param>
public void DeleteSecurity(int index)
{
if (SecuritiesNames == null ||
SecuritiesNames.Count <= index)
{
return;
}
for (int i = 0; _mySeries != null && i < _mySeries.Count; i++)
{
if (_mySeries[i].Security.Name == SecuritiesNames[index])
{
_mySeries[i].Stop();
_mySeries.Remove(_mySeries[i]);
i--;
}
}
SecuritiesNames.RemoveAt(index);
Save();
}
// сохранение данных
/// <summary>
/// серии свечек созданные для скачивания
/// </summary>
private List<CandleSeries> _mySeries;
/// <summary>
/// выбранный сет
/// </summary>
private bool _setIsActive;
/// <summary>
/// сервер к которому подключен сет
/// </summary>
private IServer _myServer;
/// <summary>
/// работа основного потока
/// </summary>
private void WorkerArea()
{
try
{
Thread.Sleep(5000);
LoadSets();
Paint();
while (true)
{
Thread.Sleep(10000);
if (_regime == DataSetState.Off &&
_setIsActive == false)
{
// полностью выключены
continue;
}
if (_regime == DataSetState.Off &&
_setIsActive == true)
{
// пользователь запросил отключить скачивание
_setIsActive = false;
StopSets();
continue;
}
if (_regime == DataSetState.On &&
_setIsActive == false)
{
// пользователь запросил включение
StartSets();
continue;
}
if (_regime == DataSetState.On &&
_setIsActive == true)
{
// тут по идее можно сохранять
SaveData();
}
}
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
private void LoadSets()
{
_candleSaveInfo = new List<CandleSaveInfo>();
for (int i = 0; i < SecuritiesNames.Count; i++)
{
if (Tf1MinuteIsOn)
{
LoadSetsFromFile(SecuritiesNames[i] ,TimeFrame.Min1);
}
if (Tf2MinuteIsOn)
{
LoadSetsFromFile(SecuritiesNames[i] ,TimeFrame.Min2);
}
if (Tf5MinuteIsOn)
{
LoadSetsFromFile(SecuritiesNames[i],TimeFrame.Min5);
}
if (Tf10MinuteIsOn)
{
LoadSetsFromFile(SecuritiesNames[i],TimeFrame.Min10);
}
if (Tf15MinuteIsOn)
{
LoadSetsFromFile(SecuritiesNames[i],TimeFrame.Min15);
}
if (Tf30MinuteIsOn)
{
LoadSetsFromFile(SecuritiesNames[i],TimeFrame.Min30);
}
if (Tf1HourIsOn)
{
LoadSetsFromFile(SecuritiesNames[i],TimeFrame.Hour1);
}
if (Tf2HourIsOn)
{
LoadSetsFromFile(SecuritiesNames[i],TimeFrame.Hour2);
}
if (Tf1SecondIsOn)
{
LoadSetsFromFile(SecuritiesNames[i], TimeFrame.Sec1);
}
if (Tf2SecondIsOn)
{
LoadSetsFromFile(SecuritiesNames[i], TimeFrame.Sec2);
}
if (Tf5SecondIsOn)
{
LoadSetsFromFile(SecuritiesNames[i], TimeFrame.Sec5);
}
if (Tf10SecondIsOn)
{
LoadSetsFromFile(SecuritiesNames[i], TimeFrame.Sec10);
}
if (Tf15SecondIsOn)
{
LoadSetsFromFile(SecuritiesNames[i], TimeFrame.Sec15);
}
if (Tf20SecondIsOn)
{
LoadSetsFromFile(SecuritiesNames[i], TimeFrame.Sec20);
}
if (Tf30SecondIsOn)
{
LoadSetsFromFile(SecuritiesNames[i], TimeFrame.Sec30);
}
}
}
private void LoadSetsFromFile(string securityName, TimeFrame frame)
{
string path = "Data\\" + SetName + "\\" + securityName.Replace("/", "") +"\\" + frame;
if (!Directory.Exists(path))
{
return;
}
CandleSaveInfo candleSaveInfo = new CandleSaveInfo();
candleSaveInfo.Frame = frame;
candleSaveInfo.NameSecurity = securityName;
_candleSaveInfo.Add(candleSaveInfo);
List<Candle> candles = new List<Candle>();
string[] files = Directory.GetFiles(path);
if (files.Length != 0)
{
try
{
using (StreamReader reader = new StreamReader(files[0]))
{
while (!reader.EndOfStream)
{
Candle candle = new Candle();
candle.SetCandleFromString(reader.ReadLine());
candles.Add(candle);
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
}
candleSaveInfo.LoadNewCandles(candles);
if (candles.Count != 0)
{
candleSaveInfo.LastSaveObjectTime = candles[candles.Count - 1].TimeStart;
}
}
/// <summary>
/// создать серии свечек и подписаться на данные
/// </summary>
private void StartSets()
{
// сначала сервер
if (_myServer != null)
{
_myServer.NewMarketDepthEvent -= _myServer_NewMarketDepthEvent;
}
_myServer = ServerMaster.GetServers().Find(server => server.ServerType == Source);
if (_myServer == null || _myServer.ServerStatus == ServerConnectStatus.Disconnect)
{
return;
}
_myServer.NewMarketDepthEvent += _myServer_NewMarketDepthEvent;
// теперь свечи
if (SecuritiesNames == null ||
SecuritiesNames.Count == 0)
{
// проверяем бумаги
return;
}
if (_mySeries != null &&
_mySeries.Count != 0)
{
// убираем старые серии
for (int i = 0; i < _mySeries.Count; i++)
{
_mySeries[i].Stop();
_myServer.StopThisSecurity(_mySeries[i]);
}
}
_mySeries = new List<CandleSeries>();
if (Tf1SecondIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Sec1);
}
}
if (Tf2SecondIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Sec2);
}
}
if (Tf5SecondIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Sec5);
}
}
if (Tf10SecondIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Sec10);
}
}
if (Tf15SecondIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Sec15);
}
}
if (Tf20SecondIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Sec20);
}
}
if (Tf30SecondIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Sec30);
}
}
if (Tf1MinuteIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Min1);
}
}
if (Tf2MinuteIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Min2);
}
}
if (Tf5MinuteIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Min5);
}
}
if (Tf10MinuteIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Min10);
}
}
if (Tf15MinuteIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Min15);
}
}
if (Tf30MinuteIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Min30);
}
}
if (Tf1HourIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Hour1);
}
}
if (Tf2HourIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
StartThis(SecuritiesNames[i], TimeFrame.Hour2);
}
}
if (TfTickIsOn && _myServer != null && _myServer.ServerType == ServerType.Finam)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
while (
((FinamServer) _myServer).StartTickToSecurity(SecuritiesNames[i], TimeStart, TimeEnd,
GetActualTimeToTrade("Data\\" + SetName + "\\" + SecuritiesNames[i].Replace("/", "") + "\\Tick"), NeadToUpdate) == false)
{
Thread.Sleep(5000);
}
}
}
_setIsActive = true;
}
/// <summary>
/// запустить на скачивание
/// </summary>
/// <param name="name">название бумаги</param>
/// <param name="timeFrame">тайм фрейм</param>
private void StartThis(string name, TimeFrame timeFrame)
{
CandleSeries series = null;
while (series == null)
{
TimeFrameBuilder timeFrameBuilder = new TimeFrameBuilder();
timeFrameBuilder.TimeFrame = timeFrame;
if (_myServer.ServerType == ServerType.Finam)
{
series = ((FinamServer)_myServer).StartThisSecurity(name, timeFrameBuilder, TimeStart,
TimeEnd, GetActualTimeToCandle("Data\\" + SetName + "\\" + name.Replace("/", "") + "\\" + timeFrame), NeadToUpdate);
}
else
{
series = _myServer.StartThisSecurity(name, timeFrameBuilder);
}
Thread.Sleep(10);
}
_mySeries.Add(series);
}
/// <summary>
/// остановить скачивание данных
/// </summary>
private void StopSets()
{
// сначала сервер
if (_myServer != null)
{
_myServer.NewMarketDepthEvent -= _myServer_NewMarketDepthEvent;
}
if (_myServer == null)
{
for (int i = 0; _mySeries != null && i < _mySeries.Count; i++)
{
_mySeries[i].Stop();
}
_mySeries = new List<CandleSeries>();
return;
}
// теперь свечи
if (_mySeries != null &&
_mySeries.Count != 0)
{
// убираем старые серии
for (int i = 0; i < _mySeries.Count; i++)
{
_mySeries[i].Stop();
_myServer.StopThisSecurity(_mySeries[i]);
}
}
_mySeries = new List<CandleSeries>();
}
/// <summary>
/// сохранить данные
/// </summary>
private void SaveData()
{
// создаём папки под все инструменты
// Data\Имя сета\Имя бумаги
if (!Directory.Exists("Data"))
{
Directory.CreateDirectory("Data");
}
if (!Directory.Exists("Data\\" + SetName))
{
Directory.CreateDirectory("Data\\" + SetName);
}
for (int i = 0; i < SecuritiesNames.Count; i++)
{
string s = SecuritiesNames[i].Replace("/","");
if (!Directory.Exists("Data\\" + SetName + "\\" + SecuritiesNames[i].Replace("/", "") ))
{
Directory.CreateDirectory("Data\\" + SetName + "\\" + SecuritiesNames[i].Replace("/", ""));
}
}
string pathToSet = "Data\\" + SetName + "\\";
// свечи
for (int i = 0; i < _mySeries.Count; i++)
{
List<Candle> candles = _mySeries[i].CandlesOnlyReady;
if (candles == null || candles.Count == 0)
{
continue;
}
SaveThisCandles(candles, pathToSet + _mySeries[i].Security.Name.Replace("/", "") + "\\" + _mySeries[i].TimeFrame,
_mySeries[i].TimeFrame, _mySeries[i].Security.Name);
}
Paint();
// тики
if (TfTickIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
if (_myServer.ServerType != ServerType.Finam)
{
List<Trade> trades = _myServer.GetAllTradesToSecurity(_myServer.GetSecurityForName(SecuritiesNames[i]));
if (trades == null ||
trades.Count == 0)
{
continue;
}
string path = pathToSet + SecuritiesNames[i].Replace("/", "") ;
for (int i2 = 0; i2 < trades.Count; i2++)
{
SaveThisTick(trades[i2],
path, SecuritiesNames[i], null, path + "\\" + "Tick");
}
}
else
{ // Финам
List<string> trades = ((FinamServer)_myServer).GetAllFilesWhithTradeToSecurity(SecuritiesNames[i]);
SaveThisTickFromFiles(trades,
pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\", SecuritiesNames[i]);
}
}
}
// стаканы
if (TfMarketDepthIsOn)
{
for (int i = 0; i < SecuritiesNames.Count; i++)
{
SaveThisMarketDepth(
pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "MarketDepth", SecuritiesNames[i]);
}
}
if (NeadToLoadDataInServers)
{
if (_lastUpdateTradesInServerTime != DateTime.MinValue &&
_lastUpdateTradesInServerTime.AddSeconds(20) > DateTime.Now)
{
return;
}
_lastUpdateTradesInServerTime = DateTime.Now;
if (!Directory.Exists("Data\\QuikServerTrades"))
{
Directory.CreateDirectory("Data\\QuikServerTrades");
}
if (!Directory.Exists("Data\\SmartComServerTrades"))
{
Directory.CreateDirectory("Data\\SmartComServerTrades");
}
if (!Directory.Exists("Data\\InteractivBrokersServerTrades"))
{
Directory.CreateDirectory("Data\\InteractivBrokersServerTrades");
}
if (!Directory.Exists("Data\\AstsBridgeServerTrades"))
{
Directory.CreateDirectory("Data\\AstsBridgeServerTrades");
}
if (!Directory.Exists("Data\\PlazaServerTrades"))
{
Directory.CreateDirectory("Data\\PlazaServerTrades");
}
for (int i = 0; i < SecuritiesNames.Count; i++)
{
if (
!File.Exists(pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\" +
SecuritiesNames[i].Replace("/", "") + ".txt"))
{
continue;
}
Security sec = _myServer.GetSecurityForName(SecuritiesNames[i]);
string nameSecurityToSave = sec.NameFull.Replace("'", "");
if (File.Exists(pathToSet + SecuritiesNames[i] + "\\" + "Tick" + "\\" +
nameSecurityToSave + ".txt")
&&
File.Exists("Data\\QuikServerTrades\\" + nameSecurityToSave + ".txt"))
{
FileInfo info = new FileInfo(pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\" + nameSecurityToSave + ".txt");
FileInfo info2 = new FileInfo("Data\\QuikServerTrades\\" + nameSecurityToSave + ".txt");
if (info.Length == info2.Length)
{
continue;
}
}
File.Delete("Data\\QuikServerTrades\\" + nameSecurityToSave + ".txt");
File.Delete("Data\\SmartComServerTrades\\" + nameSecurityToSave + ".txt");
File.Delete("Data\\InteractivBrokersServerTrades\\" + nameSecurityToSave + ".txt");
File.Delete("Data\\AstsBridgeServerTrades\\" + nameSecurityToSave + ".txt");
File.Delete("Data\\PlazaServerTrades\\" + nameSecurityToSave + ".txt");
File.Copy(pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\" + SecuritiesNames[i].Replace("/", "") + ".txt",
"Data\\QuikServerTrades\\" + nameSecurityToSave + ".txt");
File.Copy(pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\" + SecuritiesNames[i].Replace("/", "") + ".txt",
"Data\\SmartComServerTrades\\" + nameSecurityToSave + ".txt");
File.Copy(pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\" + SecuritiesNames[i].Replace("/", "") + ".txt",
"Data\\InteractivBrokersServerTrades\\" + nameSecurityToSave + ".txt");
File.Copy(pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\" + SecuritiesNames[i].Replace("/", "") + ".txt",
"Data\\AstsBridgeServerTrades\\" + nameSecurityToSave + ".txt");
File.Copy(pathToSet + SecuritiesNames[i].Replace("/", "") + "\\" + "Tick" + "\\" + SecuritiesNames[i].Replace("/", "") + ".txt",
"Data\\PlazaServerTrades\\" + nameSecurityToSave + ".txt");
}
}
}
private DateTime _lastUpdateTradesInServerTime;
/// <summary>
/// взять актуальное время из файла
/// </summary>
/// <param name="pathToFile">путь к файлу</param>
private DateTime GetActualTimeToCandle(string pathToFile)
{
if(!Directory.Exists(pathToFile))
{
return DateTime.MinValue;
}
string[] files = Directory.GetFiles(pathToFile);
if (files.Length != 0)
{
try
{
using (StreamReader reader = new StreamReader(files[0]))
{
string lastStr = "";
while (!reader.EndOfStream)
{
lastStr = reader.ReadLine();
}
if (!string.IsNullOrWhiteSpace(lastStr))
{
Candle candle = new Candle();
candle.SetCandleFromString(lastStr);
return candle.TimeStart;
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
}
return DateTime.MinValue;
}
/// <summary>
/// взять актуальное время из файла
/// </summary>
/// <param name="pathToFile">путь к файлу</param>
private DateTime GetActualTimeToTrade(string pathToFile)
{
if (!Directory.Exists(pathToFile))
{
return DateTime.MinValue;
}
string[] files = Directory.GetFiles(pathToFile);
if (files.Length != 0)
{
try
{
using (StreamReader reader = new StreamReader(files[0]))
{
Trade trade = new Trade();
string str = "";
while (!reader.EndOfStream)
{
str = reader.ReadLine();
}
if (str != "")
{
trade.SetTradeFromString(str);
return trade.Time;
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
}
return DateTime.MinValue;
}
// свечи
/// <summary>
/// сервисная информация для сохранения свечек
/// </summary>
private List<CandleSaveInfo> _candleSaveInfo;
/// <summary>
/// сохранить новые свечеки по инструменту
/// </summary>
/// <param name="candles">свечи</param>
/// <param name="path">путь</param>
/// <param name="frame">таймфрейм</param>
/// <param name="securityName">название инструмента</param>
private void SaveThisCandles(List<Candle> candles, string path, TimeFrame frame, string securityName)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (_candleSaveInfo == null)
{
_candleSaveInfo = new List<CandleSaveInfo>();
}
// берём хранилище свечек
CandleSaveInfo candleSaveInfo =
_candleSaveInfo.Find(info => info.NameSecurity == securityName && info.Frame == frame);
if (candleSaveInfo == null)
{
LoadSetsFromFile(securityName, frame);
candleSaveInfo =
_candleSaveInfo.Find(info => info.NameSecurity == securityName && info.Frame == frame);
}
if (candleSaveInfo == null)
{
// если сохраняем эти свечи в первый раз, пробуем поднять их из файла
candleSaveInfo = new CandleSaveInfo();
candleSaveInfo.Frame = frame;
candleSaveInfo.NameSecurity = securityName;
_candleSaveInfo.Add(candleSaveInfo);
string[] files = Directory.GetFiles(path);
if (files.Length != 0)
{
try
{
using (StreamReader reader = new StreamReader(files[0]))
{
string lastStr = "";
while (!reader.EndOfStream)
{
lastStr = reader.ReadLine();
}
if (!string.IsNullOrWhiteSpace(lastStr))
{
Candle candle = new Candle();
candle.SetCandleFromString(lastStr);
candleSaveInfo.LastSaveObjectTime = candle.TimeStart;
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
}
}
// обновляем свечи в хранилище
candleSaveInfo.LoadNewCandles(candles);
int firstCandle = 0;
for (int i = candles.Count - 1; i > -1; i--)
{
if (candles[i].TimeStart <= candleSaveInfo.LastSaveObjectTime)
{
firstCandle = i + 1;
break;
}
}
// записываем
try
{
using (StreamWriter writer = new StreamWriter(path + "\\" + securityName.Replace("/", "") + ".txt", true))
{
for (int i = firstCandle; i < candles.Count; i++)
{
if (candles[i].TimeStart > TimeEnd)
{
break;
}
if (candles[i].TimeStart == candleSaveInfo.LastSaveObjectTime)
{ // нужно перезаписать последнюю свечку
//writer.Write(candles[i].StringToSave, 1);
}
else
{
writer.WriteLine(candles[i].StringToSave);
}
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
candleSaveInfo.LastSaveObjectTime = candles[candles.Count - 1].TimeStart;
}
// тики
/// <summary>
/// сервисная информация для сохранения свечек
/// </summary>
private List<TradeSaveInfo> _tradeSaveInfo;
/// <summary>
/// сохранить серию тиков
/// </summary>
/// <param name="tradeLast">тики</param>
/// <param name="pathToFolder">путь</param>
/// <param name="securityName">имя бумаги</param>
private void SaveThisTick(Trade tradeLast, string pathToFolder, string securityName, StreamWriter writer, string pathToFile)
{
if (!Directory.Exists(pathToFolder))
{
Directory.CreateDirectory(pathToFolder);
}
if (_tradeSaveInfo == null)
{
_tradeSaveInfo = new List<TradeSaveInfo>();
}
// берём хранилище тиков
TradeSaveInfo tradeSaveInfo =
_tradeSaveInfo.Find(info => info.NameSecurity == securityName);
if (tradeSaveInfo == null)
{
// если сохраняем эти свечи в первый раз, пробуем поднять их из файла
tradeSaveInfo = new TradeSaveInfo();
tradeSaveInfo.NameSecurity = securityName;
_tradeSaveInfo.Add(tradeSaveInfo);
string[] files = Directory.GetFiles(pathToFolder);
if (files.Length != 0 )
{
if (writer != null)
{
writer.Close();
writer = null;
}
try
{
using (StreamReader reader = new StreamReader(files[0]))
{
string str = "";
while (!reader.EndOfStream)
{
str = reader.ReadLine();
}
if (str != "")
{
Trade trade = new Trade();
trade.SetTradeFromString(str);
tradeSaveInfo.LastSaveObjectTime = trade.Time;
tradeSaveInfo.LastTradeId = trade.Id;
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
return;
}
}
}
int firstCandle = 0;
if (tradeSaveInfo.LastSaveObjectTime >
tradeLast.Time ||
(tradeLast.Id != null && tradeLast.Id == tradeSaveInfo.LastTradeId)
)
{
// если у нас старые тики совпадают с новыми.
return;
}
tradeSaveInfo.LastSaveObjectTime = tradeLast.Time;
tradeSaveInfo.LastTradeId = tradeLast.Id;
// записываем
try
{
if (writer != null)
{
writer.WriteLine(tradeLast.GetSaveString());
}
else
{
using (
StreamWriter writer2 =
new StreamWriter(pathToFolder + "\\" + securityName.Replace("/", "") + ".txt", true))
{
writer2.WriteLine(tradeLast.GetSaveString());
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
}
private void SaveThisTickFromFiles(List<string> files, string path, string securityName)
{
Trade newTrade = new Trade();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
for (int i = 0; files != null && i < files.Count; i++)
{
if (files[i] == null)
{
continue;
}
if (_savedTradeFiles.Find(str => str == files[i]) != null &&
files.Count - 1 != i)
{
// уже сохранили этот файл
continue;
}
if (_savedTradeFiles.Find(str => str == files[i]) == null)
{
_savedTradeFiles.Add(files[i]);
}
StreamReader reader = new StreamReader(files[i]);
if ((!reader.EndOfStream))
{
newTrade.SetTradeFromString(reader.ReadLine());
SaveThisTick(newTrade,
path, securityName, null, path + securityName.Replace("/", "") + ".txt");
}
using ( StreamWriter writer =
new StreamWriter(path + securityName.Replace("/", "") + ".txt", true))
{
while (!reader.EndOfStream)
{
newTrade.SetTradeFromString(reader.ReadLine());
if (newTrade.Time.Hour < 10)
{
continue;
}
SaveThisTick(newTrade,
path, securityName, writer, path + securityName.Replace("/", "") + ".txt");
}
}
reader.Close();
}
}
private List<string> _savedTradeFiles = new List<string>();
// стаканы
/// <summary>
/// сервисная информация для сохранения стаканов
/// </summary>
private List<MarketDepthSaveInfo> _marketDepthSaveInfo;
/// <summary>
/// сохранить стаканы по инструменту
/// </summary>
/// <param name="path">путь</param>
/// <param name="securityName">название бумаги</param>
private void SaveThisMarketDepth(string path, string securityName)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (_tradeSaveInfo == null)
{
_tradeSaveInfo = new List<TradeSaveInfo>();
}
if (_marketDepthSaveInfo == null)
{
return;
}
MarketDepthSaveInfo marketDepthSave =
_marketDepthSaveInfo.Find(info => info.NameSecurity == securityName);
if (marketDepthSave == null)
{
// если сохраняем эти свечи в первый раз, пробуем поднять их из файла
marketDepthSave = new MarketDepthSaveInfo();
marketDepthSave.NameSecurity = securityName;
_marketDepthSaveInfo.Add(marketDepthSave);
string[] files = Directory.GetFiles(path);
if (files.Length != 0)
{
try
{
using (StreamReader reader = new StreamReader(files[0]))
{
string save = "";
while (!reader.EndOfStream)
{
save = reader.ReadLine();
}
if (save != "")
{
MarketDepth marketDepth = new MarketDepth();
marketDepth.SetMarketDepthFromString(save);
marketDepthSave.LastSaveTime = marketDepth.Time;
marketDepthSave.NameSecurity = securityName;
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
}
}
int firstCandle = 0;
List<MarketDepth> depths = marketDepthSave.MarketDepths;
if (depths == null ||
depths.Count == 0 ||
marketDepthSave.LastSaveTime == depths[depths.Count - 1].Time)
{
// если у нас старые тики совпадают с новыми.
return;
}
for (int i = depths.Count - 1; i > -1; i--)
{
if (depths[i].Time <= marketDepthSave.LastSaveTime)
{
firstCandle = i + 1;
break;
}
}
marketDepthSave.LastSaveTime = depths[depths.Count - 1].Time;
// записываем
try
{
using (StreamWriter writer = new StreamWriter(path + "\\" + securityName.Replace("/", "") + ".txt", true))
{
for (int i = firstCandle; i < depths.Count; i++)
{
writer.WriteLine(depths[i].GetSaveStringToAllDepfh(MarketDepthDepth));
}
}
}
catch (Exception error)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(error.ToString(), LogMessageType.Error);
}
}
}
/// <summary>
/// из сервера пришёл новый стакан
/// </summary>
/// <param name="depth"></param>
private void _myServer_NewMarketDepthEvent(MarketDepth depth)
{
try
{
if (_marketDepthSaveInfo == null)
{
_marketDepthSaveInfo = new List<MarketDepthSaveInfo>();
}
MarketDepthSaveInfo mydDepth = _marketDepthSaveInfo.Find(list => list.NameSecurity == depth.SecurityNameCode);
if (mydDepth == null)
{
return;
}
if (mydDepth.MarketDepths == null)
{
mydDepth.MarketDepths = new List<MarketDepth>();
}
mydDepth.MarketDepths.Add(depth);
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
// прорисовка графика
/// <summary>
/// выбранный таймфрейм
/// </summary>
private TimeFrame _selectedTf;
/// <summary>
/// выбранный инструмент
/// </summary>
private string _selectedSecurity;
/// <summary>
/// мастер прорисовки чарта
/// </summary>
private ChartMaster _chartMaster;
/// <summary>
/// меню выбора инструмента
/// </summary>
private System.Windows.Controls.ComboBox _comboBoxSecurity;
/// <summary>
/// меню выбора таймфрейма
/// </summary>
private System.Windows.Controls.ComboBox _comboBoxTimeFrame;
/// <summary>
/// выбран ли текущий сет для прорисовки
/// </summary>
private bool _isSelected;
/// <summary>
/// событие изменения тайфрейма в меню его выбора
/// </summary>
void _comboBoxTimeFrame_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
try
{
if (_isSelected == false ||
_comboBoxTimeFrame.SelectedItem == null)
{
return;
}
Enum.TryParse(_comboBoxTimeFrame.SelectedItem.ToString(), out _selectedTf);
Paint();
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
/// <summary>
/// событие изменения бумаги в меню его выбора
/// </summary>
void _comboBoxSecurity_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
try
{
if (_isSelected == false ||
_comboBoxSecurity.SelectedItem == null)
{
return;
}
_selectedSecurity = _comboBoxSecurity.SelectedItem.ToString();
_chartMaster.Clear();
Paint();
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
/// <summary>
/// включить прорисовку этого сета
/// </summary>
public void StartPaint(WindowsFormsHost hostChart, Rectangle rectangle)
{
try
{
if (!_comboBoxTimeFrame.Dispatcher.CheckAccess())
{
_comboBoxTimeFrame.Dispatcher.Invoke(new Action<WindowsFormsHost, Rectangle>(StartPaint), hostChart, rectangle);
return;
}
_chartMaster.Clear();
_chartMaster.StartPaint(hostChart, rectangle);
ReBuildComboBox();
_isSelected = true;
Paint();
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
/// <summary>
/// остановить прорисовку этого сета
/// </summary>
public void StopPaint()
{
_chartMaster.StopPaint();
_isSelected = false;
}
/// <summary>
/// перестроить меню выбора
/// </summary>
private void ReBuildComboBox()
{
try
{
_comboBoxTimeFrame.SelectionChanged -= _comboBoxTimeFrame_SelectionChanged;
_comboBoxSecurity.SelectionChanged -= _comboBoxSecurity_SelectionChanged;
_comboBoxTimeFrame.Items.Clear();
if (Tf1HourIsOn)
{
_comboBoxTimeFrame.SelectedItem = TimeFrame.Hour1;
_comboBoxTimeFrame.Items.Add(TimeFrame.Hour1);
}
if (Tf2HourIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Hour2);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Hour2;
}
if (Tf1MinuteIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Min1);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Min1;
}
if (Tf2MinuteIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Min2);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Min2;
}
if (Tf5MinuteIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Min5);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Min5;
}
if (Tf10MinuteIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Min10);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Min10;
}
if (Tf15MinuteIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Min15);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Min15;
}
if (Tf30MinuteIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Min30);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Min30;
}
if (Tf1SecondIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Sec1);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Sec1;
}
if (Tf2SecondIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Sec2);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Sec2;
}
if (Tf5SecondIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Sec5);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Sec5;
}
if (Tf10SecondIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Sec10);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Sec10;
}
if (Tf15SecondIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Sec15);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Sec15;
}
if (Tf20SecondIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Sec20);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Sec20;
}
if (Tf30SecondIsOn)
{
_comboBoxTimeFrame.Items.Add(TimeFrame.Sec30);
_comboBoxTimeFrame.SelectedItem = TimeFrame.Sec30;
}
bool haveTf = false;
for (int i = 0; i < _comboBoxTimeFrame.Items.Count; i++)
{
if (_comboBoxTimeFrame.Items[i].ToString() == _selectedTf.ToString())
{
haveTf = true;
break;
}
}
if (haveTf == true)
{
_comboBoxTimeFrame.SelectedItem = _selectedTf;
}
else if (_comboBoxTimeFrame.Items.Count != 0)
{
Enum.TryParse(_comboBoxTimeFrame.Items[0].ToString(), out _selectedTf);
_comboBoxTimeFrame.SelectedItem = _selectedTf;
}
_comboBoxSecurity.Items.Clear();
for (int i = 0; SecuritiesNames != null && i < SecuritiesNames.Count; i++)
{
_comboBoxSecurity.Items.Add(SecuritiesNames[i]);
}
if (string.IsNullOrWhiteSpace(_selectedSecurity) &&
SecuritiesNames != null && SecuritiesNames.Count != 0)
{
_selectedSecurity = SecuritiesNames[0];
}
if (!string.IsNullOrWhiteSpace(_selectedSecurity))
{
_comboBoxSecurity.SelectedItem = _selectedSecurity;
}
if ((_comboBoxSecurity.SelectedItem == null ||
_comboBoxSecurity.SelectedItem.ToString() == "") &&
SecuritiesNames != null && SecuritiesNames.Count != 0)
{
_selectedSecurity = SecuritiesNames[0];
_comboBoxSecurity.SelectedItem = _selectedSecurity;
}
_comboBoxTimeFrame.SelectionChanged += _comboBoxTimeFrame_SelectionChanged;
_comboBoxSecurity.SelectionChanged += _comboBoxSecurity_SelectionChanged;
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
/// <summary>
/// прорисовать выбранный инстрмент и ТФ на графике
/// </summary>
private void Paint()
{
try
{
if (_candleSaveInfo == null)
{
return;
}
if (_isSelected == false ||
_selectedSecurity == null)
{
return;
}
CandleSaveInfo series =
_candleSaveInfo.Find(
candleSeries =>
candleSeries.NameSecurity == _selectedSecurity && candleSeries.Frame == _selectedTf);
if (series == null ||
series.Candles == null)
{
return;
}
if (_selectedTf != TimeFrame.Tick &&
_selectedTf != TimeFrame.Sec1 &&
_selectedTf != TimeFrame.Sec2 &&
_selectedTf != TimeFrame.Sec5 &&
_selectedTf != TimeFrame.Sec10 &&
_selectedTf != TimeFrame.Sec15 &&
_selectedTf != TimeFrame.Sec30)
{
_chartMaster.SetCandles(series.Candles);
}
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
// сообщения в лог
/// <summary>
/// выслать новое сообщение на верх
/// </summary>
private void SendNewLogMessage(string message, LogMessageType type)
{
if (NewLogMessageEvent != null)
{
NewLogMessageEvent(message, type);
}
else
{
System.Windows.MessageBox.Show(message);
}
}
/// <summary>
/// выслать новое сообщение в лог
/// </summary>
public event Action<string, LogMessageType> NewLogMessageEvent;
}
/// <summary>
/// статус серии данных
/// </summary>
public enum DataSetState
{
/// <summary>
/// вкл
/// </summary>
On,
/// <summary>
/// выкл
/// </summary>
Off
}
/// <summary>
/// информация для сохранения свечек
/// </summary>
public class CandleSaveInfo
{
/// <summary>
/// имя бумаги
/// </summary>
public string NameSecurity;
/// <summary>
/// таймфрейм
/// </summary>
public TimeFrame Frame;
/// <summary>
/// последнее время сохранения
/// </summary>
public DateTime LastSaveObjectTime;
/// <summary>
/// свечи инструмента
/// </summary>
public List<Candle> Candles;
/// <summary>
/// добавить свечи
/// </summary>
public void LoadNewCandles(List<Candle> candles)
{
if (candles == null || candles.Count == 0)
{
return;
}
if (Candles == null || Candles.Count == 0)
{
Candles = candles;
}
else if (Candles[Candles.Count - 1].TimeStart == candles[candles.Count - 1].TimeStart)
{
Candles[Candles.Count - 1] = candles[candles.Count - 1];
}
else if (Candles[Candles.Count - 1].TimeStart < candles[0].TimeStart)
{
Candles.AddRange(candles);
}
else if (candles[candles.Count - 1].TimeStart < Candles[0].TimeStart)
{
candles.AddRange(Candles);
Candles = candles;
}
else
{
int firstIndex = 0;
for (int i = candles.Count - 1; i > -1; i--)
{
if (Candles[Candles.Count - 1].TimeStart > candles[i].TimeStart)
{
firstIndex = i+1;
break;
}
}
for (int i = firstIndex; i < candles.Count; i++)
{
Candles.Add(candles[i]);
}
}
}
}
/// <summary>
/// информация для сохранения тиков
/// </summary>
public class TradeSaveInfo
{
/// <summary>
/// имя бумаги
/// </summary>
public string NameSecurity;
/// <summary>
/// последнее время сохранения
/// </summary>
public DateTime LastSaveObjectTime;
/// <summary>
/// последний Id трейда который мы сохранили
/// </summary>
public string LastTradeId;
/// <summary>
/// последнее сохранённый индекс
/// </summary>
public int LastSaveIndex;
}
/// <summary>
/// информация для сохранения стаканов
/// </summary>
public class MarketDepthSaveInfo
{
/// <summary>
/// название бумаги
/// </summary>
public string NameSecurity;
/// <summary>
/// коллекция стаканов по инструменту
/// </summary>
public List<MarketDepth> MarketDepths;
/// <summary>
/// последнее время сохранения
/// </summary>
public DateTime LastSaveTime;
}
}
| 32.715251 | 155 | 0.445682 | [
"Apache-2.0"
] | Schuft/OsEngine-Schuft | project/OsEngine/OsData/OsDataSet.cs | 70,985 | C# |
using System;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using CacheManager.Core;
using CacheManager.Core.Configuration;
using CacheManager.Core.Internal;
using FluentAssertions;
using Xunit;
namespace CacheManager.RedisAsync.Tests
{
/// <summary>
/// To run the test, the app.config of the test project must at least contain a cacheManager section.
/// </summary>
[ExcludeFromCodeCoverage]
public class InvalidConfigurationValidationTests
{
[Fact]
[ReplaceCulture]
public void Cfg_BuildConfiguration_MissingSettings()
{
// arrange act
Action act = () => ConfigurationBuilder.BuildConfiguration(null);
// assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Parameter name: settings");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfiguration_EmptyString()
{
// arrange
string cfgName = string.Empty;
// act
Action act = () => ConfigurationBuilder.LoadConfiguration(cfgName);
// assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Parameter name: configName");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfiguration_NullString()
{
// arrange
string cfgName = null;
// act
Action act = () => ConfigurationBuilder.LoadConfiguration(cfgName);
// assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Parameter name: configName");
}
#if !NO_APP_CONFIG
[Fact]
[ReplaceCulture]
[Trait("category", "NotOnMono")]
public void Cfg_LoadConfiguration_NotExistingCacheCfgName()
{
// arrange
string cfgName = Guid.NewGuid().ToString();
// act
Action act = () => ConfigurationBuilder.LoadConfiguration(cfgName);
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("No cache manager configuration found for name*");
}
#endif
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfiguration_InvalidSectionName()
{
// arrange act
Action act = () => ConfigurationBuilder.LoadConfiguration(null, "config");
// assert
act.Should().Throw<ArgumentNullException>()
.WithMessage("*Parameter name: sectionName*");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfiguration_InvalidConfigName()
{
// arrange act
Action act = () => ConfigurationBuilder.LoadConfiguration("cacheManager", string.Empty);
// assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Parameter name: configName*");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfiguration_SectionDoesNotExist()
{
// arrange
var sectionName = Guid.NewGuid().ToString();
// act
Action act = () => ConfigurationBuilder.LoadConfiguration(sectionName, "configName");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("*No section defined with name " + sectionName + ".");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfigurationFile_EmptyCfgFileName()
{
// arrange act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(string.Empty, "configName");
// assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Parameter name: configFileName*");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfigurationFile_EmptySectionName()
{
// arrange act
Action act = () => ConfigurationBuilder.LoadConfigurationFile("file", null, "configName");
// assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Parameter name: sectionName*");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfigurationFile_EmptyConfigName()
{
// arrange act
Action act = () => ConfigurationBuilder.LoadConfigurationFile("file", "section", null);
// assert
act.Should().Throw<ArgumentException>()
.WithMessage("*Parameter name: configName*");
}
[Fact]
[ReplaceCulture]
public void Cfg_LoadConfigurationFile_NotExistingCfgFileName()
{
// arrange
string fileName = "notexistingconfiguration.config";
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Configuration file not found*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_MissingCacheManagerCfgName()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.missingName.config");
// act
var exception = Record.Exception(() => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName"));
// assert
exception.Should().NotBeNull();
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_NoSection()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.noSection.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("No section with name * found in file *");
}
/* handle definition */
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_MissingDefId()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.missingDefId.config");
// act
var exception = Record.Exception(() => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName"));
// assert
exception.Should().NotBeNull();
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_InvalidType()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidType.config");
// act
var exception = Record.Exception(() => CacheFactory.FromConfiguration<object>(
ConfigurationBuilder.LoadConfigurationFile(fileName, "configName")));
// assert
exception.Should().NotBeNull();
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_InvalidType_NumberOfGenericArgs()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidType.config");
// act
var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, "cacheManager2", "configName");
Action act = () => CacheFactory.FromConfiguration<string>(cfg);
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Cache handle type* should not have any generic arguments*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_InvalidType_HandleType()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidType.config");
// act
var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, "cacheManager4", "configName");
Action act = () => CacheFactory.FromConfiguration<object>(cfg);
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Configured cache handle does not implement*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_InvalidType_WrongNumberOfGenericTypeArgs()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidType.config");
// act
var exception = Record.Exception(() => CacheFactory.FromConfiguration<object>(
ConfigurationBuilder.LoadConfigurationFile(fileName, "configName")));
// assert
exception.Should().NotBeNull();
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_NoHandleDef()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.emptyHandleDefinition.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("There are no cache handles defined.");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_CacheManagerWithoutLinkedHandles()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.managerWithoutHandles.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("There are no valid cache handles linked to the cache manager configuration [c1]");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_CacheManagerWithOneInvalidRef()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidRef.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Referenced cache handle [thisRefIsInvalid] cannot be found in cache handles definition.");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_HandleDefInvalidExpirationMode()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidDefExpMode.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<ConfigurationErrorsException>()
.WithMessage("*defaultExpirationMode*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_HandleDefInvalidTimeout()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidDefTimeout.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("The value of the property 'defaultTimeout' cannot be parsed [20Invalid].");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_InvalidExpirationMode()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidExpMode.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("*ThisIsInvalid*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_InvalidEnableStats()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidEnableStats.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<ConfigurationErrorsException>()
.WithMessage("*enableStatistics*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_InvalidEnablePerfCounters()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidEnablePerfCounters.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<ConfigurationErrorsException>()
.WithMessage("*enablePerformanceCounters*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_ManagerInvalidTimeout()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidTimeout.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("The value of the property 'timeout' cannot be parsed [thisisinvalid].");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_ManagerInvalidUpdateMode()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidUpdateMode.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<ConfigurationErrorsException>()
.WithMessage("*updateMode*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_ExpirationModeWithoutTimeout()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.ExpirationWithoutTimeout.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Expiration mode set without a valid timeout specified for handle [h1]");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_MaxRetriesLessThanOne()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.MaxRetries.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Maximum number of retries must be greater than zero.");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_RetryTimeoutLessThanZero()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.RetryTimeout.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Retry timeout must be greater than or equal to zero.");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_BackplaneNameButNoType()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneNameNoType.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Backplane type cannot be null if backplane name is specified.");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_BackplaneTypeButNoName()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneTypeNoName.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("Backplane name cannot be null if backplane type is specified.");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_BackplaneInvalidType()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneTypeNoName.config");
// act
var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, "invalidType");
Action act = () => new BaseCacheManager<string>(cfg);
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("*does not extend from CacheBackplane*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_BackplaneTypeNotFound()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneTypeNoName.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "typeNotFound");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("*Backplane type not found*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_SerializerType_A()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.serializerType.config");
// act
Action act = () => CacheFactory.FromConfiguration<object>(ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"));
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("*must implement " + nameof(ICacheSerializer) + "*");
}
[Fact]
[ReplaceCulture]
public void Cfg_InvalidCfgFile_SerializerType_B()
{
// arrange
string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.serializerType.config");
// act
Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c2");
// assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("*type not found*");
}
[Fact]
[ReplaceCulture]
public void Cfg_CreateConfig_CacheManagerHandleCollection()
{
// arrange act
var col = new CacheManagerHandleCollection()
{
Name = "name",
UpdateMode = CacheUpdateMode.Up,
EnablePerformanceCounters = true,
EnableStatistics = true,
MaximumRetries = 10012,
RetryTimeout = 234,
BackplaneName = "backplane",
BackplaneType = typeof(string).AssemblyQualifiedName
};
// assert
col.Name.Should().Be("name");
col.BackplaneName.Should().Be("backplane");
col.BackplaneType.Should().Be(typeof(string).AssemblyQualifiedName);
col.UpdateMode.Should().Be(CacheUpdateMode.Up);
col.EnablePerformanceCounters.Should().BeTrue();
col.EnableStatistics.Should().BeTrue();
col.MaximumRetries.Should().Be(10012);
col.RetryTimeout.Should().Be(234);
}
[Fact]
[ReplaceCulture]
public void Cfg_CreateConfig_CacheManagerHandle()
{
// arrange act
var col = new CacheManagerHandle()
{
IsBackplaneSource = true,
Name = "name",
ExpirationMode = ExpirationMode.Absolute.ToString(),
Timeout = "22m",
RefHandleId = "ref"
};
// assert
col.Name.Should().Be("name");
col.ExpirationMode.Should().Be(ExpirationMode.Absolute.ToString());
col.Timeout.Should().Be("22m");
col.RefHandleId.Should().Be("ref");
col.IsBackplaneSource.Should().BeTrue();
}
[Fact]
[ReplaceCulture]
public void Cfg_CreateConfig_CacheHandleDefinition()
{
// arrange act
var col = new CacheHandleDefinition()
{
Id = "id",
HandleType = typeof(string),
DefaultTimeout = "22m",
DefaultExpirationMode = ExpirationMode.None
};
// assert
col.Id.Should().Be("id");
col.HandleType.Should().Be(typeof(string));
col.DefaultTimeout.Should().Be("22m");
col.DefaultExpirationMode.Should().Be(ExpirationMode.None);
}
}
}
| 35.045669 | 143 | 0.592073 | [
"ECL-2.0",
"Apache-2.0"
] | mjebrahimi/CacheManager | test/CacheManager.RedisAsync.Tests/InvalidConfigurationValidationTests.cs | 22,256 | C# |
namespace EvidencijaStudenata
{
partial class NoviStudent
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtTim = new System.Windows.Forms.TextBox();
this.lblTim = new System.Windows.Forms.Label();
this.txtNapomena = new System.Windows.Forms.TextBox();
this.lblNapomena = new System.Windows.Forms.Label();
this.txtEmail = new System.Windows.Forms.TextBox();
this.lblEmail = new System.Windows.Forms.Label();
this.btnUredu = new System.Windows.Forms.Button();
this.btnOdustani = new System.Windows.Forms.Button();
this.txtOdabraniModel = new System.Windows.Forms.TextBox();
this.txtStatus = new System.Windows.Forms.TextBox();
this.txtPrezime = new System.Windows.Forms.TextBox();
this.txtIme = new System.Windows.Forms.TextBox();
this.txtId = new System.Windows.Forms.TextBox();
this.lblOdabraniModel = new System.Windows.Forms.Label();
this.lblStatus = new System.Windows.Forms.Label();
this.lblPrezime = new System.Windows.Forms.Label();
this.lblIme = new System.Windows.Forms.Label();
this.lblId = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// txtTim
//
this.txtTim.Location = new System.Drawing.Point(163, 297);
this.txtTim.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtTim.MaxLength = 255;
this.txtTim.Name = "txtTim";
this.txtTim.ReadOnly = true;
this.txtTim.Size = new System.Drawing.Size(260, 22);
this.txtTim.TabIndex = 65;
//
// lblTim
//
this.lblTim.AutoSize = true;
this.lblTim.Location = new System.Drawing.Point(35, 300);
this.lblTim.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblTim.Name = "lblTim";
this.lblTim.Size = new System.Drawing.Size(35, 17);
this.lblTim.TabIndex = 64;
this.lblTim.Text = "Tim:";
//
// txtNapomena
//
this.txtNapomena.Location = new System.Drawing.Point(163, 214);
this.txtNapomena.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtNapomena.MaxLength = 255;
this.txtNapomena.Multiline = true;
this.txtNapomena.Name = "txtNapomena";
this.txtNapomena.Size = new System.Drawing.Size(260, 74);
this.txtNapomena.TabIndex = 53;
//
// lblNapomena
//
this.lblNapomena.AutoSize = true;
this.lblNapomena.Location = new System.Drawing.Point(36, 214);
this.lblNapomena.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblNapomena.Name = "lblNapomena";
this.lblNapomena.Size = new System.Drawing.Size(81, 17);
this.lblNapomena.TabIndex = 63;
this.lblNapomena.Text = "Napomena:";
//
// txtEmail
//
this.txtEmail.Location = new System.Drawing.Point(163, 182);
this.txtEmail.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtEmail.MaxLength = 255;
this.txtEmail.Name = "txtEmail";
this.txtEmail.Size = new System.Drawing.Size(260, 22);
this.txtEmail.TabIndex = 52;
//
// lblEmail
//
this.lblEmail.AutoSize = true;
this.lblEmail.Location = new System.Drawing.Point(35, 186);
this.lblEmail.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblEmail.Name = "lblEmail";
this.lblEmail.Size = new System.Drawing.Size(46, 17);
this.lblEmail.TabIndex = 62;
this.lblEmail.Text = "Email:";
//
// btnUredu
//
this.btnUredu.Location = new System.Drawing.Point(216, 329);
this.btnUredu.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnUredu.Name = "btnUredu";
this.btnUredu.Size = new System.Drawing.Size(100, 28);
this.btnUredu.TabIndex = 54;
this.btnUredu.Text = "Uredu";
this.btnUredu.UseVisualStyleBackColor = true;
this.btnUredu.Click += new System.EventHandler(this.btnUredu_Click);
//
// btnOdustani
//
this.btnOdustani.Location = new System.Drawing.Point(324, 329);
this.btnOdustani.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnOdustani.Name = "btnOdustani";
this.btnOdustani.Size = new System.Drawing.Size(100, 28);
this.btnOdustani.TabIndex = 55;
this.btnOdustani.Text = "Odustani";
this.btnOdustani.UseVisualStyleBackColor = true;
this.btnOdustani.Click += new System.EventHandler(this.btnOdustani_Click);
//
// txtOdabraniModel
//
this.txtOdabraniModel.Location = new System.Drawing.Point(163, 150);
this.txtOdabraniModel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtOdabraniModel.MaxLength = 255;
this.txtOdabraniModel.Name = "txtOdabraniModel";
this.txtOdabraniModel.Size = new System.Drawing.Size(260, 22);
this.txtOdabraniModel.TabIndex = 51;
//
// txtStatus
//
this.txtStatus.Location = new System.Drawing.Point(163, 118);
this.txtStatus.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtStatus.Name = "txtStatus";
this.txtStatus.Size = new System.Drawing.Size(260, 22);
this.txtStatus.TabIndex = 50;
//
// txtPrezime
//
this.txtPrezime.Location = new System.Drawing.Point(163, 86);
this.txtPrezime.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtPrezime.Name = "txtPrezime";
this.txtPrezime.Size = new System.Drawing.Size(260, 22);
this.txtPrezime.TabIndex = 49;
//
// txtIme
//
this.txtIme.Location = new System.Drawing.Point(163, 54);
this.txtIme.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtIme.Name = "txtIme";
this.txtIme.Size = new System.Drawing.Size(260, 22);
this.txtIme.TabIndex = 48;
//
// txtId
//
this.txtId.Location = new System.Drawing.Point(163, 22);
this.txtId.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtId.Name = "txtId";
this.txtId.ReadOnly = true;
this.txtId.Size = new System.Drawing.Size(115, 22);
this.txtId.TabIndex = 61;
//
// lblOdabraniModel
//
this.lblOdabraniModel.AutoSize = true;
this.lblOdabraniModel.Location = new System.Drawing.Point(35, 154);
this.lblOdabraniModel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblOdabraniModel.Name = "lblOdabraniModel";
this.lblOdabraniModel.Size = new System.Drawing.Size(113, 17);
this.lblOdabraniModel.TabIndex = 60;
this.lblOdabraniModel.Text = "Odabrani model:";
//
// lblStatus
//
this.lblStatus.AutoSize = true;
this.lblStatus.Location = new System.Drawing.Point(35, 122);
this.lblStatus.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblStatus.Name = "lblStatus";
this.lblStatus.Size = new System.Drawing.Size(52, 17);
this.lblStatus.TabIndex = 59;
this.lblStatus.Text = "Status:";
//
// lblPrezime
//
this.lblPrezime.AutoSize = true;
this.lblPrezime.Location = new System.Drawing.Point(36, 90);
this.lblPrezime.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblPrezime.Name = "lblPrezime";
this.lblPrezime.Size = new System.Drawing.Size(63, 17);
this.lblPrezime.TabIndex = 58;
this.lblPrezime.Text = "Prezime:";
//
// lblIme
//
this.lblIme.AutoSize = true;
this.lblIme.Location = new System.Drawing.Point(36, 58);
this.lblIme.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblIme.Name = "lblIme";
this.lblIme.Size = new System.Drawing.Size(34, 17);
this.lblIme.TabIndex = 57;
this.lblIme.Text = "Ime:";
//
// lblId
//
this.lblId.AutoSize = true;
this.lblId.Location = new System.Drawing.Point(36, 22);
this.lblId.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblId.Name = "lblId";
this.lblId.Size = new System.Drawing.Size(23, 17);
this.lblId.TabIndex = 56;
this.lblId.Text = "Id:";
//
// NoviStudent
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(459, 389);
this.Controls.Add(this.txtTim);
this.Controls.Add(this.lblTim);
this.Controls.Add(this.txtNapomena);
this.Controls.Add(this.lblNapomena);
this.Controls.Add(this.txtEmail);
this.Controls.Add(this.lblEmail);
this.Controls.Add(this.btnUredu);
this.Controls.Add(this.btnOdustani);
this.Controls.Add(this.txtOdabraniModel);
this.Controls.Add(this.txtStatus);
this.Controls.Add(this.txtPrezime);
this.Controls.Add(this.txtIme);
this.Controls.Add(this.txtId);
this.Controls.Add(this.lblOdabraniModel);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.lblPrezime);
this.Controls.Add(this.lblIme);
this.Controls.Add(this.lblId);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "NoviStudent";
this.Text = "Dodavanje/Izmjena studenta";
this.Load += new System.EventHandler(this.FrmNoviStudent_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtTim;
private System.Windows.Forms.Label lblTim;
private System.Windows.Forms.TextBox txtNapomena;
private System.Windows.Forms.Label lblNapomena;
private System.Windows.Forms.TextBox txtEmail;
private System.Windows.Forms.Label lblEmail;
private System.Windows.Forms.Button btnUredu;
private System.Windows.Forms.Button btnOdustani;
private System.Windows.Forms.TextBox txtOdabraniModel;
private System.Windows.Forms.TextBox txtStatus;
private System.Windows.Forms.TextBox txtPrezime;
private System.Windows.Forms.TextBox txtIme;
private System.Windows.Forms.TextBox txtId;
private System.Windows.Forms.Label lblOdabraniModel;
private System.Windows.Forms.Label lblStatus;
private System.Windows.Forms.Label lblPrezime;
private System.Windows.Forms.Label lblIme;
private System.Windows.Forms.Label lblId;
}
} | 45.643885 | 107 | 0.571203 | [
"MIT"
] | NovakVed/evidencijaStudenata | EvidencijaStudenata/NoviStudent.designer.cs | 12,691 | C# |
// <copyright file="NullRule.cs" company="Automate The Planet Ltd.">
// Copyright 2019 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
namespace RulesDesignPattern
{
public class NullRule : BaseRule
{
public NullRule(System.Action actionToBeExecuted) : base(actionToBeExecuted)
{
}
public override IRuleResult Eval()
{
RuleResult.IsSuccess = true;
return RuleResult;
}
}
} | 37.034483 | 85 | 0.700186 | [
"Apache-2.0"
] | FrancielleWN/AutomateThePlanet-Learning-Series | DesignPatternsInAutomatedTesting-Series/RulesDesignPattern/NullRule.cs | 1,076 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using Stride.Core.Annotations;
namespace Stride.Core.Storage
{
/// <summary>
/// A hash to uniquely identify data.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
#if !STRIDE_ASSEMBLY_PROCESSOR
[DataContract("ObjectId"),Serializable]
#endif
public unsafe partial struct ObjectId : IEquatable<ObjectId>, IComparable<ObjectId>
{
// ***************************************************************
// NOTE: This file is shared with the AssemblyProcessor.
// If this file is modified, the AssemblyProcessor has to be
// recompiled separately. See build\Stride-AssemblyProcessor.sln
// ***************************************************************
// Murmurshash3 ahsh size is 128 bits.
public const int HashSize = 16;
public const int HashStringLength = HashSize * 2;
private const int HashSizeInUInt = HashSize / sizeof(uint);
private const string HexDigits = "0123456789abcdef";
public static readonly ObjectId Empty = new ObjectId();
private uint hash1;
private uint hash2;
private uint hash3;
private uint hash4;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectId"/> struct.
/// </summary>
/// <param name="hash">The hash.</param>
/// <exception cref="System.ArgumentNullException">hash</exception>
/// <exception cref="System.InvalidOperationException">ObjectId value doesn't match expected size.</exception>
public ObjectId([NotNull] byte[] hash)
{
if (hash == null) throw new ArgumentNullException(nameof(hash));
if (hash.Length != HashSize)
throw new InvalidOperationException("ObjectId value doesn't match expected size.");
fixed (byte* hashSource = hash)
{
var hashSourceCurrent = (uint*)hashSource;
hash1 = *hashSourceCurrent++;
hash2 = *hashSourceCurrent++;
hash3 = *hashSourceCurrent++;
hash4 = *hashSourceCurrent;
}
}
public ObjectId(uint hash1, uint hash2, uint hash3, uint hash4)
{
this.hash1 = hash1;
this.hash2 = hash2;
this.hash3 = hash3;
this.hash4 = hash4;
}
public static unsafe explicit operator ObjectId(Guid guid)
{
return *(ObjectId*)&guid;
}
public static ObjectId Combine(ObjectId left, ObjectId right)
{
// Note: we don't carry (probably not worth the performance hit)
return new ObjectId
{
hash1 = left.hash1 * 3 + right.hash1,
hash2 = left.hash2 * 3 + right.hash2,
hash3 = left.hash3 * 3 + right.hash3,
hash4 = left.hash4 * 3 + right.hash4,
};
}
public static void Combine(ref ObjectId left, ref ObjectId right, out ObjectId result)
{
// Note: we don't carry (probably not worth the performance hit)
result = new ObjectId
{
hash1 = left.hash1 * 3 + right.hash1,
hash2 = left.hash2 * 3 + right.hash2,
hash3 = left.hash3 * 3 + right.hash3,
hash4 = left.hash4 * 3 + right.hash4,
};
}
/// <summary>
/// Performs an explicit conversion from <see cref="ObjectId"/> to <see cref="byte[]"/>.
/// </summary>
/// <param name="objectId">The object id.</param>
/// <returns>The result of the conversion.</returns>
[NotNull]
public static explicit operator byte[](ObjectId objectId)
{
var result = new byte[HashSize];
var hashSource = &objectId.hash1;
fixed (byte* hashDest = result)
{
var hashSourceCurrent = (uint*)hashSource;
var hashDestCurrent = (uint*)hashDest;
for (var i = 0; i < HashSizeInUInt; ++i)
*hashDestCurrent++ = *hashSourceCurrent++;
}
return result;
}
/// <summary>
/// Implements the ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(ObjectId left, ObjectId right)
{
return left.Equals(right);
}
/// <summary>
/// Implements the !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(ObjectId left, ObjectId right)
{
return !left.Equals(right);
}
/// <summary>
/// Tries to parse an <see cref="ObjectId"/> from a string.
/// </summary>
/// <param name="input">The input hexa string.</param>
/// <param name="result">The result ObjectId.</param>
/// <returns><c>true</c> if parsing was successfull, <c>false</c> otherwise</returns>
public static bool TryParse([NotNull] string input, out ObjectId result)
{
if (input.Length != HashStringLength)
{
result = Empty;
return false;
}
var hash = new byte[HashSize];
for (var i = 0; i < HashStringLength; i += 2)
{
var c1 = input[i];
var c2 = input[i + 1];
int digit1, digit2;
if (((digit1 = HexDigits.IndexOf(c1)) == -1)
|| ((digit2 = HexDigits.IndexOf(c2)) == -1))
{
result = Empty;
return false;
}
hash[i >> 1] = (byte)((digit1 << 4) | digit2);
}
result = new ObjectId(hash);
return true;
}
/// <inheritdoc/>
public bool Equals(ObjectId other)
{
// Compare content
fixed (uint* xPtr = &hash1)
{
var x1 = xPtr;
var y1 = &other.hash1;
for (var i = 0; i < HashSizeInUInt; ++i)
{
if (*x1++ != *y1++)
return false;
}
}
return true;
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is ObjectId && Equals((ObjectId)obj);
}
/// <inheritdoc/>
public override int GetHashCode()
{
fixed (uint* objPtr = &hash1)
{
var obj1 = (int*)objPtr;
return *obj1;
}
}
/// <inheritdoc/>
public int CompareTo(ObjectId other)
{
// Compare content
fixed (uint* xPtr = &hash1)
{
var x1 = xPtr;
var y1 = &other.hash1;
for (var i = 0; i < HashSizeInUInt; ++i)
{
var compareResult = (*x1++).CompareTo(*y1++);
if (compareResult != 0)
return compareResult;
}
}
return 0;
}
public override string ToString()
{
var c = new char[HashStringLength];
fixed (uint* hashStart = &hash1)
{
var hashBytes = (byte*)hashStart;
for (var i = 0; i < HashStringLength; ++i)
{
var index0 = i >> 1;
var b = (byte)(hashBytes[index0] >> 4);
c[i++] = HexDigits[b];
b = (byte)(hashBytes[index0] & 0x0F);
c[i] = HexDigits[b];
}
}
return new string(c);
}
/// <summary>
/// Gets a <see cref="Guid"/> from this object identifier.
/// </summary>
/// <returns>Guid.</returns>
public Guid ToGuid()
{
fixed (void* hashStart = &hash1)
{
return *(Guid*)hashStart;
}
}
/// <summary>
/// News this instance.
/// </summary>
/// <returns>ObjectId.</returns>
public static ObjectId New()
{
return FromBytes(Guid.NewGuid().ToByteArray());
}
/// <summary>
/// Computes a hash from a byte buffer.
/// </summary>
/// <param name="buffer">The byte buffer.</param>
/// <returns>The hash of the object.</returns>
/// <exception cref="System.ArgumentNullException">buffer</exception>
public static ObjectId FromBytes([NotNull] byte[] buffer)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
return FromBytes(buffer, 0, buffer.Length);
}
/// <summary>
/// Computes a hash from a byte buffer.
/// </summary>
/// <param name="buffer">The byte buffer.</param>
/// <param name="offset">The offset into the buffer.</param>
/// <param name="count">The number of bytes to read from the buffer starting at offset position.</param>
/// <returns>The hash of the object.</returns>
/// <exception cref="System.ArgumentNullException">buffer</exception>
public static ObjectId FromBytes([NotNull] byte[] buffer, int offset, int count)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
var builder = new ObjectIdBuilder();
builder.Write(buffer, offset, count);
return builder.ComputeHash();
}
}
}
| 34.128713 | 163 | 0.501305 | [
"MIT"
] | Alan-love/xenko | sources/core/Stride.Core/Storage/ObjectId.cs | 10,341 | 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.CognitiveServices.Outputs
{
/// <summary>
/// The user owned storage for Cognitive Services account.
/// </summary>
[OutputType]
public sealed class UserOwnedStorageResponse
{
/// <summary>
/// Full resource id of a Microsoft.Storage resource.
/// </summary>
public readonly string? ResourceId;
[OutputConstructor]
private UserOwnedStorageResponse(string? resourceId)
{
ResourceId = resourceId;
}
}
}
| 26.935484 | 81 | 0.664671 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/CognitiveServices/Outputs/UserOwnedStorageResponse.cs | 835 | C# |
using UnityEngine;
public class Ball : MonoBehaviour
{
private Vector3 velocity;
//speed
public float maxX;
public float maxZ;
// Start is called before the first frame update
void Start()
{
velocity = new Vector3(0, 0, -maxZ);
}
// Update is called once per frame
void Update()
{
transform.position += velocity * Time.deltaTime;
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Paddle"))
{
float maxDist = other.transform.localScale.x * 1 * 0.5f + transform.localScale.x * 1 * 0.5f;
float dist = transform.position.x - other.transform.position.x; //actual distance
//normalize distance to -1 to 1
float nDist = dist / maxDist;
velocity = new Vector3(nDist * maxX, velocity.y, -velocity.z);
GetComponent<AudioSource>().Play();
}
else if (other.CompareTag("Breakable"))
{
FindObjectOfType<Paddle>().IncreaseScore();
other.GetComponent<Block>().Hit();
velocity = new Vector3(velocity.x, velocity.y, -velocity.z);
GetComponent<AudioSource>().Play();
}
else if (other.CompareTag("TopWall"))
{
velocity = new Vector3(velocity.x, velocity.y, -velocity.z);
}
else if (other.CompareTag("Wall"))
{
velocity = new Vector3(-velocity.x, velocity.y, velocity.z);
}
else if (other.CompareTag("Finish"))
{
FindObjectOfType<Paddle>().DecreaseLife();
}
}
}
| 28.101695 | 104 | 0.553679 | [
"MIT"
] | NickPfeiffer/Arkanoid | Assets/Ball.cs | 1,658 | C# |
namespace CleanGraphQLApi.Presentation.Tests.Integration.Models.Common;
using System.Text.Json.Serialization;
public partial class Extensions
{
[JsonPropertyName("tracing")]
public Tracing Tracing { get; set; }
}
| 22.3 | 71 | 0.775785 | [
"MIT"
] | hnguyenec/CleanGraphQLApi | tests/Presentation.Tests.Integration/Models/Common/Extensions.cs | 223 | C# |
namespace Builder.Common
{
public class PrintMessages
{
public const string MenuHotDrink = "Hot Drink: {0}";
public const string MenuColdDrink = "Cold Drink: {0}";
public const string MenuDessert = "Dessert: {0}";
public const string FrenchBreakfastMenu = "French Breakfast Menu: ";
public const string ItalianBreakfast = "Italian Breakfast Menu: ";
public const string VehicleType = "Vehicle Type: {0}";
public const string Frame = " Frame: {0}";
public const string Engine = " Engine: {0}";
public const string Wheels = " #Wheels: {0}";
public const string Doors = " #Doors: {0}";
}
}
| 35.894737 | 76 | 0.621701 | [
"MIT"
] | Inseparable7v/Design-Patterns-master | CreationalPatterns/Builder/Builder.Common/PrintMessages.cs | 684 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
namespace EdFi.Ods.AdminApp.Management.Helpers
{
public class AppSettings
{
public string AppStartup { get; set; }
public string DatabaseEngine { get; set; }
public string ApplicationInsightsInstrumentationKey { get; set; }
public string XsdFolder { get; set; }
public string DefaultOdsInstance { get; set; }
public string ProductionApiUrl { get; set; }
public string ApiExternalUrl { get; set; }
public string SecurityMetadataCacheTimeoutMinutes { get; set; }
public string ApiStartupType { get; set; }
public string LocalEducationAgencyTypeValue { get; set; }
public string PostSecondaryInstitutionTypeValue { get; set; }
public string SchoolTypeValue { get; set; }
public string BulkUploadHashCache { get; set; }
public string IdaAADInstance { get; set; }
public string IdaClientId { get; set; }
public string IdaClientSecret { get; set; }
public string IdaTenantId { get; set; }
public string IdaSubscriptionId { get; set; }
public string AwsCurrentVersion { get; set; }
public string Log4NetConfigPath { get; set; }
public string EncryptionKey { get; set; }
public string GoogleAnalyticsMeasurementId { get; set; }
public string ProductRegistrationUrl { get; set; }
}
}
| 45.611111 | 86 | 0.676614 | [
"Apache-2.0"
] | CSR2017/Ed-Fi-ODS-AdminApp | Application/EdFi.Ods.AdminApp.Management/Helpers/AppSettings.cs | 1,642 | C# |
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.IfcBuildingControlsDomain
{
public enum IfcAlarmTypeEnum
{
[Description("An audible alarm.")]
BELL = 1,
[Description("An alarm activation mechanism in which a protective glass has to be broken to ena" +
"ble a button to be pressed.")]
BREAKGLASSBUTTON = 2,
[Description("A visual alarm.")]
LIGHT = 3,
[Description("An alarm activation mechanism in which activation is achieved by a pulling action" +
".")]
MANUALPULLBOX = 4,
[Description("An audible alarm.")]
SIREN = 5,
[Description("An audible alarm.")]
WHISTLE = 6,
[Description("User-defined type.")]
USERDEFINED = -1,
[Description("Undefined type.")]
NOTDEFINED = 0,
}
}
| 25.456522 | 100 | 0.735269 | [
"Unlicense",
"MIT"
] | BuildingSMART/IfcDoc | IfcKit/schemas/IfcBuildingControlsDomain/IfcAlarmTypeEnum.cs | 1,171 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Vodka : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.position += new Vector3(Mathf.Sin(Time.time * 0.2f) * 0.005f, Mathf.Sin(Time.time * 0.2f) * 0.005f, 0);
}
}
| 21.117647 | 122 | 0.671309 | [
"MIT"
] | esenti/minusczterywskalimorswina | MinusCzteryWSkaliMorswina/Assets/Scripts/Vodka.cs | 361 | C# |
namespace Xamarin.Essentials
{
public static partial class Compass
{
internal static bool IsSupported =>
throw ExceptionUtils.NotSupportedOrImplementedException;
internal static void PlatformStart(SensorSpeed sensorSpeed, bool applyLowPassFilter) =>
throw ExceptionUtils.NotSupportedOrImplementedException;
internal static void PlatformStop() =>
throw ExceptionUtils.NotSupportedOrImplementedException;
}
}
| 28.533333 | 89 | 0.817757 | [
"MIT"
] | dhindrik/maui | src/Essentials/src/Xamarin.Essentials/Compass/Compass.netstandard.tvos.watchos.macos.cs | 430 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Tools;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Edit.Compose.Components;
namespace osu.Game.Rulesets.Osu.Edit
{
public class OsuHitObjectComposer : HitObjectComposer<OsuHitObject>
{
public OsuHitObjectComposer(Ruleset ruleset)
: base(ruleset)
{
}
protected override DrawableRuleset<OsuHitObject> CreateDrawableRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
=> new DrawableOsuEditRuleset(ruleset, beatmap, mods);
protected override IReadOnlyList<HitObjectCompositionTool> CompositionTools => new HitObjectCompositionTool[]
{
new HitCircleCompositionTool(),
new SliderCompositionTool(),
new SpinnerCompositionTool()
};
public override SelectionHandler CreateSelectionHandler() => new OsuSelectionHandler();
public override SelectionBlueprint CreateBlueprintFor(DrawableHitObject hitObject)
{
switch (hitObject)
{
case DrawableHitCircle circle:
return new HitCircleSelectionBlueprint(circle);
case DrawableSlider slider:
return new SliderSelectionBlueprint(slider);
case DrawableSpinner spinner:
return new SpinnerSelectionBlueprint(spinner);
}
return base.CreateBlueprintFor(hitObject);
}
protected override DistanceSnapGrid CreateDistanceSnapGrid(IEnumerable<HitObject> selectedHitObjects)
{
var objects = selectedHitObjects.ToList();
if (objects.Count == 0)
return createGrid(h => h.StartTime <= EditorClock.CurrentTime);
double minTime = objects.Min(h => h.StartTime);
return createGrid(h => h.StartTime < minTime, objects.Count + 1);
}
/// <summary>
/// Creates a grid from the last <see cref="HitObject"/> matching a predicate to a target <see cref="HitObject"/>.
/// </summary>
/// <param name="sourceSelector">A predicate that matches <see cref="HitObject"/>s where the grid can start from.
/// Only the last <see cref="HitObject"/> matching the predicate is used.</param>
/// <param name="targetOffset">An offset from the <see cref="HitObject"/> selected via <paramref name="sourceSelector"/> at which the grid should stop.</param>
/// <returns>The <see cref="OsuDistanceSnapGrid"/> from a selected <see cref="HitObject"/> to a target <see cref="HitObject"/>.</returns>
private OsuDistanceSnapGrid createGrid(Func<HitObject, bool> sourceSelector, int targetOffset = 1)
{
if (targetOffset < 1) throw new ArgumentOutOfRangeException(nameof(targetOffset));
int sourceIndex = -1;
for (int i = 0; i < EditorBeatmap.HitObjects.Count; i++)
{
if (!sourceSelector(EditorBeatmap.HitObjects[i]))
break;
sourceIndex = i;
}
if (sourceIndex == -1)
return null;
HitObject sourceObject = EditorBeatmap.HitObjects[sourceIndex];
int targetIndex = sourceIndex + targetOffset;
HitObject targetObject = null;
// Keep advancing the target object while its start time falls before the end time of the source object
while (true)
{
if (targetIndex >= EditorBeatmap.HitObjects.Count)
break;
if (EditorBeatmap.HitObjects[targetIndex].StartTime >= sourceObject.GetEndTime())
{
targetObject = EditorBeatmap.HitObjects[targetIndex];
break;
}
targetIndex++;
}
return new OsuDistanceSnapGrid((OsuHitObject)sourceObject, (OsuHitObject)targetObject);
}
}
}
| 40 | 168 | 0.623093 | [
"MIT"
] | Azn9/osu | osu.Game.Rulesets.Osu/Edit/OsuHitObjectComposer.cs | 4,603 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.