content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using AdventureWorks.Application.DataEngine.Production.WorkOrder.Queries.GetWorkOrders;
using AdventureWorks.Domain;
using MediatR;
using Entities = AdventureWorks.Domain.Entities.Production;
namespace AdventureWorks.Application.DataEngine.Production.WorkOrder.Commands.UpdateWorkOrder
{
public partial class
UpdateWorkOrderSetCommandHandler : IRequestHandler<UpdateWorkOrderSetCommand, List<WorkOrderLookupModel>>
{
private readonly IAdventureWorksContext _context;
private readonly IMediator _mediator;
private readonly IMapper _mapper;
public UpdateWorkOrderSetCommandHandler(IAdventureWorksContext context, IMediator mediator, IMapper mapper)
{
_context = context;
_mediator = mediator;
_mapper = mapper;
}
public async Task<List<WorkOrderLookupModel>> Handle(UpdateWorkOrderSetCommand request,
CancellationToken cancellationToken)
{
var result = new List<WorkOrderLookupModel>();
await using (var transaction = await _context.Database.BeginTransactionAsync(cancellationToken))
{
foreach (var singleRequest in request.Commands)
{
var singleUpdateResult = await _mediator.Send(singleRequest, cancellationToken);
result.Add(singleUpdateResult);
}
await transaction.CommitAsync(cancellationToken);
}
return result;
}
}
} | 37.181818 | 115 | 0.688875 | [
"Unlicense"
] | CodeSwifterGit/adventure-works | src/AdventureWorks.Application/DataEngine/Production/WorkOrder/Commands/UpdateWorkOrder/UpdateWorkOrderSetCommandHandler.cs | 1,636 | C# |
using Newtonsoft.Json;
using ShuftiPro.Enums;
namespace ShuftiPro.Contracts.Abstractions
{
interface IShuftiProFeedbackBase : IShuftiProReference
{
[JsonProperty("event")]
ShuftiProEvent Event { get; set; }
[JsonProperty("country")]
string Country { get; set; }
[JsonProperty("declined_reason", NullValueHandling = NullValueHandling.Ignore)]
string DeclinedReason { get; set; }
[JsonProperty("declined_codes", NullValueHandling = NullValueHandling.Ignore)]
string[] DeclinedCodes { get; set; }
[JsonProperty("services_declined_codes", NullValueHandling = NullValueHandling.Ignore)]
ShuftiProServiceDeclinedCodes ServiceDeclinedCodes { get; set; }
[JsonProperty("error", NullValueHandling = NullValueHandling.Ignore)]
ShuftiProFeedbackError Error { get; set; }
[JsonProperty("verification_result", NullValueHandling = NullValueHandling.Ignore)]
ShuftiProFeedbackResult Result { get; set; }
[JsonProperty("verification_data", NullValueHandling = NullValueHandling.Ignore)]
ShuftiProFeedbackData Data { get; set; }
[JsonProperty("info", NullValueHandling = NullValueHandling.Ignore)]
ShuftiProUserInfo Info { get; set; }
}
}
| 35.777778 | 95 | 0.698758 | [
"MIT"
] | Psmaryan/ShuftiPro.Net | src/ShuftiPro/Contracts/Abstractions/IShuftiProFeedbackBase.cs | 1,290 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class DataConfig_Mineral
{
public readonly string id;
public readonly string name;
public readonly string spriteName;
public int atack;
public int durability;
} | 22.307692 | 38 | 0.768966 | [
"MIT"
] | kompyang/UnityGamePlayPocketLab | CraftRPG/Assets/Scripts/dataConfig/DataConfig_Mineral.cs | 292 | C# |
namespace Hangfire.Configuration
{
public class CreateServerConfiguration
{
public string StorageConnectionString { get; set; }
public string SchemaCreatorConnectionString { get; set; }
public string Name { get; set; }
public string Server { get; set; }
public string Database { get; set; }
public string User { get; set; }
public string Password { get; set; }
public string SchemaCreatorUser { get; set; }
public string SchemaCreatorPassword { get; set; }
public string SchemaName { get; set; }
public string DatabaseProvider { get; set; }
}
} | 33.55 | 65 | 0.611028 | [
"MIT"
] | Teleopti/HangfireConfiguration | Hangfire.Configuration/CreateServerConfiguration.cs | 671 | C# |
using System;
namespace SmtpPilot.Server.Conversation
{
public struct Mailbox : IEquatable<Mailbox>
{
public static Mailbox Parse(ReadOnlySpan<char> mailbox)
{
// Determine address format and limits.
int startLocal = 0, endLocal = 0;
int startDomain = 0, endDomain = 0;
ReadState state = ReadState.None;
for (int i = 0; i < mailbox.Length; i++)
{
state = (state, mailbox[i]) switch
{
(ReadState.None, ' ') => ReadState.None,
(ReadState.None, '<') => ReadState.BeforeLocalPart,
(ReadState.BeforeLocalPart, '"') => UpdateState(ref startLocal, i, ReadState.QuotedLocalPart),
(ReadState.BeforeLocalPart, _) => UpdateState(ref startLocal, i, ReadState.LocalPart),
(ReadState.QuotedLocalPart, '\\') when mailbox[i + 1] >= ' ' && mailbox[i + 1] <= '~' => UpdateState(ref i, 1, ReadState.QuotedLocalPart),
(ReadState.QuotedLocalPart, _) when mailbox[i] != '"' && mailbox[i] != '\\' => ReadState.QuotedLocalPart,
(ReadState.QuotedLocalPart, '"') => ReadState.EndQuotedLocalPart,
(ReadState.EndQuotedLocalPart, '@') => UpdateState(ref endLocal, i, ReadState.StartDomain),
(ReadState.LocalPart, _) when mailbox[i] == '@' => UpdateState(ref endLocal, i, ReadState.StartDomain),
(ReadState.LocalPartDotAllowed, _) when mailbox[i] == '@' => UpdateState(ref endLocal, i, ReadState.StartDomain),
(ReadState.LocalPart, _) when mailbox[i] != '.' => ReadState.LocalPartDotAllowed,
(ReadState.LocalPartDotAllowed, _) when mailbox[i] == '.' => ReadState.LocalPart,
(ReadState.LocalPartDotAllowed, _) when IsAtom(mailbox[i]) => ReadState.LocalPartDotAllowed,
(ReadState.StartDomain, '[') => UpdateState(ref startDomain, i + 1, ReadState.AddressLiteral),
(ReadState.AddressLiteral, '>') => ReadState.Done,
(ReadState.AddressLiteral, ']') => UpdateState(ref endDomain, i, ReadState.AddressLiteral),
(ReadState.AddressLiteral, _) => state,
(ReadState.StartDomain, _) => UpdateState(ref startDomain, i, ReadState.Domain),
(ReadState.Domain, '>') => UpdateState(ref endDomain, i, ReadState.Done),
(ReadState.Domain, ' ') => UpdateState(ref endDomain, i, ReadState.Done),
(ReadState.Domain, _) => state,
(ReadState.Done, _) => state,
(_, _) => throw new Exception($"Exit during {state}:{mailbox[i]}"),
};
}
return new Mailbox
{
Domain = mailbox[startDomain..endDomain].ToString(),
LocalPart = mailbox[startLocal..endLocal].ToString(),
};
static ReadState UpdateState(ref int one, int mod, ReadState newState)
{
one += mod;
return newState;
}
}
private static bool IsAtom(char v)
{
return v switch
{
'!' => true,
'#' => true,
'$' => true,
'&' => true,
'%' => true,
'*' => true,
'+' => true,
'-' => true,
'/' => true,
'=' => true,
'?' => true,
'^' => true,
'_' => true,
'`' => true,
'{' => true,
'}' => true,
'|' => true,
'~' => true,
'\'' => true,
_ when Char.IsLetterOrDigit(v) => true,
_ => false
};
}
public override bool Equals(object obj)
{
return obj is Mailbox mailbox && Equals(mailbox);
}
public bool Equals(Mailbox other)
{
return String.Equals(LocalPart, other.LocalPart, StringComparison.Ordinal) &&
String.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
return StringComparer.Ordinal.GetHashCode(LocalPart) * 31
^ StringComparer.OrdinalIgnoreCase.GetHashCode(Domain) * 17;
}
public string LocalPart { get; private set; }
public string Domain { get; private set; }
public static bool operator ==(Mailbox left, Mailbox right)
{
return left.Equals(right);
}
public static bool operator !=(Mailbox left, Mailbox right)
{
return !(left == right);
}
}
internal enum ReadState
{
None,
BeforeLocalPart,
LocalPart,
LocalPartDotAllowed,
QuotedLocalPart,
EndQuotedLocalPart,
StartDomain,
Domain,
AddressLiteral,
EndAddressLiteral,
Done,
}
}
| 37.280576 | 158 | 0.501158 | [
"MIT"
] | cmcquillan/SMTPileIt | src/SmtpPilot.Server/Conversation/Mailbox.cs | 5,184 | 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("Greetings")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Greetings")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2875c927-b00d-4f41-93a8-387cc61d94a4")]
// 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.594595 | 84 | 0.744069 | [
"MIT"
] | vesopk/Programming-Basics-Problems | DataTypesAndValues/Greetings/Properties/AssemblyInfo.cs | 1,394 | C# |
using System;
using System.Collections.Generic;
namespace TensorShader.Operators.Connection1D {
/// <summary>ストライド逆プーリング</summary>
internal class StrideUnpooling : Operator {
/// <summary>チャネル数</summary>
public int Channels { private set; get; }
/// <summary>ストライド</summary>
public int Stride { private set; get; }
/// <summary>バッチサイズ</summary>
public int Batch { private set; get; }
/// <summary>コンストラクタ</summary>
public StrideUnpooling(int outwidth, int channels, int stride, int batch = 1) {
if (stride < 2) {
throw new ArgumentException(nameof(stride));
}
this.arguments = new List<(ArgumentType type, Shape shape)>{
(ArgumentType.In, Shape.Map1D(channels, outwidth / stride, batch)),
(ArgumentType.Out, Shape.Map1D(channels, outwidth, batch)),
};
this.Channels = channels;
this.Stride = stride;
this.Batch = batch;
}
/// <summary>操作を実行</summary>
public override void Execute(params Tensor[] tensors) {
CheckArgumentShapes(tensors);
Tensor inmap = tensors[0], outmap = tensors[1];
TensorShaderCudaBackend.Pool.StrideUnpool1D((uint)Channels, (uint)outmap.Width, (uint)Batch, (uint)Stride, inmap.Buffer, outmap.Buffer);
}
/// <summary>操作を実行</summary>
public void Execute(Tensor inmap, Tensor outmap) {
Execute(new Tensor[] { inmap, outmap });
}
}
}
| 33.468085 | 148 | 0.588048 | [
"MIT"
] | tk-yoshimura/TensorShader | TensorShader/Operators/Connection1D/Pool/StrideUnpooling.cs | 1,661 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Threading.Tasks;
using Microsoft.DotNet.Interactive;
using Microsoft.DotNet.Interactive.Formatting;
using static Microsoft.DotNet.Interactive.Formatting.PocketViewTags;
namespace ClockExtension
{
public class ClockKernelExtension : IKernelExtension
{
public async Task OnLoadAsync(Kernel kernel)
{
Formatter.Register<DateTime>((date, writer) =>
{
writer.Write(date.DrawSvgClock());
}, "text/html");
Formatter.Register<DateTimeOffset>((date, writer) =>
{
writer.Write(date.DrawSvgClock());
}, "text/html");
var clockCommand = new Command("#!clock", "Displays a clock showing the current or specified time.")
{
new Option<int>(new[]{"-o","--hour"},
"The position of the hour hand"),
new Option<int>(new[]{"-m","--minute"},
"The position of the minute hand"),
new Option<int>(new[]{"-s","--second"},
"The position of the second hand")
};
clockCommand.Handler = CommandHandler.Create(
async (int hour, int minute, int second, KernelInvocationContext context) =>
{
await context.DisplayAsync(SvgClock.DrawSvgClock(hour, minute, second));
});
kernel.AddDirective(clockCommand);
if (KernelInvocationContext.Current is { } context)
{
PocketView view = div(
code(nameof(ClockExtension)),
" is loaded. It adds visualizations for ",
code(typeof(System.DateTime)),
" and ",
code(typeof(System.DateTimeOffset)),
". Try it by running: ",
code("DateTime.Now"),
" or ",
code("#!clock -h")
);
await context.DisplayAsync(view);
}
}
}
} | 36.166667 | 112 | 0.526602 | [
"MIT"
] | AngelusGi/interactive | samples/extensions/ClockExtension/ClockKernelExtension.cs | 2,387 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/timestamp.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.WellKnownTypes {
/// <summary>Holder for reflection information generated from google/protobuf/timestamp.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class TimestampReflection {
#region Descriptor
/// <summary>File descriptor for google/protobuf/timestamp.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TimestampReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJv",
"dG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MY",
"AiABKAVCUQoTY29tLmdvb2dsZS5wcm90b2J1ZkIOVGltZXN0YW1wUHJvdG9Q",
"AaABAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Timestamp), global::Google.Protobuf.WellKnownTypes.Timestamp.Parser, new[]{ "Seconds", "Nanos" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A Timestamp represents a point in time independent of any time zone
/// or calendar, represented as seconds and fractions of seconds at
/// nanosecond resolution in UTC Epoch time. It is encoded using the
/// Proleptic Gregorian Calendar which extends the Gregorian calendar
/// backwards to year one. It is encoded assuming all minutes are 60
/// seconds long, i.e. leap seconds are "smeared" so that no leap second
/// table is needed for interpretation. Range is from
/// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
/// By restricting to that range, we ensure that we can convert to
/// and from RFC 3339 date strings.
/// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
///
/// Example 1: Compute Timestamp from POSIX `time()`.
///
/// Timestamp timestamp;
/// timestamp.set_seconds(time(NULL));
/// timestamp.set_nanos(0);
///
/// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
///
/// struct timeval tv;
/// gettimeofday(&tv, NULL);
///
/// Timestamp timestamp;
/// timestamp.set_seconds(tv.tv_sec);
/// timestamp.set_nanos(tv.tv_usec * 1000);
///
/// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
///
/// FILETIME ft;
/// GetSystemTimeAsFileTime(&ft);
/// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
///
/// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
/// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
/// Timestamp timestamp;
/// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
/// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
///
/// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
///
/// long millis = System.currentTimeMillis();
///
/// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
/// .setNanos((int) ((millis % 1000) * 1000000)).build();
///
/// Example 5: Compute Timestamp from current time in Python.
///
/// now = time.time()
/// seconds = int(now)
/// nanos = int((now - seconds) * 10**9)
/// timestamp = Timestamp(seconds=seconds, nanos=nanos)
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Timestamp : pb::IMessage<Timestamp> {
private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp());
public static pb::MessageParser<Timestamp> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Timestamp() {
OnConstruction();
}
partial void OnConstruction();
public Timestamp(Timestamp other) : this() {
seconds_ = other.seconds_;
nanos_ = other.nanos_;
}
public Timestamp Clone() {
return new Timestamp(this);
}
/// <summary>Field number for the "seconds" field.</summary>
public const int SecondsFieldNumber = 1;
private long seconds_;
/// <summary>
/// Represents seconds of UTC time since Unix epoch
/// 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
/// 9999-12-31T23:59:59Z inclusive.
/// </summary>
public long Seconds {
get { return seconds_; }
set {
seconds_ = value;
}
}
/// <summary>Field number for the "nanos" field.</summary>
public const int NanosFieldNumber = 2;
private int nanos_;
/// <summary>
/// Non-negative fractions of a second at nanosecond resolution. Negative
/// second values with fractions must still have non-negative nanos values
/// that count forward in time. Must be from 0 to 999,999,999
/// inclusive.
/// </summary>
public int Nanos {
get { return nanos_; }
set {
nanos_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Timestamp);
}
public bool Equals(Timestamp other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Seconds != other.Seconds) return false;
if (Nanos != other.Nanos) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Seconds != 0L) hash ^= Seconds.GetHashCode();
if (Nanos != 0) hash ^= Nanos.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Seconds != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(16);
output.WriteInt32(Nanos);
}
}
public int CalculateSize() {
int size = 0;
if (Seconds != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds);
}
if (Nanos != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos);
}
return size;
}
public void MergeFrom(Timestamp other) {
if (other == null) {
return;
}
if (other.Seconds != 0L) {
Seconds = other.Seconds;
}
if (other.Nanos != 0) {
Nanos = other.Nanos;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Seconds = input.ReadInt64();
break;
}
case 16: {
Nanos = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 33.120332 | 200 | 0.628289 | [
"Apache-2.0"
] | daugraph/tensorflow-dev | google/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs | 7,982 | C# |
namespace Improbable.Gdk.Guns
{
public interface IRecoil
{
void Recoil(bool aiming);
void SetRecoilSettings(GunSettings.RecoilSettings hipRecoilSettings,
GunSettings.RecoilSettings aimRecoilSettings);
}
}
| 22.454545 | 76 | 0.700405 | [
"MIT"
] | Dechichi01/gdk-for-unity-fps-starter-project | workers/unity/Packages/com.improbable.gdk.guns/Behaviours/IRecoil.cs | 249 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.DotNet.XHarness.CLI.CommandArguments.Apple;
internal class ListInstalledArgument : SwitchArgument
{
public ListInstalledArgument()
: base("installed", "Lists installed simulators only", false)
{
}
}
| 31.785714 | 71 | 0.748315 | [
"MIT"
] | jkoritzinsky/xharness | src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/ListInstalledArgument.cs | 447 | C# |
using System;
namespace Hubx.Net.Identity
{
public class Class1
{
}
}
| 9.333333 | 27 | 0.619048 | [
"MIT"
] | victorioferrario/hubx-identity | hubx/Hubx.Net.Identity/Class1.cs | 86 | C# |
namespace Model{
public class Subject{
public int? id { get; set; }
public string name { get; set; }
public Subject()
{
}
public Subject(int? id, string name)
{
this.id = id;
this.name = name;
}
}
} | 18.5625 | 44 | 0.444444 | [
"MIT"
] | g-gar/DAL | examples/school/model/src/Subject.cs | 299 | C# |
using System.Linq;
using NSubstitute;
using NUnit.Framework;
using NUnit.VisualStudio.TestAdapter.NUnitEngine;
// ReSharper disable StringLiteralTypo
namespace NUnit.VisualStudio.TestAdapter.Tests.NUnitEngineTests
{
public class NUnitDiscoveryTests
{
private ITestLogger logger;
private IAdapterSettings settings;
private const string FullDiscoveryXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='108'>
<test-suite type='Assembly' id='0-1157' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='108'>
<properties>
<property name='_PID' value='9856' />
<property name='_APPDOMAIN' value='domain-807ad471-CSharpTestDemo.dll' />
</properties>
<test-suite type='TestSuite' id='0-1158' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='108'>
<test-suite type='TestFixture' id='0-1004' name='AsyncTests' fullname='NUnitTestDemo.AsyncTests' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='7'>
<test-case id='0-1007' name='AsyncTaskTestFails' fullname='NUnitTestDemo.AsyncTests.AsyncTaskTestFails' methodname='AsyncTaskTestFails' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='771768390'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1006' name='AsyncTaskTestSucceeds' fullname='NUnitTestDemo.AsyncTests.AsyncTaskTestSucceeds' methodname='AsyncTaskTestSucceeds' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='1918603611'>
<properties>
<property name='Expect' value='Pass' />
</properties>
</test-case>
<test-case id='0-1008' name='AsyncTaskTestThrowsException' fullname='NUnitTestDemo.AsyncTests.AsyncTaskTestThrowsException' methodname='AsyncTaskTestThrowsException' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='1307982736'>
<properties>
<property name='Expect' value='Error' />
</properties>
</test-case>
<test-suite type='ParameterizedMethod' id='0-1012' name='AsyncTaskWithResultFails' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultFails' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Failure' />
</properties>
<test-case id='0-1011' name='AsyncTaskWithResultFails()' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultFails()' methodname='AsyncTaskWithResultFails' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='1830045852' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1010' name='AsyncTaskWithResultSucceeds' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultSucceeds' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1009' name='AsyncTaskWithResultSucceeds()' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultSucceeds()' methodname='AsyncTaskWithResultSucceeds' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='175092178' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1014' name='AsyncTaskWithResultThrowsException' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultThrowsException' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Error' />
</properties>
<test-case id='0-1013' name='AsyncTaskWithResultThrowsException()' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultThrowsException()' methodname='AsyncTaskWithResultThrowsException' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='778775186' />
</test-suite>
<test-case id='0-1005' name='AsyncVoidTestIsInvalid' fullname='NUnitTestDemo.AsyncTests.AsyncVoidTestIsInvalid' methodname='AsyncVoidTestIsInvalid' classname='NUnitTestDemo.AsyncTests' runstate='NotRunnable' seed='1368779348'>
<properties>
<property name='_SKIPREASON' value='Async test method must have non-void return type' />
<property name='Expect' value='Error' />
</properties>
</test-case>
</test-suite>
<test-suite type='TestFixture' id='0-1015' name='ConfigFileTests' fullname='NUnitTestDemo.ConfigFileTests' classname='NUnitTestDemo.ConfigFileTests' runstate='Runnable' testcasecount='2'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1017' name='CanReadConfigFile' fullname='NUnitTestDemo.ConfigFileTests.CanReadConfigFile' methodname='CanReadConfigFile' classname='NUnitTestDemo.ConfigFileTests' runstate='Runnable' seed='676901490' />
<test-case id='0-1016' name='ProperConfigFileIsUsed' fullname='NUnitTestDemo.ConfigFileTests.ProperConfigFileIsUsed' methodname='ProperConfigFileIsUsed' classname='NUnitTestDemo.ConfigFileTests' runstate='Runnable' seed='1953588481' />
</test-suite>
<test-suite type='TestFixture' id='0-1135' name='ExplicitClass' fullname='NUnitTestDemo.ExplicitClass' classname='NUnitTestDemo.ExplicitClass' runstate='Explicit' testcasecount='1'>
<test-case id='0-1136' name='ThisIsIndirectlyExplicit' fullname='NUnitTestDemo.ExplicitClass.ThisIsIndirectlyExplicit' methodname='ThisIsIndirectlyExplicit' classname='NUnitTestDemo.ExplicitClass' runstate='Runnable' seed='1259099403' />
</test-suite>
<test-suite type='TestFixture' id='0-1000' name='FixtureWithApartmentAttributeOnClass' fullname='NUnitTestDemo.FixtureWithApartmentAttributeOnClass' classname='NUnitTestDemo.FixtureWithApartmentAttributeOnClass' runstate='Runnable' testcasecount='1'>
<properties>
<property name='ApartmentState' value='STA' />
</properties>
<test-case id='0-1001' name='TestMethodInSTAFixture' fullname='NUnitTestDemo.FixtureWithApartmentAttributeOnClass.TestMethodInSTAFixture' methodname='TestMethodInSTAFixture' classname='NUnitTestDemo.FixtureWithApartmentAttributeOnClass' runstate='Runnable' seed='1032816623' />
</test-suite>
<test-suite type='TestFixture' id='0-1002' name='FixtureWithApartmentAttributeOnMethod' fullname='NUnitTestDemo.FixtureWithApartmentAttributeOnMethod' classname='NUnitTestDemo.FixtureWithApartmentAttributeOnMethod' runstate='Runnable' testcasecount='1'>
<test-case id='0-1003' name='TestMethodInSTA' fullname='NUnitTestDemo.FixtureWithApartmentAttributeOnMethod.TestMethodInSTA' methodname='TestMethodInSTA' classname='NUnitTestDemo.FixtureWithApartmentAttributeOnMethod' runstate='Runnable' seed='1439800533'>
<properties>
<property name='ApartmentState' value='STA' />
</properties>
</test-case>
</test-suite>
<test-suite type='GenericFixture' id='0-1025' name='GenericTests_IList<TList>' fullname='NUnitTestDemo.GenericTests_IList<TList>' runstate='Runnable' testcasecount='2'>
<test-suite type='TestFixture' id='0-1021' name='GenericTests_IList<ArrayList>' fullname='NUnitTestDemo.GenericTests_IList<ArrayList>' classname='NUnitTestDemo.GenericTests_IList`1' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1022' name='CanAddToList' fullname='NUnitTestDemo.GenericTests_IList<ArrayList>.CanAddToList' methodname='CanAddToList' classname='NUnitTestDemo.GenericTests_IList`1' runstate='Runnable' seed='879941949' />
</test-suite>
<test-suite type='TestFixture' id='0-1023' name='GenericTests_IList<List<Int32>>' fullname='NUnitTestDemo.GenericTests_IList<List<Int32>>' classname='NUnitTestDemo.GenericTests_IList`1' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1024' name='CanAddToList' fullname='NUnitTestDemo.GenericTests_IList<List<Int32>>.CanAddToList' methodname='CanAddToList' classname='NUnitTestDemo.GenericTests_IList`1' runstate='Runnable' seed='2082560719' />
</test-suite>
</test-suite>
<test-suite type='GenericFixture' id='0-1020' name='GenericTests<T>' fullname='NUnitTestDemo.GenericTests<T>' runstate='Runnable' testcasecount='1'>
<test-suite type='TestFixture' id='0-1018' name='GenericTests<Int32>' fullname='NUnitTestDemo.GenericTests<Int32>' classname='NUnitTestDemo.GenericTests`1' runstate='Runnable' testcasecount='1'>
<test-case id='0-1019' name='TestIt' fullname='NUnitTestDemo.GenericTests<Int32>.TestIt' methodname='TestIt' classname='NUnitTestDemo.GenericTests`1' runstate='Runnable' seed='130064420'>
<properties>
<property name='Expect' value='Pass' />
</properties>
</test-case>
</test-suite>
</test-suite>
<test-suite type='TestFixture' id='0-1026' name='InheritedTestDerivedClass' fullname='NUnitTestDemo.InheritedTestDerivedClass' classname='NUnitTestDemo.InheritedTestDerivedClass' runstate='Runnable' testcasecount='1'>
<test-case id='0-1027' name='TestInBaseClass' fullname='NUnitTestDemo.InheritedTestDerivedClass.TestInBaseClass' methodname='TestInBaseClass' classname='NUnitTestDemo.InheritedTestBaseClass' runstate='Runnable' seed='1519764308' />
</test-suite>
<test-suite type='TestFixture' id='0-1028' name='OneTimeSetUpTests' fullname='NUnitTestDemo.OneTimeSetUpTests' classname='NUnitTestDemo.OneTimeSetUpTests' runstate='Runnable' testcasecount='2'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1029' name='Test1' fullname='NUnitTestDemo.OneTimeSetUpTests.Test1' methodname='Test1' classname='NUnitTestDemo.OneTimeSetUpTests' runstate='Runnable' seed='1237452323' />
<test-case id='0-1030' name='Test2' fullname='NUnitTestDemo.OneTimeSetUpTests.Test2' methodname='Test2' classname='NUnitTestDemo.OneTimeSetUpTests' runstate='Runnable' seed='204346535' />
</test-suite>
<test-suite type='ParameterizedFixture' id='0-1151' name='ParameterizedTestFixture' fullname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' testcasecount='6'>
<test-suite type='TestFixture' id='0-1142' name='ParameterizedTestFixture(""hello"",""hello"",""goodbye"")' fullname='NUnitTestDemo.ParameterizedTestFixture(""hello"",""hello"",""goodbye"")' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' testcasecount='2'>
<test-case id='0-1143' name='TestEquality' fullname='NUnitTestDemo.ParameterizedTestFixture(""hello"",""hello"",""goodbye"").TestEquality' methodname='TestEquality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='1603810031' />
<test-case id='0-1144' name='TestInequality' fullname='NUnitTestDemo.ParameterizedTestFixture(""hello"",""hello"",""goodbye"").TestInequality' methodname='TestInequality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='272235298' />
</test-suite>
<test-suite type='TestFixture' id='0-1145' name='ParameterizedTestFixture(""zip"",""zip"")' fullname='NUnitTestDemo.ParameterizedTestFixture(""zip"",""zip"")' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' testcasecount='2'>
<test-case id='0-1146' name='TestEquality' fullname='NUnitTestDemo.ParameterizedTestFixture(""zip"",""zip"").TestEquality' methodname='TestEquality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='297749680' />
<test-case id='0-1147' name='TestInequality' fullname='NUnitTestDemo.ParameterizedTestFixture(""zip"",""zip"").TestInequality' methodname='TestInequality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='270828005' />
</test-suite>
<test-suite type='TestFixture' id='0-1148' name='ParameterizedTestFixture(42,42,99)' fullname='NUnitTestDemo.ParameterizedTestFixture(42,42,99)' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' testcasecount='2'>
<test-case id='0-1149' name='TestEquality' fullname='NUnitTestDemo.ParameterizedTestFixture(42,42,99).TestEquality' methodname='TestEquality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='1055390819' />
<test-case id='0-1150' name='TestInequality' fullname='NUnitTestDemo.ParameterizedTestFixture(42,42,99).TestInequality' methodname='TestInequality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='889637628' />
</test-suite>
</test-suite>
<test-suite type='TestFixture' id='0-1031' name='ParameterizedTests' fullname='NUnitTestDemo.ParameterizedTests' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='23'>
<test-suite type='ParameterizedMethod' id='0-1041' name='TestCaseFails' fullname='NUnitTestDemo.ParameterizedTests.TestCaseFails' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Failure' />
</properties>
<test-case id='0-1040' name='TestCaseFails(31,11,99)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseFails(31,11,99)' methodname='TestCaseFails' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='834237553' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1047' name='TestCaseFails_Result' fullname='NUnitTestDemo.ParameterizedTests.TestCaseFails_Result' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Failure' />
</properties>
<test-case id='0-1046' name='TestCaseFails_Result(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseFails_Result(31,11)' methodname='TestCaseFails_Result' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1915510679' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1061' name='TestCaseIsExplicit' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsExplicit' classname='NUnitTestDemo.ParameterizedTests' runstate='Explicit' testcasecount='1'>
<properties>
<property name='Expect' value='Skipped' />
</properties>
<test-case id='0-1060' name='TestCaseIsExplicit(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsExplicit(31,11)' methodname='TestCaseIsExplicit' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='2121477676' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1055' name='TestCaseIsIgnored_Assert' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsIgnored_Assert' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Ignore' />
</properties>
<test-case id='0-1054' name='TestCaseIsIgnored_Assert(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsIgnored_Assert(31,11)' methodname='TestCaseIsIgnored_Assert' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1371891043' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1051' name='TestCaseIsIgnored_Attribute' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsIgnored_Attribute' classname='NUnitTestDemo.ParameterizedTests' runstate='Ignored' testcasecount='1'>
<properties>
<property name='_SKIPREASON' value='Ignored test' />
<property name='Expect' value='Ignore' />
</properties>
<test-case id='0-1050' name='TestCaseIsIgnored_Attribute(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsIgnored_Attribute(31,11)' methodname='TestCaseIsIgnored_Attribute' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='2018055565' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1053' name='TestCaseIsIgnored_Property' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsIgnored_Property' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Ignore' />
</properties>
<test-case id='0-1052' name='TestCaseIsIgnored_Property(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsIgnored_Property(31,11)' methodname='TestCaseIsIgnored_Property' classname='NUnitTestDemo.ParameterizedTests' runstate='Ignored' seed='458259159'>
<properties>
<property name='_SKIPREASON' value='Ignoring this' />
</properties>
</test-case>
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1049' name='TestCaseIsInconclusive' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsInconclusive' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Inconclusive' />
</properties>
<test-case id='0-1048' name='TestCaseIsInconclusive(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsInconclusive(31,11)' methodname='TestCaseIsInconclusive' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1073275212' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1059' name='TestCaseIsSkipped_Attribute' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsSkipped_Attribute' classname='NUnitTestDemo.ParameterizedTests' runstate='Skipped' testcasecount='1'>
<properties>
<property name='_SKIPREASON' value='Not supported on NET' />
<property name='Expect' value='Skipped' />
</properties>
<test-case id='0-1058' name='TestCaseIsSkipped_Attribute(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsSkipped_Attribute(31,11)' methodname='TestCaseIsSkipped_Attribute' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='712512917' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1057' name='TestCaseIsSkipped_Property' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsSkipped_Property' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Skipped' />
</properties>
<test-case id='0-1056' name='TestCaseIsSkipped_Property(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsSkipped_Property(31,11)' methodname='TestCaseIsSkipped_Property' classname='NUnitTestDemo.ParameterizedTests' runstate='Skipped' seed='750348381'>
<properties>
<property name='_SKIPREASON' value='Not supported on NET' />
</properties>
</test-case>
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1035' name='TestCaseSucceeds' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='3'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1032' name='TestCaseSucceeds(2,2,4)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds(2,2,4)' methodname='TestCaseSucceeds' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='218080466' />
<test-case id='0-1033' name='TestCaseSucceeds(0,5,5)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds(0,5,5)' methodname='TestCaseSucceeds' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='169775980' />
<test-case id='0-1034' name='TestCaseSucceeds(31,11,42)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds(31,11,42)' methodname='TestCaseSucceeds' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1283490061' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1039' name='TestCaseSucceeds_Result' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds_Result' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='3'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1036' name='TestCaseSucceeds_Result(2,2)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds_Result(2,2)' methodname='TestCaseSucceeds_Result' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1501681017' />
<test-case id='0-1037' name='TestCaseSucceeds_Result(0,5)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds_Result(0,5)' methodname='TestCaseSucceeds_Result' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1559240459' />
<test-case id='0-1038' name='TestCaseSucceeds_Result(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseSucceeds_Result(31,11)' methodname='TestCaseSucceeds_Result' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1262629200' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1063' name='TestCaseThrowsException' fullname='NUnitTestDemo.ParameterizedTests.TestCaseThrowsException' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Error' />
</properties>
<test-case id='0-1062' name='TestCaseThrowsException(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseThrowsException(31,11)' methodname='TestCaseThrowsException' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1261348723' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1043' name='TestCaseWarns' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWarns' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Warning' />
</properties>
<test-case id='0-1042' name='TestCaseWarns(31,11,99)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWarns(31,11,99)' methodname='TestCaseWarns' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1417543801' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1045' name='TestCaseWarnsThreeTimes' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWarnsThreeTimes' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Warning' />
</properties>
<test-case id='0-1044' name='TestCaseWarnsThreeTimes(31,11,99)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWarnsThreeTimes(31,11,99)' methodname='TestCaseWarnsThreeTimes' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='271344885' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1065' name='TestCaseWithAlternateName' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWithAlternateName' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1064' name='AlternateTestName' fullname='NUnitTestDemo.ParameterizedTests.AlternateTestName' methodname='TestCaseWithAlternateName' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='450773561' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1069' name='TestCaseWithRandomParameter' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWithRandomParameter' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1068' name='TestCaseWithRandomParameter(1787281192)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWithRandomParameter(1787281192)' methodname='TestCaseWithRandomParameter' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1248901625' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1072' name='TestCaseWithRandomParameterWithFixedNaming' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWithRandomParameterWithFixedNaming' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='2'>
<test-case id='0-1070' name='TestCaseWithRandomParameterWithFixedNaming' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWithRandomParameterWithFixedNaming' methodname='TestCaseWithRandomParameterWithFixedNaming' classname='NUnitTestDemo.ParameterizedTests' runstate='NotRunnable' seed='216518253'>
<properties>
<property name='_SKIPREASON' value='System.Reflection.TargetParameterCountException : Method requires 1 arguments but TestCaseAttribute only supplied 0' />
<property name='_PROVIDERSTACKTRACE' value=' at NUnit.Framework.TestCaseAttribute.GetParametersForTestCase(IMethodInfo method) in D:\a\1\s\src\NUnitFramework\framework\Attributes\TestCaseAttribute.cs:line 329' />
</properties>
</test-case>
<test-case id='0-1071' name='TestCaseWithRandomParameterWithFixedNaming(1325111790)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWithRandomParameterWithFixedNaming(1325111790)' methodname='TestCaseWithRandomParameterWithFixedNaming' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='214923416' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1067' name='TestCaseWithSpecialCharInName' fullname='NUnitTestDemo.ParameterizedTests.TestCaseWithSpecialCharInName' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1066' name='NameWithSpecialChar->Here' fullname='NUnitTestDemo.ParameterizedTests.NameWithSpecialChar->Here' methodname='TestCaseWithSpecialCharInName' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='337857533' />
</test-suite>
</test-suite>
<test-suite type='SetUpFixture' id='0-1152' name='SetUpFixture' fullname='NUnitTestDemo.SetUpFixture.SetUpFixture' classname='NUnitTestDemo.SetUpFixture.SetUpFixture' runstate='Runnable' testcasecount='2'>
<test-suite type='TestFixture' id='0-1153' name='TestFixture1' fullname='NUnitTestDemo.SetUpFixture.TestFixture1' classname='NUnitTestDemo.SetUpFixture.TestFixture1' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1154' name='Test1' fullname='NUnitTestDemo.SetUpFixture.TestFixture1.Test1' methodname='Test1' classname='NUnitTestDemo.SetUpFixture.TestFixture1' runstate='Runnable' seed='56266244' />
</test-suite>
<test-suite type='TestFixture' id='0-1155' name='TestFixture2' fullname='NUnitTestDemo.SetUpFixture.TestFixture2' classname='NUnitTestDemo.SetUpFixture.TestFixture2' runstate='Runnable' testcasecount='1'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1156' name='Test2' fullname='NUnitTestDemo.SetUpFixture.TestFixture2.Test2' methodname='Test2' classname='NUnitTestDemo.SetUpFixture.TestFixture2' runstate='Runnable' seed='1924396815' />
</test-suite>
</test-suite>
<test-suite type='TestFixture' id='0-1073' name='SimpleTests' fullname='NUnitTestDemo.SimpleTests' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' testcasecount='20'>
<test-case id='0-1076' name='TestFails' fullname='NUnitTestDemo.SimpleTests.TestFails' methodname='TestFails' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='664323801'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1083' name='TestFails_StringEquality' fullname='NUnitTestDemo.SimpleTests.TestFails_StringEquality' methodname='TestFails_StringEquality' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1599618939'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1088' name='TestIsExplicit' fullname='NUnitTestDemo.SimpleTests.TestIsExplicit' methodname='TestIsExplicit' classname='NUnitTestDemo.SimpleTests' runstate='Explicit' seed='1554997188'>
<properties>
<property name='Expect' value='Skipped' />
</properties>
</test-case>
<test-case id='0-1086' name='TestIsIgnored_Assert' fullname='NUnitTestDemo.SimpleTests.TestIsIgnored_Assert' methodname='TestIsIgnored_Assert' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1962471277'>
<properties>
<property name='Expect' value='Ignore' />
</properties>
</test-case>
<test-case id='0-1085' name='TestIsIgnored_Attribute' fullname='NUnitTestDemo.SimpleTests.TestIsIgnored_Attribute' methodname='TestIsIgnored_Attribute' classname='NUnitTestDemo.SimpleTests' runstate='Ignored' seed='1497112956'>
<properties>
<property name='_SKIPREASON' value='Ignoring this test deliberately' />
<property name='Expect' value='Ignore' />
</properties>
</test-case>
<test-case id='0-1084' name='TestIsInconclusive' fullname='NUnitTestDemo.SimpleTests.TestIsInconclusive' methodname='TestIsInconclusive' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1420725265'>
<properties>
<property name='Expect' value='Inconclusive' />
</properties>
</test-case>
<test-case id='0-1087' name='TestIsSkipped_Platform' fullname='NUnitTestDemo.SimpleTests.TestIsSkipped_Platform' methodname='TestIsSkipped_Platform' classname='NUnitTestDemo.SimpleTests' runstate='NotRunnable' seed='250061069'>
<properties>
<property name='Expect' value='Skipped' />
<property name='_SKIPREASON' value='Invalid platform name: Exclude=""NET""' />
</properties>
</test-case>
<test-case id='0-1074' name='TestSucceeds' fullname='NUnitTestDemo.SimpleTests.TestSucceeds' methodname='TestSucceeds' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1794834702'>
<properties>
<property name='Expect' value='Pass' />
</properties>
</test-case>
<test-case id='0-1075' name='TestSucceeds_Message' fullname='NUnitTestDemo.SimpleTests.TestSucceeds_Message' methodname='TestSucceeds_Message' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1551974055'>
<properties>
<property name='Expect' value='Pass' />
</properties>
</test-case>
<test-case id='0-1089' name='TestThrowsException' fullname='NUnitTestDemo.SimpleTests.TestThrowsException' methodname='TestThrowsException' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='894649592'>
<properties>
<property name='Expect' value='Error' />
</properties>
</test-case>
<test-case id='0-1077' name='TestWarns' fullname='NUnitTestDemo.SimpleTests.TestWarns' methodname='TestWarns' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='344483815'>
<properties>
<property name='Expect' value='Warning' />
</properties>
</test-case>
<test-case id='0-1078' name='TestWarnsThreeTimes' fullname='NUnitTestDemo.SimpleTests.TestWarnsThreeTimes' methodname='TestWarnsThreeTimes' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1176908295'>
<properties>
<property name='Expect' value='Warning' />
</properties>
</test-case>
<test-case id='0-1092' name='TestWithCategory' fullname='NUnitTestDemo.SimpleTests.TestWithCategory' methodname='TestWithCategory' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1683743891'>
<properties>
<property name='Expect' value='Pass' />
<property name='Category' value='Slow' />
</properties>
</test-case>
<test-case id='0-1081' name='TestWithFailureAndWarning' fullname='NUnitTestDemo.SimpleTests.TestWithFailureAndWarning' methodname='TestWithFailureAndWarning' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='380112843'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1090' name='TestWithProperty' fullname='NUnitTestDemo.SimpleTests.TestWithProperty' methodname='TestWithProperty' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1583983115'>
<properties>
<property name='Expect' value='Pass' />
<property name='Priority' value='High' />
</properties>
</test-case>
<test-case id='0-1079' name='TestWithThreeFailures' fullname='NUnitTestDemo.SimpleTests.TestWithThreeFailures' methodname='TestWithThreeFailures' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1223327733'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1093' name='TestWithTwoCategories' fullname='NUnitTestDemo.SimpleTests.TestWithTwoCategories' methodname='TestWithTwoCategories' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='705800364'>
<properties>
<property name='Expect' value='Pass' />
<property name='Category' value='Slow' />
<property name='Category' value='Data' />
</properties>
</test-case>
<test-case id='0-1080' name='TestWithTwoFailuresAndAnError' fullname='NUnitTestDemo.SimpleTests.TestWithTwoFailuresAndAnError' methodname='TestWithTwoFailuresAndAnError' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='1061304289'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1082' name='TestWithTwoFailuresAndAWarning' fullname='NUnitTestDemo.SimpleTests.TestWithTwoFailuresAndAWarning' methodname='TestWithTwoFailuresAndAWarning' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='982769804'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1091' name='TestWithTwoProperties' fullname='NUnitTestDemo.SimpleTests.TestWithTwoProperties' methodname='TestWithTwoProperties' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='702450911'>
<properties>
<property name='Expect' value='Pass' />
<property name='Priority' value='Low' />
<property name='Action' value='Ignore' />
</properties>
</test-case>
</test-suite>
<test-suite type='TestFixture' id='0-1137' name='TestCaseSourceTests' fullname='NUnitTestDemo.TestCaseSourceTests' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' testcasecount='3'>
<test-suite type='ParameterizedMethod' id='0-1141' name='DivideTest' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' testcasecount='3'>
<test-case id='0-1138' name='DivideTest(12,3)' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest(12,3)' methodname='DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' seed='411915691' />
<test-case id='0-1139' name='DivideTest(12,2)' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest(12,2)' methodname='DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' seed='303613405' />
<test-case id='0-1140' name='DivideTest(12,4)' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest(12,4)' methodname='DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' seed='1073425063' />
</test-suite>
</test-suite>
<test-suite type='TestFixture' id='0-1094' name='TextOutputTests' fullname='NUnitTestDemo.TextOutputTests' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' testcasecount='9'>
<properties>
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1103' name='DisplayTestParameters' fullname='NUnitTestDemo.TextOutputTests.DisplayTestParameters' methodname='DisplayTestParameters' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='1255004500' />
<test-case id='0-1102' name='DisplayTestSettings' fullname='NUnitTestDemo.TextOutputTests.DisplayTestSettings' methodname='DisplayTestSettings' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='2022379752'>
<properties>
<property name='Description' value='Displays various settings for verification' />
</properties>
</test-case>
<test-case id='0-1095' name='WriteToConsole' fullname='NUnitTestDemo.TextOutputTests.WriteToConsole' methodname='WriteToConsole' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='499152285' />
<test-case id='0-1096' name='WriteToError' fullname='NUnitTestDemo.TextOutputTests.WriteToError' methodname='WriteToError' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='148858386' />
<test-case id='0-1097' name='WriteToTestContext' fullname='NUnitTestDemo.TextOutputTests.WriteToTestContext' methodname='WriteToTestContext' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='583572471' />
<test-case id='0-1099' name='WriteToTestContextError' fullname='NUnitTestDemo.TextOutputTests.WriteToTestContextError' methodname='WriteToTestContextError' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='1668790421' />
<test-case id='0-1098' name='WriteToTestContextOut' fullname='NUnitTestDemo.TextOutputTests.WriteToTestContextOut' methodname='WriteToTestContextOut' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='1175978318' />
<test-case id='0-1100' name='WriteToTestContextProgress' fullname='NUnitTestDemo.TextOutputTests.WriteToTestContextProgress' methodname='WriteToTestContextProgress' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='1300651902' />
<test-case id='0-1101' name='WriteToTrace' fullname='NUnitTestDemo.TextOutputTests.WriteToTrace' methodname='WriteToTrace' classname='NUnitTestDemo.TextOutputTests' runstate='Runnable' seed='1132298491' />
</test-suite>
<test-suite type='TestFixture' id='0-1104' name='Theories' fullname='NUnitTestDemo.Theories' classname='NUnitTestDemo.Theories' runstate='Runnable' testcasecount='27'>
<test-suite type='Theory' id='0-1114' name='Theory_AllCasesSucceed' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' testcasecount='9'>
<properties>
<property name='_JOINTYPE' value='Combinatorial' />
<property name='Expect' value='Pass' />
</properties>
<test-case id='0-1105' name='Theory_AllCasesSucceed(0,0)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(0,0)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='517808090' />
<test-case id='0-1106' name='Theory_AllCasesSucceed(0,1)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(0,1)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1765293654' />
<test-case id='0-1107' name='Theory_AllCasesSucceed(0,42)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(0,42)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1811935833' />
<test-case id='0-1108' name='Theory_AllCasesSucceed(1,0)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(1,0)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1966725421' />
<test-case id='0-1109' name='Theory_AllCasesSucceed(1,1)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(1,1)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='605556575' />
<test-case id='0-1110' name='Theory_AllCasesSucceed(1,42)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(1,42)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1040383709' />
<test-case id='0-1111' name='Theory_AllCasesSucceed(42,0)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(42,0)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='657673472' />
<test-case id='0-1112' name='Theory_AllCasesSucceed(42,1)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(42,1)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1042500770' />
<test-case id='0-1113' name='Theory_AllCasesSucceed(42,42)' fullname='NUnitTestDemo.Theories.Theory_AllCasesSucceed(42,42)' methodname='Theory_AllCasesSucceed' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='145107667' />
</test-suite>
<test-suite type='Theory' id='0-1124' name='Theory_SomeCasesAreInconclusive' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' testcasecount='9'>
<properties>
<property name='_JOINTYPE' value='Combinatorial' />
<property name='Expect' value='Mixed' />
</properties>
<test-case id='0-1115' name='Theory_SomeCasesAreInconclusive(0,0)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(0,0)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='856382451' />
<test-case id='0-1116' name='Theory_SomeCasesAreInconclusive(0,1)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(0,1)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='779713124' />
<test-case id='0-1117' name='Theory_SomeCasesAreInconclusive(0,42)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(0,42)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='397402022' />
<test-case id='0-1118' name='Theory_SomeCasesAreInconclusive(1,0)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(1,0)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1716122258' />
<test-case id='0-1119' name='Theory_SomeCasesAreInconclusive(1,1)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(1,1)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='277984056' />
<test-case id='0-1120' name='Theory_SomeCasesAreInconclusive(1,42)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(1,42)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1042633645' />
<test-case id='0-1121' name='Theory_SomeCasesAreInconclusive(42,0)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(42,0)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1484009345' />
<test-case id='0-1122' name='Theory_SomeCasesAreInconclusive(42,1)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(42,1)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1436803723' />
<test-case id='0-1123' name='Theory_SomeCasesAreInconclusive(42,42)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesAreInconclusive(42,42)' methodname='Theory_SomeCasesAreInconclusive' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='266670815' />
</test-suite>
<test-suite type='Theory' id='0-1134' name='Theory_SomeCasesFail' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' testcasecount='9'>
<properties>
<property name='_JOINTYPE' value='Combinatorial' />
<property name='Expect' value='Mixed' />
</properties>
<test-case id='0-1125' name='Theory_SomeCasesFail(0,0)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(0,0)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1942687535' />
<test-case id='0-1126' name='Theory_SomeCasesFail(0,1)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(0,1)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1651837205' />
<test-case id='0-1127' name='Theory_SomeCasesFail(0,42)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(0,42)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='18903538' />
<test-case id='0-1128' name='Theory_SomeCasesFail(1,0)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(1,0)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='65078373' />
<test-case id='0-1129' name='Theory_SomeCasesFail(1,1)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(1,1)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='517378582' />
<test-case id='0-1130' name='Theory_SomeCasesFail(1,42)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(1,42)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1234934953' />
<test-case id='0-1131' name='Theory_SomeCasesFail(42,0)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(42,0)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='1167797098' />
<test-case id='0-1132' name='Theory_SomeCasesFail(42,1)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(42,1)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='195996329' />
<test-case id='0-1133' name='Theory_SomeCasesFail(42,42)' fullname='NUnitTestDemo.Theories.Theory_SomeCasesFail(42,42)' methodname='Theory_SomeCasesFail' classname='NUnitTestDemo.Theories' runstate='Runnable' seed='258037408' />
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[SetUp]
public void SetUp()
{
logger = Substitute.For<ITestLogger>();
settings = Substitute.For<IAdapterSettings>();
settings.DiscoveryMethod.Returns(DiscoveryMethod.Legacy);
}
[Test]
public void ThatWeCanParseDiscoveryXml()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(FullDiscoveryXml)));
Assert.That(ndr.Id, Is.EqualTo("2"));
Assert.That(ndr.TestAssembly, Is.Not.Null, "Missing test assembly");
Assert.That(ndr.TestAssembly.NUnitDiscoveryProperties.Properties.Count(), Is.EqualTo(2));
Assert.That(ndr.TestAssembly.NUnitDiscoveryProperties.AllInternal);
var suite = ndr.TestAssembly.TestSuites.SingleOrDefault();
Assert.That(suite, Is.Not.Null, "No top level suite");
var fixturesCount = suite.TestFixtures.Count();
var genericFixturesCount = suite.GenericFixtures.Count();
var parameterizedFicturesCount = suite.ParameterizedFixtures.Count();
var setupFixturesCount = suite.SetUpFixtures.Count();
Assert.Multiple(() =>
{
Assert.That(fixturesCount, Is.EqualTo(12), nameof(fixturesCount));
Assert.That(genericFixturesCount, Is.EqualTo(2), nameof(genericFixturesCount));
Assert.That(parameterizedFicturesCount, Is.EqualTo(1), nameof(parameterizedFicturesCount));
Assert.That(setupFixturesCount, Is.EqualTo(1), nameof(setupFixturesCount));
});
}
private const string SimpleTestXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='1'>
<test-suite type='Assembly' id='0-1160' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='1'>
<test-suite type='TestSuite' id='0-1161' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='1'>
<test-suite type='TestFixture' id='0-1162' name='SimpleTests' fullname='NUnitTestDemo.SimpleTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1074' name='TestSucceeds' fullname='NUnitTestDemo.SimpleTests.TestSucceeds' methodname='TestSucceeds' classname='NUnitTestDemo.SimpleTests' runstate='Runnable' seed='296066266'>
<properties>
<property name='Category' value='Whatever' />
<property name='Expect' value='Pass' />
</properties>
</test-case>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatTestCaseHasAllData()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(SimpleTestXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
var testCase = topLevelSuite.TestFixtures.First().TestCases.First();
Assert.Multiple(() =>
{
Assert.That(testCase.Id, Is.EqualTo("0-1074"), "Id fails");
Assert.That(testCase.Name, Is.EqualTo("TestSucceeds"), "Name fails");
Assert.That(testCase.FullName, Is.EqualTo("NUnitTestDemo.SimpleTests.TestSucceeds"), "Fullname fails");
Assert.That(testCase.MethodName, Is.EqualTo("TestSucceeds"), "Methodname fails");
Assert.That(testCase.ClassName, Is.EqualTo("NUnitTestDemo.SimpleTests"), "Classname fails");
Assert.That(testCase.RunState, Is.EqualTo(RunStateEnum.Runnable), "Runstate fails");
Assert.That(testCase.Seed, Is.EqualTo(296066266), "Seed fails");
Assert.That(
testCase.NUnitDiscoveryProperties.Properties.Single(o => o.Name == "Category").Value,
Is.EqualTo("Whatever"));
Assert.That(testCase.Parent, Is.Not.Null, "Parent missing");
});
}
[Test]
public void ThatNumberOfTestCasesAreCorrect()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(FullDiscoveryXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
var count = topLevelSuite.TestCaseCount;
Assert.That(count, Is.EqualTo(108));
var actualCount = topLevelSuite.NoOfActualTestCases;
Assert.Multiple(() =>
{
// Special count checks for some
Assert.That(topLevelSuite.GenericFixtures.Sum(o => o.NoOfActualTestCases), Is.EqualTo(3),
"Generic fixtures counts fails in itself");
// Test Case count checks
Assert.That(actualCount, Is.EqualTo(count), "Actual count doesn't match given count");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "AsyncTests").Sum(o => o.NoOfActualTestCases),
Is.EqualTo(7), "Asynctests wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "ConfigFileTests").Sum(o => o.NoOfActualTestCases),
Is.EqualTo(2), "ConfigFileTests wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "ExplicitClass").Sum(o => o.NoOfActualTestCases),
Is.EqualTo(1), "ExplicitClass wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "FixtureWithApartmentAttributeOnClass")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(1), "FixtureWithApartmentAttributeOnClass wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "FixtureWithApartmentAttributeOnMethod")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(1), "FixtureWithApartmentAttributeOnMethod wrong");
Assert.That(
topLevelSuite.GenericFixtures.Where(o => o.Name == "GenericTests_IList<TList>")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(2), "GenericTests_IList<TList> wrong");
Assert.That(
topLevelSuite.GenericFixtures.Where(o => o.Name == "GenericTests<T>")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(1), "GenericTests<T> wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "InheritedTestDerivedClass")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(1), "InheritedTestDerivedClass wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "OneTimeSetUpTests")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(2), "OneTimeSetUpTests wrong");
Assert.That(
topLevelSuite.ParameterizedFixtures.Where(o => o.Name == "ParameterizedTestFixture")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(6), "ParameterizedTestFixture wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "ParameterizedTests")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(23), "ParameterizedTests wrong");
Assert.That(
topLevelSuite.SetUpFixtures.Where(o => o.Name == "SetUpFixture").Sum(o => o.NoOfActualTestCases),
Is.EqualTo(2), "SetUpFixture wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "SimpleTests").Sum(o => o.NoOfActualTestCases),
Is.EqualTo(20), "SimpleTests wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "TestCaseSourceTests")
.Sum(o => o.NoOfActualTestCases),
Is.EqualTo(3), "TestCaseSourceTests wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "TextOutputTests").Sum(o => o.NoOfActualTestCases),
Is.EqualTo(9), "TextOutputTests wrong");
Assert.That(
topLevelSuite.TestFixtures.Where(o => o.Name == "Theories").Sum(o => o.NoOfActualTestCases),
Is.EqualTo(27), "Theories wrong");
});
Assert.That(ndr.TestAssembly.AllTestCases.Count, Is.EqualTo(108));
}
private const string SetupFixtureXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='2'>
<test-suite type='Assembly' id='0-1160' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='2'>
<test-suite type='TestSuite' id='0-1161' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='2'>
<test-suite type='SetUpFixture' id='0-1162' name='SetUpFixture' fullname='NUnitTestDemo.SetUpFixture.SetUpFixture' runstate='Runnable' testcasecount='2'>
<test-suite type='TestFixture' id='0-1163' name='TestFixture1' fullname='NUnitTestDemo.SetUpFixture.TestFixture1' runstate='Runnable' testcasecount='1'>
<test-case id='0-1154' name='Test1' fullname='NUnitTestDemo.SetUpFixture.TestFixture1.Test1' methodname='Test1' classname='NUnitTestDemo.SetUpFixture.TestFixture1' runstate='Runnable' seed='1119121101' />
</test-suite>
<test-suite type='TestFixture' id='0-1164' name='TestFixture2' fullname='NUnitTestDemo.SetUpFixture.TestFixture2' runstate='Runnable' testcasecount='1'>
<test-case id='0-1156' name='Test2' fullname='NUnitTestDemo.SetUpFixture.TestFixture2.Test2' methodname='Test2' classname='NUnitTestDemo.SetUpFixture.TestFixture2' runstate='Runnable' seed='1598200053' />
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatSetUpFixtureWorks()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(SetupFixtureXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
Assert.That(topLevelSuite.SetUpFixtures.Count, Is.EqualTo(1), "Setupfixture count");
foreach (var setupFixture in topLevelSuite.SetUpFixtures)
{
Assert.That(setupFixture.TestFixtures.Count, Is.EqualTo(2), "Test fixtures count");
Assert.That(setupFixture.RunState, Is.EqualTo(RunStateEnum.Runnable),
"Runstate fails for setupfixture");
foreach (var testFixture in setupFixture.TestFixtures)
{
Assert.That(testFixture.RunState, Is.EqualTo(RunStateEnum.Runnable),
"Runstate fails for testFixture");
Assert.That(testFixture.TestCases.Count, Is.EqualTo(1), "Testcase count per fixture");
foreach (var testCase in testFixture.TestCases)
{
Assert.Multiple(() =>
{
Assert.That(testCase.Name, Does.StartWith("Test"), "Name is wrong");
Assert.That(testCase.FullName, Does.StartWith("NUnitTestDemo.SetUpFixture.TestFixture"));
Assert.That(testCase.MethodName, Does.StartWith("Test"), "MethodName is wrong");
Assert.That(testCase.ClassName, Does.StartWith("NUnitTestDemo.SetUpFixture.TestFixture"),
"Name is wrong");
Assert.That(testCase.RunState, Is.EqualTo(RunStateEnum.Runnable),
"Runstate fails for testCase");
Assert.That(testCase.Seed, Is.GreaterThan(0), "Seed missing");
});
}
}
}
}
private const string ParameterizedMethodXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='3'>
<test-suite type='Assembly' id='0-1160' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='3'>
<test-suite type='TestSuite' id='0-1161' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='3'>
<test-suite type='TestFixture' id='0-1162' name='TestCaseSourceTests' fullname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' testcasecount='3'>
<test-suite type='ParameterizedMethod' id='0-1163' name='DivideTest' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' testcasecount='3'>
<test-case id='0-1138' name='DivideTest(12,3)' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest(12,3)' methodname='DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' seed='1090869545' />
<test-case id='0-1139' name='DivideTest(12,2)' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest(12,2)' methodname='DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' seed='1213876025' />
<test-case id='0-1140' name='DivideTest(12,4)' fullname='NUnitTestDemo.TestCaseSourceTests.DivideTest(12,4)' methodname='DivideTest' classname='NUnitTestDemo.TestCaseSourceTests' runstate='Runnable' seed='1587561378' />
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatParameterizedMethodsWorks()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(ParameterizedMethodXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
Assert.That(topLevelSuite.TestCaseCount, Is.EqualTo(3), "Count number from NUnit is wrong");
Assert.That(topLevelSuite.TestFixtures.Count, Is.EqualTo(1), "Missing text fixture");
Assert.That(topLevelSuite.TestFixtures.Single().ParameterizedMethods.Count(), Is.EqualTo(1),
"Missing parameterizedMethod");
Assert.That(
topLevelSuite.TestFixtures.Single().ParameterizedMethods.Single().TestCases.Count,
Is.EqualTo(3));
}
[Test]
public void ThatTheoryWorks()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(FullDiscoveryXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
var theoryFixture = topLevelSuite.TestFixtures.FirstOrDefault(o => o.Name == "Theories");
Assert.That(theoryFixture, Is.Not.Null);
}
private const string ExplicitXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='3'>
<test-suite type='Assembly' id='0-1160' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='3'>
<test-suite type='TestSuite' id='0-1161' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='3'>
<test-suite type='TestFixture' id='0-1162' name='ExplicitClass' fullname='NUnitTestDemo.ExplicitClass' runstate='Explicit' testcasecount='1'>
<test-case id='0-1136' name='ThisIsIndirectlyExplicit' fullname='NUnitTestDemo.ExplicitClass.ThisIsIndirectlyExplicit' methodname='ThisIsIndirectlyExplicit' classname='NUnitTestDemo.ExplicitClass' runstate='Runnable' seed='289706323' />
</test-suite>
<test-suite type='TestFixture' id='0-1163' name='ParameterizedTests' fullname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<test-suite type='ParameterizedMethod' id='0-1164' name='TestCaseIsExplicit' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsExplicit' classname='NUnitTestDemo.ParameterizedTests' runstate='Explicit' testcasecount='1'>
<test-case id='0-1060' name='TestCaseIsExplicit(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsExplicit(31,11)' methodname='TestCaseIsExplicit' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1206901902' />
</test-suite>
</test-suite>
<test-suite type='TestFixture' id='0-1165' name='SimpleTests' fullname='NUnitTestDemo.SimpleTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1088' name='TestIsExplicit' fullname='NUnitTestDemo.SimpleTests.TestIsExplicit' methodname='TestIsExplicit' classname='NUnitTestDemo.SimpleTests' runstate='Explicit' seed='450521388'>
<properties>
<property name='Expect' value='Skipped' />
</properties>
</test-case>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
private const string ExplicitQuickTestXml =
@"<test-run id='0' name='NUnit.VisualStudio.TestAdapter.Tests.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter\src\NUnitTestAdapterTests\bin\Debug\netcoreapp2.1\NUnit.VisualStudio.TestAdapter.Tests.dll' runstate='Runnable' testcasecount='1'>
<test-suite type='Assembly' id='0-1358' name='NUnit.VisualStudio.TestAdapter.Tests.dll' fullname='D:/repos/NUnit/nunit3-vs-adapter/src/NUnitTestAdapterTests/bin/Debug/netcoreapp2.1/NUnit.VisualStudio.TestAdapter.Tests.dll' runstate='Runnable' testcasecount='1'>
<test-suite type='TestSuite' id='0-1359' name='NUnit' fullname='NUnit' runstate='Runnable' testcasecount='1'>
<test-suite type='TestSuite' id='0-1360' name='VisualStudio' fullname='NUnit.VisualStudio' runstate='Runnable' testcasecount='1'>
<test-suite type='TestSuite' id='0-1361' name='TestAdapter' fullname='NUnit.VisualStudio.TestAdapter' runstate='Runnable' testcasecount='1'>
<test-suite type='TestSuite' id='0-1362' name='Tests' fullname='NUnit.VisualStudio.TestAdapter.Tests' runstate='Runnable' testcasecount='1'>
<test-suite type='TestFixture' id='0-1363' name='IssueNo24Tests' fullname='NUnit.VisualStudio.TestAdapter.Tests.IssueNo24Tests' runstate='Explicit' testcasecount='1'>
<test-case id='0-1100' name='Quick' fullname='NUnit.VisualStudio.TestAdapter.Tests.IssueNo24Tests.Quick' methodname='Quick' classname='NUnit.VisualStudio.TestAdapter.Tests.IssueNo24Tests' runstate='Explicit' seed='845750879' />
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[TestCase(ExplicitXml, 3, TestName = nameof(ThatExplicitWorks) + "." + nameof(ExplicitXml))]
public void ThatExplicitWorks(string xml, int count)
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(xml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
Assert.Multiple(() =>
{
var first = topLevelSuite.TestFixtures.First();
Assert.That(first.IsExplicit, $"First {first.Id} failed");
var second = topLevelSuite.TestFixtures.Skip(1).First();
Assert.That(second.IsExplicit, $"Second {first.Id} failed");
var third = topLevelSuite.TestFixtures.Skip(2).First();
Assert.That(third.IsExplicit, $"Third {first.Id} failed");
});
Assert.That(topLevelSuite.IsExplicit, "TopLevelsuite failed");
Assert.That(ndr.TestAssembly.AllTestCases.Count(), Is.EqualTo(count), "Count failed");
Assert.Multiple(() =>
{
foreach (var testCase in ndr.TestAssembly.AllTestCases)
{
Assert.That(testCase.IsExplicitReverse, $"Failed for {testCase.Id}");
}
});
}
[TestCase(ExplicitQuickTestXml, 1, TestName = nameof(ThatExplicitWorks2) + "." + nameof(ExplicitQuickTestXml))]
public void ThatExplicitWorks2(string xml, int count)
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(xml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
Assert.Multiple(() =>
{
Assert.That(topLevelSuite.IsExplicit, "TopLevelsuite failed");
var first = topLevelSuite.TestSuites.First();
Assert.That(first.IsExplicit, $"First {first.Id} failed");
});
Assert.That(ndr.TestAssembly.AllTestCases.Count(), Is.EqualTo(count), "Count failed");
Assert.Multiple(() =>
{
foreach (var testCase in ndr.TestAssembly.AllTestCases)
{
Assert.That(testCase.IsExplicitReverse, $"Failed for {testCase.Id}");
}
});
}
private const string NotExplicitXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='3'>
<test-suite type='Assembly' id='0-1160' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='3'>
<test-suite type='TestSuite' id='0-1161' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='3'>
<test-suite type='TestFixture' id='0-1162' name='ExplicitClass' fullname='NUnitTestDemo.ExplicitClass' runstate='Explicit' testcasecount='1'>
<test-case id='0-1136' name='ThisIsIndirectlyExplicit' fullname='NUnitTestDemo.ExplicitClass.ThisIsIndirectlyExplicit' methodname='ThisIsIndirectlyExplicit' classname='NUnitTestDemo.ExplicitClass' runstate='Runnable' seed='289706323' />
</test-suite>
<test-suite type='TestFixture' id='0-1163' name='ParameterizedTests' fullname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' testcasecount='1'>
<test-suite type='ParameterizedMethod' id='0-1164' name='TestCaseIsExplicit' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsExplicit' classname='NUnitTestDemo.ParameterizedTests' runstate='Explicit' testcasecount='1'>
<test-case id='0-1060' name='TestCaseIsExplicit(31,11)' fullname='NUnitTestDemo.ParameterizedTests.TestCaseIsExplicit(31,11)' methodname='TestCaseIsExplicit' classname='NUnitTestDemo.ParameterizedTests' runstate='Runnable' seed='1206901902' />
</test-suite>
</test-suite>
<test-suite type='TestFixture' id='0-1165' name='SimpleTests' fullname='NUnitTestDemo.SimpleTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1088' name='TestIsExplicit' fullname='NUnitTestDemo.SimpleTests.TestIsExplicit' methodname='TestIsExplicit' classname='NUnitTestDemo.SimpleTests' runstate='Explicit' seed='450521388'>
<properties>
<property name='Expect' value='Skipped' />
</properties>
</test-case>
<test-case id='0-1008' name='RunnableTest' fullname='NUnitTestDemo.AsyncTests.AsyncTaskTestThrowsException' methodname='AsyncTaskTestThrowsException' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='1342062567'>
<properties>
<property name='Expect' value='Error' />
</properties>
</test-case>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatExplicitWorksWhenOneTestIsNotExplicit()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(NotExplicitXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
Assert.That(topLevelSuite.IsExplicit, Is.False);
}
private const string AsyncTestsXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='7'>
<test-suite type='Assembly' id='0-1160' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='7'>
<test-suite type='TestSuite' id='0-1161' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='7'>
<test-suite type='TestFixture' id='0-1162' name='AsyncTests' fullname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='7'>
<test-case id='0-1007' name='AsyncTaskTestFails' fullname='NUnitTestDemo.AsyncTests.AsyncTaskTestFails' methodname='AsyncTaskTestFails' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='564983252'>
<properties>
<property name='Expect' value='Failure' />
</properties>
</test-case>
<test-case id='0-1006' name='AsyncTaskTestSucceeds' fullname='NUnitTestDemo.AsyncTests.AsyncTaskTestSucceeds' methodname='AsyncTaskTestSucceeds' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='1418808408'>
<properties>
<property name='Expect' value='Pass' />
</properties>
</test-case>
<test-case id='0-1008' name='AsyncTaskTestThrowsException' fullname='NUnitTestDemo.AsyncTests.AsyncTaskTestThrowsException' methodname='AsyncTaskTestThrowsException' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='1342062567'>
<properties>
<property name='Expect' value='Error' />
</properties>
</test-case>
<test-suite type='ParameterizedMethod' id='0-1163' name='AsyncTaskWithResultFails' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultFails' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1011' name='AsyncTaskWithResultFails()' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultFails()' methodname='AsyncTaskWithResultFails' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='1018572466' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1164' name='AsyncTaskWithResultSucceeds' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultSucceeds' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1009' name='AsyncTaskWithResultSucceeds()' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultSucceeds()' methodname='AsyncTaskWithResultSucceeds' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='823587191' />
</test-suite>
<test-suite type='ParameterizedMethod' id='0-1165' name='AsyncTaskWithResultThrowsException' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultThrowsException' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' testcasecount='1'>
<test-case id='0-1013' name='AsyncTaskWithResultThrowsException()' fullname='NUnitTestDemo.AsyncTests.AsyncTaskWithResultThrowsException()' methodname='AsyncTaskWithResultThrowsException' classname='NUnitTestDemo.AsyncTests' runstate='Runnable' seed='922873877' />
</test-suite>
<test-case id='0-1005' name='AsyncVoidTestIsInvalid' fullname='NUnitTestDemo.AsyncTests.AsyncVoidTestIsInvalid' methodname='AsyncVoidTestIsInvalid' classname='NUnitTestDemo.AsyncTests' runstate='NotRunnable' seed='691553472'>
<properties>
<property name='_SKIPREASON' value='Async test method must have non-void return type' />
<property name='Expect' value='Error' />
</properties>
</test-case>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatAsyncTestsHasSevenTests()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(AsyncTestsXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
Assert.That(topLevelSuite.NoOfActualTestCases, Is.EqualTo(7));
}
private const string ParameterizedTestFixtureXml =
@"<test-run id='2' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' testcasecount='6'>
<test-suite type='Assembly' id='0-1160' name='CSharpTestDemo.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter-demo\solutions\vs2017\CSharpTestDemo\bin\Debug\CSharpTestDemo.dll' runstate='Runnable' testcasecount='6'>
<test-suite type='TestSuite' id='0-1161' name='NUnitTestDemo' fullname='NUnitTestDemo' runstate='Runnable' testcasecount='6'>
<test-suite type='ParameterizedFixture' id='0-1162' name='ParameterizedTestFixture' fullname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' testcasecount='6'>
<test-suite type='TestFixture' id='0-1163' name='ParameterizedTestFixture(""hello"",""hello"",""goodbye"")' fullname='NUnitTestDemo.ParameterizedTestFixture(""hello"",""hello"",""goodbye"")' runstate='Runnable' testcasecount='2'>
<test-case id='0-1143' name='TestEquality' fullname='NUnitTestDemo.ParameterizedTestFixture(""hello"",""hello"",""goodbye"").TestEquality' methodname='TestEquality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='1153785709' />
<test-case id='0-1144' name='TestInequality' fullname='NUnitTestDemo.ParameterizedTestFixture(""hello"",""hello"",""goodbye"").TestInequality' methodname='TestInequality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='336594823' />
</test-suite>
<test-suite type='TestFixture' id='0-1164' name='ParameterizedTestFixture(""zip"",""zip"")' fullname='NUnitTestDemo.ParameterizedTestFixture(""zip"",""zip"")' runstate='Runnable' testcasecount='2'>
<test-case id='0-1146' name='TestEquality' fullname='NUnitTestDemo.ParameterizedTestFixture(""zip"",""zip"").TestEquality' methodname='TestEquality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='176412041' />
<test-case id='0-1147' name='TestInequality' fullname='NUnitTestDemo.ParameterizedTestFixture(""zip"",""zip"").TestInequality' methodname='TestInequality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='872346411' />
</test-suite>
<test-suite type='TestFixture' id='0-1165' name='ParameterizedTestFixture(42,42,99)' fullname='NUnitTestDemo.ParameterizedTestFixture(42,42,99)' runstate='Runnable' testcasecount='2'>
<test-case id='0-1149' name='TestEquality' fullname='NUnitTestDemo.ParameterizedTestFixture(42,42,99).TestEquality' methodname='TestEquality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='1898578770' />
<test-case id='0-1150' name='TestInequality' fullname='NUnitTestDemo.ParameterizedTestFixture(42,42,99).TestInequality' methodname='TestInequality' classname='NUnitTestDemo.ParameterizedTestFixture' runstate='Runnable' seed='590170168' />
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatParameterizedTestFixtureHasSixTests()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(ParameterizedTestFixtureXml)));
var topLevelSuite = ndr.TestAssembly.TestSuites.Single();
Assert.That(topLevelSuite.NoOfActualTestCases, Is.EqualTo(6));
}
private const string DotnetXml =
@"<test-run id='2' name='Filtering.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter.issues\Issue497\bin\Debug\net461\Filtering.dll' testcasecount='20000'>
<test-suite type='Assembly' id='0-21501' name='Filtering.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter.issues\Issue497\bin\Debug\net461\Filtering.dll' runstate='Runnable' testcasecount='20000'>
<properties>
<property name='Something' value='Foo' />
</properties>
<test-suite type='TestSuite' id='0-21506' name='Filtering' fullname='Filtering' runstate='Runnable' testcasecount='2'>
<test-suite type='TestFixture' id='0-21507' name='ANonGeneratedExplicitTest' fullname='Filtering.ANonGeneratedExplicitTest' runstate='Runnable' testcasecount='2'>
<test-case id='0-21511' name='TestExplicitTest' fullname='Filtering.ANonGeneratedExplicitTest.TestExplicitTest' methodname='TestExplicitTest' classname='Filtering.ANonGeneratedExplicitTest' runstate='Explicit' seed='154804577' />
<test-case id='0-21512' name='TestNotExplicitTest' fullname='Filtering.ANonGeneratedExplicitTest.TestNotExplicitTest' methodname='TestNotExplicitTest' classname='Filtering.ANonGeneratedExplicitTest' runstate='Runnable' seed='334435265' />
</test-suite>
</test-suite>
<test-suite type='TestFixture' id='0-21502' name='GeneratedTest0' fullname='GeneratedTest0' runstate='Runnable' testcasecount='40'>
<properties>
<property name='SomethingElse' value='FooToo' />
</properties>
<test-case id='0-1001' name='Test1' fullname='GeneratedTest0.Test1' methodname='Test1' classname='GeneratedTest0' runstate='Runnable' seed='1044071786'>
<properties>
<property name='Category' value='Foo' />
</properties>
</test-case>
<test-case id='0-1010' name='Test10' fullname='GeneratedTest0.Test10' methodname='Test10' classname='GeneratedTest0' runstate='Runnable' seed='117332475' />
<test-case id='0-1011' name='Test11' fullname='GeneratedTest0.Test11' methodname='Test11' classname='GeneratedTest0' runstate='Runnable' seed='12294536' />
</test-suite>
<test-suite type='TestFixture' id='0-21503' name='GeneratedTest1' fullname='GeneratedTest1' runstate='Runnable' testcasecount='40'>
<test-case id='0-1042' name='Test1' fullname='GeneratedTest1.Test1' methodname='Test1' classname='GeneratedTest1' runstate='Runnable' seed='907302604' />
<test-case id='0-1051' name='Test10' fullname='GeneratedTest1.Test10' methodname='Test10' classname='GeneratedTest1' runstate='Runnable' seed='542403258' />
<test-case id='0-1052' name='Test11' fullname='GeneratedTest1.Test11' methodname='Test11' classname='GeneratedTest1' runstate='Runnable' seed='2036961476' />
</test-suite>
<test-suite type='TestFixture' id='0-21504' name='GeneratedTest10' fullname='GeneratedTest10' runstate='Runnable' testcasecount='40'>
<test-case id='0-1083' name='Test1' fullname='GeneratedTest10.Test1' methodname='Test1' classname='GeneratedTest10' runstate='Runnable' seed='857897643' />
<test-case id='0-1092' name='Test10' fullname='GeneratedTest10.Test10' methodname='Test10' classname='GeneratedTest10' runstate='Runnable' seed='162525546' />
<test-case id='0-1093' name='Test11' fullname='GeneratedTest10.Test11' methodname='Test11' classname='GeneratedTest10' runstate='Runnable' seed='48042500' />
</test-suite>
</test-suite>
</test-run>";
/// <summary>
/// The dotnetxml has no top level suite, but fixtures directly under assembly.
/// </summary>
[Test]
public void ThatDotNetTestWorks()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(DotnetXml)));
var fixtures = ndr.TestAssembly.TestFixtures;
Assert.That(fixtures.Count(), Is.EqualTo(3), "Didnt find all fixtures");
foreach (var fixture in fixtures)
{
Assert.That(fixture.TestCases.Count, Is.EqualTo(3),
"Didnt find all testcases for fixture");
}
Assert.That(ndr.TestAssembly.TestSuites.Count, Is.EqualTo(1));
var suite = ndr.TestAssembly.TestSuites.Single();
Assert.That(suite.TestFixtures.Count, Is.EqualTo(1));
Assert.That(suite.TestCaseCount, Is.EqualTo(2));
}
private const string MixedExplicitTestSourceXmlForNUnit312 =
@"<test-run id='0' name='Issue545.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter.issues\Issue545\Issue545\bin\Debug\Issue545.dll' runstate='Runnable' testcasecount='3'>
<test-suite type='Assembly' id='0-1007' name='Issue545.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter.issues\Issue545\Issue545\bin\Debug\Issue545.dll' runstate='Runnable' testcasecount='3'>
<test-suite type='TestSuite' id='0-1008' name='Issue545' fullname='Issue545' runstate='Runnable' testcasecount='3'>
<test-suite type='TestFixture' id='0-1009' name='FooTests' fullname='Issue545.FooTests' runstate='Runnable' testcasecount='3'>
<test-suite type='ParameterizedMethod' id='0-1010' name='Test1' fullname='Issue545.FooTests.Test1' classname='Issue545.FooTests' runstate='Explicit' testcasecount='2'>
<test-case id='0-1001' name='Test1(1)' fullname='Issue545.FooTests.Test1(1)' methodname='Test1' classname='Issue545.FooTests' runstate='Runnable' seed='727400600' />
<test-case id='0-1002' name='Test1(2)' fullname='Issue545.FooTests.Test1(2)' methodname='Test1' classname='Issue545.FooTests' runstate='Runnable' seed='6586680' />
</test-suite>
<test-case id='0-1004' name='Test2' fullname='Issue545.FooTests.Test2' methodname='Test2' classname='Issue545.FooTests' runstate='Runnable' seed='756826920' />
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatMixedExplicitTestSourceWorksFor312()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(MixedExplicitTestSourceXmlForNUnit312)));
Assert.Multiple(() =>
{
Assert.That(ndr.IsExplicit, Is.False, "Explicit check fails");
Assert.That(ndr.TestAssembly.RunnableTestCases.Count, Is.EqualTo(1), "Runnable number fails");
Assert.That(ndr.TestAssembly.AllTestCases.Count, Is.EqualTo(3), "Can't find all testcases");
});
}
private const string ExplicitRun =
@"<test-run id='0' name='Issue545.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter.issues\Issue545\Issue545\bin\Debug\Issue545.dll' runstate='Runnable' testcasecount='2'>
<test-suite type='Assembly' id='0-1007' name='Issue545.dll' fullname='D:\repos\NUnit\nunit3-vs-adapter.issues\Issue545\Issue545\bin\Debug\Issue545.dll' runstate='Runnable' testcasecount='2'>
<test-suite type='TestSuite' id='0-1008' name='Issue545' fullname='Issue545' runstate='Runnable' testcasecount='2'>
<test-suite type='TestFixture' id='0-1009' name='FooTests' fullname='Issue545.FooTests' runstate='Runnable' testcasecount='2'>
<test-suite type='ParameterizedMethod' id='0-1010' name='Test1' fullname='Issue545.FooTests.Test1' classname='Issue545.FooTests' runstate='Explicit' testcasecount='2'>
<test-case id='0-1001' name='Test1(1)' fullname='Issue545.FooTests.Test1(1)' methodname='Test1' classname='Issue545.FooTests' runstate='Runnable' seed='581862553' />
<test-case id='0-1002' name='Test1(2)' fullname='Issue545.FooTests.Test1(2)' methodname='Test1' classname='Issue545.FooTests' runstate='Runnable' seed='243299682' />
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Test]
public void ThatExplicitRunWorks()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(ExplicitRun)));
Assert.Multiple(() =>
{
Assert.That(ndr.IsExplicit, "Explicit check fails");
Assert.That(ndr.TestAssembly.AllTestCases.Count, Is.EqualTo(2), "All testcases number fails");
Assert.That(ndr.TestAssembly.AllTestCases.Count, Is.EqualTo(2), "Can't find all testcases");
Assert.That(ndr.TestAssembly.TestSuites.First().IsExplicit, "Test suite don't match explicit");
Assert.That(
ndr.TestAssembly.TestSuites.First().TestFixtures.First().IsExplicit,
"Test fixture don't match explicit");
Assert.That(
ndr.TestAssembly.TestSuites.First().TestFixtures.First().ParameterizedMethods.First().IsExplicit,
"Parameterized method don't match explicit");
Assert.That(
ndr.TestAssembly.TestSuites.First().TestFixtures.First().ParameterizedMethods.First().RunState,
Is.EqualTo(RunStateEnum.Explicit), "Runstate fails for parameterizedfixture");
});
}
private const string SetupFixtureIssue770 =
@"<test-run id='0' name='TestLib.dll' fullname='d:\repos\NUnit\nunit3-vs-adapter.issues\Issue770\TestLib\bin\Debug\netcoreapp3.1\TestLib.dll' runstate='Runnable' testcasecount='1'>
<test-suite type='Assembly' id='0-1005' name='TestLib.dll' fullname='d:/repos/NUnit/nunit3-vs-adapter.issues/Issue770/TestLib/bin/Debug/netcoreapp3.1/TestLib.dll' runstate='Runnable' testcasecount='1'>
<test-suite type='SetUpFixture' id='0-1006' name='[default namespace]' fullname='SetupF' runstate='Runnable' testcasecount='1'>
<test-suite type='TestSuite' id='0-1007' name='L' fullname='L' runstate='Runnable' testcasecount='1'>
<test-suite type='TestFixture' id='0-1008' name='Class1' fullname='L.Class1' runstate='Runnable' testcasecount='1'>
<test-case id='0-1002' name='Test' fullname='L.Class1.Test' methodname='Test' classname='L.Class1' runstate='Runnable' seed='1622556793' />
</test-suite>
</test-suite>
</test-suite>
</test-suite>
</test-run>";
[Ignore("Not ready yet, Issue 770")]
[Test]
public void ThatSetUpFixtureWorks2()
{
var sut = new DiscoveryConverter(logger, settings);
var ndr = sut.ConvertXml(
new NUnitResults(XmlHelper.CreateXmlNode(SetupFixtureIssue770)));
Assert.That(ndr, Is.Not.Null);
}
}
}
| 86.378329 | 339 | 0.682957 | [
"MIT"
] | ovebastiansen/nunit3-vs-adapter | src/NUnitTestAdapterTests/NUnitEngineTests/NUnitDiscoveryTests.cs | 94,068 | 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)
// See the LICENSE.md file in the project root for full license information.
using Stride.Core.Mathematics;
using Stride.Graphics;
namespace Stride.Rendering.Background
{
public class RenderBackground : RenderObject
{
public bool Is2D;
public Texture Texture;
public float Intensity;
public Quaternion Rotation;
}
}
| 31.736842 | 81 | 0.723051 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Rendering/Rendering/Background/RenderBackground.cs | 603 | 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("PubComp.NoSql.Core")]
[assembly: AssemblyDescription("A NoSQL abstraction layer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("PubComp.NoSql.Core")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("8b0aad64-4c6b-4475-9735-5a8aa5ab9e77")]
// 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")]
| 39.911765 | 85 | 0.731024 | [
"MIT"
] | pub-comp/no-sql | NoSql.Core/Properties/AssemblyInfo.cs | 1,360 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using MvcContrib.Samples.UI.Models;
namespace MvcContrib.Samples.UI.Services
{
public class CompanyService
{
private static IList<Company> cachedCompanies = new List<Company>
{
new Company { Id = Guid.NewGuid(), Name = "Acme Inc"},
new Company { Id = Guid.NewGuid(), Name = "MicorSoft" }
};
public static IList<Company> GetCompanies()
{
return cachedCompanies;
}
public static Company GetCompany(Guid id)
{
return cachedCompanies.Where(x => x.Id == id).FirstOrDefault();
}
}
} | 26.076923 | 75 | 0.60177 | [
"Apache-2.0"
] | ignatandrei/MvcContrib | src/Samples/MvcContrib.Samples.UI/Services/CompanyService.cs | 678 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
/// <summary> The LongTermRetentionBackups service client. </summary>
public partial class LongTermRetentionBackupsOperations
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal LongTermRetentionBackupsRestOperations RestClient { get; }
/// <summary> Initializes a new instance of LongTermRetentionBackupsOperations for mocking. </summary>
protected LongTermRetentionBackupsOperations()
{
}
/// <summary> Initializes a new instance of LongTermRetentionBackupsOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="endpoint"> server parameter. </param>
internal LongTermRetentionBackupsOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
RestClient = new LongTermRetentionBackupsRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Gets a long term retention backup. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<LongTermRetentionBackup>> GetByResourceGroupAsync(string resourceGroupName, string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.GetByResourceGroup");
scope.Start();
try
{
return await RestClient.GetByResourceGroupAsync(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets a long term retention backup. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<LongTermRetentionBackup> GetByResourceGroup(string resourceGroupName, string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.GetByResourceGroup");
scope.Start();
try
{
return RestClient.GetByResourceGroup(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets a long term retention backup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<LongTermRetentionBackup>> GetAsync(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.Get");
scope.Start();
try
{
return await RestClient.GetAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets a long term retention backup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<LongTermRetentionBackup> Get(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.Get");
scope.Start();
try
{
return RestClient.Get(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all long term retention backups for a database. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, or <paramref name="longTermRetentionDatabaseName"/> is null. </exception>
public virtual AsyncPageable<LongTermRetentionBackup> ListByResourceGroupDatabaseAsync(string resourceGroupName, string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
async Task<Page<LongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupDatabase");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupDatabaseAsync(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupDatabase");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupDatabaseNextPageAsync(nextLink, resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists all long term retention backups for a database. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, or <paramref name="longTermRetentionDatabaseName"/> is null. </exception>
public virtual Pageable<LongTermRetentionBackup> ListByResourceGroupDatabase(string resourceGroupName, string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
Page<LongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupDatabase");
scope.Start();
try
{
var response = RestClient.ListByResourceGroupDatabase(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupDatabase");
scope.Start();
try
{
var response = RestClient.ListByResourceGroupDatabaseNextPage(nextLink, resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given location. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="locationName"/> is null. </exception>
public virtual AsyncPageable<LongTermRetentionBackup> ListByResourceGroupLocationAsync(string resourceGroupName, string locationName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
async Task<Page<LongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupLocation");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupLocationAsync(resourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupLocation");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupLocationNextPageAsync(nextLink, resourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given location. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="locationName"/> is null. </exception>
public virtual Pageable<LongTermRetentionBackup> ListByResourceGroupLocation(string resourceGroupName, string locationName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
Page<LongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupLocation");
scope.Start();
try
{
var response = RestClient.ListByResourceGroupLocation(resourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupLocation");
scope.Start();
try
{
var response = RestClient.ListByResourceGroupLocationNextPage(nextLink, resourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given server. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="locationName"/>, or <paramref name="longTermRetentionServerName"/> is null. </exception>
public virtual AsyncPageable<LongTermRetentionBackup> ListByResourceGroupServerAsync(string resourceGroupName, string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
async Task<Page<LongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupServer");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupServerAsync(resourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupServer");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupServerNextPageAsync(nextLink, resourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given server. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="locationName"/>, or <paramref name="longTermRetentionServerName"/> is null. </exception>
public virtual Pageable<LongTermRetentionBackup> ListByResourceGroupServer(string resourceGroupName, string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
Page<LongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupServer");
scope.Start();
try
{
var response = RestClient.ListByResourceGroupServer(resourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByResourceGroupServer");
scope.Start();
try
{
var response = RestClient.ListByResourceGroupServerNextPage(nextLink, resourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists all long term retention backups for a database. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, or <paramref name="longTermRetentionDatabaseName"/> is null. </exception>
public virtual AsyncPageable<LongTermRetentionBackup> ListByDatabaseAsync(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
async Task<Page<LongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByDatabase");
scope.Start();
try
{
var response = await RestClient.ListByDatabaseAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByDatabase");
scope.Start();
try
{
var response = await RestClient.ListByDatabaseNextPageAsync(nextLink, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists all long term retention backups for a database. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, or <paramref name="longTermRetentionDatabaseName"/> is null. </exception>
public virtual Pageable<LongTermRetentionBackup> ListByDatabase(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
Page<LongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByDatabase");
scope.Start();
try
{
var response = RestClient.ListByDatabase(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByDatabase");
scope.Start();
try
{
var response = RestClient.ListByDatabaseNextPage(nextLink, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given location. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/> is null. </exception>
public virtual AsyncPageable<LongTermRetentionBackup> ListByLocationAsync(string locationName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
async Task<Page<LongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByLocation");
scope.Start();
try
{
var response = await RestClient.ListByLocationAsync(locationName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByLocation");
scope.Start();
try
{
var response = await RestClient.ListByLocationNextPageAsync(nextLink, locationName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given location. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/> is null. </exception>
public virtual Pageable<LongTermRetentionBackup> ListByLocation(string locationName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
Page<LongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByLocation");
scope.Start();
try
{
var response = RestClient.ListByLocation(locationName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByLocation");
scope.Start();
try
{
var response = RestClient.ListByLocationNextPage(nextLink, locationName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given server. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/> or <paramref name="longTermRetentionServerName"/> is null. </exception>
public virtual AsyncPageable<LongTermRetentionBackup> ListByServerAsync(string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
async Task<Page<LongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByServer");
scope.Start();
try
{
var response = await RestClient.ListByServerAsync(locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<LongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByServer");
scope.Start();
try
{
var response = await RestClient.ListByServerNextPageAsync(nextLink, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists the long term retention backups for a given server. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/> or <paramref name="longTermRetentionServerName"/> is null. </exception>
public virtual Pageable<LongTermRetentionBackup> ListByServer(string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, LongTermRetentionDatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
Page<LongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByServer");
scope.Start();
try
{
var response = RestClient.ListByServer(locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<LongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.ListByServer");
scope.Start();
try
{
var response = RestClient.ListByServerNextPage(nextLink, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Deletes a long term retention backup. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, <paramref name="longTermRetentionDatabaseName"/>, or <paramref name="backupName"/> is null. </exception>
public virtual async Task<LongTermRetentionBackupsDeleteByResourceGroupOperation> StartDeleteByResourceGroupAsync(string resourceGroupName, string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
if (backupName == null)
{
throw new ArgumentNullException(nameof(backupName));
}
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.StartDeleteByResourceGroup");
scope.Start();
try
{
var originalResponse = await RestClient.DeleteByResourceGroupAsync(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken).ConfigureAwait(false);
return new LongTermRetentionBackupsDeleteByResourceGroupOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteByResourceGroupRequest(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a long term retention backup. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, <paramref name="longTermRetentionDatabaseName"/>, or <paramref name="backupName"/> is null. </exception>
public virtual LongTermRetentionBackupsDeleteByResourceGroupOperation StartDeleteByResourceGroup(string resourceGroupName, string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
if (backupName == null)
{
throw new ArgumentNullException(nameof(backupName));
}
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.StartDeleteByResourceGroup");
scope.Start();
try
{
var originalResponse = RestClient.DeleteByResourceGroup(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken);
return new LongTermRetentionBackupsDeleteByResourceGroupOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteByResourceGroupRequest(resourceGroupName, locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a long term retention backup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, <paramref name="longTermRetentionDatabaseName"/>, or <paramref name="backupName"/> is null. </exception>
public virtual async Task<LongTermRetentionBackupsDeleteOperation> StartDeleteAsync(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
if (backupName == null)
{
throw new ArgumentNullException(nameof(backupName));
}
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.StartDelete");
scope.Start();
try
{
var originalResponse = await RestClient.DeleteAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken).ConfigureAwait(false);
return new LongTermRetentionBackupsDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a long term retention backup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <param name="backupName"> The backup name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="locationName"/>, <paramref name="longTermRetentionServerName"/>, <paramref name="longTermRetentionDatabaseName"/>, or <paramref name="backupName"/> is null. </exception>
public virtual LongTermRetentionBackupsDeleteOperation StartDelete(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName, string backupName, CancellationToken cancellationToken = default)
{
if (locationName == null)
{
throw new ArgumentNullException(nameof(locationName));
}
if (longTermRetentionServerName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionServerName));
}
if (longTermRetentionDatabaseName == null)
{
throw new ArgumentNullException(nameof(longTermRetentionDatabaseName));
}
if (backupName == null)
{
throw new ArgumentNullException(nameof(backupName));
}
using var scope = _clientDiagnostics.CreateScope("LongTermRetentionBackupsOperations.StartDelete");
scope.Start();
try
{
var originalResponse = RestClient.Delete(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName, cancellationToken);
return new LongTermRetentionBackupsDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(locationName, longTermRetentionServerName, longTermRetentionDatabaseName, backupName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 59.539851 | 352 | 0.639549 | [
"MIT"
] | AME-Redmond/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/LongTermRetentionBackupsOperations.cs | 56,027 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConditionalExpression_01()
{
string source = @"
class P
{
private void M()
{
int i = 0;
int j = 2;
var z = (/*<bind>*/true ? i : j/*</bind>*/);
}
}
";
string expectedOperationTree = @"
IConditionalOperation (OperationKind.Conditional, Type: System.Int32) (Syntax: 'true ? i : j')
Condition:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
WhenTrue:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
WhenFalse:
ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ConditionalExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConditionalExpression_02()
{
string source = @"
class P
{
private void M()
{
int i = 0;
int j = 2;
(/*<bind>*/true ? ref i : ref j/*</bind>*/) = 4;
}
}
";
string expectedOperationTree = @"
IConditionalOperation (IsRef) (OperationKind.Conditional, Type: System.Int32) (Syntax: 'true ? ref i : ref j')
Condition:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
WhenTrue:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
WhenFalse:
ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ConditionalExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TargetTypedConditionalExpression_ImplicitCast()
{
var source = @"
using System;
bool b = true;
/*<bind>*/Action<string> a = b ? arg => {} : arg => {};/*</bind>*/";
var expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action<stri ... arg => {};')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action<stri ... : arg => {}')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action<System.String> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = b ? arg ... : arg => {}')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= b ? arg = ... : arg => {}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.String>, IsImplicit) (Syntax: 'b ? arg => ... : arg => {}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IConditionalOperation (OperationKind.Conditional, Type: System.Action<System.String>) (Syntax: 'b ? arg => ... : arg => {}')
Condition:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b')
WhenTrue:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
WhenFalse:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TargetTypedConditionalExpression_ExplicitCast()
{
var source = @"
using System;
bool b = true;
/*<bind>*/var a = (Action<string>)(b ? arg => {} : arg => {});/*</bind>*/";
var expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var a = (Ac ... arg => {});')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = (Ac ... arg => {})')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action<System.String> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = (Action ... arg => {})')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (Action<s ... arg => {})')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.String>) (Syntax: '(Action<str ... arg => {})')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IConditionalOperation (OperationKind.Conditional, Type: System.Action<System.String>) (Syntax: 'b ? arg => ... : arg => {}')
Condition:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b')
WhenTrue:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
WhenFalse:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ConditionalExpressionFlow_01()
{
string source = @"
class P
{
void M(bool a, bool b)
/*<bind>*/{
GetArray()[0] = a && b ? 1 : 2;
}/*</bind>*/
static int[] GetArray() => null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'GetArray()[0]')
Array reference:
IInvocationOperation (System.Int32[] P.GetArray()) (OperationKind.Invocation, Type: System.Int32[]) (Syntax: 'GetArray()')
Instance Receiver:
null
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B1] [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... b ? 1 : 2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'GetArray()[ ... & b ? 1 : 2')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'GetArray()[0]')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a && b ? 1 : 2')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ConditionalExpressionFlow_02()
{
string source = @"
class P
{
void M(bool a, bool b, bool c)
/*<bind>*/{
GetArray()[0] = a ? (b ? 1 : 2) : (c ? 3 : 4);
}/*</bind>*/
static int[] GetArray() => null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'GetArray()[0]')
Array reference:
IInvocationOperation (System.Int32[] P.GetArray()) (OperationKind.Invocation, Type: System.Int32[]) (Syntax: 'GetArray()')
Instance Receiver:
null
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B8]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B8]
Block[B5] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B3] [B4] [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... c ? 3 : 4);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'GetArray()[ ... (c ? 3 : 4)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'GetArray()[0]')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? (b ? 1 ... (c ? 3 : 4)')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ConditionalExpressionFlow_03()
{
string source = @"
class P
{
void M(bool a, bool b, bool c, bool d, bool e)
/*<bind>*/{
GetArray()[0] = a ? (b && c) : (d || e);
}/*</bind>*/
static bool[] GetArray() => null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Boolean) (Syntax: 'GetArray()[0]')
Array reference:
IInvocationOperation (System.Boolean[] P.GetArray()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'GetArray()')
Instance Receiver:
null
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B8]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'b')
Next (Regular) Block[B8]
Block[B5] - Block
Predecessors: [B1]
Statements (0)
Jump if True (Regular) to Block[B7]
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'd')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e')
Value:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'e')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'd')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B3] [B4] [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... : (d || e);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'GetArray()[ ... : (d || e)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'GetArray()[0]')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'a ? (b && c) : (d || e)')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
}
}
| 43.935551 | 177 | 0.601287 | [
"MIT"
] | Acidburn0zzz/roslyn | src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IConditionalOperation.cs | 21,135 | C# |
//**********************************************************************************
//* フレームワーク・テストクラス(D層)
//**********************************************************************************
// テスト用サンプルなので、必要に応じて流用 or 削除して下さい。
//**********************************************************************************
//* クラス名 :DaoProducts
//* クラス日本語名 :自動生成Daoクラス
//*
//* 作成日時 :2014/2/9
//* 作成者 :棟梁 D層自動生成ツール(墨壺), 日立 太郎
//* 更新履歴 :
//*
//* 日時 更新者 内容
//* ---------- ---------------- -------------------------------------------------
//* 20xx/xx/xx XX XX XXXX
//* 2012/06/14 西野 大介 ResourceLoaderに加え、EmbeddedResourceLoaderに対応
//* 2013/09/09 西野 大介 ExecGenerateSQLメソッドを追加した(バッチ更新用)。
//**********************************************************************************
using System.Data;
using System.Collections;
using Touryo.Infrastructure.Business.Dao;
using Touryo.Infrastructure.Public.Db;
/// <summary>自動生成Daoクラス</summary>
public class DaoProducts : MyBaseDao
{
#region インスタンス変数
/// <summary>ユーザ パラメタ(文字列置換)用ハッシュ テーブル</summary>
protected Hashtable HtUserParameter = new Hashtable();
/// <summary>パラメタ ライズド クエリのパラメタ用ハッシュ テーブル</summary>
protected Hashtable HtParameter = new Hashtable();
#endregion
#region コンストラクタ
/// <summary>コンストラクタ</summary>
public DaoProducts(BaseDam dam) : base(dam) { }
#endregion
#region 共通関数(パラメタの制御)
/// <summary>ユーザ パラメタ(文字列置換)をハッシュ テーブルに設定する。</summary>
/// <param name="userParamName">ユーザ パラメタ名</param>
/// <param name="userParamValue">ユーザ パラメタ値</param>
public void SetUserParameteToHt(string userParamName, string userParamValue)
{
// ユーザ パラメタをハッシュ テーブルに設定
this.HtUserParameter[userParamName] = userParamValue;
}
/// <summary>パラメタ ライズド クエリのパラメタをハッシュ テーブルに設定する。</summary>
/// <param name="paramName">パラメタ名</param>
/// <param name="paramValue">パラメタ値</param>
public void SetParameteToHt(string paramName, object paramValue)
{
// ユーザ パラメタをハッシュ テーブルに設定
this.HtParameter[paramName] = paramValue;
}
/// <summary>
/// ・ユーザ パラメタ(文字列置換)
/// ・パラメタ ライズド クエリのパラメタ
/// を格納するハッシュ テーブルをクリアする。
/// </summary>
public void ClearParametersFromHt()
{
// ユーザ パラメタ(文字列置換)用ハッシュ テーブルを初期化
this.HtUserParameter = new Hashtable();
// パラメタ ライズド クエリのパラメタ用ハッシュ テーブルを初期化
this.HtParameter = new Hashtable();
}
/// <summary>パラメタの設定(内部用)</summary>
protected void SetParametersFromHt()
{
// ユーザ パラメタ(文字列置換)を設定する。
foreach (string userParamName in this.HtUserParameter.Keys)
{
this.SetUserParameter(userParamName, this.HtUserParameter[userParamName].ToString());
}
// パラメタ ライズド クエリのパラメタを設定する。
foreach (string paramName in this.HtParameter.Keys)
{
this.SetParameter(paramName, this.HtParameter[paramName]);
}
}
#endregion
#region プロパティ プロシージャ(setter、getter)
/// <summary>ProductID列(主キー列)に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object PK_ProductID
{
set
{
this.HtParameter["ProductID"] = value;
}
get
{
return this.HtParameter["ProductID"];
}
}
/// <summary>ProductName列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object ProductName
{
set
{
this.HtParameter["ProductName"] = value;
}
get
{
return this.HtParameter["ProductName"];
}
}
/// <summary>SupplierID列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object SupplierID
{
set
{
this.HtParameter["SupplierID"] = value;
}
get
{
return this.HtParameter["SupplierID"];
}
}
/// <summary>CategoryID列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object CategoryID
{
set
{
this.HtParameter["CategoryID"] = value;
}
get
{
return this.HtParameter["CategoryID"];
}
}
/// <summary>QuantityPerUnit列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object QuantityPerUnit
{
set
{
this.HtParameter["QuantityPerUnit"] = value;
}
get
{
return this.HtParameter["QuantityPerUnit"];
}
}
/// <summary>UnitPrice列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object UnitPrice
{
set
{
this.HtParameter["UnitPrice"] = value;
}
get
{
return this.HtParameter["UnitPrice"];
}
}
/// <summary>UnitsInStock列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object UnitsInStock
{
set
{
this.HtParameter["UnitsInStock"] = value;
}
get
{
return this.HtParameter["UnitsInStock"];
}
}
/// <summary>UnitsOnOrder列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object UnitsOnOrder
{
set
{
this.HtParameter["UnitsOnOrder"] = value;
}
get
{
return this.HtParameter["UnitsOnOrder"];
}
}
/// <summary>ReorderLevel列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object ReorderLevel
{
set
{
this.HtParameter["ReorderLevel"] = value;
}
get
{
return this.HtParameter["ReorderLevel"];
}
}
/// <summary>Discontinued列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタを除く</remarks>
public object Discontinued
{
set
{
this.HtParameter["Discontinued"] = value;
}
get
{
return this.HtParameter["Discontinued"];
}
}
/// <summary>Set_ProductID_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_ProductID_forUPD
{
set
{
this.HtParameter["Set_ProductID_forUPD"] = value;
}
get
{
return this.HtParameter["Set_ProductID_forUPD"];
}
}
/// <summary>Set_ProductName_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_ProductName_forUPD
{
set
{
this.HtParameter["Set_ProductName_forUPD"] = value;
}
get
{
return this.HtParameter["Set_ProductName_forUPD"];
}
}
/// <summary>Set_SupplierID_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_SupplierID_forUPD
{
set
{
this.HtParameter["Set_SupplierID_forUPD"] = value;
}
get
{
return this.HtParameter["Set_SupplierID_forUPD"];
}
}
/// <summary>Set_CategoryID_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_CategoryID_forUPD
{
set
{
this.HtParameter["Set_CategoryID_forUPD"] = value;
}
get
{
return this.HtParameter["Set_CategoryID_forUPD"];
}
}
/// <summary>Set_QuantityPerUnit_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_QuantityPerUnit_forUPD
{
set
{
this.HtParameter["Set_QuantityPerUnit_forUPD"] = value;
}
get
{
return this.HtParameter["Set_QuantityPerUnit_forUPD"];
}
}
/// <summary>Set_UnitPrice_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_UnitPrice_forUPD
{
set
{
this.HtParameter["Set_UnitPrice_forUPD"] = value;
}
get
{
return this.HtParameter["Set_UnitPrice_forUPD"];
}
}
/// <summary>Set_UnitsInStock_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_UnitsInStock_forUPD
{
set
{
this.HtParameter["Set_UnitsInStock_forUPD"] = value;
}
get
{
return this.HtParameter["Set_UnitsInStock_forUPD"];
}
}
/// <summary>Set_UnitsOnOrder_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_UnitsOnOrder_forUPD
{
set
{
this.HtParameter["Set_UnitsOnOrder_forUPD"] = value;
}
get
{
return this.HtParameter["Set_UnitsOnOrder_forUPD"];
}
}
/// <summary>Set_ReorderLevel_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_ReorderLevel_forUPD
{
set
{
this.HtParameter["Set_ReorderLevel_forUPD"] = value;
}
get
{
return this.HtParameter["Set_ReorderLevel_forUPD"];
}
}
/// <summary>Set_Discontinued_forUPD列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>更新処理時のSET句で使用するパラメタ専用</remarks>
public object Set_Discontinued_forUPD
{
set
{
this.HtParameter["Set_Discontinued_forUPD"] = value;
}
get
{
return this.HtParameter["Set_Discontinued_forUPD"];
}
}
/// <summary>ProductID_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object ProductID_Like
{
set
{
this.HtParameter["ProductID_Like"] = value;
}
get
{
return this.HtParameter["ProductID_Like"];
}
}
/// <summary>ProductName_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object ProductName_Like
{
set
{
this.HtParameter["ProductName_Like"] = value;
}
get
{
return this.HtParameter["ProductName_Like"];
}
}
/// <summary>SupplierID_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object SupplierID_Like
{
set
{
this.HtParameter["SupplierID_Like"] = value;
}
get
{
return this.HtParameter["SupplierID_Like"];
}
}
/// <summary>CategoryID_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object CategoryID_Like
{
set
{
this.HtParameter["CategoryID_Like"] = value;
}
get
{
return this.HtParameter["CategoryID_Like"];
}
}
/// <summary>QuantityPerUnit_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object QuantityPerUnit_Like
{
set
{
this.HtParameter["QuantityPerUnit_Like"] = value;
}
get
{
return this.HtParameter["QuantityPerUnit_Like"];
}
}
/// <summary>UnitPrice_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object UnitPrice_Like
{
set
{
this.HtParameter["UnitPrice_Like"] = value;
}
get
{
return this.HtParameter["UnitPrice_Like"];
}
}
/// <summary>UnitsInStock_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object UnitsInStock_Like
{
set
{
this.HtParameter["UnitsInStock_Like"] = value;
}
get
{
return this.HtParameter["UnitsInStock_Like"];
}
}
/// <summary>UnitsOnOrder_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object UnitsOnOrder_Like
{
set
{
this.HtParameter["UnitsOnOrder_Like"] = value;
}
get
{
return this.HtParameter["UnitsOnOrder_Like"];
}
}
/// <summary>ReorderLevel_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object ReorderLevel_Like
{
set
{
this.HtParameter["ReorderLevel_Like"] = value;
}
get
{
return this.HtParameter["ReorderLevel_Like"];
}
}
/// <summary>Discontinued_Like列に対するパラメタ ライズド クエリのパラメタを設定する。</summary>
/// <remarks>動的参照処理時のLIKE検索で使用するパラメタ専用</remarks>
public object Discontinued_Like
{
set
{
this.HtParameter["Discontinued_Like"] = value;
}
get
{
return this.HtParameter["Discontinued_Like"];
}
}
#endregion
#region クエリ メソッド
#region Insert
/// <summary>1レコード挿入する。</summary>
/// <returns>挿入された行の数</returns>
public int S1_Insert()
{
// ファイルからSQL(Insert)を設定する。
this.SetSqlByFile2("DaoProducts_S1_Insert.sql");
// パラメタの設定
this.SetParametersFromHt();
// SQL(Insert)を実行し、戻り値を戻す。
return this.ExecInsUpDel_NonQuery();
}
/// <summary>1レコード挿入する。</summary>
/// <returns>挿入された行の数</returns>
/// <remarks>パラメタで指定した列のみ挿入値が有効になる。</remarks>
public int D1_Insert()
{
// ファイルからSQL(DynIns)を設定する。
this.SetSqlByFile2("DaoProducts_D1_Insert.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(DynIns)を実行し、戻り値を戻す。
return this.ExecInsUpDel_NonQuery();
}
#endregion
#region Select
/// <summary>主キーを指定し、1レコード参照する。</summary>
/// <param name="dt">結果を格納するDataTable</param>
public void S2_Select(DataTable dt)
{
// ファイルからSQL(Select)を設定する。
this.SetSqlByFile2("DaoProducts_S2_Select.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(Select)を実行し、戻り値を戻す。
this.ExecSelectFill_DT(dt);
}
/// <summary>検索条件を指定し、結果セットを参照する。</summary>
/// <param name="dt">結果を格納するDataTable</param>
public void D2_Select(DataTable dt)
{
// ファイルからSQL(DynSel)を設定する。
this.SetSqlByFile2("DaoProducts_D2_Select.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(DynSel)を実行し、戻り値を戻す。
this.ExecSelectFill_DT(dt);
}
#endregion
#region Update
/// <summary>主キーを指定し、1レコード更新する。</summary>
/// <returns>更新された行の数</returns>
/// <remarks>パラメタで指定した列のみ更新値が有効になる。</remarks>
public int S3_Update()
{
// ファイルからSQL(Update)を設定する。
this.SetSqlByFile2("DaoProducts_S3_Update.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(Update)を実行し、戻り値を戻す。
return this.ExecInsUpDel_NonQuery();
}
/// <summary>任意の検索条件でデータを更新する。</summary>
/// <returns>更新された行の数</returns>
/// <remarks>パラメタで指定した列のみ更新値が有効になる。</remarks>
public int D3_Update()
{
// ファイルからSQL(DynUpd)を設定する。
this.SetSqlByFile2("DaoProducts_D3_Update.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(DynUpd)を実行し、戻り値を戻す。
return this.ExecInsUpDel_NonQuery();
}
#endregion
#region Delete
/// <summary>主キーを指定し、1レコード削除する。</summary>
/// <returns>削除された行の数</returns>
public int S4_Delete()
{
// ファイルからSQL(Delete)を設定する。
this.SetSqlByFile2("DaoProducts_S4_Delete.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(Delete)を実行し、戻り値を戻す。
return this.ExecInsUpDel_NonQuery();
}
/// <summary>任意の検索条件でデータを削除する。</summary>
/// <returns>削除された行の数</returns>
public int D4_Delete()
{
// ファイルからSQL(DynDel)を設定する。
this.SetSqlByFile2("DaoProducts_D4_Delete.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(DynDel)を実行し、戻り値を戻す。
return this.ExecInsUpDel_NonQuery();
}
#endregion
#region 拡張メソッド
/// <summary>テーブルのレコード件数を取得する</summary>
/// <returns>テーブルのレコード件数</returns>
public object D5_SelCnt()
{
// ファイルからSQL(DynSelCnt)を設定する。
this.SetSqlByFile2("DaoProducts_D5_SelCnt.xml");
// パラメタの設定
this.SetParametersFromHt();
// SQL(SELECT COUNT)を実行し、戻り値を戻す。
return this.ExecSelectScalar();
}
/// <summary>静的SQLを生成する。</summary>
/// <param name="fileName">ファイル名</param>
/// <param name="sqlUtil">SQLユーティリティ</param>
/// <returns>生成した静的SQL</returns>
public string ExecGenerateSQL(string fileName, SQLUtility sqlUtil)
{
// ファイルからSQLを設定する。
this.SetSqlByFile2(fileName);
// パラメタの設定
this.SetParametersFromHt();
return base.ExecGenerateSQL(sqlUtil);
}
#endregion
#endregion
}
| 24.784615 | 97 | 0.573444 | [
"Apache-2.0"
] | OpenTouryoProject/OpenTouryo | root/programs/CS/Samples/2CS_sample/GenDaoAndBatUpd_sample/Dao/DaoProducts.cs | 22,911 | C# |
using System;
using Foundation;
using Shopping.DemoApp.iOS.Extensions;
using Shopping.DemoApp.Models;
using Shopping.DemoApp.Services;
using UIKit;
namespace Shopping.DemoApp.iOS.Controllers
{
public partial class ItemDetailViewController : UIViewController
{
public SaleItem SaleItem { get; set; }
public ItemDetailViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
this.AddDefaultNavigationTitle();
LoadData();
BuyButton.TouchUpInside += OnBuyRequested;
}
private async void LoadData()
{
await ItemImageView.BindImageViewAsync(SaleItem);
ItemTitleLabel.Text = (SaleItem.Name ?? string.Empty).ToUpper();
ItemDescriptionLabel.Text = SaleItem.Description;
var smallAttributes = new UIStringAttributes
{
Font = UIFont.FromName(ItemPriceLabel.Font.Name, 20f)
};
string priceStr = "$" + SaleItem.Price.ToString("0.00");
NSMutableAttributedString mutablePriceStr = new NSMutableAttributedString(priceStr);
mutablePriceStr.SetAttributes(smallAttributes.Dictionary, new NSRange(0, 1));
mutablePriceStr.SetAttributes(smallAttributes.Dictionary, new NSRange(priceStr.Length - 3, 3));
ItemPriceLabel.AttributedText = mutablePriceStr;
}
private async void OnBuyRequested(object sender, EventArgs e)
{
await SaleItemDataService.Instance.BuySaleItemAsync(SaleItem);
}
}
} | 27.698113 | 98 | 0.726158 | [
"MIT"
] | Bhaskers-Blu-Org2/XamarinAzure_ShoppingDemoApp | Shopping.DemoApp.iOS/Controllers/ItemDetailViewController.cs | 1,468 | C# |
namespace ApiFox.Areas.HelpPage
{
/// <summary>
/// Indicates whether the sample is used for request or response
/// </summary>
public enum SampleDirection
{
Request = 0,
Response
}
} | 20.272727 | 68 | 0.600897 | [
"MIT"
] | Mrkebubun/ApiFox | ApiFox/Areas/HelpPage/SampleGeneration/SampleDirection.cs | 223 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TesteAPI.Repositorio.Contexto;
namespace TesteAPI.Repositorio.Migrations
{
[DbContext(typeof(CastGroupContexto))]
[Migration("20210928180512_PrimeiraVersaoBaseDados")]
partial class PrimeiraVersaoBaseDados
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 64)
.HasAnnotation("ProductVersion", "5.0.10");
modelBuilder.Entity("TesteAPI.Dominio.Entidades.Categoria", b =>
{
b.Property<int>("Codigo")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Descricao")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Codigo");
b.ToTable("Categorias");
});
modelBuilder.Entity("TesteAPI.Dominio.Entidades.Curso", b =>
{
b.Property<int>("CodigoCurso")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("CategoriaCodigo")
.HasColumnType("int");
b.Property<int>("CodigoCategoria")
.HasColumnType("int");
b.Property<DateTime>("DataInicio")
.HasColumnType("date");
b.Property<DateTime>("DataTernmino")
.HasColumnType("date");
b.Property<string>("DescricaoAssunto")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("QuantidadeTurma")
.HasColumnType("int");
b.HasKey("CodigoCurso");
b.HasIndex("CategoriaCodigo");
b.ToTable("Cursos");
});
modelBuilder.Entity("TesteAPI.Dominio.Entidades.Curso", b =>
{
b.HasOne("TesteAPI.Dominio.Entidades.Categoria", "Categoria")
.WithMany("Cursos")
.HasForeignKey("CategoriaCodigo");
b.Navigation("Categoria");
});
modelBuilder.Entity("TesteAPI.Dominio.Entidades.Categoria", b =>
{
b.Navigation("Cursos");
});
#pragma warning restore 612, 618
}
}
}
| 33.37931 | 81 | 0.506887 | [
"MIT"
] | rafael-act/CastGroup-Teste | TesteAPI/TesteAPI.Repositorio/Migrations/20210928180512_PrimeiraVersaoBaseDados.Designer.cs | 2,906 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// SmsCommandResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Supersim.V1
{
public class SmsCommandResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Queued = new StatusEnum("queued");
public static readonly StatusEnum Sent = new StatusEnum("sent");
public static readonly StatusEnum Delivered = new StatusEnum("delivered");
public static readonly StatusEnum Received = new StatusEnum("received");
public static readonly StatusEnum Failed = new StatusEnum("failed");
}
public sealed class DirectionEnum : StringEnum
{
private DirectionEnum(string value) : base(value) {}
public DirectionEnum() {}
public static implicit operator DirectionEnum(string value)
{
return new DirectionEnum(value);
}
public static readonly DirectionEnum ToSim = new DirectionEnum("to_sim");
public static readonly DirectionEnum FromSim = new DirectionEnum("from_sim");
}
private static Request BuildCreateRequest(CreateSmsCommandOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Supersim,
"/v1/SmsCommands",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Send SMS Command to a Sim.
/// </summary>
/// <param name="options"> Create SmsCommand parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SmsCommand </returns>
public static SmsCommandResource Create(CreateSmsCommandOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Send SMS Command to a Sim.
/// </summary>
/// <param name="options"> Create SmsCommand parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SmsCommand </returns>
public static async System.Threading.Tasks.Task<SmsCommandResource> CreateAsync(CreateSmsCommandOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Send SMS Command to a Sim.
/// </summary>
/// <param name="sim"> The sid or unique_name of the SIM to send the SMS Command to </param>
/// <param name="payload"> The message body of the SMS Command </param>
/// <param name="callbackMethod"> The HTTP method we should use to call callback_url </param>
/// <param name="callbackUrl"> The URL we should call after we have sent the command </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SmsCommand </returns>
public static SmsCommandResource Create(string sim,
string payload,
Twilio.Http.HttpMethod callbackMethod = null,
Uri callbackUrl = null,
ITwilioRestClient client = null)
{
var options = new CreateSmsCommandOptions(sim, payload){CallbackMethod = callbackMethod, CallbackUrl = callbackUrl};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Send SMS Command to a Sim.
/// </summary>
/// <param name="sim"> The sid or unique_name of the SIM to send the SMS Command to </param>
/// <param name="payload"> The message body of the SMS Command </param>
/// <param name="callbackMethod"> The HTTP method we should use to call callback_url </param>
/// <param name="callbackUrl"> The URL we should call after we have sent the command </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SmsCommand </returns>
public static async System.Threading.Tasks.Task<SmsCommandResource> CreateAsync(string sim,
string payload,
Twilio.Http.HttpMethod callbackMethod = null,
Uri callbackUrl = null,
ITwilioRestClient client = null)
{
var options = new CreateSmsCommandOptions(sim, payload){CallbackMethod = callbackMethod, CallbackUrl = callbackUrl};
return await CreateAsync(options, client);
}
#endif
private static Request BuildFetchRequest(FetchSmsCommandOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Supersim,
"/v1/SmsCommands/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch SMS Command instance from your account.
/// </summary>
/// <param name="options"> Fetch SmsCommand parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SmsCommand </returns>
public static SmsCommandResource Fetch(FetchSmsCommandOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch SMS Command instance from your account.
/// </summary>
/// <param name="options"> Fetch SmsCommand parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SmsCommand </returns>
public static async System.Threading.Tasks.Task<SmsCommandResource> FetchAsync(FetchSmsCommandOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch SMS Command instance from your account.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SmsCommand </returns>
public static SmsCommandResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchSmsCommandOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch SMS Command instance from your account.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SmsCommand </returns>
public static async System.Threading.Tasks.Task<SmsCommandResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchSmsCommandOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadSmsCommandOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Supersim,
"/v1/SmsCommands",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of SMS Commands from your account.
/// </summary>
/// <param name="options"> Read SmsCommand parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SmsCommand </returns>
public static ResourceSet<SmsCommandResource> Read(ReadSmsCommandOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<SmsCommandResource>.FromJson("sms_commands", response.Content);
return new ResourceSet<SmsCommandResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of SMS Commands from your account.
/// </summary>
/// <param name="options"> Read SmsCommand parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SmsCommand </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SmsCommandResource>> ReadAsync(ReadSmsCommandOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<SmsCommandResource>.FromJson("sms_commands", response.Content);
return new ResourceSet<SmsCommandResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of SMS Commands from your account.
/// </summary>
/// <param name="sim"> The SID or unique name of the Sim resource that SMS Command was sent to or from. </param>
/// <param name="status"> The status of the SMS Command </param>
/// <param name="direction"> The direction of the SMS Command </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SmsCommand </returns>
public static ResourceSet<SmsCommandResource> Read(string sim = null,
SmsCommandResource.StatusEnum status = null,
SmsCommandResource.DirectionEnum direction = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSmsCommandOptions(){Sim = sim, Status = status, Direction = direction, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of SMS Commands from your account.
/// </summary>
/// <param name="sim"> The SID or unique name of the Sim resource that SMS Command was sent to or from. </param>
/// <param name="status"> The status of the SMS Command </param>
/// <param name="direction"> The direction of the SMS Command </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SmsCommand </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SmsCommandResource>> ReadAsync(string sim = null,
SmsCommandResource.StatusEnum status = null,
SmsCommandResource.DirectionEnum direction = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSmsCommandOptions(){Sim = sim, Status = status, Direction = direction, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<SmsCommandResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<SmsCommandResource>.FromJson("sms_commands", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<SmsCommandResource> NextPage(Page<SmsCommandResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Supersim)
);
var response = client.Request(request);
return Page<SmsCommandResource>.FromJson("sms_commands", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<SmsCommandResource> PreviousPage(Page<SmsCommandResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Supersim)
);
var response = client.Request(request);
return Page<SmsCommandResource>.FromJson("sms_commands", response.Content);
}
/// <summary>
/// Converts a JSON string into a SmsCommandResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> SmsCommandResource object represented by the provided JSON </returns>
public static SmsCommandResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<SmsCommandResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the SIM that this SMS Command was sent to or from
/// </summary>
[JsonProperty("sim_sid")]
public string SimSid { get; private set; }
/// <summary>
/// The message body of the SMS Command sent to or from the SIM
/// </summary>
[JsonProperty("payload")]
public string Payload { get; private set; }
/// <summary>
/// The status of the SMS Command
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public SmsCommandResource.StatusEnum Status { get; private set; }
/// <summary>
/// The direction of the SMS Command
/// </summary>
[JsonProperty("direction")]
[JsonConverter(typeof(StringEnumConverter))]
public SmsCommandResource.DirectionEnum Direction { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The absolute URL of the SMS Command resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private SmsCommandResource()
{
}
}
} | 46.73012 | 149 | 0.557314 | [
"MIT"
] | BrimmingDev/twilio-csharp | src/Twilio/Rest/Supersim/V1/SmsCommandResource.cs | 19,393 | C# |
using System;
using System.Xml.Serialization;
using Top.Api.Domain;
namespace Top.Api.Response
{
/// <summary>
/// TmallProductTemplateGetResponse.
/// </summary>
public class TmallProductTemplateGetResponse : TopResponse
{
/// <summary>
/// 见SpuTemplateDO说明
/// </summary>
[XmlElement("template")]
public SpuTemplateDO Template { get; set; }
}
}
| 21.684211 | 62 | 0.623786 | [
"MIT"
] | objectyan/MyTools | OY.Solution/OY.TopSdk/Response/TmallProductTemplateGetResponse.cs | 418 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace MegaCasting.WPF
{
/// <summary>
/// Logique d'interaction pour App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.555556 | 43 | 0.706587 | [
"Apache-2.0"
] | MegaProduction/MegaCastingClientLourd | MegaCasting.WPF/App.xaml.cs | 336 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MovieManager.Core.Entities
{
public class Category : EntityObject
{
[Required]
public String CategoryName { get; set; }
public ICollection<Movie> Movies { get; set; }
public Category()
{
Movies = new List<Movie>();
}
}
}
| 20 | 54 | 0.62 | [
"MIT"
] | MIGU-1/csharp_samples_ef_uow_moviemanager-template | source/MovieManager.Core/Entities/Category.cs | 402 | C# |
using System;
using System.Collections.Generic;
namespace Bing.Swashbuckle.Internals
{
/// <summary>
/// 内部缓存
/// </summary>
internal static class InternalCache
{
/// <summary>
/// 枚举字典
/// </summary>
public static Dictionary<Type, List<(int Value, string Name, string Description)>> EnumDict =
new Dictionary<Type, List<(int Value, string Name, string Description)>>();
}
}
| 24.722222 | 101 | 0.606742 | [
"MIT"
] | bing-framework/Bing.Extensions.Swashbuckle | src/Bing.Extensions.Swashbuckle/Bing/Swashbuckle/Internals/InternalCache.cs | 463 | C# |
using UnityEngine;
using System.IO;
[AddComponentMenu("Modifiers/Path Deform")]
public class MegaPathDeform : MegaModifier
{
public float percent = 0.0f;
public float stretch = 1.0f;
public float twist = 0.0f;
public float rotate = 0.0f;
public MegaAxis axis = MegaAxis.X;
public bool flip = false;
public MegaShape path = null;
public bool animate = false;
public float speed = 1.0f;
public bool drawpath = false;
public float tangent = 1.0f;
[HideInInspector]
public Matrix4x4 mat = new Matrix4x4();
public bool UseTwistCurve = false;
public AnimationCurve twistCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
public bool UseStretchCurve = false;
public AnimationCurve stretchCurve = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1, 1));
public override string ModName() { return "PathDeform"; }
public override string GetHelpURL() { return "?page_id=273"; }
public Vector3 Up = Vector3.up;
public int curve = 0;
public bool usedist = false;
public float distance = 0.0f;
public MegaLoopMode loopmode = MegaLoopMode.None;
Vector3 start;
Quaternion tw = Quaternion.identity;
float usepercent;
float usetan;
float ovlen;
public override Vector3 Map(int i, Vector3 p)
{
p = tm.MultiplyPoint3x4(p); // Dont need either, so saving 3 vector mat mults but gaining a mat mult
float alpha;
float tws = 0.0f;
if ( UseStretchCurve )
{
float str = stretchCurve.Evaluate(Mathf.Repeat(p.z * ovlen + usepercent, 1.0f)) * stretch;
alpha = (p.z * ovlen * str) + usepercent; //(percent / 100.0f); // can precalc this
}
else
alpha = (p.z * ovlen * stretch) + usepercent; //(percent / 100.0f); // can precalc this
Vector3 ps = path.InterpCurve3D(curve, alpha, path.normalizedInterp, ref tws) - start;
Vector3 ps1 = path.InterpCurve3D(curve, alpha + usetan, path.normalizedInterp) - start;
if ( path.splines[curve].closed )
alpha = Mathf.Repeat(alpha, 1.0f);
else
alpha = Mathf.Clamp01(alpha);
if ( UseTwistCurve )
{
float twst = twistCurve.Evaluate(alpha) * twist;
tw = Quaternion.AngleAxis(twst + tws, Vector3.forward);
}
else
tw = Quaternion.AngleAxis(tws + (twist * alpha), Vector3.forward);
Vector3 relativePos = ps1 - ps;
Quaternion rotation = Quaternion.LookRotation(relativePos, Up) * tw;
//wtm.SetTRS(ps, rotation, Vector3.one);
Matrix4x4 wtm = Matrix4x4.identity;
MegaMatrix.SetTR(ref wtm, ps, rotation);
wtm = mat * wtm;
p.z = 0.0f;
return wtm.MultiplyPoint3x4(p);
}
public override void ModStart(MegaModifiers mc)
{
}
public override bool ModLateUpdate(MegaModContext mc)
{
if ( animate )
{
if ( Application.isPlaying )
percent += speed * Time.deltaTime;
if ( usedist )
distance = percent * 0.01f * path.splines[curve].length;
}
return Prepare(mc);
}
public override bool Prepare(MegaModContext mc)
{
if ( path != null )
{
if ( curve >= path.splines.Count )
curve = 0;
if ( usedist )
percent = distance / path.splines[curve].length * 100.0f;
usepercent = percent / 100.0f;
switch ( loopmode )
{
case MegaLoopMode.Clamp: usepercent = Mathf.Clamp01(usepercent); break;
case MegaLoopMode.Loop: usepercent = Mathf.Repeat(usepercent, 1.0f); break;
case MegaLoopMode.PingPong: usepercent = Mathf.PingPong(usepercent, 1.0f); break;
}
ovlen = (1.0f / path.splines[curve].length); // * stretch;
usetan = (tangent * 0.01f);
mat = Matrix4x4.identity;
switch ( axis )
{
case MegaAxis.Z: MegaMatrix.RotateX(ref mat, -Mathf.PI * 0.5f); break;
}
MegaMatrix.RotateZ(ref mat, Mathf.Deg2Rad * rotate);
SetAxis(mat);
start = path.splines[curve].knots[0].p;
Vector3 p1 = path.InterpCurve3D(0, 0.01f, path.normalizedInterp);
Vector3 up = Vector3.zero;
switch ( axis )
{
case MegaAxis.X: up = Vector3.left; break;
case MegaAxis.Y: up = Vector3.back; break;
case MegaAxis.Z: up = Vector3.up; break;
}
Quaternion lrot = Quaternion.identity;
if ( flip )
up = -up;
lrot = Quaternion.FromToRotation(p1 - start, up);
mat.SetTRS(Vector3.zero, lrot, Vector3.one);
return true;
}
return false;
}
public void OnDrawGizmos()
{
if ( drawpath )
Display(this);
}
// Mmm should be in gizmo code
void Display(MegaPathDeform pd)
{
if ( pd.path != null )
{
// Need to do a lookat on first point to get the direction
pd.mat = Matrix4x4.identity;
Vector3 p = pd.path.splines[curve].knots[0].p;
Vector3 p1 = pd.path.InterpCurve3D(curve, 0.01f, pd.path.normalizedInterp);
Vector3 up = Vector3.zero;
switch ( axis )
{
case MegaAxis.X: up = Vector3.left; break;
case MegaAxis.Y: up = Vector3.back; break;
case MegaAxis.Z: up = Vector3.up; break;
}
Quaternion lrot = Quaternion.identity;
if ( flip )
up = -up;
lrot = Quaternion.FromToRotation(p1 - p, up);
pd.mat.SetTRS(Vector3.zero, lrot, Vector3.one);
Matrix4x4 mat = pd.transform.localToWorldMatrix * pd.mat;
for ( int s = 0; s < pd.path.splines.Count; s++ )
{
float ldist = pd.path.stepdist * 0.1f;
if ( ldist < 0.01f )
ldist = 0.01f;
float ds = pd.path.splines[s].length / (pd.path.splines[s].length / ldist);
int c = 0;
int k = -1;
int lk = -1;
Vector3 first = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref lk) - p;
for ( float dist = ds; dist < pd.path.splines[s].length; dist += ds )
{
float alpha = dist / pd.path.splines[s].length;
Vector3 pos = pd.path.splines[s].Interpolate(alpha, pd.path.normalizedInterp, ref k) - p;
if ( (c & 1) == 1 )
Gizmos.color = pd.path.col1;
else
Gizmos.color = pd.path.col2;
if ( k != lk )
{
for ( lk = lk + 1; lk <= k; lk++ )
{
Gizmos.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pd.path.splines[s].knots[lk].p - p));
first = pd.path.splines[s].knots[lk].p - p;
}
}
lk = k;
Gizmos.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
c++;
first = pos;
}
if ( (c & 1) == 1 )
Gizmos.color = pd.path.col1;
else
Gizmos.color = pd.path.col2;
if ( pd.path.splines[s].closed )
{
Vector3 pos = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref k) - p;
Gizmos.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
}
}
Vector3 p0 = pd.path.InterpCurve3D(curve, (percent / 100.0f), pd.path.normalizedInterp) - p;
p1 = pd.path.InterpCurve3D(curve, (percent / 100.0f) + (tangent * 0.01f), pd.path.normalizedInterp) - p;
Gizmos.color = Color.blue;
Vector3 sz = new Vector3(pd.path.KnotSize * 0.01f, pd.path.KnotSize * 0.01f, pd.path.KnotSize * 0.01f);
Gizmos.DrawCube(mat.MultiplyPoint(p0), sz);
Gizmos.DrawCube(mat.MultiplyPoint(p1), sz);
}
}
public override void DrawGizmo(MegaModContext context)
{
if ( !Prepare(context) )
return;
Vector3 min = context.bbox.min;
Vector3 max = context.bbox.max;
if ( context.mod.sourceObj != null )
Gizmos.matrix = context.mod.sourceObj.transform.localToWorldMatrix; // * gtm;
else
Gizmos.matrix = transform.localToWorldMatrix; // * gtm;
corners[0] = new Vector3(min.x, min.y, min.z);
corners[1] = new Vector3(min.x, max.y, min.z);
corners[2] = new Vector3(max.x, max.y, min.z);
corners[3] = new Vector3(max.x, min.y, min.z);
corners[4] = new Vector3(min.x, min.y, max.z);
corners[5] = new Vector3(min.x, max.y, max.z);
corners[6] = new Vector3(max.x, max.y, max.z);
corners[7] = new Vector3(max.x, min.y, max.z);
DrawEdge(corners[0], corners[1]);
DrawEdge(corners[1], corners[2]);
DrawEdge(corners[2], corners[3]);
DrawEdge(corners[3], corners[0]);
DrawEdge(corners[4], corners[5]);
DrawEdge(corners[5], corners[6]);
DrawEdge(corners[6], corners[7]);
DrawEdge(corners[7], corners[4]);
DrawEdge(corners[0], corners[4]);
DrawEdge(corners[1], corners[5]);
DrawEdge(corners[2], corners[6]);
DrawEdge(corners[3], corners[7]);
ExtraGizmo(context);
}
} | 28.197987 | 108 | 0.626562 | [
"MIT"
] | oliverellmers/UnityARKitDetection | Assets/Mega-Fiers/Scripts/MegaFiers/Modifiers/MegaPathDeform.cs | 8,403 | C# |
//---------------------------------------------------------------------
// <copyright file="AliasedSlot.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner Microsoft
// @backupOwner Microsoft
//---------------------------------------------------------------------
using System.Linq;
using System.Data.Mapping.ViewGeneration.Structures;
using System.Text;
using System.Diagnostics;
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.ExpressionBuilder;
using System.Data.Common.Utils;
using System.Collections.Generic;
namespace System.Data.Mapping.ViewGeneration.CqlGeneration
{
/// <summary>
/// Encapsulates a slot in a particular cql block.
/// </summary>
internal sealed class QualifiedSlot : ProjectedSlot
{
#region Constructor
/// <summary>
/// Creates a qualified slot "block_alias.slot_alias"
/// </summary>
internal QualifiedSlot(CqlBlock block, ProjectedSlot slot)
{
Debug.Assert(block != null && slot != null, "Null input to QualifiedSlot constructor");
m_block = block;
m_slot = slot; // Note: slot can be another qualified slot.
}
#endregion
#region Fields
private readonly CqlBlock m_block;
private readonly ProjectedSlot m_slot;
#endregion
#region Methods
/// <summary>
/// Creates new <see cref="ProjectedSlot"/> that is qualified with <paramref name="block"/>.CqlAlias.
/// If current slot is composite (such as <see cref="CaseStatementProjectedSlot"/>, then this method recursively qualifies all parts
/// and returns a new deeply qualified slot (as opposed to <see cref="CqlBlock.QualifySlotWithBlockAlias"/>).
/// </summary>
internal override ProjectedSlot DeepQualify(CqlBlock block)
{
// We take the slot inside this and change the block
QualifiedSlot result = new QualifiedSlot(block, m_slot);
return result;
}
/// <summary>
/// Delegates alias generation to the leaf slot in the qualified chain.
/// </summary>
internal override string GetCqlFieldAlias(MemberPath outputMember)
{
// Keep looking inside the chain of qualified slots till we find a non-qualified slot and then get the alias name for it.
string result = GetOriginalSlot().GetCqlFieldAlias(outputMember);
return result;
}
/// <summary>
/// Walks the chain of <see cref="QualifiedSlot"/>s starting from the current one and returns the original slot.
/// </summary>
internal ProjectedSlot GetOriginalSlot()
{
ProjectedSlot slot = m_slot;
while (true)
{
QualifiedSlot qualifiedSlot = slot as QualifiedSlot;
if (qualifiedSlot == null)
{
break;
}
slot = qualifiedSlot.m_slot;
}
return slot;
}
internal string GetQualifiedCqlName(MemberPath outputMember)
{
return CqlWriter.GetQualifiedName(m_block.CqlAlias, GetCqlFieldAlias(outputMember));
}
internal override StringBuilder AsEsql(StringBuilder builder, MemberPath outputMember, string blockAlias, int indentLevel)
{
Debug.Assert(blockAlias == null || m_block.CqlAlias == blockAlias, "QualifiedSlot: blockAlias mismatch");
builder.Append(GetQualifiedCqlName(outputMember));
return builder;
}
internal override DbExpression AsCqt(DbExpression row, MemberPath outputMember)
{
return m_block.GetInput(row).Property(GetCqlFieldAlias(outputMember));
}
internal override void ToCompactString(StringBuilder builder)
{
StringUtil.FormatStringBuilder(builder, "{0} ", m_block.CqlAlias);
m_slot.ToCompactString(builder);
}
#endregion
}
}
| 37.697248 | 140 | 0.609637 | [
"MIT"
] | Abdalla-rabie/referencesource | System.Data.Entity/System/Data/Mapping/ViewGeneration/CqlGeneration/AliasedSlot.cs | 4,109 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SuperVision.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.387097 | 151 | 0.581614 | [
"MIT"
] | 1bastien1/CSA | csa-master/SuperVision/Properties/Settings.Designer.cs | 1,068 | C# |
using System;
namespace Net.Mapper
{
[AttributeUsage(AttributeTargets.Property,AllowMultiple =false)]
public class NoMapAttribute:Attribute
{
}
}
| 16.4 | 68 | 0.72561 | [
"MIT"
] | kelessal/net-mapper | Net.Mapper/NoMapAttribute.cs | 166 | C# |
using System;
using System.Drawing;
using System.Threading;
using System.Collections.Generic;
using Animatroller.Framework;
using Animatroller.Framework.Extensions;
using Expander = Animatroller.Framework.Expander;
using Animatroller.Framework.LogicalDevice;
using Import = Animatroller.Framework.Import;
using Effect = Animatroller.Framework.Effect;
using Effect2 = Animatroller.Framework.Effect2;
using Physical = Animatroller.Framework.PhysicalDevice;
using Controller = Animatroller.Framework.Controller;
using System.Threading.Tasks;
using System.Media;
using CSCore;
using CSCore.SoundOut;
using CSCore.Codecs;
namespace Animatroller.Scenes
{
internal class LORScene : BaseScene
{
IWaveSource waveSource;
ISoundOut soundOut = new WasapiOut();
//private ColorDimmer light1_1;
//private ColorDimmer light1_2;
//private ColorDimmer light1_3;
//private ColorDimmer light1_4;
//private ColorDimmer light1_5;
//private ColorDimmer light1_6;
//private ColorDimmer light1_7;
//private ColorDimmer light1_8;
//private ColorDimmer light1_9;
//private ColorDimmer light1_10;
//private ColorDimmer light1_11;
//private ColorDimmer light1_12;
//private ColorDimmer light1_13;
//private ColorDimmer light1_14;
//private ColorDimmer light1_15;
//private ColorDimmer light1_16;
//private ColorDimmer light2_1;
//private ColorDimmer light2_2;
//private ColorDimmer light2_3;
//private ColorDimmer light2_4;
//private ColorDimmer light2_5;
//private ColorDimmer light2_6;
//private ColorDimmer light2_7;
//private ColorDimmer light2_8;
//private ColorDimmer light2_9;
//private ColorDimmer light2_10;
//private ColorDimmer light2_11;
//private ColorDimmer light2_12;
//private ColorDimmer light2_13;
//private ColorDimmer light2_14;
//private ColorDimmer light2_15;
//private ColorDimmer light2_16;
//private ColorDimmer light3_1;
//private ColorDimmer light3_2;
//private ColorDimmer light3_3;
//private ColorDimmer light3_4;
//private ColorDimmer light3_5;
//private ColorDimmer light3_6;
//private ColorDimmer light3_7;
//private ColorDimmer light3_8;
//private ColorDimmer light3_9;
//private ColorDimmer light3_10;
//private ColorDimmer light3_11;
//private ColorDimmer light3_12;
//private ColorDimmer light3_13;
//private ColorDimmer light3_14;
//private ColorDimmer light3_15;
//private ColorDimmer light3_16;
//private ColorDimmer light4_1;
//private ColorDimmer light4_2;
//private ColorDimmer light4_3;
//private ColorDimmer light4_4;
//private ColorDimmer light4_5;
//private ColorDimmer light4_6;
//private ColorDimmer light4_7;
//private ColorDimmer light4_8;
//private ColorDimmer light4_9;
//private ColorDimmer light4_10;
//private ColorDimmer light4_11;
//private ColorDimmer light4_12;
//private ColorDimmer light4_13;
//private ColorDimmer light4_14;
//private ColorDimmer light4_15;
//private ColorDimmer light4_16;
private ColorDimmer3 lightRoof1 = new ColorDimmer3();
private ColorDimmer3 lightRoof2 = new ColorDimmer3();
private ColorDimmer3 lightRoof3 = new ColorDimmer3();
private ColorDimmer3 lightRoof4 = new ColorDimmer3();
private ColorDimmer3 lightSidewalk1 = new ColorDimmer3();
private ColorDimmer3 lightSidewalk2 = new ColorDimmer3();
private ColorDimmer3 lightSidewalk3 = new ColorDimmer3();
private ColorDimmer3 lightSidewalk4 = new ColorDimmer3();
private ColorDimmer3 light5_2 = new ColorDimmer3();
//private ColorDimmer light5_2;
//private ColorDimmer light5_3;
//private ColorDimmer light5_4;
//private ColorDimmer light5_5;
//private ColorDimmer light5_6;
//private ColorDimmer light5_7;
//private ColorDimmer light5_8;
//private ColorDimmer light5_9;
//private ColorDimmer light5_10;
//private ColorDimmer light5_11;
//private ColorDimmer light5_12;
//private ColorDimmer light5_13;
//private ColorDimmer light5_14;
//private ColorDimmer light5_15;
//private ColorDimmer light5_16;
private VirtualPixel1D allPixels;
private DigitalInput2 testButton = new DigitalInput2();
private Import.LorImport2 lorImport = new Import.LorImport2();
public LORScene(IEnumerable<string> args)
{
allPixels = new VirtualPixel1D(80);
allPixels.SetAll(Color.White, 0);
lorImport.LoadFromFile(@"..\..\..\Test Files\Cannon Rock104.lms");
lorImport.MapDevice("Roof 1", lightRoof1);
lorImport.MapDevice("Roof 2", lightRoof2);
lorImport.MapDevice("Roof 3", lightRoof3);
lorImport.MapDevice("Roof 4", lightRoof4);
lorImport.MapDevice("Sidewalk 1", lightSidewalk1);
lorImport.MapDevice("Sidewalk 2", lightSidewalk2);
lorImport.MapDevice("Sidewalk 3", lightSidewalk3);
lorImport.MapDevice("Sidewalk 4", lightSidewalk4);
lorImport.MapDevice("Sidewalk 5", lightSidewalk1);
lorImport.MapDevice("Sidewalk 6", lightSidewalk2);
lorImport.MapDevice("Sidewalk 7", lightSidewalk3);
lorImport.MapDevice("Sidewalk 8", lightSidewalk4);
lorImport.MapDevice("Arch 1", light5_2);
lorImport.Prepare();
lorImport.Dump();
waveSource = CodecFactory.Instance.GetCodec(@"C:\Projects\Other\ChristmasSounds\trk\21. Christmas Canon Rock.wav");
soundOut.Initialize(waveSource);
// light5_1 = lorImport.MapDevice(1, 1, name => new StrobeColorDimmer(name));
/*
light1_1 = lorImport.MapDevice(1, 1, name => new StrobeColorDimmer(name));
light1_2 = lorImport.MapDevice(1, 2, name => new StrobeColorDimmer(name));
light1_3 = lorImport.MapDevice(1, 3, name => new StrobeColorDimmer(name));
light1_4 = lorImport.MapDevice(1, 4, name => new StrobeColorDimmer(name));
light1_5 = lorImport.MapDevice(1, 5, name => new StrobeColorDimmer(name));
light1_6 = lorImport.MapDevice(1, 6, name => new StrobeColorDimmer(name));
light1_7 = lorImport.MapDevice(1, 7, name => new StrobeColorDimmer(name));
light1_8 = lorImport.MapDevice(1, 8, name => new StrobeColorDimmer(name));
light1_9 = lorImport.MapDevice(1, 9, name => new StrobeColorDimmer(name));
light1_10 = lorImport.MapDevice(1, 10, name => new StrobeColorDimmer(name));
light1_11 = lorImport.MapDevice(1, 11, name => new StrobeColorDimmer(name));
light1_12 = lorImport.MapDevice(1, 12, name => new StrobeColorDimmer(name));
light1_13 = lorImport.MapDevice(1, 13, name => new StrobeColorDimmer(name));
light1_14 = lorImport.MapDevice(1, 14, name => new StrobeColorDimmer(name));
light1_15 = lorImport.MapDevice(1, 15, name => new StrobeColorDimmer(name));
light1_16 = lorImport.MapDevice(1, 16, name => new StrobeColorDimmer(name));
light2_1 = lorImport.MapDevice(2, 1, name => new StrobeColorDimmer(name));
light2_2 = lorImport.MapDevice(2, 2, name => new StrobeColorDimmer(name));
light2_3 = lorImport.MapDevice(2, 3, name => new StrobeColorDimmer(name));
light2_4 = lorImport.MapDevice(2, 4, name => new StrobeColorDimmer(name));
light2_5 = lorImport.MapDevice(2, 5, name => new StrobeColorDimmer(name));
light2_6 = lorImport.MapDevice(2, 6, name => new StrobeColorDimmer(name));
light2_7 = lorImport.MapDevice(2, 7, name => new StrobeColorDimmer(name));
light2_8 = lorImport.MapDevice(2, 8, name => new StrobeColorDimmer(name));
light2_9 = lorImport.MapDevice(2, 9, name => new StrobeColorDimmer(name));
light2_10 = lorImport.MapDevice(2, 10, name => new StrobeColorDimmer(name));
light2_11 = lorImport.MapDevice(2, 11, name => new StrobeColorDimmer(name));
light2_12 = lorImport.MapDevice(2, 12, name => new StrobeColorDimmer(name));
light2_13 = lorImport.MapDevice(2, 13, name => new StrobeColorDimmer(name));
light2_14 = lorImport.MapDevice(2, 14, name => new StrobeColorDimmer(name));
light2_15 = lorImport.MapDevice(2, 15, name => new StrobeColorDimmer(name));
light2_16 = lorImport.MapDevice(2, 16, name => new StrobeColorDimmer(name));
light3_1 = lorImport.MapDevice(3, 1, name => new StrobeColorDimmer(name));
light3_2 = lorImport.MapDevice(3, 2, name => new StrobeColorDimmer(name));
light3_3 = lorImport.MapDevice(3, 3, name => new StrobeColorDimmer(name));
light3_4 = lorImport.MapDevice(3, 4, name => new StrobeColorDimmer(name));
light3_5 = lorImport.MapDevice(3, 5, name => new StrobeColorDimmer(name));
light3_6 = lorImport.MapDevice(3, 6, name => new StrobeColorDimmer(name));
light3_7 = lorImport.MapDevice(3, 7, name => new StrobeColorDimmer(name));
light3_8 = lorImport.MapDevice(3, 8, name => new StrobeColorDimmer(name));
light3_9 = lorImport.MapDevice(3, 9, name => new StrobeColorDimmer(name));
light3_10 = lorImport.MapDevice(3, 10, name => new StrobeColorDimmer(name));
light3_11 = lorImport.MapDevice(3, 11, name => new StrobeColorDimmer(name));
light3_12 = lorImport.MapDevice(3, 12, name => new StrobeColorDimmer(name));
light3_13 = lorImport.MapDevice(3, 13, name => new StrobeColorDimmer(name));
light3_14 = lorImport.MapDevice(3, 14, name => new StrobeColorDimmer(name));
light3_15 = lorImport.MapDevice(3, 15, name => new StrobeColorDimmer(name));
light3_16 = lorImport.MapDevice(3, 16, name => new StrobeColorDimmer(name));
light4_1 = lorImport.MapDevice(4, 1, name => new StrobeColorDimmer(name));
light4_2 = lorImport.MapDevice(4, 2, name => new StrobeColorDimmer(name));
light4_3 = lorImport.MapDevice(4, 3, name => new StrobeColorDimmer(name));
light4_4 = lorImport.MapDevice(4, 4, name => new StrobeColorDimmer(name));
light4_5 = lorImport.MapDevice(4, 5, name => new StrobeColorDimmer(name));
light4_6 = lorImport.MapDevice(4, 6, name => new StrobeColorDimmer(name));
light4_7 = lorImport.MapDevice(4, 7, name => new StrobeColorDimmer(name));
light4_8 = lorImport.MapDevice(4, 8, name => new StrobeColorDimmer(name));
light4_9 = lorImport.MapDevice(4, 9, name => new StrobeColorDimmer(name));
light4_10 = lorImport.MapDevice(4, 10, name => new StrobeColorDimmer(name));
light4_11 = lorImport.MapDevice(4, 11, name => new StrobeColorDimmer(name));
light4_12 = lorImport.MapDevice(4, 12, name => new StrobeColorDimmer(name));
light4_13 = lorImport.MapDevice(4, 13, name => new StrobeColorDimmer(name));
light4_14 = lorImport.MapDevice(4, 14, name => new StrobeColorDimmer(name));
light4_15 = lorImport.MapDevice(4, 15, name => new StrobeColorDimmer(name));
light4_16 = lorImport.MapDevice(4, 16, name => new StrobeColorDimmer(name));
light5_1 = lorImport.MapDevice(5, 1, name => new StrobeColorDimmer(name));
light5_2 = lorImport.MapDevice(5, 2, name => new StrobeColorDimmer(name));
light5_3 = lorImport.MapDevice(5, 3, name => new StrobeColorDimmer(name));
light5_4 = lorImport.MapDevice(5, 4, name => new StrobeColorDimmer(name));
light5_5 = lorImport.MapDevice(5, 5, name => new StrobeColorDimmer(name));
light5_6 = lorImport.MapDevice(5, 6, name => new StrobeColorDimmer(name));
light5_7 = lorImport.MapDevice(5, 7, name => new StrobeColorDimmer(name));
light5_8 = lorImport.MapDevice(5, 8, name => new StrobeColorDimmer(name));
light5_9 = lorImport.MapDevice(5, 9, name => new StrobeColorDimmer(name));
light5_10 = lorImport.MapDevice(5, 10, name => new StrobeColorDimmer(name));
light5_11 = lorImport.MapDevice(5, 11, name => new StrobeColorDimmer(name));
light5_12 = lorImport.MapDevice(5, 12, name => new StrobeColorDimmer(name));
light5_13 = lorImport.MapDevice(5, 13, name => new StrobeColorDimmer(name));
light5_14 = lorImport.MapDevice(5, 14, name => new StrobeColorDimmer(name));
light5_15 = lorImport.MapDevice(5, 15, name => new StrobeColorDimmer(name));
light5_16 = lorImport.MapDevice(5, 16, name => new StrobeColorDimmer(name));
*/
/*TEST light5_1 = lorImport.MapDevice(new Import.LorImport.UnitCircuit(5, 1), name => new StrobeColorDimmer(name));
for (int unit = 1; unit <= 5; unit++)
{
for (int circuit = 1; circuit <= 16; circuit++)
{
int pixelPos = (unit - 1) * 16 + circuit - 1;
var pixel = lorImport.MapDevice(new Import.LorImport.UnitCircuit(unit, circuit), name => new SinglePixel(name, allPixels, pixelPos));
//FIXME var color = lorImport.GetChannelColor(unit, circuit);
//FIXME allPixels.SetColor(pixelPos, color, 0);
log.Debug("Mapping unit {0} circuit {1} to pixel {2} [{3}]", unit, circuit, pixelPos, pixel.Name);
}
}
*/
}
public override void Start()
{
// Set color
testButton.Output.Subscribe(button =>
{
if (button)
{
this.log.Information("Button press!");
log.Debug("Sound pos: {0}", waveSource.GetMilliseconds(waveSource.Position));
}
});
}
public override void Run()
{
lorImport.Start();
soundOut.Play();
}
public override void Stop()
{
soundOut.Stop();
}
}
}
| 53.135593 | 165 | 0.592855 | [
"Unlicense",
"MIT"
] | HakanL/animatroller | Animatroller/src/Scenes/Old/ReallyOld/LORScene.cs | 15,677 | C# |
// Copyright (c) 2021 DXNET - Pomianowski Leszek & Contributors
// Copyright (c) 2010-2019 SharpDX - Alexandre Mutel & SharpDX Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using DXNET.Mathematics.Interop;
namespace DXNET.Direct2D1.Effects
{
/// <summary>
/// Built in Atlas effect.
/// </summary>
public class Atlas : Effect
{
/// <summary>
/// Initializes a new instance of <see cref="Atlas"/> effect.
/// </summary>
/// <param name="context"></param>
public Atlas(DeviceContext context) : base(context, Effect.Atlas)
{
}
/// <summary>
/// The portion of the image passed to the next effect.
/// </summary>
public RawVector4 InputRectangle
{
get
{
return GetVector4Value((int)AtlasProperties.InputRectangle);
}
set
{
SetValue((int)AtlasProperties.InputRectangle, value);
}
}
/// <summary>
/// The portion of the image passed to the next effect.
/// </summary>
public RawVector4 InputPaddingRectangle
{
get
{
return GetVector4Value((int)AtlasProperties.InputPaddingRectangle);
}
set
{
SetValue((int)AtlasProperties.InputPaddingRectangle, value);
}
}
}
} | 36.057971 | 83 | 0.632637 | [
"MIT"
] | lepoco/dxnet | Modules/DXNET.Direct2D1/Effects/Atlas.cs | 2,490 | C# |
using MediatR;
using System.Collections.Generic;
namespace UsersMgmt.App.Security.Commands.DeleteAppUser
{
public class DeleteAppUserCommand : IRequest<List<string>>
{
public string Id { get; set; }
}
}
| 20.454545 | 62 | 0.711111 | [
"MIT"
] | nagasudhirpulla/users_mgmt_csharp | src/UsersMgmt.App/Security/Commands/DeleteAppUser/DeleteAppUserCommand.cs | 227 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
[GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MkDir", CharSet = CharSet.Ansi, SetLastError = true)]
internal static partial int MkDir(string path, int mode);
}
}
| 32.133333 | 132 | 0.742739 | [
"MIT"
] | AnudeepGunukula/runtime | src/libraries/Common/src/Interop/Unix/System.Native/Interop.MkDir.cs | 482 | C# |
using System;
namespace _09.CharsToString
{
class Program
{
static void Main(string[] args)
{
var s1 = Console.ReadLine();
var s2 = Console.ReadLine();
var s3 = Console.ReadLine();
Console.WriteLine($"{s1}{s2}{s3}");
}
}
}
| 18.235294 | 47 | 0.496774 | [
"MIT"
] | Miroslav-Miro/SoftUni-Software-Engineering | CSharpFundamental/Data Types and Variables - Lab/09.CharsToString/Program.cs | 312 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DiagramaClasse
{
class PFR : Continuo
{
}
} | 13.909091 | 33 | 0.712418 | [
"MIT"
] | Frosky01/DiagramaClasseTCC | DiagramaClasse/PFR.cs | 155 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayOverseasTravelFliggyAuthorityQueryResponse.
/// </summary>
public class AlipayOverseasTravelFliggyAuthorityQueryResponse : AlipayResponse
{
/// <summary>
/// 错误码
/// </summary>
[JsonPropertyName("error_code")]
public string ErrorCode { get; set; }
/// <summary>
/// 错误描述
/// </summary>
[JsonPropertyName("error_msg")]
public string ErrorMsg { get; set; }
/// <summary>
/// 是否有权限,true有权限,false无权限
/// </summary>
[JsonPropertyName("success")]
public bool Success { get; set; }
}
}
| 25.344828 | 82 | 0.578231 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayOverseasTravelFliggyAuthorityQueryResponse.cs | 777 | C# |
namespace IOCPlatform
{
partial class FrmMain
{
/// <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.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.Btn_AddressGen = new System.Windows.Forms.ToolStripMenuItem();
this.tRC20ManagerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.eRC20ManagerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.lbl_Sync_Time = new System.Windows.Forms.Label();
this.lbl_Sync_Status = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.Btn_Sync_Stop = new System.Windows.Forms.Button();
this.Btn_Sync_Start = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.Txt_Log = new System.Windows.Forms.TextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.statusStrip1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
this.statusStrip1.Location = new System.Drawing.Point(0, 279);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(888, 26);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(100, 20);
this.toolStripStatusLabel1.Text = "System Status";
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.aboutToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(888, 28);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem1,
this.Btn_AddressGen,
this.tRC20ManagerToolStripMenuItem,
this.eRC20ManagerToolStripMenuItem,
this.toolStripMenuItem2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(46, 24);
this.fileToolStripMenuItem.Text = "File";
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(220, 6);
//
// Btn_AddressGen
//
this.Btn_AddressGen.Name = "Btn_AddressGen";
this.Btn_AddressGen.Size = new System.Drawing.Size(223, 26);
this.Btn_AddressGen.Text = "Address Generateor";
this.Btn_AddressGen.Click += new System.EventHandler(this.Btn_AddressGen_Click);
//
// tRC20ManagerToolStripMenuItem
//
this.tRC20ManagerToolStripMenuItem.Name = "tRC20ManagerToolStripMenuItem";
this.tRC20ManagerToolStripMenuItem.Size = new System.Drawing.Size(223, 26);
this.tRC20ManagerToolStripMenuItem.Text = "TRC20 Manager";
//
// eRC20ManagerToolStripMenuItem
//
this.eRC20ManagerToolStripMenuItem.Name = "eRC20ManagerToolStripMenuItem";
this.eRC20ManagerToolStripMenuItem.Size = new System.Drawing.Size(223, 26);
this.eRC20ManagerToolStripMenuItem.Text = "ERC20 Manager";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(220, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(223, 26);
this.exitToolStripMenuItem.Text = "Exit";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem3,
this.aboutToolStripMenuItem1});
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(64, 24);
this.aboutToolStripMenuItem.Text = "About";
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(130, 6);
//
// aboutToolStripMenuItem1
//
this.aboutToolStripMenuItem1.Name = "aboutToolStripMenuItem1";
this.aboutToolStripMenuItem1.Size = new System.Drawing.Size(133, 26);
this.aboutToolStripMenuItem1.Text = "About";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.lbl_Sync_Time);
this.groupBox1.Controls.Add(this.lbl_Sync_Status);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.Btn_Sync_Stop);
this.groupBox1.Controls.Add(this.Btn_Sync_Start);
this.groupBox1.Location = new System.Drawing.Point(12, 31);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(468, 112);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "TRC20-ERC20 Sync";
//
// lbl_Sync_Time
//
this.lbl_Sync_Time.AutoSize = true;
this.lbl_Sync_Time.Location = new System.Drawing.Point(297, 32);
this.lbl_Sync_Time.Name = "lbl_Sync_Time";
this.lbl_Sync_Time.Size = new System.Drawing.Size(15, 20);
this.lbl_Sync_Time.TabIndex = 1;
this.lbl_Sync_Time.Text = "-";
//
// lbl_Sync_Status
//
this.lbl_Sync_Status.AutoSize = true;
this.lbl_Sync_Status.Location = new System.Drawing.Point(129, 32);
this.lbl_Sync_Status.Name = "lbl_Sync_Status";
this.lbl_Sync_Status.Size = new System.Drawing.Size(54, 20);
this.lbl_Sync_Status.TabIndex = 1;
this.lbl_Sync_Status.Text = "Ready!";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(28, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 20);
this.label1.TabIndex = 1;
this.label1.Text = "Status :";
//
// Btn_Sync_Stop
//
this.Btn_Sync_Stop.Location = new System.Drawing.Point(254, 73);
this.Btn_Sync_Stop.Name = "Btn_Sync_Stop";
this.Btn_Sync_Stop.Size = new System.Drawing.Size(119, 29);
this.Btn_Sync_Stop.TabIndex = 0;
this.Btn_Sync_Stop.Text = "Stop";
this.Btn_Sync_Stop.UseVisualStyleBackColor = true;
//
// Btn_Sync_Start
//
this.Btn_Sync_Start.Location = new System.Drawing.Point(129, 73);
this.Btn_Sync_Start.Name = "Btn_Sync_Start";
this.Btn_Sync_Start.Size = new System.Drawing.Size(119, 29);
this.Btn_Sync_Start.TabIndex = 0;
this.Btn_Sync_Start.Text = "Start";
this.Btn_Sync_Start.UseVisualStyleBackColor = true;
this.Btn_Sync_Start.Click += new System.EventHandler(this.Btn_Sync_Start_Click);
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.Txt_Log);
this.groupBox2.Location = new System.Drawing.Point(489, 31);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(387, 233);
this.groupBox2.TabIndex = 4;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Live Log";
//
// Txt_Log
//
this.Txt_Log.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Txt_Log.Dock = System.Windows.Forms.DockStyle.Fill;
this.Txt_Log.Location = new System.Drawing.Point(3, 23);
this.Txt_Log.Multiline = true;
this.Txt_Log.Name = "Txt_Log";
this.Txt_Log.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.Txt_Log.Size = new System.Drawing.Size(381, 207);
this.Txt_Log.TabIndex = 0;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.label2);
this.groupBox3.Controls.Add(this.label3);
this.groupBox3.Controls.Add(this.label4);
this.groupBox3.Controls.Add(this.button2);
this.groupBox3.Controls.Add(this.button4);
this.groupBox3.Location = new System.Drawing.Point(12, 149);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(468, 112);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Transaction Sync";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(297, 32);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(15, 20);
this.label2.TabIndex = 1;
this.label2.Text = "-";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(129, 32);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(54, 20);
this.label3.TabIndex = 1;
this.label3.Text = "Ready!";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(28, 32);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(56, 20);
this.label4.TabIndex = 1;
this.label4.Text = "Status :";
//
// button2
//
this.button2.Location = new System.Drawing.Point(254, 73);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(119, 29);
this.button2.TabIndex = 0;
this.button2.Text = "Stop";
this.button2.UseVisualStyleBackColor = true;
//
// button4
//
this.button4.Location = new System.Drawing.Point(129, 73);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(119, 29);
this.button4.TabIndex = 0;
this.button4.Text = "Start";
this.button4.UseVisualStyleBackColor = true;
//
// FrmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(888, 305);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FrmMain";
this.Text = "FrmMain";
this.Load += new System.EventHandler(this.FrmMain_Load);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private StatusStrip statusStrip1;
private MenuStrip menuStrip1;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripSeparator toolStripMenuItem1;
private ToolStripMenuItem Btn_AddressGen;
private ToolStripMenuItem tRC20ManagerToolStripMenuItem;
private ToolStripMenuItem eRC20ManagerToolStripMenuItem;
private ToolStripSeparator toolStripMenuItem2;
private ToolStripMenuItem exitToolStripMenuItem;
private ToolStripMenuItem aboutToolStripMenuItem;
private ToolStripSeparator toolStripMenuItem3;
private ToolStripMenuItem aboutToolStripMenuItem1;
private ToolStripStatusLabel toolStripStatusLabel1;
private GroupBox groupBox1;
private Label lbl_Sync_Time;
private Label lbl_Sync_Status;
private Label label1;
private Button Btn_Sync_Start;
private Button Btn_Sync_Stop;
private GroupBox groupBox2;
private TextBox Txt_Log;
private GroupBox groupBox3;
private Label label2;
private Label label3;
private Label label4;
private Button button2;
private Button button4;
}
} | 46.361878 | 157 | 0.59453 | [
"MIT"
] | maftooh/ICO-Platform-Client | Src/IOCPlatform/IOCPlatform.UI/View/FrmMain.Designer.cs | 16,785 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.Embc.Interfaces.Models
{
using Newtonsoft.Json;
using System.Linq; using System.ComponentModel.DataAnnotations.Schema;
/// <summary>
/// timezonerule
/// </summary>
public partial class MicrosoftDynamicsCRMtimezonerule
{
/// <summary>
/// Initializes a new instance of the MicrosoftDynamicsCRMtimezonerule
/// class.
/// </summary>
public MicrosoftDynamicsCRMtimezonerule()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the MicrosoftDynamicsCRMtimezonerule
/// class.
/// </summary>
public MicrosoftDynamicsCRMtimezonerule(int? daylighthour = default(int?), int? daylightminute = default(int?), int? standardsecond = default(int?), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), int? standardmonth = default(int?), int? standardhour = default(int?), int? bias = default(int?), string _timezonedefinitionidValue = default(string), long? versionnumber = default(long?), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), int? standardday = default(int?), int? daylightbias = default(int?), int? standardminute = default(int?), string _createdonbehalfbyValue = default(string), string timezoneruleid = default(string), int? daylightyear = default(int?), int? standardbias = default(int?), int? timezoneruleversionnumber = default(int?), int? standardyear = default(int?), string _modifiedonbehalfbyValue = default(string), string _createdbyValue = default(string), int? standarddayofweek = default(int?), int? daylightsecond = default(int?), int? daylightmonth = default(int?), string _organizationidValue = default(string), int? daylightdayofweek = default(int?), string _modifiedbyValue = default(string), int? daylightday = default(int?), System.DateTimeOffset? effectivedatetime = default(System.DateTimeOffset?), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMtimezonedefinition timezonedefinitionid = default(MicrosoftDynamicsCRMtimezonedefinition), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser))
{
Daylighthour = daylighthour;
Daylightminute = daylightminute;
Standardsecond = standardsecond;
Createdon = createdon;
Standardmonth = standardmonth;
Standardhour = standardhour;
Bias = bias;
this._timezonedefinitionidValue = _timezonedefinitionidValue;
Versionnumber = versionnumber;
Modifiedon = modifiedon;
Standardday = standardday;
Daylightbias = daylightbias;
Standardminute = standardminute;
this._createdonbehalfbyValue = _createdonbehalfbyValue;
Timezoneruleid = timezoneruleid;
Daylightyear = daylightyear;
Standardbias = standardbias;
Timezoneruleversionnumber = timezoneruleversionnumber;
Standardyear = standardyear;
this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue;
this._createdbyValue = _createdbyValue;
Standarddayofweek = standarddayofweek;
Daylightsecond = daylightsecond;
Daylightmonth = daylightmonth;
this._organizationidValue = _organizationidValue;
Daylightdayofweek = daylightdayofweek;
this._modifiedbyValue = _modifiedbyValue;
Daylightday = daylightday;
Effectivedatetime = effectivedatetime;
Createdby = createdby;
Createdonbehalfby = createdonbehalfby;
Timezonedefinitionid = timezonedefinitionid;
Modifiedonbehalfby = modifiedonbehalfby;
Modifiedby = modifiedby;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylighthour")]
public int? Daylighthour { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylightminute")]
public int? Daylightminute { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standardsecond")]
public int? Standardsecond { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdon")]
public System.DateTimeOffset? Createdon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standardmonth")]
public int? Standardmonth { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standardhour")]
public int? Standardhour { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bias")]
public int? Bias { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_timezonedefinitionid_value")]
public string _timezonedefinitionidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public long? Versionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedon")]
public System.DateTimeOffset? Modifiedon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standardday")]
public int? Standardday { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylightbias")]
public int? Daylightbias { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standardminute")]
public int? Standardminute { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdonbehalfby_value")]
public string _createdonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "timezoneruleid")]
public string Timezoneruleid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylightyear")]
public int? Daylightyear { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standardbias")]
public int? Standardbias { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "timezoneruleversionnumber")]
public int? Timezoneruleversionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standardyear")]
public int? Standardyear { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedonbehalfby_value")]
public string _modifiedonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdby_value")]
public string _createdbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "standarddayofweek")]
public int? Standarddayofweek { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylightsecond")]
public int? Daylightsecond { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylightmonth")]
public int? Daylightmonth { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_organizationid_value")]
public string _organizationidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylightdayofweek")]
public int? Daylightdayofweek { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedby_value")]
public string _modifiedbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "daylightday")]
public int? Daylightday { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "effectivedatetime")]
public System.DateTimeOffset? Effectivedatetime { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdby")]
public MicrosoftDynamicsCRMsystemuser Createdby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdonbehalfby")]
public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "timezonedefinitionid")]
public MicrosoftDynamicsCRMtimezonedefinition Timezonedefinitionid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedonbehalfby")]
public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedby")]
public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; }
}
}
| 39.898374 | 1,743 | 0.622517 | [
"Apache-2.0"
] | CodingVelocista/embc-ess | embc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMtimezonerule.cs | 9,815 | 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.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Common;
namespace Microsoft.Data.SqlClient
{
sealed internal class LastIOTimer
{
internal long _value;
}
internal abstract class TdsParserStateObject
{
private const int AttentionTimeoutSeconds = 5;
// Ticks to consider a connection "good" after a successful I/O (10,000 ticks = 1 ms)
// The resolution of the timer is typically in the range 10 to 16 milliseconds according to msdn.
// We choose a value that is smaller than the likely timer resolution, but
// large enough to ensure that check connection execution will be 0.1% or less
// of very small open, query, close loops.
private const long CheckConnectionWindow = 50000;
protected readonly TdsParser _parser; // TdsParser pointer
private readonly WeakReference _owner = new WeakReference(null); // the owner of this session, used to track when it's been orphaned
internal SqlDataReader.SharedState _readerState; // susbset of SqlDataReader state (if it is the owner) necessary for parsing abandoned results in TDS
private int _activateCount; // 0 when we're in the pool, 1 when we're not, all others are an error
// Two buffers exist in tdsparser, an in buffer and an out buffer. For the out buffer, only
// one bookkeeping variable is needed, the number of bytes used in the buffer. For the in buffer,
// three variables are actually needed. First, we need to record from the netlib how many bytes it
// read from the netlib, this variable is _inBytesRead. Then, we need to also keep track of how many
// bytes we have used as we consume the bytes from the buffer, that variable is _inBytesUsed. Third,
// we need to keep track of how many bytes are left in the packet, so that we know when we have reached
// the end of the packet and so we need to consume the next header. That variable is _inBytesPacket.
// Header length constants
internal readonly int _inputHeaderLen = TdsEnums.HEADER_LEN;
internal readonly int _outputHeaderLen = TdsEnums.HEADER_LEN;
// Out buffer variables
internal byte[] _outBuff; // internal write buffer - initialize on login
internal int _outBytesUsed = TdsEnums.HEADER_LEN; // number of bytes used in internal write buffer -
// - initialize past header
// In buffer variables
protected byte[] _inBuff; // internal read buffer - initialize on login
internal int _inBytesUsed = 0; // number of bytes used in internal read buffer
internal int _inBytesRead = 0; // number of bytes read into internal read buffer
internal int _inBytesPacket = 0; // number of bytes left in packet
// Packet state variables
internal byte _outputMessageType = 0; // tds header type
internal byte _messageStatus; // tds header status
internal byte _outputPacketNumber = 1; // number of packets sent to server in message - start at 1 per ramas
internal uint _outputPacketCount;
internal bool _pendingData = false;
internal volatile bool _fResetEventOwned = false; // ResetEvent serializing call to sp_reset_connection
internal volatile bool _fResetConnectionSent = false; // For multiple packet execute
internal bool _errorTokenReceived = false; // Keep track of whether an error was received for the result.
// This is reset upon each done token - there can be
internal bool _bulkCopyOpperationInProgress = false; // Set to true during bulk copy and used to turn toggle write timeouts.
internal bool _bulkCopyWriteTimeout = false; // Set to trun when _bulkCopyOpeperationInProgress is trun and write timeout happens
// SNI variables // multiple resultsets in one batch.
protected readonly object _writePacketLockObject = new object(); // Used to synchronize access to _writePacketCache and _pendingWritePackets
// Async variables
private int _pendingCallbacks; // we increment this before each async read/write call and decrement it in the callback. We use this to determine when to release the GcHandle...
// Timeout variables
private long _timeoutMilliseconds;
private long _timeoutTime; // variable used for timeout computations, holds the value of the hi-res performance counter at which this request should expire
internal volatile bool _attentionSent = false; // true if we sent an Attention to the server
internal bool _attentionReceived = false; // NOTE: Received is not volatile as it is only ever accessed\modified by TryRun its callees (i.e. single threaded access)
internal volatile bool _attentionSending = false;
internal bool _internalTimeout = false; // an internal timeout occurred
private readonly LastIOTimer _lastSuccessfulIOTimer;
// secure password information to be stored
// At maximum number of secure string that need to be stored is two; one for login password and the other for new change password
private SecureString[] _securePasswords = new SecureString[2] { null, null };
private int[] _securePasswordOffsetsInBuffer = new int[2];
// This variable is used to track whether another thread has requested a cancel. The
// synchronization points are
// On the user's execute thread:
// 1) the first packet write
// 2) session close - return this stateObj to the session pool
// On cancel thread we only have the cancel call.
// Currently all access to this variable is inside a lock, The state diagram is:
// 1) pre first packet write, if cancel is requested, set variable so exception is triggered
// on user thread when first packet write is attempted
// 2) post first packet write, but before session return - a call to cancel will send an
// attention to the server
// 3) post session close - no attention is allowed
private bool _cancelled;
private const int _waitForCancellationLockPollTimeout = 100;
private WeakReference _cancellationOwner = new WeakReference(null);
internal bool _hasOpenResult = false;
// Cache the transaction for which this command was executed so upon completion we can
// decrement the appropriate result count.
internal SqlInternalTransaction _executedUnderTransaction = null;
// TDS stream processing variables
internal ulong _longlen; // plp data length indicator
internal ulong _longlenleft; // Length of data left to read (64 bit lengths)
internal int[] _decimalBits = null; // scratch buffer for decimal/numeric data
internal byte[] _bTmp = new byte[TdsEnums.YUKON_HEADER_LEN]; // Scratch buffer for misc use
internal int _bTmpRead = 0; // Counter for number of temporary bytes read
internal Decoder _plpdecoder = null; // Decoder object to process plp character data
internal bool _accumulateInfoEvents = false; // TRUE - accumulate info messages during TdsParser.Run, FALSE - fire them
internal List<SqlError> _pendingInfoEvents = null;
internal byte[] _bLongBytes = null; // scratch buffer to serialize Long values (8 bytes).
internal byte[] _bIntBytes = null; // scratch buffer to serialize Int values (4 bytes).
internal byte[] _bShortBytes = null; // scratch buffer to serialize Short values (2 bytes).
internal byte[] _bDecimalBytes = null; // scratch buffer to serialize decimal values (17 bytes).
//
// DO NOT USE THIS BUFFER FOR OTHER THINGS.
// ProcessHeader can be called ANYTIME while doing network reads.
private byte[] _partialHeaderBuffer = new byte[TdsEnums.HEADER_LEN]; // Scratch buffer for ProcessHeader
internal int _partialHeaderBytesRead = 0;
internal _SqlMetaDataSet _cleanupMetaData = null;
internal _SqlMetaDataSetCollection _cleanupAltMetaDataSetArray = null;
internal bool _receivedColMetaData; // Used to keep track of when to fire StatementCompleted event.
private SniContext _sniContext = SniContext.Undefined;
#if DEBUG
private SniContext _debugOnlyCopyOfSniContext = SniContext.Undefined;
#endif
private bool _bcpLock = false;
// Null bitmap compression (NBC) information for the current row
private NullBitmap _nullBitmapInfo;
// Async
internal TaskCompletionSource<object> _networkPacketTaskSource;
private Timer _networkPacketTimeout;
internal bool _syncOverAsync = true;
private bool _snapshotReplay = false;
private StateSnapshot _snapshot;
internal ExecutionContext _executionContext;
internal bool _asyncReadWithoutSnapshot = false;
#if DEBUG
// Used to override the assert than ensures that the stacktraces on subsequent replays are the same
// This is useful is you are purposefully running the replay from a different thread (e.g. during SqlDataReader.Close)
internal bool _permitReplayStackTraceToDiffer = false;
// Used to indicate that the higher level object believes that this stateObj has enough data to complete an operation
// If this stateObj has to read, then it will raise an assert
internal bool _shouldHaveEnoughData = false;
#endif
// local exceptions to cache warnings and errors
internal SqlErrorCollection _errors;
internal SqlErrorCollection _warnings;
internal object _errorAndWarningsLock = new object();
private bool _hasErrorOrWarning = false;
// local exceptions to cache warnings and errors that occurred prior to sending attention
internal SqlErrorCollection _preAttentionErrors;
internal SqlErrorCollection _preAttentionWarnings;
private volatile TaskCompletionSource<object> _writeCompletionSource = null;
protected volatile int _asyncWriteCount = 0;
private volatile Exception _delayedWriteAsyncCallbackException = null; // set by write async callback if completion source is not yet created
// _readingcount is incremented when we are about to read.
// We check the parser state afterwards.
// When the read is completed, we decrement it before handling errors
// as the error handling may end up calling Dispose.
private int _readingCount;
// Test hooks
#if DEBUG
// This is a test hook to enable testing of the retry paths.
// When set to true, almost every possible retry point will be attempted.
// This will drastically impact performance.
//
// Sample code to enable:
//
// Type type = typeof(SqlDataReader).Assembly.GetType("Microsoft.Data.SqlClient.TdsParserStateObject");
// System.Reflection.FieldInfo field = type.GetField("_forceAllPends", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
// if (field != null) {
// field.SetValue(null, true);
// }
//
internal static bool _forceAllPends = false;
// set this while making a call that should not block.
// instead of blocking it will fail.
internal static bool _failAsyncPends = false;
// If this is set and an async read is made, then
// we will switch to syncOverAsync mode for the
// remainder of the async operation.
internal static bool _forceSyncOverAsyncAfterFirstPend = false;
// Requests to send attention will be ignored when _skipSendAttention is true.
// This is useful to simulate circumstances where timeouts do not recover.
internal static bool _skipSendAttention = false;
// Prevents any pending read from completing until the user signals it using
// CompletePendingReadWithSuccess() or CompletePendingReadWithFailure(int errorCode) in SqlCommand\SqlDataReader
internal static bool _forcePendingReadsToWaitForUser;
internal TaskCompletionSource<object> _realNetworkPacketTaskSource = null;
// Field is never assigned to, and will always have its default value
#pragma warning disable 0649
// Set to true to enable checking the call stacks match when packet retry occurs.
internal static bool _checkNetworkPacketRetryStacks;
#pragma warning restore 0649
#endif
//////////////////
// Constructors //
//////////////////
internal TdsParserStateObject(TdsParser parser)
{
// Construct a physical connection
Debug.Assert(null != parser, "no parser?");
_parser = parser;
// For physical connection, initialize to default login packet size.
SetPacketSize(TdsEnums.DEFAULT_LOGIN_PACKET_SIZE);
// we post a callback that represents the call to dispose; once the
// object is disposed, the next callback will cause the GC Handle to
// be released.
IncrementPendingCallbacks();
_lastSuccessfulIOTimer = new LastIOTimer();
}
internal TdsParserStateObject(TdsParser parser, TdsParserStateObject physicalConnection, bool async)
{
// Construct a MARS session
Debug.Assert(null != parser, "no parser?");
_parser = parser;
SniContext = SniContext.Snix_GetMarsSession;
Debug.Assert(null != _parser._physicalStateObj, "no physical session?");
Debug.Assert(null != _parser._physicalStateObj._inBuff, "no in buffer?");
Debug.Assert(null != _parser._physicalStateObj._outBuff, "no out buffer?");
Debug.Assert(_parser._physicalStateObj._outBuff.Length ==
_parser._physicalStateObj._inBuff.Length, "Unexpected unequal buffers.");
// Determine packet size based on physical connection buffer lengths.
SetPacketSize(_parser._physicalStateObj._outBuff.Length);
CreateSessionHandle(physicalConnection, async);
if (IsFailedHandle())
{
AddError(parser.ProcessSNIError(this));
ThrowExceptionAndWarning();
}
// we post a callback that represents the call to dispose; once the
// object is disposed, the next callback will cause the GC Handle to
// be released.
IncrementPendingCallbacks();
_lastSuccessfulIOTimer = parser._physicalStateObj._lastSuccessfulIOTimer;
}
////////////////
// Properties //
////////////////
// BcpLock - use to lock this object if there is a potential risk of using this object
// between tds packets
internal bool BcpLock
{
get
{
return _bcpLock;
}
set
{
_bcpLock = value;
}
}
#if DEBUG
internal SniContext DebugOnlyCopyOfSniContext
{
get
{
return _debugOnlyCopyOfSniContext;
}
}
#endif
internal bool HasOpenResult
{
get
{
return _hasOpenResult;
}
}
#if DEBUG
internal void InvalidateDebugOnlyCopyOfSniContext()
{
_debugOnlyCopyOfSniContext = SniContext.Undefined;
}
#endif
internal bool IsOrphaned
{
get
{
Debug.Assert((0 == _activateCount && !_owner.IsAlive) // in pool
|| (1 == _activateCount && _owner.IsAlive && _owner.Target != null)
|| (1 == _activateCount && !_owner.IsAlive), "Unknown state on TdsParserStateObject.IsOrphaned!");
return (0 != _activateCount && !_owner.IsAlive);
}
}
internal object Owner
{
set
{
Debug.Assert(value == null || !_owner.IsAlive || ((value is SqlDataReader) && (((SqlDataReader)value).Command == _owner.Target)), "Should not be changing the owner of an owned stateObj");
SqlDataReader reader = value as SqlDataReader;
if (reader == null)
{
_readerState = null;
}
else
{
_readerState = reader._sharedState;
}
_owner.Target = value;
}
}
internal abstract uint DisabeSsl();
internal bool HasOwner
{
get
{
return _owner.IsAlive;
}
}
internal TdsParser Parser
{
get
{
return _parser;
}
}
internal abstract uint EnableMars(ref uint info);
internal SniContext SniContext
{
get
{
return _sniContext;
}
set
{
_sniContext = value;
#if DEBUG
_debugOnlyCopyOfSniContext = value;
#endif
}
}
internal abstract uint Status
{
get;
}
internal abstract SessionHandle SessionHandle
{
get;
}
internal bool TimeoutHasExpired
{
get
{
Debug.Assert(0 == _timeoutMilliseconds || 0 == _timeoutTime, "_timeoutTime hasn't been reset");
return TdsParserStaticMethods.TimeoutHasExpired(_timeoutTime);
}
}
internal long TimeoutTime
{
get
{
if (0 != _timeoutMilliseconds)
{
_timeoutTime = TdsParserStaticMethods.GetTimeout(_timeoutMilliseconds);
_timeoutMilliseconds = 0;
}
return _timeoutTime;
}
set
{
_timeoutMilliseconds = 0;
_timeoutTime = value;
}
}
internal int GetTimeoutRemaining()
{
int remaining;
if (0 != _timeoutMilliseconds)
{
remaining = (int)Math.Min((long)int.MaxValue, _timeoutMilliseconds);
_timeoutTime = TdsParserStaticMethods.GetTimeout(_timeoutMilliseconds);
_timeoutMilliseconds = 0;
}
else
{
remaining = TdsParserStaticMethods.GetTimeoutMilliseconds(_timeoutTime);
}
return remaining;
}
internal bool TryStartNewRow(bool isNullCompressed, int nullBitmapColumnsCount = 0)
{
Debug.Assert(!isNullCompressed || nullBitmapColumnsCount > 0, "Null-Compressed row requires columns count");
if (_snapshot != null)
{
_snapshot.CloneNullBitmapInfo();
}
// initialize or unset null bitmap information for the current row
if (isNullCompressed)
{
// assert that NBCROW is not in use by Yukon or before
Debug.Assert(_parser.IsKatmaiOrNewer, "NBCROW is sent by pre-Katmai server");
if (!_nullBitmapInfo.TryInitialize(this, nullBitmapColumnsCount))
{
return false;
}
}
else
{
_nullBitmapInfo.Clean();
}
return true;
}
internal bool IsRowTokenReady()
{
// Removing one byte since TryReadByteArray\TryReadByte will aggressively read the next packet if there is no data left - so we need to ensure there is a spare byte
int bytesRemaining = Math.Min(_inBytesPacket, _inBytesRead - _inBytesUsed) - 1;
if (bytesRemaining > 0)
{
if (_inBuff[_inBytesUsed] == TdsEnums.SQLROW)
{
// At a row token, so we're ready
return true;
}
else if (_inBuff[_inBytesUsed] == TdsEnums.SQLNBCROW)
{
// NBC row token, ensure that we have enough data for the bitmap
// SQLNBCROW + Null Bitmap (copied from NullBitmap.TryInitialize)
int bytesToRead = 1 + (_cleanupMetaData.Length + 7) / 8;
return (bytesToRead <= bytesRemaining);
}
}
// No data left, or not at a row token
return false;
}
internal bool IsNullCompressionBitSet(int columnOrdinal)
{
return _nullBitmapInfo.IsGuaranteedNull(columnOrdinal);
}
private struct NullBitmap
{
private byte[] _nullBitmap;
private int _columnsCount; // set to 0 if not used or > 0 for NBC rows
internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount)
{
_columnsCount = columnsCount;
// 1-8 columns need 1 byte
// 9-16: 2 bytes, and so on
int bitmapArrayLength = (columnsCount + 7) / 8;
// allow reuse of previously allocated bitmap
if (_nullBitmap == null || _nullBitmap.Length != bitmapArrayLength)
{
_nullBitmap = new byte[bitmapArrayLength];
}
// read the null bitmap compression information from TDS
if (!stateObj.TryReadByteArray(_nullBitmap, _nullBitmap.Length))
{
return false;
}
return true;
}
internal bool ReferenceEquals(NullBitmap obj)
{
return object.ReferenceEquals(_nullBitmap, obj._nullBitmap);
}
internal NullBitmap Clone()
{
NullBitmap newBitmap = new NullBitmap();
newBitmap._nullBitmap = _nullBitmap == null ? null : (byte[])_nullBitmap.Clone();
newBitmap._columnsCount = _columnsCount;
return newBitmap;
}
internal void Clean()
{
_columnsCount = 0;
// no need to free _nullBitmap array - it is cached for the next row
}
/// <summary>
/// If this method returns true, the value is guaranteed to be null. This is not true vice versa:
/// if the bitmap value is false (if this method returns false), the value can be either null or non-null - no guarantee in this case.
/// To determine whether it is null or not, read it from the TDS (per NBCROW design spec, for IMAGE/TEXT/NTEXT columns server might send
/// bitmap = 0, when the actual value is null).
/// </summary>
internal bool IsGuaranteedNull(int columnOrdinal)
{
if (_columnsCount == 0)
{
// not an NBC row
return false;
}
Debug.Assert(columnOrdinal >= 0 && columnOrdinal < _columnsCount, "Invalid column ordinal");
byte testBit = (byte)(1 << (columnOrdinal & 0x7)); // columnOrdinal & 0x7 == columnOrdinal MOD 0x7
byte testByte = _nullBitmap[columnOrdinal >> 3];
return (testBit & testByte) != 0;
}
}
/////////////////////
// General methods //
/////////////////////
// If this object is part of a TdsParserSessionPool, then this *must* be called inside the pool's lock
internal void Activate(object owner)
{
Debug.Assert(_parser.MARSOn, "Can not activate a non-MARS connection");
Owner = owner; // must assign an owner for reclamation to work
int result = Interlocked.Increment(ref _activateCount); // must have non-zero activation count for reclamation to work too.
Debug.Assert(result == 1, "invalid deactivate count");
}
// This method is only called by the command or datareader as a result of a user initiated
// cancel request.
internal void Cancel(object caller)
{
Debug.Assert(caller != null, "Null caller for Cancel!");
Debug.Assert(caller is SqlCommand || caller is SqlDataReader, "Calling API with invalid caller type: " + caller.GetType());
bool hasLock = false;
try
{
// Keep looping until we either grabbed the lock (and therefore sent attention) or the connection closes\breaks
while ((!hasLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
{
Monitor.TryEnter(this, _waitForCancellationLockPollTimeout, ref hasLock);
if (hasLock)
{ // Lock for the time being - since we need to synchronize the attention send.
// This lock is also protecting against concurrent close and async continuations
// Ensure that, once we have the lock, that we are still the owner
if ((!_cancelled) && (_cancellationOwner.Target == caller))
{
_cancelled = true;
if (_pendingData && !_attentionSent)
{
bool hasParserLock = false;
// Keep looping until we have the parser lock (and so are allowed to write), or the connection closes\breaks
while ((!hasParserLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
{
try
{
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false, timeout: _waitForCancellationLockPollTimeout, lockTaken: ref hasParserLock);
if (hasParserLock)
{
_parser.Connection.ThreadHasParserLockForClose = true;
SendAttention();
}
}
finally
{
if (hasParserLock)
{
if (_parser.Connection.ThreadHasParserLockForClose)
{
_parser.Connection.ThreadHasParserLockForClose = false;
}
_parser.Connection._parserLock.Release();
}
}
}
}
}
}
}
}
finally
{
if (hasLock)
{
Monitor.Exit(this);
}
}
}
// CancelRequest - use to cancel while writing a request to the server
//
// o none of the request might have been sent to the server, simply reset the buffer,
// sending attention does not hurt
// o the request was partially written. Send an ignore header to the server. attention is
// required if the server was waiting for data (e.g. insert bulk rows)
// o the request was completely written out and the server started to process the request.
// attention is required to have the server stop processing.
//
internal void CancelRequest()
{
ResetBuffer(); // clear out unsent buffer
// If the first sqlbulkcopy timeout, _outputPacketNumber may not be 1,
// the next sqlbulkcopy (same connection string) requires this to be 1, hence reset
// it here when exception happens in the first sqlbulkcopy
ResetPacketCounters();
// VSDD#907507, if bulkcopy write timeout happens, it already sent the attention,
// so no need to send it again
if (!_bulkCopyWriteTimeout)
{
SendAttention();
Parser.ProcessPendingAck(this);
}
}
public void CheckSetResetConnectionState(uint error, CallbackType callbackType)
{
// Should only be called for MARS - that is the only time we need to take
// the ResetConnection lock!
// It was raised in a security review by Microsoft questioning whether
// we need to actually process the resulting packet (sp_reset ack or error) to know if the
// reset actually succeeded. There was a concern that if the reset failed and we proceeded
// there might be a security issue present. We have been assured by the server that if
// sp_reset fails, they guarantee they will kill the resulting connection. So - it is
// safe for us to simply receive the packet and then consume the pre-login later.
Debug.Assert(_parser.MARSOn, "Should not be calling CheckSetResetConnectionState on non MARS connection");
if (_fResetEventOwned)
{
if (callbackType == CallbackType.Read && TdsEnums.SNI_SUCCESS == error)
{
// RESET SUCCEEDED!
// If we are on read callback and no error occurred (and we own reset event) -
// then we sent the sp_reset_connection and so we need to reset sp_reset_connection
// flag to false, and then release the ResetEvent.
_parser._fResetConnection = false;
_fResetConnectionSent = false;
_fResetEventOwned = !_parser._resetConnectionEvent.Set();
Debug.Assert(!_fResetEventOwned, "Invalid AutoResetEvent state!");
}
if (TdsEnums.SNI_SUCCESS != error)
{
// RESET FAILED!
// If write or read failed with reset, we need to clear event but not mark connection
// as reset.
_fResetConnectionSent = false;
_fResetEventOwned = !_parser._resetConnectionEvent.Set();
Debug.Assert(!_fResetEventOwned, "Invalid AutoResetEvent state!");
}
}
}
internal void CloseSession()
{
ResetCancelAndProcessAttention();
#if DEBUG
InvalidateDebugOnlyCopyOfSniContext();
#endif
Parser.PutSession(this);
}
private void ResetCancelAndProcessAttention()
{
// This method is shared by CloseSession initiated by DataReader.Close or completed
// command execution, as well as the session reclamation code for cases where the
// DataReader is opened and then GC'ed.
lock (this)
{
// Reset cancel state.
_cancelled = false;
_cancellationOwner.Target = null;
if (_attentionSent)
{
// Make sure we're cleaning up the AttentionAck if Cancel happened before taking the lock.
// We serialize Cancel/CloseSession to prevent a race condition between these two states.
// The problem is that both sending and receiving attentions are time taking
// operations.
Parser.ProcessPendingAck(this);
}
_internalTimeout = false;
}
}
internal abstract void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool fParallel, bool isIntegratedSecurity = false);
internal abstract uint SniGetConnectionId(ref Guid clientConnectionId);
internal abstract bool IsFailedHandle();
protected abstract void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async);
protected abstract void FreeGcHandle(int remaining, bool release);
internal abstract uint EnableSsl(ref uint info);
internal abstract uint WaitForSSLHandShakeToComplete();
internal abstract void Dispose();
internal abstract void DisposePacketCache();
internal abstract bool IsPacketEmpty(PacketHandle readPacket);
internal abstract PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error);
internal abstract PacketHandle ReadAsync(SessionHandle handle, out uint error);
internal abstract uint CheckConnection();
internal abstract uint SetConnectionBufferSize(ref uint unsignedPacketSize);
internal abstract void ReleasePacket(PacketHandle syncReadPacket);
protected abstract uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize);
internal abstract PacketHandle GetResetWritePacket();
internal abstract void ClearAllWritePackets();
internal abstract PacketHandle AddPacketToPendingList(PacketHandle packet);
protected abstract void RemovePacketFromPendingList(PacketHandle pointer);
internal abstract uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer);
internal bool Deactivate()
{
bool goodForReuse = false;
try
{
TdsParserState state = Parser.State;
if (state != TdsParserState.Broken && state != TdsParserState.Closed)
{
if (_pendingData)
{
Parser.DrainData(this); // This may throw - taking us to catch block.c
}
if (HasOpenResult)
{
DecrementOpenResultCount();
}
ResetCancelAndProcessAttention();
goodForReuse = true;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
}
return goodForReuse;
}
// If this object is part of a TdsParserSessionPool, then this *must* be called inside the pool's lock
internal void RemoveOwner()
{
if (_parser.MARSOn)
{
// We only care about the activation count for MARS connections
int result = Interlocked.Decrement(ref _activateCount); // must have non-zero activation count for reclamation to work too.
Debug.Assert(result == 0, "invalid deactivate count");
}
Owner = null;
}
internal void DecrementOpenResultCount()
{
if (_executedUnderTransaction == null)
{
// If we were not executed under a transaction - decrement the global count
// on the parser.
_parser.DecrementNonTransactedOpenResultCount();
}
else
{
// If we were executed under a transaction - decrement the count on the transaction.
_executedUnderTransaction.DecrementAndObtainOpenResultCount();
_executedUnderTransaction = null;
}
_hasOpenResult = false;
}
internal int DecrementPendingCallbacks(bool release)
{
int remaining = Interlocked.Decrement(ref _pendingCallbacks);
FreeGcHandle(remaining, release);
// NOTE: TdsParserSessionPool may call DecrementPendingCallbacks on a TdsParserStateObject which is already disposed
// This is not dangerous (since the stateObj is no longer in use), but we need to add a workaround in the assert for it
Debug.Assert((remaining == -1 && SessionHandle.IsNull) || (0 <= remaining && remaining < 3), $"_pendingCallbacks values is invalid after decrementing: {remaining}");
return remaining;
}
internal void DisposeCounters()
{
Timer networkPacketTimeout = _networkPacketTimeout;
if (networkPacketTimeout != null)
{
_networkPacketTimeout = null;
networkPacketTimeout.Dispose();
}
Debug.Assert(Volatile.Read(ref _readingCount) >= 0, "_readingCount is negative");
if (Volatile.Read(ref _readingCount) > 0)
{
// if _reading is true, we need to wait for it to complete
// if _reading is false, then future read attempts will
// already see the null _sessionHandle and abort.
// We block after nulling _sessionHandle but before disposing it
// to give a chance for a read that has already grabbed the
// handle to complete.
SpinWait.SpinUntil(() => Volatile.Read(ref _readingCount) == 0);
}
}
internal int IncrementAndObtainOpenResultCount(SqlInternalTransaction transaction)
{
_hasOpenResult = true;
if (transaction == null)
{
// If we are not passed a transaction, we are not executing under a transaction
// and thus we should increment the global connection result count.
return _parser.IncrementNonTransactedOpenResultCount();
}
else
{
// If we are passed a transaction, we are executing under a transaction
// and thus we should increment the transaction's result count.
_executedUnderTransaction = transaction;
return transaction.IncrementAndObtainOpenResultCount();
}
}
internal int IncrementPendingCallbacks()
{
int remaining = Interlocked.Increment(ref _pendingCallbacks);
Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}");
return remaining;
}
internal void SetTimeoutSeconds(int timeout)
{
SetTimeoutMilliseconds((long)timeout * 1000L);
}
internal void SetTimeoutMilliseconds(long timeout)
{
if (timeout <= 0)
{
// 0 or less (i.e. Timespan.Infinite) == infinite (which is represented by Int64.MaxValue)
_timeoutMilliseconds = 0;
_timeoutTime = long.MaxValue;
}
else
{
_timeoutMilliseconds = timeout;
_timeoutTime = 0;
}
}
internal void StartSession(object cancellationOwner)
{
_cancellationOwner.Target = cancellationOwner;
}
internal void ThrowExceptionAndWarning(bool callerHasConnectionLock = false, bool asyncClose = false)
{
_parser.ThrowExceptionAndWarning(this, callerHasConnectionLock, asyncClose);
}
////////////////////////////////////////////
// TDS Packet/buffer manipulation methods //
////////////////////////////////////////////
internal Task ExecuteFlush()
{
lock (this)
{
if (_cancelled && 1 == _outputPacketNumber)
{
ResetBuffer();
_cancelled = false;
throw SQL.OperationCancelled();
}
else
{
Task writePacketTask = WritePacket(TdsEnums.HARDFLUSH);
if (writePacketTask == null)
{
_pendingData = true;
_messageStatus = 0;
return null;
}
else
{
return AsyncHelper.CreateContinuationTask(writePacketTask, () => { _pendingData = true; _messageStatus = 0; });
}
}
}
}
// Processes the tds header that is present in the buffer
internal bool TryProcessHeader()
{
Debug.Assert(_inBytesPacket == 0, "there should not be any bytes left in packet when ReadHeader is called");
// if the header splits buffer reads - special case!
if ((_partialHeaderBytesRead > 0) || (_inBytesUsed + _inputHeaderLen > _inBytesRead))
{
// VSTS 219884: when some kind of MITM (man-in-the-middle) tool splits the network packets, the message header can be split over
// several network packets.
// Note: cannot use ReadByteArray here since it uses _inBytesPacket which is not set yet.
do
{
int copy = Math.Min(_inBytesRead - _inBytesUsed, _inputHeaderLen - _partialHeaderBytesRead);
Debug.Assert(copy > 0, "ReadNetworkPacket read empty buffer");
Buffer.BlockCopy(_inBuff, _inBytesUsed, _partialHeaderBuffer, _partialHeaderBytesRead, copy);
_partialHeaderBytesRead += copy;
_inBytesUsed += copy;
Debug.Assert(_partialHeaderBytesRead <= _inputHeaderLen, "Read more bytes for header than required");
if (_partialHeaderBytesRead == _inputHeaderLen)
{
// All read
_partialHeaderBytesRead = 0;
_inBytesPacket = ((int)_partialHeaderBuffer[TdsEnums.HEADER_LEN_FIELD_OFFSET] << 8 |
(int)_partialHeaderBuffer[TdsEnums.HEADER_LEN_FIELD_OFFSET + 1]) - _inputHeaderLen;
_messageStatus = _partialHeaderBuffer[1];
}
else
{
Debug.Assert(_inBytesUsed == _inBytesRead, "Did not use all data while reading partial header");
// Require more data
if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
{
// NOTE: ReadNetworkPacket does nothing if the parser state is closed or broken
// to avoid infinite loop, we raise an exception
ThrowExceptionAndWarning();
return true;
}
if (!TryReadNetworkPacket())
{
return false;
}
if (_internalTimeout)
{
ThrowExceptionAndWarning();
return true;
}
}
} while (_partialHeaderBytesRead != 0); // This is reset to 0 once we have read everything that we need
AssertValidState();
}
else
{
// normal header processing...
_messageStatus = _inBuff[_inBytesUsed + 1];
_inBytesPacket = ((int)_inBuff[_inBytesUsed + TdsEnums.HEADER_LEN_FIELD_OFFSET] << 8 |
(int)_inBuff[_inBytesUsed + TdsEnums.HEADER_LEN_FIELD_OFFSET + 1]) - _inputHeaderLen;
_inBytesUsed += _inputHeaderLen;
AssertValidState();
}
if (_inBytesPacket < 0)
{
// either TDS stream is corrupted or there is multithreaded misuse of connection
throw SQL.ParsingError();
}
return true;
}
// This ensure that there is data available to be read in the buffer and that the header has been processed
// NOTE: This method (and all it calls) should be retryable without replaying a snapshot
internal bool TryPrepareBuffer()
{
Debug.Assert(_inBuff != null, "packet buffer should not be null!");
// Header spans packets, or we haven't read the header yet - process header
if ((_inBytesPacket == 0) && (_inBytesUsed < _inBytesRead))
{
if (!TryProcessHeader())
{
return false;
}
Debug.Assert(_inBytesPacket != 0, "_inBytesPacket cannot be 0 after processing header!");
AssertValidState();
}
// If we're out of data, need to read more
if (_inBytesUsed == _inBytesRead)
{
// If the _inBytesPacket is not zero, then we have data left in the packet, but the data in the packet
// spans the buffer, so we can read any amount of data possible, and we do not need to call ProcessHeader
// because there isn't a header at the beginning of the data that we are reading.
if (_inBytesPacket > 0)
{
if (!TryReadNetworkPacket())
{
return false;
}
}
else if (_inBytesPacket == 0)
{
// Else we have finished the packet and so we must read as much data as possible
if (!TryReadNetworkPacket())
{
return false;
}
if (!TryProcessHeader())
{
return false;
}
Debug.Assert(_inBytesPacket != 0, "_inBytesPacket cannot be 0 after processing header!");
if (_inBytesUsed == _inBytesRead)
{
// we read a header but didn't get anything else except it
// VSTS 219884: it can happen that the TDS packet header and its data are split across two network packets.
// Read at least one more byte to get/cache the first data portion of this TDS packet
if (!TryReadNetworkPacket())
{
return false;
}
}
}
else
{
Debug.Fail("entered negative _inBytesPacket loop");
}
AssertValidState();
}
return true;
}
internal void ResetBuffer()
{
_outBytesUsed = _outputHeaderLen;
}
internal void ResetPacketCounters()
{
_outputPacketNumber = 1;
_outputPacketCount = 0;
}
internal bool SetPacketSize(int size)
{
if (size > TdsEnums.MAX_PACKET_SIZE)
{
throw SQL.InvalidPacketSize();
}
Debug.Assert(size >= 1, "Cannot set packet size to less than 1.");
Debug.Assert((_outBuff == null && _inBuff == null) ||
(_outBuff.Length == _inBuff.Length),
"Buffers are not in consistent state");
Debug.Assert((_outBuff == null && _inBuff == null) ||
this == _parser._physicalStateObj,
"SetPacketSize should only be called on a stateObj with null buffers on the physicalStateObj!");
Debug.Assert(_inBuff == null
|| (
_outBytesUsed == (_outputHeaderLen + BitConverter.ToInt32(_outBuff, _outputHeaderLen)) &&
_outputPacketNumber == 1)
||
(_outBytesUsed == _outputHeaderLen && _outputPacketNumber == 1),
"SetPacketSize called with data in the buffer!");
if (_inBuff == null || _inBuff.Length != size)
{ // We only check _inBuff, since two buffers should be consistent.
// Allocate or re-allocate _inBuff.
if (_inBuff == null)
{
_inBuff = new byte[size];
_inBytesRead = 0;
_inBytesUsed = 0;
}
else if (size != _inBuff.Length)
{
// If new size is other than existing...
if (_inBytesRead > _inBytesUsed)
{
// if we still have data left in the buffer we must keep that array reference and then copy into new one
byte[] temp = _inBuff;
_inBuff = new byte[size];
// copy remainder of unused data
int remainingData = _inBytesRead - _inBytesUsed;
if ((temp.Length < _inBytesUsed + remainingData) || (_inBuff.Length < remainingData))
{
string errormessage = SRHelper.GetString(SR.SQL_InvalidInternalPacketSize) + ' ' + temp.Length + ", " + _inBytesUsed + ", " + remainingData + ", " + _inBuff.Length;
throw SQL.InvalidInternalPacketSize(errormessage);
}
Buffer.BlockCopy(temp, _inBytesUsed, _inBuff, 0, remainingData);
_inBytesRead = _inBytesRead - _inBytesUsed;
_inBytesUsed = 0;
AssertValidState();
}
else
{
// buffer is empty - just create the new one that is double the size of the old one
_inBuff = new byte[size];
_inBytesRead = 0;
_inBytesUsed = 0;
}
}
// Always re-allocate _outBuff - assert is above to verify state.
_outBuff = new byte[size];
_outBytesUsed = _outputHeaderLen;
AssertValidState();
return true;
}
return false;
}
///////////////////////////////////////
// Buffer read methods - data values //
///////////////////////////////////////
// look at the next byte without pulling it off the wire, don't just return _inBytesUsed since we may
// have to go to the network to get the next byte.
internal bool TryPeekByte(out byte value)
{
if (!TryReadByte(out value))
{
return false;
}
// now do fixup
_inBytesPacket++;
_inBytesUsed--;
AssertValidState();
return true;
}
// Takes a byte array, an offset, and a len and fills the array from the offset to len number of
// bytes from the in buffer.
public bool TryReadByteArray(Span<byte> buff, int len)
{
return TryReadByteArray(buff, len, out _);
}
// NOTE: This method must be retriable WITHOUT replaying a snapshot
// Every time you call this method increment the offset and decrease len by the value of totalRead
public bool TryReadByteArray(Span<byte> buff, int len, out int totalRead)
{
totalRead = 0;
#if DEBUG
if (_snapshot != null && _snapshot.DoPend())
{
_networkPacketTaskSource = new TaskCompletionSource<object>();
Interlocked.MemoryBarrier();
if (_forcePendingReadsToWaitForUser)
{
_realNetworkPacketTaskSource = new TaskCompletionSource<object>();
_realNetworkPacketTaskSource.SetResult(null);
}
else
{
_networkPacketTaskSource.TrySetResult(null);
}
return false;
}
#endif
Debug.Assert(buff == null || buff.Length >= len, "Invalid length sent to ReadByteArray()!");
// loop through and read up to array length
while (len > 0)
{
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
return false;
}
}
int bytesToRead = Math.Min(len, Math.Min(_inBytesPacket, _inBytesRead - _inBytesUsed));
Debug.Assert(bytesToRead > 0, "0 byte read in TryReadByteArray");
if (!buff.IsEmpty)
{
var copyFrom = new ReadOnlySpan<byte>(_inBuff, _inBytesUsed, bytesToRead);
Span<byte> copyTo = buff.Slice(totalRead, bytesToRead);
copyFrom.CopyTo(copyTo);
}
totalRead += bytesToRead;
_inBytesUsed += bytesToRead;
_inBytesPacket -= bytesToRead;
len -= bytesToRead;
AssertValidState();
}
return true;
}
// Takes no arguments and returns a byte from the buffer. If the buffer is empty, it is filled
// before the byte is returned.
internal bool TryReadByte(out byte value)
{
Debug.Assert(_inBytesUsed >= 0 && _inBytesUsed <= _inBytesRead, "ERROR - TDSParser: _inBytesUsed < 0 or _inBytesUsed > _inBytesRead");
value = 0;
#if DEBUG
if (_snapshot != null && _snapshot.DoPend())
{
_networkPacketTaskSource = new TaskCompletionSource<object>();
Interlocked.MemoryBarrier();
if (_forcePendingReadsToWaitForUser)
{
_realNetworkPacketTaskSource = new TaskCompletionSource<object>();
_realNetworkPacketTaskSource.SetResult(null);
}
else
{
_networkPacketTaskSource.TrySetResult(null);
}
return false;
}
#endif
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
return false;
}
}
// decrement the number of bytes left in the packet
_inBytesPacket--;
Debug.Assert(_inBytesPacket >= 0, "ERROR - TDSParser: _inBytesPacket < 0");
// return the byte from the buffer and increment the counter for number of bytes used in the in buffer
value = (_inBuff[_inBytesUsed++]);
AssertValidState();
return true;
}
internal bool TryReadChar(out char value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
byte[] buffer;
int offset;
if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2))
{
// If the char isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 2))
{
value = '\0';
return false;
}
buffer = _bTmp;
offset = 0;
}
else
{
// The entire char is in the packet and in the buffer, so just return it
// and take care of the counters.
buffer = _inBuff;
offset = _inBytesUsed;
_inBytesUsed += 2;
_inBytesPacket -= 2;
}
AssertValidState();
value = (char)((buffer[offset + 1] << 8) + buffer[offset]);
return true;
}
internal bool TryReadInt16(out short value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
byte[] buffer;
int offset;
if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2))
{
// If the int16 isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 2))
{
value = default;
return false;
}
buffer = _bTmp;
offset = 0;
}
else
{
// The entire int16 is in the packet and in the buffer, so just return it
// and take care of the counters.
buffer = _inBuff;
offset = _inBytesUsed;
_inBytesUsed += 2;
_inBytesPacket -= 2;
}
AssertValidState();
value = (short)((buffer[offset + 1] << 8) + buffer[offset]);
return true;
}
internal bool TryReadInt32(out int value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
if (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4))
{
// If the int isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 4))
{
value = 0;
return false;
}
AssertValidState();
value = BitConverter.ToInt32(_bTmp, 0);
return true;
}
else
{
// The entire int is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToInt32(_inBuff, _inBytesUsed);
_inBytesUsed += 4;
_inBytesPacket -= 4;
AssertValidState();
return true;
}
}
// This method is safe to call when doing async without snapshot
internal bool TryReadInt64(out long value)
{
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
value = 0;
return false;
}
}
if ((_bTmpRead > 0) || (((_inBytesUsed + 8) > _inBytesRead) || (_inBytesPacket < 8)))
{
// If the long isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
int bytesRead = 0;
if (!TryReadByteArray(_bTmp.AsSpan(_bTmpRead), 8 - _bTmpRead, out bytesRead))
{
Debug.Assert(_bTmpRead + bytesRead <= 8, "Read more data than required");
_bTmpRead += bytesRead;
value = 0;
return false;
}
else
{
Debug.Assert(_bTmpRead + bytesRead == 8, "TryReadByteArray returned true without reading all data required");
_bTmpRead = 0;
AssertValidState();
value = BitConverter.ToInt64(_bTmp, 0);
return true;
}
}
else
{
// The entire long is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToInt64(_inBuff, _inBytesUsed);
_inBytesUsed += 8;
_inBytesPacket -= 8;
AssertValidState();
return true;
}
}
internal bool TryReadUInt16(out ushort value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
byte[] buffer;
int offset;
if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2))
{
// If the uint16 isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 2))
{
value = default;
return false;
}
buffer = _bTmp;
offset = 0;
}
else
{
// The entire uint16 is in the packet and in the buffer, so just return it
// and take care of the counters.
buffer = _inBuff;
offset = _inBytesUsed;
_inBytesUsed += 2;
_inBytesPacket -= 2;
}
AssertValidState();
value = (ushort)((buffer[offset + 1] << 8) + buffer[offset]);
return true;
}
// This method is safe to call when doing async without replay
internal bool TryReadUInt32(out uint value)
{
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
value = 0;
return false;
}
}
if ((_bTmpRead > 0) || (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4)))
{
// If the int isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
int bytesRead = 0;
if (!TryReadByteArray(_bTmp.AsSpan(_bTmpRead), 4 - _bTmpRead, out bytesRead))
{
Debug.Assert(_bTmpRead + bytesRead <= 4, "Read more data than required");
_bTmpRead += bytesRead;
value = 0;
return false;
}
else
{
Debug.Assert(_bTmpRead + bytesRead == 4, "TryReadByteArray returned true without reading all data required");
_bTmpRead = 0;
AssertValidState();
value = BitConverter.ToUInt32(_bTmp, 0);
return true;
}
}
else
{
// The entire int is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToUInt32(_inBuff, _inBytesUsed);
_inBytesUsed += 4;
_inBytesPacket -= 4;
AssertValidState();
return true;
}
}
internal bool TryReadSingle(out float value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
if (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4))
{
// If the float isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 4))
{
value = default(float);
return false;
}
AssertValidState();
value = BitConverter.ToSingle(_bTmp, 0);
return true;
}
else
{
// The entire float is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToSingle(_inBuff, _inBytesUsed);
_inBytesUsed += 4;
_inBytesPacket -= 4;
AssertValidState();
return true;
}
}
internal bool TryReadDouble(out double value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
if (((_inBytesUsed + 8) > _inBytesRead) || (_inBytesPacket < 8))
{
// If the double isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 8))
{
value = default;
return false;
}
AssertValidState();
value = BitConverter.ToDouble(_bTmp, 0);
return true;
}
else
{
// The entire double is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToDouble(_inBuff, _inBytesUsed);
_inBytesUsed += 8;
_inBytesPacket -= 8;
AssertValidState();
return true;
}
}
internal bool TryReadString(int length, out string value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
int cBytes = length << 1;
byte[] buf;
int offset = 0;
if (((_inBytesUsed + cBytes) > _inBytesRead) || (_inBytesPacket < cBytes))
{
if (_bTmp == null || _bTmp.Length < cBytes)
{
_bTmp = new byte[cBytes];
}
if (!TryReadByteArray(_bTmp, cBytes))
{
value = null;
return false;
}
// assign local to point to parser scratch buffer
buf = _bTmp;
AssertValidState();
}
else
{
// assign local to point to _inBuff
buf = _inBuff;
offset = _inBytesUsed;
_inBytesUsed += cBytes;
_inBytesPacket -= cBytes;
AssertValidState();
}
value = System.Text.Encoding.Unicode.GetString(buf, offset, cBytes);
return true;
}
internal bool TryReadStringWithEncoding(int length, System.Text.Encoding encoding, bool isPlp, out string value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
if (null == encoding)
{
// Need to skip the current column before throwing the error - this ensures that the state shared between this and the data reader is consistent when calling DrainData
if (isPlp)
{
ulong ignored;
if (!_parser.TrySkipPlpValue((ulong)length, this, out ignored))
{
value = null;
return false;
}
}
else
{
if (!TrySkipBytes(length))
{
value = null;
return false;
}
}
_parser.ThrowUnsupportedCollationEncountered(this);
}
byte[] buf = null;
int offset = 0;
if (isPlp)
{
if (!TryReadPlpBytes(ref buf, 0, int.MaxValue, out length))
{
value = null;
return false;
}
AssertValidState();
}
else
{
if (((_inBytesUsed + length) > _inBytesRead) || (_inBytesPacket < length))
{
if (_bTmp == null || _bTmp.Length < length)
{
_bTmp = new byte[length];
}
if (!TryReadByteArray(_bTmp, length))
{
value = null;
return false;
}
// assign local to point to parser scratch buffer
buf = _bTmp;
AssertValidState();
}
else
{
// assign local to point to _inBuff
buf = _inBuff;
offset = _inBytesUsed;
_inBytesUsed += length;
_inBytesPacket -= length;
AssertValidState();
}
}
// BCL optimizes to not use char[] underneath
value = encoding.GetString(buf, offset, length);
return true;
}
internal ulong ReadPlpLength(bool returnPlpNullIfNull)
{
ulong value;
Debug.Assert(_syncOverAsync, "Should not attempt pends in a synchronous call");
bool result = TryReadPlpLength(returnPlpNullIfNull, out value);
if (!result)
{
throw SQL.SynchronousCallMayNotPend();
}
return value;
}
// Reads the length of either the entire data or the length of the next chunk in a
// partially length prefixed data
// After this call, call ReadPlpBytes/ReadPlpUnicodeChars until the specified length of data
// is consumed. Repeat this until ReadPlpLength returns 0 in order to read the
// entire stream.
// When this function returns 0, it means the data stream is read completely and the
// plp state in the tdsparser is cleaned.
internal bool TryReadPlpLength(bool returnPlpNullIfNull, out ulong lengthLeft)
{
uint chunklen;
// bool firstchunk = false;
bool isNull = false;
Debug.Assert(_longlenleft == 0, "Out of synch length read request");
if (_longlen == 0)
{
// First chunk is being read. Find out what type of chunk it is
long value;
if (!TryReadInt64(out value))
{
lengthLeft = 0;
return false;
}
_longlen = (ulong)value;
// firstchunk = true;
}
if (_longlen == TdsEnums.SQL_PLP_NULL)
{
_longlen = 0;
_longlenleft = 0;
isNull = true;
}
else
{
// Data is coming in uint chunks, read length of next chunk
if (!TryReadUInt32(out chunklen))
{
lengthLeft = 0;
return false;
}
if (chunklen == TdsEnums.SQL_PLP_CHUNK_TERMINATOR)
{
_longlenleft = 0;
_longlen = 0;
}
else
{
_longlenleft = (ulong)chunklen;
}
}
AssertValidState();
if (isNull && returnPlpNullIfNull)
{
lengthLeft = TdsEnums.SQL_PLP_NULL;
return true;
}
lengthLeft = _longlenleft;
return true;
}
internal int ReadPlpBytesChunk(byte[] buff, int offset, int len)
{
Debug.Assert(_syncOverAsync, "Should not attempt pends in a synchronous call");
Debug.Assert(_longlenleft > 0, "Read when no data available");
int value;
int bytesToRead = (int)Math.Min(_longlenleft, (ulong)len);
bool result = TryReadByteArray(buff.AsSpan(offset), bytesToRead, out value);
_longlenleft -= (ulong)bytesToRead;
if (!result)
{
throw SQL.SynchronousCallMayNotPend();
}
return value;
}
// Reads the requested number of bytes from a plp data stream, or the entire data if
// requested length is -1 or larger than the actual length of data. First call to this method
// should be preceded by a call to ReadPlpLength or ReadDataLength.
// Returns the actual bytes read.
// NOTE: This method must be retriable WITHOUT replaying a snapshot
// Every time you call this method increment the offset and decrease len by the value of totalBytesRead
internal bool TryReadPlpBytes(ref byte[] buff, int offset, int len, out int totalBytesRead)
{
int bytesRead = 0;
int bytesLeft;
byte[] newbuf;
ulong ignored;
if (_longlen == 0)
{
Debug.Assert(_longlenleft == 0);
if (buff == null)
{
buff = Array.Empty<byte>();
}
AssertValidState();
totalBytesRead = 0;
return true; // No data
}
Debug.Assert((_longlen != TdsEnums.SQL_PLP_NULL),
"Out of sync plp read request");
Debug.Assert((buff == null && offset == 0) || (buff.Length >= offset + len), "Invalid length sent to ReadPlpBytes()!");
bytesLeft = len;
// If total length is known up front, allocate the whole buffer in one shot instead of realloc'ing and copying over each time
if (buff == null && _longlen != TdsEnums.SQL_PLP_UNKNOWNLEN)
{
buff = new byte[(int)Math.Min((int)_longlen, len)];
}
if (_longlenleft == 0)
{
if (!TryReadPlpLength(false, out ignored))
{
totalBytesRead = 0;
return false;
}
if (_longlenleft == 0)
{ // Data read complete
totalBytesRead = 0;
return true;
}
}
if (buff == null)
{
buff = new byte[_longlenleft];
}
totalBytesRead = 0;
while (bytesLeft > 0)
{
int bytesToRead = (int)Math.Min(_longlenleft, (ulong)bytesLeft);
if (buff.Length < (offset + bytesToRead))
{
// Grow the array
newbuf = new byte[offset + bytesToRead];
Buffer.BlockCopy(buff, 0, newbuf, 0, offset);
buff = newbuf;
}
bool result = TryReadByteArray(buff.AsSpan(offset), bytesToRead, out bytesRead);
Debug.Assert(bytesRead <= bytesLeft, "Read more bytes than we needed");
Debug.Assert((ulong)bytesRead <= _longlenleft, "Read more bytes than is available");
bytesLeft -= bytesRead;
offset += bytesRead;
totalBytesRead += bytesRead;
_longlenleft -= (ulong)bytesRead;
if (!result)
{
return false;
}
if (_longlenleft == 0)
{ // Read the next chunk or cleanup state if hit the end
if (!TryReadPlpLength(false, out ignored))
{
return false;
}
}
AssertValidState();
// Catch the point where we read the entire plp data stream and clean up state
if (_longlenleft == 0) // Data read complete
break;
}
return true;
}
/////////////////////////////////////////
// Value Skip Logic //
/////////////////////////////////////////
// Reads bytes from the buffer but doesn't return them, in effect simply deleting them.
// Does not handle plp fields, need to use SkipPlpBytesValue for those.
// Does not handle null values or NBC bitmask, ensure the value is not null before calling this method
internal bool TrySkipLongBytes(long num)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
int cbSkip = 0;
while (num > 0)
{
cbSkip = (int)Math.Min((long)int.MaxValue, num);
if (!TryReadByteArray(Span<byte>.Empty, cbSkip))
{
return false;
}
num -= (long)cbSkip;
}
return true;
}
// Reads bytes from the buffer but doesn't return them, in effect simply deleting them.
internal bool TrySkipBytes(int num)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
return TryReadByteArray(Span<byte>.Empty, num);
}
/////////////////////////////////////////
// Network/Packet Reading & Processing //
/////////////////////////////////////////
internal void SetSnapshot()
{
_snapshot = new StateSnapshot(this);
_snapshot.Snap();
_snapshotReplay = false;
}
internal void ResetSnapshot()
{
_snapshot = null;
_snapshotReplay = false;
}
#if DEBUG
private string _lastStack;
#endif
internal bool TryReadNetworkPacket()
{
#if DEBUG
Debug.Assert(!_shouldHaveEnoughData || _attentionSent, "Caller said there should be enough data, but we are currently reading a packet");
#endif
if (_snapshot != null)
{
if (_snapshotReplay)
{
if (_snapshot.Replay())
{
#if DEBUG
if (_checkNetworkPacketRetryStacks)
{
_snapshot.CheckStack(Environment.StackTrace);
}
#endif
return true;
}
#if DEBUG
else
{
if (_checkNetworkPacketRetryStacks)
{
_lastStack = Environment.StackTrace;
}
}
#endif
}
// previous buffer is in snapshot
_inBuff = new byte[_inBuff.Length];
}
if (_syncOverAsync)
{
ReadSniSyncOverAsync();
return true;
}
ReadSni(new TaskCompletionSource<object>());
#if DEBUG
if (_failAsyncPends)
{
throw new InvalidOperationException("Attempted to pend a read when _failAsyncPends test hook was enabled");
}
if (_forceSyncOverAsyncAfterFirstPend)
{
_syncOverAsync = true;
}
#endif
Debug.Assert((_snapshot != null) ^ _asyncReadWithoutSnapshot, "Must have either _snapshot set up or _asyncReadWithoutSnapshot enabled (but not both) to pend a read");
return false;
}
internal void PrepareReplaySnapshot()
{
_networkPacketTaskSource = null;
_snapshot.PrepareReplay();
}
internal void ReadSniSyncOverAsync()
{
if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
{
throw ADP.ClosedConnectionError();
}
PacketHandle readPacket = default;
uint error;
bool shouldDecrement = false;
try
{
Interlocked.Increment(ref _readingCount);
shouldDecrement = true;
readPacket = ReadSyncOverAsync(GetTimeoutRemaining(), out error);
Interlocked.Decrement(ref _readingCount);
shouldDecrement = false;
if (_parser.MARSOn)
{ // Only take reset lock on MARS and Async.
CheckSetResetConnectionState(error, CallbackType.Read);
}
if (TdsEnums.SNI_SUCCESS == error)
{ // Success - process results!
Debug.Assert(!IsPacketEmpty(readPacket), "ReadNetworkPacket cannot be null in synchronous operation!");
ProcessSniPacket(readPacket, 0);
#if DEBUG
if (_forcePendingReadsToWaitForUser)
{
_networkPacketTaskSource = new TaskCompletionSource<object>();
Interlocked.MemoryBarrier();
_networkPacketTaskSource.Task.Wait();
_networkPacketTaskSource = null;
}
#endif
}
else
{ // Failure!
Debug.Assert(!IsValidPacket(readPacket), "unexpected readPacket without corresponding SNIPacketRelease");
ReadSniError(this, error);
}
}
finally
{
if (shouldDecrement)
{
Interlocked.Decrement(ref _readingCount);
}
if (!IsPacketEmpty(readPacket))
{
ReleasePacket(readPacket);
}
AssertValidState();
}
}
internal void OnConnectionClosed()
{
// the stateObj is not null, so the async invocation that registered this callback
// via the SqlReferenceCollection has not yet completed. We will look for a
// _networkPacketTaskSource and mark it faulted. If we don't find it, then
// TdsParserStateObject.ReadSni will abort when it does look to see if the parser
// is open. If we do, then when the call that created it completes and a continuation
// is registered, we will ensure the completion is called.
// Note, this effort is necessary because when the app domain is being unloaded,
// we don't get callback from SNI.
// first mark parser broken. This is to ensure that ReadSni will abort if it has
// not yet executed.
Parser.State = TdsParserState.Broken;
Parser.Connection.BreakConnection();
// Ensure that changing state occurs before checking _networkPacketTaskSource
Interlocked.MemoryBarrier();
// then check for networkPacketTaskSource
var taskSource = _networkPacketTaskSource;
if (taskSource != null)
{
taskSource.TrySetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
}
taskSource = _writeCompletionSource;
if (taskSource != null)
{
taskSource.TrySetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
}
}
private void OnTimeout(object state)
{
if (!_internalTimeout)
{
_internalTimeout = true;
// lock protects against Close and Cancel
lock (this)
{
if (!_attentionSent)
{
AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _parser.Server, _parser.Connection.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
// Grab a reference to the _networkPacketTaskSource in case it becomes null while we are trying to use it
TaskCompletionSource<object> source = _networkPacketTaskSource;
if (_parser.Connection.IsInPool)
{
// We should never timeout if the connection is currently in the pool: the safest thing to do here is to doom the connection to avoid corruption
Debug.Assert(_parser.Connection.IsConnectionDoomed, "Timeout occurred while the connection is in the pool");
_parser.State = TdsParserState.Broken;
_parser.Connection.BreakConnection();
if (source != null)
{
source.TrySetCanceled();
}
}
else if (_parser.State == TdsParserState.OpenLoggedIn)
{
try
{
SendAttention(mustTakeWriteLock: true);
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
// if unable to send attention, cancel the _networkPacketTaskSource to
// request the parser be broken. SNIWritePacket errors will already
// be in the _errors collection.
if (source != null)
{
source.TrySetCanceled();
}
}
}
// If we still haven't received a packet then we don't want to actually close the connection
// from another thread, so complete the pending operation as cancelled, informing them to break it
if (source != null)
{
Task.Delay(AttentionTimeoutSeconds * 1000).ContinueWith(_ =>
{
// Only break the connection if the read didn't finish
if (!source.Task.IsCompleted)
{
int pendingCallback = IncrementPendingCallbacks();
try
{
// If pendingCallback is at 3, then ReadAsyncCallback hasn't been called yet
// So it is safe for us to break the connection and cancel the Task (since we are not sure that ReadAsyncCallback will ever be called)
if ((pendingCallback == 3) && (!source.Task.IsCompleted))
{
Debug.Assert(source == _networkPacketTaskSource, "_networkPacketTaskSource which is being timed is not the current task source");
// Try to throw the timeout exception and store it in the task
bool exceptionStored = false;
try
{
CheckThrowSNIException();
}
catch (Exception ex)
{
if (source.TrySetException(ex))
{
exceptionStored = true;
}
}
// Ensure that the connection is no longer usable
// This is needed since the timeout error added above is non-fatal (and so throwing it won't break the connection)
_parser.State = TdsParserState.Broken;
_parser.Connection.BreakConnection();
// If we didn't get an exception (something else observed it?) then ensure that the task is cancelled
if (!exceptionStored)
{
source.TrySetCanceled();
}
}
}
finally
{
DecrementPendingCallbacks(release: false);
}
}
});
}
}
}
}
}
internal void ReadSni(TaskCompletionSource<object> completion)
{
Debug.Assert(_networkPacketTaskSource == null || ((_asyncReadWithoutSnapshot) && (_networkPacketTaskSource.Task.IsCompleted)), "Pending async call or failed to replay snapshot when calling ReadSni");
_networkPacketTaskSource = completion;
// Ensure that setting the completion source is completed before checking the state
Interlocked.MemoryBarrier();
// We must check after assigning _networkPacketTaskSource to avoid races with
// SqlCommand.OnConnectionClosed
if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
{
throw ADP.ClosedConnectionError();
}
#if DEBUG
if (_forcePendingReadsToWaitForUser)
{
_realNetworkPacketTaskSource = new TaskCompletionSource<object>();
}
#endif
PacketHandle readPacket = default;
uint error = 0;
try
{
Debug.Assert(completion != null, "Async on but null asyncResult passed");
if (_networkPacketTimeout == null)
{
_networkPacketTimeout = ADP.UnsafeCreateTimer(
new TimerCallback(OnTimeout),
null,
Timeout.Infinite,
Timeout.Infinite);
}
// -1 == Infinite
// 0 == Already timed out (NOTE: To simulate the same behavior as sync we will only timeout on 0 if we receive an IO Pending from SNI)
// >0 == Actual timeout remaining
int msecsRemaining = GetTimeoutRemaining();
if (msecsRemaining > 0)
{
ChangeNetworkPacketTimeout(msecsRemaining, Timeout.Infinite);
}
Interlocked.Increment(ref _readingCount);
SessionHandle handle = SessionHandle;
if (!handle.IsNull)
{
IncrementPendingCallbacks();
readPacket = ReadAsync(handle, out error);
if (!(TdsEnums.SNI_SUCCESS == error || TdsEnums.SNI_SUCCESS_IO_PENDING == error))
{
DecrementPendingCallbacks(false); // Failure - we won't receive callback!
}
}
Interlocked.Decrement(ref _readingCount);
if (handle.IsNull)
{
throw ADP.ClosedConnectionError();
}
if (TdsEnums.SNI_SUCCESS == error)
{ // Success - process results!
Debug.Assert(IsValidPacket(readPacket), "ReadNetworkPacket should not have been null on this async operation!");
// Evaluate this condition for MANAGED_SNI. This may not be needed because the network call is happening Async and only the callback can receive a success.
ReadAsyncCallback(IntPtr.Zero, readPacket, 0);
}
else if (TdsEnums.SNI_SUCCESS_IO_PENDING != error)
{ // FAILURE!
Debug.Assert(IsPacketEmpty(readPacket), "unexpected readPacket without corresponding SNIPacketRelease");
ReadSniError(this, error);
#if DEBUG
if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null))
{
_realNetworkPacketTaskSource.TrySetResult(null);
}
else
#endif
{
_networkPacketTaskSource.TrySetResult(null);
}
// Disable timeout timer on error
ChangeNetworkPacketTimeout(Timeout.Infinite, Timeout.Infinite);
}
else if (msecsRemaining == 0)
{ // Got IO Pending, but we have no time left to wait
// Immediately schedule the timeout timer to fire
ChangeNetworkPacketTimeout(0, Timeout.Infinite);
}
// DO NOT HANDLE PENDING READ HERE - which is TdsEnums.SNI_SUCCESS_IO_PENDING state.
// That is handled by user who initiated async read, or by ReadNetworkPacket which is sync over async.
}
finally
{
if (!TdsParserStateObjectFactory.UseManagedSNI)
{
if (!IsPacketEmpty(readPacket))
{
// Be sure to release packet, otherwise it will be leaked by native.
ReleasePacket(readPacket);
}
}
AssertValidState();
}
}
/// <summary>
/// Checks to see if the underlying connection is still alive (used by connection pool resiliency)
/// NOTE: This is not safe to do on a connection that is currently in use
/// NOTE: This will mark the connection as broken if it is found to be dead
/// </summary>
/// <param name="throwOnException">If true then an exception will be thrown if the connection is found to be dead, otherwise no exception will be thrown</param>
/// <returns>True if the connection is still alive, otherwise false</returns>
internal bool IsConnectionAlive(bool throwOnException)
{
Debug.Assert(_parser.Connection == null || _parser.Connection.Pool != null, "Shouldn't be calling IsConnectionAlive on non-pooled connections");
bool isAlive = true;
if (DateTime.UtcNow.Ticks - _lastSuccessfulIOTimer._value > CheckConnectionWindow)
{
if ((_parser == null) || ((_parser.State == TdsParserState.Broken) || (_parser.State == TdsParserState.Closed)))
{
isAlive = false;
if (throwOnException)
{
throw SQL.ConnectionDoomed();
}
}
else if ((_pendingCallbacks > 1) || ((_parser.Connection != null) && (!_parser.Connection.IsInPool)))
{
// This connection is currently in use, assume that the connection is 'alive'
// NOTE: SNICheckConnection is not currently supported for connections that are in use
Debug.Assert(true, "Call to IsConnectionAlive while connection is in use");
}
else
{
uint error;
SniContext = SniContext.Snix_Connect;
error = CheckConnection();
if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT))
{
// Connection is dead
isAlive = false;
if (throwOnException)
{
// Get the error from SNI so that we can throw the correct exception
AddError(_parser.ProcessSNIError(this));
ThrowExceptionAndWarning();
}
}
else
{
_lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
}
}
}
return isAlive;
}
/// <summary>
/// Checks to see if the underlying connection is still valid (used by idle connection resiliency - for active connections)
/// NOTE: This is not safe to do on a connection that is currently in use
/// NOTE: This will mark the connection as broken if it is found to be dead
/// </summary>
/// <returns>True if the connection is still alive, otherwise false</returns>
internal bool ValidateSNIConnection()
{
if ((_parser == null) || ((_parser.State == TdsParserState.Broken) || (_parser.State == TdsParserState.Closed)))
{
return false;
}
if (DateTime.UtcNow.Ticks - _lastSuccessfulIOTimer._value <= CheckConnectionWindow)
{
return true;
}
uint error = TdsEnums.SNI_SUCCESS;
SniContext = SniContext.Snix_Connect;
try
{
Interlocked.Increment(ref _readingCount);
error = CheckConnection();
}
finally
{
Interlocked.Decrement(ref _readingCount);
}
return (error == TdsEnums.SNI_SUCCESS) || (error == TdsEnums.SNI_WAIT_TIMEOUT);
}
// This method should only be called by ReadSni! If not - it may have problems with timeouts!
private void ReadSniError(TdsParserStateObject stateObj, uint error)
{
if (TdsEnums.SNI_WAIT_TIMEOUT == error)
{
Debug.Assert(_syncOverAsync, "Should never reach here with async on!");
bool fail = false;
if (_internalTimeout)
{ // This is now our second timeout - time to give up.
fail = true;
}
else
{
stateObj._internalTimeout = true;
Debug.Assert(_parser.Connection != null, "SqlConnectionInternalTds handler can not be null at this point.");
AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _parser.Server, _parser.Connection.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
if (!stateObj._attentionSent)
{
if (stateObj.Parser.State == TdsParserState.OpenLoggedIn)
{
stateObj.SendAttention(mustTakeWriteLock: true);
PacketHandle syncReadPacket = default;
bool shouldDecrement = false;
try
{
Interlocked.Increment(ref _readingCount);
shouldDecrement = true;
syncReadPacket = ReadSyncOverAsync(stateObj.GetTimeoutRemaining(), out error);
Interlocked.Decrement(ref _readingCount);
shouldDecrement = false;
if (TdsEnums.SNI_SUCCESS == error)
{
// We will end up letting the run method deal with the expected done:done_attn token stream.
stateObj.ProcessSniPacket(syncReadPacket, 0);
return;
}
else
{
Debug.Assert(!IsValidPacket(syncReadPacket), "unexpected syncReadPacket without corresponding SNIPacketRelease");
fail = true; // Subsequent read failed, time to give up.
}
}
finally
{
if (shouldDecrement)
{
Interlocked.Decrement(ref _readingCount);
}
if (!IsPacketEmpty(syncReadPacket))
{
ReleasePacket(syncReadPacket);
}
}
}
else
{
if (_parser._loginWithFailover)
{
// For DbMirroring Failover during login, never break the connection, just close the TdsParser
_parser.Disconnect();
}
else if ((_parser.State == TdsParserState.OpenNotLoggedIn) && (_parser.Connection.ConnectionOptions.MultiSubnetFailover))
{
// For MultiSubnet Failover during login, never break the connection, just close the TdsParser
_parser.Disconnect();
}
else
fail = true; // We aren't yet logged in - just fail.
}
}
}
if (fail)
{
_parser.State = TdsParserState.Broken; // We failed subsequent read, we have to quit!
_parser.Connection.BreakConnection();
}
}
else
{
// Caution: ProcessSNIError always returns a fatal error!
AddError(_parser.ProcessSNIError(stateObj));
}
ThrowExceptionAndWarning();
AssertValidState();
}
public void ProcessSniPacket(PacketHandle packet, uint error)
{
if (error != 0)
{
if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
{
// Do nothing with callback if closed or broken and error not 0 - callback can occur
// after connection has been closed. PROBLEM IN NETLIB - DESIGN FLAW.
return;
}
AddError(_parser.ProcessSNIError(this));
AssertValidState();
}
else
{
uint dataSize = 0;
uint getDataError = SNIPacketGetData(packet, _inBuff, ref dataSize);
if (getDataError == TdsEnums.SNI_SUCCESS)
{
if (_inBuff.Length < dataSize)
{
Debug.Assert(true, "Unexpected dataSize on Read");
throw SQL.InvalidInternalPacketSize(SRHelper.GetString(SR.SqlMisc_InvalidArraySizeMessage));
}
_lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
_inBytesRead = (int)dataSize;
_inBytesUsed = 0;
if (_snapshot != null)
{
_snapshot.PushBuffer(_inBuff, _inBytesRead);
if (_snapshotReplay)
{
_snapshot.Replay();
#if DEBUG
_snapshot.AssertCurrent();
#endif
}
}
SniReadStatisticsAndTracing();
AssertValidState();
}
else
{
throw SQL.ParsingError();
}
}
}
private void ChangeNetworkPacketTimeout(int dueTime, int period)
{
Timer networkPacketTimeout = _networkPacketTimeout;
if (networkPacketTimeout != null)
{
try
{
networkPacketTimeout.Change(dueTime, period);
}
catch (ObjectDisposedException)
{
// _networkPacketTimeout is set to null before Disposing, but there is still a slight chance
// that object was disposed after we took a copy
}
}
}
private void SetBufferSecureStrings()
{
if (_securePasswords != null)
{
for (int i = 0; i < _securePasswords.Length; i++)
{
if (_securePasswords[i] != null)
{
IntPtr str = IntPtr.Zero;
try
{
str = Marshal.SecureStringToBSTR(_securePasswords[i]);
byte[] data = new byte[_securePasswords[i].Length * 2];
Marshal.Copy(str, data, 0, _securePasswords[i].Length * 2);
TdsParserStaticMethods.ObfuscatePassword(data);
data.CopyTo(_outBuff, _securePasswordOffsetsInBuffer[i]);
}
finally
{
Marshal.ZeroFreeBSTR(str);
}
}
}
}
}
public void ReadAsyncCallback(PacketHandle packet, uint error) =>
ReadAsyncCallback(IntPtr.Zero, packet, error);
public void ReadAsyncCallback(IntPtr key, PacketHandle packet, uint error)
{
// Key never used.
// Note - it's possible that when native calls managed that an asynchronous exception
// could occur in the native->managed transition, which would
// have two impacts:
// 1) user event not called
// 2) DecrementPendingCallbacks not called, which would mean this object would be leaked due
// to the outstanding GCRoot until AppDomain.Unload.
// We live with the above for the time being due to the constraints of the current
// reliability infrastructure provided by the CLR.
TaskCompletionSource<object> source = _networkPacketTaskSource;
#if DEBUG
if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null))
{
source = _realNetworkPacketTaskSource;
}
#endif
// The mars physical connection can get a callback
// with a packet but no result after the connection is closed.
if (source == null && _parser._pMarsPhysicalConObj == this)
{
return;
}
bool processFinallyBlock = true;
try
{
Debug.Assert(CheckPacket(packet, source) && source != null, "AsyncResult null on callback");
if (_parser.MARSOn)
{ // Only take reset lock on MARS and Async.
CheckSetResetConnectionState(error, CallbackType.Read);
}
ChangeNetworkPacketTimeout(Timeout.Infinite, Timeout.Infinite);
ProcessSniPacket(packet, error);
}
catch (Exception e)
{
processFinallyBlock = ADP.IsCatchableExceptionType(e);
throw;
}
finally
{
// pendingCallbacks may be 2 after decrementing, this indicates that a fatal timeout is occurring, and therefore we shouldn't complete the task
int pendingCallbacks = DecrementPendingCallbacks(false); // may dispose of GC handle.
if ((processFinallyBlock) && (source != null) && (pendingCallbacks < 2))
{
if (error == 0)
{
if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, (state) => source.TrySetResult(null), null);
}
else
{
source.TrySetResult(null);
}
}
else
{
if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, (state) => ReadAsyncCallbackCaptureException(source), null);
}
else
{
ReadAsyncCallbackCaptureException(source);
}
}
}
AssertValidState();
}
}
protected abstract bool CheckPacket(PacketHandle packet, TaskCompletionSource<object> source);
private void ReadAsyncCallbackCaptureException(TaskCompletionSource<object> source)
{
bool captureSuccess = false;
try
{
if (_hasErrorOrWarning)
{
// Do the close on another thread, since we don't want to block the callback thread
ThrowExceptionAndWarning(asyncClose: true);
}
else if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
{
// Connection was closed by another thread before we parsed the packet, so no error was added to the collection
throw ADP.ClosedConnectionError();
}
}
catch (Exception ex)
{
if (source.TrySetException(ex))
{
// There was an exception, and it was successfully stored in the task
captureSuccess = true;
}
}
if (!captureSuccess)
{
// Either there was no exception, or the task was already completed
// This is unusual, but possible if a fatal timeout occurred on another thread (which should mean that the connection is now broken)
Debug.Assert(_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed || _parser.Connection.IsConnectionDoomed, "Failed to capture exception while the connection was still healthy");
// The safest thing to do is to ensure that the connection is broken and attempt to cancel the task
// This must be done from another thread to not block the callback thread
Task.Factory.StartNew(() =>
{
_parser.State = TdsParserState.Broken;
_parser.Connection.BreakConnection();
source.TrySetCanceled();
});
}
}
public void WriteAsyncCallback(PacketHandle packet, uint sniError) =>
WriteAsyncCallback(IntPtr.Zero, packet, sniError);
public void WriteAsyncCallback(IntPtr key, PacketHandle packet, uint sniError)
{ // Key never used.
RemovePacketFromPendingList(packet);
try
{
if (sniError != TdsEnums.SNI_SUCCESS)
{
try
{
AddError(_parser.ProcessSNIError(this));
ThrowExceptionAndWarning(asyncClose: true);
}
catch (Exception e)
{
var writeCompletionSource = _writeCompletionSource;
if (writeCompletionSource != null)
{
writeCompletionSource.TrySetException(e);
}
else
{
_delayedWriteAsyncCallbackException = e;
// Ensure that _delayedWriteAsyncCallbackException is set before checking _writeCompletionSource
Interlocked.MemoryBarrier();
// Double check that _writeCompletionSource hasn't been created in the meantime
writeCompletionSource = _writeCompletionSource;
if (writeCompletionSource != null)
{
var delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
writeCompletionSource.TrySetException(delayedException);
}
}
}
return;
}
}
else
{
_lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
}
}
finally
{
#if DEBUG
if (SqlCommand.DebugForceAsyncWriteDelay > 0)
{
new Timer(obj =>
{
Interlocked.Decrement(ref _asyncWriteCount);
var writeCompletionSource = _writeCompletionSource;
if (_asyncWriteCount == 0 && writeCompletionSource != null)
{
writeCompletionSource.TrySetResult(null);
}
}, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite);
}
else
{
#else
{
#endif
Interlocked.Decrement(ref _asyncWriteCount);
}
}
#if DEBUG
if (SqlCommand.DebugForceAsyncWriteDelay > 0)
{
return;
}
#endif
var completionSource = _writeCompletionSource;
if (_asyncWriteCount == 0 && completionSource != null)
{
completionSource.TrySetResult(null);
}
}
/////////////////////////////////////////
// Network/Packet Writing & Processing //
/////////////////////////////////////////
internal void WriteSecureString(SecureString secureString)
{
Debug.Assert(_securePasswords[0] == null || _securePasswords[1] == null, "There are more than two secure passwords");
int index = _securePasswords[0] != null ? 1 : 0;
_securePasswords[index] = secureString;
_securePasswordOffsetsInBuffer[index] = _outBytesUsed;
// loop through and write the entire array
int lengthInBytes = secureString.Length * 2;
// It is guaranteed both secure password and secure change password should fit into the first packet
// Given current TDS format and implementation it is not possible that one of secure string is the last item and exactly fill up the output buffer
// if this ever happens and it is correct situation, the packet needs to be written out after _outBytesUsed is update
Debug.Assert((_outBytesUsed + lengthInBytes) < _outBuff.Length, "Passwords cannot be splited into two different packet or the last item which fully fill up _outBuff!!!");
_outBytesUsed += lengthInBytes;
}
internal void ResetSecurePasswordsInformation()
{
for (int i = 0; i < _securePasswords.Length; ++i)
{
_securePasswords[i] = null;
_securePasswordOffsetsInBuffer[i] = 0;
}
}
internal Task WaitForAccumulatedWrites()
{
// Checked for stored exceptions
var delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
throw delayedException;
}
#pragma warning restore 420
if (_asyncWriteCount == 0)
{
return null;
}
_writeCompletionSource = new TaskCompletionSource<object>();
Task task = _writeCompletionSource.Task;
// Ensure that _writeCompletionSource is set before checking state
Interlocked.MemoryBarrier();
// Now that we have set _writeCompletionSource, check if parser is closed or broken
if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
{
throw ADP.ClosedConnectionError();
}
// Check for stored exceptions
delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
throw delayedException;
}
// If there are no outstanding writes, see if we can shortcut and return null
if ((_asyncWriteCount == 0) && ((!task.IsCompleted) || (task.Exception == null)))
{
task = null;
}
return task;
}
// Takes in a single byte and writes it to the buffer. If the buffer is full, it is flushed
// and then the buffer is re-initialized in flush() and then the byte is put in the buffer.
internal void WriteByte(byte b)
{
Debug.Assert(_outBytesUsed <= _outBuff.Length, "ERROR - TDSParser: _outBytesUsed > _outBuff.Length");
// check to make sure we haven't used the full amount of space available in the buffer, if so, flush it
if (_outBytesUsed == _outBuff.Length)
{
WritePacket(TdsEnums.SOFTFLUSH, canAccumulate: true);
}
// set byte in buffer and increment the counter for number of bytes used in the out buffer
_outBuff[_outBytesUsed++] = b;
}
internal Task WriteByteSpan(ReadOnlySpan<byte> span, bool canAccumulate = true, TaskCompletionSource<object> completion = null)
{
return WriteBytes(span, span.Length, 0, canAccumulate, completion);
}
internal Task WriteByteArray(byte[] b, int len, int offsetBuffer, bool canAccumulate = true, TaskCompletionSource<object> completion = null)
{
return WriteBytes(ReadOnlySpan<byte>.Empty, len, offsetBuffer, canAccumulate, completion, b);
}
//
// Takes a span or a byte array and writes it to the buffer
// If you pass in a span and a null array then the span wil be used.
// If you pass in a non-null array then the array will be used and the span is ignored.
// if the span cannot be written into the current packet then the remaining contents of the span are copied to a
// new heap allocated array that will used to callback into the method to continue the write operation.
private Task WriteBytes(ReadOnlySpan<byte> b, int len, int offsetBuffer, bool canAccumulate = true, TaskCompletionSource<object> completion = null, byte[] array = null)
{
if (array != null)
{
b = new ReadOnlySpan<byte>(array, offsetBuffer, len);
}
try
{
bool async = _parser._asyncWrite; // NOTE: We are capturing this now for the assert after the Task is returned, since WritePacket will turn off async if there is an exception
Debug.Assert(async || _asyncWriteCount == 0);
// Do we have to send out in packet size chunks, or can we rely on netlib layer to break it up?
// would prefer to do something like:
//
// if (len > what we have room for || len > out buf)
// flush buffer
// UnsafeNativeMethods.Write(b)
//
int offset = offsetBuffer;
Debug.Assert(b.Length >= len, "Invalid length sent to WriteBytes()!");
// loop through and write the entire array
do
{
if ((_outBytesUsed + len) > _outBuff.Length)
{
// If the remainder of the data won't fit into the buffer, then we have to put
// whatever we can into the buffer, and flush that so we can then put more into
// the buffer on the next loop of the while.
int remainder = _outBuff.Length - _outBytesUsed;
// write the remainder
Span<byte> copyTo = _outBuff.AsSpan(_outBytesUsed, remainder);
ReadOnlySpan<byte> copyFrom = b.Slice(0, remainder);
Debug.Assert(copyTo.Length == copyFrom.Length, $"copyTo.Length:{copyTo.Length} and copyFrom.Length{copyFrom.Length:D} should be the same");
copyFrom.CopyTo(copyTo);
offset += remainder;
_outBytesUsed += remainder;
len -= remainder;
b = b.Slice(remainder, len);
Task packetTask = WritePacket(TdsEnums.SOFTFLUSH, canAccumulate);
if (packetTask != null)
{
Task task = null;
Debug.Assert(async, "Returned task in sync mode");
if (completion == null)
{
completion = new TaskCompletionSource<object>();
task = completion.Task; // we only care about return from topmost call, so do not access Task property in other cases
}
if (array == null)
{
byte[] tempArray = new byte[len];
Span<byte> copyTempTo = tempArray.AsSpan();
Debug.Assert(copyTempTo.Length == b.Length, $"copyTempTo.Length:{copyTempTo.Length} and copyTempFrom.Length:{b.Length:D} should be the same");
b.CopyTo(copyTempTo);
array = tempArray;
offset = 0;
}
WriteBytesSetupContinuation(array, len, completion, offset, packetTask);
return task;
}
}
else
{
//((stateObj._outBytesUsed + len) <= stateObj._outBuff.Length )
// Else the remainder of the string will fit into the buffer, so copy it into the
// buffer and then break out of the loop.
Span<byte> copyTo = _outBuff.AsSpan(_outBytesUsed, len);
ReadOnlySpan<byte> copyFrom = b.Slice(0, len);
Debug.Assert(copyTo.Length == copyFrom.Length, $"copyTo.Length:{copyTo.Length} and copyFrom.Length:{copyFrom.Length:D} should be the same");
copyFrom.CopyTo(copyTo);
// handle out buffer bytes used counter
_outBytesUsed += len;
break;
}
} while (len > 0);
if (completion != null)
{
completion.SetResult(null);
}
return null;
}
catch (Exception e)
{
if (completion != null)
{
completion.SetException(e);
return null;
}
else
{
throw;
}
}
}
// This is in its own method to avoid always allocating the lambda in WriteBytes
private void WriteBytesSetupContinuation(byte[] array, int len, TaskCompletionSource<object> completion, int offset, Task packetTask)
{
AsyncHelper.ContinueTask(packetTask, completion,
onSuccess: () => WriteBytes(ReadOnlySpan<byte>.Empty, len: len, offsetBuffer: offset, canAccumulate: false, completion: completion, array)
);
}
// Dumps contents of buffer to SNI for network write.
internal Task WritePacket(byte flushMode, bool canAccumulate = false)
{
TdsParserState state = _parser.State;
if ((state == TdsParserState.Closed) || (state == TdsParserState.Broken))
{
throw ADP.ClosedConnectionError();
}
if (
// This appears to be an optimization to avoid writing empty packets in Yukon
// However, since we don't know the version prior to login IsYukonOrNewer was always false prior to login
// So removing the IsYukonOrNewer check causes issues since the login packet happens to meet the rest of the conditions below
// So we need to avoid this check prior to login completing
state == TdsParserState.OpenLoggedIn &&
!_bulkCopyOpperationInProgress && // ignore the condition checking for bulk copy
_outBytesUsed == (_outputHeaderLen + BitConverter.ToInt32(_outBuff, _outputHeaderLen))
&& _outputPacketCount == 0
|| _outBytesUsed == _outputHeaderLen
&& _outputPacketCount == 0)
{
return null;
}
byte status;
byte packetNumber = _outputPacketNumber;
// Set Status byte based whether this is end of message or not
bool willCancel = (_cancelled) && (_parser._asyncWrite);
if (willCancel)
{
status = TdsEnums.ST_EOM | TdsEnums.ST_IGNORE;
ResetPacketCounters();
}
else if (TdsEnums.HARDFLUSH == flushMode)
{
status = TdsEnums.ST_EOM;
ResetPacketCounters();
}
else if (TdsEnums.SOFTFLUSH == flushMode)
{
status = TdsEnums.ST_BATCH;
_outputPacketNumber++;
_outputPacketCount++;
}
else
{
status = TdsEnums.ST_EOM;
Debug.Fail($"Unexpected argument {flushMode,-2:x2} to WritePacket");
}
_outBuff[0] = _outputMessageType; // Message Type
_outBuff[1] = status;
_outBuff[2] = (byte)(_outBytesUsed >> 8); // length - upper byte
_outBuff[3] = (byte)(_outBytesUsed & 0xff); // length - lower byte
_outBuff[4] = 0; // channel
_outBuff[5] = 0;
_outBuff[6] = packetNumber; // packet
_outBuff[7] = 0; // window
Task task = null;
_parser.CheckResetConnection(this); // HAS SIDE EFFECTS - re-org at a later time if possible
task = WriteSni(canAccumulate);
AssertValidState();
if (willCancel)
{
// If we have been cancelled, then ensure that we write the ATTN packet as well
task = AsyncHelper.CreateContinuationTask(task, CancelWritePacket);
}
return task;
}
private void CancelWritePacket()
{
Debug.Assert(_cancelled, "Should not call CancelWritePacket if _cancelled is not set");
_parser.Connection.ThreadHasParserLockForClose = true; // In case of error, let the connection know that we are holding the lock
try
{
// Send the attention and wait for the ATTN_ACK
SendAttention();
ResetCancelAndProcessAttention();
// Let the caller know that we've given up
throw SQL.OperationCancelled();
}
finally
{
_parser.Connection.ThreadHasParserLockForClose = false;
}
}
#pragma warning disable 0420 // a reference to a volatile field will not be treated as volatile
private Task SNIWritePacket(PacketHandle packet, out uint sniError, bool canAccumulate, bool callerHasConnectionLock)
{
// Check for a stored exception
var delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
throw delayedException;
}
Task task = null;
_writeCompletionSource = null;
PacketHandle packetPointer = EmptyReadPacket;
bool sync = !_parser._asyncWrite;
if (sync && _asyncWriteCount > 0)
{ // for example, SendAttention while there are writes pending
Task waitForWrites = WaitForAccumulatedWrites();
if (waitForWrites != null)
{
try
{
waitForWrites.Wait();
}
catch (AggregateException ae)
{
throw ae.InnerException;
}
}
Debug.Assert(_asyncWriteCount == 0, "All async write should be finished");
}
if (!sync)
{
// Add packet to the pending list (since the callback can happen any time after we call SNIWritePacket)
packetPointer = AddPacketToPendingList(packet);
}
// Async operation completion may be delayed (success pending).
try
{
}
finally
{
sniError = WritePacket(packet, sync);
}
if (sniError == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
Debug.Assert(!sync, "Completion should be handled in SniManagedWwrapper");
Interlocked.Increment(ref _asyncWriteCount);
Debug.Assert(_asyncWriteCount >= 0);
if (!canAccumulate)
{
// Create completion source (for callback to complete)
_writeCompletionSource = new TaskCompletionSource<object>();
task = _writeCompletionSource.Task;
// Ensure that setting _writeCompletionSource completes before checking _delayedWriteAsyncCallbackException
Interlocked.MemoryBarrier();
// Check for a stored exception
delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
throw delayedException;
}
// If there are no outstanding writes, see if we can shortcut and return null
if ((_asyncWriteCount == 0) && ((!task.IsCompleted) || (task.Exception == null)))
{
task = null;
}
}
}
#if DEBUG
else if (!sync && !canAccumulate && SqlCommand.DebugForceAsyncWriteDelay > 0)
{
// Executed synchronously - callback will not be called
TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
uint error = sniError;
new Timer(obj =>
{
try
{
if (_parser.MARSOn)
{ // Only take reset lock on MARS.
CheckSetResetConnectionState(error, CallbackType.Write);
}
if (error != TdsEnums.SNI_SUCCESS)
{
AddError(_parser.ProcessSNIError(this));
ThrowExceptionAndWarning();
}
AssertValidState();
completion.SetResult(null);
}
catch (Exception e)
{
completion.SetException(e);
}
}, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite);
task = completion.Task;
}
#endif
else
{
if (_parser.MARSOn)
{ // Only take reset lock on MARS.
CheckSetResetConnectionState(sniError, CallbackType.Write);
}
if (sniError == TdsEnums.SNI_SUCCESS)
{
_lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
if (!sync)
{
// Since there will be no callback, remove the packet from the pending list
Debug.Assert(IsValidPacket(packetPointer), "Packet added to list has an invalid pointer, can not remove from pending list");
RemovePacketFromPendingList(packetPointer);
}
}
else
{
AddError(_parser.ProcessSNIError(this));
ThrowExceptionAndWarning(callerHasConnectionLock);
}
AssertValidState();
}
return task;
}
internal abstract bool IsValidPacket(PacketHandle packetPointer);
internal abstract uint WritePacket(PacketHandle packet, bool sync);
// Sends an attention signal - executing thread will consume attn.
internal void SendAttention(bool mustTakeWriteLock = false)
{
if (!_attentionSent)
{
// Dumps contents of buffer to OOB write (currently only used for
// attentions. There is no body for this message
// Doesn't touch this._outBytesUsed
if (_parser.State == TdsParserState.Closed || _parser.State == TdsParserState.Broken)
{
return;
}
PacketHandle attnPacket = CreateAndSetAttentionPacket();
try
{
// Dev11 #344723: SqlClient stress hang System_Data!Tcp::ReadSync via a call to SqlDataReader::Close
// Set _attentionSending to true before sending attention and reset after setting _attentionSent
// This prevents a race condition between receiving the attention ACK and setting _attentionSent
_attentionSending = true;
#if DEBUG
if (!_skipSendAttention)
{
#endif
// Take lock and send attention
bool releaseLock = false;
if ((mustTakeWriteLock) && (!_parser.Connection.ThreadHasParserLockForClose))
{
releaseLock = true;
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false);
_parser.Connection.ThreadHasParserLockForClose = true;
}
try
{
// Check again (just in case the connection was closed while we were waiting)
if (_parser.State == TdsParserState.Closed || _parser.State == TdsParserState.Broken)
{
return;
}
uint sniError;
_parser._asyncWrite = false; // stop async write
SNIWritePacket(attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false);
}
finally
{
if (releaseLock)
{
_parser.Connection.ThreadHasParserLockForClose = false;
_parser.Connection._parserLock.Release();
}
}
#if DEBUG
}
#endif
SetTimeoutSeconds(AttentionTimeoutSeconds); // Initialize new attention timeout of 5 seconds.
_attentionSent = true;
}
finally
{
_attentionSending = false;
}
AssertValidState();
}
}
internal abstract PacketHandle CreateAndSetAttentionPacket();
internal abstract void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed);
private Task WriteSni(bool canAccumulate)
{
// Prepare packet, and write to packet.
PacketHandle packet = GetResetWritePacket();
SetBufferSecureStrings();
SetPacketData(packet, _outBuff, _outBytesUsed);
uint sniError;
Debug.Assert(Parser.Connection._parserLock.ThreadMayHaveLock(), "Thread is writing without taking the connection lock");
Task task = SNIWritePacket(packet, out sniError, canAccumulate, callerHasConnectionLock: true);
// Check to see if the timeout has occurred. This time out code is special case code to allow BCP writes to timeout. Eventually we should make all writes timeout.
if (_bulkCopyOpperationInProgress && 0 == GetTimeoutRemaining())
{
_parser.Connection.ThreadHasParserLockForClose = true;
try
{
Debug.Assert(_parser.Connection != null, "SqlConnectionInternalTds handler can not be null at this point.");
AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _parser.Server, _parser.Connection.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
_bulkCopyWriteTimeout = true;
SendAttention();
_parser.ProcessPendingAck(this);
ThrowExceptionAndWarning();
}
finally
{
_parser.Connection.ThreadHasParserLockForClose = false;
}
}
// Special case logic for encryption removal.
if (_parser.State == TdsParserState.OpenNotLoggedIn &&
_parser.EncryptionOptions == EncryptionOptions.LOGIN)
{
// If no error occurred, and we are Open but not logged in, and
// our encryptionOption state is login, remove the SSL Provider.
// We only need encrypt the very first packet of the login message to the server.
// We wanted to encrypt entire login channel, but there is
// currently no mechanism to communicate this. Removing encryption post 1st packet
// is a hard-coded agreement between client and server. We need some mechanism or
// common change to be able to make this change in a non-breaking fashion.
_parser.RemoveEncryption(); // Remove the SSL Provider.
_parser.EncryptionOptions = EncryptionOptions.OFF; // Turn encryption off.
// Since this packet was associated with encryption, dispose and re-create.
ClearAllWritePackets();
}
SniWriteStatisticsAndTracing();
ResetBuffer();
AssertValidState();
return task;
}
//////////////////////////////////////////////
// Statistics, Tracing, and related methods //
//////////////////////////////////////////////
private void SniReadStatisticsAndTracing()
{
SqlStatistics statistics = Parser.Statistics;
if (null != statistics)
{
if (statistics.WaitForReply)
{
statistics.SafeIncrement(ref statistics._serverRoundtrips);
statistics.ReleaseAndUpdateNetworkServerTimer();
}
statistics.SafeAdd(ref statistics._bytesReceived, _inBytesRead);
statistics.SafeIncrement(ref statistics._buffersReceived);
}
}
private void SniWriteStatisticsAndTracing()
{
SqlStatistics statistics = _parser.Statistics;
if (null != statistics)
{
statistics.SafeIncrement(ref statistics._buffersSent);
statistics.SafeAdd(ref statistics._bytesSent, _outBytesUsed);
statistics.RequestNetworkServerTimer();
}
}
[Conditional("DEBUG")]
private void AssertValidState()
{
if (_inBytesUsed < 0 || _inBytesRead < 0)
{
Debug.Fail($"Invalid TDS Parser State: either _inBytesUsed or _inBytesRead is negative: {_inBytesUsed}, {_inBytesRead}");
}
else if (_inBytesUsed > _inBytesRead)
{
Debug.Fail($"Invalid TDS Parser State: _inBytesUsed > _inBytesRead: {_inBytesUsed} > {_inBytesRead}");
}
Debug.Assert(_inBytesPacket >= 0, "Packet must not be negative");
}
//////////////////////////////////////////////
// Errors and Warnings //
//////////////////////////////////////////////
/// <summary>
/// True if there is at least one error or warning (not counting the pre-attention errors\warnings)
/// </summary>
internal bool HasErrorOrWarning
{
get
{
return _hasErrorOrWarning;
}
}
/// <summary>
/// Adds an error to the error collection
/// </summary>
/// <param name="error"></param>
internal void AddError(SqlError error)
{
Debug.Assert(error != null, "Trying to add a null error");
// Switch to sync once we see an error
_syncOverAsync = true;
lock (_errorAndWarningsLock)
{
_hasErrorOrWarning = true;
if (_errors == null)
{
_errors = new SqlErrorCollection();
}
_errors.Add(error);
}
}
/// <summary>
/// Gets the number of errors currently in the error collection
/// </summary>
internal int ErrorCount
{
get
{
int count = 0;
lock (_errorAndWarningsLock)
{
if (_errors != null)
{
count = _errors.Count;
}
}
return count;
}
}
/// <summary>
/// Adds an warning to the warning collection
/// </summary>
/// <param name="error"></param>
internal void AddWarning(SqlError error)
{
Debug.Assert(error != null, "Trying to add a null error");
// Switch to sync once we see a warning
_syncOverAsync = true;
lock (_errorAndWarningsLock)
{
_hasErrorOrWarning = true;
if (_warnings == null)
{
_warnings = new SqlErrorCollection();
}
_warnings.Add(error);
}
}
/// <summary>
/// Gets the number of warnings currently in the warning collection
/// </summary>
internal int WarningCount
{
get
{
int count = 0;
lock (_errorAndWarningsLock)
{
if (_warnings != null)
{
count = _warnings.Count;
}
}
return count;
}
}
protected abstract PacketHandle EmptyReadPacket { get; }
/// <summary>
/// Gets the full list of errors and warnings (including the pre-attention ones), then wipes all error and warning lists
/// </summary>
/// <param name="broken">If true, the connection should be broken</param>
/// <returns>An array containing all of the errors and warnings</returns>
internal SqlErrorCollection GetFullErrorAndWarningCollection(out bool broken)
{
SqlErrorCollection allErrors = new SqlErrorCollection();
broken = false;
lock (_errorAndWarningsLock)
{
_hasErrorOrWarning = false;
// Merge all error lists, then reset them
AddErrorsToCollection(_errors, ref allErrors, ref broken);
AddErrorsToCollection(_warnings, ref allErrors, ref broken);
_errors = null;
_warnings = null;
// We also process the pre-attention error lists here since, if we are here and they are populated, then an error occurred while sending attention so we should show the errors now (otherwise they'd be lost)
AddErrorsToCollection(_preAttentionErrors, ref allErrors, ref broken);
AddErrorsToCollection(_preAttentionWarnings, ref allErrors, ref broken);
_preAttentionErrors = null;
_preAttentionWarnings = null;
}
return allErrors;
}
private void AddErrorsToCollection(SqlErrorCollection inCollection, ref SqlErrorCollection collectionToAddTo, ref bool broken)
{
if (inCollection != null)
{
foreach (SqlError error in inCollection)
{
collectionToAddTo.Add(error);
broken |= (error.Class >= TdsEnums.FATAL_ERROR_CLASS);
}
}
}
/// <summary>
/// Stores away current errors and warnings so that an attention can be processed
/// </summary>
internal void StoreErrorAndWarningForAttention()
{
lock (_errorAndWarningsLock)
{
Debug.Assert(_preAttentionErrors == null && _preAttentionWarnings == null, "Can't store errors for attention because there are already errors stored");
_hasErrorOrWarning = false;
_preAttentionErrors = _errors;
_preAttentionWarnings = _warnings;
_errors = null;
_warnings = null;
}
}
/// <summary>
/// Restores errors and warnings that were stored in order to process an attention
/// </summary>
internal void RestoreErrorAndWarningAfterAttention()
{
lock (_errorAndWarningsLock)
{
Debug.Assert(_errors == null && _warnings == null, "Can't restore errors after attention because there are already other errors");
_hasErrorOrWarning = (((_preAttentionErrors != null) && (_preAttentionErrors.Count > 0)) || ((_preAttentionWarnings != null) && (_preAttentionWarnings.Count > 0)));
_errors = _preAttentionErrors;
_warnings = _preAttentionWarnings;
_preAttentionErrors = null;
_preAttentionWarnings = null;
}
}
/// <summary>
/// Checks if an error is stored in _error and, if so, throws an error
/// </summary>
internal void CheckThrowSNIException()
{
if (HasErrorOrWarning)
{
ThrowExceptionAndWarning();
}
}
/// <summary>
/// Debug Only: Ensures that the TdsParserStateObject has no lingering state and can safely be re-used
/// </summary>
[Conditional("DEBUG")]
internal void AssertStateIsClean()
{
// If our TdsParser is closed or broken, then we don't really care about our state
var parser = _parser;
if ((parser != null) && (parser.State != TdsParserState.Closed) && (parser.State != TdsParserState.Broken))
{
// Async reads
Debug.Assert(_snapshot == null && !_snapshotReplay, "StateObj has leftover snapshot state");
Debug.Assert(!_asyncReadWithoutSnapshot, "StateObj has AsyncReadWithoutSnapshot still enabled");
Debug.Assert(_executionContext == null, "StateObj has a stored execution context from an async read");
// Async writes
Debug.Assert(_asyncWriteCount == 0, "StateObj still has outstanding async writes");
Debug.Assert(_delayedWriteAsyncCallbackException == null, "StateObj has an unobserved exceptions from an async write");
// Attention\Cancellation\Timeouts
Debug.Assert(!_attentionReceived && !_attentionSent && !_attentionSending, $"StateObj is still dealing with attention: Sent: {_attentionSent}, Received: {_attentionReceived}, Sending: {_attentionSending}");
Debug.Assert(!_cancelled, "StateObj still has cancellation set");
Debug.Assert(!_internalTimeout, "StateObj still has internal timeout set");
// Errors and Warnings
Debug.Assert(!_hasErrorOrWarning, "StateObj still has stored errors or warnings");
}
}
#if DEBUG
internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait)
{
var realNetworkPacketTaskSource = _realNetworkPacketTaskSource;
var networkPacketTaskSource = _networkPacketTaskSource;
Debug.Assert(_forcePendingReadsToWaitForUser, "Not forcing pends to wait for user - can't force complete");
Debug.Assert(networkPacketTaskSource != null, "No pending read to complete");
try
{
if (realNetworkPacketTaskSource != null)
{
// Wait for the real read to complete
realNetworkPacketTaskSource.Task.Wait();
}
}
finally
{
if (networkPacketTaskSource != null)
{
if (resetForcePendingReadsToWait)
{
_forcePendingReadsToWaitForUser = false;
}
networkPacketTaskSource.TrySetResult(null);
}
}
}
internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait)
{
var realNetworkPacketTaskSource = _realNetworkPacketTaskSource;
var networkPacketTaskSource = _networkPacketTaskSource;
Debug.Assert(_forcePendingReadsToWaitForUser, "Not forcing pends to wait for user - can't force complete");
Debug.Assert(networkPacketTaskSource != null, "No pending read to complete");
try
{
if (realNetworkPacketTaskSource != null)
{
// Wait for the real read to complete
realNetworkPacketTaskSource.Task.Wait();
}
}
finally
{
if (networkPacketTaskSource != null)
{
if (resetForcePendingReadsToWait)
{
_forcePendingReadsToWaitForUser = false;
}
AddError(new SqlError(errorCode, 0x00, TdsEnums.FATAL_ERROR_CLASS, _parser.Server, string.Empty, string.Empty, 0));
try
{
ThrowExceptionAndWarning();
}
catch (Exception ex)
{
networkPacketTaskSource.TrySetException(ex);
}
}
}
}
#endif
internal void CloneCleanupAltMetaDataSetArray()
{
if (_snapshot != null)
{
_snapshot.CloneCleanupAltMetaDataSetArray();
}
}
private class PacketData
{
public byte[] Buffer;
public int Read;
#if DEBUG
public string Stack;
#endif
}
private class StateSnapshot
{
private List<PacketData> _snapshotInBuffs;
private int _snapshotInBuffCurrent = 0;
private int _snapshotInBytesUsed = 0;
private int _snapshotInBytesPacket = 0;
private bool _snapshotPendingData = false;
private bool _snapshotErrorTokenReceived = false;
private bool _snapshotHasOpenResult = false;
private bool _snapshotReceivedColumnMetadata = false;
private bool _snapshotAttentionReceived;
private byte _snapshotMessageStatus;
private NullBitmap _snapshotNullBitmapInfo;
private ulong _snapshotLongLen;
private ulong _snapshotLongLenLeft;
private _SqlMetaDataSet _snapshotCleanupMetaData;
private _SqlMetaDataSetCollection _snapshotCleanupAltMetaDataSetArray;
private readonly TdsParserStateObject _stateObj;
public StateSnapshot(TdsParserStateObject state)
{
_snapshotInBuffs = new List<PacketData>();
_stateObj = state;
}
#if DEBUG
private int _rollingPend = 0;
private int _rollingPendCount = 0;
internal bool DoPend()
{
if (_failAsyncPends || !_forceAllPends)
{
return false;
}
if (_rollingPendCount == _rollingPend)
{
_rollingPend++;
_rollingPendCount = 0;
return true;
}
_rollingPendCount++;
return false;
}
#endif
internal void CloneNullBitmapInfo()
{
if (_stateObj._nullBitmapInfo.ReferenceEquals(_snapshotNullBitmapInfo))
{
_stateObj._nullBitmapInfo = _stateObj._nullBitmapInfo.Clone();
}
}
internal void CloneCleanupAltMetaDataSetArray()
{
if (_stateObj._cleanupAltMetaDataSetArray != null && object.ReferenceEquals(_snapshotCleanupAltMetaDataSetArray, _stateObj._cleanupAltMetaDataSetArray))
{
_stateObj._cleanupAltMetaDataSetArray = (_SqlMetaDataSetCollection)_stateObj._cleanupAltMetaDataSetArray.Clone();
}
}
internal void PushBuffer(byte[] buffer, int read)
{
Debug.Assert(!_snapshotInBuffs.Any(b => object.ReferenceEquals(b.Buffer, buffer)));
PacketData packetData = new PacketData();
packetData.Buffer = buffer;
packetData.Read = read;
#if DEBUG
packetData.Stack = _stateObj._lastStack;
#endif
_snapshotInBuffs.Add(packetData);
}
#if DEBUG
internal void AssertCurrent()
{
Debug.Assert(_snapshotInBuffCurrent == _snapshotInBuffs.Count, "Should not be reading new packets when not replaying last packet");
}
internal void CheckStack(string trace)
{
PacketData prev = _snapshotInBuffs[_snapshotInBuffCurrent - 1];
if (prev.Stack == null)
{
prev.Stack = trace;
}
else
{
Debug.Assert(_stateObj._permitReplayStackTraceToDiffer || prev.Stack.ToString() == trace.ToString(), "The stack trace on subsequent replays should be the same");
}
}
#endif
internal bool Replay()
{
if (_snapshotInBuffCurrent < _snapshotInBuffs.Count)
{
PacketData next = _snapshotInBuffs[_snapshotInBuffCurrent];
_stateObj._inBuff = next.Buffer;
_stateObj._inBytesUsed = 0;
_stateObj._inBytesRead = next.Read;
_snapshotInBuffCurrent++;
return true;
}
return false;
}
internal void Snap()
{
_snapshotInBuffs.Clear();
_snapshotInBuffCurrent = 0;
_snapshotInBytesUsed = _stateObj._inBytesUsed;
_snapshotInBytesPacket = _stateObj._inBytesPacket;
_snapshotPendingData = _stateObj._pendingData;
_snapshotErrorTokenReceived = _stateObj._errorTokenReceived;
_snapshotMessageStatus = _stateObj._messageStatus;
// _nullBitmapInfo must be cloned before it is updated
_snapshotNullBitmapInfo = _stateObj._nullBitmapInfo;
_snapshotLongLen = _stateObj._longlen;
_snapshotLongLenLeft = _stateObj._longlenleft;
_snapshotCleanupMetaData = _stateObj._cleanupMetaData;
// _cleanupAltMetaDataSetArray must be cloned before it is updated
_snapshotCleanupAltMetaDataSetArray = _stateObj._cleanupAltMetaDataSetArray;
_snapshotHasOpenResult = _stateObj._hasOpenResult;
_snapshotReceivedColumnMetadata = _stateObj._receivedColMetaData;
_snapshotAttentionReceived = _stateObj._attentionReceived;
#if DEBUG
_rollingPend = 0;
_rollingPendCount = 0;
_stateObj._lastStack = null;
Debug.Assert(_stateObj._bTmpRead == 0, "Has partially read data when snapshot taken");
Debug.Assert(_stateObj._partialHeaderBytesRead == 0, "Has partially read header when snapshot taken");
#endif
PushBuffer(_stateObj._inBuff, _stateObj._inBytesRead);
}
internal void ResetSnapshotState()
{
// go back to the beginning
_snapshotInBuffCurrent = 0;
Replay();
_stateObj._inBytesUsed = _snapshotInBytesUsed;
_stateObj._inBytesPacket = _snapshotInBytesPacket;
_stateObj._pendingData = _snapshotPendingData;
_stateObj._errorTokenReceived = _snapshotErrorTokenReceived;
_stateObj._messageStatus = _snapshotMessageStatus;
_stateObj._nullBitmapInfo = _snapshotNullBitmapInfo;
_stateObj._cleanupMetaData = _snapshotCleanupMetaData;
_stateObj._cleanupAltMetaDataSetArray = _snapshotCleanupAltMetaDataSetArray;
_stateObj._hasOpenResult = _snapshotHasOpenResult;
_stateObj._receivedColMetaData = _snapshotReceivedColumnMetadata;
_stateObj._attentionReceived = _snapshotAttentionReceived;
// Reset partially read state (these only need to be maintained if doing async without snapshot)
_stateObj._bTmpRead = 0;
_stateObj._partialHeaderBytesRead = 0;
// reset plp state
_stateObj._longlen = _snapshotLongLen;
_stateObj._longlenleft = _snapshotLongLenLeft;
_stateObj._snapshotReplay = true;
_stateObj.AssertValidState();
}
internal void PrepareReplay()
{
ResetSnapshotState();
}
}
/*
// leave this in. comes handy if you have to do Console.WriteLine style debugging ;)
private void DumpBuffer() {
Console.WriteLine("dumping buffer");
Console.WriteLine("_inBytesRead = {0}", _inBytesRead);
Console.WriteLine("_inBytesUsed = {0}", _inBytesUsed);
int cc = 0; // character counter
int i;
Console.WriteLine("used buffer:");
for (i=0; i< _inBytesUsed; i++) {
if (cc==16) {
Console.WriteLine();
cc = 0;
}
Console.Write("{0,-2:X2} ", _inBuff[i]);
cc++;
}
if (cc>0) {
Console.WriteLine();
}
cc = 0;
Console.WriteLine("unused buffer:");
for (i=_inBytesUsed; i<_inBytesRead; i++) {
if (cc==16) {
Console.WriteLine();
cc = 0;
}
Console.Write("{0,-2:X2} ", _inBuff[i]);
cc++;
}
if (cc>0) {
Console.WriteLine();
}
}
*/
}
}
| 40.837938 | 246 | 0.514179 | [
"MIT"
] | Gary-Zh/SqlClient | src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs | 165,557 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Diagnostics.Runtime.DacInterface
{
public struct ExtendedModuleData
{
public int IsDynamic;
public int IsInMemory;
public int IsFlatLayout;
public ClrDataAddress PEFile;
public ClrDataAddress LoadedPEAddress;
public ulong LoadedPESize; // size of file on disk
public ClrDataAddress InMemoryPdbAddress;
public ulong InMemoryPdbSize;
}
}
| 33.526316 | 71 | 0.715856 | [
"MIT"
] | Bhaskers-Blu-Org2/clrmd | src/Microsoft.Diagnostics.Runtime/src/DacInterface/Structs/ExtendedModuleData.cs | 639 | C# |
using System;
namespace eth.Common
{
public interface IHttpClientTimeout
{
TimeSpan HttpClientTimeout { get; set; }
}
}
| 15.1 | 49 | 0.615894 | [
"Apache-2.0"
] | etherealko/StasyanBot | src/eth.Common/IHttpClientTimeout.cs | 153 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
public class GCodeMeshGenerator
{
private float plasticwidth = 0.6f;
public int layercluster = 1;
internal int createdLayers;
private Queue<MeshCreatorInput> meshCreatorInputQueue = new Queue<MeshCreatorInput>();
/* internal void CreateObjectFromGCode(string[] Lines, MeshLoader loader, GCodeHandler gcodeHandler)//takes ages and munches on all that juicy cpu, only use if absolutely necessary
{
}*/
internal void CreateObjectFromGCode(string[] Lines, MeshLoader loader, GCodeHandler gcodeHandler)
{
if (Lines[0].Contains("Cura"))
{
CreateObjectFromGCodeCura(Lines, loader, gcodeHandler);
}
else if (Lines[0].Contains("Prusa"))
{
CreateObjectFromGCodePrusa(Lines, loader, gcodeHandler);
}
}
internal void CreateObjectFromGCodeCura(string[] Lines, MeshLoader loader, GCodeHandler gcodeHandler)//takes ages and munches on all that juicy cpu, only use if absolutely necessary
{
//Read the text from directly from the test.txt file
gcodeHandler.loading = true;
loader.filesLoadingfinished = false;
List<string> meshnames = new List<string>();
int currentmesh = -1;
Dictionary<string, List<List<Vector3>>> tmpmove = new Dictionary<string, List<List<Vector3>>>();
Vector3 currpos = new Vector3(0, 0, 0);
float accumulateddist = 0.0f;
Vector3 lastpointcache = new Vector3(0, 0, 0);
int linesread = 0;
int layernum = 0;
bool accumulating = false;
float lastanglecache = 0.0f;
float accumulatedangle = 0.0f;
bool ismesh = false;
foreach (string line in Lines)
{
linesread += 1;
if (line.StartsWith(";TYPE:"))
{
ismesh = true;
string namemesh = line.Substring(6) + " " + layernum.ToString("D8");
if (line.Substring(6).Contains("WALL") || line.Substring(6).Contains("SKIN"))
{
namemesh = "WALLS " + layernum.ToString("D8");
}
//here i change the type of 3d printed part i print next, this only works in cura-sliced stuff, slic3r doesnt have those comments
if (!meshnames.Contains(namemesh))
{
meshnames.Add(namemesh);
currentmesh = meshnames.Count - 1;
tmpmove[namemesh] = new List<List<Vector3>>();
tmpmove[namemesh].Add(new List<Vector3>());
}
else
{
currentmesh = meshnames.FindIndex((namemesh).EndsWith);
}
}
else if (line.StartsWith(";LAYER:"))
{
layernum = int.Parse(line.Substring(7));
foreach (string namepart in tmpmove.Keys)
{
createlayer(tmpmove[namepart], namepart, loader);
}
tmpmove.Clear();
//todo create layer
}
else if ((line.StartsWith("G1") || line.StartsWith("G0")) && ((layernum % layercluster) == 0 || layercluster == 1))
{
//here i add a point to the list of visited points of the current part
readG1Cura(gcodeHandler.distanceclustersize, gcodeHandler.rotationclustersize, line, ref accumulating, ref accumulateddist, ref accumulatedangle, ref meshnames, ref currentmesh, ref currpos, ref lastpointcache, ref lastanglecache, ref tmpmove, ref ismesh);
}
else if (line.StartsWith(";MESH:"))
{
ismesh = false;
}
}
gcodeHandler.layersvisible = layernum;
loader.filesLoadingfinished = true;
gcodeHandler.newloaded = true;
}
void readG1Cura(float distanceclustersize, float rotationclustersize, string line, ref bool accumulating, ref float accumulateddist, ref float accumulatedangle, ref List<string> meshnames, ref int currentmesh, ref Vector3 currpos, ref Vector3 lastpointcache, ref float lastanglecache, ref Dictionary<string, List<List<Vector3>>> tmpmove, ref bool ismesh)
{
string[] parts = line.Split(' ');
if (accumulating)
{
accumulateddist += Vector3.Distance(currpos, lastpointcache);
accumulatedangle += Mathf.Abs(lastanglecache - Vector2.Angle(new Vector2(1, 0), new Vector2((currpos - lastpointcache).x, (currpos - lastpointcache).z)));
}
lastpointcache = currpos;
lastanglecache = Vector2.Angle(new Vector2(1, 0), new Vector2((currpos - lastpointcache).x, (currpos - lastpointcache).z));
if (!accumulating &&
(line.Contains("X") || line.Contains("Y") || line.Contains("Z")) &&
line.Contains("E") &&
currpos != new Vector3(0, 0, 0)
&& currentmesh != -1)
{
string meshname = meshnames[currentmesh];
if (tmpmove.ContainsKey(meshname))
{
tmpmove[meshname][tmpmove[meshname].Count - 1].Add(currpos);
}
}
foreach (string part in parts)
{
if (part.StartsWith("X"))
{
currpos.x = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
}
else if (part.StartsWith("Y"))
{
currpos.z = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
}
else if (part.StartsWith("Z"))
{
currpos.y = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
}
}
if (((!accumulating || accumulateddist > distanceclustersize || accumulatedangle > rotationclustersize) && (ismesh || line.Contains("E"))) && (line.Contains("X") || line.Contains("Y") || line.Contains("Z")) && currpos != new Vector3(0, 0, 0))
{
if (currentmesh != -1 && tmpmove.ContainsKey(meshnames[currentmesh]))
{
string meshname = meshnames[currentmesh];
tmpmove[meshname][tmpmove[meshname].Count - 1].Add(currpos);
}
accumulateddist = 0.0f;
accumulatedangle = 0.0f;
}
accumulating = true;
if (line.Contains("E") &&
(line.Contains("X") || line.Contains("Y") || line.Contains("Z")))
{
ismesh = true;
}
else
{
ismesh = false;
accumulating = false;
if (currentmesh != -1 && tmpmove.ContainsKey(meshnames[currentmesh]) && tmpmove[meshnames[currentmesh]][tmpmove[meshnames[currentmesh]].Count - 1].Count > 1)
{
tmpmove[meshnames[currentmesh]].Add(new List<Vector3>());
}
}
}
internal void CreateObjectFromGCodePrusa(string[] Lines, MeshLoader loader, GCodeHandler gcodeHandler)//takes ages and munches on all that juicy cpu, only use if absolutely necessary
{
//Read the text from directly from the test.txt file
//StreamReader reader = new StreamReader(new FileStream(filename, FileMode.Open));
gcodeHandler.loading = true;
loader.filesLoadingfinished = false;
//mc.print("loading " + filename);
List<string> meshnames = new List<string>();
int currentmesh = -1;
Dictionary<string, List<List<Vector3>>> tmpmove = new Dictionary<string, List<List<Vector3>>>();
Vector3 currpos = new Vector3(0, 0, 0);
float accumulateddist = 0.0f;
Vector3 lastpointcache = new Vector3(0, 0, 0);
int linesread = 0;
int layernum = -1;
bool accumulating = false;
float lastanglecache = 0.0f;
float accumulatedangle = 0.0f;
bool ismesh = false;
bool islayerheight = false;
foreach (string line in Lines)
{
//Layerheigt is defined in Prusa by writing ";AFTER_LAYER_CHANGE" and in the next line writing the height, therefore this happens:
linesread += 1;
if (islayerheight)
{
currpos.y = float.Parse(line.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
islayerheight = false;
}
if (line.Contains("support"))
{
bool ishere = true;
}
bool isnotmeshmove = line.Contains("wipe and retract") || line.Contains("move to first") || line.Contains("move inwards before travel") || line.Contains("retract") || line.Contains("lift Z") || line.Contains("move to first perimeter point") || line.Contains("restore layer Z") || line.Contains("unretract") || line.Contains("Move") || line.Contains("home");
if (line.StartsWith(";AFTER_LAYER_CHANGE"))
{
layernum = layernum + 1;
islayerheight = true;
foreach (string namepart in tmpmove.Keys)
{
createlayer(tmpmove[namepart], namepart, loader);
}
tmpmove.Clear();
//todo create layer
}
//movement commands are all G0 or G1 in Prusa Gcode
else if ((line.StartsWith("G1") || line.StartsWith("G0")) && layernum != -1 && ((layernum % layercluster) == 0 || layercluster == 1))
{
//bool isnew = false;
if (line.Contains(";")&&!isnotmeshmove)
{
string namemesh = line.Split(';')[1].Split(' ')[1]+ " " + layernum.ToString("D8");//In Prusaslicer the comments about what the Line Means are right next to the line
if (!meshnames.Contains(namemesh))
{
//isnew = true;
meshnames.Add(namemesh);
currentmesh = meshnames.Count - 1;
tmpmove[namemesh] = new List<List<Vector3>>();
tmpmove[namemesh].Add(new List<Vector3>());
}
else
{
if (meshnames[currentmesh] != namemesh||!ismesh)//Sometimes a type like infill happens more often inside one layer
{
tmpmove[namemesh].Add(new List<Vector3>());
//isnew = true;
}
currentmesh = meshnames.FindIndex((namemesh).EndsWith);
}
ismesh = true;
}
string[] parts = line.Split(' ');
if (line.Contains(";") && !isnotmeshmove)
{
if (accumulating)
{
accumulateddist += Vector3.Distance(currpos, lastpointcache);
accumulatedangle += Mathf.Abs(lastanglecache - Vector2.Angle(new Vector2(1, 0), new Vector2((currpos - lastpointcache).x, (currpos - lastpointcache).z)));
}
lastpointcache = currpos;
lastanglecache = Vector2.Angle(new Vector2(1, 0), new Vector2((currpos - lastpointcache).x, (currpos - lastpointcache).z));
//Since The G1 or G0 Commands are just "go to" commands, we need to store the Previous position as well, so before we touch currpos, we add it to the mesh, but only once per mesh
if (!accumulating &&
(line.Contains("X") || line.Contains("Y") || line.Contains("Z")) &&
line.Contains("E") &&
currpos.x != 0 && currpos.z != 0
&& currentmesh != -1)
{
string meshname = meshnames[currentmesh];
if (tmpmove.ContainsKey(meshname))
{
tmpmove[meshname][tmpmove[meshname].Count - 1].Add(currpos);
}
}
//now we can update currpos
foreach (string part in parts)
{
if (part.StartsWith("X"))
{
currpos.x = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
}
else if (part.StartsWith("Y"))
{
currpos.z = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat); //Unity has a Lefthanded Coordinate System (Y up), Gcode a Righthanded (Z up)
}
else if (part.StartsWith("Z"))
{
currpos.y = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
}
}/*
if (currentmesh != -1 && tmpmove.ContainsKey(meshnames[currentmesh]) && tmpmove[meshnames[currentmesh]][tmpmove[meshnames[currentmesh]].Count - 1].Count > 1)
{
if (isnew)
tmpmove[meshnames[currentmesh]].Add(new List<Vector3>());
//createlayer(tmpmove, meshnames[currentmesh]);
}*/
// if it is needed
if (((!accumulating || accumulateddist > gcodeHandler.distanceclustersize || accumulatedangle > gcodeHandler.rotationclustersize) && (ismesh || line.Contains("E"))) && (line.Contains("X") || line.Contains("Y") || line.Contains("Z")) && currpos != new Vector3(0, 0, 0))
{
/*if (currentmesh != -1 && meshnames[currentmesh].Contains("WALLS 60"))
print("second");*/
if (currentmesh != -1 && tmpmove.ContainsKey(meshnames[currentmesh]))
{
string meshname = meshnames[currentmesh];
tmpmove[meshname][tmpmove[meshname].Count - 1].Add(currpos);
}
accumulateddist = 0.0f;
accumulatedangle = 0.0f;
accumulating = true;
}
/*if (line.Contains("E") &&
(line.Contains("X") || line.Contains("Y") || line.Contains("Z")))
{
ismesh = true;
}*/
//ismesh = false;
//tmpmove.Clear();
}
else
{
foreach (string part in parts)
{
if (part.StartsWith("X"))
{
currpos.x = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
}
else if (part.StartsWith("Y"))
{
currpos.z = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat); //Unity has a Lefthanded Coordinate System (Y up), Gcode a Righthanded (Z up)
}
else if (part.StartsWith("Z"))
{
if(part.Length>1)
currpos.y = float.Parse(part.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
}
}
}
}
if (line.StartsWith(";BEFORE-LAYER-CHANGE")||line.Contains("retract"))
{
ismesh = false;
}
/*if(meshnames[currentmesh].Contains("WALLS 60"))
{
print(line);
}*/
}
gcodeHandler.layersvisible = layernum;
//loading = false;
loader.filesLoadingfinished = true;
gcodeHandler.newloaded = true;
}
void createlayer(List<List<Vector3>> tmpmoves, string meshname, MeshLoader loader)
{
List<Vector3> newVertices = new List<Vector3>();
List<Vector3> newNormals = new List<Vector3>();
List<Vector2> newUV = new List<Vector2>();
List<int> newTriangles = new List<int>();
List<Dictionary<int, Dictionary<int, int>>> neighbours = new List<Dictionary<int, Dictionary<int, int>>>();
for (int tmpmvn = 0; tmpmvn < tmpmoves.Count; tmpmvn++)
{
List<Vector3> tmpmove = tmpmoves[tmpmvn];
if (tmpmove.Count > 1)
{
createMesh(ref newVertices,ref tmpmove,ref newNormals,ref newUV,ref newTriangles);
}
}
MeshCreatorInput mci = new MeshCreatorInput
{
meshname = meshname,
newUV = newUV.ToArray(),
newNormals = newNormals.ToArray(),
newVertices = newVertices.ToArray(),
newTriangles = newTriangles.ToArray()
};
meshCreatorInputQueue.Enqueue(mci);
createdLayers++;
}
internal void createMesh(ref List<Vector3> newVertices, ref List<Vector3> tmpmove, ref List<Vector3> newNormals, ref List<Vector2> newUV, ref List<int> newTriangles)
{
//here i generate the mesh from the tmpmove list, wich is a list of points the extruder goes to
int vstart = newVertices.Count;
Vector3 dv = tmpmove[1] - tmpmove[0];
Vector3 dvt = dv; dvt.x = dv.z; dvt.z = -dv.x;
dvt = -dvt.normalized;
newVertices.Add(tmpmove[0] - dv.normalized * 0.5f + dvt * plasticwidth * 0.5f);
newVertices.Add(tmpmove[0] - dv.normalized * 0.5f - dvt * 0.5f * plasticwidth);
newVertices.Add(tmpmove[0] - dv.normalized * 0.5f - dvt * 0.5f * plasticwidth - new Vector3(0, -0.25f, 0) * layercluster);
newVertices.Add(tmpmove[0] - dv.normalized * 0.5f + dvt * plasticwidth * 0.5f - new Vector3(0, -0.25f, 0) * layercluster);
newNormals.Add((dvt.normalized * plasticwidth / 2 + new Vector3(0, plasticwidth / 2, 0) - dv.normalized * plasticwidth / 2).normalized);
newNormals.Add((dvt.normalized * -plasticwidth / 2 + new Vector3(0, plasticwidth / 2, 0) - dv.normalized * plasticwidth / 2).normalized);
newNormals.Add((dvt.normalized * -plasticwidth / 2 + new Vector3(0, -plasticwidth / 2, 0) - dv.normalized * plasticwidth / 2).normalized);
newNormals.Add((dvt.normalized * plasticwidth / 2 + new Vector3(0, -plasticwidth / 2, 0) - dv.normalized * plasticwidth / 2).normalized);
newUV.Add(new Vector2(0.0f, 0.0f));
newUV.Add(new Vector2(0.0f, 1.0f));
newUV.Add(new Vector2(1.0f, 1.0f));
newUV.Add(new Vector2(1.0f, 0.0f));
newTriangles.Add(vstart + 2);
newTriangles.Add(vstart + 1);
newTriangles.Add(vstart + 0); //back (those need to be in clockwise orientation for culling to work right)
newTriangles.Add(vstart + 0);
newTriangles.Add(vstart + 3);
newTriangles.Add(vstart + 2);
for (int i = 1; i < tmpmove.Count - 1; i++)
{
Vector3 dv1 = tmpmove[i] - tmpmove[i - 1];
Vector3 dvt1 = dv1; dvt1.x = dv1.z; dvt1.z = -dv1.x;
Vector3 dv2 = tmpmove[i + 1] - tmpmove[i];
Vector3 dvt2 = dv2; dvt2.x = dv2.z; dvt2.z = -dv2.x;
dvt = (dvt1 + dvt2).normalized * -plasticwidth;
newVertices.Add(tmpmove[i] + dvt * 0.5f);
newVertices.Add(tmpmove[i] - dvt * 0.5f);
newVertices.Add(tmpmove[i] - dvt * 0.5f - new Vector3(0, -0.25f, 0) * layercluster);
newVertices.Add(tmpmove[i] + dvt * 0.5f - new Vector3(0, -0.25f, 0) * layercluster);
newNormals.Add((dvt.normalized + new Vector3(0, 0.125f, 0)).normalized);
newNormals.Add((dvt.normalized + new Vector3(0, 0.125f, 0)).normalized);
newNormals.Add((dvt.normalized + new Vector3(0, -0.125f, 0)).normalized);
newNormals.Add((dvt.normalized + new Vector3(0, -0.125f, 0)).normalized);
newUV.Add(new Vector2(0.0f, 0.0f));
newUV.Add(new Vector2(0.0f, 1.0f));
newUV.Add(new Vector2(1.0f, 1.0f));
newUV.Add(new Vector2(1.0f, 0.0f));
newTriangles.Add(vstart + 0 + 4 * (i - 1));
newTriangles.Add(vstart + 1 + 4 * (i - 1));
newTriangles.Add(vstart + 5 + 4 * (i - 1)); //top
newTriangles.Add(vstart + 0 + 4 * (i - 1));
newTriangles.Add(vstart + 5 + 4 * (i - 1));
newTriangles.Add(vstart + 4 + 4 * (i - 1));
newTriangles.Add(vstart + 1 + 4 * (i - 1));
newTriangles.Add(vstart + 2 + 4 * (i - 1));
newTriangles.Add(vstart + 6 + 4 * (i - 1));//left
newTriangles.Add(vstart + 1 + 4 * (i - 1));
newTriangles.Add(vstart + 6 + 4 * (i - 1));
newTriangles.Add(vstart + 5 + 4 * (i - 1));
newTriangles.Add(vstart + 0 + 4 * (i - 1));
newTriangles.Add(vstart + 4 + 4 * (i - 1));
newTriangles.Add(vstart + 3 + 4 * (i - 1));//right
newTriangles.Add(vstart + 3 + 4 * (i - 1));
newTriangles.Add(vstart + 4 + 4 * (i - 1));
newTriangles.Add(vstart + 7 + 4 * (i - 1));
newTriangles.Add(vstart + 2 + 4 * (i - 1));
newTriangles.Add(vstart + 3 + 4 * (i - 1));
newTriangles.Add(vstart + 7 + 4 * (i - 1));//bottom
newTriangles.Add(vstart + 2 + 4 * (i - 1));
newTriangles.Add(vstart + 7 + 4 * (i - 1));
newTriangles.Add(vstart + 6 + 4 * (i - 1));
}
dv = tmpmove[tmpmove.Count - 1] - tmpmove[tmpmove.Count - 2];
dvt = dv; dvt.x = dv.z; dvt.z = -dv.x;
dvt = dvt.normalized * plasticwidth;
dv = dv.normalized * plasticwidth / 2;
int maxi = tmpmove.Count - 2;
newVertices.Add(tmpmove[maxi] + dv + dvt * 0.5f);
newVertices.Add(tmpmove[maxi] + dv - dvt * 0.5f);
newVertices.Add(tmpmove[maxi] + dv - dvt * 0.5f - new Vector3(0, -0.25f, 0) * layercluster);
newVertices.Add(tmpmove[maxi] + dv + dvt * 0.5f - new Vector3(0, -0.25f, 0) * layercluster);
newNormals.Add((dvt + new Vector3(0, plasticwidth / 2, 0) + dv).normalized);
newNormals.Add((-dvt + new Vector3(0, plasticwidth / 2, 0) + dv).normalized);
newNormals.Add((-dvt + new Vector3(0, -plasticwidth / 2, 0) + dv).normalized);
newNormals.Add((dvt + new Vector3(0, -plasticwidth / 2, 0) + dv).normalized);
newUV.Add(new Vector2(0.0f, 0.0f));
newUV.Add(new Vector2(0.0f, 1.0f));
newUV.Add(new Vector2(1.0f, 1.0f));
newUV.Add(new Vector2(1.0f, 0.0f));
newTriangles.Add(vstart + 0 + 4 * maxi);
newTriangles.Add(vstart + 1 + 4 * maxi);
newTriangles.Add(vstart + 5 + 4 * maxi); //top
newTriangles.Add(vstart + 0 + 4 * maxi);
newTriangles.Add(vstart + 5 + 4 * maxi);
newTriangles.Add(vstart + 4 + 4 * maxi);
newTriangles.Add(vstart + 1 + 4 * maxi);
newTriangles.Add(vstart + 2 + 4 * maxi);
newTriangles.Add(vstart + 6 + 4 * maxi);//left
newTriangles.Add(vstart + 1 + 4 * maxi);
newTriangles.Add(vstart + 6 + 4 * maxi);
newTriangles.Add(vstart + 5 + 4 * maxi);
newTriangles.Add(vstart + 0 + 4 * maxi);
newTriangles.Add(vstart + 4 + 4 * maxi);
newTriangles.Add(vstart + 3 + 4 * maxi);//right
newTriangles.Add(vstart + 3 + 4 * maxi);
newTriangles.Add(vstart + 4 + 4 * maxi);
newTriangles.Add(vstart + 7 + 4 * maxi);
newTriangles.Add(vstart + 2 + 4 * maxi);
newTriangles.Add(vstart + 3 + 4 * maxi);
newTriangles.Add(vstart + 7 + 4 * maxi);//bottom
newTriangles.Add(vstart + 2 + 4 * maxi);
newTriangles.Add(vstart + 7 + 4 * maxi);
newTriangles.Add(vstart + 6 + 4 * maxi);
newTriangles.Add(vstart + 4 + 4 * maxi);
newTriangles.Add(vstart + 5 + 4 * maxi);
newTriangles.Add(vstart + 7 + 4 * maxi);//front
newTriangles.Add(vstart + 7 + 4 * maxi);
newTriangles.Add(vstart + 5 + 4 * maxi);
newTriangles.Add(vstart + 6 + 4 * maxi);
}
internal void Update(GCodeHandler source, MeshLoader loader)
{
if (meshCreatorInputQueue.Count > 0)
{
MeshCreatorInput mci = meshCreatorInputQueue.Dequeue();
source.createmesh(mci.meshname, mci.newVertices, mci.newNormals, mci.newUV, mci.newTriangles, source.RootForObject.transform);
}
}
} | 47.178368 | 369 | 0.533765 | [
"MIT"
] | lsls421/ExtendedPrinter-Unity | ExtendedPrinter/Assets/Extended-Printer/Scripts/GCodeMeshGenerator.cs | 24,865 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ada.Framework.Util.Core.Editions.TO
{
/// <summary>
/// Entrega el resultado de la edición
/// </summary>
/// <remarks>
/// Registro de versiones:
///
/// 1.0 02/03/2015 Marcos Abraham Hernández Bravo (Ada Ltda.): versión inicial.
/// </remarks>
/// <typeparam name="E">Enumeración de errores</typeparam>
public class ResultadoEdicion<E>
{
/// <summary>
/// Obtiene o establece el valor de enumeración que indica el estado del valor, por ejemplo, Valido.
/// </summary>
/// <remarks>
/// Registro de versiones:
///
/// 1.0 02/03/2015 Marcos Abraham Hernández Bravo (Ada Ltda.): versión inicial.
/// </remarks>
public E CodigoEstado { get; set; }
/// <summary>
/// Obtiene o establece el valor adicional al error señalado.
/// </summary>
/// <remarks>
/// Registro de versiones:
///
/// 1.0 02/03/2015 Marcos Abraham Hernández Bravo (Ada Ltda.): versión inicial.
/// </remarks>
public string ValorAdicional { get; set; }
/// <summary>
/// Obtiene o establece el valor
/// </summary>
/// <remarks>
/// Registro de versiones:
///
/// 1.0 02/03/2015 Marcos Abraham Hernández Bravo (Ada Ltda.): versión inicial.
/// </remarks>
public string ValorFormateado { get; set; }
}
}
| 33.2 | 109 | 0.523494 | [
"MIT"
] | adasoluciones/Util.Core | Source/Editions/TO/ResultadoEdicion.cs | 1,674 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace EPPlusTest
{
[TestClass]
public class DTS_FailingTests
{
[TestMethod]
public void DeleteWorksheetWithReferencedImage()
{
var ms = new MemoryStream();
using (var pck = new ExcelPackage())
{
var ws = pck.Workbook.Worksheets.Add("original");
ws.Drawings.AddPicture("Pic1", Properties.Resources.Test1);
pck.Workbook.Worksheets.Copy("original", "copy");
pck.SaveAs(ms);
}
ms.Position = 0;
using (var pck = new ExcelPackage(ms))
{
var ws = pck.Workbook.Worksheets["original"];
pck.Workbook.Worksheets.Delete(ws);
pck.Save();
}
}
[TestMethod]
public void CopyAndDeleteWorksheetWithImage()
{
using (var pck = new ExcelPackage(new MemoryStream()))
{
var ws = pck.Workbook.Worksheets.Add("original");
ws.Drawings.AddPicture("Pic1", Properties.Resources.Test1);
pck.Workbook.Worksheets.Copy("original", "copy");
pck.Workbook.Worksheets.Delete(ws);
pck.Save();
}
}
}
}
| 29.04 | 75 | 0.546832 | [
"MIT"
] | Afonsof91/Magicodes.IE | src/EPPlus/EPPlusTest/DTS_FailingTests.cs | 1,454 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Microsoft.Data.Common;
using Microsoft.Data.SqlClient;
namespace Microsoft.Data.SqlClient
{
internal static class SNINativeMethodWrapper
{
private static int s_sniMaxComposedSpnLength = -1;
private static readonly bool s_is64bitProcess = Environment.Is64BitProcess;
private const int SniOpenTimeOut = -1; // infinite
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SqlAsyncCallbackDelegate(IntPtr m_ConsKey, IntPtr pPacket, uint dwError);
internal delegate IntPtr SqlClientCertificateDelegate(IntPtr pCallbackContext);
internal const int ConnTerminatedError = 2;
internal const int InvalidParameterError = 5;
internal const int ProtocolNotSupportedError = 8;
internal const int ConnTimeoutError = 11;
internal const int ConnNotUsableError = 19;
internal const int InvalidConnStringError = 25;
internal const int HandshakeFailureError = 31;
internal const int InternalExceptionError = 35;
internal const int ConnOpenFailedError = 40;
internal const int ErrorSpnLookup = 44;
internal const int LocalDBErrorCode = 50;
internal const int MultiSubnetFailoverWithMoreThan64IPs = 47;
internal const int MultiSubnetFailoverWithInstanceSpecified = 48;
internal const int MultiSubnetFailoverWithNonTcpProtocol = 49;
internal const int MaxErrorValue = 50157;
internal const int LocalDBNoInstanceName = 51;
internal const int LocalDBNoInstallation = 52;
internal const int LocalDBInvalidConfig = 53;
internal const int LocalDBNoSqlUserInstanceDllPath = 54;
internal const int LocalDBInvalidSqlUserInstanceDllPath = 55;
internal const int LocalDBFailedToLoadDll = 56;
internal const int LocalDBBadRuntime = 57;
internal static int SniMaxComposedSpnLength
{
get
{
if (s_sniMaxComposedSpnLength == -1)
{
s_sniMaxComposedSpnLength = checked((int)GetSniMaxComposedSpnLength());
}
return s_sniMaxComposedSpnLength;
}
}
static AppDomain GetDefaultAppDomainInternal()
{
return AppDomain.CurrentDomain;
}
internal static _AppDomain GetDefaultAppDomain()
{
return GetDefaultAppDomainInternal();
}
[ResourceExposure(ResourceScope.Process)] // SxS: there is no way to set scope = Instance, using Process which is wider
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal unsafe static byte[] GetData()
{
int size;
IntPtr ptr = (IntPtr)(SqlDependencyProcessDispatcherStorage.NativeGetData(out size));
byte[] result = null;
if (ptr != IntPtr.Zero)
{
result = new byte[size];
Marshal.Copy(ptr, result, 0, size);
}
return result;
}
[ResourceExposure(ResourceScope.Process)] // SxS: there is no way to set scope = Instance, using Process which is wider
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal unsafe static void SetData(Byte[] data)
{
//cli::pin_ptr<System::Byte> pin_dispatcher = &data[0];
fixed (byte* pin_dispatcher = &data[0])
{
SqlDependencyProcessDispatcherStorage.NativeSetData(pin_dispatcher, data.Length);
}
}
unsafe internal class SqlDependencyProcessDispatcherStorage
{
static void* data;
static int size;
static volatile int thelock; // Int used for a spin-lock.
public static void* NativeGetData(out int passedSize)
{
passedSize = size;
return data;
}
internal static bool NativeSetData(void* passedData, int passedSize)
{
bool success = false;
while (0 != Interlocked.CompareExchange(ref thelock, 1, 0))
{ // Spin until we have the lock.
Thread.Sleep(50); // Sleep with short-timeout to prevent starvation.
}
Trace.Assert(1 == thelock); // Now that we have the lock, lock should be equal to 1.
if (null == data)
{
data = Marshal.AllocHGlobal(passedSize).ToPointer();
Trace.Assert(null != data);
System.Buffer.MemoryCopy(passedData, data, passedSize, passedSize);
Trace.Assert(0 == size); // Size should still be zero at this point.
size = passedSize;
success = true;
}
int result = Interlocked.CompareExchange(ref thelock, 0, 1);
Trace.Assert(1 == result); // The release of the lock should have been successful.
return success;
}
}
internal enum SniSpecialErrors : uint
{
LocalDBErrorCode = SNINativeMethodWrapper.LocalDBErrorCode,
// multi-subnet-failover specific error codes
MultiSubnetFailoverWithMoreThan64IPs = SNINativeMethodWrapper.MultiSubnetFailoverWithMoreThan64IPs,
MultiSubnetFailoverWithInstanceSpecified = SNINativeMethodWrapper.MultiSubnetFailoverWithInstanceSpecified,
MultiSubnetFailoverWithNonTcpProtocol = SNINativeMethodWrapper.MultiSubnetFailoverWithNonTcpProtocol,
// max error code value
MaxErrorValue = SNINativeMethodWrapper.MaxErrorValue,
}
#region Structs\Enums
[StructLayout(LayoutKind.Sequential)]
internal struct ConsumerInfo
{
internal int defaultBufferSize;
internal SqlAsyncCallbackDelegate readDelegate;
internal SqlAsyncCallbackDelegate writeDelegate;
internal IntPtr key;
}
internal struct AuthProviderInfo
{
internal uint flags;
internal string certId;
internal bool certHash;
internal object clientCertificateCallbackContext;
internal SqlClientCertificateDelegate clientCertificateCallback;
};
internal struct CTAIPProviderInfo
{
internal byte[] originalNetworkAddress;
internal Boolean fromDataSecurityProxy;
};
struct SNIAuthProviderInfoWrapper
{
internal object pDelegateContext;
internal SqlClientCertificateDelegate pSqlClientCertificateDelegate;
};
internal struct SNICTAIPProviderInfo
{
internal SNIHandle pConn;
internal byte prgbAddress;
internal ulong cbAddress;
internal bool fFromDataSecurityProxy;
};
[StructLayout(LayoutKind.Sequential)]
internal struct CredHandle
{
internal IntPtr dwLower;
internal IntPtr dwUpper;
};
internal enum ContextAttribute
{
// sspi.h
SECPKG_ATTR_SIZES = 0,
SECPKG_ATTR_NAMES = 1,
SECPKG_ATTR_LIFESPAN = 2,
SECPKG_ATTR_DCE_INFO = 3,
SECPKG_ATTR_STREAM_SIZES = 4,
SECPKG_ATTR_AUTHORITY = 6,
SECPKG_ATTR_PACKAGE_INFO = 10,
SECPKG_ATTR_NEGOTIATION_INFO = 12,
SECPKG_ATTR_UNIQUE_BINDINGS = 25,
SECPKG_ATTR_ENDPOINT_BINDINGS = 26,
SECPKG_ATTR_CLIENT_SPECIFIED_TARGET = 27,
SECPKG_ATTR_APPLICATION_PROTOCOL = 35,
// minschannel.h
SECPKG_ATTR_REMOTE_CERT_CONTEXT = 0x53, // returns PCCERT_CONTEXT
SECPKG_ATTR_LOCAL_CERT_CONTEXT = 0x54, // returns PCCERT_CONTEXT
SECPKG_ATTR_ROOT_STORE = 0x55, // returns HCERTCONTEXT to the root store
SECPKG_ATTR_ISSUER_LIST_EX = 0x59, // returns SecPkgContext_IssuerListInfoEx
SECPKG_ATTR_CONNECTION_INFO = 0x5A, // returns SecPkgContext_ConnectionInfo
SECPKG_ATTR_UI_INFO = 0x68, // sets SEcPkgContext_UiInfo
}
internal enum ConsumerNumber
{
SNI_Consumer_SNI,
SNI_Consumer_SSB,
SNI_Consumer_PacketIsReleased,
SNI_Consumer_Invalid,
}
internal enum IOType
{
READ,
WRITE,
}
internal enum PrefixEnum
{
UNKNOWN_PREFIX,
SM_PREFIX,
TCP_PREFIX,
NP_PREFIX,
VIA_PREFIX,
INVALID_PREFIX,
}
internal enum ProviderEnum
{
HTTP_PROV,
NP_PROV,
SESSION_PROV,
SIGN_PROV,
SM_PROV,
SMUX_PROV,
SSL_PROV,
TCP_PROV,
VIA_PROV,
CTAIP_PROV,
MAX_PROVS,
INVALID_PROV,
}
internal enum QTypes
{
SNI_QUERY_CONN_INFO,
SNI_QUERY_CONN_BUFSIZE,
SNI_QUERY_CONN_KEY,
SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE,
SNI_QUERY_SERVER_ENCRYPT_POSSIBLE,
SNI_QUERY_CERTIFICATE,
SNI_QUERY_LOCALDB_HMODULE,
SNI_QUERY_CONN_ENCRYPT,
SNI_QUERY_CONN_PROVIDERNUM,
SNI_QUERY_CONN_CONNID,
SNI_QUERY_CONN_PARENTCONNID,
SNI_QUERY_CONN_SECPKG,
SNI_QUERY_CONN_NETPACKETSIZE,
SNI_QUERY_CONN_NODENUM,
SNI_QUERY_CONN_PACKETSRECD,
SNI_QUERY_CONN_PACKETSSENT,
SNI_QUERY_CONN_PEERADDR,
SNI_QUERY_CONN_PEERPORT,
SNI_QUERY_CONN_LASTREADTIME,
SNI_QUERY_CONN_LASTWRITETIME,
SNI_QUERY_CONN_CONSUMER_ID,
SNI_QUERY_CONN_CONNECTTIME,
SNI_QUERY_CONN_HTTPENDPOINT,
SNI_QUERY_CONN_LOCALADDR,
SNI_QUERY_CONN_LOCALPORT,
SNI_QUERY_CONN_SSLHANDSHAKESTATE,
SNI_QUERY_CONN_SOBUFAUTOTUNING,
SNI_QUERY_CONN_SECPKGNAME,
SNI_QUERY_CONN_SECPKGMUTUALAUTH,
SNI_QUERY_CONN_CONSUMERCONNID,
SNI_QUERY_CONN_SNIUCI,
SNI_QUERY_CONN_SUPPORTS_EXTENDED_PROTECTION,
SNI_QUERY_CONN_CHANNEL_PROVIDES_AUTHENTICATION_CONTEXT,
SNI_QUERY_CONN_PEERID,
SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC,
SNI_QUERY_CONN_SSL_SECCTXTHANDLE,
}
internal enum TransparentNetworkResolutionMode : byte
{
DisabledMode = 0,
SequentialMode,
ParallelMode
};
[StructLayout(LayoutKind.Sequential)]
internal struct Sni_Consumer_Info
{
public int DefaultUserDataLength;
public IntPtr ConsumerKey;
public IntPtr fnReadComp;
public IntPtr fnWriteComp;
public IntPtr fnTrace;
public IntPtr fnAcceptComp;
public uint dwNumProts;
public IntPtr rgListenInfo;
public IntPtr NodeAffinity;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct SNI_CLIENT_CONSUMER_INFO
{
public Sni_Consumer_Info ConsumerInfo;
[MarshalAs(UnmanagedType.LPWStr)]
public string wszConnectionString;
public PrefixEnum networkLibrary;
public byte* szSPN;
public uint cchSPN;
public byte* szInstanceName;
public uint cchInstanceName;
[MarshalAs(UnmanagedType.Bool)]
public bool fOverrideLastConnectCache;
[MarshalAs(UnmanagedType.Bool)]
public bool fSynchronousConnection;
public int timeout;
[MarshalAs(UnmanagedType.Bool)]
public bool fParallel;
public TransparentNetworkResolutionMode transparentNetworkResolution;
public int totalTimeout;
public bool isAzureSqlServerEndpoint;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct SNI_Error
{
internal ProviderEnum provider;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 261)]
internal string errorMessage;
internal uint nativeError;
internal uint sniError;
[MarshalAs(UnmanagedType.LPWStr)]
internal string fileName;
[MarshalAs(UnmanagedType.LPWStr)]
internal string function;
internal uint lineNumber;
}
#endregion
#region DLL Imports
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("secur32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern uint QueryContextAttributes(ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] IntPtr buffer);
internal static uint SNIAddProvider(SNIHandle pConn, ProviderEnum ProvNum, [In] ref uint pInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIAddProvider(pConn, ProvNum, ref pInfo) :
SNINativeManagedWrapperX86.SNIAddProvider(pConn, ProvNum, ref pInfo);
}
internal static uint SNIAddProviderWrapper(SNIHandle pConn, ProviderEnum ProvNum, [In] ref SNICTAIPProviderInfo pInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIAddProviderWrapper(pConn, ProvNum, ref pInfo) :
SNINativeManagedWrapperX86.SNIAddProviderWrapper(pConn, ProvNum, ref pInfo);
}
internal static uint SNIAddProviderWrapper(SNIHandle pConn, ProviderEnum ProvNum, [In] ref AuthProviderInfo pInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIAddProviderWrapper(pConn, ProvNum, ref pInfo) :
SNINativeManagedWrapperX86.SNIAddProviderWrapper(pConn, ProvNum, ref pInfo);
}
internal static uint SNICheckConnection([In] SNIHandle pConn)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNICheckConnection(pConn) :
SNINativeManagedWrapperX86.SNICheckConnection(pConn);
}
internal static uint SNIClose(IntPtr pConn)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIClose(pConn) :
SNINativeManagedWrapperX86.SNIClose(pConn);
}
internal static void SNIGetLastError(out SNI_Error pErrorStruct)
{
if (s_is64bitProcess)
{
SNINativeManagedWrapperX64.SNIGetLastError(out pErrorStruct);
}
else
{
SNINativeManagedWrapperX86.SNIGetLastError(out pErrorStruct);
}
}
internal static void SNIPacketRelease(IntPtr pPacket)
{
if (s_is64bitProcess)
{
SNINativeManagedWrapperX64.SNIPacketRelease(pPacket);
}
else
{
SNINativeManagedWrapperX86.SNIPacketRelease(pPacket);
}
}
internal static void SNIPacketReset([In] SNIHandle pConn, IOType IOType, SNIPacket pPacket, ConsumerNumber ConsNum)
{
if (s_is64bitProcess)
{
SNINativeManagedWrapperX64.SNIPacketReset(pConn, IOType, pPacket, ConsNum);
}
else
{
SNINativeManagedWrapperX86.SNIPacketReset(pConn, IOType, pPacket, ConsNum);
}
}
internal static uint SNIQueryInfo(QTypes QType, ref uint pbQInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIQueryInfo(QType, ref pbQInfo) :
SNINativeManagedWrapperX86.SNIQueryInfo(QType, ref pbQInfo);
}
internal static uint SNIQueryInfo(QTypes QType, ref IntPtr pbQInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIQueryInfo(QType, ref pbQInfo) :
SNINativeManagedWrapperX86.SNIQueryInfo(QType, ref pbQInfo);
}
internal static uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIReadAsync(pConn, ref ppNewPacket) :
SNINativeManagedWrapperX86.SNIReadAsync(pConn, ref ppNewPacket);
}
internal static uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIReadSyncOverAsync(pConn, ref ppNewPacket, timeout) :
SNINativeManagedWrapperX86.SNIReadSyncOverAsync(pConn, ref ppNewPacket, timeout);
}
internal static uint SNIRemoveProvider(SNIHandle pConn, ProviderEnum ProvNum)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIRemoveProvider(pConn, ProvNum) :
SNINativeManagedWrapperX86.SNIRemoveProvider(pConn, ProvNum);
}
internal static uint SNISecInitPackage(ref uint pcbMaxToken)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNISecInitPackage(ref pcbMaxToken) :
SNINativeManagedWrapperX86.SNISecInitPackage(ref pcbMaxToken);
}
internal static uint SNISetInfo(SNIHandle pConn, QTypes QType, [In] ref uint pbQInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNISetInfo(pConn, QType, ref pbQInfo) :
SNINativeManagedWrapperX86.SNISetInfo(pConn, QType, ref pbQInfo);
}
internal static uint SNITerminate()
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNITerminate() :
SNINativeManagedWrapperX86.SNITerminate();
}
internal static uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIWaitForSSLHandshakeToComplete(pConn, dwMilliseconds) :
SNINativeManagedWrapperX86.SNIWaitForSSLHandshakeToComplete(pConn, dwMilliseconds);
}
internal static uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.UnmanagedIsTokenRestricted(token, out isRestricted) :
SNINativeManagedWrapperX86.UnmanagedIsTokenRestricted(token, out isRestricted);
}
private static uint GetSniMaxComposedSpnLength()
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.GetSniMaxComposedSpnLength() :
SNINativeManagedWrapperX86.GetSniMaxComposedSpnLength();
}
private static uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out Guid pbQInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIGetInfoWrapper(pConn, QType, out pbQInfo) :
SNINativeManagedWrapperX86.SNIGetInfoWrapper(pConn, QType, out pbQInfo);
}
private static uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, [MarshalAs(UnmanagedType.Bool)] out bool pbQInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIGetInfoWrapper(pConn, QType, out pbQInfo) :
SNINativeManagedWrapperX86.SNIGetInfoWrapper(pConn, QType, out pbQInfo);
}
private static uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, ref IntPtr pbQInfo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIGetInfoWrapper(pConn, QType, ref pbQInfo) :
SNINativeManagedWrapperX86.SNIGetInfoWrapper(pConn, QType, ref pbQInfo);
}
private static uint SNIInitialize([In] IntPtr pmo)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIInitialize(pmo) :
SNINativeManagedWrapperX86.SNIInitialize(pmo);
}
private static uint SNIOpenSyncExWrapper(ref SNI_CLIENT_CONSUMER_INFO pClientConsumerInfo, out IntPtr ppConn)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIOpenSyncExWrapper(ref pClientConsumerInfo, out ppConn) :
SNINativeManagedWrapperX86.SNIOpenSyncExWrapper(ref pClientConsumerInfo, out ppConn);
}
private static uint SNIOpenWrapper(
[In] ref Sni_Consumer_Info pConsumerInfo,
[MarshalAs(UnmanagedType.LPWStr)] string szConnect,
[In] SNIHandle pConn,
out IntPtr ppConn,
[MarshalAs(UnmanagedType.Bool)] bool fSync)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIOpenWrapper(ref pConsumerInfo, szConnect, pConn, out ppConn, fSync) :
SNINativeManagedWrapperX86.SNIOpenWrapper(ref pConsumerInfo, szConnect, pConn, out ppConn, fSync);
}
private static IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IOType IOType)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIPacketAllocateWrapper(pConn, IOType) :
SNINativeManagedWrapperX86.SNIPacketAllocateWrapper(pConn, IOType);
}
private static uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize) :
SNINativeManagedWrapperX86.SNIPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize);
}
private static unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf)
{
if (s_is64bitProcess)
{
SNINativeManagedWrapperX64.SNIPacketSetData(pPacket, pbBuf, cbBuf);
}
else
{
SNINativeManagedWrapperX86.SNIPacketSetData(pPacket, pbBuf, cbBuf);
}
}
private static unsafe uint SNISecGenClientContextWrapper(
[In] SNIHandle pConn,
[In, Out] byte[] pIn,
uint cbIn,
[In, Out] byte[] pOut,
[In] ref uint pcbOut,
[MarshalAsAttribute(UnmanagedType.Bool)] out bool pfDone,
byte* szServerInfo,
uint cbServerInfo,
[MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszUserName,
[MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszPassword)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNISecGenClientContextWrapper(pConn, pIn, cbIn, pOut, ref pcbOut, out pfDone, szServerInfo, cbServerInfo, pwszUserName, pwszPassword) :
SNINativeManagedWrapperX86.SNISecGenClientContextWrapper(pConn, pIn, cbIn, pOut, ref pcbOut, out pfDone, szServerInfo, cbServerInfo, pwszUserName, pwszPassword);
}
private static uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIWriteAsyncWrapper(pConn, pPacket) :
SNINativeManagedWrapperX86.SNIWriteAsyncWrapper(pConn, pPacket);
}
private static uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIWriteSyncOverAsync(pConn, pPacket) :
SNINativeManagedWrapperX86.SNIWriteSyncOverAsync(pConn, pPacket);
}
private static IntPtr SNIClientCertificateFallbackWrapper(IntPtr pCallbackContext)
{
return s_is64bitProcess ?
SNINativeManagedWrapperX64.SNIClientCertificateFallbackWrapper(pCallbackContext) :
SNINativeManagedWrapperX86.SNIClientCertificateFallbackWrapper(pCallbackContext);
}
#endregion
internal static uint SNISecGetServerCertificate(SNIHandle pConnectionObject, ref X509Certificate2 certificate)
{
System.UInt32 ret;
CredHandle pSecHandle;
X509Certificate pCertContext = null;
// provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
pConnectionObject.DangerousAddRef(ref mustRelease);
Debug.Assert(mustRelease, "AddRef Failed!");
IntPtr secHandlePtr = Marshal.AllocHGlobal(Marshal.SizeOf<CredHandle>());
ret = SNIGetInfoWrapper(pConnectionObject, QTypes.SNI_QUERY_CONN_SSL_SECCTXTHANDLE, ref secHandlePtr);
//ERROR_SUCCESS
if (0 == ret)
{
// Cast an unmanaged block to pSecHandle;
pSecHandle = Marshal.PtrToStructure<CredHandle>(secHandlePtr);
// SEC_E_OK
if (0 == (ret = QueryContextAttributes(ref pSecHandle, ContextAttribute.SECPKG_ATTR_REMOTE_CERT_CONTEXT, pCertContext.Handle)))
{
certificate = new X509Certificate2(pCertContext.Handle);
}
}
Marshal.FreeHGlobal(secHandlePtr);
}
finally
{
if (pCertContext != null)
{
pCertContext.Dispose();
}
if (mustRelease)
{
pConnectionObject.DangerousRelease();
}
}
return ret;
}
internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId)
{
return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId);
}
internal static uint SNIInitialize()
{
return SNIInitialize(IntPtr.Zero);
}
internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync)
{
// initialize consumer info for MARS
Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info();
MarshalConsumerInfo(consumerInfo, ref native_consumerInfo);
return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync);
}
internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel, Int32 transparentNetworkResolutionStateNo, Int32 totalTimeout, Boolean isAzureSqlServerEndpoint)
{
fixed (byte* pin_instanceName = &instanceName[0])
{
SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = new SNI_CLIENT_CONSUMER_INFO();
// initialize client ConsumerInfo part first
MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo);
clientConsumerInfo.wszConnectionString = constring;
clientConsumerInfo.networkLibrary = PrefixEnum.UNKNOWN_PREFIX;
clientConsumerInfo.szInstanceName = pin_instanceName;
clientConsumerInfo.cchInstanceName = (uint)instanceName.Length;
clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache;
clientConsumerInfo.fSynchronousConnection = fSync;
clientConsumerInfo.timeout = timeout;
clientConsumerInfo.fParallel = fParallel;
clientConsumerInfo.isAzureSqlServerEndpoint = ADP.IsAzureSqlServerEndpoint(constring);
switch (transparentNetworkResolutionStateNo)
{
case (0):
clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.DisabledMode;
break;
case (1):
clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.SequentialMode;
break;
case (2):
clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.ParallelMode;
break;
};
clientConsumerInfo.totalTimeout = totalTimeout;
if (spnBuffer != null)
{
fixed (byte* pin_spnBuffer = &spnBuffer[0])
{
clientConsumerInfo.szSPN = pin_spnBuffer;
clientConsumerInfo.cchSPN = (uint)spnBuffer.Length;
return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn);
}
}
else
{
// else leave szSPN null (SQL Auth)
return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn);
}
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal static uint SNIAddProvider(SNIHandle pConn,
ProviderEnum providerEnum,
AuthProviderInfo authInfo)
{
UInt32 ret;
uint ERROR_SUCCESS = 0;
SNIAuthProviderInfoWrapper sniAuthInfoWrapper;
if (authInfo.clientCertificateCallback != null)
{
sniAuthInfoWrapper.pDelegateContext = authInfo.clientCertificateCallbackContext;
sniAuthInfoWrapper.pSqlClientCertificateDelegate = authInfo.clientCertificateCallback;
authInfo.clientCertificateCallbackContext = sniAuthInfoWrapper;
authInfo.clientCertificateCallback = SNIClientCertificateFallbackWrapper;
}
ret = SNIAddProviderWrapper(pConn, providerEnum, ref authInfo);
if (ret == ERROR_SUCCESS)
{
// added a provider, need to requery for sync over async support
bool fSupportsSyncOverAsync;
ret = SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC, out fSupportsSyncOverAsync);
Debug.Assert(ret == ERROR_SUCCESS, "SNIGetInfo cannot fail with this QType");
}
return ret;
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal static uint SNIAddProvider(SNIHandle pConn,
ProviderEnum providerEnum,
CTAIPProviderInfo authInfo)
{
UInt32 ret;
uint ERROR_SUCCESS = 0;
SNICTAIPProviderInfo ctaipInfo = new SNICTAIPProviderInfo();
ctaipInfo.prgbAddress = authInfo.originalNetworkAddress[0];
ctaipInfo.cbAddress = (byte)authInfo.originalNetworkAddress.Length;
ctaipInfo.fFromDataSecurityProxy = authInfo.fromDataSecurityProxy;
ret = SNIAddProviderWrapper(pConn, providerEnum, ref ctaipInfo);
if (ret == ERROR_SUCCESS)
{
// added a provider, need to requery for sync over async support
bool fSupportsSyncOverAsync;
ret = SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC, out fSupportsSyncOverAsync);
Debug.Assert(ret == ERROR_SUCCESS, "SNIGetInfo cannot fail with this QType");
}
return ret;
}
internal static void SNIPacketAllocate(SafeHandle pConn, IOType IOType, ref IntPtr pPacket)
{
pPacket = SNIPacketAllocateWrapper(pConn, IOType);
}
internal static unsafe uint SNIPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize)
{
return SNIPacketGetDataWrapper(packet, readBuffer, (uint)readBuffer.Length, out dataSize);
}
internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int length)
{
fixed (byte* pin_data = &data[0])
{
SNIPacketSetData(packet, pin_data, (uint)length);
}
}
//[ResourceExposure(ResourceScope::None)]
//
// Notes on SecureString: Writing out security sensitive information to managed buffer should be avoid as these can be moved
// around by GC. There are two set of information which falls into this category: passwords and new changed password which
// are passed in as SecureString by a user. Writing out clear passwords information is delayed until this layer to ensure that
// the information is written out to buffer which is pinned in this method already. This also ensures that processing a clear password
// is done right before it is written out to SNI_Packet where gets encrypted properly.
// TdsParserStaticMethods.EncryptPassword operation is also done here to minimize the time the clear password is held in memory. Any changes
// to loose encryption algorithm is changed it should be done in both in this method as well as TdsParserStaticMethods.EncryptPassword.
// Up to current release, it is also guaranteed that both password and new change password will fit into a single login packet whose size is fixed to 4096
// So, there is no splitting logic is needed.
internal static void SNIPacketSetData(SNIPacket packet,
Byte[] data,
Int32 length,
SecureString[] passwords, // pointer to the passwords which need to be written out to SNI Packet
Int32[] passwordOffsets // Offset into data buffer where the password to be written out to
)
{
Debug.Assert(passwords == null || (passwordOffsets != null && passwords.Length == passwordOffsets.Length), "The number of passwords does not match the number of password offsets");
bool mustRelease = false;
bool mustClearBuffer = false;
IntPtr clearPassword = IntPtr.Zero;
// provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions
RuntimeHelpers.PrepareConstrainedRegions();
try
{
unsafe
{
fixed (byte* pin_data = &data[0])
{ }
if (passwords != null)
{
// Process SecureString
for (int i = 0; i < passwords.Length; ++i)
{
// SecureString is used
if (passwords[i] != null)
{
// provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions
RuntimeHelpers.PrepareConstrainedRegions();
try
{
// ==========================================================================
// Get the clear text of secure string without converting it to String type
// ==========================================================================
clearPassword = Marshal.SecureStringToCoTaskMemUnicode(passwords[i]);
// ==========================================================================================================================
// Losely encrypt the clear text - The encryption algorithm should exactly match the TdsParserStaticMethods.EncryptPassword
// ==========================================================================================================================
unsafe
{
char* pwChar = (char*)clearPassword.ToPointer();
byte* pByte = (byte*)(clearPassword.ToPointer());
int s;
byte bLo;
byte bHi;
int passwordsLength = passwords[i].Length;
for (int j = 0; j < passwordsLength; ++j)
{
s = (int)*pwChar;
bLo = (byte)(s & 0xff);
bHi = (byte)((s >> 8) & 0xff);
*(pByte++) = (Byte)((((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5);
*(pByte++) = (Byte)((((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5);
++pwChar;
}
// ===========================================================
// Write out the losely encrypted passwords to data buffer
// ===========================================================
mustClearBuffer = true;
Marshal.Copy(clearPassword, data, passwordOffsets[i], passwordsLength * 2);
}
}
finally
{
// Make sure that we clear the security sensitive information
if (clearPassword != IntPtr.Zero)
{
Marshal.ZeroFreeCoTaskMemUnicode(clearPassword);
}
}
}
}
}
packet.DangerousAddRef(ref mustRelease);
Debug.Assert(mustRelease, "AddRef Failed!");
fixed (byte* pin_data = &data[0])
{
SNIPacketSetData(packet, pin_data, (uint)length);
}
}
}
finally
{
if (mustRelease)
{
packet.DangerousRelease();
}
// Make sure that we clear the security sensitive information
// data->Initialize() is not safe to call under CER
if (mustClearBuffer)
{
for (int i = 0; i < data.Length; ++i)
{
data[i] = 0;
}
}
}
}
internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, byte[] inBuff, uint receivedLength, byte[] OutBuff, ref uint sendLength, byte[] serverUserName)
{
fixed (byte* pin_serverUserName = &serverUserName[0])
{
bool local_fDone;
return SNISecGenClientContextWrapper(
pConnectionObject,
inBuff,
receivedLength,
OutBuff,
ref sendLength,
out local_fDone,
pin_serverUserName,
(uint)serverUserName.Length,
null,
null);
}
}
internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync)
{
if (sync)
{
return SNIWriteSyncOverAsync(pConn, packet);
}
else
{
return SNIWriteAsyncWrapper(pConn, packet);
}
}
private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo)
{
native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize;
native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate
? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate)
: IntPtr.Zero;
native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate
? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate)
: IntPtr.Zero;
native_consumerInfo.ConsumerKey = consumerInfo.key;
}
}
}
namespace Microsoft.Data
{
internal static partial class SafeNativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)]
internal static extern IntPtr GetProcAddress(IntPtr HModule, [MarshalAs(UnmanagedType.LPStr), In] string funcName);
}
}
namespace Microsoft.Data
{
internal static class Win32NativeMethods
{
internal static bool IsTokenRestrictedWrapper(IntPtr token)
{
bool isRestricted;
uint result = SNINativeMethodWrapper.UnmanagedIsTokenRestricted(token, out isRestricted);
if (result != 0)
{
Marshal.ThrowExceptionForHR(unchecked((int)result));
}
return isRestricted;
}
}
}
| 41.928295 | 310 | 0.583014 | [
"MIT"
] | alexdougie/SqlClient | src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs | 43,290 | C# |
using FluentAssertions;
using GarageManager.Data.Repository;
using GarageManager.Domain;
using MockQueryable.Moq;
using Moq;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace GarageManager.Services.Tests
{
public class ManufacturerServiceTests : BaseTest
{
#region GetAllTypesAsync Tests
[Fact]
public async Task GetAllAsyncShouldReturnCollectionOfManufacturerIfAny()
{
//Arrange
var repository = this.GetManufacturerRepository(this.GetTestManufacturerList());
var manufacturerService = new ManufacturerService(repository.Object);
//Act
var result = await manufacturerService.GetAllAsync();
//Assert
result
.Should()
.NotBeEmpty();
}
[Fact]
public async Task GetAllAsyncShouldReturnEmptyCollectionIfNoManufacturers()
{
//Arrange
var repository = this.GetManufacturerRepository(new List<VehicleManufacturer>());
var manufacturerService = new ManufacturerService(repository.Object);
//Act
var result = await manufacturerService.GetAllAsync();
//Assert
result
.Should()
.BeEmpty();
}
#endregion
#region Configuration of Mock<IdeletableEntityRepository<VehicleManufacturer>>
private Mock<IDeletableEntityRepository<VehicleManufacturer>> GetManufacturerRepository(List<VehicleManufacturer> testManufacturerList)
{
var repository = new Mock<IDeletableEntityRepository<VehicleManufacturer>>();
repository.Setup(all => all.All()).Returns(testManufacturerList.Where(x => !x.IsDeleted).AsQueryable().BuildMockDbQuery().Object);
return repository;
}
#endregion
#region TestFuelManufacturerList
private List<VehicleManufacturer> GetTestManufacturerList()
{
var list = new List<VehicleManufacturer>
{
new VehicleManufacturer
{
Id ="1",
Name = "Opel"
},
new VehicleManufacturer
{
Id ="2",
Name = "Ford"
}
};
return list;
}
#endregion
}
}
| 30.296296 | 143 | 0.58965 | [
"MIT"
] | TodorChapkanov/Garage-Manager | Tests/GarageManager.Services.Tests/ManufacturerServiceTests.cs | 2,456 | C# |
using System.Text.Json.Serialization;
namespace Trakx.Common.Sources.Messari.DTOs
{
public partial class StakingStats
{
[JsonPropertyName("staking_yield_percent")]
public double? StakingYieldPercent { get; set; }
[JsonPropertyName("staking_type")]
public string StakingType { get; set; }
[JsonPropertyName("staking_minimum")]
public object StakingMinimum { get; set; }
[JsonPropertyName("tokens_staked")]
public double? TokensStaked { get; set; }
[JsonPropertyName("tokens_staked_percent")]
public double? TokensStakedPercent { get; set; }
[JsonPropertyName("real_staking_yield_percent")]
public double? RealStakingYieldPercent { get; set; }
}
} | 30.4 | 60 | 0.671053 | [
"MIT"
] | fakecoinbase/trakxslashtrakx-tools | src/Trakx.Common/Sources/Messari/DTOs/StakingStats.cs | 762 | C# |
using OpenBots.Core.Settings;
using OpenBots.UI.Forms.Supplement_Forms;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace OpenBots.UI.Forms.Sequence_Forms
{
public partial class frmSequence : Form
{
#region UI Buttons
#region File Actions Tool Strip and Buttons
private void ClearSelectedListViewItems()
{
SelectedTabScriptActions.SelectedItems.Clear();
SelectedTabScriptActions.Invalidate();
}
#region Restart And Close Buttons
private void uiBtnClose_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
#endregion
#endregion
#region Options Tool Strip and Buttons
private void uiBtnAddVariable_Click(object sender, EventArgs e)
{
OpenVariableManager();
}
private void OpenVariableManager()
{
frmScriptVariables scriptVariableEditor = new frmScriptVariables(TypeContext)
{
ScriptName = uiScriptTabControl.SelectedTab.Name
};
scriptVariableEditor.ScriptContext = ScriptContext;
if (scriptVariableEditor.ShowDialog() == DialogResult.OK)
{
if (!uiScriptTabControl.SelectedTab.Text.Contains(" *"))
uiScriptTabControl.SelectedTab.Text += " *";
}
ResetVariableArgumentBindings();
scriptVariableEditor.Dispose();
ScriptContext.AddIntellisenseControls(Controls);
}
private void uiBtnAddArgument_Click(object sender, EventArgs e)
{
OpenArgumentManager();
}
private void OpenArgumentManager()
{
frmScriptArguments scriptArgumentEditor = new frmScriptArguments(TypeContext)
{
ScriptName = uiScriptTabControl.SelectedTab.Name,
ScriptContext = ScriptContext
};
if (scriptArgumentEditor.ShowDialog() == DialogResult.OK)
{
if (!uiScriptTabControl.SelectedTab.Text.Contains(" *"))
uiScriptTabControl.SelectedTab.Text += " *";
}
ResetVariableArgumentBindings();
scriptArgumentEditor.Dispose();
ScriptContext.AddIntellisenseControls(Controls);
}
private void uiBtnAddElement_Click(object sender, EventArgs e)
{
OpenElementManager();
}
private void OpenElementManager()
{
frmScriptElements scriptElementEditor = new frmScriptElements
{
ScriptName = uiScriptTabControl.SelectedTab.Name,
ScriptContext = ScriptContext
};
if (scriptElementEditor.ShowDialog() == DialogResult.OK)
{
CreateUndoSnapshot();
}
scriptElementEditor.Dispose();
ScriptContext.AddIntellisenseControls(Controls);
}
private void uiBtnSettings_Click(object sender, EventArgs e)
{
OpenSettingsManager();
}
private void OpenSettingsManager()
{
//show settings dialog
frmSettings newSettings = new frmSettings(AContainer);
newSettings.ShowDialog();
//reload app settings
_appSettings = new ApplicationSettings().GetOrCreateApplicationSettings();
newSettings.Dispose();
}
private void clearAllToolStripMenuItem_Click(object sender, EventArgs e)
{
uiBtnClearAll_Click(sender, e);
}
private void uiBtnClearAll_Click(object sender, EventArgs e)
{
CreateUndoSnapshot();
SelectedTabScriptActions.Items.Clear();
}
private void aboutOpenBotsToolStripMenuItem_Click(object sender, EventArgs e)
{
frmAbout frmAboutForm = new frmAbout();
frmAboutForm.Show();
}
#endregion
#region Recorder Buttons
private void uiBtnSaveSequence_Click(object sender, EventArgs e)
{
dgvVariables.EndEdit();
dgvArguments.EndEdit();
if (SelectedTabScriptActions.Items.Count == 0)
{
Notify("You must have at least 1 automation command to save.", Color.Yellow);
return;
}
int beginLoopValidationCount = 0;
int beginIfValidationCount = 0;
int tryCatchValidationCount = 0;
int beginSwitchValidationCount = 0;
foreach (ListViewItem item in SelectedTabScriptActions.Items)
{
switch (item.Tag.GetType().Name)
{
case "BrokenCodeCommentCommand":
Notify("Please verify that all broken code has been removed or replaced.", Color.Yellow);
return;
case "BeginForEachCommand":
case "LoopContinuouslyCommand":
case "LoopNumberOfTimesCommand":
case "BeginWhileCommand":
case "BeginMultiWhileCommand":
case "BeginDoWhileCommand":
beginLoopValidationCount++;
break;
case "EndLoopCommand":
beginLoopValidationCount--;
break;
case "BeginIfCommand":
case "BeginMultiIfCommand":
beginIfValidationCount++;
break;
case "EndIfCommand":
beginIfValidationCount--;
break;
case "BeginTryCommand":
case "BeginRetryCommand":
tryCatchValidationCount++;
break;
case "EndTryCommand":
tryCatchValidationCount--;
break;
case "BeginSwitchCommand":
beginSwitchValidationCount++;
break;
case "EndSwitchCommand":
beginSwitchValidationCount--;
break;
}
//end loop was found first
if (beginLoopValidationCount < 0)
{
Notify("Please verify the ordering of your loops.", Color.Yellow);
return;
}
//end if was found first
if (beginIfValidationCount < 0)
{
Notify("Please verify the ordering of your ifs.", Color.Yellow);
return;
}
if (tryCatchValidationCount < 0)
{
Notify("Please verify the ordering of your try/catch blocks.", Color.Yellow);
return;
}
if (beginSwitchValidationCount < 0)
{
Notify("Please verify the ordering of your switch/case blocks.", Color.Yellow);
return;
}
}
//extras were found
if (beginLoopValidationCount != 0)
{
Notify("Please verify the ordering of your loops.", Color.Yellow);
return;
}
//extras were found
if (beginIfValidationCount != 0)
{
Notify("Please verify the ordering of your ifs.", Color.Yellow);
return;
}
if (tryCatchValidationCount != 0)
{
Notify("Please verify the ordering of your try/catch blocks.", Color.Yellow);
return;
}
if (beginSwitchValidationCount != 0)
{
Notify("Please verify the ordering of your switch/case blocks.", Color.Yellow);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void uiBtnRenameSequence_Click(object sender, EventArgs e)
{
frmInputBox renameSequence = new frmInputBox("New Sequence Name", "Rename Sequence");
renameSequence.txtInput.Text = Text;
renameSequence.ShowDialog();
if (renameSequence.DialogResult == DialogResult.OK)
{
Text = renameSequence.txtInput.Text;
if (!uiScriptTabControl.SelectedTab.Text.Contains(" *"))
uiScriptTabControl.SelectedTab.Text += " *";
}
renameSequence.Dispose();
}
private void shortcutMenuToolStripMenuItem_Click(object sender, EventArgs e)
{
frmShortcutMenu shortcutMenuForm = new frmShortcutMenu();
shortcutMenuForm.Show();
}
private void openShortcutMenuToolStripMenuItem_Click(object sender, EventArgs e)
{
shortcutMenuToolStripMenuItem_Click(sender, e);
}
#endregion
#endregion
}
}
| 33.190647 | 113 | 0.531375 | [
"MIT"
] | OpenBotsAI/OpenBots.Studio | OpenBots.Studio/UI/Forms/Sequence Forms/frmSequenceUIButtons.cs | 9,229 | C# |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: Assembly
**
** Purpose: For Assembly-related stuff.
**
=============================================================================*/
namespace System.Reflection
{
using System;
using System.Runtime.CompilerServices;
//| <include path='docs/doc[@for="Assembly"]/*' />
[RequiredByBartok]
public partial class Assembly
{
[RequiredByBartok]
private AssemblyName assemblyName;
}
}
| 21.714286 | 79 | 0.457237 | [
"MIT"
] | pmache/singularityrdk | SOURCE/base/Imported/Bartok/Reflection/Assembly.cs | 608 | C# |
public class Company
{
public Company() { }
public Company(string name, string department, decimal salary)
{
this.Name = name;
this.Department = department;
this.Salary = salary;
}
public string Name { get; set; }
public string Department { get; set; }
public decimal Salary { get; set; }
public override string ToString()
{
return $"{this.Name} {this.Department} {this.Salary:f2}";
}
} | 21.090909 | 66 | 0.599138 | [
"MIT"
] | BoykoNeov/C-Sharp-OOP-Basics-SoftUni | DefiningClasses/Google/Company.cs | 466 | C# |
// Decompiled with JetBrains decompiler
// Type: System.Fabric.Management.ServiceModel.ServicePackageTypeDigestedServiceTypes
// Assembly: System.Fabric.Management.ServiceModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: C6D32D4D-966E-4EA3-BD3A-F4CF14D36DBC
// Assembly location: C:\Git\ServiceFabricSdkContrib\ServiceFabricSdkContrib.MsBuild\bin\Debug\netstandard2.0\publish\runtimes\win\lib\netstandard2.0\System.Fabric.Management.ServiceModel.dll
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Xml.Serialization;
namespace System.Fabric.Management.ServiceModel
{
[GeneratedCode("xsd", "4.0.30319.17929")]
[DebuggerStepThrough]
[XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/2011/01/fabric")]
public class ServicePackageTypeDigestedServiceTypes
{
private ServiceTypeType[] serviceTypesField;
private string rolloutVersionField;
[XmlArrayItem("StatefulServiceType", typeof (StatefulServiceTypeType), IsNullable = false)]
[XmlArrayItem("StatelessServiceType", typeof (StatelessServiceTypeType), IsNullable = false)]
public ServiceTypeType[] ServiceTypes
{
get
{
return this.serviceTypesField;
}
set
{
this.serviceTypesField = value;
}
}
[XmlAttribute]
public string RolloutVersion
{
get
{
return this.rolloutVersionField;
}
set
{
this.rolloutVersionField = value;
}
}
}
}
| 30.979592 | 191 | 0.727931 | [
"MIT"
] | aL3891/ServiceFabricSdk-Contrib | System.Fabric.Management.ServiceModel/ServicePackageTypeDigestedServiceTypes.cs | 1,520 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using X_SMS_REP;
using X_SMS_DAL.Database;
using X_SMS_DAL.Services;
namespace X_SMS_API.AIHelper
{
class PlayerAILogics : IDisposable
{
StockDetail shouldBuy;
StockDetail shouldSell;
int shouldntBuy;
int shouldntSell;
PlayerService playerService = null;
XSmsEntities aiEntities = null;
GameDTO curGame = null;
List<AIBuySellDetails> list = null;
public PlayerAILogics()
{
aiEntities = new XSmsEntities();
playerService = new PlayerService();
list = new List<AIBuySellDetails>();
}
public void setGame(GameDTO game)
{
curGame = game;
}
public void BuyStocksForFirstTime(int playerID)
{
list.Clear();
List<Stock> stocks = playerService.getAllStocks();
List<Stock> firstThree = new List<Stock>(stocks.OrderBy(c => c.StartingPrice).Take(3));
decimal totPrice = 0;
foreach (Stock item in firstThree)
{
totPrice += item.StartingPrice;
}
foreach (Stock item in firstThree)
{
StockDetail stockDetail = new StockDetail();
stockDetail.StockId = item.StockId;
stockDetail.StockName = item.StockName;
stockDetail.StartingPrice = item.StartingPrice;
stockDetail.CurrentPrice = 0;
try
{
int avgPrice = (int)((item.StartingPrice / totPrice) * 100);
int quanCategory = CheckQuanAmountForFirstTime(avgPrice);
int buyingQuanRange = CalcQuantityForFirstTime(quanCategory); //buying for first time
int buyingQuan = (int)(buyingQuanRange / item.StartingPrice);
AIBuySellDetails itemBuySell = new AIBuySellDetails();
if (buyingQuan > 0)
{
itemBuySell.GameId = curGame.GameId;
itemBuySell.PlayerId = playerID;
itemBuySell.SectorId = item.SectorId;
itemBuySell.Quantity = buyingQuan;
itemBuySell.Stock = stockDetail;
itemBuySell.Buy = true;
list.Add(itemBuySell);
}
//playerService.buyStocks(playerID, buyingQuan, stockDetail, item.StartingPrice);
}
catch (Exception e)
{
}
}
}
public void SellAllStocks(int playerId, List<StockDetail> ownStocks)
{
list.Clear();
foreach (StockDetail item in ownStocks)
{
try
{
int quan = playerService.checkStockQuantity(playerId, item.StockId);
AIBuySellDetails itemBuySell = new AIBuySellDetails();
if (quan > 0)
{
itemBuySell.GameId = curGame.GameId;
itemBuySell.PlayerId = playerId;
itemBuySell.SectorId = item.SectorId;
itemBuySell.Quantity = quan;
itemBuySell.Stock = item;
itemBuySell.Buy = false;
list.Add(itemBuySell);
}
//playerService.buyStocks(playerID, buyingQuan, stockDetail, item.StartingPrice);
}
catch (Exception e)
{
}
}
}
public void CheckHistoryForBuy(List<TurnDetail> prevTurns, List<StockDetail> currentStocks)
{
//shouldBuy = new StockDetail();
//List<TurnDetail> prevTurns = prevTurnsArray.Cast<TurnDetail>().ToList();
foreach (TurnDetail turn in prevTurns)
{
foreach (SectorDetail sector in turn.Sectors)
{
foreach (StockDetail stock in sector.Stocks)
{
int i = 0;
foreach (StockDetail owned in currentStocks)
{
if (stock.StockId != owned.StockId)
{
i++; continue;
}
else
{
if (shouldBuy == null)
shouldBuy = stock;
else if (shouldBuy.CurrentPrice > stock.CurrentPrice)
shouldBuy = stock;
}
}
if (i == currentStocks.Capacity && stock.CurrentPrice > shouldBuy.CurrentPrice)
{//this stock is never bought but its cur price is greater than shouldBuy's price
shouldBuy = stock;
}
}
}
}
}
public void CheckHistoryForSell(List<TurnDetail> prevTurns, List<StockDetail> currentStocks)
{
//shouldSell = new StockDetail();
//List<TurnDetail> prevTurns = prevTurnsArray.Cast<TurnDetail>().ToList();
foreach (TurnDetail turn in prevTurns)
{
foreach (SectorDetail sector in turn.Sectors)
{
foreach (StockDetail stock in sector.Stocks)
{
foreach (StockDetail owned in currentStocks)
{
if (stock.StockId != owned.StockId)
continue;
else
{
if (shouldSell == null)
shouldSell = stock;
else if (shouldSell.CurrentPrice < stock.CurrentPrice)
shouldSell = stock;
}
}
}
}
}
}
public void SetBuySellForAI(List<StockDetail> ownStocks, int playerID)
{
list.Clear();
CheckHistoryWithCurrent(ownStocks);
if(ownStocks != null)
{
foreach (StockDetail item in ownStocks)
{
AIBuySellDetails itemBuySell = new AIBuySellDetails();
decimal averagePrice = 0;
try
{
averagePrice = playerService.amountSpentForStocks(playerID, item.StockId);
}
catch (Exception)
{
averagePrice = 0;
}
if (averagePrice > 0)
{
if (((item.CurrentPrice - averagePrice) >= (decimal)0.2) && item.StockId != shouldntSell) //sell
{
try
{
int decidingPrice = (int)((averagePrice * 100) / item.CurrentPrice);
int quanCategory = CheckQuanAmount(decidingPrice);
int sellingQuan = CalcQuantity(quanCategory, playerService.checkStockQuantity(playerID, item.StockId));
if (quanCategory > 0 && sellingQuan > 0 && curGame != null)
{
itemBuySell.GameId = curGame.GameId;
itemBuySell.PlayerId = playerID;
itemBuySell.SectorId = item.SectorId;
itemBuySell.Quantity = sellingQuan;
itemBuySell.Stock = item;
itemBuySell.Buy = false;
list.Add(itemBuySell);
}
//hub.SellStocks(curGame.GameId, playerID, item.SectorId, item, sellingQuan);
//playerService.sellStocks(playerID, sellingQuan, item, item.CurrentPrice);
}
catch (Exception e)
{
}
}
else if (((item.CurrentPrice - averagePrice) < (decimal)0.2) && item.StockId != shouldntBuy)//buy
{
try
{
int decidingPrice = (int)((item.CurrentPrice * 100)/ averagePrice);
int quanCategory = CheckQuanAmount(decidingPrice);
int buyingQuan = CalcQuantity(quanCategory, playerService.checkStockQuantity(playerID, item.StockId));
if (quanCategory > 0 && buyingQuan > 0)
{
itemBuySell.GameId = curGame.GameId;
itemBuySell.PlayerId = playerID;
itemBuySell.SectorId = item.SectorId;
itemBuySell.Quantity = buyingQuan;
itemBuySell.Stock = item;
itemBuySell.Buy = true;
list.Add(itemBuySell);
}
//hub.BuyStocks(curGame.GameId, playerID, item.SectorId, item, buyingQuan);
//playerService.buyStocks(playerID, buyingQuan, item, item.CurrentPrice);
}
catch (Exception e)
{
}
}
}
}
}
}
private void CheckHistoryWithCurrent(List<StockDetail> ownStocks)
{
if (shouldSell != null && shouldBuy != null && ownStocks != null)
{
foreach (StockDetail item in ownStocks)
{
if (item.StockId != shouldBuy.StockId)
continue;
else
{
if (item.CurrentPrice > shouldBuy.CurrentPrice)
shouldntBuy = item.StockId;
}
}
foreach (StockDetail item in ownStocks)
{
if (item.StockId != shouldSell.StockId)
continue;
else
{
if (item.CurrentPrice < shouldSell.CurrentPrice)
shouldntSell = item.StockId;
}
}
}
}
private int CheckQuanAmount(int decidingPrice)
{
switch (decidingPrice)
{
case int n when (n >= 104 && n <= 107): //1 - max buying side should buy
return 1;
case 103:
return 2;
case 102:
return 3;
case 101:
return 4;
case 100: //lowest should buy
return 5;
case int n when (n >= 90 && n <= 95): // selling should sell max
return 10;
case 96:
return 9;
case 97:
return 8;
case 98:
return 7;
case 99:
return 6; //lowest should sell
default:
return 0;
}
}
private int CalcQuantity(int category, int currentStockQuan)
{
switch (category)
{
case 1:
return ((currentStockQuan * 90) / 100); //buy start
case 2:
return ((currentStockQuan * 80) / 100);
case 3:
return ((currentStockQuan * 70) / 100);
case 4:
return ((currentStockQuan * 60) / 100);
case 5:
return ((currentStockQuan * 50) / 100); //buy calc end
case 6:
return ((currentStockQuan * 50) / 100); //sell start
case 7:
return ((currentStockQuan * 60) / 100);
case 8:
return ((currentStockQuan * 70) / 100);
case 9:
return ((currentStockQuan * 80) / 100);
case 10:
return ((currentStockQuan * 90) / 100); //sell max end
default:
return 0;
}
}
private int CheckQuanAmountForFirstTime(int decidingPrice)
{
switch (decidingPrice)
{
case int n when (n >= 1 && n <= 10):
return 1;
case int n when (n > 10 && n <= 20):
return 2;
case int n when (n > 20 && n <= 30):
return 3;
case int n when (n > 30 && n <= 40):
return 4;
case int n when (n > 40 && n <= 50):
return 5;
case int n when (n > 50 && n <= 60):
return 6;
case int n when (n > 60 && n <= 70):
return 7;
case int n when (n > 70 && n <= 80):
return 8;
case int n when (n > 80 && n <= 90):
return 9;
case int n when (n > 90 && n <= 100):
return 10;
default:
return 0;
}
}
private int CalcQuantityForFirstTime(int category)
{
switch (category)
{
case 1:
return (500 * 50) / 100;
case 2:
return (500 * 40) / 100;
case 3:
return (500 * 30) / 100;
case 4:
return (500 * 25) / 100;
case 5:
return (500 * 20) / 100;
case 6:
return (500 * 15) / 100;
case 7:
return (500 * 10) / 100;
case 8:
return (500 * 5) / 100;
case 9:
return (500 * 3) / 100;
case 10:
return (500 * 1) / 100;
default:
return 0;
}
}
public List<AIBuySellDetails> returnBuySellList()
{
if (list != null)
return list;
else
return null;
}
public void Dispose()
{
if (playerService != null)
{
playerService.Dispose();
playerService = null;
}
if (aiEntities != null)
{
aiEntities.Dispose();
aiEntities = null;
}
if (shouldSell != null)
shouldSell = null;
if (shouldBuy != null)
shouldBuy = null;
if (curGame != null)
curGame = null;
if (list != null)
list = null;
}
}
} | 38.12114 | 135 | 0.403203 | [
"MIT"
] | imanshu15/x-sms | X-SMS/X-SMS-API/AIHelper/PlayerAILogics.cs | 16,051 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static Root;
using static core;
using Caller = System.Runtime.CompilerServices.CallerMemberNameAttribute;
public readonly struct ApiIdentityBuilder
{
/// <summary>
/// Produces an identifier of the form {opname}_{bitsize(kind)}{u | i | f}
/// </summary>
/// <param name="opname">The base operator name</param>
/// <param name="k">The primal kind over which the identifier is deined</param>
[MethodImpl(Inline)]
public static OpIdentity NumericOp(string opname, NumericKind k, bool generic = false)
=> build(opname, NativeTypeWidth.None, k, generic);
/// <summary>
/// Produces an identifier of the form {opname}_g{kind}{u | i | f}
/// </summary>
/// <param name="opname">The base operator name</param>
/// <param name="t">A primal type representative</param>
/// <typeparam name="T">The primal type</typeparam>
[MethodImpl(Inline)]
public static OpIdentity NumericOp<T>(string opname, bool generic = true)
where T : unmanaged
=> build(opname, NativeTypeWidth.None, NumericKinds.kind<T>(), generic);
public static string name<W,C>(Type host, string label, bool generic)
where W : unmanaged, ITypeWidth
where C : unmanaged
=> $"{PartName.from(host)}/{host.Name}{IDI.UriPathSep}{build(label, default(W).TypeWidth, NumericKinds.kind<C>(), generic)}";
/// <summary>
/// Produces a test case identifier predicated on a parametrically-specialized label
/// <param name="label">The case label</param>
/// <typeparam name="T">The label specialization type</typeparam>
public static OpIdentity NumericId<T>([Caller] string label = null)
where T : unmanaged
=> numeric($"{label}", typeof(T).NumericKind());
/// <summary>
/// Produces an identifier of the form {opname}_{bitsize(kind)}{u | i | f}
/// </summary>
/// <param name="opname">The base operator name</param>
/// <param name="k">The primal kind over which the identifier is deined</param>
[MethodImpl(Inline), Op]
public static OpIdentity numeric(string opname, NumericKind k, bool generic = false)
=> build(opname, NativeTypeWidth.None, k, generic);
public static OpIdentity kind<K,T>(K kind, T t = default)
where K : unmanaged
where T : unmanaged
=> build(kind.ToString().ToLower(), (NativeTypeWidth)width<T>(), NumericKinds.kind<T>(), true);
public static OpIdentity klass<K,T>(K @class, T t = default)
where K : unmanaged, IApiClass
where T : unmanaged
=> build(@class.Format(), (NativeTypeWidth)width<T>(), NumericKinds.kind<T>(), true);
/// <summary>
/// Defines an identifier of the form {opname}_WxN{u | i | f} where N := bitsize[T]
/// </summary>
/// <param name="opname">The base operator name</param>
/// <param name="w">The covering bit width representative</param>
/// <param name="t">A primal cell type representative</param>
/// <typeparam name="W">The bit width type</typeparam>
/// <typeparam name="T">The cell type</typeparam>
[Op]
public static OpIdentity build(string opname, NativeTypeWidth tw, NumericKind k, bool generic)
{
var w = (CpuCellWidth)tw;
var g = generic ? $"{IDI.Generic}" : EmptyString;
if(generic && k == 0)
return ApiUri.opid(string.Concat(opname, IDI.PartSep, IDI.Generic));
else if(w.IsSome())
return ApiUri.opid(string.Concat(opname, IDI.PartSep, $"{g}{w.FormatValue()}{IDI.SegSep}{k.Format()}"));
else
return ApiUri.opid(string.Concat($"{opname}_{g}{k.Format()}"));
}
/// <summary>
/// Produces an identifier of the form {opname}_{g}{bitsize(kind)}{u | i | f}
/// </summary>
/// <param name="opname">The base operator name</param>
/// <param name="k">The primal kind over which the identifier is deined</param>
[Op]
public static OpIdentity build(string opname, NumericKind k, bool generic)
=> build(opname, NativeTypeWidth.None, k, generic);
[Op]
public static OpIdentity build(ApiClassKind k, NumericKind nk, bool generic)
=> build(k.Format(), nk, generic);
/// <summary>
/// Defines an identifier of the form {opname}_WxN{u | i | f} where N := bitsize[T]
/// </summary>
/// <param name="opname">The base operator name</param>
/// <param name="w">The covering bit width representative</param>
/// <param name="t">A primal cell type representative</param>
/// <typeparam name="W">The bit width type</typeparam>
/// <typeparam name="T">The cell type</typeparam>
[MethodImpl(Inline)]
public static OpIdentity build<W,T>(string opname, W w = default, T t = default)
where W : unmanaged, ITypeWidth
where T : unmanaged
=> build(opname, w.TypeWidth, NumericKinds.kind<T>(), true);
}
} | 47.615385 | 141 | 0.576019 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/apicore/src/services/ApiIdentityBuilder.cs | 5,571 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Xml;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Microsoft.Build.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// Contains a list of the special (reserved) properties that are settable by MSBuild code only.
/// </summary>
/// <owner>RGoel</owner>
internal static class ReservedPropertyNames
{
internal const string projectDirectory = "MSBuildProjectDirectory";
internal const string projectDirectoryNoRoot = "MSBuildProjectDirectoryNoRoot";
internal const string projectFile = "MSBuildProjectFile";
internal const string projectExtension = "MSBuildProjectExtension";
internal const string projectFullPath = "MSBuildProjectFullPath";
internal const string projectName = "MSBuildProjectName";
internal const string binPath = "MSBuildBinPath";
internal const string projectDefaultTargets = "MSBuildProjectDefaultTargets";
internal const string extensionsPath = "MSBuildExtensionsPath";
internal const string extensionsPath32 = "MSBuildExtensionsPath32";
internal const string toolsPath = "MSBuildToolsPath";
internal const string toolsVersion = "MSBuildToolsVersion";
internal const string startupDirectory = "MSBuildStartupDirectory";
internal const string buildNodeCount = "MSBuildNodeCount";
internal const string extensionsPathSuffix = "MSBuild";
internal const string programFiles32 = "MSBuildProgramFiles32";
internal const string assemblyVersion = "MSBuildAssemblyVersion";
/// <summary>
/// Indicates if the given property is a reserved property.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="property"></param>
/// <returns>true, if specified property is reserved</returns>
internal static bool IsReservedProperty(string property)
{
return
(String.Equals(property, projectDirectory, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, projectFile, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, projectExtension, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, projectFullPath, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, projectName, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, binPath, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, toolsPath, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, projectDefaultTargets, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, programFiles32, StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(property, assemblyVersion, StringComparison.OrdinalIgnoreCase))
// Intentionally do not include MSBuildExtensionsPath or MSBuildExtensionsPath32 in this list. We need tasks to be able to override those.
;
}
}
/// <summary>
/// Constants used by the Engine
/// </summary>
internal static class Constants
{
/// <summary>
/// If no default tools version is specified in the config file or registry, we'll use 2.0.
/// The engine will use its binpath for the matching toolset path.
/// </summary>
internal const string defaultToolsVersion = "2.0";
/// <summary>
/// The toolsversion we will fall back to as a last resort if the default one cannot be found, this fallback should be the most current toolsversion known
/// </summary>
internal const string defaultFallbackToolsVersion = "4.0";
internal const string defaultSolutionWrapperProjectToolsVersion = "4.0";
/// <summary>
/// Current version of this MSBuild Engine assembly in the
/// form, e.g, "4.0"
/// </summary>
internal static string AssemblyVersion
{
get
{
return MSBuildConstants.CurrentToolsVersion;
}
}
internal const string defaultTargetCacheName = "##DefaultTargets##";
internal const string initialTargetCacheName = "##InitialTargets##";
internal const string projectIdCacheName = "##ProjectId##";
// Name of the environment variable that always points to 32-bit program files.
internal const string programFilesx86 = "ProgramFiles(x86)";
}
/// <summary>
/// Function related constants.
/// </summary>
/// <remarks>
/// Placed here to avoid StyleCop error.
/// </remarks>
internal static class FunctionConstants
{
/// <summary>
/// Static methods that are allowed in constants. Key = Type or Type::Method, Value = AssemblyQualifiedTypeName (where null = mscorlib)
/// </summary>
private static ConcurrentDictionary<string, Tuple<string, Type>> availableStaticMethods;
/// <summary>
/// The set of available static methods.
/// NOTE: Do not allow methods here that could do "bad" things under any circumstances.
/// These must be completely benign operations, as they run during project load, which must be safe in VS.
/// Key = Type or Type::Method, Value = AssemblyQualifiedTypeName (where null = mscorlib)
/// </summary>
internal static IDictionary<string, Tuple<string, Type>> AvailableStaticMethods
{
get
{
// Initialize lazily, as many projects might not
// even use functions
if (availableStaticMethods == null)
{
// Initialization is thread-safe
InitializeAvailableMethods();
}
return availableStaticMethods;
}
}
/// <summary>
/// Re-initialize.
/// Unit tests need this when they enable "unsafe" methods -- which will then go in the collection,
/// and mess up subsequent tests.
/// </summary>
internal static void Reset_ForUnitTestsOnly()
{
InitializeAvailableMethods();
}
/// <summary>
/// Fill up the dictionary for first use
/// </summary>
private static void InitializeAvailableMethods()
{
availableStaticMethods = new ConcurrentDictionary<string, Tuple<string, Type>>(StringComparer.OrdinalIgnoreCase);
// Pre declare our common type Tuples
Tuple<string, Type> environmentType = new Tuple<string, Type>(null, typeof(System.Environment));
Tuple<string, Type> directoryType = new Tuple<string, Type>(null, typeof(System.IO.Directory));
Tuple<string, Type> fileType = new Tuple<string, Type>(null, typeof(System.IO.File));
// Make specific static methods available (Assembly qualified type names are *NOT* supported, only null which means mscorlib):
availableStaticMethods.TryAdd("System.Environment::CommandLine", environmentType);
availableStaticMethods.TryAdd("System.Environment::ExpandEnvironmentVariables", environmentType);
availableStaticMethods.TryAdd("System.Environment::GetEnvironmentVariable", environmentType);
availableStaticMethods.TryAdd("System.Environment::GetEnvironmentVariables", environmentType);
availableStaticMethods.TryAdd("System.Environment::GetFolderPath", environmentType);
availableStaticMethods.TryAdd("System.Environment::GetLogicalDrives", environmentType);
availableStaticMethods.TryAdd("System.Environment::Is64BitOperatingSystem", environmentType);
availableStaticMethods.TryAdd("System.Environment::Is64BitProcess", environmentType);
availableStaticMethods.TryAdd("System.Environment::MachineName", environmentType);
availableStaticMethods.TryAdd("System.Environment::OSVersion", environmentType);
availableStaticMethods.TryAdd("System.Environment::ProcessorCount", environmentType);
availableStaticMethods.TryAdd("System.Environment::StackTrace", environmentType);
availableStaticMethods.TryAdd("System.Environment::SystemDirectory", environmentType);
availableStaticMethods.TryAdd("System.Environment::SystemPageSize", environmentType);
availableStaticMethods.TryAdd("System.Environment::TickCount", environmentType);
availableStaticMethods.TryAdd("System.Environment::UserDomainName", environmentType);
availableStaticMethods.TryAdd("System.Environment::UserInteractive", environmentType);
availableStaticMethods.TryAdd("System.Environment::UserName", environmentType);
availableStaticMethods.TryAdd("System.Environment::Version", environmentType);
availableStaticMethods.TryAdd("System.Environment::WorkingSet", environmentType);
availableStaticMethods.TryAdd("System.IO.Directory::GetDirectories", directoryType);
availableStaticMethods.TryAdd("System.IO.Directory::GetFiles", directoryType);
availableStaticMethods.TryAdd("System.IO.Directory::GetLastAccessTime", directoryType);
availableStaticMethods.TryAdd("System.IO.Directory::GetLastWriteTime", directoryType);
availableStaticMethods.TryAdd("System.IO.Directory::GetParent", directoryType);
availableStaticMethods.TryAdd("System.IO.File::Exists", fileType);
availableStaticMethods.TryAdd("System.IO.File::GetCreationTime", fileType);
availableStaticMethods.TryAdd("System.IO.File::GetAttributes", fileType);
availableStaticMethods.TryAdd("System.IO.File::GetLastAccessTime", fileType);
availableStaticMethods.TryAdd("System.IO.File::GetLastWriteTime", fileType);
availableStaticMethods.TryAdd("System.IO.File::ReadAllText", fileType);
availableStaticMethods.TryAdd("System.Globalization.CultureInfo::GetCultureInfo", new Tuple<string, Type>(null, typeof(System.Globalization.CultureInfo))); // user request
availableStaticMethods.TryAdd("System.Globalization.CultureInfo::CurrentUICulture", new Tuple<string, Type>(null, typeof(System.Globalization.CultureInfo))); // user request
// All static methods of the following are available (Assembly qualified type names are supported):
availableStaticMethods.TryAdd("MSBuild", new Tuple<string, Type>(null, typeof(Microsoft.Build.BuildEngine.IntrinsicFunctions)));
availableStaticMethods.TryAdd("System.Byte", new Tuple<string, Type>(null, typeof(System.Byte)));
availableStaticMethods.TryAdd("System.Char", new Tuple<string, Type>(null, typeof(System.Char)));
availableStaticMethods.TryAdd("System.Convert", new Tuple<string, Type>(null, typeof(System.Convert)));
availableStaticMethods.TryAdd("System.DateTime", new Tuple<string, Type>(null, typeof(System.DateTime)));
availableStaticMethods.TryAdd("System.Decimal", new Tuple<string, Type>(null, typeof(System.Decimal)));
availableStaticMethods.TryAdd("System.Double", new Tuple<string, Type>(null, typeof(System.Double)));
availableStaticMethods.TryAdd("System.Enum", new Tuple<string, Type>(null, typeof(System.Enum)));
availableStaticMethods.TryAdd("System.Guid", new Tuple<string, Type>(null, typeof(System.Guid)));
availableStaticMethods.TryAdd("System.Int16", new Tuple<string, Type>(null, typeof(System.Int16)));
availableStaticMethods.TryAdd("System.Int32", new Tuple<string, Type>(null, typeof(System.Int32)));
availableStaticMethods.TryAdd("System.Int64", new Tuple<string, Type>(null, typeof(System.Int64)));
availableStaticMethods.TryAdd("System.IO.Path", new Tuple<string, Type>(null, typeof(System.IO.Path)));
availableStaticMethods.TryAdd("System.Math", new Tuple<string, Type>(null, typeof(System.Math)));
availableStaticMethods.TryAdd("System.UInt16", new Tuple<string, Type>(null, typeof(System.UInt16)));
availableStaticMethods.TryAdd("System.UInt32", new Tuple<string, Type>(null, typeof(System.UInt32)));
availableStaticMethods.TryAdd("System.UInt64", new Tuple<string, Type>(null, typeof(System.UInt64)));
availableStaticMethods.TryAdd("System.SByte", new Tuple<string, Type>(null, typeof(System.SByte)));
availableStaticMethods.TryAdd("System.Single", new Tuple<string, Type>(null, typeof(System.Single)));
availableStaticMethods.TryAdd("System.String", new Tuple<string, Type>(null, typeof(System.String)));
availableStaticMethods.TryAdd("System.StringComparer", new Tuple<string, Type>(null, typeof(System.StringComparer)));
availableStaticMethods.TryAdd("System.TimeSpan", new Tuple<string, Type>(null, typeof(System.TimeSpan)));
availableStaticMethods.TryAdd("System.Text.RegularExpressions.Regex", new Tuple<string, Type>(null, typeof(System.Text.RegularExpressions.Regex)));
availableStaticMethods.TryAdd("System.UriBuilder", new Tuple<string, Type>(null, typeof(System.UriBuilder)));
availableStaticMethods.TryAdd("System.Version", new Tuple<string, Type>(null, typeof(System.Version)));
availableStaticMethods.TryAdd("Microsoft.Build.Utilities.ToolLocationHelper", new Tuple<string, Type>("Microsoft.Build.Utilities.ToolLocationHelper, Microsoft.Build.Utilities.Core, Version=" + MSBuildConstants.CurrentAssemblyVersion + ", Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", null));
}
}
}
| 62.867257 | 308 | 0.679969 | [
"MIT"
] | Youssef1313/msbuild | src/Deprecated/Engine/Resources/Constants.cs | 14,208 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Compute.Models;
namespace Azure.ResourceManager.Compute
{
/// <summary> The Usage service client. </summary>
public partial class UsageOperations
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal UsageRestOperations RestClient { get; }
/// <summary> Initializes a new instance of UsageOperations for mocking. </summary>
protected UsageOperations()
{
}
/// <summary> Initializes a new instance of UsageOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="endpoint"> server parameter. </param>
internal UsageOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
RestClient = new UsageRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Gets, for the specified location, the current compute resource usage information as well as the limits for compute resources under the subscription. </summary>
/// <param name="location"> The location for which resource usage is queried. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="location"/> is null. </exception>
public virtual AsyncPageable<Usage> ListAsync(string location, CancellationToken cancellationToken = default)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
async Task<Page<Usage>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("UsageOperations.List");
scope.Start();
try
{
var response = await RestClient.ListAsync(location, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<Usage>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("UsageOperations.List");
scope.Start();
try
{
var response = await RestClient.ListNextPageAsync(nextLink, location, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Gets, for the specified location, the current compute resource usage information as well as the limits for compute resources under the subscription. </summary>
/// <param name="location"> The location for which resource usage is queried. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="location"/> is null. </exception>
public virtual Pageable<Usage> List(string location, CancellationToken cancellationToken = default)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
Page<Usage> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("UsageOperations.List");
scope.Start();
try
{
var response = RestClient.List(location, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<Usage> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("UsageOperations.List");
scope.Start();
try
{
var response = RestClient.ListNextPage(nextLink, location, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
}
}
| 45.44186 | 195 | 0.598089 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/UsageOperations.cs | 5,862 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Reflection.Emit;
using csfe.compilation;
using Microsoft.SqlServer.Server;
using NUnit.Framework;
namespace csfe.tests
{
[TestFixture]
public class test_compiler
{
[SetUp]
public void Setup() {
Environment.CurrentDirectory = TestContext.CurrentContext.TestDirectory;
var ioDirs = Directory.GetDirectories(".", "*", SearchOption.AllDirectories);
foreach (var d in ioDirs)
{
if (d.EndsWith("output") || d.EndsWith("input") || d.EndsWith("tmp"))
Directory.Delete(d, true);
}
}
const string SOURCE_FILENAME = "flowsource.txt";
[Test]
public void Compile() {
File.WriteAllText(SOURCE_FILENAME, "toupper");
var services = new Dictionary<string, ServiceInfo>{
{
"toupper",
new ServiceInfo{Path = "testflow1/service2", Executable="mono", Arguments="TestServiceToUpper.exe"}
}
};
var flow = Compiler.Compile(SOURCE_FILENAME, "testflow1", services, out string _);
// Run
flow.ProcessText("hello");
var results = flow.Output;
Assert.AreEqual(1, results.Length);
Assert.AreEqual("HELLO", File.ReadAllText(results[0]));
}
[Test]
public void Compile_with_error() {
File.WriteAllText(SOURCE_FILENAME, "XYZ");
var services = new Dictionary<string, ServiceInfo>{
{
"toupper",
new ServiceInfo{Path = "testflow1/service2", Executable="mono", Arguments="TestServiceToUpper.exe"}
}
};
var flow = Compiler.Compile(SOURCE_FILENAME, "testflow1", services, out string errors);
Assert.IsNull(flow);
Debug.Print(errors);
Assert.IsTrue(errors.IndexOf("XYZ") > 0);
}
}
} | 31.084507 | 119 | 0.537381 | [
"Apache-2.0"
] | ralfw/csfe | src/csfe.tests/test_Compiler.cs | 2,209 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CertificateManager.Entities
{
class JavascriptConfigurationHelper
{
}
}
| 16.307692 | 39 | 0.773585 | [
"MIT"
] | corymurphy/CertificateManager | CertificateManager.Entities/JavascriptConfigurationHelper.cs | 214 | C# |
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace EasyLOB.Library.WebApi
{
public class OperationResultResponseException : HttpResponseException
{
#region Methods
public OperationResultResponseException(HttpRequestMessage request, ZOperationResult operationResult)
: base(request.CreateResponse<ZOperationResult>(HttpStatusCode.BadRequest, operationResult))
{
}
#endregion Methods
}
} | 27.388889 | 110 | 0.701826 | [
"MIT"
] | EasyLOB/EasyLOB-1 | EasyLOB.Library/EasyLOB.Library.WebApi/OperationResultResponseException.cs | 495 | C# |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudioTools.Project {
internal enum tagDVASPECT {
DVASPECT_CONTENT = 1,
DVASPECT_THUMBNAIL = 2,
DVASPECT_ICON = 4,
DVASPECT_DOCPRINT = 8
}
internal enum tagTYMED {
TYMED_HGLOBAL = 1,
TYMED_FILE = 2,
TYMED_ISTREAM = 4,
TYMED_ISTORAGE = 8,
TYMED_GDI = 16,
TYMED_MFPICT = 32,
TYMED_ENHMF = 64,
TYMED_NULL = 0
}
internal sealed class DataCacheEntry : IDisposable {
#region fields
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
private FORMATETC format;
private long data;
private DATADIR dataDir;
private bool isDisposed;
#endregion
#region properties
internal FORMATETC Format {
get {
return this.format;
}
}
internal long Data {
get {
return this.data;
}
}
internal DATADIR DataDir {
get {
return this.dataDir;
}
}
#endregion
/// <summary>
/// The IntPtr is data allocated that should be removed. It is allocated by the ProcessSelectionData method.
/// </summary>
internal DataCacheEntry(FORMATETC fmt, IntPtr data, DATADIR dir) {
this.format = fmt;
this.data = (long)data;
this.dataDir = dir;
}
#region Dispose
~DataCacheEntry() {
Dispose(false);
}
/// <summary>
/// The IDispose interface Dispose method for disposing the object determinastically.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing) {
// Everybody can go here.
if (!this.isDisposed) {
// Synchronize calls to the Dispose simulteniously.
lock (Mutex) {
if (disposing && this.data != 0) {
Marshal.FreeHGlobal((IntPtr)this.data);
this.data = 0;
}
this.isDisposed = true;
}
}
}
#endregion
}
/// <summary>
/// Unfortunately System.Windows.Forms.IDataObject and
/// Microsoft.VisualStudio.OLE.Interop.IDataObject are different...
/// </summary>
internal sealed class DataObject : IDataObject {
#region fields
internal const int DATA_S_SAMEFORMATETC = 0x00040130;
EventSinkCollection map;
ArrayList entries;
#endregion
internal DataObject() {
this.map = new EventSinkCollection();
this.entries = new ArrayList();
}
internal void SetData(FORMATETC format, IntPtr data) {
this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET));
}
#region IDataObject methods
int IDataObject.DAdvise(FORMATETC[] e, uint adv, IAdviseSink sink, out uint cookie) {
Utilities.ArgumentNotNull("e", e);
STATDATA sdata = new STATDATA();
sdata.ADVF = adv;
sdata.FORMATETC = e[0];
sdata.pAdvSink = sink;
cookie = this.map.Add(sdata);
sdata.dwConnection = cookie;
return 0;
}
void IDataObject.DUnadvise(uint cookie) {
this.map.RemoveAt(cookie);
}
int IDataObject.EnumDAdvise(out IEnumSTATDATA e) {
e = new EnumSTATDATA((IEnumerable)this.map);
return 0; //??
}
int IDataObject.EnumFormatEtc(uint direction, out IEnumFORMATETC penum) {
penum = new EnumFORMATETC((DATADIR)direction, (IEnumerable)this.entries);
return 0;
}
int IDataObject.GetCanonicalFormatEtc(FORMATETC[] format, FORMATETC[] fmt) {
throw new System.Runtime.InteropServices.COMException("", DATA_S_SAMEFORMATETC);
}
void IDataObject.GetData(FORMATETC[] fmt, STGMEDIUM[] m) {
STGMEDIUM retMedium = new STGMEDIUM();
if (fmt == null || fmt.Length < 1)
return;
foreach (DataCacheEntry e in this.entries) {
if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/) {
retMedium.tymed = e.Format.tymed;
// Caller must delete the memory.
retMedium.unionmember = DragDropHelper.CopyHGlobal(new IntPtr(e.Data));
break;
}
}
if (m != null && m.Length > 0)
m[0] = retMedium;
}
void IDataObject.GetDataHere(FORMATETC[] fmt, STGMEDIUM[] m) {
}
int IDataObject.QueryGetData(FORMATETC[] fmt) {
if (fmt == null || fmt.Length < 1)
return VSConstants.S_FALSE;
foreach (DataCacheEntry e in this.entries) {
if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/)
return VSConstants.S_OK;
}
return VSConstants.S_FALSE;
}
void IDataObject.SetData(FORMATETC[] fmt, STGMEDIUM[] m, int fRelease) {
}
#endregion
}
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
internal static class DragDropHelper {
#pragma warning disable 414
internal static readonly ushort CF_VSREFPROJECTITEMS;
internal static readonly ushort CF_VSSTGPROJECTITEMS;
internal static readonly ushort CF_VSPROJECTCLIPDESCRIPTOR;
#pragma warning restore 414
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static DragDropHelper() {
CF_VSREFPROJECTITEMS = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_VSREFPROJECTITEMS");
CF_VSSTGPROJECTITEMS = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_VSSTGPROJECTITEMS");
CF_VSPROJECTCLIPDESCRIPTOR = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_PROJECTCLIPBOARDDESCRIPTOR");
}
public static FORMATETC CreateFormatEtc(ushort iFormat) {
FORMATETC fmt = new FORMATETC();
fmt.cfFormat = iFormat;
fmt.ptd = IntPtr.Zero;
fmt.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT;
fmt.lindex = -1;
fmt.tymed = (uint)TYMED.TYMED_HGLOBAL;
return fmt;
}
public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) {
FORMATETC[] af = new FORMATETC[1];
af[0] = fmtetc;
int result = pDataObject.QueryGetData(af);
if (result == VSConstants.S_OK) {
fmtetc = af[0];
return VSConstants.S_OK;
}
return result;
}
public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) {
FORMATETC[] af = new FORMATETC[1];
af[0] = fmtetc;
STGMEDIUM[] sm = new STGMEDIUM[1];
pDataObject.GetData(af, sm);
fmtetc = af[0];
return sm[0];
}
/// <summary>
/// Retrieves data from a VS format.
/// </summary>
public static List<string> GetDroppedFiles(ushort format, Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject, out DropDataType ddt) {
ddt = DropDataType.None;
List<string> droppedFiles = new List<string>();
// try HDROP
FORMATETC fmtetc = CreateFormatEtc(format);
if (QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) {
STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc);
if (stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) {
// We are releasing the cloned hglobal here.
IntPtr dropInfoHandle = stgmedium.unionmember;
if (dropInfoHandle != IntPtr.Zero) {
ddt = DropDataType.Shell;
try {
uint numFiles = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, 0xFFFFFFFF, null, 0);
// We are a directory based project thus a projref string is placed on the clipboard.
// We assign the maximum length of a projref string.
// The format of a projref is : <Proj Guid>|<project rel path>|<file path>
uint lenght = (uint)Guid.Empty.ToString().Length + 2 * NativeMethods.MAX_PATH + 2;
char[] moniker = new char[lenght + 1];
for (uint fileIndex = 0; fileIndex < numFiles; fileIndex++) {
uint queryFileLength = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, fileIndex, moniker, lenght);
string filename = new String(moniker, 0, (int)queryFileLength);
droppedFiles.Add(filename);
}
} finally {
Marshal.FreeHGlobal(dropInfoHandle);
}
}
}
}
return droppedFiles;
}
public static string GetSourceProjectPath(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject) {
string projectPath = null;
FORMATETC fmtetc = CreateFormatEtc(CF_VSPROJECTCLIPDESCRIPTOR);
if (QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) {
STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc);
if (stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) {
// We are releasing the cloned hglobal here.
IntPtr dropInfoHandle = stgmedium.unionmember;
if (dropInfoHandle != IntPtr.Zero) {
try {
string path = GetData(dropInfoHandle);
// Clone the path that we can release our memory.
if (!String.IsNullOrEmpty(path)) {
projectPath = String.Copy(path);
}
} finally {
Marshal.FreeHGlobal(dropInfoHandle);
}
}
}
}
return projectPath;
}
/// <summary>
/// Returns the data packed after the DROPFILES structure.
/// </summary>
/// <param name="dropHandle"></param>
/// <returns></returns>
internal static string GetData(IntPtr dropHandle) {
IntPtr data = UnsafeNativeMethods.GlobalLock(dropHandle);
try {
_DROPFILES df = (_DROPFILES)Marshal.PtrToStructure(data, typeof(_DROPFILES));
if (df.fWide != 0) {
IntPtr pdata = new IntPtr((long)data + df.pFiles);
return Marshal.PtrToStringUni(pdata);
}
} finally {
if (data != IntPtr.Zero) {
UnsafeNativeMethods.GlobalUnLock(data);
}
}
return null;
}
internal static IntPtr CopyHGlobal(IntPtr data) {
IntPtr src = UnsafeNativeMethods.GlobalLock(data);
var size = UnsafeNativeMethods.GlobalSize(data).ToInt32();
IntPtr ptr = Marshal.AllocHGlobal(size);
IntPtr buffer = UnsafeNativeMethods.GlobalLock(ptr);
try {
for (int i = 0; i < size; i++) {
byte val = Marshal.ReadByte(new IntPtr((long)src + i));
Marshal.WriteByte(new IntPtr((long)buffer + i), val);
}
} finally {
if (buffer != IntPtr.Zero) {
UnsafeNativeMethods.GlobalUnLock(buffer);
}
if (src != IntPtr.Zero) {
UnsafeNativeMethods.GlobalUnLock(src);
}
}
return ptr;
}
internal static void CopyStringToHGlobal(string s, IntPtr data, int bufferSize) {
Int16 nullTerminator = 0;
int dwSize = Marshal.SizeOf(nullTerminator);
if ((s.Length + 1) * Marshal.SizeOf(s[0]) > bufferSize)
throw new System.IO.InternalBufferOverflowException();
// IntPtr memory already locked...
for (int i = 0, len = s.Length; i < len; i++) {
Marshal.WriteInt16(data, i * dwSize, s[i]);
}
// NULL terminate it
Marshal.WriteInt16(new IntPtr((long)data + (s.Length * dwSize)), nullTerminator);
}
} // end of dragdrophelper
internal class EnumSTATDATA : IEnumSTATDATA {
IEnumerable i;
IEnumerator e;
public EnumSTATDATA(IEnumerable i) {
this.i = i;
this.e = i.GetEnumerator();
}
void IEnumSTATDATA.Clone(out IEnumSTATDATA clone) {
clone = new EnumSTATDATA(i);
}
int IEnumSTATDATA.Next(uint celt, STATDATA[] d, out uint fetched) {
uint rc = 0;
//uint size = (fetched != null) ? fetched[0] : 0;
for (uint i = 0; i < celt; i++) {
if (e.MoveNext()) {
STATDATA sdata = (STATDATA)e.Current;
rc++;
if (d != null && d.Length > i) {
d[i] = sdata;
}
}
}
fetched = rc;
return 0;
}
int IEnumSTATDATA.Reset() {
e.Reset();
return 0;
}
int IEnumSTATDATA.Skip(uint celt) {
for (uint i = 0; i < celt; i++) {
e.MoveNext();
}
return 0;
}
}
internal class EnumFORMATETC : IEnumFORMATETC {
IEnumerable cache; // of DataCacheEntrys.
DATADIR dir;
IEnumerator e;
public EnumFORMATETC(DATADIR dir, IEnumerable cache) {
this.cache = cache;
this.dir = dir;
e = cache.GetEnumerator();
}
void IEnumFORMATETC.Clone(out IEnumFORMATETC clone) {
clone = new EnumFORMATETC(dir, cache);
}
int IEnumFORMATETC.Next(uint celt, FORMATETC[] d, uint[] fetched) {
uint rc = 0;
//uint size = (fetched != null) ? fetched[0] : 0;
for (uint i = 0; i < celt; i++) {
if (e.MoveNext()) {
DataCacheEntry entry = (DataCacheEntry)e.Current;
rc++;
if (d != null && d.Length > i) {
d[i] = entry.Format;
}
} else {
return VSConstants.S_FALSE;
}
}
if (fetched != null && fetched.Length > 0)
fetched[0] = rc;
return VSConstants.S_OK;
}
int IEnumFORMATETC.Reset() {
e.Reset();
return 0;
}
int IEnumFORMATETC.Skip(uint celt) {
for (uint i = 0; i < celt; i++) {
e.MoveNext();
}
return 0;
}
}
}
| 34.691057 | 148 | 0.538493 | [
"Apache-2.0"
] | Bhaskers-Blu-Org2/PTVS | Common/Product/SharedProject/DataObject.cs | 17,068 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ActivitiesExample
{
delegate void ActivityScopeHandler(ref ActivityScope activityScope);
public class ActivitySource : IDisposable
{
ActivitySourceRegistry _registry;
volatile IActivityListener[] _listeners;
public ActivitySource(string name) : this(name, ActivitySourceRegistry.DefaultRegistry) { }
public ActivitySource(string name, ActivitySourceRegistry registry)
{
Name = name;
_registry = registry;
_registry?.Add(this);
}
public string Name { get; }
public void Dispose()
{
_registry?.Remove(this);
_registry = null;
_listeners = null;
}
public void AddListener(IActivityListener listener)
{
lock(this)
{
if(_registry == null)
{
return; //already disposed
}
List<IActivityListener> newListeners = new List<IActivityListener>();
if(_listeners != null)
{
newListeners.AddRange(_listeners);
}
newListeners.Add(listener);
_listeners = newListeners.ToArray();
}
}
public void RemoveListener(IActivityListener listener)
{
lock (this)
{
if (_registry == null)
{
return; //already disposed
}
List<IActivityListener> newListeners = new List<IActivityListener>();
if (_listeners != null)
{
newListeners.AddRange(_listeners);
}
newListeners.Remove(listener);
_listeners = newListeners.ToArray();
}
}
internal void OnScopeStarted(ref ActivityScope activityScope)
{
// This array is immutable once assigned to _listeners
// TODO: If this is in a final implementation we'd want
// to confirm .NET gives us the memory model guarantees to
// do this without a lock or an explicit read barrier, but
// I this it does.
IActivityListener[] listeners = _listeners;
if (listeners == null)
return;
for(int i = 0; i < listeners.Length; i++)
{
listeners[i].ActivityScopeStarted(this, ref activityScope);
}
}
internal void OnScopeStopped(ref ActivityScope activityScope)
{
// This array is immutable once assigned to _listeners
// TODO: If this is in a final implementation we'd want
// to confirm .NET gives us the memory model guarantees to
// do this without a lock or an explicit read barrier, but
// I this it does.
IActivityListener[] listeners = _listeners;
if (listeners == null)
return;
for (int i = 0; i < listeners.Length; i++)
{
listeners[i].ActivityScopeStopped(this, ref activityScope);
}
}
}
}
| 32.86 | 99 | 0.530128 | [
"MIT"
] | noahfalk/ActivitiesExperiment | ActivitiesExample/BCL/ActivitySource.cs | 3,288 | C# |
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using EventStore.ClientAPI.Common.Utils;
using EventStore.ClientAPI.Exceptions;
using EventStore.ClientAPI.SystemData;
using EventStore.Core.Authentication;
using EventStore.Core.Bus;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
namespace EventStore.ClientAPI.Embedded
{
internal class EmbeddedSubscription : EmbeddedSubscriptionBase<EventStoreSubscription>
{
private readonly UserCredentials _userCredentials;
private readonly IAuthenticationProvider _authenticationProvider;
private readonly bool _resolveLinkTos;
public EmbeddedSubscription(
ILogger log, IPublisher publisher, Guid connectionId, TaskCompletionSource<EventStoreSubscription> source,
string streamId, UserCredentials userCredentials, IAuthenticationProvider authenticationProvider,
bool resolveLinkTos, Action<EventStoreSubscription, ResolvedEvent> eventAppeared,
Action<EventStoreSubscription, SubscriptionDropReason, Exception> subscriptionDropped)
: base(log, publisher, connectionId, source, streamId, eventAppeared, subscriptionDropped)
{
_userCredentials = userCredentials;
_authenticationProvider = authenticationProvider;
_resolveLinkTos = resolveLinkTos;
}
override protected EventStoreSubscription CreateVolatileSubscription(long lastCommitPosition, long? lastEventNumber)
{
return new EmbeddedVolatileEventStoreSubscription(Unsubscribe, StreamId, lastCommitPosition, lastEventNumber);
}
public override void Start(Guid correlationId)
{
CorrelationId = correlationId;
Publisher.PublishWithAuthentication(_authenticationProvider, _userCredentials,
ex => DropSubscription(EventStore.Core.Services.SubscriptionDropReason.AccessDenied, ex),
user => new ClientMessage.SubscribeToStream(
correlationId,
correlationId,
new PublishEnvelope(Publisher, true),
ConnectionId,
StreamId,
_resolveLinkTos,
user));
}
}
}
| 41.553571 | 124 | 0.707778 | [
"Apache-2.0"
] | shaan1337/EventStore | src/EventStore.ClientAPI.Embedded/EmbeddedSubscription.cs | 2,327 | C# |
using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.QuickFixes;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Tests.Unity.CSharp.Intentions.QuickFixes
{
[TestUnity]
public class ConvertCoalescingToConditionalQuickFixAvailabilityTest : QuickFixAvailabilityTestBase
{
protected override string RelativeTestDataPath => @"CSharp\Intentions\QuickFixes\ConvertCoalescingToConditional\Availability";
[Test] public void Test01() { DoNamedTest(); }
[Test] public void Test02() { DoNamedTest(); }
[Test] public void Test03() { DoNamedTest(); }
[Test] public void Test04() { DoNamedTest(); }
[Test] public void Test05() { DoNamedTest(); }
}
[TestUnity]
public class ConvertCoalescingToConditionalQuickFixTests : QuickFixTestBase<ConvertCoalescingToConditionalQuickFix>
{
protected override string RelativeTestDataPath => @"CSharp\Intentions\QuickFixes\ConvertCoalescingToConditional";
protected override bool AllowHighlightingOverlap => true;
[Test] public void Test01() { DoNamedTest(); }
[Test] public void Test02() { DoNamedTest(); }
[Test] public void Test03() { DoNamedTest(); }
[Test] public void Test04() { DoNamedTest(); }
[Test, ExecuteScopedQuickFixInFile] public void Test05() { DoNamedTest(); }
}
}
| 44.625 | 134 | 0.717087 | [
"Apache-2.0"
] | SirDuke/resharper-unity | resharper/resharper-unity/test/src/Unity.Tests/Unity/CSharp/Intentions/QuickFixes/ConvertCoalescingToConditionalQuickFixTests.cs | 1,430 | C# |
using System;
using Newtonsoft.Json;
using Shiny.Infrastructure;
namespace Shiny.Integrations.JsonNet
{
public class JsonNetSerializer : ISerializer
{
public T Deserialize<T>(string value) => JsonConvert.DeserializeObject<T>(value);
public object Deserialize(Type objectType, string value) => JsonConvert.DeserializeObject(value, objectType);
public string Serialize(object value) => JsonConvert.SerializeObject(value);
}
}
| 30.866667 | 117 | 0.742981 | [
"MIT"
] | AlexAba/shiny | src/Shiny.Integrations.JsonNet/JsonNetSerializer.cs | 465 | C# |
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PpCalculator
{
public abstract class PpCalculator
{
public WorkingBeatmap WorkingBeatmap { get; private set; }
public IBeatmap PlayableBeatmap { get; private set; }
public abstract Ruleset Ruleset { get; }
public virtual double Accuracy { get; set; } = 100;
public virtual int? Combo { get; set; }
public virtual double PercentCombo { get; set; } = 100;
public virtual int Score { get; set; }
private string[] _Mods { get; set; }
public virtual string[] Mods
{
get => _Mods;
set => _Mods = value;
}
public virtual int Misses { get; set; }
public virtual int? Mehs { get; set; }
public virtual int? Goods { get; set; }
protected virtual ScoreInfo ScoreInfo { get; set; } = new ScoreInfo();
protected virtual PerformanceCalculator PerformanceCalculator { get; set; }
public int? RulesetId => Ruleset.LegacyID;
public void PreProcess(ProcessorWorkingBeatmap workingBeatmap)
{
WorkingBeatmap = workingBeatmap;
ResetPerformanceCalculator = true;
}
public void PreProcess(string file) => PreProcess(new ProcessorWorkingBeatmap(file));
protected string LastMods { get; set; } = null;
protected bool ResetPerformanceCalculator { get; set; }
public double Calculate(double startTime, double endTime = double.NaN, Dictionary<string, double> categoryAttribs = null)
{
var orginalWorkingBeatmap = WorkingBeatmap;
var tempMap = new Beatmap();
tempMap.HitObjects.AddRange(WorkingBeatmap.Beatmap.HitObjects.Where(h => h.StartTime >= startTime && h.StartTime <= endTime));
if (tempMap.HitObjects.Count <= 1)
return -1;
tempMap.ControlPointInfo = WorkingBeatmap.Beatmap.ControlPointInfo;
tempMap.BeatmapInfo = WorkingBeatmap.BeatmapInfo;
WorkingBeatmap = new ProcessorWorkingBeatmap(tempMap);
ResetPerformanceCalculator = true;
var result = Calculate(null, categoryAttribs);
WorkingBeatmap = orginalWorkingBeatmap;
ResetPerformanceCalculator = true;
return result;
}
public double Calculate(double? time = null, Dictionary<string, double> categoryAttribs = null)
{
if (WorkingBeatmap == null)
return -1d;
//huge performance gains by reusing existing performance calculator when possible
var createPerformanceCalculator = PerformanceCalculator == null || ResetPerformanceCalculator;
var ruleset = Ruleset;
Mod[] mods = null;
var newMods = _Mods != null ? string.Concat(_Mods) : "";
if (LastMods != newMods || ResetPerformanceCalculator)
{
mods = getMods(ruleset).ToArray();
LastMods = newMods;
PlayableBeatmap = WorkingBeatmap.GetPlayableBeatmap(ruleset.RulesetInfo, mods);
ScoreInfo.Mods = mods;
createPerformanceCalculator = true;
}
IReadOnlyList<HitObject> hitObjects = time.HasValue
? PlayableBeatmap.HitObjects.Where(h => h.StartTime <= time).ToList()
: PlayableBeatmap.HitObjects;
int beatmapMaxCombo = GetMaxCombo(hitObjects);
var maxCombo = Combo ?? (int)Math.Round(PercentCombo / 100 * beatmapMaxCombo);
var statistics = GenerateHitResults(Accuracy / 100, hitObjects, Misses, Mehs, Goods);
var score = Score;
var accuracy = GetAccuracy(statistics);
ScoreInfo.Accuracy = accuracy;
ScoreInfo.MaxCombo = maxCombo;
ScoreInfo.Statistics = statistics;
ScoreInfo.TotalScore = score;
if (createPerformanceCalculator)
{
PerformanceCalculator = ruleset.CreatePerformanceCalculator(WorkingBeatmap, ScoreInfo);
ResetPerformanceCalculator = false;
}
double pp;
if (time.HasValue)
pp = PerformanceCalculator.Calculate(time.Value, categoryAttribs);
else
{
try
{
pp = PerformanceCalculator.Calculate(categoryAttribs);
}
catch (InvalidOperationException)
{
pp = -1;
}
}
return pp;
}
private List<Mod> getMods(Ruleset ruleset)
{
var mods = new List<Mod>();
if (_Mods == null)
return mods;
var availableMods = ruleset.GetAllMods().ToList();
foreach (var modString in _Mods)
{
Mod newMod = availableMods.FirstOrDefault(m => string.Equals(m.Acronym, modString, StringComparison.CurrentCultureIgnoreCase));
if (newMod == null)
{
continue;
}
mods.Add(newMod);
}
return mods;
}
public int GetMaxCombo(int? fromTime = null)
{
if (PlayableBeatmap == null)
return -1;
if (fromTime.HasValue)
return GetComboFromTime(PlayableBeatmap, fromTime.Value);
return GetMaxCombo(PlayableBeatmap);
}
protected int GetMaxCombo(IBeatmap beatmap) => GetMaxCombo(beatmap.HitObjects);
protected int GetComboFromTime(IBeatmap beatmap, int fromTime) =>
GetMaxCombo(beatmap.HitObjects.Where(h => h.StartTime > fromTime).ToList());
protected int GetComboToTime(IBeatmap beatmap, int toTime) =>
GetMaxCombo(beatmap.HitObjects.Where(h => h.StartTime < toTime).ToList());
protected abstract int GetMaxCombo(IReadOnlyList<HitObject> hitObjects);
protected abstract Dictionary<HitResult, int> GenerateHitResults(double accuracy, IReadOnlyList<HitObject> hitObjects, int countMiss, int? countMeh, int? countGood);
protected abstract double GetAccuracy(Dictionary<HitResult, int> statistics);
}
}
| 33.131313 | 173 | 0.598933 | [
"MIT"
] | SentimentalDesu/StreamCompanion | PpCalculator/PpCalculator.cs | 6,562 | C# |
using System;
namespace VMFParser
{
public class MapProperty
{
/// <summary>
/// Returns the computed boolean of this property.
/// </summary>
public bool Boolean
{
get
{
return String == "1";
}
}
/// <summary>
/// Returns the computed decimal (double) of this property.
/// </summary>
public double? Decimal
{
get
{
try
{
return double.Parse(String);
}
catch { return null; }
}
}
/// <summary>
/// Returns the computed integer of this property.
/// </summary>
public int? Integer
{
get
{
try
{
return int.Parse(String);
}
catch { return null; }
}
}
/// <summary>
/// Returns the string value of this property.
/// </summary>
public string String { get; set; }
/// <summary>
/// Predicts what type of value it is based on the string, incompatible with booleans.
/// Dynamic type so use with caution.
/// </summary>
public dynamic PredictedValue
{
get
{
int? i = Integer;
if (i != null) return i;
double? d = Decimal;
if (d != null) return d;
return String;
}
}
public MapProperty(string s)
{
String = s;
}
public static implicit operator MapProperty(int i)
{
return new MapProperty(i.ToString());
}
public static implicit operator MapProperty(double d)
{
return new MapProperty(d.ToString());
}
public static implicit operator MapProperty(bool b)
{
return new MapProperty(b ? "1" : "0");
}
public static implicit operator MapProperty(string s)
{
return new MapProperty(s);
}
}
} | 24.898876 | 94 | 0.431859 | [
"MIT"
] | AshkoreDracson/VMF-Parser | VMF Parser/VMF Parser/MapProperty.cs | 2,218 | C# |
using System.Windows;
namespace Kebler.UI.Dialogs
{
public partial class AddTorrentView
{
public AddTorrentView()
{
InitializeComponent();
}
}
} | 16.25 | 40 | 0.579487 | [
"Apache-2.0"
] | 69NEO69/Kebler | src/Kebler.UI/Dialogs/AddTorrentView.xaml.cs | 197 | C# |
namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns
{
class AcmeArguments
{
public string AcmeDnsServer { get; set; }
}
}
| 18.125 | 54 | 0.668966 | [
"Apache-2.0"
] | FuseCP-TRobinson/win-acme | src/main/Plugins/ValidationPlugins/Dns/Acme/AcmeArguments.cs | 147 | C# |
namespace DI.BLL
{
public interface ITestBLL
{
string SayHello();
}
} | 12.857143 | 29 | 0.566667 | [
"MIT"
] | Ran-snow/aspnetcorestudy | DI/BLL/ITestBLL.cs | 92 | C# |
using System;
namespace Web_E_Commerce.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 17.75 | 70 | 0.671362 | [
"MIT"
] | DNADEVELOPERSOFTWARE/PROJETO-E-COMMERCE_2020 | src/Web_E-Commerce/Models/ErrorViewModel.cs | 213 | C# |
using Microsoft.AspNetCore.Mvc;
namespace HairSalon.Controllers
{
public class HomeController : Controller
{
[HttpGet("/")]
public ActionResult Index()
{
return View();
}
}
}
| 15.4 | 44 | 0.5671 | [
"MIT"
] | skillitzimberg/HairSalon.Solution | HairSalon/Controllers/HomeController.cs | 231 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aggregates.Contracts;
using NServiceBus;
using NServiceBus.Settings;
using NServiceBus.Unicast;
using NServiceBus.Unicast.Messages;
namespace Aggregates.Internal
{
[ExcludeFromCodeCoverage]
internal class NServiceBusMessaging : IMessaging
{
private readonly MessageHandlerRegistry _handlers;
private readonly MessageMetadataRegistry _metadata;
private readonly ReadOnlySettings _settings;
public NServiceBusMessaging(MessageHandlerRegistry handlers, MessageMetadataRegistry metadata, ReadOnlySettings settings)
{
_handlers = handlers;
_metadata = metadata;
_settings = settings;
}
public Type[] GetHandledTypes()
{
return _handlers.GetMessageTypes().ToArray();
}
public Type[] GetMessageTypes()
{
// include Domain Assemblies because NSB's assembly scanning doesn't catch all types
return AppDomain.CurrentDomain.GetAssemblies()
.Where(x => !x.IsDynamic)
.SelectMany(x => x.DefinedTypes.Where(IsMessageType)).ToArray()
.Distinct().ToArray();
}
public Type[] GetEntityTypes()
{
return AppDomain.CurrentDomain.GetAssemblies()
.Where(x => !x.IsDynamic)
.SelectMany(x => x.DefinedTypes.Where(IsEntityType)).ToArray()
.Distinct().ToArray();
}
public Type[] GetMessageHierarchy(Type messageType)
{
var metadata = _metadata.GetMessageMetadata(messageType);
return metadata.MessageHierarchy;
}
private static bool IsEntityType(Type type)
{
if (type.IsGenericTypeDefinition)
return false;
return IsSubclassOfRawGeneric(typeof(Entity<,>), type);
}
private static bool IsMessageType(Type type)
{
if (type.IsGenericTypeDefinition)
return false;
return typeof(Messages.IMessage).IsAssignableFrom(type) && !typeof(IState).IsAssignableFrom(type);
}
// https://stackoverflow.com/a/457708/223547
static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
}
}
| 33.795181 | 129 | 0.606061 | [
"MIT"
] | ashithraj/Aggregates.NET | src/Aggregates.NET.NServiceBus/Internal/NServiceBusMessaging.cs | 2,807 | C# |
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
namespace brotliparser
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 4) return (int) ReturnType.IllegalArgs;
#region 解压指令
//BrotliDecompress
//调用 -bd [输入文件路径] [输出路径] [保存文件名]
if (args[0].Equals("-bd"))
{
//检查合法路径正则表达式
Regex isDir = new Regex(@"^([a-zA-Z]:\\)?[^\/\:\*\?\""\<\>\|\,]*$");
//检查合法文件名正则表达式
Regex isFileName = new Regex(@"^[^\/\:\*\?\""\<\>\|\,]+$");
if (
File.Exists(args[1]) && //检查是否有文件存在
isDir.Match(Path.GetDirectoryName(args[2]) ?? string.Empty).Success &&//检查是否为合法路径
isFileName.Match(args[3] ?? string.Empty).Success) //检查文件名是否合法
{
//在不存在路径时创建文件夹
Directory.CreateDirectory(Path.GetDirectoryName(args[2]) ?? string.Empty);
Console.WriteLine("读取文件...");
byte[] inputBuff;
try
{
//尝试读取文件
inputBuff = ByteArrayIO.File2Byte(args[1]);
}
catch (Exception e)
{
//读取文件发生错误
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"保存文件时发生错误\n{e}");
Thread.Sleep(3000);
return (int)ReturnType.IOError;
}
//读取到空文件
if (inputBuff.Length == 0)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("读取到空文件");
return (int) ReturnType.EmptyFile;
}
byte[] outBuff;
try
{
Console.WriteLine("解压文件...");
//尝试解压文件数据
outBuff = BrotliUtils.BrotliDecompress(inputBuff);
}
catch (Exception e)
{
//解压发生错误
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"此文件不是Brotli压缩算法构建的无法解压\n{e}");
Thread.Sleep(3000);
return (int)ReturnType.ParseError;
}
try
{
Console.WriteLine("保存文件...");
//将文件保存到指定路径
ByteArrayIO.Bytes2File(outBuff,$"{args[2]}\\{args[3]}");
}
catch (Exception e)
{
//保存时发生错误
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"保存文件时发生错误\n{e}");
Thread.Sleep(3000);
return (int)ReturnType.IOError;
}
}
else
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("无效参数");
Console.ForegroundColor = ConsoleColor.White;
Thread.Sleep(3000);
return (int)ReturnType.IllegalArgs;
}
}
#endregion
Console.ReadLine();
return (int)ReturnType.Success;
}
}
}
| 38.27551 | 107 | 0.390829 | [
"MIT"
] | CBGan/BrotliParser | brotliparser/Program.cs | 4,131 | C# |
// <copyright file="StackFrame.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2011-2013 Microsoft Open Technologies, Inc. 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.
// </copyright>
using System.Collections.Generic;
namespace Microsoft.Owin.Diagnostics.Views
{
/// <summary>
/// Detailed exception stack information used to generate a view
/// </summary>
public class StackFrame
{
/// <summary>
/// Function containing instruction
/// </summary>
public string Function { get; set; }
/// <summary>
/// File containing the instruction
/// </summary>
public string File { get; set; }
/// <summary>
/// The line number of the instruction
/// </summary>
public int Line { get; set; }
/// <summary>
/// The line preceeding the frame line
/// </summary>
public int PreContextLine { get; set; }
/// <summary>
///
/// </summary>
public IEnumerable<string> PreContextCode { get; set; }
/// <summary>
///
/// </summary>
public string ContextCode { get; set; }
/// <summary>
///
/// </summary>
public IEnumerable<string> PostContextCode { get; set; }
}
}
| 29.919355 | 79 | 0.607008 | [
"Apache-2.0"
] | 15901213541/-OAuth2.0 | src/Microsoft.Owin.Diagnostics/Views/StackFrame.cs | 1,855 | C# |
using inSSIDer.HTML;
using inSSIDer.UI.Controls;
namespace inSSIDer.UI.Forms
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
this.mainMenu = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.configureGPSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.changeLogFilenameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.startStopLoggingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.convertLogToKMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.exportToNS1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.crashToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.normalModeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fullscreenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.shortcutsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.nextTabToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prevTabToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.inSSIDerForumsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.checkForUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.aboutInSSIDerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.gpsStatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.developerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.startNullScanningToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.stopNullScanningToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sdlgLog = new System.Windows.Forms.SaveFileDialog();
this.sdlgNs1 = new System.Windows.Forms.SaveFileDialog();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.apCountLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.gpsToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.locationToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.loggingToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.gripContainer1 = new inSSIDer.UI.Controls.GripSplitContainer();
this.scannerView = new inSSIDer.UI.Controls.ScannerView();
this.filtersView = new MetaGeek.Filters.Views.FiltersView();
this.detailsTabControl = new inSSIDer.UI.Controls.CustomTabControl();
this.tabNews = new System.Windows.Forms.TabPage();
this.htmlControl = new inSSIDer.HTML.HtmlControl();
this.tabTimeGraph = new System.Windows.Forms.TabPage();
this.timeGraph1 = new inSSIDer.UI.Controls.TimeGraph();
this.tab24Chan = new System.Windows.Forms.TabPage();
this.chanView24 = new inSSIDer.UI.Controls.ChannelView();
this.tab58Chan = new System.Windows.Forms.TabPage();
this.chanView58 = new inSSIDer.UI.Controls.ChannelView();
this.tabGps = new System.Windows.Forms.TabPage();
this.gpsMon1 = new inSSIDer.UI.Controls.GpsMon();
this.networkInterfaceSelector1 = new inSSIDer.UI.Controls.NetworkInterfaceSelector();
this.mainMenu.SuspendLayout();
this.statusStrip.SuspendLayout();
this.gripContainer1.Panel1.SuspendLayout();
this.gripContainer1.Panel2.SuspendLayout();
this.gripContainer1.SuspendLayout();
this.detailsTabControl.SuspendLayout();
this.tabNews.SuspendLayout();
this.tabTimeGraph.SuspendLayout();
this.tab24Chan.SuspendLayout();
this.tab58Chan.SuspendLayout();
this.tabGps.SuspendLayout();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.GripMargin = new System.Windows.Forms.Padding(2);
this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.viewToolStripMenuItem,
this.shortcutsToolStripMenuItem,
this.helpToolStripMenuItem,
this.gpsStatToolStripMenuItem,
this.developerToolStripMenuItem});
this.mainMenu.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
this.mainMenu.Location = new System.Drawing.Point(0, 0);
this.mainMenu.Name = "mainMenu";
this.mainMenu.Size = new System.Drawing.Size(1008, 24);
this.mainMenu.TabIndex = 0;
this.mainMenu.Text = "Main Menu";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.configureGPSToolStripMenuItem,
this.toolStripSeparator6,
this.changeLogFilenameToolStripMenuItem,
this.startStopLoggingToolStripMenuItem,
this.convertLogToKMLToolStripMenuItem,
this.toolStripSeparator5,
this.exportToNS1ToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem,
this.crashToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// configureGPSToolStripMenuItem
//
this.configureGPSToolStripMenuItem.Name = "configureGPSToolStripMenuItem";
this.configureGPSToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.configureGPSToolStripMenuItem.Text = "Configure GPS";
this.configureGPSToolStripMenuItem.Click += new System.EventHandler(this.ConfigureGpsToolStripMenuItemClick);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(181, 6);
//
// changeLogFilenameToolStripMenuItem
//
this.changeLogFilenameToolStripMenuItem.Name = "changeLogFilenameToolStripMenuItem";
this.changeLogFilenameToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.changeLogFilenameToolStripMenuItem.Text = "Change log filename";
this.changeLogFilenameToolStripMenuItem.Click += new System.EventHandler(this.ChangeLogFilenameToolStripMenuItemClick);
//
// startStopLoggingToolStripMenuItem
//
this.startStopLoggingToolStripMenuItem.Name = "startStopLoggingToolStripMenuItem";
this.startStopLoggingToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.startStopLoggingToolStripMenuItem.Text = "Start Logging";
this.startStopLoggingToolStripMenuItem.Click += new System.EventHandler(this.StartStopLoggingToolStripMenuItemClick);
//
// convertLogToKMLToolStripMenuItem
//
this.convertLogToKMLToolStripMenuItem.Name = "convertLogToKMLToolStripMenuItem";
this.convertLogToKMLToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.convertLogToKMLToolStripMenuItem.Text = "Convert GPX to KML";
this.convertLogToKMLToolStripMenuItem.Click += new System.EventHandler(this.ConvertLogToKmlToolStripMenuItemClick);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(181, 6);
//
// exportToNS1ToolStripMenuItem
//
this.exportToNS1ToolStripMenuItem.Name = "exportToNS1ToolStripMenuItem";
this.exportToNS1ToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.exportToNS1ToolStripMenuItem.Text = "Export to NS1";
this.exportToNS1ToolStripMenuItem.Click += new System.EventHandler(this.ExportToNs1ToolStripMenuItemClick);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(181, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolStripMenuItemClick);
//
// crashToolStripMenuItem
//
this.crashToolStripMenuItem.Name = "crashToolStripMenuItem";
this.crashToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.crashToolStripMenuItem.Text = "Crash";
this.crashToolStripMenuItem.Visible = false;
this.crashToolStripMenuItem.Click += new System.EventHandler(this.CrashToolStripMenuItemClick);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.normalModeToolStripMenuItem,
this.fullscreenToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.viewToolStripMenuItem.Text = "View";
//
// normalModeToolStripMenuItem
//
this.normalModeToolStripMenuItem.Checked = true;
this.normalModeToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.normalModeToolStripMenuItem.Enabled = false;
this.normalModeToolStripMenuItem.Name = "normalModeToolStripMenuItem";
this.normalModeToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.normalModeToolStripMenuItem.Text = "Normal Mode";
this.normalModeToolStripMenuItem.Click += new System.EventHandler(this.NormalModeToolStripMenuItemClick);
//
// fullscreenToolStripMenuItem
//
this.fullscreenToolStripMenuItem.Name = "fullscreenToolStripMenuItem";
this.fullscreenToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F11;
this.fullscreenToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.fullscreenToolStripMenuItem.Text = "Fullscreen";
this.fullscreenToolStripMenuItem.Click += new System.EventHandler(this.FullscreenToolStripMenuItemClick);
//
// shortcutsToolStripMenuItem
//
this.shortcutsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nextTabToolStripMenuItem,
this.prevTabToolStripMenuItem});
this.shortcutsToolStripMenuItem.Name = "shortcutsToolStripMenuItem";
this.shortcutsToolStripMenuItem.Size = new System.Drawing.Size(69, 20);
this.shortcutsToolStripMenuItem.Text = "Shortcuts";
this.shortcutsToolStripMenuItem.Visible = false;
//
// nextTabToolStripMenuItem
//
this.nextTabToolStripMenuItem.Name = "nextTabToolStripMenuItem";
this.nextTabToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Tab)));
this.nextTabToolStripMenuItem.Size = new System.Drawing.Size(206, 22);
this.nextTabToolStripMenuItem.Text = "Next Tab";
this.nextTabToolStripMenuItem.Click += new System.EventHandler(this.NextTabToolStripMenuItemClick);
//
// prevTabToolStripMenuItem
//
this.prevTabToolStripMenuItem.Name = "prevTabToolStripMenuItem";
this.prevTabToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.Tab)));
this.prevTabToolStripMenuItem.Size = new System.Drawing.Size(206, 22);
this.prevTabToolStripMenuItem.Text = "Prev Tab";
this.prevTabToolStripMenuItem.Click += new System.EventHandler(this.PrevTabToolStripMenuItemClick);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.inSSIDerForumsToolStripMenuItem,
this.toolStripSeparator3,
this.checkForUpdatesToolStripMenuItem,
this.toolStripSeparator4,
this.aboutInSSIDerToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "Help";
//
// inSSIDerForumsToolStripMenuItem
//
this.inSSIDerForumsToolStripMenuItem.Name = "inSSIDerForumsToolStripMenuItem";
this.inSSIDerForumsToolStripMenuItem.Size = new System.Drawing.Size(170, 22);
this.inSSIDerForumsToolStripMenuItem.Text = "inSSIDer Forums";
this.inSSIDerForumsToolStripMenuItem.Click += new System.EventHandler(this.InSsiDerForumsToolStripMenuItemClick);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(167, 6);
//
// checkForUpdatesToolStripMenuItem
//
this.checkForUpdatesToolStripMenuItem.Name = "checkForUpdatesToolStripMenuItem";
this.checkForUpdatesToolStripMenuItem.Size = new System.Drawing.Size(170, 22);
this.checkForUpdatesToolStripMenuItem.Text = "Check for updates";
this.checkForUpdatesToolStripMenuItem.Click += new System.EventHandler(this.CheckForUpdatesToolStripMenuItemClick);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(167, 6);
//
// aboutInSSIDerToolStripMenuItem
//
this.aboutInSSIDerToolStripMenuItem.Name = "aboutInSSIDerToolStripMenuItem";
this.aboutInSSIDerToolStripMenuItem.Size = new System.Drawing.Size(170, 22);
this.aboutInSSIDerToolStripMenuItem.Text = "About inSSIDer";
this.aboutInSSIDerToolStripMenuItem.Click += new System.EventHandler(this.AboutInSsiDerToolStripMenuItemClick);
//
// gpsStatToolStripMenuItem
//
this.gpsStatToolStripMenuItem.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.gpsStatToolStripMenuItem.Image = global::inSSIDer.Properties.Resources.wifiPlay;
this.gpsStatToolStripMenuItem.Margin = new System.Windows.Forms.Padding(0, 0, 186, 0);
this.gpsStatToolStripMenuItem.Name = "gpsStatToolStripMenuItem";
this.gpsStatToolStripMenuItem.Size = new System.Drawing.Size(83, 20);
this.gpsStatToolStripMenuItem.Text = "Start GPS";
this.gpsStatToolStripMenuItem.Click += new System.EventHandler(this.GpsStatToolStripMenuItemClick);
//
// developerToolStripMenuItem
//
this.developerToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.startNullScanningToolStripMenuItem,
this.stopNullScanningToolStripMenuItem});
this.developerToolStripMenuItem.Name = "developerToolStripMenuItem";
this.developerToolStripMenuItem.Size = new System.Drawing.Size(72, 20);
this.developerToolStripMenuItem.Text = "Developer";
this.developerToolStripMenuItem.Visible = false;
//
// startNullScanningToolStripMenuItem
//
this.startNullScanningToolStripMenuItem.Name = "startNullScanningToolStripMenuItem";
this.startNullScanningToolStripMenuItem.Size = new System.Drawing.Size(175, 22);
this.startNullScanningToolStripMenuItem.Text = "Start Null Scanning";
this.startNullScanningToolStripMenuItem.Click += new System.EventHandler(this.StartNullScanningToolStripMenuItemClick);
//
// stopNullScanningToolStripMenuItem
//
this.stopNullScanningToolStripMenuItem.Name = "stopNullScanningToolStripMenuItem";
this.stopNullScanningToolStripMenuItem.Size = new System.Drawing.Size(175, 22);
this.stopNullScanningToolStripMenuItem.Text = "Stop Null Scanning";
this.stopNullScanningToolStripMenuItem.Click += new System.EventHandler(this.StopNullScanningToolStripMenuItemClick);
//
// sdlgLog
//
this.sdlgLog.DefaultExt = "gpx";
this.sdlgLog.Filter = "GPX log files (*.gpx)|*.gpx";
this.sdlgLog.SupportMultiDottedExtensions = true;
this.sdlgLog.Title = "Select where to place the log file";
//
// sdlgNs1
//
this.sdlgNs1.DefaultExt = "ns1";
this.sdlgNs1.Filter = "NetStumbler files (*.ns1)|*.ns1";
this.sdlgNs1.SupportMultiDottedExtensions = true;
this.sdlgNs1.Title = "Select where to place the output NS1 file";
//
// statusStrip
//
this.statusStrip.BackColor = System.Drawing.SystemColors.Control;
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.apCountLabel,
this.gpsToolStripStatusLabel,
this.locationToolStripStatusLabel,
this.loggingToolStripStatusLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 538);
this.statusStrip.Name = "statusStrip";
this.statusStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.statusStrip.Size = new System.Drawing.Size(1008, 24);
this.statusStrip.TabIndex = 1;
this.statusStrip.Text = "statusStrip1";
//
// apCountLabel
//
this.apCountLabel.AutoSize = false;
this.apCountLabel.Name = "apCountLabel";
this.apCountLabel.Size = new System.Drawing.Size(100, 19);
this.apCountLabel.Text = "0 / 0 AP(s)";
this.apCountLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// gpsToolStripStatusLabel
//
this.gpsToolStripStatusLabel.AutoSize = false;
this.gpsToolStripStatusLabel.Margin = new System.Windows.Forms.Padding(0, 3, 5, 2);
this.gpsToolStripStatusLabel.Name = "gpsToolStripStatusLabel";
this.gpsToolStripStatusLabel.Size = new System.Drawing.Size(118, 19);
this.gpsToolStripStatusLabel.Text = "GPS Status";
this.gpsToolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// locationToolStripStatusLabel
//
this.locationToolStripStatusLabel.AutoSize = false;
this.locationToolStripStatusLabel.Name = "locationToolStripStatusLabel";
this.locationToolStripStatusLabel.Size = new System.Drawing.Size(320, 19);
this.locationToolStripStatusLabel.Text = "Location";
this.locationToolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// loggingToolStripStatusLabel
//
this.loggingToolStripStatusLabel.Name = "loggingToolStripStatusLabel";
this.loggingToolStripStatusLabel.Size = new System.Drawing.Size(86, 19);
this.loggingToolStripStatusLabel.Text = "Logging Status";
//
// gripContainer1
//
this.gripContainer1.BackColor = System.Drawing.Color.Black;
this.gripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.gripContainer1.Location = new System.Drawing.Point(0, 24);
this.gripContainer1.Margin = new System.Windows.Forms.Padding(3, 3, 3, 0);
this.gripContainer1.Name = "gripContainer1";
this.gripContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// gripContainer1.Panel1
//
this.gripContainer1.Panel1.Controls.Add(this.scannerView);
this.gripContainer1.Panel1.Controls.Add(this.filtersView);
this.gripContainer1.Panel1MinSize = 69;
//
// gripContainer1.Panel2
//
this.gripContainer1.Panel2.Controls.Add(this.detailsTabControl);
this.gripContainer1.Panel2MinSize = 150;
this.gripContainer1.Size = new System.Drawing.Size(1008, 514);
this.gripContainer1.SplitterDistance = 245;
this.gripContainer1.SplitterWidth = 7;
this.gripContainer1.TabIndex = 1;
//
// scannerView
//
this.scannerView.Dock = System.Windows.Forms.DockStyle.Fill;
this.scannerView.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.scannerView.Location = new System.Drawing.Point(0, 66);
this.scannerView.Name = "scannerView";
this.scannerView.Size = new System.Drawing.Size(1008, 179);
this.scannerView.TabIndex = 0;
//
// filtersView
//
this.filtersView.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(50)))));
this.filtersView.Dock = System.Windows.Forms.DockStyle.Top;
this.filtersView.Location = new System.Drawing.Point(0, 0);
this.filtersView.MaximumSize = new System.Drawing.Size(0, 66);
this.filtersView.Name = "filtersView";
this.filtersView.Padding = new System.Windows.Forms.Padding(3);
this.filtersView.Size = new System.Drawing.Size(1008, 66);
this.filtersView.TabIndex = 1;
//
// detailsTabControl
//
this.detailsTabControl.Controls.Add(this.tabNews);
this.detailsTabControl.Controls.Add(this.tabTimeGraph);
this.detailsTabControl.Controls.Add(this.tab24Chan);
this.detailsTabControl.Controls.Add(this.tab58Chan);
this.detailsTabControl.Controls.Add(this.tabGps);
this.detailsTabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.detailsTabControl.ItemSize = new System.Drawing.Size(0, 25);
this.detailsTabControl.Location = new System.Drawing.Point(0, 0);
this.detailsTabControl.Name = "detailsTabControl";
this.detailsTabControl.Padding = new System.Drawing.Point(0, 0);
this.detailsTabControl.SelectedIndex = 0;
this.detailsTabControl.Size = new System.Drawing.Size(1008, 262);
this.detailsTabControl.TabIndex = 0;
this.detailsTabControl.TabStop = false;
this.detailsTabControl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.detailsTabControl_MouseDown);
//
// tabNews
//
this.tabNews.Controls.Add(this.htmlControl);
this.tabNews.Location = new System.Drawing.Point(4, 29);
this.tabNews.Name = "tabNews";
this.tabNews.Size = new System.Drawing.Size(1000, 229);
this.tabNews.TabIndex = 5;
this.tabNews.Text = "News";
this.tabNews.UseVisualStyleBackColor = true;
//
// htmlControl
//
this.htmlControl.AnalyticsSource = "NewsTab";
this.htmlControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.htmlControl.IsWebBrowserContextMenuEnabled = false;
this.htmlControl.Location = new System.Drawing.Point(0, 0);
this.htmlControl.MinimumSize = new System.Drawing.Size(20, 20);
this.htmlControl.Name = "htmlControl";
this.htmlControl.OpenWebLinks = false;
this.htmlControl.Size = new System.Drawing.Size(1000, 229);
this.htmlControl.TabIndex = 0;
this.htmlControl.UpdateIntervalDays = 1F;
this.htmlControl.UpdateUrl = "http://www.metageek.net/blog/feed";
this.htmlControl.Url = new System.Uri("about:blank", System.UriKind.Absolute);
this.htmlControl.WebBrowserShortcutsEnabled = false;
//
// tabTimeGraph
//
this.tabTimeGraph.BackColor = System.Drawing.Color.Black;
this.tabTimeGraph.Controls.Add(this.timeGraph1);
this.tabTimeGraph.ForeColor = System.Drawing.Color.DimGray;
this.tabTimeGraph.Location = new System.Drawing.Point(4, 29);
this.tabTimeGraph.Name = "tabTimeGraph";
this.tabTimeGraph.Size = new System.Drawing.Size(1000, 229);
this.tabTimeGraph.TabIndex = 0;
this.tabTimeGraph.Text = "Time Graph";
this.tabTimeGraph.UseVisualStyleBackColor = true;
//
// timeGraph1
//
this.timeGraph1.Dock = System.Windows.Forms.DockStyle.Fill;
this.timeGraph1.ForeColor = System.Drawing.Color.DimGray;
this.timeGraph1.Location = new System.Drawing.Point(0, 0);
this.timeGraph1.MaxAmplitude = -10F;
this.timeGraph1.MaxTime = new System.DateTime(2010, 7, 28, 12, 8, 7, 739);
this.timeGraph1.MinAmplitude = -100F;
this.timeGraph1.Name = "timeGraph1";
this.timeGraph1.RightMargin = 32;
this.timeGraph1.ShowSSIDs = true;
this.timeGraph1.Size = new System.Drawing.Size(1000, 229);
this.timeGraph1.TabIndex = 0;
this.timeGraph1.TimeSpan = System.TimeSpan.Parse("00:05:00");
//
// tab24Chan
//
this.tab24Chan.BackColor = System.Drawing.Color.Black;
this.tab24Chan.Controls.Add(this.chanView24);
this.tab24Chan.ForeColor = System.Drawing.Color.DimGray;
this.tab24Chan.Location = new System.Drawing.Point(4, 29);
this.tab24Chan.Name = "tab24Chan";
this.tab24Chan.Size = new System.Drawing.Size(1000, 229);
this.tab24Chan.TabIndex = 1;
this.tab24Chan.Text = "2.4 GHz Channels";
this.tab24Chan.UseVisualStyleBackColor = true;
//
// chanView24
//
this.chanView24.Dock = System.Windows.Forms.DockStyle.Fill;
this.chanView24.ForeColor = System.Drawing.Color.DimGray;
this.chanView24.Location = new System.Drawing.Point(0, 0);
this.chanView24.MaxAmplitude = -10F;
this.chanView24.MaxFrequency = 2495F;
this.chanView24.MinAmplitude = -100F;
this.chanView24.MinFrequency = 2400F;
this.chanView24.Name = "chanView24";
this.chanView24.RightMargin = 20;
this.chanView24.Size = new System.Drawing.Size(1000, 229);
this.chanView24.TabIndex = 0;
//
// tab58Chan
//
this.tab58Chan.BackColor = System.Drawing.Color.Black;
this.tab58Chan.Controls.Add(this.chanView58);
this.tab58Chan.ForeColor = System.Drawing.Color.DimGray;
this.tab58Chan.Location = new System.Drawing.Point(4, 29);
this.tab58Chan.Name = "tab58Chan";
this.tab58Chan.Size = new System.Drawing.Size(1000, 229);
this.tab58Chan.TabIndex = 4;
this.tab58Chan.Text = "5 GHz Channels";
this.tab58Chan.UseVisualStyleBackColor = true;
//
// chanView58
//
this.chanView58.Band = inSSIDer.UI.Controls.ChannelView.BandType.Band5000MHz;
this.chanView58.Dock = System.Windows.Forms.DockStyle.Fill;
this.chanView58.ForeColor = System.Drawing.Color.DimGray;
this.chanView58.Location = new System.Drawing.Point(0, 0);
this.chanView58.MaxAmplitude = -10F;
this.chanView58.MaxFrequency = 5850F;
this.chanView58.MinAmplitude = -100F;
this.chanView58.MinFrequency = 5150F;
this.chanView58.Name = "chanView58";
this.chanView58.RightMargin = 20;
this.chanView58.Size = new System.Drawing.Size(1000, 229);
this.chanView58.TabIndex = 1;
//
// tabGps
//
this.tabGps.BackColor = System.Drawing.Color.Black;
this.tabGps.Controls.Add(this.gpsMon1);
this.tabGps.ForeColor = System.Drawing.Color.DimGray;
this.tabGps.Location = new System.Drawing.Point(4, 29);
this.tabGps.Name = "tabGps";
this.tabGps.Size = new System.Drawing.Size(1000, 229);
this.tabGps.TabIndex = 3;
this.tabGps.Text = "GPS";
this.tabGps.UseVisualStyleBackColor = true;
//
// gpsMon1
//
this.gpsMon1.BackColor = System.Drawing.Color.Black;
this.gpsMon1.Dock = System.Windows.Forms.DockStyle.Fill;
this.gpsMon1.ForeColor = System.Drawing.Color.DimGray;
this.gpsMon1.Location = new System.Drawing.Point(0, 0);
this.gpsMon1.Name = "gpsMon1";
this.gpsMon1.Size = new System.Drawing.Size(1000, 229);
this.gpsMon1.TabIndex = 0;
//
// networkInterfaceSelector1
//
this.networkInterfaceSelector1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.networkInterfaceSelector1.AutoSize = true;
this.networkInterfaceSelector1.Location = new System.Drawing.Point(827, -1);
this.networkInterfaceSelector1.Name = "networkInterfaceSelector1";
this.networkInterfaceSelector1.Size = new System.Drawing.Size(181, 25);
this.networkInterfaceSelector1.TabIndex = 2;
this.networkInterfaceSelector1.SizeChanged += new System.EventHandler(this.NetworkInterfaceSelector1SizeChanged);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(1008, 562);
this.Controls.Add(this.gripContainer1);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.networkInterfaceSelector1);
this.Controls.Add(this.mainMenu);
this.ForeColor = System.Drawing.SystemColors.ControlText;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MainMenuStrip = this.mainMenu;
this.MinimumSize = new System.Drawing.Size(700, 500);
this.Name = "FormMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "inSSIDer 2.1";
this.LocationChanged += new System.EventHandler(this.FormMainLocationChanged);
this.SizeChanged += new System.EventHandler(this.FormMainSizeChanged);
this.mainMenu.ResumeLayout(false);
this.mainMenu.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.gripContainer1.Panel1.ResumeLayout(false);
this.gripContainer1.Panel2.ResumeLayout(false);
this.gripContainer1.ResumeLayout(false);
this.detailsTabControl.ResumeLayout(false);
this.tabNews.ResumeLayout(false);
this.tabTimeGraph.ResumeLayout(false);
this.tab24Chan.ResumeLayout(false);
this.tab58Chan.ResumeLayout(false);
this.tabGps.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip mainMenu;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private GripSplitContainer gripContainer1;
private ScannerView scannerView;
private NetworkInterfaceSelector networkInterfaceSelector1;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog sdlgLog;
private System.Windows.Forms.ToolStripMenuItem fullscreenToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportToNS1ToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog sdlgNs1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem shortcutsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem nextTabToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prevTabToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutInSSIDerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem inSSIDerForumsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem checkForUpdatesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem crashToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem gpsStatToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem configureGPSToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem changeLogFilenameToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem startStopLoggingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem convertLogToKMLToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel gpsToolStripStatusLabel;
private System.Windows.Forms.ToolStripStatusLabel loggingToolStripStatusLabel;
private System.Windows.Forms.ToolStripStatusLabel locationToolStripStatusLabel;
private System.Windows.Forms.ToolStripMenuItem normalModeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem developerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem startNullScanningToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem stopNullScanningToolStripMenuItem;
private System.Windows.Forms.ToolStripStatusLabel apCountLabel;
private MetaGeek.Filters.Views.FiltersView filtersView;
private System.Windows.Forms.TabPage tabNews;
private HtmlControl htmlControl;
private System.Windows.Forms.TabPage tabTimeGraph;
private TimeGraph timeGraph1;
private System.Windows.Forms.TabPage tab24Chan;
private ChannelView chanView24;
private System.Windows.Forms.TabPage tab58Chan;
private ChannelView chanView58;
private System.Windows.Forms.TabPage tabGps;
private GpsMon gpsMon1;
private CustomTabControl detailsTabControl;
}
} | 57.836524 | 174 | 0.642815 | [
"Apache-2.0"
] | akpotter/inSSIDer-2 | MetaScanner/UI/Forms/frmMain.Designer.cs | 39,273 | C# |
using System;
namespace GVFS.Common
{
public class RetryableException : Exception
{
public RetryableException(string message) : base(message)
{
}
}
}
| 16.583333 | 66 | 0.582915 | [
"MIT"
] | Mattlk13/GVFS | GVFS/GVFS.Common/RetryableException.cs | 201 | 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 glue-2017-03-31.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.Glue.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Glue.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ConcurrentRunsExceededException Object
/// </summary>
public class ConcurrentRunsExceededExceptionUnmarshaller : IErrorResponseUnmarshaller<ConcurrentRunsExceededException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ConcurrentRunsExceededException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public ConcurrentRunsExceededException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse)
{
context.Read();
ConcurrentRunsExceededException unmarshalledObject = new ConcurrentRunsExceededException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static ConcurrentRunsExceededExceptionUnmarshaller _instance = new ConcurrentRunsExceededExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ConcurrentRunsExceededExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.058824 | 153 | 0.679935 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/Glue/Generated/Model/Internal/MarshallTransformations/ConcurrentRunsExceededExceptionUnmarshaller.cs | 3,065 | C# |
// <auto-generated />
using System;
using ForeSpark.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace ForeSpark.Migrations
{
[DbContext(typeof(ForeSparkDbContext))]
[Migration("20201126153159_check")]
partial class check
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.7")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration")
.HasColumnType("int");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("MethodName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<string>("ReturnValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("ServiceName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsGranted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<long?>("UserLinkId")
.HasColumnType("bigint");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("LoginProvider")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<byte>("Result")
.HasColumnType("tinyint");
b.Property<string>("TenancyName")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("UserNameOrEmailAddress")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime?>("ExpireDate")
.HasColumnType("datetime2");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsAbandoned")
.HasColumnType("bit");
b.Property<string>("JobArgs")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime")
.HasColumnType("datetime2");
b.Property<DateTime>("NextTryTime")
.HasColumnType("datetime2");
b.Property<byte>("Priority")
.HasColumnType("tinyint");
b.Property<short>("TryCount")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name", "UserId")
.IsUnique();
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityProperty", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("DynamicPropertyId")
.HasColumnType("int");
b.Property<string>("EntityFullName")
.HasColumnType("nvarchar(450)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DynamicPropertyId");
b.HasIndex("EntityFullName", "DynamicPropertyId", "TenantId")
.IsUnique()
.HasFilter("[EntityFullName] IS NOT NULL AND [TenantId] IS NOT NULL");
b.ToTable("AbpDynamicEntityProperties");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityPropertyValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("DynamicEntityPropertyId")
.HasColumnType("int");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DynamicEntityPropertyId");
b.ToTable("AbpDynamicEntityPropertyValues");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicProperty", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("DisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("InputType")
.HasColumnType("nvarchar(max)");
b.Property<string>("Permission")
.HasColumnType("nvarchar(max)");
b.Property<string>("PropertyName")
.HasColumnType("nvarchar(450)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PropertyName", "TenantId")
.IsUnique()
.HasFilter("[PropertyName] IS NOT NULL AND [TenantId] IS NOT NULL");
b.ToTable("AbpDynamicProperties");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicPropertyValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("DynamicPropertyId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DynamicPropertyId");
b.ToTable("AbpDynamicPropertyValues");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("ChangeTime")
.HasColumnType("datetime2");
b.Property<byte>("ChangeType")
.HasColumnType("tinyint");
b.Property<long>("EntityChangeSetId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(48)")
.HasMaxLength(48);
b.Property<string>("EntityTypeFullName")
.HasColumnType("nvarchar(192)")
.HasMaxLength(192);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EntityChangeSetId");
b.HasIndex("EntityTypeFullName", "EntityId");
b.ToTable("AbpEntityChanges");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("ExtensionData")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("Reason")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "CreationTime");
b.HasIndex("TenantId", "Reason");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpEntityChangeSets");
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<long>("EntityChangeId")
.HasColumnType("bigint");
b.Property<string>("NewValue")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("NewValueHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("OriginalValue")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("OriginalValueHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PropertyName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("PropertyTypeFullName")
.HasColumnType("nvarchar(192)")
.HasMaxLength(192);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EntityChangeId");
b.ToTable("AbpEntityPropertyChanges");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Icon")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsDisabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<string>("TenantIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int>("State")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("TenantNotificationId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(95)")
.HasMaxLength(95);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<long?>("ParentId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnitRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "RoleId");
b.ToTable("AbpOrganizationUnitRoles");
});
modelBuilder.Entity("Abp.Webhooks.WebhookEvent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("WebhookName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("AbpWebhookEvents");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<string>("Response")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ResponseStatusCode")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("WebhookEventId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("WebhookSubscriptionId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("WebhookEventId");
b.ToTable("AbpWebhookSendAttempts");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Headers")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Secret")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("WebhookUri")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Webhooks")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("AbpWebhookSubscriptions");
});
modelBuilder.Entity("ForeSpark.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDefault")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsStatic")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("ForeSpark.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AuthenticationSource")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("CNIC")
.HasColumnType("nvarchar(max)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsEmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsLockoutEnabled")
.HasColumnType("bit");
b.Property<bool>("IsPhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsTwoFactorEnabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LockoutEndDateUtc")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("ForeSpark.Cities.Cities", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Cities");
});
modelBuilder.Entity("ForeSpark.Installations.Installations", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<int>("CityId")
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<double>("Lat")
.HasColumnType("float");
b.Property<double>("Lng")
.HasColumnType("float");
b.Property<string>("Make")
.HasColumnType("nvarchar(max)");
b.Property<string>("Serial")
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CityId");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.ToTable("Installations");
});
modelBuilder.Entity("ForeSpark.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ConnectionString")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("EditionId")
.HasColumnType("int");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("ForeSpark.Request.Request", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<string>("CNIC")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<double?>("Lat")
.HasColumnType("float");
b.Property<double?>("Lng")
.HasColumnType("float");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int>("StatusId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("StatusId");
b.ToTable("Requests");
});
modelBuilder.Entity("ForeSpark.Request.RequestImages", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Image")
.HasColumnType("nvarchar(max)");
b.Property<int>("RequestId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RequestId");
b.ToTable("RequestImages");
});
modelBuilder.Entity("ForeSpark.Request.RequestStatus", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Status")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("RequestStatuses");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId")
.HasColumnType("int");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("ForeSpark.Authorization.Roles.Role", null)
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", null)
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", null)
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityProperty", b =>
{
b.HasOne("Abp.DynamicEntityProperties.DynamicProperty", "DynamicProperty")
.WithMany()
.HasForeignKey("DynamicPropertyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicEntityPropertyValue", b =>
{
b.HasOne("Abp.DynamicEntityProperties.DynamicEntityProperty", "DynamicEntityProperty")
.WithMany()
.HasForeignKey("DynamicEntityPropertyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.DynamicEntityProperties.DynamicPropertyValue", b =>
{
b.HasOne("Abp.DynamicEntityProperties.DynamicProperty", "DynamicProperty")
.WithMany("DynamicPropertyValues")
.HasForeignKey("DynamicPropertyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChangeSet", null)
.WithMany("EntityChanges")
.HasForeignKey("EntityChangeSetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChange", null)
.WithMany("PropertyChanges")
.HasForeignKey("EntityChangeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b =>
{
b.HasOne("Abp.Webhooks.WebhookEvent", "WebhookEvent")
.WithMany()
.HasForeignKey("WebhookEventId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ForeSpark.Authorization.Roles.Role", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("ForeSpark.Authorization.Users.User", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("ForeSpark.Installations.Installations", b =>
{
b.HasOne("ForeSpark.Cities.Cities", "City")
.WithMany()
.HasForeignKey("CityId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ForeSpark.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("ForeSpark.MultiTenancy.Tenant", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("ForeSpark.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("ForeSpark.Request.Request", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("ForeSpark.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
b.HasOne("ForeSpark.Request.RequestStatus", "Status")
.WithMany()
.HasForeignKey("StatusId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ForeSpark.Request.RequestImages", b =>
{
b.HasOne("ForeSpark.Request.Request", "Request")
.WithMany("ProductImages")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("ForeSpark.Authorization.Roles.Role", null)
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("ForeSpark.Authorization.Users.User", null)
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.981571 | 125 | 0.445696 | [
"MIT"
] | ali-kiyani/ForeSpark | aspnet-core/src/ForeSpark.EntityFrameworkCore/Migrations/20201126153159_check.Designer.cs | 76,258 | C# |
using Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using Neo.SmartContract.Framework.Services.System;
using Helper = Neo.SmartContract.Framework.Helper;
using System;
using System.ComponentModel;
using System.Numerics;
namespace dapp_nnc
{
public class nnc : SmartContract
{
/*存储结构有
* map(address,balance) 存储地址余额 key = 0x11+address
* map(txid,TransferInfo) 存储交易详情 key = 0x13+txid
*/
public delegate void deleTransfer(byte[] from, byte[] to, BigInteger value);
[DisplayName("transfer")]
public static event deleTransfer Transferred;
public class TransferInfo
{
public byte[] from;
public byte[] to;
public BigInteger value;
}
static readonly byte[] superAdmin = Helper.ToScriptHash("AMNFdmGuBrU1iaMbYd63L1zucYMdU9hvQU");//管理员
public static string name()
{
return "NEO Name Credit";
}
public static string symbol()
{
return "NNC";
}
private const ulong factor = 100;//精度2
private const ulong totalCoin = 10 * 100000000 * factor;//发行量10亿
public static byte decimals()
{
return 2;
}
//nnc 发行总量
public static BigInteger totalSupply()
{
return Storage.Get(Storage.CurrentContext, "totalSupply").AsBigInteger();
}
public static BigInteger balanceOf(byte[] who)
{
var keyAddress = new byte[] { 0x11 }.Concat(who);
return Storage.Get(Storage.CurrentContext, keyAddress).AsBigInteger();
}
public static bool transfer(byte[] from, byte[] to, BigInteger value)
{
if (value <= 0) return false;
if (from == to) return true;
//付款方
if (from.Length > 0)
{
var keyFrom = new byte[] { 0x11 }.Concat(from);
BigInteger from_value = Storage.Get(Storage.CurrentContext, keyFrom).AsBigInteger();
if (from_value < value) return false;
if (from_value == value)
Storage.Delete(Storage.CurrentContext, keyFrom);
else
Storage.Put(Storage.CurrentContext, keyFrom, from_value - value);
}
//收款方
if (to.Length > 0)
{
var keyTo = new byte[] { 0x11 }.Concat(to);
BigInteger to_value = Storage.Get(Storage.CurrentContext, keyTo).AsBigInteger();
Storage.Put(Storage.CurrentContext, keyTo, to_value + value);
}
//记录交易信息
setTxInfo(from, to, value);
//notify
Transferred(from, to, value);
return true;
}
private static void setTxInfo(byte[] from, byte[] to, BigInteger value)
{
TransferInfo info = new TransferInfo();
info.from = from;
info.to = to;
info.value = value;
byte[] txinfo = Helper.Serialize(info);
var txid = (ExecutionEngine.ScriptContainer as Transaction).Hash;
var keytxid = new byte[] { 0x13 }.Concat(txid);
Storage.Put(Storage.CurrentContext, keytxid, txinfo);
}
public static TransferInfo getTxInfo(byte[] txid)
{
byte[] keytxid = new byte[] { 0x13 }.Concat(txid);
byte[] v = Storage.Get(Storage.CurrentContext, keytxid);
if (v.Length == 0)
return null;
return Helper.Deserialize(v) as TransferInfo;
}
public static object Main(string method, object[] args)
{
var magicstr = "20180628";
if (Runtime.Trigger == TriggerType.Verification)//取钱才会涉及这里
{
return false;
}
else if (Runtime.Trigger == TriggerType.VerificationR)
{
return true;
}
else if (Runtime.Trigger == TriggerType.Application)
{
//必须在入口函数取得callscript,调用脚本的函数,也会导致执行栈变化,再取callscript就晚了
var callscript = ExecutionEngine.CallingScriptHash;
//this is in nep5
if (method == "totalSupply") return totalSupply();
if (method == "name") return name();
if (method == "symbol") return symbol();
if (method == "decimals") return decimals();
if (method == "deploy")
{
if (args.Length != 1) return false;
if (!Runtime.CheckWitness(superAdmin)) return false;
byte[] total_supply = Storage.Get(Storage.CurrentContext, "totalSupply");
if (total_supply.Length != 0) return false;
var keySuperAdmin = new byte[] { 0x11 }.Concat(superAdmin);
Storage.Put(Storage.CurrentContext, keySuperAdmin, totalCoin);
Storage.Put(Storage.CurrentContext, "totalSupply", totalCoin);
Transferred(null, superAdmin, totalCoin);
}
if (method == "balanceOf")
{
if (args.Length != 1) return 0;
byte[] who = (byte[])args[0];
if (who.Length != 20)
return false;
return balanceOf(who);
}
if (method == "transfer")
{
if (args.Length != 3) return false;
byte[] from = (byte[])args[0];
byte[] to = (byte[])args[1];
if (from == to)
return true;
if (from.Length != 20 || to.Length != 20)
return false;
BigInteger value = (BigInteger)args[2];
//没有from签名,不让转
if (!Runtime.CheckWitness(from))
return false;
//如果有跳板调用,不让转
if (ExecutionEngine.EntryScriptHash.AsBigInteger() != callscript.AsBigInteger())
return false;
//如果to是不可收钱合约,不让转
if (!IsPayable(to)) return false;
return transfer(from, to, value);
}
if (method == "transfer_app")
{
if (args.Length != 3) return false;
byte[] from = (byte[])args[0];
byte[] to = (byte[])args[1];
BigInteger value = (BigInteger)args[2];
//如果from 不是 传入脚本 不让转
if (from.AsBigInteger() != callscript.AsBigInteger())
return false;
return transfer(from, to, value);
}
if (method == "getTxInfo")
{
if (args.Length != 1) return 0;
byte[] txid = (byte[])args[0];
return getTxInfo(txid);
}
#region 升级合约,耗费490,仅限管理员
if (method == "upgrade")
{
//不是管理员 不能操作
if (!Runtime.CheckWitness(superAdmin))
return false;
if (args.Length != 1 && args.Length != 9)
return false;
byte[] script = Blockchain.GetContract(ExecutionEngine.ExecutingScriptHash).Script;
byte[] new_script = (byte[])args[0];
//如果传入的脚本一样 不继续操作
if (script == new_script)
return false;
byte[] parameter_list = new byte[] { 0x07, 0x10 };
byte return_type = 0x05;
bool need_storage = (bool)(object)05;
string name = "nnc";
string version = "1";
string author = "NEL";
string email = "0";
string description = "nnc";
if (args.Length == 9)
{
parameter_list = (byte[])args[1];
return_type = (byte)args[2];
need_storage = (bool)args[3];
name = (string)args[4];
version = (string)args[5];
author = (string)args[6];
email = (string)args[7];
description = (string)args[8];
}
Contract.Migrate(new_script, parameter_list, return_type, need_storage, name, version, author, email, description);
return true;
}
#endregion
}
return false;
}
public static bool IsPayable(byte[] to)
{
var c = Blockchain.GetContract(to);
if (c.Equals(null))
return true;
return c.IsPayable;
}
}
}
| 37.600823 | 135 | 0.475539 | [
"MIT"
] | NewEconoLab/neo-ns | dapp_nnc4.0/nnc.cs | 9,457 | C# |
using System;
using System.Diagnostics;
using System.Threading;
namespace HAL.Simulator
{
/// <summary>
/// This class contains static hooks that can be used by simulators to get specific Data.
/// </summary>
public static class SimHooks
{
private static readonly Stopwatch s_timer = new Stopwatch();
internal static void RestartTiming()
{
s_timer.Restart();
}
/// <summary>
/// Gets the FPGA time.
/// </summary>
/// <remarks>This value is in increments of 10 nanoseconds. Use <see cref="GetFPGATimestamp"/>
/// to get the timestamp in seconds.</remarks>
/// <returns>The FPGA time on a 10 nanosecond scale.</returns>
public static long GetFPGATime()
{
var seconds = (double)s_timer.ElapsedTicks / Stopwatch.Frequency;
return (long)(seconds * 1000000);
}
/// <summary>
/// Gets the FPGA time in seconds.
/// </summary>
/// <returns>The FPGA time in seconds</returns>
public static double GetFPGATimestamp()
{
return (double)s_timer.ElapsedTicks / Stopwatch.Frequency;
}
/// <summary>
/// Gets the current number of 100 nanosecond ticks from the system.
/// </summary>
/// <returns></returns>
public static long GetTime()
{
return DateTime.UtcNow.Ticks;
}
/// <summary>
/// Delays the current thread by a number of milliseconds.
/// </summary>
/// <param name="ms">Delay time</param>
public static void DelayMillis(double ms)
{
int milliSeconds = (int) ms;
var sw = Stopwatch.StartNew();
if (milliSeconds >= 20)
{
Thread.Sleep(milliSeconds - 12);
}
while (sw.ElapsedMilliseconds < milliSeconds)
{
}
}
/// <summary>
/// Delays the current thread by a number of seconds.
/// </summary>
/// <param name="s">Delay time</param>
public static void DelaySeconds(double s)
{
int milliSeconds = (int)(s * 1e3);
var sw = Stopwatch.StartNew();
if (milliSeconds >= 20)
{
Thread.Sleep(milliSeconds - 12);
}
while (sw.ElapsedMilliseconds < milliSeconds)
{
}
}
/// <summary>
/// Waits for the robot program to say it has started. In the 2 primary robot bases, this is called when RobotInit returns.
/// </summary>
public static void WaitForProgramStart()
{
int count = 0;
Console.WriteLine("Waiting for program to start. If you are using a Gyro, this should take about 5 seconds. " +
"Otherwise it should start immediately.");
while (!SimData.GlobalData.ProgramStarted)
{
count++;
Console.WriteLine("Waiting for program start signal: " + count);
Thread.Sleep(500);
}
}
}
}
| 31.284314 | 131 | 0.530868 | [
"MIT"
] | Team-1922/OzWPILib.NET | HAL/Simulator/SimHooks.cs | 3,193 | C# |
using System;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using CDR.DataHolder.IdentityServer.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Xunit;
using static CDR.DataHolder.IdentityServer.CdsConstants;
namespace CDR.DataHolder.IdentityServer.UnitTests
{
public class SecurityServiceTests
{
private readonly IConfiguration _configuration;
public SecurityServiceTests()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
_configuration = configuration;
}
[Fact]
public async Task Sign_PS256_Success()
{
//Arrange
var securityService = new SecurityService(_configuration);
//Create jwt token
var keys = await securityService.GetActiveSecurityKeys(SecurityAlgorithms.RsaSsaPssSha256);
var jwtSecurityToken = new JwtSecurityToken(
claims: GetClaims(),
issuer: _configuration["CTSDataHolderBrandId"],
audience: _configuration["ArrangementRevocationUri"],
expires: DateTime.UtcNow.AddMinutes(int.Parse(_configuration["DefaultExpiryMinutes"])));
jwtSecurityToken.Header["alg"] = Algorithms.Signing.PS256;
jwtSecurityToken.Header["kid"] = keys.First().Key.KeyId;
jwtSecurityToken.Header["typ"] = JwtToken.JwtType;
var plaintext = $"{jwtSecurityToken.EncodedHeader}.{jwtSecurityToken.EncodedPayload}";
var digest = Encoding.UTF8.GetBytes(plaintext);
var signature = Base64UrlTextEncoder.Encode(await securityService.Sign(jwtSecurityToken.SignatureAlgorithm, digest));
var token = $"{plaintext}.{signature}";
//Validate jwt token
var tokenHandler = new JwtSecurityTokenHandler();
//Read token
var parsedJwt = tokenHandler.ReadToken(token) as JwtSecurityToken;
//Create the certificate which has only public key
var cert = new X509Certificate2(_configuration["SigningCertificatePublic:Path"], SecurityAlgorithms.RsaSsaPssSha256);
//Get credentials from certificate
var certificateSecurityKey = new X509SecurityKey(cert);
//Set token validation parameters
var validationParameters = new TokenValidationParameters()
{
IssuerSigningKey = certificateSecurityKey,
ValidateIssuerSigningKey = true,
ValidIssuer = _configuration["CTSDataHolderBrandId"],
ValidateIssuer = true,
ValidAudience = _configuration["ArrangementRevocationUri"],
ValidateAudience = false,
ValidateLifetime = false
};
SecurityToken validatedToken;
//Act
var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
//Assert
Assert.True(validatedToken != null);
Assert.True(validatedToken.Issuer == _configuration["CTSDataHolderBrandId"]);
var iss = principal.Claims.Single(x => x.Type == "iss").Value;
var aud = principal.Claims.Single(x => x.Type == "aud").Value;
Assert.True(iss == _configuration["CTSDataHolderBrandId"]);
Assert.True(aud == _configuration["ArrangementRevocationUri"]);
}
[Fact]
public async Task Sign_PS256_InvalidToken_Failure()
{
//Arrange
var securityService = new SecurityService(_configuration);
//Create jwt token
var keys = await securityService.GetActiveSecurityKeys(SecurityAlgorithms.RsaSsaPssSha256);
var jwtSecurityToken = new JwtSecurityToken(
claims: GetClaims(),
issuer: _configuration["CTSDataHolderBrandId"],
audience: _configuration["ArrangementRevocationUri"],
expires: DateTime.UtcNow.AddMinutes(int.Parse(_configuration["DefaultExpiryMinutes"])));
jwtSecurityToken.Header["alg"] = Algorithms.Signing.PS256;
jwtSecurityToken.Header["kid"] = keys.First().Key.KeyId;
jwtSecurityToken.Header["typ"] = JwtToken.JwtType;
var plaintext = $"{jwtSecurityToken.EncodedHeader}.{jwtSecurityToken.EncodedPayload}";
var digest = Encoding.UTF8.GetBytes(plaintext);
var signature = Base64UrlTextEncoder.Encode(await securityService.Sign(jwtSecurityToken.SignatureAlgorithm, digest));
var token = $"{plaintext}.{signature}";
//Create invalid token
token = token.Replace('a', 'b');
//Validate jwt token
var tokenHandler = new JwtSecurityTokenHandler();
//Read token
var parsedJwt = tokenHandler.ReadToken(token) as JwtSecurityToken;
//Create the certificate which has only public key
var cert = new X509Certificate2(_configuration["SigningCertificatePublic:Path"], SecurityAlgorithms.RsaSsaPssSha256);
//Get credentials from certificate
var certificateSecurityKey = new X509SecurityKey(cert);
//Set token validation parameters
var validationParameters = new TokenValidationParameters()
{
IssuerSigningKey = certificateSecurityKey,
ValidateIssuerSigningKey = true,
ValidIssuer = _configuration["CTSDataHolderBrandId"],
ValidateIssuer = true,
ValidAudience = _configuration["ArrangementRevocationUri"],
ValidateAudience = false,
ValidateLifetime = false
};
try
{
SecurityToken validatedToken;
//Act
var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
}
catch (Exception ex)
{
var isInvalidSignatureError = ex.Message.StartsWith("IDX10511: Signature validation failed.");
//Assert
Assert.True(isInvalidSignatureError);
}
}
[Fact]
public async Task Sign_PS256_InvalidCertificate_Failure()
{
//Arrange
var securityService = new SecurityService(_configuration);
//Create jwt token
var keys = await securityService.GetActiveSecurityKeys(SecurityAlgorithms.RsaSsaPssSha256);
var jwtSecurityToken = new JwtSecurityToken(
claims: GetClaims(),
issuer: _configuration["CTSDataHolderBrandId"],
audience: _configuration["ArrangementRevocationUri"],
expires: DateTime.UtcNow.AddMinutes(int.Parse(_configuration["DefaultExpiryMinutes"])));
jwtSecurityToken.Header["alg"] = Algorithms.Signing.PS256;
jwtSecurityToken.Header["kid"] = keys.First().Key.KeyId;
jwtSecurityToken.Header["typ"] = JwtToken.JwtType;
var plaintext = $"{jwtSecurityToken.EncodedHeader}.{jwtSecurityToken.EncodedPayload}";
var digest = Encoding.UTF8.GetBytes(plaintext);
var signature = Base64UrlTextEncoder.Encode(await securityService.Sign(jwtSecurityToken.SignatureAlgorithm, digest));
var token = $"{plaintext}.{signature}";
//Validate jwt token
var tokenHandler = new JwtSecurityTokenHandler();
//Read token
var parsedJwt = tokenHandler.ReadToken(token) as JwtSecurityToken;
//Create the certificate which has only public key
var cert = new X509Certificate2(_configuration["InvalidSigningCertificatePublic:Path"], SecurityAlgorithms.RsaSsaPssSha256);
//Get credentials from certificate
var certificateSecurityKey = new X509SecurityKey(cert);
//Set token validation parameters
var validationParameters = new TokenValidationParameters()
{
IssuerSigningKey = certificateSecurityKey,
ValidateIssuerSigningKey = true,
ValidIssuer = _configuration["CTSDataHolderBrandId"],
ValidateIssuer = true,
ValidAudience = _configuration["ArrangementRevocationUri"],
ValidateAudience = false,
ValidateLifetime = false
};
try
{
SecurityToken validatedToken;
//Act
var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
}
catch (Exception ex)
{
var isInvalidSignatureError = ex.Message.StartsWith("IDX10501: Signature validation failed.");
//Assert
Assert.True(isInvalidSignatureError);
}
}
private Claim[] GetClaims(string subClaim = null)
{
subClaim ??= _configuration["CTSDataHolderBrandId"];
return new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, subClaim),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
}
}
}
| 41.444444 | 136 | 0.622809 | [
"MIT"
] | CDR-AmirM/mock-data-holder | Source/CDR.DataHolder.IdentityServer.UnitTests/SecurityServiceTests.cs | 9,698 | C# |
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI.WebControls;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.UserInterface.TypeEditors;
using DisplayNameAttribute=GuruComponents.Netrix.UserInterface.TypeEditors.DisplayNameAttribute;
using TE=GuruComponents.Netrix.UserInterface.TypeEditors;
namespace GuruComponents.Netrix.WebEditing.Elements
{
/// <summary>
/// This class represents the <form> element.
/// </summary>
/// <remarks>
/// <para>
/// FORM indicates the beginning of a form. All other form tags go inside
/// <FORM ...>. In its simplest use, <FORM ...> can be used without any attributes.
/// Most forms require either the
/// <see cref="GuruComponents.Netrix.WebEditing.Elements.FormElement.action">action</see> or
/// <see cref="GuruComponents.Netrix.WebEditing.Elements.FormElement.Name">Name</see> attributes to do anything meaningful.
/// </para>
/// Classes directly or indirectly inherited from
/// <see cref="GuruComponents.Netrix.WebEditing.Elements.Element">Element</see> are not intended to be instantiated
/// directly by the host application. Use the various insertion or creation methods in the base classes
/// instead. The return values are of type <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement">IElement</see>
/// and can be casted into the element just created.
/// <para>
/// Examples of how to create and modify elements with the native element classes can be found in the
/// description of other element classes.
/// </para>
/// </remarks>
public sealed class FormElement : StyledElement
{
/// <summary>
/// ACTION gives the URL of the CGI program which will process this form.
/// </summary>
[DefaultValue("")]
[CategoryAttribute("Element Behavior")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorUrl),
typeof(UITypeEditor))]
[DisplayNameAttribute()]
public string action
{
set
{
this.SetStringAttribute ("action", this.GetRelativeUrl(value));
return;
}
get
{
return this.GetRelativeUrl (this.GetStringAttribute ("action"));
}
}
/// <summary>
/// In most cases you will not need to use this attribute at all.
/// </summary>
/// <remarks>
/// The default value (i.e. if you don't use this attribute at all) is "application/x-www-form-urlencoded",
/// which is sufficient for almost any kind of form data.
/// <para>
/// The one exception is if you want to do file uploads. In that case you should use "multipart/form-data".
/// Because many people use this attribute for file upload only the definition here sets the string
/// "multipart/form-data" as the default value. This changes the behavior of the property grid.
/// </para>
/// <para>
/// The allowed values for this attribute are the following ones:
/// <list>
/// <item>"application/x-www-form-urlencoded" (default from the HTML 4.01 viewpoint)</item>
/// <item>"multipart/form-data" (default in the NetRix UI)</item>
/// <item>"text/plain"</item>
/// </list>
/// </para>
/// </remarks>
/// <seealso cref="GuruComponents.Netrix.WebEditing.Elements.EncodingType"/>
[DescriptionAttribute("")]
[DefaultValueAttribute(EncodingType.UrlEncoded)]
[CategoryAttribute("Element Behavior")]
[DisplayName()]
public EncodingType encType
{
get
{
if (!base.GetStringAttribute("encoding").Equals("multipart/form-data"))
{
return EncodingType.UrlEncoded;
}
else
{
return EncodingType.Multipart;
}
}
set
{
base.SetStringAttribute("encoding", (value != EncodingType.Multipart) ? String.Empty : "multipart/form-data");
}
}
/// <summary>
/// METHOD specifies the method of transferring the form data to the web server.
/// </summary>
/// <remarks>
/// METHOD can be either GET or POST. Each method has its advantages and disadvantages. If the method is not set
/// the browser assumes GET. But from the viewpoint of the developer the method POST is the preferred standard.
/// Therefore the NetRix UI (not supported by Light version) will assume the POST is the default value. It is still
/// recommended to set this attribute explicitly for all standard HTML pages.
/// <para>
/// Some environments will recreate this attribute automatically (just like ASP.NET does). If the editor creates
/// pages for such server driven applications there is often no need to set the attribute.
/// </para>
/// </remarks>
[DescriptionAttribute("")]
[CategoryAttribute("Element Behavior")]
[DefaultValueAttribute(FormMethod.Post)]
[DisplayName()]
public FormMethod method
{
get
{
return (FormMethod)base.GetEnumAttribute("method", FormMethod.Get);
}
set
{
base.SetEnumAttribute("method", value, FormMethod.Get);
}
}
[DescriptionAttribute("")]
[DefaultValueAttribute("")]
[CategoryAttribute("JavaScript Events")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
[ScriptingVisible()] public string ScriptOnKeyPress
{
get
{
return base.GetStringAttribute("onKeyPress");
}
set
{
base.SetStringAttribute("onKeyPress", value);
}
}
/// <summary>
/// NAME gives a name to the form.</summary>
/// <remarks>
/// This is most useful in scripting, where you frequently need to refer to the form in order to refer to the element within the form.
/// </remarks>
[DefaultValueAttribute("")]
[CategoryAttribute("Element Behavior")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName("name_Form")]
public string Name
{
get
{
return base.GetStringAttribute("name");
}
set
{
base.SetStringAttribute("name", value);
}
}
[DefaultValueAttribute("")]
[CategoryAttribute("JavaScript Events")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
[ScriptingVisible()] public string ScriptOnMouseDown
{
get
{
return base.GetStringAttribute("onMouseDown");
}
set
{
base.SetStringAttribute("onMouseDown", value);
}
}
[DescriptionAttribute("")]
[DefaultValueAttribute("")]
[CategoryAttribute("JavaScript Events")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
[ScriptingVisible()] public string ScriptOnMouseUp
{
get
{
return base.GetStringAttribute("onMouseUp");
}
set
{
base.SetStringAttribute("onMouseUp", value);
}
}
/// <summary>
/// onReset runs a script when the user resets the form.
/// </summary>
/// <remarks>
/// If onReset returns false, the reset is cancelled. Often when people hit reset they don't really mean to reset all their typing, they just hit it accidentally. onReset gives them a chance to cancel the action.
/// </remarks>
[CategoryAttribute("JavaScript Events")]
[DefaultValueAttribute("")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
[ScriptingVisible()] public string ScriptOnReset
{
get
{
return base.GetStringAttribute("onReset");
}
set
{
base.SetStringAttribute("onReset", value);
}
}
/// <summary>
/// onSubmit is a scripting event that occurs when the user attempts to submit the form to the CGI.
/// </summary>
/// <remarks>
/// onSubmit can be used to do some error checking on the form data, and to cancel the submit if an error is found.
/// </remarks>
[CategoryAttribute("JavaScript Events")]
[DescriptionAttribute("")]
[DefaultValueAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
[ScriptingVisible()] public string ScriptOnSubmit
{
get
{
return base.GetStringAttribute("onSubmit");
}
set
{
base.SetStringAttribute("onSubmit", value);
}
}
/// <include file='DocumentorIncludes.xml' path='WebEditing/Elements[@name="TargetAttribute"]'/>
[CategoryAttribute("Element Behavior")]
[TypeConverterAttribute(typeof(TargetConverter))]
[DescriptionAttribute("")]
[DefaultValueAttribute("")]
[DisplayName()]
public string target
{
get
{
return base.GetStringAttribute("target");
}
set
{
base.SetStringAttribute("target", value);
}
}
/// <summary>
/// Creates the specified element.
/// </summary>
/// <remarks>
/// The element is being created and attached to the current document, but nevertheless not visible,
/// until it's being placed anywhere within the DOM. To attach an element it's possible to either
/// use the <see cref="ElementDom"/> property of any other already placed element and refer to this
/// DOM or use the body element (<see cref="HtmlEditor.GetBodyElement"/>) and add the element there. Also, in
/// case of user interactive solutions, it's possible to add an element near the current caret
/// position, using <see cref="HtmlEditor.CreateElementAtCaret(string)"/> method.
/// <para>
/// Note: Invisible elements do neither appear in the DOM nor do they get saved.
/// </para>
/// </remarks>
/// <param name="editor">The editor this element belongs to.</param>
public FormElement(IHtmlEditor editor)
: base(@"form", editor)
{
}
internal FormElement(Interop.IHTMLElement peer, IHtmlEditor editor) : base (peer, editor)
{
}
}
}
| 34.056213 | 220 | 0.573886 | [
"MIT"
] | andydunkel/netrix | Netrix2.0/NetRixMain/NetRix/WebEditing/Elements/FormElements/FormElement.cs | 11,511 | C# |
/*
* Copyright 2019 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : ScadaSchemeCommon
* Summary : Item of the component list in the editor
*
* Author : Mikhail Shiryaev
* Created : 2017
* Modified : 2019
*/
using System;
using System.Drawing;
namespace Scada.Scheme
{
/// <summary>
/// Item of the component list in the editor
/// <para>Элемент списка компонентов в редакторе</para>
/// </summary>
public class CompItem
{
/// <summary>
/// Конструктор
/// </summary>
public CompItem(Image icon, Type compType)
: this(icon, GetDisplayName(compType), compType)
{
}
/// <summary>
/// Конструктор
/// </summary>
public CompItem(Image icon, string displayName, Type compType)
{
if (string.IsNullOrEmpty(displayName))
throw new ArgumentException("Display name must not be empty.", "displayName");
Icon = icon;
DisplayName = displayName;
CompType = compType ?? throw new ArgumentNullException("compType");
}
/// <summary>
/// Получить иконку, отображаемую в редакторе
/// </summary>
public Image Icon { get; }
/// <summary>
/// Получить наименование, отображаемое в редакторе
/// </summary>
public string DisplayName { get; }
/// <summary>
/// Получить тип компонента
/// </summary>
public Type CompType { get; }
/// <summary>
/// Получить отображаемое наименование из словарей
/// </summary>
private static string GetDisplayName(Type compType)
{
return Localization.GetDictionary(compType.FullName).GetPhrase("DisplayName", compType.Name);
}
}
}
| 28.535714 | 105 | 0.609929 | [
"Apache-2.0"
] | Arvid-new/scada | ScadaWeb/ScadaScheme/ScadaSchemeCommon/CompItem.cs | 2,596 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// mybank.credit.supplychain.creditpay.sellerunsign.query
/// </summary>
public class MybankCreditSupplychainCreditpaySellerunsignQueryRequest : IAlipayRequest<MybankCreditSupplychainCreditpaySellerunsignQueryResponse>
{
/// <summary>
/// 供应链-1688和赊呗融合-卖家解约咨询
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "mybank.credit.supplychain.creditpay.sellerunsign.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.483871 | 149 | 0.56147 | [
"MIT"
] | Msy1989/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/MybankCreditSupplychainCreditpaySellerunsignQueryRequest.cs | 2,942 | C# |
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using System;
using System.ComponentModel;
using System.Globalization;
using System.Threading.Tasks;
using Cube.Mixin.Assembly;
using Cube.Mixin.Collections;
namespace Cube
{
/* --------------------------------------------------------------------- */
///
/// Logger
///
/// <summary>
/// Provides settings and methods for logging.
/// </summary>
///
/* --------------------------------------------------------------------- */
public static class Logger
{
#region Properties
/* ----------------------------------------------------------------- */
///
/// Separator
///
/// <summary>
/// Gets or sets values to separate words.
/// </summary>
///
/* ----------------------------------------------------------------- */
public static string Separator { get; set; } = "\t";
#endregion
#region Debug
/* ----------------------------------------------------------------- */
///
/// LogDebug
///
/// <summary>
/// Outputs log as DEBUG level.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="values">User messages.</param>
///
/* ----------------------------------------------------------------- */
public static void LogDebug(this Type type, params string[] values) =>
GetCore(type).Debug(GetMessage(values));
#endregion
#region Info
/* ----------------------------------------------------------------- */
///
/// LogInfo
///
/// <summary>
/// Outputs log as INFO level.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="values">User messages.</param>
///
/* ----------------------------------------------------------------- */
public static void LogInfo(this Type type, params string[] values) =>
GetCore(type).Info(GetMessage(values));
/* ----------------------------------------------------------------- */
///
/// LogInfo
///
/// <summary>
/// Outputs system information as INFO level.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="assembly">Assembly object.</param>
///
/* ----------------------------------------------------------------- */
public static void LogInfo(this Type type, System.Reflection.Assembly assembly)
{
LogInfo(type, $"{assembly.GetProduct()} {assembly.GetVersionString(4, true)}");
LogInfo(type, $"CLR {Environment.Version} ({Environment.OSVersion})");
LogInfo(type, $"{Environment.UserName}@{Environment.MachineName} ({CultureInfo.CurrentCulture})");
}
#endregion
#region Warn
/* ----------------------------------------------------------------- */
///
/// LogWarn
///
/// <summary>
/// Outputs log as WARN level.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="values">User messages.</param>
///
/* ----------------------------------------------------------------- */
public static void LogWarn(this Type type, params string[] values) =>
GetCore(type).Warn(GetMessage(values));
/* ----------------------------------------------------------------- */
///
/// LogWarn
///
/// <summary>
/// Outputs log as WARN level.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="error">Exception object.</param>
///
/* ----------------------------------------------------------------- */
public static void LogWarn(this Type type, Exception error) =>
GetCore(type).Warn(GetErrorMessage(error));
/* ----------------------------------------------------------------- */
///
/// LogWarn
///
/// <summary>
/// Outputs log as WARN level when an exception occurs.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="action">Function to monitor.</param>
///
/* ----------------------------------------------------------------- */
public static void LogWarn(this Type type, Action action) =>
Invoke(action, e => LogWarn(type, e));
#endregion
#region Error
/* ----------------------------------------------------------------- */
///
/// LogError
///
/// <summary>
/// Outputs log as ERROR level.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="values">User messages.</param>
///
/* ----------------------------------------------------------------- */
public static void LogError(this Type type, params string[] values) =>
GetCore(type).Error(GetMessage(values));
/* ----------------------------------------------------------------- */
///
/// LogError
///
/// <summary>
/// Outputs log as ERROR level.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="error">Exception object.</param>
///
/* ----------------------------------------------------------------- */
public static void LogError(this Type type, Exception error) =>
GetCore(type).Error(GetErrorMessage(error));
/* ----------------------------------------------------------------- */
///
/// LogError
///
/// <summary>
/// Outputs log as ERROR level when an exception occurs.
/// </summary>
///
/// <param name="type">Target type information.</param>
/// <param name="action">Function to monitor.</param>
///
/* ----------------------------------------------------------------- */
public static void LogError(this Type type, Action action) =>
Invoke(action, e => LogError(type, e));
#endregion
#region Others
/* ----------------------------------------------------------------- */
///
/// ObserveTaskException
///
/// <summary>
/// Observes UnobservedTaskException exceptions and outputs to the
/// log file.
/// </summary>
///
/// <returns>Disposable object to stop to monitor.</returns>
///
/* ----------------------------------------------------------------- */
public static IDisposable ObserveTaskException()
{
TaskScheduler.UnobservedTaskException -= WhenTaskError;
TaskScheduler.UnobservedTaskException += WhenTaskError;
return Disposable.Create(() => TaskScheduler.UnobservedTaskException -= WhenTaskError);
}
#endregion
#region Implementations
/* ----------------------------------------------------------------- */
///
/// GetCore
///
/// <summary>
/// Gets the logger object.
/// </summary>
///
/* ----------------------------------------------------------------- */
private static NLog.Logger GetCore(Type type) => NLog.LogManager.GetLogger(type.FullName);
/* ----------------------------------------------------------------- */
///
/// GetMessage
///
/// <summary>
/// Gets the message from the specified arguments.
/// </summary>
///
/* ----------------------------------------------------------------- */
private static string GetMessage(string[] values) =>
values.Length == 1 ? values[0] :
values.Length > 1 ? values.Join(Separator) : string.Empty;
/* ----------------------------------------------------------------- */
///
/// GetErrorMessage
///
/// <summary>
/// Gets the error message from the specified exception.
/// </summary>
///
/* ----------------------------------------------------------------- */
private static string GetErrorMessage(Exception src) =>
src is Win32Exception we ?
$"{we.Message} (0x{we.NativeErrorCode:X8}){Environment.NewLine}{we.StackTrace}" :
src.ToString();
/* ----------------------------------------------------------------- */
///
/// Invoke
///
/// <summary>
/// Invokes the specified action.
/// </summary>
///
/* ----------------------------------------------------------------- */
private static void Invoke(Action action, Action<Exception> error)
{
try { action(); }
catch (Exception err) { error(err); }
}
/* ----------------------------------------------------------------- */
///
/// WhenTaskError
///
/// <summary>
/// Occurs when the UnobservedTaskException is raised.
/// </summary>
///
/* ----------------------------------------------------------------- */
private static void WhenTaskError(object s, UnobservedTaskExceptionEventArgs e) =>
typeof(TaskScheduler).LogError(e.Exception);
#endregion
}
}
| 35.033223 | 110 | 0.386249 | [
"Apache-2.0"
] | bubdm/Cube.Core | Libraries/Core/Sources/Logger.cs | 10,547 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Doublel.EntityAccessor.Constructs
{
public interface IUserLevelConstruct
{
int UserId { get; set; }
}
}
| 16.916667 | 43 | 0.70936 | [
"MIT"
] | Olymo/Doublel.EntityAccessor | src/Constructs/IUserLevelConstruct.cs | 205 | C# |
using System;
namespace Common
{
/// <summary>
/// コンソール アプリケーションで発生したエラーを表します。
/// </summary>
public class ConsoleException : Exception
{
/// <summary>終了コードを指定しなかった場合の規定の終了コード</summary>
public const int DefaultExitCode = 1;
/// <summary>
/// 終了コードを取得します。
/// </summary>
public int ExitCode { get; }
/// <summary>
/// 既定のエラー メッセージおよび終了コードを使用して、
/// <see cref="ConsoleException"/> の新しいインスタンスを生成します。
/// </summary>
public ConsoleException() :
this(DefaultExitCode)
{
}
/// <summary>
/// 指定した終了コードと既定のエラー メッセージを使用して、
/// <see cref="ConsoleException"/> の新しいインスタンスを生成します。
/// </summary>
/// <param name="exitCode">終了コード。</param>
public ConsoleException(int exitCode) :
base()
{
ExitCode = exitCode;
}
/// <summary>
/// 指定したエラー メッセージと既定の終了コードを使用して、
/// <see cref="ConsoleException"/> の新しいインスタンスを生成します。
/// </summary>
/// <param name="message">エラーの原因を説明するメッセージ。</param>
public ConsoleException(string message) :
this(message, DefaultExitCode, null)
{
}
/// <summary>
/// 指定したエラー メッセージおよび終了コードを使用して、
/// <see cref="ConsoleException"/> の新しいインスタンスを生成します。
/// </summary>
/// <param name="message">エラーの原因を説明するメッセージ。</param>
/// <param name="exitCode">終了コード。</param>
public ConsoleException(string message, int exitCode) :
this(message, exitCode, null)
{
}
/// <summary>
/// 指定したエラー メッセージおよびこの例外の原因となった内部例外への参照と既定の終了コードを使用して、
/// <see cref="ConsoleException"/> の新しいインスタンスを生成します。
/// </summary>
/// <param name="message">エラーの原因を説明するメッセージ。</param>
/// <param name="innerException">現在の例外の原因である例外。内部例外が指定されていない場合は null 参照。</param>
public ConsoleException(string message, Exception? innerException) :
this(message, DefaultExitCode, innerException)
{
}
/// <summary>
/// 指定したエラー メッセージ、終了コードおよびこの例外の原因となった内部例外への参照を使用して、
/// <see cref="ConsoleException"/> の新しいインスタンスを生成します。
/// </summary>
/// <param name="message">エラーの原因を説明するメッセージ。</param>
/// <param name="exitCode">終了コード。</param>
/// <param name="innerException">現在の例外の原因である例外。内部例外が指定されていない場合は null 参照。</param>
public ConsoleException(string message, int exitCode, Exception? innerException) :
base(message, innerException)
{
ExitCode = exitCode;
}
}
}
| 32.77381 | 91 | 0.551035 | [
"MIT"
] | TanaUmbreon/EarliestFuhaRanking | Common/ConsoleException.cs | 3,789 | C# |
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebShop.Product
{
public class ProductManager : DomainService, IProductManager
{
private readonly IRepository<Product, long> ProductRepository;
public ProductManager(IRepository<Product, long> productRepository)
{
ProductRepository = productRepository;
}
public async Task CreateProduct(
string Name,
decimal Price,
string Description,
long? CoverImageId,
long[] ProductImages,
long SellerId,
long? BrandId,
long[] ProductCategories
)
{
Product product = new Product
{
Name = Name,
BrandId = BrandId,
SellerId = SellerId,
Description = Description,
Price = Price
};
if (CoverImageId.HasValue)
{
ProductCoverImage cover = new ProductCoverImage
{
ImageId = CoverImageId.Value
};
product.CoverImage = cover;
}
product.ProductCategories = new List<ProductCategory>();
foreach (long category in ProductCategories)
{
ProductCategory productCategory = new ProductCategory
{
CategoryId = category
};
product.ProductCategories.Add(productCategory);
}
product.ProductImages = new List<ProductImage>();
foreach (long image in ProductImages)
{
ProductImage productImage = new ProductImage
{
ImageId = image
};
product.ProductImages.Add(productImage);
}
await ProductRepository.InsertAsync(product);
}
public async Task DeleteProduct(long id, long sellerId)
{
}
public async Task UpdateProduct(
long Id,
string Name,
decimal Price,
string Description,
long? CoverImageId,
long[] ProductImages,
long? BrandId,
long[] ProductCategories)
{
Product product = await Get(Id, 0);
product.Name = Name;
product.Price = Price;
product.Description = Description;
product.BrandId = BrandId;
if (product.CoverImageId.HasValue && product.CoverImage.ImageId != CoverImageId.Value)
{
product.CoverImage = new ProductCoverImage
{
ImageId = CoverImageId.Value
};
}
if (CoverImageId.HasValue)
{
ProductCoverImage cover = new ProductCoverImage
{
ImageId = CoverImageId.Value
};
product.CoverImage = cover;
}
product.ProductCategories = new List<ProductCategory>();
foreach (long category in ProductCategories)
{
ProductCategory productCategory = new ProductCategory
{
CategoryId = category
};
product.ProductCategories.Add(productCategory);
}
product.ProductImages = new List<ProductImage>();
foreach (long image in ProductImages)
{
ProductImage productImage = new ProductImage
{
ImageId = image
};
product.ProductImages.Add(productImage);
}
await ProductRepository.UpdateAsync(product);
}
public async Task<IQueryable<Product>> GetAll(
string keyword,
decimal? minPrice,
decimal? maxPrice,
DateTime? minCreateDate,
DateTime? maxCreateDate,
long? brandId,
long[] categories
)
{
Microsoft.EntityFrameworkCore.Query.IIncludableQueryable<Product, Domain.Brand.Brand> result = ProductRepository
.GetAll()
.Include(s => s.ProductImages)
.ThenInclude(s => s.Image)
.Include(s => s.CoverImage)
.ThenInclude(s => s.Image)
.Include(s => s.Brand);
return result;
}
public Task<IQueryable<Product>> GetAllByBrand(long brandId)
{
throw new NotImplementedException();
}
public Task<IQueryable<Product>> GetAllByCategory(long categoryId)
{
throw new NotImplementedException();
}
public Task<IQueryable<Product>> GetAllForBuyer()
{
throw new NotImplementedException();
}
public Task<IQueryable<Product>> SearchForBuyer(string searchText)
{
throw new NotImplementedException();
}
public Task<IQueryable<Product>> SearchForSeller(long sellerId, string searchText)
{
throw new NotImplementedException();
}
private async Task Commit()
{
await CurrentUnitOfWork.SaveChangesAsync();
}
public Task<IQueryable<Product>> GetAll(string keyword, decimal minPrice, decimal maxPrice, DateTime minCreateDate, DateTime maxCreateDate, long brandId, long[] categories)
{
throw new NotImplementedException();
}
public async Task<Product> Get(long id, long sellerId)
{
Product product = ProductRepository
.GetAll()
.Include(s => s.ProductImages)
.ThenInclude(s => s.Image)
.Include(s => s.CoverImage)
.ThenInclude(s => s.Image)
.Include(s => s.Brand)
.Include(s => s.ProductCategories)
.ThenInclude(s => s.Category)
.FirstOrDefault(s => s.Id == id);
return product;
}
public async Task<IQueryable<Product>> GetAllForSeller(long sellerId, string keyword)
{
return (await GetAll(keyword, null, null, null, null, null, null))
.Where(s => s.SellerId == sellerId);
}
}
}
| 30.142202 | 180 | 0.525795 | [
"MIT"
] | dangminhbk/auction | aspnet-core/src/WebShop.Core/Domain/Product/ProductManager.cs | 6,573 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301
{
using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Scope" />
/// </summary>
public partial class ScopeTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"
/// /> parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"
/// /> parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <see cref="Scope"/> type.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Scope"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="Scope" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <paramref name="sourceValue" /> parameter can be converted to the <paramref name="destinationType" />
/// parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType"
/// /> parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType" /> parameter using <paramref
/// name="formatProvider" /> and <paramref name="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="Scope" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <paramref name="sourceValue" /> parameter into an instance of <see cref="Scope" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="Scope" />.</param>
/// <returns>
/// an instance of <see cref="Scope" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IScope ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IScope).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return Scope.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return Scope.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return Scope.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 51.561644 | 277 | 0.589798 | [
"MIT"
] | AlanFlorance/azure-powershell | src/KubernetesConfiguration/generated/api/Models/Api20220301/Scope.TypeConverter.cs | 7,383 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace EspartoWorld.Data.Migrations
{
public partial class UserCoursesCourseUsers : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ApplicationUserCourse",
columns: table => new
{
CoursesId = table.Column<int>(type: "int", nullable: false),
ParticipantsId = table.Column<string>(type: "nvarchar(450)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ApplicationUserCourse", x => new { x.CoursesId, x.ParticipantsId });
table.ForeignKey(
name: "FK_ApplicationUserCourse_AspNetUsers_ParticipantsId",
column: x => x.ParticipantsId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ApplicationUserCourse_Courses_CoursesId",
column: x => x.CoursesId,
principalTable: "Courses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_ApplicationUserCourse_ParticipantsId",
table: "ApplicationUserCourse",
column: "ParticipantsId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ApplicationUserCourse");
}
}
}
| 39.826087 | 109 | 0.531659 | [
"MIT"
] | antonjekov/EspartoWorld | Data/EspartoWorld.Data/Migrations/20201127150424_User Courses Course Users.cs | 1,834 | C# |
using AutoMapper;
using TodoApp.Infrastructure.Data;
namespace TodoApp.Infrastructure.Mediator
{
public abstract class QueryHandlerBase : HandlerBase
{
protected QueryHandlerBase(ToDoContext context, IMapper mapper)
: base(context)
{
Mapper = mapper;
}
protected IMapper Mapper { get; private set; }
}
}
| 21.882353 | 71 | 0.653226 | [
"MIT"
] | fernandoescolar/netcoreconf2020 | src/Infrastructure/Mediator/QueryHandlerBase.cs | 374 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.OData.Core;
namespace Simple.OData.Client.V4.Adapter
{
#if SILVERLIGH
class ODataRequestMessage : IODataRequestMessage
#else
class ODataRequestMessage : IODataRequestMessageAsync
#endif
{
private MemoryStream _stream;
private readonly Dictionary<string, string> _headers = new Dictionary<string, string>();
public ODataRequestMessage()
{
}
public string GetHeader(string headerName)
{
string value;
return _headers.TryGetValue(headerName, out value) ? value : null;
}
public void SetHeader(string headerName, string headerValue)
{
_headers.Add(headerName, headerValue);
}
public Stream GetStream()
{
return _stream ?? (_stream = new MemoryStream());
}
public Task<Stream> GetStreamAsync()
{
var completionSource = new TaskCompletionSource<Stream>();
completionSource.SetResult(this.GetStream());
return completionSource.Task;
}
public IEnumerable<KeyValuePair<string, string>> Headers
{
get { return _headers; }
}
public Uri Url { get; set; }
public string Method { get; set; }
}
}
| 25.290909 | 96 | 0.61826 | [
"MIT"
] | GGZORR/OdataSample | Simple.OData.Client.V4.Adapter/ODataRequestMessage.cs | 1,393 | C# |
using UnityEngine;
namespace UnityToolKit
{
// Used to mark an 'int' field as a sorting layer so it will use the SortingLayerDrawer to display in the Inspector window.
public class SortingLayerAttribute : PropertyAttribute
{
}
}
| 24.7 | 127 | 0.736842 | [
"MIT"
] | suntabu/UnityToolKit | SortingLayer/SortingLayerAttribute.cs | 249 | C# |
namespace jIAnSoft.Nami.Channels
{
/// <summary>
/// Message filter delegate
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="msg"></param>
/// <returns></returns>
public delegate bool Filter<in T>(T msg);
/// <summary>
/// Callback method and parameters for a channel subscription
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISubscribable<T> : IProducerThreadSubscriber<T>
{
/// <summary>
/// Filter called from producer threads. Should be thread safe as it may be called from
/// multiple threads.
/// </summary>
Filter<T> FilterOnProducerThread { get; set; }
}
} | 30.73913 | 95 | 0.598303 | [
"MIT"
] | jiansoft/nami | Nami/Channels/ISubscribable.cs | 707 | C# |
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
//https://channel9.msdn.com/Blogs/MVP-VisualStudio-Dev/EF-Core-Quick-Starts-ASPNET-Core-in-Visual-Studio-2017
namespace ScheduleService
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
} | 26.130435 | 109 | 0.59401 | [
"MIT"
] | QuinntyneBrown/ScheduleService | Program.cs | 603 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RedCell_S : MonoBehaviour
{
public Vector2 target;
public Vector2 currentPos;
public Vector2 combineTarget;
public Vector2 velocity = Vector2.zero;
public bool move = true;
public float speed;
public float maxSpeed;
public bool combine;
public bool combining;
// Start is called before the first frame update
void Start()
{
target = new Vector2(Random.Range(-8.5f, 8.5f), Random.Range(-5f, 5f));
gameObject.name = "RedBlood_S";
}
// Update is called once per frame
void Update()
{
currentPos = transform.position;
if (move)
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
//transform.position = Vector2.SmoothDamp(transform.position, target, ref velocity, speed * Time.deltaTime, maxSpeed * Time.deltaTime);
if (currentPos == target)
{
StartCoroutine(MoveAgain());
}
if (combine)
{
StartCoroutine(Combine());
}
}
IEnumerator MoveAgain()
{
if (!combining)
{
move = false;
target = new Vector2(Random.Range(-8.5f, 8.5f), Random.Range(-5f, 5f));
yield return new WaitForSeconds(Random.Range(0.8f, 1.2f));
move = true;
}
}
IEnumerator Combine()
{
if (!combining)
{
combining = true;
yield return new WaitForSeconds(0.4f);
GetComponent<Animator>().SetTrigger("Light");
yield return new WaitForSeconds(0.3f);
target = combineTarget;
speed += 5;
}
}
}
| 27.96875 | 143 | 0.578771 | [
"MIT"
] | rafalink1996/BodyIdle | Idle Body/Assets/Scripts/RafaTestingScripts/RedCell_S.cs | 1,792 | 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 osuTK;
using osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Charts;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Multi;
using osu.Game.Screens.Select;
namespace osu.Game.Screens.Menu
{
public class MainMenu : OsuScreen
{
public const float FADE_IN_DURATION = 300;
public const float FADE_OUT_DURATION = 400;
public override bool HideOverlaysOnEnter => buttons == null || buttons.State == ButtonSystemState.Initial;
public override bool AllowBackButton => false;
public override bool AllowExternalScreenChange => true;
private Screen songSelect;
private MenuSideFlashes sideFlashes;
private ButtonSystem buttons;
[Resolved]
private GameHost host { get; set; }
[Resolved(canBeNull: true)]
private MusicController music { get; set; }
private BackgroundScreenDefault background;
protected override BackgroundScreen CreateBackground() => background;
[BackgroundDependencyLoader(true)]
private void load(DirectOverlay direct, SettingsOverlay settings)
{
if (host.CanExit)
AddInternal(new ExitConfirmOverlay { Action = this.Exit });
AddRangeInternal(new Drawable[]
{
new ParallaxContainer
{
ParallaxAmount = 0.01f,
Children = new Drawable[]
{
buttons = new ButtonSystem
{
OnChart = delegate { this.Push(new ChartListing()); },
OnEdit = delegate { this.Push(new Editor()); },
OnSolo = onSolo,
OnMulti = delegate { this.Push(new Multiplayer()); },
OnExit = this.Exit,
}
}
},
sideFlashes = new MenuSideFlashes(),
});
buttons.StateChanged += state =>
{
switch (state)
{
case ButtonSystemState.Initial:
case ButtonSystemState.Exit:
Background.FadeColour(Color4.White, 500, Easing.OutSine);
break;
default:
Background.FadeColour(OsuColour.Gray(0.8f), 500, Easing.OutSine);
break;
}
};
buttons.OnSettings = () => settings?.ToggleVisibility();
buttons.OnDirect = () => direct?.ToggleVisibility();
LoadComponentAsync(background = new BackgroundScreenDefault());
preloadSongSelect();
}
private void preloadSongSelect()
{
if (songSelect == null)
LoadComponentAsync(songSelect = new PlaySongSelect());
}
public void LoadToSolo() => Schedule(onSolo);
private void onSolo() => this.Push(consumeSongSelect());
private Screen consumeSongSelect()
{
var s = songSelect;
songSelect = null;
return s;
}
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
buttons.FadeInFromZero(500);
var track = Beatmap.Value.Track;
var metadata = Beatmap.Value.Metadata;
if (last is IntroScreen && track != null)
{
if (!track.IsRunning)
{
track.Seek(metadata.PreviewTime != -1 ? metadata.PreviewTime : 0.4f * track.Length);
track.Start();
}
}
Beatmap.ValueChanged += beatmap_ValueChanged;
}
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
buttons.SetOsuLogo(logo);
logo.FadeColour(Color4.White, 100, Easing.OutQuint);
logo.FadeIn(100, Easing.OutQuint);
if (resuming)
{
buttons.State = ButtonSystemState.TopLevel;
this.FadeIn(FADE_IN_DURATION, Easing.OutQuint);
this.MoveTo(new Vector2(0, 0), FADE_IN_DURATION, Easing.OutQuint);
sideFlashes.Delay(FADE_IN_DURATION).FadeIn(64, Easing.InQuint);
}
}
protected override void LogoSuspending(OsuLogo logo)
{
var seq = logo.FadeOut(300, Easing.InSine)
.ScaleTo(0.2f, 300, Easing.InSine);
seq.OnComplete(_ => buttons.SetOsuLogo(null));
seq.OnAbort(_ => buttons.SetOsuLogo(null));
}
private void beatmap_ValueChanged(ValueChangedEvent<WorkingBeatmap> e)
{
if (!this.IsCurrentScreen())
return;
((BackgroundScreenDefault)Background).Next();
}
public override void OnSuspending(IScreen next)
{
base.OnSuspending(next);
buttons.State = ButtonSystemState.EnteringMode;
this.FadeOut(FADE_OUT_DURATION, Easing.InSine);
this.MoveTo(new Vector2(-800, 0), FADE_OUT_DURATION, Easing.InSine);
sideFlashes.FadeOut(64, Easing.OutQuint);
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
(Background as BackgroundScreenDefault)?.Next();
//we may have consumed our preloaded instance, so let's make another.
preloadSongSelect();
if (Beatmap.Value.Track != null && music?.IsUserPaused != true)
Beatmap.Value.Track.Start();
}
public override bool OnExiting(IScreen next)
{
buttons.State = ButtonSystemState.Exit;
this.FadeOut(3000);
return base.OnExiting(next);
}
}
}
| 32.11165 | 115 | 0.53938 | [
"MIT"
] | 123tris/osu | osu.Game/Screens/Menu/MainMenu.cs | 6,410 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.AzureBackup.Helpers;
using Microsoft.Azure.Commands.AzureBackup.Models;
using Microsoft.Azure.Commands.AzureBackup.Properties;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.BackupServices.Models;
using System;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.AzureBackup.Cmdlets
{
/// <summary>
/// Get list of containers
/// </summary>
[Cmdlet(VerbsLifecycle.Register, "AzureRmBackupContainer"), OutputType(typeof(AzureRMBackupJob))]
public class RegisterAzureRMBackupContainer : AzureBackupVaultCmdletBase
{
internal const string V1VMParameterSet = "V1VM";
internal const string V2VMParameterSet = "V2VM";
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = V1VMParameterSet, HelpMessage = AzureBackupCmdletHelpMessage.VMName)]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = V2VMParameterSet, HelpMessage = AzureBackupCmdletHelpMessage.VMName)]
public string Name { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = V1VMParameterSet, HelpMessage = AzureBackupCmdletHelpMessage.ServiceName)]
public string ServiceName { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = V2VMParameterSet, HelpMessage = AzureBackupCmdletHelpMessage.RGName)]
[ResourceGroupCompleter()]
public string ResourceGroupName { get; set; }
public override void ExecuteCmdlet()
{
ExecutionBlock(() =>
{
base.ExecuteCmdlet();
string vmName = String.Empty;
string rgName = String.Empty;
string ServiceOrRG = String.Empty;
if (this.ParameterSetName == V1VMParameterSet)
{
vmName = Name;
rgName = ServiceName;
WriteDebug(String.Format(Resources.RegisteringARMVM1, vmName, rgName));
ServiceOrRG = "CloudServiceName";
}
else if (this.ParameterSetName == V2VMParameterSet)
{
vmName = Name;
rgName = ResourceGroupName;
WriteDebug(String.Format(Resources.RegisteringARMVM2, vmName, rgName));
ServiceOrRG = "ResourceGroupName";
}
else
{
throw new PSArgumentException(Resources.PSArgumentException); //TODO: PM scrub needed
}
Guid jobId = Guid.Empty;
bool isDiscoveryNeed = false;
CSMContainerResponse container = null;
isDiscoveryNeed = IsDiscoveryNeeded(vmName, rgName, out container);
if (isDiscoveryNeed)
{
WriteDebug(String.Format(Resources.VMNotDiscovered, vmName));
RefreshContainer(Vault.ResourceGroupName, Vault.Name);
isDiscoveryNeed = IsDiscoveryNeeded(vmName, rgName, out container);
if ((isDiscoveryNeed == true) || (container == null))
{
//Container is not discovered. Throw exception
string errMsg = String.Format(Resources.DiscoveryFailure, vmName, ServiceOrRG, rgName);
WriteDebug(errMsg);
ThrowTerminatingError(new ErrorRecord(new Exception(Resources.AzureVMNotFound), string.Empty, ErrorCategory.InvalidArgument, null));
}
}
//Container is discovered. Register the container
WriteDebug(String.Format(Resources.RegisteringVM, vmName));
var operationId = AzureBackupClient.RegisterContainer(Vault.ResourceGroupName, Vault.Name, container.Name);
var operationStatus = GetOperationStatus(Vault.ResourceGroupName, Vault.Name, operationId);
WriteObject(GetCreatedJobs(Vault.ResourceGroupName, Vault.Name, Vault, operationStatus.JobList).FirstOrDefault());
});
}
private void RefreshContainer(string resourceGroupName, string resourceName)
{
bool isRetryNeeded = true;
int retryCount = 1;
bool isDiscoverySuccessful = false;
string errorMessage = string.Empty;
while (isRetryNeeded && retryCount <= 3)
{
var operationId = AzureBackupClient.RefreshContainers(resourceGroupName, resourceName);
//Now wait for the operation to Complete
isRetryNeeded = WaitForDiscoveryToComplete(resourceGroupName, resourceName, operationId, out isDiscoverySuccessful, out errorMessage);
retryCount++;
}
if (!isDiscoverySuccessful)
{
ThrowTerminatingError(new ErrorRecord(new Exception(errorMessage), string.Empty, ErrorCategory.InvalidArgument, null));
}
}
private bool WaitForDiscoveryToComplete(string resourceGroupName, string resourceName, Guid operationId, out bool isDiscoverySuccessful, out string errorMessage)
{
bool isRetryNeeded = false;
var status = TrackOperation(resourceGroupName, resourceName, operationId);
errorMessage = String.Empty;
isDiscoverySuccessful = true;
//If operation fails check if retry is needed or not
if (status.Status != CSMAzureBackupOperationStatus.Succeeded.ToString())
{
isDiscoverySuccessful = false;
errorMessage = status.Error.Message;
WriteDebug(String.Format(Resources.DiscoveryFailureErrorCode, status.Error.Code));
if ((status.Error.Code == AzureBackupOperationErrorCode.DiscoveryInProgress.ToString() ||
(status.Error.Code == AzureBackupOperationErrorCode.BMSUserErrorObjectLocked.ToString())))
{
//Need to retry for this errors
isRetryNeeded = true;
WriteDebug(String.Format(Resources.RertyDiscovery));
}
}
return isRetryNeeded;
}
private bool IsDiscoveryNeeded(string vmName, string rgName, out CSMContainerResponse container)
{
bool isDiscoveryNeed = false;
ContainerQueryParameters parameters = new ContainerQueryParameters()
{
ContainerType = ManagedContainerType.IaasVM.ToString(),
FriendlyName = vmName,
Status = AzureBackupContainerRegistrationStatus.NotRegistered.ToString(),
};
//First check if container is discovered or not
var containers = AzureBackupClient.ListContainers(Vault.ResourceGroupName, Vault.Name, parameters);
WriteDebug(String.Format(Resources.ContainerCountFromService, containers.Count()));
if (containers.Count() == 0)
{
//Container is not discover
WriteDebug(Resources.ContainerNotDiscovered);
container = null;
isDiscoveryNeed = true;
}
else
{
//We can have multiple container with same friendly name.
container = containers.Where(c => ContainerHelpers.GetRGNameFromId(c.Properties.ParentContainerId).Equals(rgName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (container == null)
{
//Container is not in list of registered container
WriteDebug(String.Format(Resources.DesiredContainerNotFound));
isDiscoveryNeed = true;
}
}
return isDiscoveryNeed;
}
}
}
| 48.623656 | 185 | 0.60084 | [
"MIT"
] | AzureDataBox/azure-powershell | src/ResourceManager/AzureBackup/Commands.AzureBackup/Cmdlets/Container/RegisterAzureRMBackupContainer.cs | 8,861 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.