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 |
|---|---|---|---|---|---|---|---|---|
namespace PlacesToEat.Web.Areas.Regular.ViewModels.RestaurantFilter
{
public class RestaurantFilterRequestViewModel
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public string Search { get; set; }
public int CategoryId { get; set; }
public double? Distance { get; set; }
}
}
| 22.6875 | 68 | 0.639118 | [
"MIT"
] | tcholakov/PlacesToEat | Source/Web/PlacesToEat.Web/Areas/Regular/ViewModels/RestaurantFilter/RestaurantFilterRequestViewModel.cs | 365 | C# |
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace SimpleDialogs.Helpers
{
public sealed class KeyboardHelper
{
private static KeyboardHelper _Instance;
private readonly PropertyInfo _AlwaysShowFocusVisual;
private readonly MethodInfo _ShowFocusVisual;
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static KeyboardHelper()
{
}
private KeyboardHelper()
{
var type = typeof(KeyboardNavigation);
_AlwaysShowFocusVisual = type.GetProperty("AlwaysShowFocusVisual", BindingFlags.NonPublic | BindingFlags.Static);
_ShowFocusVisual = type.GetMethod("ShowFocusVisual", BindingFlags.NonPublic | BindingFlags.Static);
}
/// <summary>
/// Gets the KeyboardNavigationEx singleton instance.
/// </summary>
internal static KeyboardHelper Instance => _Instance ?? (_Instance = new KeyboardHelper());
/// <summary>
/// Shows the focus visual of the current focused UI element.
/// Works only together with AlwaysShowFocusVisual property.
/// </summary>
internal void ShowFocusVisualInternal()
{
_ShowFocusVisual.Invoke(null, null);
}
internal bool AlwaysShowFocusVisualInternal
{
get { return (bool)_AlwaysShowFocusVisual.GetValue(null, null); }
set { _AlwaysShowFocusVisual.SetValue(null, value, null); }
}
/// <summary>
/// Focuses the specified element and shows the focus visual style.
/// </summary>
/// <param name="element">The element which will be focused.</param>
public static void Focus(UIElement element)
{
element?.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
var keybHack = KeyboardHelper.Instance;
var oldValue = keybHack.AlwaysShowFocusVisualInternal;
keybHack.AlwaysShowFocusVisualInternal = true;
try
{
Keyboard.Focus(element);
keybHack.ShowFocusVisualInternal();
}
finally
{
keybHack.AlwaysShowFocusVisualInternal = oldValue;
}
}));
}
}
} | 33.12 | 125 | 0.602657 | [
"MIT"
] | punker76/SimpleDialogs | SimpleDialogs/Helpers/KeyboardHelper.cs | 2,486 | C# |
using GutenTag;
namespace GutenTag.Hspi
{
public class DT : Tag
{
public DT() : base("dt")
{
}
}
} | 12.272727 | 32 | 0.474074 | [
"MIT"
] | alexdresko/GutenTag.Hspi | GutenTag.Hspi/DT.cs | 135 | C# |
using System;
namespace _19_TheaThePhotographer
{
public class TheaThePhotographer
{
public static void Main(string[] args)
{
long n = long.Parse(Console.ReadLine());
long filterTime = long.Parse(Console.ReadLine());
long filterFactor = long.Parse(Console.ReadLine());
long uploadTime = long.Parse(Console.ReadLine());
long totalFilteringTime = n * filterTime;
long goodPictures = (long)(Math.Ceiling(n * filterFactor / 100d));
long totalUploadTime = goodPictures * uploadTime;
long totalTime = totalFilteringTime + totalUploadTime;
TimeSpan projectTime = TimeSpan.FromSeconds(totalTime);
Console.WriteLine("{0:D1}:{1:D2}:{2:D2}:{3:D2}",
projectTime.Days,
projectTime.Hours,
projectTime.Minutes,
projectTime.Seconds);
}
}
} | 32.689655 | 78 | 0.588608 | [
"MIT"
] | Knightwalker/KB | 02_Programming_Fundamentals/01_Programming_Fundamentals_with_C#/07_Data_Types_and_Variables_Exercise/19_thea_the_photographer.cs | 948 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using Stride.Core.Assets;
using Stride.Core.Assets.Compiler;
using Stride.Core.BuildEngine;
using Stride.Core;
using Stride.Core.IO;
using Stride.Rendering;
using Stride.Shaders.Compiler;
namespace Stride.Assets.Effect
{
/// <summary>
/// Entry point to compile an <see cref="EffectShaderAsset"/>
/// </summary>
[AssetCompiler(typeof(EffectShaderAsset), typeof(AssetCompilationContext))]
public class EffectShaderAssetCompiler : AssetCompilerBase
{
public static readonly PropertyKey<ConcurrentDictionary<string, string>> ShaderLocationsKey = new PropertyKey<ConcurrentDictionary<string, string>>("ShaderPathsKey", typeof(EffectShaderAssetCompiler));
protected override void Prepare(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result)
{
var url = EffectCompilerBase.DefaultSourceShaderFolder + "/" + Path.GetFileName(assetItem.FullPath);
var originalSourcePath = assetItem.FullPath;
result.BuildSteps = new AssetBuildStep(assetItem);
result.BuildSteps.Add(new ImportStreamCommand { SourcePath = originalSourcePath, Location = url, SaveSourcePath = true });
var shaderLocations = (ConcurrentDictionary<string, string>)context.Properties.GetOrAdd(ShaderLocationsKey, key => new ConcurrentDictionary<string, string>());
// Store directly this into the context TODO this this temporary
shaderLocations[url] = originalSourcePath;
}
}
}
| 46.214286 | 209 | 0.743946 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Assets/Effect/EffectShaderAssetCompiler.cs | 1,941 | C# |
using NtFreX.Audio.Infrastructure;
using NtFreX.Audio.Infrastructure.Container;
using NtFreX.Audio.Infrastructure.Threading;
using NtFreX.Audio.Infrastructure.Threading.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace NtFreX.Audio.Containers.Wave
{
public sealed class WaveAudioContainer : RiffContainer, IWaveAudioContainer
{
public static readonly int DefaultHeaderSize = 36;
public IReadOnlyList<UnknownSubChunk> UnknownSubChunks { get; private set; }
public FmtSubChunk FmtSubChunk { get; private set; }
public DataSubChunk DataSubChunk { get; private set; }
public WaveAudioContainer(IRiffSubChunk riffSubChunk, FmtSubChunk fmtSubChunk, DataSubChunk dataSubChunk, IReadOnlyList<UnknownSubChunk> riffSubChunks)
: base(riffSubChunk, new ISubChunk[] { fmtSubChunk, dataSubChunk }.Concat(riffSubChunks).ToList())
{
FmtSubChunk = fmtSubChunk;
DataSubChunk = dataSubChunk;
UnknownSubChunks = riffSubChunks;
}
public IAudioFormat GetFormat()
=> FmtSubChunk;
public TimeSpan GetLength()
=> TimeSpan.FromSeconds(DataSubChunk.ChunkSize / (FmtSubChunk.ByteRate * 1.0f));
public ulong GetByteLength()
=> DataSubChunk.ChunkSize;
public bool CanGetLength()
=> true;
public void Dispose() { }
public ValueTask DisposeAsync()
=> DataSubChunk.DisposeAsync();
public ISeekableAsyncEnumerable<Memory<byte>> GetAsyncAudioEnumerable(CancellationToken cancellationToken = default)
=> DataSubChunk.SelectAsync(x => x, cancellationToken);
}
} | 40.159091 | 159 | 0.702886 | [
"MIT"
] | NtFreX/NtFreX.Audio | src/NtFreX.Audio/Containers/Wave/WaveAudioContainer.cs | 1,769 | C# |
// Copyright (c) 2021-2022 Yoakke.
// Licensed under the Apache License, Version 2.0.
// Source repository: https://github.com/LanguageDev/Yoakke
using System;
namespace Yoakke.SynKit.Lexer.Attributes;
/// <summary>
/// An attribute to annotate the source character stream for the generated lexer.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class CharSourceAttribute : Attribute
{
}
| 27.125 | 81 | 0.767281 | [
"Apache-2.0"
] | LanguageDev/Yoakke | Sources/SynKit/Libraries/Lexer/Attributes/CharSourceAttribute.cs | 434 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using Hangfire;
using JetBrains.Annotations;
using Katalye.Components.Commands.Jobs;
using Katalye.Components.Common;
using Katalye.Data;
using Katalye.Data.Entities;
using MediatR;
using NLog;
using BackgroundTaskStatus = Katalye.Data.Common.BackgroundTaskStatus;
namespace Katalye.Components.Commands.Tasks
{
public static class MonitorJobExecution
{
public class Command : IRequest<Result>
{
[Required]
public string Tag { get; set; }
[Required]
public string Jid { get; set; }
[Required]
public ICollection<string> Minions { get; set; }
public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(15);
}
public class Result
{
public Guid TaskId { get; set; }
}
[UsedImplicitly]
public class Handler : IRequestHandler<Command, Result>
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IMediator _mediator;
private readonly IBackgroundJobClient _jobClient;
private readonly KatalyeContext _context;
public Handler(IMediator mediator, IBackgroundJobClient jobClient, KatalyeContext context)
{
_mediator = mediator;
_jobClient = jobClient;
_context = context;
}
public async Task<Result> Handle(Command message, CancellationToken cancellationToken)
{
using (var unit = await _context.Database.BeginTransactionAsync(cancellationToken))
{
var task = new AdHocTask
{
Tag = message.Tag,
Metadata = new Dictionary<string, string>
{
{"jid", message.Jid},
{"minions", string.Join(",", message.Minions)}
},
StartedOn = DateTimeOffset.Now,
Status = BackgroundTaskStatus.Queued
};
_context.AdHocTasks.Add(task);
await _context.SaveChangesAsync(cancellationToken);
var taskId = task.Id;
Logger.Info($"Queuing monitoring of job {message.Jid}'s execution, tracking with task {taskId}.");
_jobClient.Enqueue<Handler>(x => x.Process(message, taskId));
unit.Commit();
await _mediator.PublishEvent($"v1:tasks:{taskId}:new",
("taskId", taskId.ToString())
);
return new Result
{
TaskId = taskId
};
}
}
[UsedImplicitly]
public async Task Process(Command message, Guid taskId)
{
var task = await _context.AdHocTasks.FindAsync(taskId) ?? throw new Exception($"Task {taskId} does not exist.");
await _mediator.PublishEvent($"v1:tasks:{taskId}:processing",
("taskId", taskId.ToString())
);
task.Status = BackgroundTaskStatus.Processing;
await _context.SaveChangesAsync();
var timeoutTime = DateTimeOffset.Now + message.Timeout;
Logger.Info($"Starting monitoring session for job {message.Jid}. Timeout will occur at {timeoutTime}.");
var completed = false;
var timeout = false;
Logger.Info("Requesting job status information from minions.");
do
{
var result = await _mediator.Send(new FindJob.Command
{
Jid = message.Jid,
Minions = message.Minions
});
if (result.JobCompleted)
{
completed = true;
}
else if (result.AllMinionsTimedOut)
{
Logger.Warn("All minions timed out, assuming failure.");
timeout = true;
}
else
{
timeout = timeoutTime < DateTimeOffset.Now;
Logger.Debug($"Still waiting on completion of [{string.Join(",", result.PendingMinions)}] minions.");
if (!timeout)
{
await Task.Delay(TimeSpan.FromSeconds(10));
}
}
} while (!(completed || timeout));
if (completed)
{
Logger.Info("All minions signaled completion.");
task.Status = BackgroundTaskStatus.Succeeded;
}
else
{
Logger.Warn("Timed out while waiting for job completion.");
task.Status = BackgroundTaskStatus.Failed;
}
await _context.SaveChangesAsync();
await _mediator.PublishEvent($"v1:tasks:{taskId}:done",
("taskId", taskId.ToString())
);
}
}
}
} | 35.28481 | 128 | 0.495605 | [
"MIT"
] | Katalye/Katalye | src/Katalye.Components/Commands/Tasks/MonitorJobExecution.cs | 5,577 | C# |
using System;
using System.Text;
namespace Calamari.Integration.Processes
{
public class CommandLineException : Exception
{
public CommandLineException(
string commandLine,
int exitCode,
string additionalInformation,
string workingDirectory = null)
: base(FormatMessage(commandLine, exitCode, additionalInformation, workingDirectory))
{
}
private static string FormatMessage(
string commandLine,
int exitCode,
string additionalInformation,
string workingDirectory)
{
var sb = new StringBuilder("The following command: ");
sb.AppendLine(commandLine);
if (!String.IsNullOrEmpty(workingDirectory))
{
sb.Append("With the working directory of: ")
.AppendLine(workingDirectory);
}
sb.Append("Failed with exit code: ").Append(exitCode).AppendLine();
if (!string.IsNullOrWhiteSpace(additionalInformation))
{
sb.AppendLine(additionalInformation);
}
return sb.ToString();
}
}
} | 31.025 | 97 | 0.561644 | [
"Apache-2.0"
] | MJRichardson/Calamari | source/Calamari.Shared/Integration/Processes/CommandLineException.cs | 1,243 | C# |
namespace System
{
/// <summary>
/// Represents a method that converts an object from one type to another type.
/// </summary>
/// <typeparam name="TInput">The type of object that is to be converted.</typeparam>
/// <typeparam name="TOutput">The type the input object is to be converted to.</typeparam>
/// <param name="input">The object to convert.</param>
/// <returns>The TOutput that represents the converted TInput.</returns>
[H5.Convention(Member = H5.ConventionMember.Field | H5.ConventionMember.Method, Notation = H5.Notation.CamelCase)]
[H5.External]
[H5.Name("Converter")]
public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
} | 50.142857 | 118 | 0.695157 | [
"Apache-2.0"
] | curiosity-ai/h5 | H5/H5/System/Converter.cs | 704 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using PremierLeague.Persistence;
using System;
namespace PremierLeague.Persistence.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.0-rtm-26452")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("PremierLeague.Core.Entities.Game", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("GuestGoals");
b.Property<int>("GuestTeamId");
b.Property<int>("HomeGoals");
b.Property<int>("HomeTeamId");
b.Property<int>("Round");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate();
b.HasKey("Id");
b.HasIndex("GuestTeamId");
b.HasIndex("HomeTeamId");
b.ToTable("Games");
});
modelBuilder.Entity("PremierLeague.Core.Entities.Team", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired();
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate();
b.HasKey("Id");
b.ToTable("Teams");
});
modelBuilder.Entity("PremierLeague.Core.Entities.Game", b =>
{
b.HasOne("PremierLeague.Core.Entities.Team", "GuestTeam")
.WithMany("AwayGames")
.HasForeignKey("GuestTeamId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("PremierLeague.Core.Entities.Team", "HomeTeam")
.WithMany("HomeGames")
.HasForeignKey("HomeTeamId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 33.25 | 117 | 0.529896 | [
"MIT"
] | KienbMi/csharp_samples_ef_uow_premierleague-template | template/PremierLeague.Persistence/Migrations/ApplicationDbContextModelSnapshot.cs | 2,795 | C# |
using UnityEngine;
using System.Collections;
public class BreakObject : MonoBehaviour
{
/* public Rigidbody gameObjectRigidBody;
private Vector3 lastVelocity;
public GameObject gameObjectToBreak;
public GameObject brokenVersion;
public Material brokenTexture; //Leave blank if there isn't one
public Vector3 rotationOffset;
public Vector3 positionOffset;
private bool fractured;
public float fractureAmplification;
public float maxForce;
private void Update()
{
lastVelocity = gameObjectRigidBody.velocity;
if(Input.GetKeyDown(KeyCode.Space))
{
//fractureObject();
}
}
public void fractureObject()
{
if(!fractured)
{
fractured = true;
Quaternion objRot = Quaternion.Euler(gameObjectToBreak.transform.eulerAngles + rotationOffset);
GameObject fractureParent = GameObject.Instantiate(brokenVersion, gameObjectToBreak.transform.position + positionOffset, objRot) as GameObject;
Transform[] fragments = fractureParent.GetComponentsInChildren<Transform>();
if(brokenTexture != null)
{
setMaterialForTransformArray(fragments, brokenTexture);
}
else
{
setMaterialForTransformArray(fragments, gameObjectToBreak.GetComponent<Renderer>().material);
}
Destroy(gameObjectToBreak);
Destroy(this);
}
}
public void setMaterialForTransformArray(Transform[] array, Material mat)
{
for(int i = 1; i < array.Length; i++)
{
if(array[i].gameObject.GetComponent<fragmentMaterialException>() == false)
{
Renderer fragmentRenderer = array[i].gameObject.GetComponent<Renderer>();
fragmentRenderer.material = mat;
/* array[i].GetComponent<Rigidbody>().AddForce(lastVelocity * fractureAmplification, ForceMode.Impulse);
*//* }
}
}
private void checkForFracture(Vector3 velocity, float maxForce)
{
float totalforce = Mathf.Abs(velocity.x) + Mathf.Abs(velocity.y) + Mathf.Abs(velocity.z);
//print(totalforce);
if(totalforce > maxForce)
{
//fractureObject();
}
}
private void OnCollisionEnter(Collision collidedGameObject)
{
Rigidbody collidedGameObjectRigidbody = collidedGameObject.gameObject.GetComponent<Rigidbody>();
if(collidedGameObjectRigidbody)
{
Vector3 velocityProduct;
//print("Last Velocity: " + lastVelocity);
velocityProduct = (collidedGameObjectRigidbody.velocity += gameObjectRigidBody.velocity);
//print(velocityProduct);
checkForFracture(velocityProduct, maxForce);
}
else
{
//print("Last Velocity: " + lastVelocity);
checkForFracture(lastVelocity, maxForce);
}
}*/
} | 26.663158 | 146 | 0.744966 | [
"CC0-1.0"
] | Nelson123345/Games-Jam-8 | Games Jam 8/Assets/Scripts/BreakObject.cs | 2,535 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using Microsoft.Data.SqlClient;
namespace Microsoft.Data.Common
{
/*
internal sealed class NamedConnectionStringConverter : StringConverter {
public NamedConnectionStringConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
// Although theoretically this could be true, some people may want to just type in a name
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
StandardValuesCollection standardValues = null;
if (null != context) {
DbConnectionStringBuilder instance = (context.Instance as DbConnectionStringBuilder);
if (null != instance) {
string myProviderName = instance.GetType().Namespace;
List<string> myConnectionNames = new List<string>();
foreach(System.Configuration.ConnectionStringSetting setting in System.Configuration.ConfigurationManager.ConnectionStrings) {
if (myProviderName.EndsWith(setting.ProviderName)) {
myConnectionNames.Add(setting.ConnectionName);
}
}
standardValues = new StandardValuesCollection(myConnectionNames);
}
}
return standardValues;
}
}
*/
[Serializable()]
internal sealed class ReadOnlyCollection<T> : System.Collections.ICollection, ICollection<T>
{
private T[] _items;
internal ReadOnlyCollection(T[] items)
{
_items = items;
#if DEBUG
for (int i = 0; i < items.Length; ++i)
{
Debug.Assert(null != items[i], "null item");
}
#endif
}
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator<T>(_items);
}
public System.Collections.IEnumerator GetEnumerator()
{
return new Enumerator<T>(_items);
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
Object System.Collections.ICollection.SyncRoot
{
get { return _items; }
}
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
void ICollection<T>.Add(T value)
{
throw new NotSupportedException();
}
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<T>.Contains(T value)
{
return Array.IndexOf(_items, value) >= 0;
}
bool ICollection<T>.Remove(T value)
{
throw new NotSupportedException();
}
public int Count
{
get { return _items.Length; }
}
[Serializable()]
internal struct Enumerator<K> : IEnumerator<K>, System.Collections.IEnumerator
{ // based on List<T>.Enumerator
private K[] _items;
private int _index;
internal Enumerator(K[] items)
{
_items = items;
_index = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
return (++_index < _items.Length);
}
public K Current
{
get
{
return _items[_index];
}
}
Object System.Collections.IEnumerator.Current
{
get
{
return _items[_index];
}
}
void System.Collections.IEnumerator.Reset()
{
_index = -1;
}
}
}
internal static class DbConnectionStringBuilderUtil
{
internal static bool ConvertToBoolean(object value)
{
Debug.Assert(null != value, "ConvertToBoolean(null)");
string svalue = (value as string);
if (null != svalue)
{
if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
return false;
else
{
string tmp = svalue.Trim(); // Remove leading & trailing white space.
if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
return false;
}
return Boolean.Parse(svalue);
}
try
{
return ((IConvertible)value).ToBoolean(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e);
}
}
internal static bool ConvertToIntegratedSecurity(object value)
{
Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)");
string svalue = (value as string);
if (null != svalue)
{
if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
return false;
else
{
string tmp = svalue.Trim(); // Remove leading & trailing white space.
if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
return true;
else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
return false;
}
return Boolean.Parse(svalue);
}
try
{
return ((IConvertible)value).ToBoolean(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e);
}
}
internal static int ConvertToInt32(object value)
{
try
{
return ((IConvertible)value).ToInt32(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(Int32), e);
}
}
internal static string ConvertToString(object value)
{
try
{
return ((IConvertible)value).ToString(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw ADP.ConvertFailed(value.GetType(), typeof(String), e);
}
}
#region <<PoolBlockingPeriod Utility>>
const string PoolBlockingPeriodAutoString = "Auto";
const string PoolBlockingPeriodAlwaysBlockString = "AlwaysBlock";
const string PoolBlockingPeriodNeverBlockString = "NeverBlock";
internal static bool TryConvertToPoolBlockingPeriod(string value, out PoolBlockingPeriod result)
{
Debug.Assert(Enum.GetNames(typeof(PoolBlockingPeriod)).Length == 3, "PoolBlockingPeriod enum has changed, update needed");
Debug.Assert(null != value, "TryConvertToPoolBlockingPeriod(null,...)");
if (StringComparer.OrdinalIgnoreCase.Equals(value, PoolBlockingPeriodAutoString))
{
result = PoolBlockingPeriod.Auto;
return true;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(value, PoolBlockingPeriodAlwaysBlockString))
{
result = PoolBlockingPeriod.AlwaysBlock;
return true;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(value, PoolBlockingPeriodNeverBlockString))
{
result = PoolBlockingPeriod.NeverBlock;
return true;
}
else
{
result = DbConnectionStringDefaults.PoolBlockingPeriod;
return false;
}
}
internal static bool IsValidPoolBlockingPeriodValue(PoolBlockingPeriod value)
{
Debug.Assert(Enum.GetNames(typeof(PoolBlockingPeriod)).Length == 3, "PoolBlockingPeriod enum has changed, update needed");
return value == PoolBlockingPeriod.Auto || value == PoolBlockingPeriod.AlwaysBlock || value == PoolBlockingPeriod.NeverBlock;
}
internal static string PoolBlockingPeriodToString(PoolBlockingPeriod value)
{
Debug.Assert(IsValidPoolBlockingPeriodValue(value));
if (value == PoolBlockingPeriod.AlwaysBlock)
{
return PoolBlockingPeriodAlwaysBlockString;
}
if (value == PoolBlockingPeriod.NeverBlock)
{
return PoolBlockingPeriodNeverBlockString;
}
else
{
return PoolBlockingPeriodAutoString;
}
}
/// <summary>
/// This method attempts to convert the given value to a PoolBlockingPeriod enum. The algorithm is:
/// * if the value is from type string, it will be matched against PoolBlockingPeriod enum names only, using ordinal, case-insensitive comparer
/// * if the value is from type PoolBlockingPeriod, it will be used as is
/// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum
/// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException
///
/// in any case above, if the converted value is out of valid range, the method raises ArgumentOutOfRangeException.
/// </summary>
/// <returns>PoolBlockingPeriod value in the valid range</returns>
internal static PoolBlockingPeriod ConvertToPoolBlockingPeriod(string keyword, object value)
{
Debug.Assert(null != value, "ConvertToPoolBlockingPeriod(null)");
string sValue = (value as string);
PoolBlockingPeriod result;
if (null != sValue)
{
// We could use Enum.TryParse<PoolBlockingPeriod> here, but it accepts value combinations like
// "ReadOnly, ReadWrite" which are unwelcome here
// Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method.
if (TryConvertToPoolBlockingPeriod(sValue, out result))
{
return result;
}
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
if (TryConvertToPoolBlockingPeriod(sValue, out result))
{
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
else
{
// the value is not string, try other options
PoolBlockingPeriod eValue;
if (value is PoolBlockingPeriod)
{
// quick path for the most common case
eValue = (PoolBlockingPeriod)value;
}
else if (value.GetType().IsEnum)
{
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["PoolBlockingPeriod"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-PoolBlockingPeriod enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(PoolBlockingPeriod), null);
}
else
{
try
{
// Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
eValue = (PoolBlockingPeriod)Enum.ToObject(typeof(PoolBlockingPeriod), value);
}
catch (ArgumentException e)
{
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(PoolBlockingPeriod), e);
}
}
// ensure value is in valid range
if (IsValidPoolBlockingPeriodValue(eValue))
{
return eValue;
}
else
{
throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue);
}
}
}
#endregion
const string ApplicationIntentReadWriteString = "ReadWrite";
const string ApplicationIntentReadOnlyString = "ReadOnly";
internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result)
{
Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)");
if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadOnlyString))
{
result = ApplicationIntent.ReadOnly;
return true;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadWriteString))
{
result = ApplicationIntent.ReadWrite;
return true;
}
else
{
result = DbConnectionStringDefaults.ApplicationIntent;
return false;
}
}
internal static bool IsValidApplicationIntentValue(ApplicationIntent value)
{
Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
return value == ApplicationIntent.ReadOnly || value == ApplicationIntent.ReadWrite;
}
internal static string ApplicationIntentToString(ApplicationIntent value)
{
Debug.Assert(IsValidApplicationIntentValue(value));
if (value == ApplicationIntent.ReadOnly)
{
return ApplicationIntentReadOnlyString;
}
else
{
return ApplicationIntentReadWriteString;
}
}
/// <summary>
/// This method attempts to convert the given value tp ApplicationIntent enum. The algorithm is:
/// * if the value is from type string, it will be matched against ApplicationIntent enum names only, using ordinal, case-insensitive comparer
/// * if the value is from type ApplicationIntent, it will be used as is
/// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum
/// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException
///
/// in any case above, if the converted value is out of valid range, the method raises ArgumentOutOfRangeException.
/// </summary>
/// <returns>application intent value in the valid range</returns>
internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value)
{
Debug.Assert(null != value, "ConvertToApplicationIntent(null)");
string sValue = (value as string);
ApplicationIntent result;
if (null != sValue)
{
// We could use Enum.TryParse<ApplicationIntent> here, but it accepts value combinations like
// "ReadOnly, ReadWrite" which are unwelcome here
// Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method.
if (TryConvertToApplicationIntent(sValue, out result))
{
return result;
}
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
if (TryConvertToApplicationIntent(sValue, out result))
{
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
else
{
// the value is not string, try other options
ApplicationIntent eValue;
if (value is ApplicationIntent)
{
// quick path for the most common case
eValue = (ApplicationIntent)value;
}
else if (value.GetType().IsEnum)
{
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["ApplicationIntent"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-ApplicationIntent enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), null);
}
else
{
try
{
// Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
eValue = (ApplicationIntent)Enum.ToObject(typeof(ApplicationIntent), value);
}
catch (ArgumentException e)
{
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), e);
}
}
// ensure value is in valid range
if (IsValidApplicationIntentValue(eValue))
{
return eValue;
}
else
{
throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue);
}
}
}
const string SqlPasswordString = "Sql Password";
const string ActiveDirectoryPasswordString = "Active Directory Password";
const string ActiveDirectoryIntegratedString = "Active Directory Integrated";
const string ActiveDirectoryInteractiveString = "Active Directory Interactive";
const string ActiveDirectoryServicePrincipalString = "Active Directory Service Principal";
const string ActiveDirectoryDeviceCodeFlowString = "Active Directory Device Code Flow";
internal const string ActiveDirectoryManagedIdentityString = "Active Directory Managed Identity";
internal const string ActiveDirectoryMSIString = "Active Directory MSI";
internal const string ActiveDirectoryDefaultString = "Active Directory Default";
// const string SqlCertificateString = "Sql Certificate";
#if DEBUG
private static string[] s_supportedAuthenticationModes =
{
"NotSpecified",
"SqlPassword",
"ActiveDirectoryPassword",
"ActiveDirectoryIntegrated",
"ActiveDirectoryInteractive",
"ActiveDirectoryServicePrincipal",
"ActiveDirectoryDeviceCodeFlow",
"ActiveDirectoryManagedIdentity",
"ActiveDirectoryMSI",
"ActiveDirectoryDefault"
};
private static bool IsValidAuthenticationMethodEnum()
{
string[] names = Enum.GetNames(typeof(SqlAuthenticationMethod));
int l = s_supportedAuthenticationModes.Length;
bool listValid;
if (listValid = names.Length == l)
{
for (int i = 0; i < l; i++)
{
if (s_supportedAuthenticationModes[i].CompareTo(names[i]) != 0)
{
listValid = false;
}
}
}
return listValid;
}
#endif
internal static bool TryConvertToAuthenticationType(string value, out SqlAuthenticationMethod result)
{
#if DEBUG
Debug.Assert(IsValidAuthenticationMethodEnum(), "SqlAuthenticationMethod enum has changed, update needed");
#endif
bool isSuccess = false;
if (StringComparer.InvariantCultureIgnoreCase.Equals(value, SqlPasswordString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.SqlPassword, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.SqlPassword;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryPasswordString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryPassword, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryPassword;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryIntegratedString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryIntegrated, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryIntegrated;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryInteractiveString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryInteractive, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryInteractive;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryServicePrincipalString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryServicePrincipal, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryServicePrincipal;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryDeviceCodeFlowString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryManagedIdentityString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryManagedIdentity;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryMSIString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryMSI, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryMSI;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryDefaultString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryDefault, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.ActiveDirectoryDefault;
isSuccess = true;
}
#if ADONET_CERT_AUTH
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, SqlCertificateString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.SqlCertificate, CultureInfo.InvariantCulture))) {
result = SqlAuthenticationMethod.SqlCertificate;
isSuccess = true;
}
#endif
else
{
result = DbConnectionStringDefaults.Authentication;
}
return isSuccess;
}
/// <summary>
/// Column Encryption Setting.
/// </summary>
const string ColumnEncryptionSettingEnabledString = "Enabled";
const string ColumnEncryptionSettingDisabledString = "Disabled";
/// <summary>
/// Convert a string value to the corresponding SqlConnectionColumnEncryptionSetting.
/// </summary>
/// <param name="value"></param>
/// <param name="result"></param>
/// <returns></returns>
internal static bool TryConvertToColumnEncryptionSetting(string value, out SqlConnectionColumnEncryptionSetting result)
{
bool isSuccess = false;
if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingEnabledString))
{
result = SqlConnectionColumnEncryptionSetting.Enabled;
isSuccess = true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingDisabledString))
{
result = SqlConnectionColumnEncryptionSetting.Disabled;
isSuccess = true;
}
else
{
result = DbConnectionStringDefaults.ColumnEncryptionSetting;
}
return isSuccess;
}
/// <summary>
/// Is it a valid connection level column encryption setting ?
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
internal static bool IsValidColumnEncryptionSetting(SqlConnectionColumnEncryptionSetting value)
{
Debug.Assert(Enum.GetNames(typeof(SqlConnectionColumnEncryptionSetting)).Length == 2, "SqlConnectionColumnEncryptionSetting enum has changed, update needed");
return value == SqlConnectionColumnEncryptionSetting.Enabled || value == SqlConnectionColumnEncryptionSetting.Disabled;
}
/// <summary>
/// Convert connection level column encryption setting value to string.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
internal static string ColumnEncryptionSettingToString(SqlConnectionColumnEncryptionSetting value)
{
Debug.Assert(IsValidColumnEncryptionSetting(value), "value is not a valid connection level column encryption setting.");
switch (value)
{
case SqlConnectionColumnEncryptionSetting.Enabled:
return ColumnEncryptionSettingEnabledString;
case SqlConnectionColumnEncryptionSetting.Disabled:
return ColumnEncryptionSettingDisabledString;
default:
return null;
}
}
internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value)
{
Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 9, "SqlAuthenticationMethod enum has changed, update needed");
return value == SqlAuthenticationMethod.SqlPassword
|| value == SqlAuthenticationMethod.ActiveDirectoryPassword
|| value == SqlAuthenticationMethod.ActiveDirectoryIntegrated
|| value == SqlAuthenticationMethod.ActiveDirectoryInteractive
|| value == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal
|| value == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow
|| value == SqlAuthenticationMethod.ActiveDirectoryManagedIdentity
|| value == SqlAuthenticationMethod.ActiveDirectoryMSI
|| value == SqlAuthenticationMethod.ActiveDirectoryDefault
#if ADONET_CERT_AUTH
|| value == SqlAuthenticationMethod.SqlCertificate
#endif
|| value == SqlAuthenticationMethod.NotSpecified;
}
internal static string AuthenticationTypeToString(SqlAuthenticationMethod value)
{
Debug.Assert(IsValidAuthenticationTypeValue(value));
switch (value)
{
case SqlAuthenticationMethod.SqlPassword:
return SqlPasswordString;
case SqlAuthenticationMethod.ActiveDirectoryPassword:
return ActiveDirectoryPasswordString;
case SqlAuthenticationMethod.ActiveDirectoryIntegrated:
return ActiveDirectoryIntegratedString;
case SqlAuthenticationMethod.ActiveDirectoryInteractive:
return ActiveDirectoryInteractiveString;
case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal:
return ActiveDirectoryServicePrincipalString;
case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow:
return ActiveDirectoryDeviceCodeFlowString;
case SqlAuthenticationMethod.ActiveDirectoryManagedIdentity:
return ActiveDirectoryManagedIdentityString;
case SqlAuthenticationMethod.ActiveDirectoryMSI:
return ActiveDirectoryMSIString;
case SqlAuthenticationMethod.ActiveDirectoryDefault:
return ActiveDirectoryDefaultString;
#if ADONET_CERT_AUTH
case SqlAuthenticationMethod.SqlCertificate:
return SqlCertificateString;
#endif
default:
return null;
}
}
internal static SqlAuthenticationMethod ConvertToAuthenticationType(string keyword, object value)
{
if (null == value)
{
return DbConnectionStringDefaults.Authentication;
}
string sValue = (value as string);
SqlAuthenticationMethod result;
if (null != sValue)
{
if (TryConvertToAuthenticationType(sValue, out result))
{
return result;
}
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
if (TryConvertToAuthenticationType(sValue, out result))
{
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
else
{
// the value is not string, try other options
SqlAuthenticationMethod eValue;
if (value is SqlAuthenticationMethod)
{
// quick path for the most common case
eValue = (SqlAuthenticationMethod)value;
}
else if (value.GetType().IsEnum)
{
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["ApplicationIntent"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-ApplicationIntent enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(SqlAuthenticationMethod), null);
}
else
{
try
{
// Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
eValue = (SqlAuthenticationMethod)Enum.ToObject(typeof(SqlAuthenticationMethod), value);
}
catch (ArgumentException e)
{
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(SqlAuthenticationMethod), e);
}
}
// ensure value is in valid range
if (IsValidAuthenticationTypeValue(eValue))
{
return eValue;
}
else
{
throw ADP.InvalidEnumerationValue(typeof(SqlAuthenticationMethod), (int)eValue);
}
}
}
/// <summary>
/// Convert the provided value to a SqlConnectionColumnEncryptionSetting.
/// </summary>
/// <param name="keyword"></param>
/// <param name="value"></param>
/// <returns></returns>
internal static SqlConnectionColumnEncryptionSetting ConvertToColumnEncryptionSetting(string keyword, object value)
{
if (null == value)
{
return DbConnectionStringDefaults.ColumnEncryptionSetting;
}
string sValue = (value as string);
SqlConnectionColumnEncryptionSetting result;
if (null != sValue)
{
if (TryConvertToColumnEncryptionSetting(sValue, out result))
{
return result;
}
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
if (TryConvertToColumnEncryptionSetting(sValue, out result))
{
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
else
{
// the value is not string, try other options
SqlConnectionColumnEncryptionSetting eValue;
if (value is SqlConnectionColumnEncryptionSetting)
{
// quick path for the most common case
eValue = (SqlConnectionColumnEncryptionSetting)value;
}
else if (value.GetType().IsEnum)
{
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["SqlConnectionColumnEncryptionSetting"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-SqlConnectionColumnEncryptionSetting enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionColumnEncryptionSetting), null);
}
else
{
try
{
// Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
eValue = (SqlConnectionColumnEncryptionSetting)Enum.ToObject(typeof(SqlConnectionColumnEncryptionSetting), value);
}
catch (ArgumentException e)
{
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionColumnEncryptionSetting), e);
}
}
// ensure value is in valid range
if (IsValidColumnEncryptionSetting(eValue))
{
return eValue;
}
else
{
throw ADP.InvalidEnumerationValue(typeof(SqlConnectionColumnEncryptionSetting), (int)eValue);
}
}
}
#region <<AttestationProtocol Utility>>
/// <summary>
/// Attestation Protocol.
/// </summary>
const string AttestationProtocolHGS = "HGS";
const string AttestationProtocolAAS = "AAS";
#if ENCLAVE_SIMULATOR
const string AttestationProtocolSIM = "SIM";
#endif
/// <summary>
/// Convert a string value to the corresponding SqlConnectionAttestationProtocol
/// </summary>
/// <param name="value"></param>
/// <param name="result"></param>
/// <returns></returns>
internal static bool TryConvertToAttestationProtocol(string value, out SqlConnectionAttestationProtocol result)
{
if (StringComparer.InvariantCultureIgnoreCase.Equals(value, AttestationProtocolHGS))
{
result = SqlConnectionAttestationProtocol.HGS;
return true;
}
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, AttestationProtocolAAS))
{
result = SqlConnectionAttestationProtocol.AAS;
return true;
}
#if ENCLAVE_SIMULATOR
else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, AttestationProtocolSIM))
{
result = SqlConnectionAttestationProtocol.SIM;
return true;
}
#endif
else
{
result = DbConnectionStringDefaults.AttestationProtocol;
return false;
}
}
internal static bool IsValidAttestationProtocol(SqlConnectionAttestationProtocol value)
{
#if ENCLAVE_SIMULATOR
Debug.Assert(Enum.GetNames(typeof(SqlConnectionAttestationProtocol)).Length == 4, "SqlConnectionAttestationProtocol enum has changed, update needed");
return value == SqlConnectionAttestationProtocol.NotSpecified
|| value == SqlConnectionAttestationProtocol.HGS
|| value == SqlConnectionAttestationProtocol.AAS
|| value == SqlConnectionAttestationProtocol.SIM;
#else
Debug.Assert(Enum.GetNames(typeof(SqlConnectionAttestationProtocol)).Length == 3, "SqlConnectionAttestationProtocol enum has changed, update needed");
return value == SqlConnectionAttestationProtocol.NotSpecified
|| value == SqlConnectionAttestationProtocol.HGS
|| value == SqlConnectionAttestationProtocol.AAS;
#endif
}
internal static string AttestationProtocolToString(SqlConnectionAttestationProtocol value)
{
Debug.Assert(IsValidAttestationProtocol(value), "value is not a valid attestation protocol");
switch (value)
{
case SqlConnectionAttestationProtocol.HGS:
return AttestationProtocolHGS;
case SqlConnectionAttestationProtocol.AAS:
return AttestationProtocolAAS;
#if ENCLAVE_SIMULATOR
case SqlConnectionAttestationProtocol.SIM:
return AttestationProtocolSIM;
#endif
default:
return null;
}
}
internal static SqlConnectionAttestationProtocol ConvertToAttestationProtocol(string keyword, object value)
{
if (null == value)
{
return DbConnectionStringDefaults.AttestationProtocol;
}
string sValue = (value as string);
SqlConnectionAttestationProtocol result;
if (null != sValue)
{
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
if (TryConvertToAttestationProtocol(sValue, out result))
{
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
else
{
// the value is not string, try other options
SqlConnectionAttestationProtocol eValue;
if (value is SqlConnectionAttestationProtocol)
{
eValue = (SqlConnectionAttestationProtocol)value;
}
else if (value.GetType().IsEnum)
{
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["SqlConnectionAttestationProtocol"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-SqlConnectionAttestationProtocol enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionAttestationProtocol), null);
}
else
{
try
{
// Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
eValue = (SqlConnectionAttestationProtocol)Enum.ToObject(typeof(SqlConnectionAttestationProtocol), value);
}
catch (ArgumentException e)
{
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionAttestationProtocol), e);
}
}
if (IsValidAttestationProtocol(eValue))
{
return eValue;
}
else
{
throw ADP.InvalidEnumerationValue(typeof(SqlConnectionAttestationProtocol), (int)eValue);
}
}
}
#endregion
#region <<IPAddressPreference Utility>>
/// <summary>
/// IP Address Preference.
/// </summary>
private readonly static Dictionary<string, SqlConnectionIPAddressPreference> s_preferenceNames = new(StringComparer.InvariantCultureIgnoreCase);
static DbConnectionStringBuilderUtil()
{
foreach (SqlConnectionIPAddressPreference item in Enum.GetValues(typeof(SqlConnectionIPAddressPreference)))
{
s_preferenceNames.Add(item.ToString(), item);
}
}
/// <summary>
/// Convert a string value to the corresponding IPAddressPreference.
/// </summary>
/// <param name="value">The string representation of the enumeration name to convert.</param>
/// <param name="result">When this method returns, `result` contains an object of type `SqlConnectionIPAddressPreference` whose value is represented by `value` if the operation succeeds.
/// If the parse operation fails, `result` contains the default value of the `SqlConnectionIPAddressPreference` type.</param>
/// <returns>`true` if the value parameter was converted successfully; otherwise, `false`.</returns>
internal static bool TryConvertToIPAddressPreference(string value, out SqlConnectionIPAddressPreference result)
{
if (!s_preferenceNames.TryGetValue(value, out result))
{
result = DbConnectionStringDefaults.IPAddressPreference;
return false;
}
return true;
}
/// <summary>
/// Verifies if the `value` is defined in the expected Enum.
/// </summary>
internal static bool IsValidIPAddressPreference(SqlConnectionIPAddressPreference value)
=> value == SqlConnectionIPAddressPreference.IPv4First
|| value == SqlConnectionIPAddressPreference.IPv6First
|| value == SqlConnectionIPAddressPreference.UsePlatformDefault;
internal static string IPAddressPreferenceToString(SqlConnectionIPAddressPreference value)
=> Enum.GetName(typeof(SqlConnectionIPAddressPreference), value);
internal static SqlConnectionIPAddressPreference ConvertToIPAddressPreference(string keyword, object value)
{
if (value is null)
{
return DbConnectionStringDefaults.IPAddressPreference; // IPv4First
}
if (value is string sValue)
{
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
if (TryConvertToIPAddressPreference(sValue, out SqlConnectionIPAddressPreference result))
{
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
else
{
// the value is not string, try other options
SqlConnectionIPAddressPreference eValue;
if (value is SqlConnectionIPAddressPreference preference)
{
eValue = preference;
}
else if (value.GetType().IsEnum)
{
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["SqlConnectionIPAddressPreference"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-SqlConnectionIPAddressPreference enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionIPAddressPreference), null);
}
else
{
try
{
// Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
eValue = (SqlConnectionIPAddressPreference)Enum.ToObject(typeof(SqlConnectionIPAddressPreference), value);
}
catch (ArgumentException e)
{
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionIPAddressPreference), e);
}
}
if (IsValidIPAddressPreference(eValue))
{
return eValue;
}
else
{
throw ADP.InvalidEnumerationValue(typeof(SqlConnectionIPAddressPreference), (int)eValue);
}
}
}
#endregion
internal static bool IsValidCertificateValue(string value)
{
return string.IsNullOrEmpty(value)
|| value.StartsWith("subject:", StringComparison.OrdinalIgnoreCase)
|| value.StartsWith("sha1:", StringComparison.OrdinalIgnoreCase);
}
}
internal static class DbConnectionStringDefaults
{
// all
// internal const string NamedConnection = "";
private const string _emptyString = "";
// Odbc
internal const string Driver = _emptyString;
internal const string Dsn = _emptyString;
// OleDb
internal const bool AdoNetPooler = false;
internal const string FileName = _emptyString;
internal const int OleDbServices = ~(/*DBPROPVAL_OS_AGR_AFTERSESSION*/0x00000008 | /*DBPROPVAL_OS_CLIENTCURSOR*/0x00000004); // -13
internal const string Provider = _emptyString;
// OracleClient
internal const bool Unicode = false;
internal const bool OmitOracleConnectionName = false;
// SqlClient
internal const ApplicationIntent ApplicationIntent = Microsoft.Data.SqlClient.ApplicationIntent.ReadWrite;
internal const string ApplicationName = "Framework Microsoft SqlClient Data Provider";
internal const string AttachDBFilename = _emptyString;
internal const int CommandTimeout = 30;
internal const int ConnectTimeout = 15;
internal const bool ConnectionReset = true;
internal const bool ContextConnection = false;
internal const string CurrentLanguage = _emptyString;
internal const string DataSource = _emptyString;
internal const bool Encrypt = false;
internal const bool Enlist = true;
internal const string FailoverPartner = _emptyString;
internal const string InitialCatalog = _emptyString;
internal const bool IntegratedSecurity = false;
internal const int LoadBalanceTimeout = 0; // default of 0 means don't use
internal const bool MultipleActiveResultSets = false;
internal const bool MultiSubnetFailover = false;
internal static readonly bool TransparentNetworkIPResolution = LocalAppContextSwitches.DisableTNIRByDefault ? false : true;
internal const int MaxPoolSize = 100;
internal const int MinPoolSize = 0;
internal const string NetworkLibrary = _emptyString;
internal const int PacketSize = 8000;
internal const string Password = _emptyString;
internal const bool PersistSecurityInfo = false;
internal const bool Pooling = true;
internal const bool TrustServerCertificate = false;
internal const string TypeSystemVersion = "Latest";
internal const string UserID = _emptyString;
internal const bool UserInstance = false;
internal const bool Replication = false;
internal const string WorkstationID = _emptyString;
internal const string TransactionBinding = "Implicit Unbind";
internal const int ConnectRetryCount = 1;
internal const int ConnectRetryInterval = 10;
internal static readonly SqlAuthenticationMethod Authentication = SqlAuthenticationMethod.NotSpecified;
internal static readonly SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Disabled;
internal const string EnclaveAttestationUrl = _emptyString;
internal const SqlConnectionAttestationProtocol AttestationProtocol = SqlConnectionAttestationProtocol.NotSpecified;
internal const SqlConnectionIPAddressPreference IPAddressPreference = SqlConnectionIPAddressPreference.IPv4First;
internal const string Certificate = _emptyString;
internal const PoolBlockingPeriod PoolBlockingPeriod = SqlClient.PoolBlockingPeriod.Auto;
}
internal static class DbConnectionOptionKeywords
{
// Odbc
internal const string Driver = "driver";
internal const string Pwd = "pwd";
internal const string UID = "uid";
// OleDb
internal const string DataProvider = "data provider";
internal const string ExtendedProperties = "extended properties";
internal const string FileName = "file name";
internal const string Provider = "provider";
internal const string RemoteProvider = "remote provider";
// common keywords (OleDb, OracleClient, SqlClient)
internal const string Password = "password";
internal const string UserID = "user id";
}
internal static class DbConnectionStringKeywords
{
// all
// internal const string NamedConnection = "Named Connection";
// Odbc
internal const string Driver = "Driver";
internal const string Dsn = "Dsn";
internal const string FileDsn = "FileDsn";
internal const string SaveFile = "SaveFile";
// OleDb
internal const string FileName = "File Name";
internal const string OleDbServices = "OLE DB Services";
internal const string Provider = "Provider";
// OracleClient
internal const string Unicode = "Unicode";
internal const string OmitOracleConnectionName = "Omit Oracle Connection Name";
// SqlClient
internal const string ApplicationIntent = "Application Intent";
internal const string ApplicationName = "Application Name";
internal const string AttachDBFilename = "AttachDbFilename";
internal const string ConnectTimeout = "Connect Timeout";
internal const string CommandTimeout = "Command Timeout";
internal const string ConnectionReset = "Connection Reset";
internal const string ContextConnection = "Context Connection";
internal const string CurrentLanguage = "Current Language";
internal const string Encrypt = "Encrypt";
internal const string FailoverPartner = "Failover Partner";
internal const string InitialCatalog = "Initial Catalog";
internal const string MultipleActiveResultSets = "Multiple Active Result Sets";
internal const string MultiSubnetFailover = "Multi Subnet Failover";
internal const string TransparentNetworkIPResolution = "Transparent Network IP Resolution";
internal const string NetworkLibrary = "Network Library";
internal const string PacketSize = "Packet Size";
internal const string Replication = "Replication";
internal const string TransactionBinding = "Transaction Binding";
internal const string TrustServerCertificate = "Trust Server Certificate";
internal const string TypeSystemVersion = "Type System Version";
internal const string UserInstance = "User Instance";
internal const string WorkstationID = "Workstation ID";
internal const string ConnectRetryCount = "Connect Retry Count";
internal const string ConnectRetryInterval = "Connect Retry Interval";
internal const string Authentication = "Authentication";
internal const string Certificate = "Certificate";
internal const string ColumnEncryptionSetting = "Column Encryption Setting";
internal const string EnclaveAttestationUrl = "Enclave Attestation Url";
internal const string AttestationProtocol = "Attestation Protocol";
internal const string IPAddressPreference = "IP Address Preference";
internal const string PoolBlockingPeriod = "Pool Blocking Period";
// common keywords (OleDb, OracleClient, SqlClient)
internal const string DataSource = "Data Source";
internal const string IntegratedSecurity = "Integrated Security";
internal const string Password = "Password";
internal const string PersistSecurityInfo = "Persist Security Info";
internal const string UserID = "User ID";
// managed pooling (OracleClient, SqlClient)
internal const string Enlist = "Enlist";
internal const string LoadBalanceTimeout = "Load Balance Timeout";
internal const string MaxPoolSize = "Max Pool Size";
internal const string Pooling = "Pooling";
internal const string MinPoolSize = "Min Pool Size";
}
internal static class DbConnectionStringSynonyms
{
//internal const string ApplicationName = APP;
internal const string APP = "app";
// internal const string IPAddressPreference = IPADDRESSPREFERENCE;
internal const string IPADDRESSPREFERENCE = "ipaddresspreference";
//internal const string ApplicationIntent = APPLICATIONINTENT;
internal const string APPLICATIONINTENT = "applicationintent";
//internal const string AttachDBFilename = EXTENDEDPROPERTIES+","+INITIALFILENAME;
internal const string EXTENDEDPROPERTIES = "extended properties";
internal const string INITIALFILENAME = "initial file name";
//internal const string ConnectTimeout = CONNECTIONTIMEOUT+","+TIMEOUT;
internal const string CONNECTIONTIMEOUT = "connection timeout";
internal const string TIMEOUT = "timeout";
//internal const string ConnectRetryCount = CONNECTRETRYCOUNT;
internal const string CONNECTRETRYCOUNT = "connectretrycount";
//internal const string ConnectRetryInterval = CONNECTRETRYINTERVAL;
internal const string CONNECTRETRYINTERVAL = "connectretryinterval";
//internal const string CurrentLanguage = LANGUAGE;
internal const string LANGUAGE = "language";
//internal const string OraDataSource = SERVER;
//internal const string SqlDataSource = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS;
internal const string ADDR = "addr";
internal const string ADDRESS = "address";
internal const string SERVER = "server";
internal const string NETWORKADDRESS = "network address";
//internal const string InitialCatalog = DATABASE;
internal const string DATABASE = "database";
//internal const string IntegratedSecurity = TRUSTEDCONNECTION;
internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in everett
//internal const string LoadBalanceTimeout = ConnectionLifetime;
internal const string ConnectionLifetime = "connection lifetime";
//internal const string MultipleActiveResultSets = MULTIPLEACTIVERESULTSETS;
internal const string MULTIPLEACTIVERESULTSETS = "multipleactiveresultsets";
//internal const string MultiSubnetFailover = MULTISUBNETFAILOVER;
internal const string MULTISUBNETFAILOVER = "multisubnetfailover";
//internal const string NetworkLibrary = NET+","+NETWORK;
internal const string NET = "net";
internal const string NETWORK = "network";
//internal const string PoolBlockingPeriod = POOLBLOCKINGPERIOD;
internal const string POOLBLOCKINGPERIOD = "poolblockingperiod";
internal const string WorkaroundOracleBug914652 = "Workaround Oracle Bug 914652";
//internal const string Password = Pwd;
internal const string Pwd = "pwd";
//internal const string PersistSecurityInfo = PERSISTSECURITYINFO;
internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
//internal const string TrustServerCertificate = TRUSTSERVERCERTIFICATE;
internal const string TRUSTSERVERCERTIFICATE = "trustservercertificate";
//internal const string TransparentNetworkIPResolution = TRANSPARENTNETWORKIPRESOLUTION;
internal const string TRANSPARENTNETWORKIPRESOLUTION = "transparentnetworkipresolution";
//internal const string UserID = UID+","+User;
internal const string UID = "uid";
internal const string User = "user";
//internal const string WorkstationID = WSID;
internal const string WSID = "wsid";
}
}
| 44.497118 | 195 | 0.602717 | [
"MIT"
] | JPaja/SqlClient | src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionStringCommon.cs | 61,762 | C# |
using System.Threading.Tasks;
using NClient.Annotations;
using NClient.Annotations.Http;
using NClient.Providers.Transport;
namespace NClient.Sandbox.FileService.Facade
{
[UseVersion("3.0")]
[Header("client", "NClient")]
public interface IFileClient : IFileController
{
[Override]
new Task<IResponse> GetTextFileAsync([RouteParam] long id);
[Override]
new Task<IResponse> GetImageAsync(long id);
}
}
| 23.947368 | 67 | 0.694505 | [
"Apache-2.0"
] | nclient/NClient | sandbox/NClient.Sandbox.FileService.Facade/IFileClient.cs | 457 | C# |
// Copyright 2021 Niantic, Inc. All Rights Reserved.
using System.Collections.ObjectModel;
using Niantic.ARDK.AR.Anchors;
using Niantic.ARDK.Utilities;
namespace Niantic.ARDK.AR.ARSessionEventArgs
{
public struct AnchorsMergedArgs:
IArdkEventArgs
{
public AnchorsMergedArgs(IARAnchor parent, IARAnchor[] children):
this()
{
Parent = parent;
Children = new ReadOnlyCollection<IARAnchor>(children);
}
public IARAnchor Parent { get; private set; }
public ReadOnlyCollection<IARAnchor> Children { get; private set; }
}
}
| 23.75 | 71 | 0.721053 | [
"MIT"
] | AmerAli94/ARSample_Niantic | Assets/ARDK/AR/ARSessionEventArgs/AnchorsMergedArgs.cs | 570 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis.Api
{
internal interface ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor
{
bool CanSuppressSelectedEntries { get; }
bool CanSuppressSelectedEntriesInSource { get; }
bool CanSuppressSelectedEntriesInSuppressionFiles { get; }
bool CanRemoveSuppressionsSelectedEntries { get; }
}
}
| 37.823529 | 99 | 0.772939 | [
"MIT"
] | 333fred/roslyn | src/VisualStudio/Core/Def/ExternalAccess/LegacyCodeAnalysis/Api/ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor.cs | 645 | C# |
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 Topshelf
{
public enum TopshelfExitCode
{
Ok = 0,
SudoRequired = 2,
NotRunningOnWindows = 11,
ServiceAlreadyRunning = 1056,
ServiceNotRunning = 1062,
ServiceControlRequestFailed = 1064,
AbnormalExit = 1067,
ServiceAlreadyInstalled = 1242,
ServiceNotInstalled = 1243
}
}
| 36.464286 | 83 | 0.680705 | [
"Apache-2.0"
] | bodrick/Topshelf | src/Topshelf/TopshelfExitCode.cs | 1,021 | C# |
using Xunit.Abstractions;
#if XUNIT_FRAMEWORK
namespace Xunit.Sdk
#else
namespace Xunit
#endif
{
/// <summary>
/// Default implementation of <see cref="ITestCaseStarting"/>.
/// </summary>
public class TestCaseStarting : TestCaseMessage, ITestCaseStarting
{
/// <summary>
/// Initializes a new instance of the <see cref="TestCaseStarting"/> class.
/// </summary>
public TestCaseStarting(ITestCase testCase)
: base(testCase) { }
}
} | 25.05 | 83 | 0.638723 | [
"Apache-2.0"
] | 0x0309/xunit | src/messages/TestCaseStarting.cs | 503 | C# |
using System;
using IQFeed.CSharpApiClient.Lookup.Historical.Messages;
using IQFeed.CSharpApiClient.Tests.Common;
using IQFeed.CSharpApiClient.Tests.Common.TestCases;
using NUnit.Framework;
namespace IQFeed.CSharpApiClient.Tests.Lookup.Historical.Messages
{
public class DailyWeeklyMonthlyMessageTests
{
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_DailyWeeklyMonthlyMessage_Culture_Independent(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "2018-04-27,164.3300,160.6300,164.0000,162.3200,35655839,0,";
// Act
var dailyWeeklyMonthlyMessage = new DailyWeeklyMonthlyMessage(new DateTime(2018, 04, 27), 164.33, 160.63, 164, 162.32, 35655839, 0);
var dailyWeeklyMonthlyMessageFromValues = DailyWeeklyMonthlyMessage.Parse(message);
// Assert
Assert.AreEqual(dailyWeeklyMonthlyMessage, dailyWeeklyMonthlyMessageFromValues);
}
[Test]
public void Should_Parse_DailyWeeklyMonthlyMessage_With_Large_PeriodVolume()
{
// Arrange
var message = $"2018-04-27,164.3300,160.6300,164.0000,162.3200,{long.MaxValue},0,";
// Act
var dailyWeeklyMonthlyMessage = DailyWeeklyMonthlyMessage.Parse(message);
// Assert
Assert.AreEqual(dailyWeeklyMonthlyMessage.PeriodVolume, long.MaxValue);
}
}
} | 39.410256 | 144 | 0.693559 | [
"MIT"
] | gaorufeng/IQFeed.CSharpApiClient | src/IQFeed.CSharpApiClient.Tests/Lookup/Historical/Messages/DailyWeeklyMonthlyMessageTests.cs | 1,539 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace LinqToDB.Data
{
public class DataReader : IDisposable
{
public CommandInfo? CommandInfo { get; set; }
public IDataReader? Reader { get; set; }
internal int ReadNumber { get; set; }
private DateTime StartedOn { get; } = DateTime.UtcNow;
private Stopwatch Stopwatch { get; } = Stopwatch.StartNew();
public void Dispose()
{
if (Reader != null)
{
Reader.Dispose();
if (CommandInfo?.DataConnection.TraceSwitchConnection.TraceInfo == true)
{
CommandInfo.DataConnection.OnTraceConnection(new TraceInfo(CommandInfo.DataConnection, TraceInfoStep.Completed)
{
TraceLevel = TraceLevel.Info,
Command = CommandInfo.DataConnection.Command,
StartTime = StartedOn,
ExecutionTime = Stopwatch.Elapsed,
RecordsAffected = ReadNumber,
});
}
}
}
#region Query with object reader
public IEnumerable<T> Query<T>(Func<IDataReader,T> objectReader)
{
while (Reader!.Read())
yield return objectReader(Reader);
}
#endregion
#region Query
public IEnumerable<T> Query<T>()
{
if (ReadNumber != 0)
if (!Reader!.NextResult())
return Enumerable.Empty<T>();
ReadNumber++;
return CommandInfo!.ExecuteQuery<T>(Reader!, CommandInfo.DataConnection.Command.CommandText + "$$$" + ReadNumber);
}
#endregion
#region Query with template
public IEnumerable<T> Query<T>(T template)
{
return Query<T>();
}
#endregion
#region Execute scalar
[return: MaybeNull]
public T Execute<T>()
{
if (ReadNumber != 0)
if (!Reader!.NextResult())
return default(T);
ReadNumber++;
var sql = CommandInfo!.DataConnection.Command.CommandText + "$$$" + ReadNumber;
return CommandInfo.ExecuteScalar<T>(Reader!, sql);
}
#endregion
}
}
| 22.857143 | 118 | 0.630288 | [
"MIT"
] | Feroks/linq2db | Source/LinqToDB/Data/DataReader.cs | 1,992 | C# |
namespace org.apache.lucene.analysis.cz
{
/*
* 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 org.apache.lucene.analysis.util;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static org.apache.lucene.analysis.util.StemmerUtil.*;
/// <summary>
/// Light Stemmer for Czech.
/// <para>
/// Implements the algorithm described in:
/// <i>
/// Indexing and stemming approaches for the Czech language
/// </i>
/// http://portal.acm.org/citation.cfm?id=1598600
/// </para>
/// </summary>
public class CzechStemmer
{
/// <summary>
/// Stem an input buffer of Czech text.
/// </summary>
/// <param name="s"> input buffer </param>
/// <param name="len"> length of input buffer </param>
/// <returns> length of input buffer after normalization
///
/// <para><b>NOTE</b>: Input is expected to be in lowercase,
/// but with diacritical marks</para> </returns>
public virtual int stem(char[] s, int len)
{
len = removeCase(s, len);
len = removePossessives(s, len);
if (len > 0)
{
len = normalize(s, len);
}
return len;
}
private int removeCase(char[] s, int len)
{
if (len > 7 && StemmerUtil.EndsWith(s, len, "atech"))
{
return len - 5;
}
if (len > 6 && (StemmerUtil.EndsWith(s, len,"ětem") || StemmerUtil.EndsWith(s, len,"etem") || StemmerUtil.EndsWith(s, len,"atům")))
{
return len - 4;
}
if (len > 5 && (StemmerUtil.EndsWith(s, len, "ech") || StemmerUtil.EndsWith(s, len, "ich") || StemmerUtil.EndsWith(s, len, "ích") || StemmerUtil.EndsWith(s, len, "ého") || StemmerUtil.EndsWith(s, len, "ěmi") || StemmerUtil.EndsWith(s, len, "emi") || StemmerUtil.EndsWith(s, len, "ému") || StemmerUtil.EndsWith(s, len, "ěte") || StemmerUtil.EndsWith(s, len, "ete") || StemmerUtil.EndsWith(s, len, "ěti") || StemmerUtil.EndsWith(s, len, "eti") || StemmerUtil.EndsWith(s, len, "ího") || StemmerUtil.EndsWith(s, len, "iho") || StemmerUtil.EndsWith(s, len, "ími") || StemmerUtil.EndsWith(s, len, "ímu") || StemmerUtil.EndsWith(s, len, "imu") || StemmerUtil.EndsWith(s, len, "ách") || StemmerUtil.EndsWith(s, len, "ata") || StemmerUtil.EndsWith(s, len, "aty") || StemmerUtil.EndsWith(s, len, "ých") || StemmerUtil.EndsWith(s, len, "ama") || StemmerUtil.EndsWith(s, len, "ami") || StemmerUtil.EndsWith(s, len, "ové") || StemmerUtil.EndsWith(s, len, "ovi") || StemmerUtil.EndsWith(s, len, "ými")))
{
return len - 3;
}
if (len > 4 && (StemmerUtil.EndsWith(s, len, "em") || StemmerUtil.EndsWith(s, len, "es") || StemmerUtil.EndsWith(s, len, "ém") || StemmerUtil.EndsWith(s, len, "ím") || StemmerUtil.EndsWith(s, len, "ům") || StemmerUtil.EndsWith(s, len, "at") || StemmerUtil.EndsWith(s, len, "ám") || StemmerUtil.EndsWith(s, len, "os") || StemmerUtil.EndsWith(s, len, "us") || StemmerUtil.EndsWith(s, len, "ým") || StemmerUtil.EndsWith(s, len, "mi") || StemmerUtil.EndsWith(s, len, "ou")))
{
return len - 2;
}
if (len > 3)
{
switch (s[len - 1])
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'ů':
case 'y':
case 'á':
case 'é':
case 'í':
case 'ý':
case 'ě':
return len - 1;
}
}
return len;
}
private int removePossessives(char[] s, int len)
{
if (len > 5 && (StemmerUtil.EndsWith(s, len, "ov") || StemmerUtil.EndsWith(s, len, "in") || StemmerUtil.EndsWith(s, len, "ův")))
{
return len - 2;
}
return len;
}
private int normalize(char[] s, int len)
{
if (StemmerUtil.EndsWith(s, len, "čt")) // čt -> ck
{
s[len - 2] = 'c';
s[len - 1] = 'k';
return len;
}
if (StemmerUtil.EndsWith(s, len, "št")) // št -> sk
{
s[len - 2] = 's';
s[len - 1] = 'k';
return len;
}
switch (s[len - 1])
{
case 'c': // [cč] -> k
case 'č':
s[len - 1] = 'k';
return len;
case 'z': // [zž] -> h
case 'ž':
s[len - 1] = 'h';
return len;
}
if (len > 1 && s[len - 2] == 'e')
{
s[len - 2] = s[len - 1]; // e* > *
return len - 1;
}
if (len > 2 && s[len - 2] == 'ů')
{
s[len - 2] = 'o'; // *ů* -> *o*
return len;
}
return len;
}
}
} | 31.414013 | 991 | 0.601176 | [
"Apache-2.0"
] | CerebralMischief/lucenenet | src/Lucene.Net.Analysis.Common/Analysis/Cz/CzechStemmer.cs | 4,971 | C# |
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
namespace Orleans.EntityFrameworkCore.Migrations
{
[DbContext(typeof(OrleansEFContext))]
[Migration(nameof(OrleansEFMigration001))]
public partial class OrleansEFMigration001 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "orleans_ef_storage",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
primary_key = table.Column<string>(nullable: false),
type = table.Column<string>(nullable: false),
data = table.Column<string>(nullable: false),
etag = table.Column<string>(nullable: false),
created_at = table.Column<DateTime>(nullable: false),
updated_at = table.Column<DateTime>(nullable: false),
},
constraints: table =>
{
table.PrimaryKey("PK_orleans_ef_storage", a => new
{
a.id,
});
}
);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
} | 35.589744 | 73 | 0.542507 | [
"MIT"
] | rdlaitila/Orleans.EntityFrameworkCore | src/Orleans.EntityFrameworkCore/Migrations/OrleansEFMigration001.cs | 1,388 | C# |
using Android.App;
using Android.App.Usage;
using Android.Content.PM;
using Sensus.Probes.Apps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Sensus.Android.Probes.Apps
{
public class AndroidApplicationUsageStatsProbe : ApplicationUsageStatsProbe
{
AndroidApplicationUsageManager _manager = null;
protected async override Task InitializeAsync()
{
await base.InitializeAsync();
_manager = new AndroidApplicationUsageManager(this);
await _manager.CheckPermission();
}
protected async override Task ProtectedStopAsync()
{
await base.ProtectedStopAsync();
}
protected override Task<List<Datum>> PollAsync(CancellationToken cancellationToken)
{
long now = Java.Lang.JavaSystem.CurrentTimeMillis();
long startTime = now - PollingSleepDurationMS;
List<UsageStats> usageStats = _manager.Manager.QueryAndAggregateUsageStats(startTime, now).Select(x => x.Value).ToList();
List<Datum> data = new List<Datum>();
foreach(UsageStats appStats in usageStats)
{
string applicationName = Application.Context.PackageManager.GetApplicationLabel(Application.Context.PackageManager.GetApplicationInfo(appStats.PackageName, PackageInfoFlags.MatchDefaultOnly));
data.Add(new ApplicationUsageStatsDatum(appStats.PackageName, applicationName, DateTimeOffset.FromUnixTimeMilliseconds(appStats.FirstTimeStamp), DateTimeOffset.FromUnixTimeMilliseconds(appStats.LastTimeStamp), DateTimeOffset.FromUnixTimeMilliseconds(appStats.LastTimeUsed), TimeSpan.FromMilliseconds(appStats.TotalTimeInForeground), DateTimeOffset.UtcNow));
}
return Task.FromResult(data);
}
}
}
| 34.612245 | 361 | 0.801297 | [
"Apache-2.0"
] | TeachmanLab/sensus | Sensus.Android.Shared/Probes/Apps/AndroidApplicationUsageStatsProbe.cs | 1,698 | C# |
using System;
using System.Diagnostics;
namespace SerializationInspections.Sample.QuickFixes.MissingSerializationAttribute
{
[DebuggerDisplay("x")]
[CLSCompliant(true)]
public class ExceptionWithExistingAttributes{caret} : Exception
{
}
} | 22.727273 | 82 | 0.796 | [
"MIT"
] | ulrichb/SerializablilityInspections | Src/SerializationInspections.Plugin.Tests/test/data/QuickFixes/MissingSerializationAttribute/ExceptionWithExistingAttributes.cs | 252 | C# |
using System;
using System.Threading.Tasks;
namespace RobotControl.ClassLibrary
{
public class RobotControl : RobotControlBase
{
private Action<Exception> onExceptionCallback;
IState state;
IObjectDetector objectDetector;
ICameraCapturer cameraCapturer;
IRobotCommunicationHandler robotCommunicationHandler;
IRobotLogic robotLogic;
public static IMediator Mediator = new Mediator();
private string[] LabelsOfObjectsToDetect;
public RobotControl()
: base(Mediator)
{
}
public async Task InitializeAsync(
string[] labelsOfObjectsToDetect,
int baudRate,
bool UseFakeObjectDetector = false,
bool UseFakeCameraCapturer = false,
bool UseFakeSpeechCommandListener = false,
bool UseFakeSpeaker = false,
bool UseFakeRobotCommunicationHandler = false,
bool UseFakeRobotLogic = false,
float LMultiplier = 1.0f,
float RMultiplier = 1.0f
)
{
await Task.Run(() =>
{
LabelsOfObjectsToDetect = new string[labelsOfObjectsToDetect.Length];
Array.Copy(labelsOfObjectsToDetect, LabelsOfObjectsToDetect, labelsOfObjectsToDetect.Length);
ISerialPort serialPort = UseFakeRobotCommunicationHandler ? (ISerialPort)new SerialPortFake() : new SerialPortImpl();
state = new State(Mediator);
objectDetector = new ObjectDetector(Mediator, UseFakeObjectDetector, "TinyYolo2_model.onnx", LabelsOfObjectsToDetect);
cameraCapturer = new CameraCapturer(Mediator, UseFakeCameraCapturer);
robotCommunicationHandler = new RobotCommunicationHandler(Mediator, serialPort, baudRate);
robotLogic = new RobotLogic(Mediator, UseFakeRobotLogic, state);
robotLogic.SetMotorCalibrationValues(LMultiplier, RMultiplier);
Mediator.AddTarget((IPubSubBase)robotCommunicationHandler);
Mediator.AddTarget((IPubSubBase)robotLogic);
Mediator.AddTarget((IPubSubBase)state);
Mediator.AddTarget((IPubSubBase)objectDetector);
Mediator.AddTarget((IPubSubBase)cameraCapturer);
});
}
public async Task InitializeBasicAsync(int baudRate)
{
await Task.Run(() =>
{
ISerialPort serialPort = new SerialPortImpl();
state = new State(Mediator);
robotCommunicationHandler = new RobotCommunicationHandler(Mediator, serialPort, baudRate);
robotLogic = new RobotLogic(Mediator, false, state);
Mediator.AddTarget((IPubSubBase)robotCommunicationHandler);
Mediator.AddTarget((IPubSubBase)robotLogic);
Mediator.AddTarget((IPubSubBase)state);
});
}
public override void Stop()
{
Mediator.Stop();
Mediator.WaitWhileStillRunning();
base.Stop();
}
public void BlockEvent(EventName eventName) => Mediator.BlockEvent(eventName);
public void UnblockEvent(EventName eventName) => Mediator.UnblockEvent(eventName);
}
}
| 38.639535 | 134 | 0.629552 | [
"MIT"
] | LucidioK/RobotControl01 | RobotControl.ClassLibrary.Standard/RobotControl.cs | 3,325 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Unity.Entities;
using UnityEditor.VisualScripting.Editor.SmartSearch;
using UnityEditor.VisualScripting.GraphViewModel;
using UnityEditor.VisualScripting.Model.Translators;
using UnityEditor.VisualScripting.SmartSearch;
using UnityEngine;
namespace UnityEditor.VisualScripting.Model.Stencils
{
[SearcherItem(typeof(EcsStencil), SearcherContext.Stack, "Components/Add Component")]
[Serializable]
public class AddComponentNodeModel : EcsHighLevelNodeModel, IHasEntityInputPort
{
public const string EntityLabel = "entity";
[TypeSearcher(typeof(AddComponentFilter))]
public TypeHandle ComponentType = TypeHandle.Unknown;
ComponentPortsDescription m_ComponentDescription;
public IPortModel EntityPort { get; private set; }
protected override void OnDefineNode()
{
EntityPort = AddDataInput<Entity>(EntityLabel);
m_ComponentDescription = ComponentType != TypeHandle.Unknown ? AddPortsForComponent(ComponentType) : null;
}
public IEnumerable<IPortModel> GetPortsForComponent()
{
return m_ComponentDescription == null ? Enumerable.Empty<IPortModel>() : m_ComponentDescription.GetFieldIds().Select(id => InputsById[id]);
}
}
[GraphtoolsExtensionMethods]
public static class AddComponentTranslator
{
public static IEnumerable<SyntaxNode> Build(
this RoslynEcsTranslator translator,
AddComponentNodeModel model,
IPortModel portModel)
{
var componentType = model.ComponentType.Resolve(model.GraphModel.Stencil);
var entitySyntax = translator.BuildPort(model.EntityPort).SingleOrDefault() as ExpressionSyntax;
var componentInputs = model.GetPortsForComponent().ToArray();
var componentSyntax = translator.BuildComponentFromInput(componentType, componentInputs);
var entityTranslator = translator.context.GetEntityManipulationTranslator();
return entityTranslator.AddComponent(translator.context, entitySyntax, componentType, componentSyntax);
}
}
class AddComponentFilter : ISearcherFilter
{
public SearcherFilter GetFilter(INodeModel model)
{
return new SearcherFilter(SearcherContext.Type)
.WithComponentData(model.GraphModel.Stencil)
.WithSharedComponentData(model.GraphModel.Stencil);
}
}
}
| 37.855072 | 151 | 0.718989 | [
"MIT"
] | linyuan5856/ECS_UnityVisualScript | ECSUnityVisualScript/Packages/com.unity.visualscripting.entities/Editor/Nodes/AddComponentNodeModel.cs | 2,612 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Game2D
{
/// <summary>
/// 颜色
/// </summary>
public struct Color
{
public byte R;
public byte G;
public byte B;
public byte A;
public Color(byte r, byte g, byte b, byte a)
{
R = r; G = g; B = b; A = a;
}
public Color(byte r, byte g, byte b)
{
R = r; G = g; B = b; A = 255;
}
#region 常用颜色(数据来源:developer.mozilla.org/zh-CN/docs/Web/CSS/color_value)
/// <summary>
/// 透明 (R:0, G:0, B:0, A:0)
/// </summary>
/// <returns></returns>
public static Color Transparent { get; } = new Color(0, 0, 0, 0);
/// <summary>
/// 黑 (R:0, G:0, B:0, A:255)
/// </summary>
/// <returns></returns>
public static Color Black { get; } = new Color(0, 0, 0, 255);
/// <summary>
/// 银 (R:192, G:192, B:192, A:255)
/// </summary>
/// <returns></returns>
public static Color Silver { get; } = new Color(192, 192, 192, 255);
/// <summary>
/// 灰 (R:128, G:128, B:128, A:255)
/// </summary>
/// <returns></returns>
public static Color Gray { get; } = new Color(128, 128, 128, 255);
/// <summary>
/// 白 (R:255, G:255, B:255, A:255)
/// </summary>
/// <returns></returns>
public static Color White { get; } = new Color(255, 255, 255, 255);
/// <summary>
/// 褐 (R:128, G:0, B:0, A:255)
/// </summary>
/// <returns></returns>
public static Color Maroon { get; } = new Color(128, 0, 0, 255);
/// <summary>
/// 红 (R:255, G:0, B:0, A:255)
/// </summary>
/// <returns></returns>
public static Color Red { get; } = new Color(255, 0, 0, 255);
/// <summary>
/// 紫 (R:128, G:0, B:128, A:255)
/// </summary>
/// <returns></returns>
public static Color Purple { get; } = new Color(128, 0, 128, 255);
/// <summary>
/// 紫红 (R:255, G:0, B:255, A:255)
/// </summary>
/// <returns></returns>
public static Color Fuchsia { get; } = new Color(255, 0, 255, 255);
/// <summary>
/// 绿 (R:0, G:128, B:0, A:255)
/// </summary>
/// <returns></returns>
public static Color Green { get; } = new Color(0, 128, 0, 255);
/// <summary>
/// 绿黄 (R:0, G:255, B:0, A:255)
/// </summary>
/// <returns></returns>
public static Color Lime { get; } = new Color(0, 255, 0, 255);
/// <summary>
/// 橄榄绿 (R:128, G:128, B:0, A:255)
/// </summary>
/// <returns></returns>
public static Color Olive { get; } = new Color(128, 128, 0, 255);
/// <summary>
/// 黄 (R:255, G:255, B:0, A:255)
/// </summary>
/// <returns></returns>
public static Color Yellow { get; } = new Color(255, 255, 0, 255);
/// <summary>
/// 藏青 (R:0, G:0, B:128, A:255)
/// </summary>
/// <returns></returns>
public static Color Navy { get; } = new Color(0, 0, 128, 255);
/// <summary>
/// 蓝 (R:0, G:0, B:255, A:255)
/// </summary>
/// <returns></returns>
public static Color Blue { get; } = new Color(0, 0, 255, 255);
/// <summary>
/// 青 (R:0, G:128, B:128, A:255)
/// </summary>
/// <returns></returns>
public static Color Teal { get; } = new Color(0, 128, 128, 255);
/// <summary>
/// 水绿 (R:0, G:255, B:255, A:255)
/// </summary>
/// <returns></returns>
public static Color Aqua { get; } = new Color(0, 255, 255, 255);
#endregion
}
}
| 28.518519 | 79 | 0.449351 | [
"MIT"
] | gotogame/Game2D | Game2D/Core/Graphics/Color.cs | 3,920 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 0.1.0-559
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using intersight.Client;
using intersight.Model;
namespace intersight.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IStorageFlexFlashControllerPropsApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>StorageFlexFlashControllerPropsList</returns>
StorageFlexFlashControllerPropsList StorageFlexFlashControllerPropsGet (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>ApiResponse of StorageFlexFlashControllerPropsList</returns>
ApiResponse<StorageFlexFlashControllerPropsList> StorageFlexFlashControllerPropsGetWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>StorageFlexFlashControllerProps</returns>
StorageFlexFlashControllerProps StorageFlexFlashControllerPropsMoidGet (string moid);
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>ApiResponse of StorageFlexFlashControllerProps</returns>
ApiResponse<StorageFlexFlashControllerProps> StorageFlexFlashControllerPropsMoidGetWithHttpInfo (string moid);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns></returns>
void StorageFlexFlashControllerPropsMoidPatch (string moid, StorageFlexFlashControllerProps body);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> StorageFlexFlashControllerPropsMoidPatchWithHttpInfo (string moid, StorageFlexFlashControllerProps body);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns></returns>
void StorageFlexFlashControllerPropsMoidPost (string moid, StorageFlexFlashControllerProps body);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> StorageFlexFlashControllerPropsMoidPostWithHttpInfo (string moid, StorageFlexFlashControllerProps body);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of StorageFlexFlashControllerPropsList</returns>
System.Threading.Tasks.Task<StorageFlexFlashControllerPropsList> StorageFlexFlashControllerPropsGetAsync (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of ApiResponse (StorageFlexFlashControllerPropsList)</returns>
System.Threading.Tasks.Task<ApiResponse<StorageFlexFlashControllerPropsList>> StorageFlexFlashControllerPropsGetAsyncWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>Task of StorageFlexFlashControllerProps</returns>
System.Threading.Tasks.Task<StorageFlexFlashControllerProps> StorageFlexFlashControllerPropsMoidGetAsync (string moid);
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>Task of ApiResponse (StorageFlexFlashControllerProps)</returns>
System.Threading.Tasks.Task<ApiResponse<StorageFlexFlashControllerProps>> StorageFlexFlashControllerPropsMoidGetAsyncWithHttpInfo (string moid);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task StorageFlexFlashControllerPropsMoidPatchAsync (string moid, StorageFlexFlashControllerProps body);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> StorageFlexFlashControllerPropsMoidPatchAsyncWithHttpInfo (string moid, StorageFlexFlashControllerProps body);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task StorageFlexFlashControllerPropsMoidPostAsync (string moid, StorageFlexFlashControllerProps body);
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> StorageFlexFlashControllerPropsMoidPostAsyncWithHttpInfo (string moid, StorageFlexFlashControllerProps body);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class StorageFlexFlashControllerPropsApi : IStorageFlexFlashControllerPropsApi
{
private intersight.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="StorageFlexFlashControllerPropsApi"/> class.
/// </summary>
/// <returns></returns>
public StorageFlexFlashControllerPropsApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = intersight.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StorageFlexFlashControllerPropsApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public StorageFlexFlashControllerPropsApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = intersight.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public intersight.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>StorageFlexFlashControllerPropsList</returns>
public StorageFlexFlashControllerPropsList StorageFlexFlashControllerPropsGet (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
ApiResponse<StorageFlexFlashControllerPropsList> localVarResponse = StorageFlexFlashControllerPropsGetWithHttpInfo(count, inlinecount, top, skip, filter, select, orderby, expand);
return localVarResponse.Data;
}
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>ApiResponse of StorageFlexFlashControllerPropsList</returns>
public ApiResponse< StorageFlexFlashControllerPropsList > StorageFlexFlashControllerPropsGetWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
var localVarPath = "/storage/FlexFlashControllerProps";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (count != null) localVarQueryParams.Add("$count", Configuration.ApiClient.ParameterToString(count)); // query parameter
if (inlinecount != null) localVarQueryParams.Add("$inlinecount", Configuration.ApiClient.ParameterToString(inlinecount)); // query parameter
if (top != null) localVarQueryParams.Add("$top", Configuration.ApiClient.ParameterToString(top)); // query parameter
if (skip != null) localVarQueryParams.Add("$skip", Configuration.ApiClient.ParameterToString(skip)); // query parameter
if (filter != null) localVarQueryParams.Add("$filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (select != null) localVarQueryParams.Add("$select", Configuration.ApiClient.ParameterToString(select)); // query parameter
if (orderby != null) localVarQueryParams.Add("$orderby", Configuration.ApiClient.ParameterToString(orderby)); // query parameter
if (expand != null) localVarQueryParams.Add("$expand", Configuration.ApiClient.ParameterToString(expand)); // query parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<StorageFlexFlashControllerPropsList>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(StorageFlexFlashControllerPropsList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StorageFlexFlashControllerPropsList)));
}
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of StorageFlexFlashControllerPropsList</returns>
public async System.Threading.Tasks.Task<StorageFlexFlashControllerPropsList> StorageFlexFlashControllerPropsGetAsync (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
ApiResponse<StorageFlexFlashControllerPropsList> localVarResponse = await StorageFlexFlashControllerPropsGetAsyncWithHttpInfo(count, inlinecount, top, skip, filter, select, orderby, expand);
return localVarResponse.Data;
}
/// <summary>
/// Get a list of 'storageFlexFlashControllerProps' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of ApiResponse (StorageFlexFlashControllerPropsList)</returns>
public async System.Threading.Tasks.Task<ApiResponse<StorageFlexFlashControllerPropsList>> StorageFlexFlashControllerPropsGetAsyncWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
var localVarPath = "/storage/FlexFlashControllerProps";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (count != null) localVarQueryParams.Add("$count", Configuration.ApiClient.ParameterToString(count)); // query parameter
if (inlinecount != null) localVarQueryParams.Add("$inlinecount", Configuration.ApiClient.ParameterToString(inlinecount)); // query parameter
if (top != null) localVarQueryParams.Add("$top", Configuration.ApiClient.ParameterToString(top)); // query parameter
if (skip != null) localVarQueryParams.Add("$skip", Configuration.ApiClient.ParameterToString(skip)); // query parameter
if (filter != null) localVarQueryParams.Add("$filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (select != null) localVarQueryParams.Add("$select", Configuration.ApiClient.ParameterToString(select)); // query parameter
if (orderby != null) localVarQueryParams.Add("$orderby", Configuration.ApiClient.ParameterToString(orderby)); // query parameter
if (expand != null) localVarQueryParams.Add("$expand", Configuration.ApiClient.ParameterToString(expand)); // query parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<StorageFlexFlashControllerPropsList>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(StorageFlexFlashControllerPropsList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StorageFlexFlashControllerPropsList)));
}
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>StorageFlexFlashControllerProps</returns>
public StorageFlexFlashControllerProps StorageFlexFlashControllerPropsMoidGet (string moid)
{
ApiResponse<StorageFlexFlashControllerProps> localVarResponse = StorageFlexFlashControllerPropsMoidGetWithHttpInfo(moid);
return localVarResponse.Data;
}
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>ApiResponse of StorageFlexFlashControllerProps</returns>
public ApiResponse< StorageFlexFlashControllerProps > StorageFlexFlashControllerPropsMoidGetWithHttpInfo (string moid)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidGet");
var localVarPath = "/storage/FlexFlashControllerProps/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsMoidGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<StorageFlexFlashControllerProps>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(StorageFlexFlashControllerProps) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StorageFlexFlashControllerProps)));
}
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>Task of StorageFlexFlashControllerProps</returns>
public async System.Threading.Tasks.Task<StorageFlexFlashControllerProps> StorageFlexFlashControllerPropsMoidGetAsync (string moid)
{
ApiResponse<StorageFlexFlashControllerProps> localVarResponse = await StorageFlexFlashControllerPropsMoidGetAsyncWithHttpInfo(moid);
return localVarResponse.Data;
}
/// <summary>
/// Get a specific instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <returns>Task of ApiResponse (StorageFlexFlashControllerProps)</returns>
public async System.Threading.Tasks.Task<ApiResponse<StorageFlexFlashControllerProps>> StorageFlexFlashControllerPropsMoidGetAsyncWithHttpInfo (string moid)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidGet");
var localVarPath = "/storage/FlexFlashControllerProps/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsMoidGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<StorageFlexFlashControllerProps>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(StorageFlexFlashControllerProps) Configuration.ApiClient.Deserialize(localVarResponse, typeof(StorageFlexFlashControllerProps)));
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns></returns>
public void StorageFlexFlashControllerPropsMoidPatch (string moid, StorageFlexFlashControllerProps body)
{
StorageFlexFlashControllerPropsMoidPatchWithHttpInfo(moid, body);
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> StorageFlexFlashControllerPropsMoidPatchWithHttpInfo (string moid, StorageFlexFlashControllerProps body)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPatch");
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPatch");
var localVarPath = "/storage/FlexFlashControllerProps/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsMoidPatch", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task StorageFlexFlashControllerPropsMoidPatchAsync (string moid, StorageFlexFlashControllerProps body)
{
await StorageFlexFlashControllerPropsMoidPatchAsyncWithHttpInfo(moid, body);
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> StorageFlexFlashControllerPropsMoidPatchAsyncWithHttpInfo (string moid, StorageFlexFlashControllerProps body)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPatch");
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPatch");
var localVarPath = "/storage/FlexFlashControllerProps/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsMoidPatch", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns></returns>
public void StorageFlexFlashControllerPropsMoidPost (string moid, StorageFlexFlashControllerProps body)
{
StorageFlexFlashControllerPropsMoidPostWithHttpInfo(moid, body);
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> StorageFlexFlashControllerPropsMoidPostWithHttpInfo (string moid, StorageFlexFlashControllerProps body)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPost");
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPost");
var localVarPath = "/storage/FlexFlashControllerProps/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsMoidPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task StorageFlexFlashControllerPropsMoidPostAsync (string moid, StorageFlexFlashControllerProps body)
{
await StorageFlexFlashControllerPropsMoidPostAsyncWithHttpInfo(moid, body);
}
/// <summary>
/// Update an instance of 'storageFlexFlashControllerProps'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the storageFlexFlashControllerProps instance.</param>
/// <param name="body">storageFlexFlashControllerProps to update</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> StorageFlexFlashControllerPropsMoidPostAsyncWithHttpInfo (string moid, StorageFlexFlashControllerProps body)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPost");
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling StorageFlexFlashControllerPropsApi->StorageFlexFlashControllerPropsMoidPost");
var localVarPath = "/storage/FlexFlashControllerProps/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("StorageFlexFlashControllerPropsMoidPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
}
}
| 65.84552 | 859 | 0.67907 | [
"Apache-2.0"
] | CiscoUcs/intersight-powershell | csharp/swaggerClient/src/intersight/Api/StorageFlexFlashControllerPropsApi.cs | 63,952 | C# |
/*************************************************************************************
Extended WPF Toolkit
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at http://xceed.com/wpf_toolkit
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System;
using System.Collections;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Ssz.Xceed.Wpf.Toolkit.Core.Utilities;
namespace Ssz.Xceed.Wpf.Toolkit.PropertyGrid
{
[TemplatePart(Name = PropertyGrid.PART_PropertyItemsControl, Type = typeof(PropertyItemsControl))]
[TemplatePart(Name = PART_ValueContainer, Type = typeof(ContentControl))]
public abstract class PropertyItemBase : Control, IPropertyContainer, INotifyPropertyChanged
{
internal const string PART_ValueContainer = "PART_ValueContainer";
private ContainerHelperBase _containerHelper;
#region Properties
#region AdvancedOptionsIcon
public static readonly DependencyProperty AdvancedOptionsIconProperty =
DependencyProperty.Register("AdvancedOptionsIcon", typeof(ImageSource), typeof(PropertyItemBase),
new UIPropertyMetadata(null));
public ImageSource AdvancedOptionsIcon
{
get => (ImageSource) GetValue(AdvancedOptionsIconProperty);
set => SetValue(AdvancedOptionsIconProperty, value);
}
#endregion //AdvancedOptionsIcon
#region AdvancedOptionsTooltip
public static readonly DependencyProperty AdvancedOptionsTooltipProperty =
DependencyProperty.Register("AdvancedOptionsTooltip", typeof(object), typeof(PropertyItemBase),
new UIPropertyMetadata(null));
public object AdvancedOptionsTooltip
{
get => GetValue(AdvancedOptionsTooltipProperty);
set => SetValue(AdvancedOptionsTooltipProperty, value);
}
#endregion //AdvancedOptionsTooltip
#region Description
public static readonly DependencyProperty DescriptionProperty =
DependencyProperty.Register("Description", typeof(string), typeof(PropertyItemBase),
new UIPropertyMetadata(null));
public string Description
{
get => (string) GetValue(DescriptionProperty);
set => SetValue(DescriptionProperty, value);
}
#endregion //Description
#region DisplayName
public static readonly DependencyProperty DisplayNameProperty =
DependencyProperty.Register("DisplayName", typeof(string), typeof(PropertyItemBase),
new UIPropertyMetadata(null));
public string DisplayName
{
get => (string) GetValue(DisplayNameProperty);
set => SetValue(DisplayNameProperty, value);
}
#endregion //DisplayName
#region Editor
public static readonly DependencyProperty EditorProperty = DependencyProperty.Register("Editor",
typeof(FrameworkElement), typeof(PropertyItemBase), new UIPropertyMetadata(null, OnEditorChanged));
public FrameworkElement Editor
{
get => (FrameworkElement) GetValue(EditorProperty);
set => SetValue(EditorProperty, value);
}
private static void OnEditorChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var propertyItem = o as PropertyItem;
if (propertyItem != null)
propertyItem.OnEditorChanged((FrameworkElement) e.OldValue, (FrameworkElement) e.NewValue);
}
protected virtual void OnEditorChanged(FrameworkElement oldValue, FrameworkElement newValue)
{
}
#endregion //Editor
#region IsExpanded
public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register("IsExpanded",
typeof(bool), typeof(PropertyItemBase), new UIPropertyMetadata(false, OnIsExpandedChanged));
public bool IsExpanded
{
get => (bool) GetValue(IsExpandedProperty);
set => SetValue(IsExpandedProperty, value);
}
private static void OnIsExpandedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var propertyItem = o as PropertyItemBase;
if (propertyItem != null)
propertyItem.OnIsExpandedChanged((bool) e.OldValue, (bool) e.NewValue);
}
protected virtual void OnIsExpandedChanged(bool oldValue, bool newValue)
{
}
#endregion IsExpanded
#region IsExpandable
public static readonly DependencyProperty IsExpandableProperty =
DependencyProperty.Register("IsExpandable", typeof(bool), typeof(PropertyItemBase),
new UIPropertyMetadata(false));
public bool IsExpandable
{
get => (bool) GetValue(IsExpandableProperty);
set => SetValue(IsExpandableProperty, value);
}
#endregion //IsExpandable
#region IsSelected
public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected",
typeof(bool), typeof(PropertyItemBase), new UIPropertyMetadata(false, OnIsSelectedChanged));
public bool IsSelected
{
get => (bool) GetValue(IsSelectedProperty);
set => SetValue(IsSelectedProperty, value);
}
private static void OnIsSelectedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var propertyItem = o as PropertyItemBase;
if (propertyItem != null)
propertyItem.OnIsSelectedChanged((bool) e.OldValue, (bool) e.NewValue);
}
protected virtual void OnIsSelectedChanged(bool oldValue, bool newValue)
{
RaiseItemSelectionChangedEvent();
}
#endregion //IsSelected
#region ParentElement
/// <summary>
/// Gets the parent property grid element of this property.
/// A PropertyItemBase instance if this is a sub-element,
/// or the PropertyGrid itself if this is a first-level property.
/// </summary>
public FrameworkElement ParentElement => ParentNode as FrameworkElement;
#endregion
#region ParentNode
internal IPropertyContainer ParentNode { get; set; }
#endregion
#region ValueContainer
internal ContentControl ValueContainer { get; private set; }
#endregion
#region Level
public int Level { get; internal set; }
#endregion //Level
#region Properties
public IList Properties => _containerHelper.Properties;
#endregion //Properties
#region PropertyContainerStyle
/// <summary>
/// Get the PropertyContainerStyle for sub items of this property.
/// It return the value defined on PropertyGrid.PropertyContainerStyle.
/// </summary>
public Style PropertyContainerStyle =>
ParentNode != null
? ParentNode.PropertyContainerStyle
: null;
#endregion
#region ContainerHelper
internal ContainerHelperBase ContainerHelper
{
get => _containerHelper;
set
{
if (value == null)
throw new ArgumentNullException("value");
_containerHelper = value;
// Properties property relies on the "Properties" property of the helper
// class. Raise a property-changed event.
RaisePropertyChanged(() => Properties);
}
}
#endregion
#endregion //Properties
#region Events
#region ItemSelectionChanged
internal static readonly RoutedEvent ItemSelectionChangedEvent = EventManager.RegisterRoutedEvent(
"ItemSelectionChangedEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(PropertyItemBase));
private void RaiseItemSelectionChangedEvent()
{
RaiseEvent(new RoutedEventArgs(ItemSelectionChangedEvent));
}
#endregion
#region PropertyChanged event
public event PropertyChangedEventHandler PropertyChanged;
internal void RaisePropertyChanged<TMember>(Expression<Func<TMember>> propertyExpression)
{
this.Notify(PropertyChanged, propertyExpression);
}
internal void RaisePropertyChanged(string name)
{
this.Notify(PropertyChanged, name);
}
#endregion
#endregion //Events
#region Constructors
static PropertyItemBase()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PropertyItemBase),
new FrameworkPropertyMetadata(typeof(PropertyItemBase)));
}
internal PropertyItemBase()
{
_containerHelper = new ObjectContainerHelper(this, null);
GotFocus += PropertyItemBase_GotFocus;
AddHandler(PropertyItemsControl.PreparePropertyItemEvent,
new PropertyItemEventHandler(OnPreparePropertyItemInternal));
AddHandler(PropertyItemsControl.ClearPropertyItemEvent,
new PropertyItemEventHandler(OnClearPropertyItemInternal));
}
#endregion //Constructors
#region Event Handlers
private void OnPreparePropertyItemInternal(object sender, PropertyItemEventArgs args)
{
// This is the callback of the PreparePropertyItem comming from the template PropertyItemControl.
args.PropertyItem.Level = Level + 1;
_containerHelper.PrepareChildrenPropertyItem(args.PropertyItem, args.Item);
args.Handled = true;
}
private void OnClearPropertyItemInternal(object sender, PropertyItemEventArgs args)
{
_containerHelper.ClearChildrenPropertyItem(args.PropertyItem, args.Item);
// This is the callback of the PreparePropertyItem comming from the template PropertyItemControl.
args.PropertyItem.Level = 0;
args.Handled = true;
}
#endregion //Event Handlers
#region Methods
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_containerHelper.ChildrenItemsControl =
GetTemplateChild(PropertyGrid.PART_PropertyItemsControl) as PropertyItemsControl;
ValueContainer = GetTemplateChild(PART_ValueContainer) as ContentControl;
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
IsSelected = true;
if (!IsKeyboardFocusWithin) Focus();
// Handle the event; otherwise, the possible
// parent property item will select itself too.
e.Handled = true;
}
private void PropertyItemBase_GotFocus(object sender, RoutedEventArgs e)
{
IsSelected = true;
// Handle the event; otherwise, the possible
// parent property item will select itself too.
e.Handled = true;
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
var propertyItem = e.OldValue as PropertyItem;
if (propertyItem != null) BindingOperations.ClearAllBindings(propertyItem.DescriptorDefinition);
// First check that the raised property is actually a real CLR property.
// This could be something else like an Attached DP.
if (ReflectionHelper.IsPublicInstanceProperty(GetType(), e.Property.Name))
RaisePropertyChanged(e.Property.Name);
}
#endregion //Methods
#region IPropertyContainer Members
Style IPropertyContainer.PropertyContainerStyle => PropertyContainerStyle;
EditorDefinitionCollection IPropertyContainer.EditorDefinitions => ParentNode.EditorDefinitions;
PropertyDefinitionCollection IPropertyContainer.PropertyDefinitions => null;
ContainerHelperBase IPropertyContainer.ContainerHelper => ContainerHelper;
bool IPropertyContainer.IsCategorized => false;
bool IPropertyContainer.AutoGenerateProperties => true;
FilterInfo IPropertyContainer.FilterInfo => new();
#endregion
}
} | 33.686528 | 119 | 0.648235 | [
"MIT"
] | ru-petrovi4/Ssz.Utils | Ssz.Xceed.Wpf.Toolkit/Ssz.Xceed.Wpf.Toolkit/PropertyGrid/Implementation/PropertyItemBase.cs | 13,005 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using DivideSharp;
namespace DivisionBenchmark
{
public readonly struct DelegateDispatchedUInt32Divisor : IDivisor<uint>
{
public DelegateDispatchedUInt32Divisor(uint divisor) : this()
{
Divisor = divisor;
var w = new UInt32Divisor(divisor);
Multiplier = w.Multiplier;
Strategy = w.Strategy;
Shift = w.Shift;
switch (Strategy)
{
case UnsignedIntegerDivisorStrategy.Shift:
DivideFunc = ShiftOnly;
break;
case UnsignedIntegerDivisorStrategy.MultiplyShift:
DivideFunc = Multiply;
break;
case UnsignedIntegerDivisorStrategy.MultiplyAddShift:
DivideFunc = MultiplyAdd;
break;
default:
DivideFunc = Echo;
break;
}
}
/// <summary>
/// Gets the divisor.
/// </summary>
/// <value>
/// The divisor.
/// </value>
public uint Divisor { get; }
/// <summary>
/// Gets the multiplier for actual "division".
/// </summary>
/// <value>
/// The multiplier.
/// </value>
public uint Multiplier { get; }
/// <summary>
/// Gets the strategy of a division.
/// </summary>
/// <value>
/// The strategy of a division.
/// </value>
public UnsignedIntegerDivisorStrategy Strategy { get; }
/// <summary>
/// Gets the number of bits to shift for actual "division".
/// </summary>
/// <value>
/// The number of bits to shift right.
/// </value>
public int Shift { get; }
private Func<DelegateDispatchedUInt32Divisor, uint, uint> DivideFunc { get; }
#region Divisions
#pragma warning disable IDE0060 // 未使用のパラメーターを削除します
#pragma warning disable S1172 // Unused method parameters should be removed
private static uint Echo(DelegateDispatchedUInt32Divisor divisor, uint value) => value;
#pragma warning restore S1172 // Unused method parameters should be removed
#pragma warning restore IDE0060 // 未使用のパラメーターを削除します
private static uint ShiftOnly(DelegateDispatchedUInt32Divisor divisor, uint value) => value >> divisor.Shift;
private static uint Multiply(DelegateDispatchedUInt32Divisor divisor, uint value)
{
ulong rax = value;
uint eax;
ulong multiplier = divisor.Multiplier;
int shift = divisor.Shift;
rax *= multiplier;
eax = (uint)(rax >> shift);
return eax;
}
private static uint MultiplyAdd(DelegateDispatchedUInt32Divisor divisor, uint value)
{
ulong rax = value;
uint eax;
ulong multiplier = divisor.Multiplier;
int shift = divisor.Shift;
rax *= multiplier;
eax = (uint)(rax >> 32);
value -= eax;
value >>= 1;
eax += value;
eax >>= shift;
return eax;
}
#endregion Divisions
public uint Divide(uint value) => DivideFunc(this, value);
public uint DivRem(uint value, out uint quotient) => throw new NotImplementedException();
public uint Floor(uint value) => throw new NotImplementedException();
public uint FloorRem(uint value, out uint largestMultipleOfDivisor) => throw new NotImplementedException();
public uint Modulo(uint value) => throw new NotImplementedException();
}
}
| 31.621849 | 117 | 0.563115 | [
"Apache-2.0"
] | MineCake147E/DivideSharp | DivisionBenchmark/DelegateDispatchedUInt32Divisor.cs | 3,829 | C# |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Petite.Tests
{
[TestClass]
public class ContainerCoreTests
{
[TestMethod]
public void Registers_Without_Exception()
{
var target = new Container();
target.Register<ISimpleTestService>(c => new SimpleTestService());
}
[TestMethod]
public void Registered_Interface_Is_Resolved()
{
var target = new Container();
target.Register<ISimpleTestService>(c => new SimpleTestService());
var resolved = target.Resolve<ISimpleTestService>();
Assert.IsInstanceOfType(resolved, typeof(SimpleTestService));
}
[TestMethod]
public void Named_Registration_Registers_Without_Exception()
{
var target = new Container();
target.Register<ISimpleTestService>("Name", c => new SimpleTestService());
}
[TestMethod]
public void Named_Registration_Is_Resolved()
{
var target = new Container();
target.Register<ISimpleTestService>("Name", c => new SimpleTestService());
var resolved = target.Resolve<ISimpleTestService>("Name");
Assert.IsInstanceOfType(resolved, typeof(SimpleTestService));
}
[TestMethod]
public void Named_Registration_Is_Not_Resolved_Without_Name()
{
var target = new Container();
target.Register<ISimpleTestService>("Name", c => new SimpleTestService());
Exception exceptionThrown = null;
try
{
var resolved = target.Resolve<ISimpleTestService>();
}
catch (UnknownRegistrationException ex)
{
exceptionThrown = ex;
}
Assert.IsNotNull(exceptionThrown);
}
[TestMethod]
public void Standard_Registration_Returns_New_Instance_Every_Resolve()
{
var target = new Container();
target.Register<ISimpleTestService>("Name", c => new SimpleTestService());
var resolvedFirst = target.Resolve<ISimpleTestService>("Name");
var resolvedSecond = target.Resolve<ISimpleTestService>("Name");
Assert.AreNotSame(resolvedFirst, resolvedSecond);
}
[TestMethod]
public void Standard_Registration_Returns_An_Instance_On_Resolve()
{
var target = new Container();
target.Register<ISimpleTestService>("Name", c => new SimpleTestService());
var resolved = target.Resolve<ISimpleTestService>("Name");
Assert.IsNotNull(resolved);
}
[TestMethod]
public void Singleton_Registration_Returns_Same_Instance_Every_Resolve()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>("Name", c => new SimpleTestService());
var resolvedFirst = target.Resolve<ISimpleTestService>("Name");
var resolvedSecond = target.Resolve<ISimpleTestService>("Name");
Assert.AreSame(resolvedFirst, resolvedSecond);
}
[TestMethod]
public void Singleton_Registration_Returns_An_Instance_On_Resolve()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>("Name", c => new SimpleTestService());
var resolved = target.Resolve<ISimpleTestService>("Name");
Assert.IsNotNull(resolved);
}
[TestMethod]
public void Instance_Registration_Returns_Given_Instance_Every_Resolve()
{
var target = new Container();
var instance = new SimpleTestService();
target.RegisterInstance<ISimpleTestService>("Name", instance);
var resolvedFirst = target.Resolve<ISimpleTestService>("Name");
var resolvedSecond = target.Resolve<ISimpleTestService>("Name");
Assert.AreSame(instance, resolvedFirst);
Assert.AreSame(instance, resolvedSecond);
}
[TestMethod]
public void Unnamed_Standard_Registration_Returns_New_Instance_Every_Resolve()
{
var target = new Container();
target.Register<ISimpleTestService>(c => new SimpleTestService());
var resolvedFirst = target.Resolve<ISimpleTestService>();
var resolvedSecond = target.Resolve<ISimpleTestService>();
Assert.AreNotSame(resolvedFirst, resolvedSecond);
}
[TestMethod]
public void Unnamed_Singleton_Registration_Returns_New_Instance_Every_Resolve()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>(c => new SimpleTestService());
var resolvedFirst = target.Resolve<ISimpleTestService>();
var resolvedSecond = target.Resolve<ISimpleTestService>();
Assert.AreSame(resolvedFirst, resolvedSecond);
}
[TestMethod]
public void Resolve_Sends_Same_Container_To_Factory_Method()
{
var target = new Container();
Container resolveContainer = null;
target.Register<ISimpleTestService>(c =>
{
resolveContainer = c;
return new SimpleTestService();
});
target.Resolve<ISimpleTestService>();
Assert.IsNotNull(resolveContainer);
Assert.AreSame(target, resolveContainer);
}
[TestMethod]
public void Resolve_With_Nested_Singleton_Returns_Different_Instances_With_Same_Sub_Instance()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>(c=>new SimpleTestService());
target.Register<IServiceWithNestedService>(c=>new ServiceWithNestedService(c.Resolve<ISimpleTestService>()));
var resolvedFirst = target.Resolve<IServiceWithNestedService>();
var resolvedSecond = target.Resolve<IServiceWithNestedService>();
Assert.AreNotSame(resolvedFirst, resolvedSecond);
Assert.AreSame(resolvedFirst.NestedService, resolvedSecond.NestedService);
}
[TestMethod]
public void Exception_In_Factory_Method_Throws_ResolveException()
{
var target = new Container();
target.Register<ISimpleTestService>(c => { throw new InvalidOperationException(); });
ResolveException thrownException = null;
try
{
target.Resolve<ISimpleTestService>();
}
catch(ResolveException ex)
{
thrownException = ex;
}
Assert.IsNotNull(thrownException);
Assert.AreEqual(thrownException.ServiceType, typeof(ISimpleTestService));
Assert.IsTrue(thrownException.Message.Contains(typeof(ISimpleTestService).ToString()), "Exception should contain the name of the interface that wasn't resolved.");
}
[TestMethod]
public void Exception_In_Nested_Factory_Method_Throws_ResolveException()
{
var target = new Container();
target.Register<ISimpleTestService>(c => { throw new InvalidOperationException(); });
target.Register<IServiceWithNestedService>(c => new ServiceWithNestedService(c.Resolve<ISimpleTestService>()));
ResolveException thrownException = null;
try
{
target.Resolve<IServiceWithNestedService>();
}
catch (ResolveException ex)
{
thrownException = ex;
}
Assert.IsNotNull(thrownException);
Assert.AreEqual(thrownException.ServiceType, typeof(IServiceWithNestedService));
Assert.IsTrue(thrownException.Message.Contains(typeof(ISimpleTestService).ToString()), "Exception should contain the name of the interface that wasn't resolved.");
Assert.IsTrue(thrownException.Message.Contains(typeof(ISimpleTestService).ToString()), "Exception should contain the name of the original interface that failed.");
}
[TestMethod]
public void Exception_In_Nested_Factory_Method_Throws_ResolveException_On_NonGenericResolve()
{
var target = new Container();
target.Register<ISimpleTestService>(c => { throw new InvalidOperationException(); });
target.Register<IServiceWithNestedService>(c => new ServiceWithNestedService(c.Resolve<ISimpleTestService>()));
ResolveException thrownException = null;
try
{
target.Resolve(typeof(IServiceWithNestedService));
}
catch(ResolveException ex)
{
thrownException = ex;
}
Assert.IsNotNull(thrownException);
Assert.AreEqual(thrownException.ServiceType, typeof(IServiceWithNestedService));
Assert.IsTrue(thrownException.Message.Contains(typeof(ISimpleTestService).ToString()), "Exception should contain the name of the interface that wasn't resolved.");
Assert.IsTrue(thrownException.Message.Contains(typeof(ISimpleTestService).ToString()), "Exception should contain the name of the original interface that failed.");
}
[TestMethod]
public void Non_Generic_Unnamed_Resolve_Returns_Correct_Service()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>(c => new SimpleTestService());
var resolvedFirst = target.Resolve(typeof(ISimpleTestService));
Assert.IsInstanceOfType(resolvedFirst, typeof(SimpleTestService));
}
[TestMethod]
public void Non_Generic_Unnamed_Unknown_Resolve_Throws_UnknownRegistrationException()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>(c => new SimpleTestService());
UnknownRegistrationException thrownException = null;
try
{
var resolvedFirst = target.Resolve(typeof(IOtherSimpleTestService));
}
catch(UnknownRegistrationException ex)
{
thrownException = ex;
}
Assert.IsNotNull(thrownException);
}
[TestMethod]
public void Non_Generic_Named_Resolve_Returns_Correct_Service()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>("Test", c => new SimpleTestService());
var resolvedFirst = target.Resolve("Test", typeof(ISimpleTestService));
Assert.IsInstanceOfType(resolvedFirst, typeof(SimpleTestService));
}
[TestMethod]
public void Non_Generic_Named_Unknown_Resolve_Throws_UnknownRegistrationException()
{
var target = new Container();
target.RegisterSingleton<ISimpleTestService>("Test", c => new SimpleTestService());
UnknownRegistrationException thrownException = null;
try
{
var resolvedFirst = target.Resolve("Unknown", typeof(ISimpleTestService));
}
catch(UnknownRegistrationException ex)
{
thrownException = ex;
}
Assert.IsNotNull(thrownException);
}
[TestMethod]
public void Resolve_All_Returns_All_Named_Items()
{
var target = new Container();
target.Register<ISimpleTestService>("First", c => new SimpleTestService());
target.Register<ISimpleTestService>("Second", c => new SecondSimpleTestService());
var allResolved = target.ResolveAll<ISimpleTestService>().ToArray();
var simpleTestServicesResolved = allResolved.OfType<SimpleTestService>().ToArray();
var secondSimpleTestServicesResolved = allResolved.OfType<SecondSimpleTestService>().ToArray();
Assert.AreEqual(2, allResolved.Length);
Assert.AreEqual(1, simpleTestServicesResolved.Length);
Assert.AreEqual(1, secondSimpleTestServicesResolved.Length);
}
[TestMethod]
public void Resolve_All_Returns_All_Named_And_UnnamedItems()
{
var target = new Container();
target.Register<ISimpleTestService>(c => new SimpleTestService());
target.Register<ISimpleTestService>("Second", c => new SecondSimpleTestService());
var allResolved = target.ResolveAll<ISimpleTestService>().ToArray();
var simpleTestServicesResolved = allResolved.OfType<SimpleTestService>().ToArray();
var secondSimpleTestServicesResolved = allResolved.OfType<SecondSimpleTestService>().ToArray();
Assert.AreEqual(2, allResolved.Length);
Assert.AreEqual(1, simpleTestServicesResolved.Length);
Assert.AreEqual(1, secondSimpleTestServicesResolved.Length);
}
[TestMethod]
public void Non_Generic_Named_ResolveAll_Returns_Correct_Services()
{
var target = new Container();
target.Register<ISimpleTestService>(c => new SimpleTestService());
target.Register<ISimpleTestService>("Second", c => new SecondSimpleTestService());
var allResolved = target.ResolveAll(typeof(ISimpleTestService)).ToArray();
var simpleTestServicesResolved = allResolved.OfType<SimpleTestService>().ToArray();
var secondSimpleTestServicesResolved = allResolved.OfType<SecondSimpleTestService>().ToArray();
Assert.AreEqual(2, allResolved.Length);
Assert.AreEqual(1, simpleTestServicesResolved.Length);
Assert.AreEqual(1, secondSimpleTestServicesResolved.Length);
}
/*
[TestMethod]
public void Per_Resolve_Registration_Nested_Resolve_Returns_Same_Instance()
{
var target = new Container();
target.RegisterPerResolve<ISimpleTestService>(c => new SimpleTestService());
target.Register<IServiceWithTwoNestedServices>(c => new ServiceWithTwoNestedServices(c.Resolve<ISimpleTestService>(), c.Resolve<ISimpleTestService>()));
var resolved = target.Resolve<IServiceWithTwoNestedServices>();
Assert.AreSame(resolved.FirstNestedService, resolved.SecondNestedService);
}
[TestMethod]
public void Per_Resolve_Registration_Second_Nested_Resolve_Returns_Different_Instance()
{
var target = new Container();
target.RegisterPerResolve<ISimpleTestService>(c => new SimpleTestService());
target.Register<IServiceWithTwoNestedServices>(c => new ServiceWithTwoNestedServices(c.Resolve<ISimpleTestService>(), c.Resolve<ISimpleTestService>()));
var resolvedFirst = target.Resolve<IServiceWithTwoNestedServices>();
var resolvedSecond = target.Resolve<IServiceWithTwoNestedServices>();
Assert.AreNotSame(resolvedFirst.FirstNestedService, resolvedSecond.FirstNestedService);
Assert.AreNotSame(resolvedFirst.SecondNestedService, resolvedSecond.SecondNestedService);
}
*/
}
interface ISimpleTestService
{
}
interface IOtherSimpleTestService
{
}
class SimpleTestService : ISimpleTestService
{
public SimpleTestService()
{
}
}
class SecondSimpleTestService : ISimpleTestService
{
public SecondSimpleTestService()
{
}
}
interface IServiceWithNestedService
{
ISimpleTestService NestedService { get; }
}
class ServiceWithNestedService : IServiceWithNestedService
{
public ISimpleTestService NestedService { get; private set; }
public ServiceWithNestedService(ISimpleTestService nestedService)
{
NestedService = nestedService;
}
}
interface IServiceWithTwoNestedServices
{
ISimpleTestService FirstNestedService { get; }
ISimpleTestService SecondNestedService { get; }
}
class ServiceWithTwoNestedServices : IServiceWithTwoNestedServices
{
public ISimpleTestService FirstNestedService { get; private set; }
public ISimpleTestService SecondNestedService { get; private set; }
public ServiceWithTwoNestedServices(ISimpleTestService firstNestedService, ISimpleTestService secondNestedService)
{
FirstNestedService = firstNestedService;
SecondNestedService = secondNestedService;
}
}
} | 33.753747 | 175 | 0.683309 | [
"MIT"
] | andlju/Petite | Source/Petite.Tests/ContainerCoreTests.cs | 15,763 | C# |
using System.Threading;
using UnityEngine;
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System.Collections.Generic;
using UnityEngine.EventSystems;
namespace UniRx.Async.Triggers
{
[DisallowMultipleComponent]
public class AsyncDeselectTrigger : AsyncTriggerBase, IDeselectHandler
{
private AsyncTriggerPromise<BaseEventData> onDeselect;
private AsyncTriggerPromiseDictionary<BaseEventData> onDeselects;
void IDeselectHandler.OnDeselect(BaseEventData eventData)
{
TrySetResult(onDeselect, onDeselects, eventData);
}
protected override IEnumerable<ICancelablePromise> GetPromises()
{
return Concat(onDeselect, onDeselects);
}
public UniTask<BaseEventData> OnDeselectAsync(CancellationToken cancellationToken = default)
{
return GetOrAddPromise(ref onDeselect, ref onDeselects, cancellationToken);
}
}
}
#endif
| 29.432432 | 100 | 0.724518 | [
"MIT"
] | darsausalo/UniTask | UniRx.Async/Triggers/AsyncDeselectTrigger.cs | 1,089 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.SumoLogic.Inputs
{
public sealed class ElbSourceDefaultDateFormatArgs : Pulumi.ResourceArgs
{
[Input("format", required: true)]
public Input<string> Format { get; set; } = null!;
[Input("locator")]
public Input<string>? Locator { get; set; }
public ElbSourceDefaultDateFormatArgs()
{
}
}
}
| 26.653846 | 88 | 0.672439 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-sumologic | sdk/dotnet/Inputs/ElbSourceDefaultDateFormatArgs.cs | 693 | C# |
using RssReader.Model.Abstract;
using RssReader.Models.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RssReader.Web.Models
{
public class RssFeedViewModel
{
public IEnumerable<IEnumerable<IRssFeed>> RssList { get; set; }
public IEnumerable<IRssFeed> RssFeed { get; set; }
public string URL { get; set; }
}
} | 23.555556 | 71 | 0.716981 | [
"MIT"
] | VeselinovStf/RssReader | RssReader.Web/Models/RssFeedViewModel.cs | 426 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using ClearCanvas.Common.Serialization;
using ClearCanvas.Enterprise.Common;
using System.Runtime.Serialization;
namespace ClearCanvas.Ris.Application.Common
{
[DataContract]
public class StaffGroupSummary : DataContractBase, IEquatable<StaffGroupSummary>
{
public StaffGroupSummary(EntityRef groupRef, string name, string description, bool isElective, bool deactivated)
{
this.StaffGroupRef = groupRef;
this.Name = name;
this.Description = description;
this.IsElective = isElective;
this.Deactivated = deactivated;
}
/// <summary>
/// Constructor for deserialization
/// </summary>
public StaffGroupSummary()
{
}
[DataMember]
public EntityRef StaffGroupRef;
[DataMember]
public string Name;
[DataMember]
public string Description;
[DataMember]
public bool IsElective;
[DataMember]
public bool Deactivated;
public bool Equals(StaffGroupSummary staffGroupSummary)
{
if (staffGroupSummary == null) return false;
return Equals(StaffGroupRef, staffGroupSummary.StaffGroupRef);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as StaffGroupSummary);
}
public override int GetHashCode()
{
return StaffGroupRef != null ? StaffGroupRef.GetHashCode() : 0;
}
}
}
| 25.608108 | 121 | 0.640633 | [
"Apache-2.0"
] | SNBnani/Xian | Ris/Application/Common/StaffGroupSummary.cs | 1,895 | 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("Problem_11. Convert Speed Units")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem_11. Convert Speed Units")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("32e6a585-346f-4f6a-a5ea-744f5ffa27cf")]
// 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.648649 | 84 | 0.748951 | [
"MIT"
] | Supbads/Softuni-Education | 07 ProgrammingFundamentals 05.17/04. Data-Types-and-Variables-Exercises/Problem_11. Convert Speed Units/Properties/AssemblyInfo.cs | 1,433 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Il2CppDummyDll;
// Token: 0x020004ED RID: 1261
[Token(Token = "0x20004ED")]
public class NormalPlayerTask : PlayerTask
{
// Token: 0x170003F3 RID: 1011
// (get) Token: 0x06001AF1 RID: 6897 RVA: 0x00008778 File Offset: 0x00006978
[Token(Token = "0x170003F3")]
public override int TaskStep
{
[Token(Token = "0x6001AF1")]
[Address(RVA = "0x2D5F80", Offset = "0x2D5380", VA = "0x102D5F80", Slot = "4")]
get
{
return 0;
}
}
// Token: 0x170003F4 RID: 1012
// (get) Token: 0x06001AF2 RID: 6898 RVA: 0x00008790 File Offset: 0x00006990
[Token(Token = "0x170003F4")]
public override bool IsComplete
{
[Token(Token = "0x6001AF2")]
[Address(RVA = "0x77AB30", Offset = "0x779F30", VA = "0x1077AB30", Slot = "5")]
get
{
return default(bool);
}
}
// Token: 0x06001AF3 RID: 6899 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001AF3")]
[Address(RVA = "0x7792D0", Offset = "0x7786D0", VA = "0x107792D0", Slot = "6")]
public override void Initialize()
{
}
// Token: 0x06001AF4 RID: 6900 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001AF4")]
[Address(RVA = "0x779B80", Offset = "0x778F80", VA = "0x10779B80")]
public void NextStep()
{
}
// Token: 0x06001AF5 RID: 6901 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001AF5")]
[Address(RVA = "0x77A210", Offset = "0x779610", VA = "0x1077A210", Slot = "12")]
public virtual void UpdateArrow()
{
}
// Token: 0x06001AF6 RID: 6902 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001AF6")]
[Address(RVA = "0x779130", Offset = "0x778530", VA = "0x10779130", Slot = "13")]
protected virtual void FixedUpdate()
{
}
// Token: 0x06001AF7 RID: 6903 RVA: 0x000087A8 File Offset: 0x000069A8
[Token(Token = "0x6001AF7")]
[Address(RVA = "0x77A670", Offset = "0x779A70", VA = "0x1077A670", Slot = "8")]
public override bool ValidConsole(global::Console console)
{
return default(bool);
}
// Token: 0x06001AF8 RID: 6904 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001AF8")]
[Address(RVA = "0x779120", Offset = "0x778520", VA = "0x10779120", Slot = "9")]
public override void Complete()
{
}
// Token: 0x06001AF9 RID: 6905 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001AF9")]
[Address(RVA = "0x778E40", Offset = "0x778240", VA = "0x10778E40", Slot = "10")]
public override void AppendTaskText(StringBuilder sb)
{
}
// Token: 0x06001AFA RID: 6906 RVA: 0x000087C0 File Offset: 0x000069C0
[Token(Token = "0x6001AFA")]
[Address(RVA = "0x77A040", Offset = "0x779440", VA = "0x1077A040")]
private bool ShouldYellowText()
{
return default(bool);
}
// Token: 0x06001AFB RID: 6907 RVA: 0x00002050 File Offset: 0x00000250
[Token(Token = "0x6001AFB")]
[Address(RVA = "0x779E50", Offset = "0x779250", VA = "0x10779E50")]
private List<global::Console> PickRandomConsoles(TaskTypes taskType, byte[] consoleIds)
{
return null;
}
// Token: 0x06001AFC RID: 6908 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001AFC")]
[Address(RVA = "0x77AB10", Offset = "0x779F10", VA = "0x1077AB10")]
public NormalPlayerTask()
{
}
// Token: 0x06001AFD RID: 6909 RVA: 0x000087D8 File Offset: 0x000069D8
[Token(Token = "0x6001AFD")]
[Address(RVA = "0x77A090", Offset = "0x779490", VA = "0x1077A090")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <Initialize>b__14_0(global::Console v)
{
return default(bool);
}
// Token: 0x06001AFE RID: 6910 RVA: 0x000087F0 File Offset: 0x000069F0
[Token(Token = "0x6001AFE")]
[Address(RVA = "0x77A0D0", Offset = "0x7794D0", VA = "0x1077A0D0")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <UpdateArrow>b__16_2(global::Console c)
{
return default(bool);
}
// Token: 0x06001AFF RID: 6911 RVA: 0x00008808 File Offset: 0x00006A08
[Token(Token = "0x6001AFF")]
[Address(RVA = "0x77A150", Offset = "0x779550", VA = "0x1077A150")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <UpdateArrow>b__16_3(global::Console c)
{
return default(bool);
}
// Token: 0x06001B00 RID: 6912 RVA: 0x00008820 File Offset: 0x00006A20
[Token(Token = "0x6001B00")]
[Address(RVA = "0x4B9080", Offset = "0x4B8480", VA = "0x104B9080")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <ValidConsole>b__18_0(TaskSet set)
{
return default(bool);
}
// Token: 0x06001B01 RID: 6913 RVA: 0x00008838 File Offset: 0x00006A38
[Token(Token = "0x6001B01")]
[Address(RVA = "0x77A190", Offset = "0x779590", VA = "0x1077A190")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <ValidConsole>b__18_1(TaskSet set)
{
return default(bool);
}
// Token: 0x06001B02 RID: 6914 RVA: 0x00008850 File Offset: 0x00006A50
[Token(Token = "0x6001B02")]
[Address(RVA = "0x77A1F0", Offset = "0x7795F0", VA = "0x1077A1F0")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <ValidConsole>b__18_2(TaskTypes tt)
{
return default(bool);
}
// Token: 0x06001B03 RID: 6915 RVA: 0x00008868 File Offset: 0x00006A68
[Token(Token = "0x6001B03")]
[Address(RVA = "0x77A1F0", Offset = "0x7795F0", VA = "0x1077A1F0")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <ValidConsole>b__18_3(TaskTypes tt)
{
return default(bool);
}
// Token: 0x06001B04 RID: 6916 RVA: 0x00008880 File Offset: 0x00006A80
[Token(Token = "0x6001B04")]
[Address(RVA = "0x4B9080", Offset = "0x4B8480", VA = "0x104B9080")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private bool <ValidConsole>b__18_4(TaskSet set)
{
return default(bool);
}
// Token: 0x04001AFD RID: 6909
[Token(Token = "0x4001AFD")]
[FieldOffset(Offset = "0x28")]
public int taskStep;
// Token: 0x04001AFE RID: 6910
[Token(Token = "0x4001AFE")]
[FieldOffset(Offset = "0x2C")]
public int MaxStep;
// Token: 0x04001AFF RID: 6911
[Token(Token = "0x4001AFF")]
[FieldOffset(Offset = "0x30")]
public bool ShowTaskStep;
// Token: 0x04001B00 RID: 6912
[Token(Token = "0x4001B00")]
[FieldOffset(Offset = "0x31")]
public bool ShowTaskTimer;
// Token: 0x04001B01 RID: 6913
[Token(Token = "0x4001B01")]
[FieldOffset(Offset = "0x34")]
public NormalPlayerTask.TimerState TimerStarted;
// Token: 0x04001B02 RID: 6914
[Token(Token = "0x4001B02")]
[FieldOffset(Offset = "0x38")]
public float TaskTimer;
// Token: 0x04001B03 RID: 6915
[Token(Token = "0x4001B03")]
[FieldOffset(Offset = "0x3C")]
public byte[] Data;
// Token: 0x04001B04 RID: 6916
[Token(Token = "0x4001B04")]
[FieldOffset(Offset = "0x40")]
public ArrowBehaviour Arrow;
// Token: 0x04001B05 RID: 6917
[Token(Token = "0x4001B05")]
[FieldOffset(Offset = "0x44")]
protected bool arrowSuspended;
// Token: 0x020004EE RID: 1262
[Token(Token = "0x20004EE")]
public enum TimerState
{
// Token: 0x04001B07 RID: 6919
[Token(Token = "0x4001B07")]
NotStarted,
// Token: 0x04001B08 RID: 6920
[Token(Token = "0x4001B08")]
Started,
// Token: 0x04001B09 RID: 6921
[Token(Token = "0x4001B09")]
Finished
}
// Token: 0x020004EF RID: 1263
[Token(Token = "0x20004EF")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private sealed class <>c__DisplayClass14_0
{
// Token: 0x06001B05 RID: 6917 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001B05")]
[Address(RVA = "0x273A00", Offset = "0x272E00", VA = "0x10273A00")]
public <>c__DisplayClass14_0()
{
}
// Token: 0x06001B06 RID: 6918 RVA: 0x00008898 File Offset: 0x00006A98
[Token(Token = "0x6001B06")]
[Address(RVA = "0x79A740", Offset = "0x799B40", VA = "0x1079A740")]
internal bool <Initialize>b__1(global::Console v)
{
return default(bool);
}
// Token: 0x04001B0A RID: 6922
[Token(Token = "0x4001B0A")]
[FieldOffset(Offset = "0x8")]
public byte[] consoleIds;
}
// Token: 0x020004F0 RID: 1264
[Token(Token = "0x20004F0")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
[Serializable]
private sealed class <>c
{
// Token: 0x06001B08 RID: 6920 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001B08")]
[Address(RVA = "0x273A00", Offset = "0x272E00", VA = "0x10273A00")]
public <>c()
{
}
// Token: 0x06001B09 RID: 6921 RVA: 0x000088B0 File Offset: 0x00006AB0
[Token(Token = "0x6001B09")]
[Address(RVA = "0x799C50", Offset = "0x799050", VA = "0x10799C50")]
internal bool <UpdateArrow>b__16_0(global::Console c)
{
return default(bool);
}
// Token: 0x06001B0A RID: 6922 RVA: 0x000088C8 File Offset: 0x00006AC8
[Token(Token = "0x6001B0A")]
[Address(RVA = "0x799CB0", Offset = "0x7990B0", VA = "0x10799CB0")]
internal bool <UpdateArrow>b__16_1(global::Console console)
{
return default(bool);
}
// Token: 0x06001B0B RID: 6923 RVA: 0x000088E0 File Offset: 0x00006AE0
[Token(Token = "0x6001B0B")]
[Address(RVA = "0x799D60", Offset = "0x799160", VA = "0x10799D60")]
internal bool <ValidConsole>b__18_5(byte b)
{
return default(bool);
}
// Token: 0x04001B0B RID: 6923
[Token(Token = "0x4001B0B")]
[FieldOffset(Offset = "0x0")]
public static readonly NormalPlayerTask.<>c <>9;
// Token: 0x04001B0C RID: 6924
[Token(Token = "0x4001B0C")]
[FieldOffset(Offset = "0x4")]
public static Func<global::Console, bool> <>9__16_0;
// Token: 0x04001B0D RID: 6925
[Token(Token = "0x4001B0D")]
[FieldOffset(Offset = "0x8")]
public static Func<global::Console, bool> <>9__16_1;
// Token: 0x04001B0E RID: 6926
[Token(Token = "0x4001B0E")]
[FieldOffset(Offset = "0xC")]
public static Predicate<byte> <>9__18_5;
}
// Token: 0x020004F1 RID: 1265
[Token(Token = "0x20004F1")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private sealed class <>c__DisplayClass22_0
{
// Token: 0x06001B0C RID: 6924 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x6001B0C")]
[Address(RVA = "0x273A00", Offset = "0x272E00", VA = "0x10273A00")]
public <>c__DisplayClass22_0()
{
}
// Token: 0x06001B0D RID: 6925 RVA: 0x000088F8 File Offset: 0x00006AF8
[Token(Token = "0x6001B0D")]
[Address(RVA = "0x79A900", Offset = "0x799D00", VA = "0x1079A900")]
internal bool <PickRandomConsoles>b__0(global::Console t)
{
return default(bool);
}
// Token: 0x04001B0F RID: 6927
[Token(Token = "0x4001B0F")]
[FieldOffset(Offset = "0x8")]
public TaskTypes taskType;
}
}
| 31.569801 | 89 | 0.662034 | [
"Apache-2.0"
] | KiadsCode/AmogusScipts | NormalPlayerTask.cs | 11,083 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Cdn.Fluent
{
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Cdn Management Client
/// </summary>
public partial class CdnManagementClient : Management.ResourceManager.Fluent.Core.FluentServiceClientBase<CdnManagementClient>, ICdnManagementClient, IAzureClient
{
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Azure Subscription ID.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Version of the API to be used with the client request. Current version is
/// 2017-04-02.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// The preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default value is
/// 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When set to
/// true a unique x-ms-client-request-id value is generated and included in
/// each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IProfilesOperations.
/// </summary>
public virtual IProfilesOperations Profiles { get; private set; }
/// <summary>
/// Gets the IEndpointsOperations.
/// </summary>
public virtual IEndpointsOperations Endpoints { get; private set; }
/// <summary>
/// Gets the IOriginsOperations.
/// </summary>
public virtual IOriginsOperations Origins { get; private set; }
/// <summary>
/// Gets the ICustomDomainsOperations.
/// </summary>
public virtual ICustomDomainsOperations CustomDomains { get; private set; }
/// <summary>
/// Gets the IResourceUsageOperations.
/// </summary>
public virtual IResourceUsageOperations ResourceUsage { get; private set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IEdgeNodesOperations.
/// </summary>
public virtual IEdgeNodesOperations EdgeNodes { get; private set; }
/// <summary>
/// Initializes a new instance of the CdnManagementClient class.
/// </summary>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CdnManagementClient(RestClient restClient) : base(restClient)
{
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
protected override void Initialize()
{
Profiles = new ProfilesOperations(this);
Endpoints = new EndpointsOperations(this);
Origins = new OriginsOperations(this);
CustomDomains = new CustomDomainsOperations(this);
ResourceUsage = new ResourceUsageOperations(this);
Operations = new Operations(this);
EdgeNodes = new EdgeNodesOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2017-10-12";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DeliveryRuleAction>("name"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DeliveryRuleAction>("name"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DeliveryRuleCondition>("name"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DeliveryRuleCondition>("name"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<CustomDomainHttpsParameters>("certificateSource"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<CustomDomainHttpsParameters>("certificateSource"));
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Check the availability of a resource name. This is needed for resources
/// where name is globally unique, such as a CDN endpoint.
/// </summary>
/// <param name='name'>
/// The resource name to validate.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CheckNameAvailabilityOutputInner>> CheckNameAvailabilityWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
CheckNameAvailabilityInput checkNameAvailabilityInput = new CheckNameAvailabilityInput();
if (name != null)
{
checkNameAvailabilityInput.Name = name;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("checkNameAvailabilityInput", checkNameAvailabilityInput);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailability", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/checkNameAvailability").ToString();
List<string> _queryParameters = new List<string>();
if (ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(checkNameAvailabilityInput != null)
{
_requestContent = SafeJsonConvert.SerializeObject(checkNameAvailabilityInput, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CheckNameAvailabilityOutputInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<CheckNameAvailabilityOutputInner>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Check the availability of a resource name. This is needed for resources
/// where name is globally unique, such as a CDN endpoint.
/// </summary>
/// <param name='name'>
/// The resource name to validate.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CheckNameAvailabilityOutputInner>> CheckNameAvailabilityWithSubscriptionWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId");
}
if (ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
CheckNameAvailabilityInput checkNameAvailabilityInput = new CheckNameAvailabilityInput();
if (name != null)
{
checkNameAvailabilityInput.Name = name;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("checkNameAvailabilityInput", checkNameAvailabilityInput);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailabilityWithSubscription", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkNameAvailability").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId));
List<string> _queryParameters = new List<string>();
if (ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(checkNameAvailabilityInput != null)
{
_requestContent = SafeJsonConvert.SerializeObject(checkNameAvailabilityInput, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CheckNameAvailabilityOutputInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<CheckNameAvailabilityOutputInner>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Check if the probe path is a valid path and the file can be accessed. Probe
/// path is the path to a file hosted on the origin server to help accelerate
/// the delivery of dynamic content via the CDN endpoint. This path is relative
/// to the origin path specified in the endpoint configuration.
/// </summary>
/// <param name='probeURL'>
/// The probe URL to validate.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ValidateProbeOutputInner>> ValidateProbeWithHttpMessagesAsync(string probeURL, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId");
}
if (ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
}
if (probeURL == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "probeURL");
}
ValidateProbeInput validateProbeInput = new ValidateProbeInput();
if (probeURL != null)
{
validateProbeInput.ProbeURL = probeURL;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("validateProbeInput", validateProbeInput);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ValidateProbe", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId));
List<string> _queryParameters = new List<string>();
if (ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(validateProbeInput != null)
{
_requestContent = SafeJsonConvert.SerializeObject(validateProbeInput, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ValidateProbeOutputInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ValidateProbeOutputInner>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 45.436751 | 276 | 0.578261 | [
"MIT"
] | LyndseyPaxton/azure-libraries-for-net | src/ResourceManagement/Cdn/Generated/CdnManagementClient.cs | 34,123 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190801.Inputs
{
/// <summary>
/// Defines a managed rule set.
/// </summary>
public sealed class ManagedRuleSetArgs : Pulumi.ResourceArgs
{
[Input("ruleGroupOverrides")]
private InputList<Inputs.ManagedRuleGroupOverrideArgs>? _ruleGroupOverrides;
/// <summary>
/// Defines the rule group overrides to apply to the rule set.
/// </summary>
public InputList<Inputs.ManagedRuleGroupOverrideArgs> RuleGroupOverrides
{
get => _ruleGroupOverrides ?? (_ruleGroupOverrides = new InputList<Inputs.ManagedRuleGroupOverrideArgs>());
set => _ruleGroupOverrides = value;
}
/// <summary>
/// Defines the rule set type to use.
/// </summary>
[Input("ruleSetType", required: true)]
public Input<string> RuleSetType { get; set; } = null!;
/// <summary>
/// Defines the version of the rule set to use.
/// </summary>
[Input("ruleSetVersion", required: true)]
public Input<string> RuleSetVersion { get; set; } = null!;
public ManagedRuleSetArgs()
{
}
}
}
| 31.851064 | 119 | 0.632599 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20190801/Inputs/ManagedRuleSetArgs.cs | 1,497 | C# |
using Microsoft.Extensions.DependencyInjection;
using MTAServerWrapper.Packets.Outgoing.Connection;
using SlipeServer.Packets.Definitions.Commands;
using SlipeServer.Packets.Definitions.Explosions;
using SlipeServer.Packets.Definitions.Join;
using SlipeServer.Packets.Definitions.Player;
using SlipeServer.Packets.Definitions.Satchels;
using SlipeServer.Packets.Definitions.Sync;
using SlipeServer.Packets.Definitions.Transgression;
using SlipeServer.Packets.Definitions.Vehicles;
using SlipeServer.Packets.Definitions.Voice;
using SlipeServer.Packets.Lua.Event;
using SlipeServer.Packets.Rpc;
using SlipeServer.Server.AllSeeingEye;
using SlipeServer.Server.Behaviour;
using SlipeServer.Server.PacketHandling.Handlers.AntiCheat;
using SlipeServer.Server.PacketHandling.Handlers.BulletSync;
using SlipeServer.Server.PacketHandling.Handlers.Command;
using SlipeServer.Server.PacketHandling.Handlers.Connection;
using SlipeServer.Server.PacketHandling.Handlers.Explosions;
using SlipeServer.Server.PacketHandling.Handlers.Lua;
using SlipeServer.Server.PacketHandling.Handlers.Middleware;
using SlipeServer.Server.PacketHandling.Handlers.Player;
using SlipeServer.Server.PacketHandling.Handlers.Player.Sync;
using SlipeServer.Server.PacketHandling.Handlers.Projectile;
using SlipeServer.Server.PacketHandling.Handlers.Rpc;
using SlipeServer.Server.PacketHandling.Handlers.Satchel;
using SlipeServer.Server.PacketHandling.Handlers.Vehicle;
using SlipeServer.Server.PacketHandling.Handlers.Vehicle.Sync;
using SlipeServer.Server.PacketHandling.Handlers.Voice;
using SlipeServer.Server.Repositories;
using System.IO;
namespace SlipeServer.Server.ServerOptions
{
public static class DefaultServerBuilderExtensions
{
public static void AddDefaultQueueHandlers(this ServerBuilder builder)
{
builder.AddPacketHandler<JoinedGamePacketHandler, JoinedGamePacket>();
builder.AddPacketHandler<JoinDataPacketHandler, PlayerJoinDataPacket>();
builder.AddPacketHandler<PlayerQuitPacketHandler, PlayerQuitPacket>();
builder.AddPacketHandler<PlayerTimeoutPacketHandler, PlayerTimeoutPacket>();
builder.AddPacketHandler<PlayerPureSyncPacketHandler, PlayerPureSyncPacket>();
builder.AddPacketHandler<KeySyncPacketHandler, KeySyncPacket>();
builder.AddPacketHandler<CameraSyncPacketHandler, CameraSyncPacket>();
builder.AddPacketHandler<WeaponBulletSyncPacketHandler, WeaponBulletSyncPacket>();
builder.AddPacketHandler<PlayerBulletSyncPacketHandler, PlayerBulletSyncPacket>();
builder.AddPacketHandler<ProjectileSyncPacketHandler, ProjectileSyncPacket>();
builder.AddPacketHandler<ExplosionPacketHandler, ExplosionPacket>();
builder.AddPacketHandler<CommandPacketHandler, CommandPacket>();
builder.AddPacketHandler<DetonateSatchelsPacketHandler, DetonateSatchelsPacket>();
builder.AddPacketHandler<DestroySatchelsPacketHandler, DestroySatchelsPacket>();
builder.AddPacketHandler<RpcPacketHandler, RpcPacket>();
builder.AddPacketHandler<LuaEventPacketHandler, LuaEventPacket>();
builder.AddPacketHandler<PlayerAcInfoPacketHandler, PlayerACInfoPacket>();
builder.AddPacketHandler<PlayerDiagnosticPacketHandler, PlayerDiagnosticPacket>();
builder.AddPacketHandler<PlayerModInfoPacketHandler, PlayerModInfoPacket>();
builder.AddPacketHandler<PlayerNetworkStatusPacketHandler, PlayerNetworkStatusPacket>();
builder.AddPacketHandler<PlayerScreenshotPacketHandler, PlayerScreenshotPacket>();
builder.AddPacketHandler<PlayerWastedPacketHandler, PlayerWastedPacket>();
builder.AddPacketHandler<VehicleInOutPacketHandler, VehicleInOutPacket>();
builder.AddPacketHandler<VehiclePureSyncPacketHandler, VehiclePureSyncPacket>();
builder.AddPacketHandler<VoiceDataPacketHandler, VoiceDataPacket>();
builder.AddPacketHandler<VoiceEndPacketHandler, VoiceEndPacket>();
builder.AddPacketHandler<TransgressionPacketHandler, TransgressionPacket>();
}
public static void AddDefaultBehaviours(this ServerBuilder builder)
{
builder.AddBehaviour<AseBehaviour>();
builder.AddBehaviour<MasterServerAnnouncementBehaviour>("http://master.mtasa.com/ase/add.php");
builder.AddBehaviour<EventLoggingBehaviour>();
builder.AddBehaviour<VelocityBehaviour>();
builder.AddBehaviour<DefaultChatBehaviour>();
builder.AddBehaviour<NicknameChangeBehaviour>();
builder.AddBehaviour<CollisionShapeBehaviour>();
builder.AddBehaviour<PlayerJoinElementBehaviour>();
builder.AddBehaviour<ElementPacketBehaviour>();
builder.AddBehaviour<PedPacketBehaviour>();
builder.AddBehaviour<PlayerPacketBehaviour>();
builder.AddBehaviour<VehicleWarpBehaviour>();
builder.AddBehaviour<VehicleRespawnBehaviour>();
builder.AddBehaviour<VehicleBehaviour>();
builder.AddBehaviour<VoiceBehaviour>();
builder.AddBehaviour<LightSyncBehaviour>();
builder.AddBehaviour<TeamBehaviour>();
builder.AddBehaviour<RadarAreaBehaviour>();
builder.AddBehaviour<BlipBehaviour>();
builder.AddBehaviour<ObjectPacketBehaviour>();
builder.AddBehaviour<VehicleBehaviour>();
builder.AddBehaviour<PickupBehaviour>();
builder.AddBehaviour<MarkerBehaviour>();
}
public static void AddDefaultServices(this ServerBuilder builder)
{
builder.ConfigureServices(services =>
{
services.AddSingleton<ISyncHandlerMiddleware<ProjectileSyncPacket>, RangeSyncHandlerMiddleware<ProjectileSyncPacket>>(
x => new RangeSyncHandlerMiddleware<ProjectileSyncPacket>(x.GetRequiredService<IElementRepository>(), builder.Configuration.ExplosionSyncDistance)
);
services.AddSingleton<ISyncHandlerMiddleware<DetonateSatchelsPacket>, RangeSyncHandlerMiddleware<DetonateSatchelsPacket>>(
x => new RangeSyncHandlerMiddleware<DetonateSatchelsPacket>(x.GetRequiredService<IElementRepository>(), builder.Configuration.ExplosionSyncDistance, false)
);
services.AddSingleton<ISyncHandlerMiddleware<DestroySatchelsPacket>, RangeSyncHandlerMiddleware<DestroySatchelsPacket>>(
x => new RangeSyncHandlerMiddleware<DestroySatchelsPacket>(x.GetRequiredService<IElementRepository>(), builder.Configuration.ExplosionSyncDistance, false)
);
services.AddSingleton<ISyncHandlerMiddleware<PlayerPureSyncPacket>, SubscriptionSyncHandlerMiddleware<PlayerPureSyncPacket>>();
services.AddSingleton<ISyncHandlerMiddleware<KeySyncPacket>, SubscriptionSyncHandlerMiddleware<KeySyncPacket>>();
services.AddSingleton<ISyncHandlerMiddleware<LightSyncBehaviour>, MaxRangeSyncHandlerMiddleware<LightSyncBehaviour>>(
x => new MaxRangeSyncHandlerMiddleware<LightSyncBehaviour>(x.GetRequiredService<IElementRepository>(), builder.Configuration.LightSyncRange)
);
});
}
public static void AddDefaults(this ServerBuilder builder)
{
builder.AddDefaultQueueHandlers();
builder.AddDefaultBehaviours();
builder.AddDefaultServices();
builder.AddNetWrapper(
Directory.GetCurrentDirectory(),
"net",
builder.Configuration.Host,
builder.Configuration.Port,
builder.Configuration.AntiCheat);
}
}
}
| 52.704698 | 175 | 0.741627 | [
"MIT"
] | ERAGON007/Slipe-Server | SlipeServer.Server/ServerOptions/DefaultServerBuilderExtensions.cs | 7,855 | C# |
using Dapper;
using Discount.API.Entities;
using Microsoft.Extensions.Configuration;
using Npgsql;
using System;
using System.Threading.Tasks;
namespace Discount.API.Repositories
{
public class DiscountRepository : IDiscountRepository
{
private readonly IConfiguration _configuration;
public DiscountRepository(IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public async Task<Coupon> GetDiscount(string productName)
{
using var connection = new NpgsqlConnection
(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var coupon = await connection.QueryFirstOrDefaultAsync<Coupon>
("Select * from Coupon where ProductName = @ProductName", new { ProductName = productName });
if (coupon == null)
{
return new Coupon { ProductName = "No Discount", Amount = 0, Description = "No Discount Desc" };
}
return coupon;
}
public async Task<bool> CreateDiscount(Coupon coupon)
{
using var connection = new NpgsqlConnection
(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync(
"insert into coupon(productname, description, amount) values(@ProductName, @Description, @Amount)",
new { ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount });
if (affected == 0)
{
return false;
}
return true;
}
public async Task<bool> UpdateDiscount(Coupon coupon)
{
using var connection = new NpgsqlConnection
(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync(
"update coupon set productname = @ProductName, description = @Description, amount = @Amount where id = @Id",
new { ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount, Id = coupon.Id });
if (affected == 0)
{
return false;
}
return true;
}
public async Task<bool> DeleteDiscount(string productName)
{
using var connection = new NpgsqlConnection
(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync("delete from coupon where productname = @ProductName", new { ProductName = productName });
if (affected == 0)
{
return false;
}
return true;
}
}
}
| 33.482759 | 149 | 0.603845 | [
"MIT"
] | gbeydtha/AspnetMicorservices | src/Services/Discount/Discount.API/Repositories/DiscountRepository.cs | 2,915 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class SpellEffectsDisplay : GuiBase_Draggable {
public int SlotNumber;
//public static UWCharacter UWCharacter.Instance;
private int setSpell=-1;
private RawImage thisSpell;
private static Texture2D SpellBlank;
public override void Start()
{
base.Start();
thisSpell = this.GetComponent<RawImage>();
if (SpellBlank==null)
{
SpellBlank= (Texture2D)Resources.Load <Texture2D> (_RES +"/HUD/Runes/rune_blank");
}
}
// Update is called once per frame
public override void Update ()
{
base.Update();
if (UWCharacter.Instance.ActiveSpell[SlotNumber] != null)
{
if (UWCharacter.Instance.ActiveSpell[SlotNumber].EffectIcon()!=setSpell)
{
setSpell= UWCharacter.Instance.ActiveSpell[SlotNumber].EffectIcon();
if (setSpell > -1)
{
//thisSpell.texture= Resources.Load <Texture2D> (_RES +"/HUD/Spells/spells_" + UWCharacter.Instance.ActiveSpell[SlotNumber].EffectIcon().ToString("D4"));
thisSpell.texture = GameWorldController.instance.SpellIcons.LoadImageAt(UWCharacter.Instance.ActiveSpell[SlotNumber].EffectIcon());
}
else
{
thisSpell.texture= SpellBlank;//Resources.Load <Texture2D> ("HUD/Runes/rune_blank");
}
}
}
else
{
if (setSpell>=-1)
{
thisSpell.texture= SpellBlank;//Resources.Load <Texture2D> ("HUD/Runes/rune_blank");
setSpell=-2;
}
}
}
public void OnClick(BaseEventData evnt)
{
if (Dragging){return;}
PointerEventData pntr = (PointerEventData)evnt;
//Debug.Log (pnt.pointerId);
ClickEvent(pntr.pointerId);
}
void ClickEvent(int ptrID)
{
if (UWCharacter.Instance.ActiveSpell[SlotNumber]==null)
{
return;
}
switch (ptrID)
{
case -1://Left click
{
UWCharacter.Instance.ActiveSpell[SlotNumber].CancelEffect();
break;
}
case -2://right click
{
UWHUD.instance.MessageScroll.Add (UWCharacter.Instance.ActiveSpell[SlotNumber].getSpellDescription());
break;
}
}
}
}
| 24.082353 | 158 | 0.701026 | [
"MIT"
] | FaizanMughal/UnderworldExporter | UnityScripts/scripts/UI/SpellEffectsDisplay.cs | 2,049 | C# |
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using Tektosyne;
using Tektosyne.Geometry;
using Tektosyne.IO;
using Tektosyne.Windows;
using Tektosyne.Xml;
using Hexkit.Global;
namespace Hexkit.Scenario {
/// <summary>
/// Represents a fixed image that is overlayed on the entire map display.</summary>
/// <remarks><para>
/// <b>OverlayImage</b> is serialized to the XML element "overlay" defined in <see
/// cref="FilePaths.ScenarioSchema"/> or <see cref="FilePaths.OptionsSchema"/>, depending on
/// which of two images it represents:
/// </para><list type="bullet"><item>
/// A permanent opaque image that appears behind the map display and replaces transparent
/// terrain images. This variant is saved to the <see cref="AreaSection"/> XML file.
/// </item><item>
/// A temporary image with variable opacity that appears on top of the map display within Hexkit
/// Editor only. This variant is saved to the Hexkit Editor options file.
/// </item></list></remarks>
public sealed class OverlayImage: XmlSerializable, ICloneable {
#region OverlayImage(Double)
/// <overloads>
/// Initializes a new instance of the <see cref="OverlayImage"/> class.</overloads>
/// <summary>
/// Initializes a new instance of the <see cref="OverlayImage"/> class with the specified
/// opacity.</summary>
/// <param name="opacity">
/// The initial value for the <see cref="Opacity"/> property.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="opacity"/> is less than zero or greater than one.</exception>
internal OverlayImage(double opacity) {
if (opacity < 0.0 || opacity > 1.0)
ThrowHelper.ThrowArgumentOutOfRangeExceptionWithFormat(
"opacity", opacity, Tektosyne.Strings.ArgumentLessOrGreater, 0, 1);
this._bounds = new RectI(0, 0, 1, 1);
this._opacity = opacity;
this._path = FilePaths.CreateCommonPath();
}
#endregion
#region OverlayImage(OverlayImage)
/// <summary>
/// Initializes a new instance of the <see cref="OverlayImage"/> class with property values
/// copied from the specified instance.</summary>
/// <param name="overlay">
/// The <see cref="OverlayImage"/> instance whose property values are copied to the new
/// instance.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="overlay"/> is a null reference.</exception>
/// <remarks>
/// This constructor is called by <see cref="Clone"/> to perform a deep copy of the
/// specified <paramref name="overlay"/>, including a deep copy of all mutable objects that
/// are owned by the <paramref name="overlay"/>.</remarks>
public OverlayImage(OverlayImage overlay) {
if (overlay == null)
ThrowHelper.ThrowArgumentNullException("overlay");
this._bitmap = overlay._bitmap;
this._bounds = overlay._bounds;
this._opacity = overlay._opacity;
this._path = (RootedPath) overlay._path.Clone();
this._preserveAspectRatio = overlay._preserveAspectRatio;
}
#endregion
#region Private Fields
// property backers
private BitmapSource _bitmap;
private RectI _bounds;
private double _opacity;
private RootedPath _path;
private bool _preserveAspectRatio;
#endregion
#region AspectRatio
/// <summary>
/// Gets the original aspect ratio of the associated <see cref="Bitmap"/>.</summary>
/// <value><para>
/// The <see cref="BitmapSource.PixelWidth"/> of the associated <see cref="Bitmap"/>,
/// divided by its <see cref="BitmapSource.PixelHeight"/>.
/// </para><para>-or-</para><para>
/// Zero if <see cref="Bitmap"/> is a null reference, or its <see
/// cref="BitmapSource.PixelHeight"/> is zero.</para></value>
public double AspectRatio {
get {
var bitmap = Bitmap;
if (bitmap == null) return 0.0;
int pixelHeight = bitmap.PixelHeight;
if (pixelHeight > 0)
return bitmap.PixelWidth / (double) pixelHeight;
return 0.0;
}
}
#endregion
#region Bitmap
/// <summary>
/// Gets the <see cref="BitmapSource"/> created from the file located at <see cref="Path"/>.
/// </summary>
/// <value>
/// The <see cref="BitmapSource"/> created from the file located at <see cref="Path"/>. The
/// default is a null reference.</value>
/// <remarks><para>
/// <b>Bitmap</b> holds a null reference until <see cref="Load"/> was successfully invoked
/// on the <see cref="OverlayImage"/>, and again whenever <see cref="Path"/> has changed.
/// </para><para>
/// <b>Bitmap</b> always uses the <see cref="PixelFormats.Pbgra32"/> format, regardless of
/// the format of the file located at <see cref="Path"/>.</para></remarks>
public BitmapSource Bitmap {
[DebuggerStepThrough]
get { return this._bitmap; }
}
#endregion
#region Bounds
/// <summary>
/// Gets or sets the bounds of the <see cref="OverlayImage"/>.</summary>
/// <value>
/// A <see cref="RectI"/> indicating bounds of the <see cref="OverlayImage"/>, relative to
/// the entire map display area. The default is a <see cref="RectI.Location"/> of (0,0) and
/// a <see cref="RectI.Size"/> of (1,1).</value>
/// <exception cref="ArgumentException">
/// The property is set to a value whose <see cref="RectI.Width"/> or <see
/// cref="RectI.Height"/> is equal to or less than zero.</exception>
/// <exception cref="InvalidOperationException">
/// The property is set, and <see cref="ApplicationInfo.IsEditor"/> is <c>false</c>.
/// </exception>
/// <remarks>
/// <b>Bounds</b> holds the value of the "bounds" XML element. The coordinates are relative
/// to the entire map display area, comprising the current <see cref="AreaSection.MapGrid"/>
/// plus any surrounding borders.</remarks>
public RectI Bounds {
[DebuggerStepThrough]
get { return this._bounds; }
set {
ApplicationInfo.CheckEditor();
if (value.Width <= 0)
ThrowHelper.ThrowArgumentException(
"value.Width", Tektosyne.Strings.ArgumentNotPositive);
if (value.Height <= 0)
ThrowHelper.ThrowArgumentException(
"value.Height", Tektosyne.Strings.ArgumentNotPositive);
this._bounds = value;
}
}
#endregion
#region IsEmpty
/// <summary>
/// Gets a value indicating whether the current <see cref="Path"/> is empty.</summary>
/// <value>
/// <c>true</c> if <see cref="Path"/> is an empty string; otherwise, <c>false</c>.</value>
/// <remarks>
/// If <b>IsEmpty</b> is <c>true</c>, the <see cref="OverlayImage"/> has no visual effect
/// and is not serialized to the associated XML file.</remarks>
public bool IsEmpty {
[DebuggerStepThrough]
get { return this._path.IsEmpty; }
}
#endregion
#region Opacity
/// <summary>
/// Gets or sets the opacity of the <see cref="OverlayImage"/>.</summary>
/// <value>
/// The opacity of the <see cref="OverlayImage"/>, expressed as a value within the closed
/// interval [0, 1].</value>
/// <exception cref="ArgumentOutOfRangeException">
/// The property is set to a value that is less than zero or greater than one.</exception>
/// <exception cref="InvalidOperationException">
/// The property is set, and <see cref="ApplicationInfo.IsEditor"/> is <c>false</c>.
/// </exception>
/// <remarks>
/// <b>Opacity</b> holds the value of the "opacity" XML attribute.</remarks>
public double Opacity {
[DebuggerStepThrough]
get { return this._opacity; }
set {
ApplicationInfo.CheckEditor();
if (value < 0.0 || value > 1.0)
ThrowHelper.ThrowArgumentOutOfRangeExceptionWithFormat(
"value", value, Tektosyne.Strings.ArgumentLessOrGreater, 0, 1);
this._opacity = value;
}
}
#endregion
#region Path
/// <summary>
/// Gets or sets the file path for the <see cref="OverlayImage"/>.</summary>
/// <value>
/// The file path for the <see cref="OverlayImage"/>, relative to the current root folder
/// for Hexkit user files. The default is an empty string.</value>
/// <exception cref="InvalidOperationException">
/// The property is set, and <see cref="ApplicationInfo.IsEditor"/> is <c>false</c>.
/// </exception>
/// <remarks><para>
/// <b>Path</b> returns an empty string when set to a null reference. This property holds
/// the value of the "href" XML attribute.
/// </para><para>
/// Changing <b>Path</b> sets the <see cref="Bitmap"/> property to a null reference. Clients
/// must explicitly call <see cref="Load"/> to load the new <see cref="Bitmap"/>.
/// </para></remarks>
public string Path {
get { return this._path.RelativePath; }
set {
ApplicationInfo.CheckEditor();
this._path = this._path.Change(value);
this._bitmap = null;
}
}
#endregion
#region PreserveAspectRatio
/// <summary>
/// Gets or sets a value indicating whether the original <see cref="AspectRatio"/> should be
/// preserved.</summary>
/// <value>
/// <c>true</c> to preserve the <see cref="AspectRatio"/> when changing the size of the <see
/// cref="Bounds"/>; otherwise, <c>false</c>. The default is <c>false</c>.</value>
/// <exception cref="InvalidOperationException">
/// The property is set, and <see cref="ApplicationInfo.IsEditor"/> is <c>false</c>.
/// </exception>
/// <remarks><para>
/// <b>PreserveAspectRatio</b> holds the value of the "preserveAspectRatio" XML attribute.
/// </para><para>
/// Setting this property to <c>true</c> has no immediate effect on the current <see
/// cref="Bounds"/> and does not constrain future changes to the <see cref="Bounds"/>
/// property. Clients must examine <b>PreserveAspectRatio</b> and apply the appropriate
/// constraints manually.</para></remarks>
public bool PreserveAspectRatio {
[DebuggerStepThrough]
get { return this._preserveAspectRatio; }
set {
ApplicationInfo.CheckEditor();
this._preserveAspectRatio = value;
}
}
#endregion
#region Load
/// <summary>
/// Attempts to load the <see cref="Bitmap"/> located at <see cref="Path"/>.</summary>
/// <param name="owner">
/// The parent <see cref="Window"/> for any dialogs.</param>
/// <returns>
/// <c>true</c> if <see cref="Bitmap"/> is valid; otherwise, <c>false</c>.</returns>
/// <remarks><para>
/// <b>Load</b> returns <c>false</c> and sets the <see cref="Bitmap"/> property to a null
/// reference if <see cref="IsEmpty"/> is <c>true</c> or an error occurred during loading.
/// </para><para>
/// On error, <b>Load</b> also clears the <see cref="Path"/> property and informs the user.
/// No exceptions are propagated to the caller.</para></remarks>
public bool Load(Window owner) {
if (IsEmpty) {
this._bitmap = null;
return false;
}
try {
// create bitmap from specified path
Uri source = new Uri(Path, UriKind.RelativeOrAbsolute);
this._bitmap = new BitmapImage(source);
// convert bitmap to standard color format
// (necessary to prevent exceptions during WPF composition)
this._bitmap = new FormatConvertedBitmap(
this._bitmap, PixelFormats.Pbgra32, null, 0.0);
this._bitmap.Freeze();
return true;
}
catch (Exception e) {
if (this._bitmap != null)
this._bitmap = null;
Mouse.OverrideCursor = null;
MessageDialog.Show(owner,
String.Format(ApplicationInfo.Culture, Global.Strings.ErrorImageFileOpen, Path),
Global.Strings.TitleImageError, e, MessageBoxButton.OK, Global.Images.Error);
this._path.Clear();
return false;
}
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a new <see cref="OverlayImage"/> object that is a deep copy of the current
/// instance.</summary>
/// <returns>
/// A new <see cref="OverlayImage"/> object that is a deep copy of the current instance.
/// </returns>
/// <remarks>
/// <b>Clone</b> calls the <see cref="OverlayImage(OverlayImage)"/> copy constructor with
/// this <see cref="OverlayImage"/> object.</remarks>
public object Clone() {
return new OverlayImage(this);
}
#endregion
#region XmlSerializable Members
#region ConstXmlName
/// <summary>
/// The name of the XML element associated with the <see cref="OverlayImage"/> class.
/// </summary>
/// <remarks>
/// <b>ConstXmlName</b> holds the value "overlay", indicating the XML element in <see
/// cref="FilePaths.ScenarioSchema"/> whose data is managed by the <see
/// cref="OverlayImage"/> class.</remarks>
public const string ConstXmlName = "overlay";
#endregion
#region ReadXmlAttributes
/// <summary>
/// Reads XML attribute data into the <see cref="OverlayImage"/> object using the specified
/// <see cref="XmlReader"/>.</summary>
/// <param name="reader">
/// The <see cref="XmlReader"/> from which to read.</param>
/// <exception cref="XmlException">
/// An error occurred while parsing the XML data provided by <paramref name="reader"/>.
/// </exception>
/// <exception cref="System.Xml.Schema.XmlSchemaException">
/// <paramref name="reader"/> is an <see cref="XmlValidatingReader"/>, and the XML data did
/// not conform to <see cref="FilePaths.ScenarioSchema"/>.</exception>
/// <remarks>
/// Please refer to class <see cref="XmlSerializable"/> for a complete description of this
/// method.</remarks>
protected override void ReadXmlAttributes(XmlReader reader) {
string path = null;
reader.ReadAttributeAsString("href", ref path);
this._path = this._path.Change(path);
reader.ReadAttributeAsDouble("opacity", ref this._opacity);
reader.ReadAttributeAsBoolean("preserveAspectRatio", ref this._preserveAspectRatio);
}
#endregion
#region ReadXmlElements
/// <summary>
/// Reads XML element data into the <see cref="OverlayImage"/> object using the specified
/// <see cref="XmlReader"/>.</summary>
/// <param name="reader">
/// The <see cref="XmlReader"/> from which to read.</param>
/// <returns>
/// <c>true</c> if the current node of the specified <paramref name="reader"/> contained any
/// matching data; otherwise, <c>false</c>.</returns>
/// <exception cref="XmlException">
/// An error occurred while parsing the XML data provided by <paramref name="reader"/>.
/// </exception>
/// <exception cref="System.Xml.Schema.XmlSchemaException">
/// <paramref name="reader"/> is an <see cref="XmlValidatingReader"/>, and the XML data did
/// not conform to <see cref="FilePaths.ScenarioSchema"/>.</exception>
/// <remarks>
/// Please refer to class <see cref="XmlSerializable"/> for a complete description of this
/// method.</remarks>
protected override bool ReadXmlElements(XmlReader reader) {
switch (reader.Name) {
case "bounds":
this._bounds = SimpleXml.ReadRectI(reader);
return true;
default: return false;
}
}
#endregion
#region WriteXmlAttributes
/// <summary>
/// Writes all current data of the <see cref="OverlayImage"/> object that is serialized to
/// XML attributes to the specified <see cref="XmlWriter"/>.</summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to which to write.</param>
/// <remarks>
/// Please refer to class <see cref="XmlSerializable"/> for a complete description of this
/// method.</remarks>
protected override void WriteXmlAttributes(XmlWriter writer) {
writer.WriteAttributeString("href", Path);
if (Opacity != 1.0)
writer.WriteAttributeString("opacity", XmlConvert.ToString(Opacity));
if (PreserveAspectRatio)
writer.WriteAttributeString("preserveAspectRatio",
XmlConvert.ToString(PreserveAspectRatio));
}
#endregion
#region WriteXmlElements
/// <summary>
/// Writes all current data of the <see cref="OverlayImage"/> object that is serialized to
/// nested XML elements to the specified <see cref="XmlWriter"/>.</summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to which to write.</param>
/// <remarks>
/// Please refer to class <see cref="XmlSerializable"/> for a complete description of this
/// method.</remarks>
protected override void WriteXmlElements(XmlWriter writer) {
writer.WriteStartElement("bounds");
SimpleXml.WriteRectI(writer, Bounds);
writer.WriteEndElement();
}
#endregion
#endregion
}
}
| 40.717345 | 100 | 0.579648 | [
"MIT"
] | prepare/HexKit | Hexkit.Scenario/OverlayImage.cs | 19,017 | C# |
using System;
using Microsoft.Xrm.Sdk;
#if NET
using DLaB.Xrm;
namespace DataverseUnitTest.Builders
#else
namespace DLaB.Xrm.Test.Builders
#endif
{
/// <summary>
/// Interface for OrganizationServiceBuilder messages that get called by the TestMethodClassBase
/// </summary>
public interface IAgnosticServiceBuilder
{
/// <summary>
/// Defaults the Parent BusinessUnit Id of all business units to the root BU if not already populated
/// </summary>
IAgnosticServiceBuilder WithDefaultParentBu();
/// <summary>Defaults the entity name of all created entities.</summary>
/// <param name="getName">function to call to get the name for the given Entity and it's Primary Field Info</param>
IAgnosticServiceBuilder WithEntityNameDefaulted(Func<Entity, PrimaryFieldInfo, string> getName);
/// <summary>
/// Asserts that any create of an entity has the id populated. Useful to ensure that all entities can be deleted after they have been created since the id is known.
/// </summary>
IAgnosticServiceBuilder AssertIdNonEmptyOnCreate();
/// <summary>Builds this IOrganizationService.</summary>
IOrganizationService Build();
}
}
| 39.0625 | 173 | 0.7008 | [
"MIT"
] | bobbyangers/XrmUnitTest | DLaB.Xrm.Test.Base/Builders/IAgnosticServiceBuilder.cs | 1,252 | C# |
using System.Collections.Generic;
using Orchard.AuditTrail.Services;
using Orchard.Environment.Extensions;
using Orchard.Security;
using Orchard.Users.Events;
namespace Orchard.AuditTrail.Providers.Users {
[OrchardFeature("Orchard.AuditTrail.Users")]
public class UserEventHandler : IUserEventHandler {
private readonly IAuditTrailManager _auditTrailManager;
private readonly IWorkContextAccessor _wca;
public UserEventHandler(IAuditTrailManager auditTrailManager, IWorkContextAccessor wca) {
_auditTrailManager = auditTrailManager;
_wca = wca;
}
public void LoggedIn(IUser user) {
RecordAuditTrail(UserAuditTrailEventProvider.LoggedIn, user);
}
public void LoggedOut(IUser user) {
RecordAuditTrail(UserAuditTrailEventProvider.LoggedOut, user);
}
public void LogInFailed(string userNameOrEmail, string password) {
var eventData = new Dictionary<string, object> {
{"UserName", userNameOrEmail}
};
_auditTrailManager.CreateRecord<UserAuditTrailEventProvider>(UserAuditTrailEventProvider.LogInFailed, _wca.GetContext().CurrentUser, properties: null, eventData: eventData, eventFilterKey: "user", eventFilterData: userNameOrEmail);
}
public void ChangedPassword(IUser user) {
RecordAuditTrail(UserAuditTrailEventProvider.PasswordChanged, user);
}
private void RecordAuditTrail(string eventName, IUser user) {
var properties = new Dictionary<string, object> {
{"User", user}
};
var eventData = new Dictionary<string, object> {
{"UserId", user.Id},
{"UserName", user.UserName}
};
_auditTrailManager.CreateRecord<UserAuditTrailEventProvider>(eventName, _wca.GetContext().CurrentUser, properties, eventData, eventFilterKey: "user", eventFilterData: user.UserName);
}
public void Creating(UserContext context) {
}
public void Created(UserContext context) {
}
public void LoggingIn(string userNameOrEmail, string password) {
}
public void AccessDenied(IUser user) {
}
public void SentChallengeEmail(IUser user) {
}
public void ConfirmedEmail(IUser user) {
}
public void Approved(IUser user) {
}
public void Moderate(IUser user) {
}
}
} | 33.276316 | 243 | 0.65085 | [
"BSD-3-Clause"
] | cmsilv/Orchard | src/Orchard.Web/Modules/Orchard.AuditTrail/Providers/Users/UserEventHandler.cs | 2,531 | C# |
//
// This file is a part of the Dminator project.
// https://github.com/Orace
//
using System.Collections.Generic;
using System.Linq;
namespace Dminator.Stategies
{
public class DumbStrategy : IStrategy
{
private DumbStrategy()
{
}
public static DumbStrategy Instance { get; } = new DumbStrategy();
public IEnumerable<Choice> GetChoices(IMineGame mineGame, MineDetector mineDetector)
{
var result = new MineArray<double>(mineGame.LineCount, mineGame.ColumnCount);
foreach (var coordinate in mineGame.AllCells())
{
var contant = mineGame.NeighboursMineCountAt(coordinate);
if (contant == null)
continue;
result[coordinate] = double.PositiveInfinity;
var neighbours = mineGame.GetNeighbours(coordinate).ToList();
var unclickedNeighbours =
neighbours.Where(coords => mineGame.NeighboursMineCountAt(coords) == null).ToList();
if (unclickedNeighbours.Count == 0)
continue;
var score = contant.Value / unclickedNeighbours.Count;
foreach (var c in unclickedNeighbours) result[c] += score;
}
var bestScore = result.Min();
var candidates = mineGame.AllCells().Where(coords => Equals(result[coords], bestScore));
return candidates.Select(c => new Choice(c, 0.2)).ToList();
}
}
} | 32.382979 | 104 | 0.590013 | [
"Unlicense"
] | Orace/Dminator | Dminator/Stategies/DumbStrategy.cs | 1,524 | C# |
namespace HTMLPreviewer.Web
{
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using HTMLPreviewer.Data;
using HTMLPreviewer.Web.Infrastructure.Extensions;
using HTMLPreviewer.Services.Mapping;
using HTMLPreviewer.Services.Data.Models;
using AspNetCoreHero.ToastNotification;
using AspNetCoreHero.ToastNotification.Extensions;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services
.AddDatabase(this.Configuration)
.AddApplicationServices()
.AddAntiforgerySecurity()
.AddControllersWithViews();
services
.AddNotyf(config =>
{
config.DurationInSeconds = 3;
config.IsDismissable = false;
config.Position = NotyfPosition.TopRight;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
AutoMapperConfig.RegisterMappings(typeof(ModelValidation).GetTypeInfo().Assembly);
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var dbContext = serviceScope.ServiceProvider
.GetRequiredService<HTMLPreviewerDbContext>();
dbContext.Database.EnsureCreated();
}
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app
.UseExceptionHandler("/Home/Error")
.UseHsts();
}
app
.UseNotyf()
.UseStatusCodePagesWithRedirects("/Home/NotFoundPage?statusCode={0}")
.UseHttpsRedirection()
.UseStaticFiles()
.UseRouting()
.UseAuthorization()
.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 30.788235 | 94 | 0.556744 | [
"MIT"
] | stanislavstoyanov99/HTMLPreviewer | src/Web/HTMLPreviewer.Web/Startup.cs | 2,617 | C# |
// <copyright file="GeometricTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Linq;
using MathNet.Numerics.Distributions;
using NUnit.Framework;
namespace MathNet.Numerics.Tests.DistributionTests.Discrete
{
/// <summary>
/// Geometric distribution tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class GeometricTests
{
/// <summary>
/// Can create Geometric.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void CanCreateGeometric(double p)
{
var d = new Geometric(p);
Assert.AreEqual(p, d.P);
}
/// <summary>
/// Geometric create fails with bad parameters.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(double.NaN)]
[TestCase(-1.0)]
[TestCase(2.0)]
public void GeometricCreateFailsWithBadParameters(double p)
{
Assert.That(() => new Geometric(p), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
var d = new Geometric(0.3);
Assert.AreEqual("Geometric(p = 0.3)", d.ToString());
}
/// <summary>
/// Validate entropy.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void ValidateEntropy(double p)
{
var d = new Geometric(p);
Assert.AreEqual(((-p * Math.Log(p, 2.0)) - ((1.0 - p) * Math.Log(1.0 - p, 2.0))) / p, d.Entropy);
}
/// <summary>
/// Validate skewness.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void ValidateSkewness(double p)
{
var d = new Geometric(p);
Assert.AreEqual((2.0 - p) / Math.Sqrt(1.0 - p), d.Skewness);
}
/// <summary>
/// Validate mode.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void ValidateMode(double p)
{
var d = new Geometric(p);
Assert.AreEqual(1, d.Mode);
}
[TestCase(0.0, double.PositiveInfinity)]
[TestCase(0.0001, 6932.0)]
[TestCase(0.1, 7.0)]
[TestCase(0.3, 2.0)]
[TestCase(0.9, 1.0)]
[TestCase(1.0, 1.0)]
public void ValidateMedian(double p, double expected)
{
Assert.That(new Geometric(p).Median, Is.EqualTo(expected));
}
/// <summary>
/// Validate minimum.
/// </summary>
[Test]
public void ValidateMinimum()
{
var d = new Geometric(0.3);
Assert.AreEqual(1.0, d.Minimum);
}
/// <summary>
/// Validate maximum.
/// </summary>
[Test]
public void ValidateMaximum()
{
var d = new Geometric(0.3);
Assert.AreEqual(int.MaxValue, d.Maximum);
}
/// <summary>
/// Validate probability.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
/// <param name="x">Input X value.</param>
[TestCase(0.0, -1)]
[TestCase(0.3, 0)]
[TestCase(1.0, 1)]
[TestCase(1.0, 2)]
public void ValidateProbability(double p, int x)
{
var d = new Geometric(p);
if (x > 0)
{
Assert.AreEqual(Math.Pow(1.0 - p, x - 1) * p, d.Probability(x));
}
else
{
Assert.AreEqual(0.0, d.Probability(x));
}
}
/// <summary>
/// Validate probability log.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
/// <param name="x">Input X value.</param>
/// <param name="pln">Expected value.</param>
[TestCase(0.0, -1, double.NegativeInfinity)]
[TestCase(0.0, 0, double.NegativeInfinity)]
[TestCase(0.0, 1, double.NegativeInfinity)]
[TestCase(0.0, 2, double.NegativeInfinity)]
[TestCase(0.3, -1, double.NegativeInfinity)]
[TestCase(0.3, 0, double.NegativeInfinity)]
[TestCase(0.3, 1, -1.2039728043259360296301803719337238685164245381839102)]
[TestCase(0.3, 2, -1.5606477482646686)]
[TestCase(1.0, -1, double.NegativeInfinity)]
[TestCase(1.0, 0, double.NegativeInfinity)]
[TestCase(1.0, 1, double.NaN)]
[TestCase(1.0, 2, double.NegativeInfinity)]
public void ValidateProbabilityLn(double p, int x, double pln)
{
var d = new Geometric(p);
Assert.AreEqual(pln, d.ProbabilityLn(x));
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var d = new Geometric(0.3);
d.Sample();
}
/// <summary>
/// Can sample sequence.
/// </summary>
[Test]
public void CanSampleSequence()
{
var d = new Geometric(0.3);
var ied = d.Samples();
GC.KeepAlive(ied.Take(5).ToArray());
}
/// <summary>
/// Validate cumulative distribution.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
/// <param name="x">Input X value.</param>
[TestCase(0.0, -1)]
[TestCase(0.3, 0)]
[TestCase(1.0, 1)]
[TestCase(1.0, 2)]
public void ValidateCumulativeDistribution(double p, int x)
{
var d = new Geometric(p);
Assert.AreEqual(1.0 - Math.Pow(1.0 - p, x), d.CumulativeDistribution(x));
}
}
}
| 32.497854 | 117 | 0.55177 | [
"MIT"
] | WeihanLi/mathnet-numerics | src/Numerics.Tests/DistributionTests/Discrete/GeometricTests.cs | 7,572 | C# |
using System;
using GalaSoft.MvvmLight;
namespace TLCGen.Generators.CCOL.Settings
{
[Serializable]
public class CCOLGeneratorFolderSettingModel : ViewModelBase
{
private string _Setting;
public string Default { get; set; }
public string Setting
{
get => _Setting;
set
{
if(value != null && value.EndsWith(";"))
_Setting = value;
else if (value != null)
_Setting = value + ";";
RaisePropertyChanged("Setting");
}
}
public string Description { get; set; }
public CCOLGeneratorFolderSettingModel()
{
}
}
}
| 22.875 | 64 | 0.510929 | [
"MIT"
] | PeterSnijders/TLCGen | TLCGen.PluggedInItems/TLCGen.Generators.CCOL/Settings/CCOLGeneratorFolderSettingModel.cs | 734 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
namespace Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.Tests
{
[ConfigurationElementType(typeof(MockFaultContractExceptionHandlerData))]
public class MockFaultContractExceptionHandler : IExceptionHandler
{
public Exception HandledException;
#region IExceptionHandler Members
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
this.HandledException = exception;
return new FaultContractWrapperException(new MockFaultContract(exception.Message), handlingInstanceId);
}
#endregion
}
public class MockFaultContractExceptionHandlerData : ExceptionHandlerData
{
public MockFaultContractExceptionHandlerData()
{
}
public MockFaultContractExceptionHandlerData(string name)
: base(name, typeof(FaultContractExceptionHandler))
{
}
public override IExceptionHandler BuildExceptionHandler()
{
return new MockFaultContractExceptionHandler();
}
}
}
| 31.744186 | 122 | 0.72967 | [
"Apache-2.0"
] | Microsoft/exception-handling-application-block | source/Tests/WCF/Common/MockFaultContractExceptionHandler.cs | 1,367 | C# |
using Esprima.Ast;
using Jint.Native;
using Jint.Runtime.Environments;
using Jint.Runtime.References;
namespace Jint.Runtime.Interpreter.Expressions
{
/// <summary>
/// http://www.ecma-international.org/ecma-262/5.1/#sec-11.2.1
/// </summary>
internal sealed class JintMemberExpression : JintExpression
{
private JintExpression _objectExpression;
private JintIdentifierExpression _objectIdentifierExpression;
private JintThisExpression _objectThisExpression;
private JintExpression _propertyExpression;
private JsValue _determinedProperty;
public JintMemberExpression(Engine engine, MemberExpression expression) : base(engine, expression)
{
_initialized = false;
}
protected override void Initialize()
{
var expression = (MemberExpression) _expression;
_objectExpression = Build(_engine, expression.Object);
_objectIdentifierExpression = _objectExpression as JintIdentifierExpression;
_objectThisExpression = _objectExpression as JintThisExpression;
if (!expression.Computed)
{
_determinedProperty = ((Identifier) expression.Property).Name;
}
else if (expression.Property.Type == Nodes.Literal)
{
_determinedProperty = JintLiteralExpression.ConvertToJsValue((Literal) expression.Property);
}
if (_determinedProperty is null)
{
_propertyExpression = Build(_engine, expression.Property);
}
}
protected override object EvaluateInternal()
{
string baseReferenceName = null;
JsValue baseValue = null;
var isStrictModeCode = StrictModeScope.IsStrictModeCode;
if (_objectIdentifierExpression != null)
{
baseReferenceName = _objectIdentifierExpression._expressionName.Key.Name;
var strict = isStrictModeCode;
var env = _engine.ExecutionContext.LexicalEnvironment;
LexicalEnvironment.TryGetIdentifierEnvironmentWithBindingValue(
env,
_objectIdentifierExpression._expressionName,
strict,
out _,
out baseValue);
}
else if (_objectThisExpression != null)
{
baseValue = _objectThisExpression.GetValue();
}
if (baseValue is null)
{
// fast checks failed
var baseReference = _objectExpression.Evaluate();
if (baseReference is Reference reference)
{
baseReferenceName = reference.GetReferencedName().ToString();
baseValue = _engine.GetValue(reference, false);
_engine._referencePool.Return(reference);
}
else
{
baseValue = _engine.GetValue(baseReference, false);
}
}
var property = _determinedProperty ?? _propertyExpression.GetValue();
TypeConverter.CheckObjectCoercible(_engine, baseValue, (MemberExpression) _expression, baseReferenceName);
return _engine._referencePool.Rent(baseValue, TypeConverter.ToPropertyKey(property), isStrictModeCode);
}
}
} | 39.098901 | 119 | 0.586847 | [
"MIT"
] | Bargest/LogicExtensions | Jint/Runtime/Interpreter/Expressions/JintMemberExpression.cs | 3,558 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IDirectoryRoleMembersCollectionWithReferencesRequest.
/// </summary>
public partial interface IDirectoryRoleMembersCollectionWithReferencesRequest : IBaseRequest
{
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
System.Threading.Tasks.Task<IDirectoryRoleMembersCollectionWithReferencesPage> GetAsync();
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
System.Threading.Tasks.Task<IDirectoryRoleMembersCollectionWithReferencesPage> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IDirectoryRoleMembersCollectionWithReferencesRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IDirectoryRoleMembersCollectionWithReferencesRequest Select(string value);
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
IDirectoryRoleMembersCollectionWithReferencesRequest Top(int value);
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
IDirectoryRoleMembersCollectionWithReferencesRequest Filter(string value);
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
IDirectoryRoleMembersCollectionWithReferencesRequest Skip(int value);
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
IDirectoryRoleMembersCollectionWithReferencesRequest OrderBy(string value);
}
}
| 42.039474 | 153 | 0.617527 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/IDirectoryRoleMembersCollectionWithReferencesRequest.cs | 3,195 | C# |
namespace MyWalletz.DomainObjects
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("mw_Users")]
public class User
{
private ICollection<Category> categories;
private ICollection<Account> accounts;
private ICollection<Transaction> transactions;
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Email { get; set; }
public virtual ICollection<Category> Categories
{
get { return categories ?? (categories = new HashSet<Category>()); }
}
public virtual ICollection<Account> Accounts
{
get { return accounts ?? (accounts = new HashSet<Account>()); }
}
public virtual ICollection<Transaction> Transactions
{
get
{
return transactions ??
(transactions = new HashSet<Transaction>());
}
}
}
} | 28.578947 | 80 | 0.603131 | [
"MIT"
] | kazimanzurrashid/my-walletz-angular | source/MyWalletz/DomainObjects/User.cs | 1,088 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using SFA.DAS.LoginService.Application.Services;
using SFA.DAS.LoginService.Data;
using SFA.DAS.LoginService.Data.JsonObjects;
using Client = SFA.DAS.LoginService.Data.Entities.Client;
namespace SFA.DAS.LoginService.Application.UnitTests.Services.ClientServiceTests
{
[TestFixture]
public class GetClientByReturnUrl_called_for_valid_returnUrl
{
[Test]
public async Task Then_correct_Client_is_returned()
{
var dbContextOptions = new DbContextOptionsBuilder<LoginContext>()
.UseInMemoryDatabase(databaseName: "GetClientByReturnUrlHandler_tests")
.Options;
var loginContext = new LoginContext(dbContextOptions);
var clientId = Guid.NewGuid();
var identitySeverClientId = Guid.NewGuid();
var returnUrl = Convert.ToBase64String(identitySeverClientId.ToByteArray()); // a fake returnUrl which is actually an encrypted string containing the client id
loginContext.Clients.AddRange(new List<Client>
{
new Client(){Id = Guid.NewGuid(), IdentityServerClientId = Guid.NewGuid().ToString(), ServiceDetails = new ServiceDetails{ServiceName = "Service 1", SupportUrl = "https://support/Url/1"}},
new Client(){Id = clientId, IdentityServerClientId = identitySeverClientId.ToString(), ServiceDetails = new ServiceDetails{ServiceName = "Service 2", SupportUrl = "https://support/Url/2"}},
new Client(){Id = Guid.NewGuid(), IdentityServerClientId = Guid.NewGuid().ToString(), ServiceDetails = new ServiceDetails{ServiceName = "Service 3", SupportUrl = "https://support/Url/3"}},
});
await loginContext.SaveChangesAsync();
var interactionService = Substitute.For<IIdentityServerInteractionService>();
interactionService.GetAuthorizationContextAsync(Arg.Is(returnUrl)).Returns(new AuthorizationRequest()
{
ClientId = identitySeverClientId.ToString()
});
var clientService = new ClientService(interactionService, loginContext);
var clientResult = await clientService.GetByReturnUrl(returnUrl, CancellationToken.None);
clientResult.Id.Should().Be(clientId);
clientResult.ServiceDetails.ServiceName.Should().Be("Service 2");
clientResult.ServiceDetails.SupportUrl.Should().Be("https://support/Url/2");
}
}
} | 47.482759 | 205 | 0.698983 | [
"MIT"
] | SkillsFundingAgency/das-apprentice-login | src/SFA.DAS.LoginService.Application.UnitTests/Services/ClientServiceTests/GetClientByReturnUrl_called_for_valid_returnUrl.cs | 2,754 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
namespace StructLinq.Benchmark
{
[MemoryDiagnoser]
public class Distinct
{
private const int Count = 10_000;
private readonly int[] array;
public Distinct()
{
var tmp = Enumerable.Range(0, Count).ToArray();
var list = new List<int>(tmp);
list.AddRange(tmp);
array = list.ToArray();
}
[Benchmark(Baseline = true)]
public int Linq()
{
var sum = 0;
foreach (var i in array.Distinct())
{
sum += i;
}
return sum;
}
[Benchmark]
public int StructLinq()
{
var sum = 0;
foreach (var i in array.ToStructEnumerable().Distinct())
{
sum += i;
}
return sum;
}
[Benchmark]
public int StructLinqZeroAlloc()
{
var sum = 0;
var comparer = new StructEqualityComparer();
foreach (var i in array.ToStructEnumerable().Distinct(comparer, x=>x))
{
sum += i;
}
return sum;
}
[Benchmark]
public int StructLinqZeroAllocSum()
{
var comparer = new StructEqualityComparer();
return array.ToStructEnumerable()
.Distinct(comparer, x => x)
.Sum(x=>x);
}
public readonly struct StructEqualityComparer : IEqualityComparer<int>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(int x, int y) => x == y;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetHashCode(int value) => value.GetHashCode();
}
}
} | 25.947368 | 82 | 0.500507 | [
"MIT"
] | SpriteMaster-Ext/StructLinq | src/StructLinq.Benchmark/Distinct.cs | 1,974 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using AbpDemoOne.EntityFrameworkCore;
namespace AbpDemoOne.Migrations
{
[DbContext(typeof(AbpDemoOneDbContext))]
[Migration("20170424115119_Initial_Migrations")]
partial class Initial_Migrations
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration");
b.Property<DateTime>("ExecutionTime");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("MethodName")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<bool>("IsGranted");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.Property<int?>("UserId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<long?>("UserLinkId");
b.Property<string>("UserName");
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<byte>("Result");
b.Property<string>("TenancyName")
.HasMaxLength(64);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("UserNameOrEmailAddress")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long>("OrganizationUnitId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsAbandoned");
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime");
b.Property<DateTime>("NextTryTime");
b.Property<byte>("Priority");
b.Property<short>("TryCount");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("Value")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<string>("Icon")
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(10);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<string>("TenantIds")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasMaxLength(96);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<int>("State");
b.Property<int?>("TenantId");
b.Property<Guid>("TenantNotificationId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<long?>("ParentId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("AbpDemoOne.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDefault");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsStatic");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("AbpDemoOne.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("AuthenticationSource")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasMaxLength(328);
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsEmailConfirmed");
b.Property<bool>("IsLockoutEnabled");
b.Property<bool>("IsPhoneNumberConfirmed");
b.Property<bool>("IsTwoFactorEnabled");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<DateTime?>("LockoutEndDateUtc");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasMaxLength(328);
b.Property<string>("PhoneNumber");
b.Property<string>("SecurityStamp");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("AbpDemoOne.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConnectionString")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<int?>("EditionId");
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("TenantId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("AbpDemoOne.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("AbpDemoOne.Authorization.Roles.Role", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("AbpDemoOne.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("AbpDemoOne.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("AbpDemoOne.Authorization.Users.User", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("AbpDemoOne.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("AbpDemoOne.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("AbpDemoOne.MultiTenancy.Tenant", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("AbpDemoOne.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("AbpDemoOne.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("AbpDemoOne.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("AbpDemoOne.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 31.690563 | 117 | 0.439997 | [
"MIT"
] | YandongZhao/AbpDemoOne | aspnet-core/src/AbpDemoOne.EntityFrameworkCore/Migrations/20170424115119_Initial_Migrations.Designer.cs | 34,925 | C# |
using HugsLib;
using HugsLib.Settings;
using HugsLib.Utils;
using RimWorld;
using System;
using System.Collections.Generic;
using Verse;
namespace Typhon
{
public class Mod : ModBase
{
internal static SettingHandle<bool> mimicsDestroyCorpses;
public override void DefsLoaded()
{
CreateSettings();
CreateRecipes();
}
private void CreateSettings()
{
Retextures.CreateSettings(Settings);
mimicsDestroyCorpses = Settings.GetHandle<bool>(
"mimicsDestroyCorpses",
"Mimics Destroy Corpses",
"Mimics will destroy corpses rather than desiccate them. This causes phantoms to be more rare, as they require corpses to spawn.",
false);
}
private void CreateRecipes()
{
IngredientCount gold = new IngredientCount();
gold.SetBaseCount(5);
gold.filter.SetAllow(ThingDef.Named("Gold"), true);
IngredientCount componentSpacer = new IngredientCount();
componentSpacer.SetBaseCount(20);
componentSpacer.filter.SetAllow(ThingDef.Named("ComponentSpacer"), true);
IngredientCount typhonOrgan = new IngredientCount();
typhonOrgan.SetBaseCount(75);
typhonOrgan.filter.SetAllow(ThingDef.Named("TyphonOrgan"), true);
SoundDef soundWorking = SoundDef.Named("RecipeMachining");
ThingDef unfinishedThing = ThingDef.Named("UnfinishedComponent");
EffecterDef effecterDef = DefDatabase<EffecterDef>.GetNamed("Cook");
StatDef workSpeed = StatDef.Named("GeneralLaborSpeed");
SkillRequirement skillRequirement = new SkillRequirement();
skillRequirement.skill = DefDatabase<SkillDef>.GetNamed("Intellectual");
skillRequirement.minLevel = 15;
List<SkillRequirement> skills = new List<SkillRequirement>();
skills.Add(skillRequirement);
ThingDef fabricationBench = ThingDef.Named("FabricationBench");
foreach (ThingDef thingDef in DefDatabase<ThingDef>.AllDefs)
{
try
{
if (thingDef.thingCategories != null && thingDef.thingCategories.Contains(ThingCategoryDefOf.NeurotrainersPsycast))
{
CompProperties_Neurotrainer compDef = thingDef.CompDefFor<CompNeurotrainer>() as CompProperties_Neurotrainer;
if (compDef == null) continue;
RecipeDef recipeDef = new RecipeDef();
recipeDef.defName = "Typhon_Make_Psytrainer_" + compDef.ability.defName;
recipeDef.label = "make psytrainer (" + compDef.ability.label + ")";
recipeDef.ingredients.Add(gold);
recipeDef.ingredients.Add(componentSpacer);
recipeDef.ingredients.Add(typhonOrgan);
recipeDef.adjustedCount = 1;
recipeDef.workAmount = 2000;
recipeDef.soundWorking = soundWorking;
recipeDef.unfinishedThingDef = unfinishedThing;
recipeDef.effectWorking = effecterDef;
recipeDef.workSpeedStat = workSpeed;
recipeDef.description = "Make psytrainer from typhon organs, advanced components, and gold.";
recipeDef.skillRequirements = skills;
ThingDefCountClass product = new ThingDefCountClass();
product.count = 1;
product.thingDef = thingDef;
recipeDef.products.Add(product);
recipeDef.ResolveReferences();
InjectedDefHasher.GiveShortHashToDef(recipeDef, typeof(RecipeDef));
DefDatabase<RecipeDef>.Add(recipeDef);
fabricationBench.recipes.Add(recipeDef);
}
}
catch (Exception)
{
Logger.Message("Failed to create trainer for " + thingDef);
}
}
}
}
}
| 47.988764 | 146 | 0.576914 | [
"MIT"
] | Caaz/rimworld-typhon | Source/Mod.cs | 4,273 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the medialive-2017-10-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.MediaLive.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaLive.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for EmbeddedSourceSettings Object
/// </summary>
public class EmbeddedSourceSettingsUnmarshaller : IUnmarshaller<EmbeddedSourceSettings, XmlUnmarshallerContext>, IUnmarshaller<EmbeddedSourceSettings, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
EmbeddedSourceSettings IUnmarshaller<EmbeddedSourceSettings, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public EmbeddedSourceSettings Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
EmbeddedSourceSettings unmarshalledObject = new EmbeddedSourceSettings();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("convert608To708", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Convert608To708 = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("scte20Detection", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Scte20Detection = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("source608ChannelNumber", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.Source608ChannelNumber = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("source608TrackNumber", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.Source608TrackNumber = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static EmbeddedSourceSettingsUnmarshaller _instance = new EmbeddedSourceSettingsUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static EmbeddedSourceSettingsUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.318182 | 180 | 0.611151 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/EmbeddedSourceSettingsUnmarshaller.cs | 4,215 | C# |
using System.Text;
using System.Xml;
using NUnit.Framework;
using SkbKontur.Catalogue.XmlSerializer;
using SkbKontur.Catalogue.XmlSerializer.Writing;
using SkbKontur.Catalogue.XmlSerializer.Writing.ContentWriters;
namespace Catalogue.XmlSerializer.Tests.Writing
{
[TestFixture]
public class ContentWriterCollectionTest
{
[SetUp]
public void SetUp()
{
collection = new ContentWriterCollection(new XmlAttributeInterpreter());
}
[Test]
public void TestCacheNonSimpleTypes()
{
var writer = collection.Get(typeof(C1));
Assert.AreSame(writer, collection.Get(typeof(C1)));
}
[Test]
public void TestCacheSimpleTypes()
{
var writer = collection.Get(typeof(string));
//Assert.IsInstanceOfType(typeof (StringContentWriter), writer);
Assert.AreSame(writer, collection.Get(typeof(string)));
writer = collection.Get(typeof(int));
//Assert.IsInstanceOfType(typeof (ValueContentWriter), writer);
Assert.AreSame(writer, collection.Get(typeof(int)));
}
[Test]
public void TestClassWriter()
{
Check(new C1 {S = "zzz", Z = ""}, "<S>zzz</S><Z />");
}
[Test]
public void TestClassWriterHard()
{
Check(new Cyclic {S = new Cyclic(), I = new Inner {c = new Cyclic {Q = "q"}}},
"<Q /><S><Q /><S /><I /></S><I><c><Q>q</Q><S /><I /></c></I>");
}
[Test]
public void TestCustomContent()
{
Check(new CustomWrite("z"), "z");
}
[Test]
public void TestPrimitiveTypes()
{
Check(1, "1");
Check(22332L, "22332");
Check(22333u, "22333");
}
[Test]
public void TestString()
{
Check("zZz", "zZz");
}
[Test]
public void TestWithNullable()
{
Check(new WithNullable {Int = 37843}, "<Int>37843</Int>");
}
private void Check<T>(T value, string result)
{
var writer = collection.Get(typeof(T));
var builder = new StringBuilder();
using (
var xmlWriter =
new SimpleXmlWriter(XmlWriter.Create(builder,
new XmlWriterSettings
{
OmitXmlDeclaration = true,
ConformanceLevel = ConformanceLevel.Fragment
})))
writer.Write(value, xmlWriter);
Assert.AreEqual(result, builder.ToString());
}
private ContentWriterCollection collection;
private class C1
{
public string S { get; set; }
public string Z { get; set; }
}
private class Cyclic
{
public string Q { get; set; }
public Cyclic S { get; set; }
public Inner I { get; set; }
}
private class Inner
{
public Cyclic c { get; set; }
}
private class WithNullable
{
public int? Int { get; set; }
}
private class CustomWrite : ICustomWrite
{
public CustomWrite(string s)
{
this.s = s;
}
public void Write(IWriter writer)
{
writer.WriteValue(s);
}
private readonly string s;
}
}
} | 28.164179 | 109 | 0.473238 | [
"MIT"
] | skbkontur/Catalogue.XmlSerializer | Catalogue.XmlSerializer.Tests/Writing/ContentWriterCollectionTest.cs | 3,774 | 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Diagnostics.Tracing
{
[System.FlagsAttribute]
public enum EventActivityOptions
{
Detachable = 8,
Disable = 2,
None = 0,
Recursive = 4,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Method)]
public sealed partial class EventAttribute : System.Attribute
{
public EventAttribute(int eventId) { }
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } set { } }
public int EventId { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public string Message { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } set { } }
public byte Version { get { throw null; } set { } }
}
public enum EventChannel : byte
{
Admin = (byte)16,
Analytic = (byte)18,
Debug = (byte)19,
None = (byte)0,
Operational = (byte)17,
}
public enum EventCommand
{
Disable = -3,
Enable = -2,
SendManifest = -1,
Update = 0,
}
public partial class EventCommandEventArgs : System.EventArgs
{
internal EventCommandEventArgs() { }
public System.Collections.Generic.IDictionary<string, string> Arguments { get { throw null; } }
public System.Diagnostics.Tracing.EventCommand Command { get { throw null; } }
public bool DisableEvent(int eventId) { throw null; }
public bool EnableEvent(int eventId) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct, Inherited=false)]
public partial class EventDataAttribute : System.Attribute
{
public EventDataAttribute() { }
public string Name { get { throw null; } set { } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property)]
public partial class EventFieldAttribute : System.Attribute
{
public EventFieldAttribute() { }
public System.Diagnostics.Tracing.EventFieldFormat Format { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventFieldTags Tags { get { throw null; } set { } }
}
public enum EventFieldFormat
{
Boolean = 3,
Default = 0,
Hexadecimal = 4,
HResult = 15,
Json = 12,
String = 2,
Xml = 11,
}
[System.FlagsAttribute]
public enum EventFieldTags
{
None = 0,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property)]
public partial class EventIgnoreAttribute : System.Attribute
{
public EventIgnoreAttribute() { }
}
[System.FlagsAttribute]
public enum EventKeywords : long
{
All = (long)-1,
AuditFailure = (long)4503599627370496,
AuditSuccess = (long)9007199254740992,
CorrelationHint = (long)4503599627370496,
EventLogClassic = (long)36028797018963968,
MicrosoftTelemetry = (long)562949953421312,
None = (long)0,
Sqm = (long)2251799813685248,
WdiContext = (long)562949953421312,
WdiDiagnostic = (long)1125899906842624,
}
public enum EventLevel
{
Critical = 1,
Error = 2,
Informational = 4,
LogAlways = 0,
Verbose = 5,
Warning = 3,
}
public abstract partial class EventListener : System.IDisposable
{
protected EventListener() { }
public event System.EventHandler<System.Diagnostics.Tracing.EventSourceCreatedEventArgs> EventSourceCreated { add { } remove { } }
public event System.EventHandler<System.Diagnostics.Tracing.EventWrittenEventArgs> EventWritten { add { } remove { } }
public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { }
public virtual void Dispose() { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string> arguments) { }
protected static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { throw null; }
protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
protected internal virtual void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { }
}
[System.FlagsAttribute]
public enum EventManifestOptions
{
AllCultures = 2,
AllowEventSourceOverride = 8,
None = 0,
OnlyIfNeededForRegistration = 4,
Strict = 1,
}
public enum EventOpcode
{
DataCollectionStart = 3,
DataCollectionStop = 4,
Extension = 5,
Info = 0,
Receive = 240,
Reply = 6,
Resume = 7,
Send = 9,
Start = 1,
Stop = 2,
Suspend = 8,
}
public partial class EventSource : System.IDisposable
{
protected EventSource() { }
protected EventSource(bool throwOnEventWriteErrors) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings, params string[] traits) { }
public EventSource(string eventSourceName) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config, params string[] traits) { }
public System.Exception ConstructionException { get { throw null; } }
public static System.Guid CurrentThreadActivityId { get { throw null; } }
public System.Guid Guid { get { throw null; } }
public string Name { get { throw null; } }
public System.Diagnostics.Tracing.EventSourceSettings Settings { get { throw null; } }
public event System.EventHandler<System.Diagnostics.Tracing.EventCommandEventArgs> EventCommandExecuted { add { } remove { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~EventSource() { }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest) { throw null; }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest, System.Diagnostics.Tracing.EventManifestOptions flags) { throw null; }
public static System.Guid GetGuid(System.Type eventSourceType) { throw null; }
public static string GetName(System.Type eventSourceType) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource> GetSources() { throw null; }
public string GetTrait(string key) { throw null; }
public bool IsEnabled() { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords) { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords, System.Diagnostics.Tracing.EventChannel channel) { throw null; }
protected virtual void OnEventCommand(System.Diagnostics.Tracing.EventCommandEventArgs command) { }
public static void SendCommand(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventCommand command, System.Collections.Generic.IDictionary<string, string> commandArguments) { }
public static void SetCurrentThreadActivityId(System.Guid activityId) { }
public static void SetCurrentThreadActivityId(System.Guid activityId, out System.Guid oldActivityThatWillContinue) { throw null; }
public override string ToString() { throw null; }
public void Write(string eventName) { }
public void Write(string eventName, System.Diagnostics.Tracing.EventSourceOptions options) { }
protected void WriteEvent(int eventId) { }
protected void WriteEvent(int eventId, byte[] arg1) { }
protected void WriteEvent(int eventId, int arg1) { }
protected void WriteEvent(int eventId, int arg1, int arg2) { }
protected void WriteEvent(int eventId, int arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, int arg1, string arg2) { }
protected void WriteEvent(int eventId, long arg1) { }
protected void WriteEvent(int eventId, long arg1, byte[] arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2, long arg3) { }
protected void WriteEvent(int eventId, long arg1, string arg2) { }
protected void WriteEvent(int eventId, params object[] args) { }
protected void WriteEvent(int eventId, string arg1) { }
protected void WriteEvent(int eventId, string arg1, int arg2) { }
protected void WriteEvent(int eventId, string arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, string arg1, long arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2, string arg3) { }
[System.CLSCompliantAttribute(false)]
protected unsafe void WriteEventCore(int eventId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
protected void WriteEventWithRelatedActivityId(int eventId, System.Guid relatedActivityId, params object[] args) { }
[System.CLSCompliantAttribute(false)]
protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
public void Write<T>(string eventName, System.Diagnostics.Tracing.EventSourceOptions options, T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref System.Guid activityId, ref System.Guid relatedActivityId, ref T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref T data) { }
public void Write<T>(string eventName, T data) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
protected internal partial struct EventData
{
private int _dummyPrimitive;
public System.IntPtr DataPointer { get { throw null; } set { } }
public int Size { get { throw null; } set { } }
}
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class)]
public sealed partial class EventSourceAttribute : System.Attribute
{
public EventSourceAttribute() { }
public string Guid { get { throw null; } set { } }
public string LocalizationResources { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
}
public partial class EventSourceCreatedEventArgs : System.EventArgs
{
public EventSourceCreatedEventArgs() { }
public System.Diagnostics.Tracing.EventSource EventSource { get { throw null; } }
}
public partial class EventSourceException : System.Exception
{
public EventSourceException() { }
protected EventSourceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public EventSourceException(string message) { }
public EventSourceException(string message, System.Exception innerException) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct EventSourceOptions
{
private int _dummyPrimitive;
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum EventSourceSettings
{
Default = 0,
EtwManifestEventFormat = 4,
EtwSelfDescribingEventFormat = 8,
ThrowOnEventWriteErrors = 1,
}
[System.FlagsAttribute]
public enum EventTags
{
None = 0,
}
public enum EventTask
{
None = 0,
}
public partial class EventWrittenEventArgs : System.EventArgs
{
internal EventWrittenEventArgs() { }
public System.Guid ActivityId { get { throw null; } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } }
public int EventId { get { throw null; } }
public string EventName { get { throw null; } }
public System.Diagnostics.Tracing.EventSource EventSource { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } }
public string Message { get { throw null; } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } }
public long OSThreadId { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<object> Payload { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<string> PayloadNames { get { throw null; } }
public System.Guid RelatedActivityId { get { throw null; } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } }
public System.DateTime TimeStamp { get { throw null; } }
public byte Version { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Method)]
public sealed partial class NonEventAttribute : System.Attribute
{
public NonEventAttribute() { }
}
}
| 53.443686 | 257 | 0.680056 | [
"MIT"
] | AfsanehR-zz/corefx | src/System.Diagnostics.Tracing/ref/System.Diagnostics.Tracing.cs | 15,659 | C# |
using System;
#nullable enable
namespace SocialCareCaseViewerApi.V1.Domain
{
#nullable enable
public class LastUpdatedDomain
{
public string? Type { get; set; }
public DateTime? UpdatedAt { get; set; }
}
}
| 18.076923 | 48 | 0.67234 | [
"MIT"
] | JohnFarrellDev/social-care-case-viewer-api-fork | SocialCareCaseViewerApi/V1/Domain/LastUpdated.cs | 235 | C# |
/* Copyright (c) Citrix Systems, 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using XenAdmin.Alerts;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAPI;
namespace XenAdminTests.UnitTests.AlertTests
{
[TestFixture, Category(TestCategories.Unit)]
public class XenServerUpdateAlertTests
{
private Mock<IXenConnection> connA;
private Mock<IXenConnection> connB;
private Mock<Host> hostA;
private Mock<Host> hostB;
protected Cache cacheA;
protected Cache cacheB;
[Test]
public void TestAlertWithConnectionAndHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
alert.IncludeHosts(new List<Host>() { hostA.Object, hostB.Object });
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName, ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + BrandManager.CompanyNameShort + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithHostsAndNoConnection()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
alert.IncludeHosts(new List<Host> { hostA.Object, hostB.Object });
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + BrandManager.CompanyNameShort + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithConnectionAndNoHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = "ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + BrandManager.CompanyNameShort + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Never);
}
[Test]
public void TestAlertWithNoConnectionAndNoHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = string.Empty,
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + BrandManager.CompanyNameShort + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsTrue(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Never);
}
[Test]
public void TestAlertWithNullVersion()
{
Assert.Throws(typeof(NullReferenceException), () => new XenServerVersionAlert(null));
}
private void VerifyConnExpectations(Func<Times> times)
{
connA.Verify(n => n.Name, times());
connB.Verify(n => n.Name, times());
}
private void VerifyHostsExpectations(Func<Times> times)
{
hostA.Verify(n => n.Name(), times());
hostB.Verify(n => n.Name(), times());
}
[SetUp]
public void TestSetUp()
{
connA = new Mock<IXenConnection>(MockBehavior.Strict);
connA.Setup(n => n.Name).Returns("ConnAName");
cacheA = new Cache();
connA.Setup(x => x.Cache).Returns(cacheA);
connB = new Mock<IXenConnection>(MockBehavior.Strict);
connB.Setup(n => n.Name).Returns("ConnBName");
cacheB = new Cache();
connB.Setup(x => x.Cache).Returns(cacheB);
hostA = new Mock<Host>(MockBehavior.Strict);
hostA.Setup(n => n.Name()).Returns("HostAName");
hostA.Setup(n => n.Equals(It.IsAny<Host>())).Returns((Host o) => ReferenceEquals(o, hostA.Object));
hostB = new Mock<Host>(MockBehavior.Strict);
hostB.Setup(n => n.Name()).Returns("HostBName");
hostB.Setup(n => n.Equals(It.IsAny<Host>())).Returns((Host o) => ReferenceEquals(o, hostB.Object));
}
[TearDown]
public void TestTearDown()
{
cacheA = null;
cacheB = null;
connA = null;
connB = null;
hostA = null;
hostB = null;
}
}
} | 41.551724 | 232 | 0.583521 | [
"BSD-2-Clause"
] | CitrixChris/xenadmin | XenAdminTests/UnitTests/AlertTests/XenServerUpdateAlertTests.cs | 8,435 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Windows.Storage;
namespace BackgroundAudioShared
{
/// <summary>
/// Collection of string constants used in the entire solution. This file is shared for all projects
/// </summary>
public static class ApplicationSettingsHelper
{
/// <summary>
/// Function to read a setting value and clear it after reading it
/// </summary>
public static object ReadResetSettingsValue(string key)
{
Debug.WriteLine(key);
if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
{
Debug.WriteLine("null returned");
return null;
}
else
{
var value = ApplicationData.Current.LocalSettings.Values[key];
ApplicationData.Current.LocalSettings.Values.Remove(key);
Debug.WriteLine("value found " + value.ToString());
return value;
}
}
/// <summary>
/// Save a key value pair in settings. Create if it doesn't exist
/// </summary>
public static void SaveSettingsValue(string key, object value)
{
Debug.WriteLine(key + ":" + (value == null ? "null" : value.ToString()));
if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
{
ApplicationData.Current.LocalSettings.Values.Add(key, value);
}
else
{
ApplicationData.Current.LocalSettings.Values[key] = value;
}
}
}
}
| 33.907692 | 105 | 0.548548 | [
"MIT"
] | 035/Windows-universal-samples | backgroundaudio/cs/backgroundaudioshared/applicationsettingshelper.cs | 2,142 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.42000
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace AdventureWorks.Properties {
using System;
/// <summary>
/// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。
/// </summary>
// このクラスは StronglyTypedResourceBuilder クラスが ResGen
// または Visual Studio のようなツールを使用して自動生成されました。
// メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に
// ResGen を実行し直すか、または VS プロジェクトをビルドし直します。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.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>
/// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。
/// </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("AdventureWorks.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 厳密に型指定されたこのリソース クラスを使用して、すべての検索リソースに対し、
/// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// [{"SalesOrderID":43659,"RevisionNumber":8,"OrderDate":"2011-05-31T00:00:00","DueDate":"2011-06-12T00:00:00","ShipDate":"2011-06-07T00:00:00","Status":5,"OnlineOrderFlag":false,"SalesOrderNumber":"SO43659","PurchaseOrderNumber":"PO522145787","AccountNumber":"10-4020-000676","CustomerID":29825,"SalesPersonID":279,"TerritoryID":5,"BillToAddressID":985,"ShipToAddressID":985,"ShipMethodID":5,"CreditCardID":16281,"CreditCardApprovalCode":"105041Vi84182","CurrencyRateID":null,"SubTotal":20565.6206,"TaxAmt":1971.51 [残りの文字列は切り詰められました]"; に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string SalesOrderHeaderDetail_100 {
get {
return ResourceManager.GetString("SalesOrderHeaderDetail_100", resourceCulture);
}
}
/// <summary>
/// [{"SalesOrderID":43659,"RevisionNumber":8,"OrderDate":"2011-05-31T00:00:00","DueDate":"2011-06-12T00:00:00","ShipDate":"2011-06-07T00:00:00","Status":5,"OnlineOrderFlag":false,"SalesOrderNumber":"SO43659","PurchaseOrderNumber":"PO522145787","AccountNumber":"10-4020-000676","CustomerID":29825,"SalesPersonID":279,"TerritoryID":5,"BillToAddressID":985,"ShipToAddressID":985,"ShipMethodID":5,"CreditCardID":16281,"CreditCardApprovalCode":"105041Vi84182","CurrencyRateID":null,"SubTotal":20565.6206,"TaxAmt":1971.51 [残りの文字列は切り詰められました]"; に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string SalesOrderHeaderDetail_1000 {
get {
return ResourceManager.GetString("SalesOrderHeaderDetail_1000", resourceCulture);
}
}
/// <summary>
/// [{"SalesOrderID":43659,"RevisionNumber":8,"OrderDate":"2011-05-31T00:00:00","DueDate":"2011-06-12T00:00:00","ShipDate":"2011-06-07T00:00:00","Status":5,"OnlineOrderFlag":false,"SalesOrderNumber":"SO43659","PurchaseOrderNumber":"PO522145787","AccountNumber":"10-4020-000676","CustomerID":29825,"SalesPersonID":279,"TerritoryID":5,"BillToAddressID":985,"ShipToAddressID":985,"ShipMethodID":5,"CreditCardID":16281,"CreditCardApprovalCode":"105041Vi84182","CurrencyRateID":null,"SubTotal":20565.6206,"TaxAmt":1971.51 [残りの文字列は切り詰められました]"; に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string SalesOrderHeaderDetail_10000 {
get {
return ResourceManager.GetString("SalesOrderHeaderDetail_10000", resourceCulture);
}
}
/// <summary>
/// [{"SalesOrderID":43659,"RevisionNumber":8,"OrderDate":"2011-05-31T00:00:00","DueDate":"2011-06-12T00:00:00","ShipDate":"2011-06-07T00:00:00","Status":5,"OnlineOrderFlag":false,"SalesOrderNumber":"SO43659","PurchaseOrderNumber":"PO522145787","AccountNumber":"10-4020-000676","CustomerID":29825,"SalesPersonID":279,"TerritoryID":5,"BillToAddressID":985,"ShipToAddressID":985,"ShipMethodID":5,"CreditCardID":16281,"CreditCardApprovalCode":"105041Vi84182","CurrencyRateID":null,"SubTotal":20565.6206,"TaxAmt":1971.51 [残りの文字列は切り詰められました]"; に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string SalesOrderHeaderDetail_500 {
get {
return ResourceManager.GetString("SalesOrderHeaderDetail_500", resourceCulture);
}
}
/// <summary>
/// [{"SalesOrderID":43659,"RevisionNumber":8,"OrderDate":"2011-05-31T00:00:00","DueDate":"2011-06-12T00:00:00","ShipDate":"2011-06-07T00:00:00","Status":5,"OnlineOrderFlag":false,"SalesOrderNumber":"SO43659","PurchaseOrderNumber":"PO522145787","AccountNumber":"10-4020-000676","CustomerID":29825,"SalesPersonID":279,"TerritoryID":5,"BillToAddressID":985,"ShipToAddressID":985,"ShipMethodID":5,"CreditCardID":16281,"CreditCardApprovalCode":"105041Vi84182","CurrencyRateID":null,"SubTotal":20565.6206,"TaxAmt":1971.51 [残りの文字列は切り詰められました]"; に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string SalesOrderHeaderDetail_5000 {
get {
return ResourceManager.GetString("SalesOrderHeaderDetail_5000", resourceCulture);
}
}
/// <summary>
/// [{"SalesOrderID":43659,"RevisionNumber":8,"OrderDate":"2011-05-31T00:00:00","DueDate":"2011-06-12T00:00:00","ShipDate":"2011-06-07T00:00:00","Status":5,"OnlineOrderFlag":false,"SalesOrderNumber":"SO43659","PurchaseOrderNumber":"PO522145787","AccountNumber":"10-4020-000676","CustomerID":29825,"SalesPersonID":279,"TerritoryID":5,"BillToAddressID":985,"ShipToAddressID":985,"ShipMethodID":5,"CreditCardID":16281,"CreditCardApprovalCode":"105041Vi84182","CurrencyRateID":null,"SubTotal":20565.6206,"TaxAmt":1971.51 [残りの文字列は切り詰められました]"; に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string SalesOrderHeaderDetail_50000 {
get {
return ResourceManager.GetString("SalesOrderHeaderDetail_50000", resourceCulture);
}
}
}
}
| 78.745763 | 859 | 0.689303 | [
"MIT"
] | nuitsjp/WCF-vs-Web-API-Battle | AdventureWorks/AdventureWorks/Properties/Resources.Designer.cs | 10,440 | C# |
using System;
namespace Bond
{
internal class Argument
{
internal static void IsNotNull<T>(T argument, string argumentName) where T : class
{
if (argument == null)
{
throw new ArgumentNullException(argumentName);
}
}
}
}
| 19.4375 | 90 | 0.533762 | [
"MIT"
] | osjoberg/Bond | Bond/Argument.cs | 313 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebApplication.Models.Options;
using WebApplication.Services;
using System.Security.Claims;
namespace WebApplication.Tests
{
[TestClass]
public class SecurityAccessProviderTests
{
private const string Reader = "Reader";
private const string ReaderGroupID = "ReaderSecurityId";
[TestMethod]
public void LoadingSettingsIncludesGlobalListsAndRoles()
{
var configBuilder = new ConfigurationBuilder();
configBuilder.AddJsonFile("appSettings.json");
var config = configBuilder.Build();
var optionsModel = ConfigurationBinder.Get<SecurityModelOptions>(config.GetSection("SecurityModelOptions"));
var options = Options.Create(optionsModel);
options.Should().NotBeNull();
options.Value.GlobalAllowActions.Count.Should().BeGreaterThan(0);
options.Value.GlobalDenyActions.Count.Should().BeGreaterThan(0);
options.Value.SecurityRoles.Count.Should().BeGreaterThan(0);
options.Value.SecurityRoles[Reader].AllowActions.Count.Should().BeGreaterThan(0);
}
}
}
| 37.941176 | 120 | 0.709302 | [
"MIT"
] | G-arj/azure-data-services-go-fast-codebase | solution/WebApplication/WebApplication.Tests/SecurityAccessProviderTests.cs | 1,290 | 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 Restless.Tools.Utility.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", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
/// <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("Restless.Tools.Utility.Resources.Strings", typeof(Strings).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 The object ({0}) is not allowed to be null..
/// </summary>
internal static string ArgumentNullValidateNull {
get {
return ResourceManager.GetString("ArgumentNullValidateNull", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The string ({0}) is not allowed to be null or empty..
/// </summary>
internal static string ArgumentNullValidateNullOrEmpty {
get {
return ResourceManager.GetString("ArgumentNullValidateNullOrEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value for {0} is out of range. Must be between {1} - {2}.
/// </summary>
internal static string ArgumentOutOfRangeValidateInteger {
get {
return ResourceManager.GetString("ArgumentOutOfRangeValidateInteger", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The array {0} must have a minimum length of {1}.
/// </summary>
internal static string ArgumentValidateArray {
get {
return ResourceManager.GetString("ArgumentValidateArray", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to open the specified file. Please make sure the path and file name is correct..
/// </summary>
internal static string InvalidOperationCannotOpenFile {
get {
return ResourceManager.GetString("InvalidOperationCannotOpenFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The row does not belong to the {0} table.
/// </summary>
internal static string InvalidOperationDataRowMustBeTable {
get {
return ResourceManager.GetString("InvalidOperationDataRowMustBeTable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No search scope has been specified..
/// </summary>
internal static string InvalidOperationNoSearchScopeSpecified {
get {
return ResourceManager.GetString("InvalidOperationNoSearchScopeSpecified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unhandled Exception.
/// </summary>
internal static string UnhandledExceptionCaption {
get {
return ResourceManager.GetString("UnhandledExceptionCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unknown error occured in the current domain.
/// </summary>
internal static string UnhandledExceptionCurrentDomain {
get {
return ResourceManager.GetString("UnhandledExceptionCurrentDomain", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The application will now attempt to shutdown gracefully..
/// </summary>
internal static string UnhandledExceptionMessageFooter {
get {
return ResourceManager.GetString("UnhandledExceptionMessageFooter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unhandled exception occurred..
/// </summary>
internal static string UnhandledExceptionMessageHeader {
get {
return ResourceManager.GetString("UnhandledExceptionMessageHeader", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (unspecified).
/// </summary>
internal static string UnspecifiedName {
get {
return ResourceManager.GetString("UnspecifiedName", resourceCulture);
}
}
}
}
| 41.203488 | 183 | 0.590518 | [
"MIT"
] | victor-david/restless-tools | src/Restless.Tools.Utility/Resources/Strings.Designer.cs | 7,089 | C# |
// <auto-generated>
// Auto-generated by StoneAPI, do not modify.
// </auto-generated>
namespace Dropbox.Api.Files
{
using sys = System;
using col = System.Collections.Generic;
using re = System.Text.RegularExpressions;
using enc = Dropbox.Api.Stone;
/// <summary>
/// <para>Sharing info for a file which is contained by a shared folder.</para>
/// </summary>
/// <seealso cref="Global::Dropbox.Api.Files.SharingInfo" />
public class FileSharingInfo : SharingInfo
{
#pragma warning disable 108
/// <summary>
/// <para>The encoder instance.</para>
/// </summary>
internal static enc.StructEncoder<FileSharingInfo> Encoder = new FileSharingInfoEncoder();
/// <summary>
/// <para>The decoder instance.</para>
/// </summary>
internal static enc.StructDecoder<FileSharingInfo> Decoder = new FileSharingInfoDecoder();
/// <summary>
/// <para>Initializes a new instance of the <see cref="FileSharingInfo" />
/// class.</para>
/// </summary>
/// <param name="readOnly">True if the file or folder is inside a read-only shared
/// folder.</param>
/// <param name="parentSharedFolderId">ID of shared folder that holds this
/// file.</param>
/// <param name="modifiedBy">The last user who modified the file. This field will be
/// null if the user's account has been deleted.</param>
public FileSharingInfo(bool readOnly,
string parentSharedFolderId,
string modifiedBy = null)
: base(readOnly)
{
if (parentSharedFolderId == null)
{
throw new sys.ArgumentNullException("parentSharedFolderId");
}
if (!re.Regex.IsMatch(parentSharedFolderId, @"\A(?:[-_0-9a-zA-Z:]+)\z"))
{
throw new sys.ArgumentOutOfRangeException("parentSharedFolderId", @"Value should match pattern '\A(?:[-_0-9a-zA-Z:]+)\z'");
}
if (modifiedBy != null)
{
if (modifiedBy.Length < 40)
{
throw new sys.ArgumentOutOfRangeException("modifiedBy", "Length should be at least 40");
}
if (modifiedBy.Length > 40)
{
throw new sys.ArgumentOutOfRangeException("modifiedBy", "Length should be at most 40");
}
}
this.ParentSharedFolderId = parentSharedFolderId;
this.ModifiedBy = modifiedBy;
}
/// <summary>
/// <para>Initializes a new instance of the <see cref="FileSharingInfo" />
/// class.</para>
/// </summary>
/// <remarks>This is to construct an instance of the object when
/// deserializing.</remarks>
[sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)]
public FileSharingInfo()
{
}
/// <summary>
/// <para>ID of shared folder that holds this file.</para>
/// </summary>
public string ParentSharedFolderId { get; protected set; }
/// <summary>
/// <para>The last user who modified the file. This field will be null if the user's
/// account has been deleted.</para>
/// </summary>
public string ModifiedBy { get; protected set; }
#region Encoder class
/// <summary>
/// <para>Encoder for <see cref="FileSharingInfo" />.</para>
/// </summary>
private class FileSharingInfoEncoder : enc.StructEncoder<FileSharingInfo>
{
/// <summary>
/// <para>Encode fields of given value.</para>
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public override void EncodeFields(FileSharingInfo value, enc.IJsonWriter writer)
{
WriteProperty("read_only", value.ReadOnly, writer, enc.BooleanEncoder.Instance);
WriteProperty("parent_shared_folder_id", value.ParentSharedFolderId, writer, enc.StringEncoder.Instance);
if (value.ModifiedBy != null)
{
WriteProperty("modified_by", value.ModifiedBy, writer, enc.StringEncoder.Instance);
}
}
}
#endregion
#region Decoder class
/// <summary>
/// <para>Decoder for <see cref="FileSharingInfo" />.</para>
/// </summary>
private class FileSharingInfoDecoder : enc.StructDecoder<FileSharingInfo>
{
/// <summary>
/// <para>Create a new instance of type <see cref="FileSharingInfo" />.</para>
/// </summary>
/// <returns>The struct instance.</returns>
protected override FileSharingInfo Create()
{
return new FileSharingInfo();
}
/// <summary>
/// <para>Set given field.</para>
/// </summary>
/// <param name="value">The field value.</param>
/// <param name="fieldName">The field name.</param>
/// <param name="reader">The json reader.</param>
protected override void SetField(FileSharingInfo value, string fieldName, enc.IJsonReader reader)
{
switch (fieldName)
{
case "read_only":
value.ReadOnly = enc.BooleanDecoder.Instance.Decode(reader);
break;
case "parent_shared_folder_id":
value.ParentSharedFolderId = enc.StringDecoder.Instance.Decode(reader);
break;
case "modified_by":
value.ModifiedBy = enc.StringDecoder.Instance.Decode(reader);
break;
default:
reader.Skip();
break;
}
}
}
#endregion
}
}
| 37.658537 | 139 | 0.538536 | [
"MIT"
] | AlirezaMaddah/dropbox-sdk-dotnet | dropbox-sdk-dotnet/Dropbox.Api/Generated/Files/FileSharingInfo.cs | 6,176 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace FileAndDirectoryBrowserWebApi.Exceptions.HttpExceptions
{
[Serializable]
public class NotFoundException : HttpExceptionBase
{
public override HttpStatusCode StatusCode => HttpStatusCode.NotFound;
public NotFoundException(string message)
: base(message)
{
}
protected NotFoundException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 24.038462 | 85 | 0.6976 | [
"MIT"
] | ProgrammerAl/Challenges | FileAndDirectoryBrowserWebApp/FileAndDirectoryBrowserWebApi/FileAndDirectoryBrowserWebApi/Exceptions/HttpExceptions/NotFoundException.cs | 627 | C# |
using System;
using System.Runtime.InteropServices;
using Stepon.FaceRecognizationCore.Common;
namespace Stepon.FaceRecognizationCore.Tracking.Wrapper
{
internal class TrackingWrapper
{
private const string DllPosition = "libs/libarcsoft_fsdk_face_tracking.so";
[DllImport(DllPosition, EntryPoint = "AFT_FSDK_InitialFaceEngine",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int AFT_FSDK_InitialFaceEngine(string appId, string sdkKey, byte[] buffer, int bufferSize,
out IntPtr engine, int orientPriority, int scale, int faceNumber);
[DllImport(DllPosition, EntryPoint = "AFT_FSDK_FaceFeatureDetect",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int AFT_FSDK_FaceFeatureDetect(IntPtr engine, ref ImageData pImgData,
out IntPtr pFaceRes);
[DllImport(DllPosition, EntryPoint = "AFT_FSDK_UninitialFaceEngine",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int AFT_FSDK_UninitialFaceEngine(IntPtr engine);
[DllImport(DllPosition, EntryPoint = "AFT_FSDK_GetVersion", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi)]
public static extern IntPtr AFT_FSDK_GetVersion(IntPtr engine);
}
#region Tracking data structure
[StructLayout(LayoutKind.Sequential)]
internal struct AFT_FSDK_FACERES
{
[MarshalAs(UnmanagedType.I4)] public int nFace;
[MarshalAs(UnmanagedType.I4)] public int lfaceOrient;
public IntPtr rcFace;
}
#endregion
} | 41.195122 | 119 | 0.727057 | [
"Apache-2.0"
] | JTOne123/FaceRecognization | Stepon.FaceRecognizationCore/Stepon.FaceRecognizationCore/Tracking/Wrapper/TrackingWrapper.cs | 1,691 | C# |
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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;
namespace Osc
{
/// <summary>
/// A bucket for an <see cref="IpRangeAggregation"/>
/// </summary>
public class IpRangeBucket : BucketBase
{
public IpRangeBucket(IReadOnlyDictionary<string, IAggregate> dict) : base(dict) { }
/// <summary>
/// The count of documents in the bucket
/// </summary>
public long DocCount { get; set; }
/// <summary>
/// The IP address from
/// </summary>
public string From { get; set; }
/// <summary>
/// The key for the bucket
/// </summary>
public string Key { get; set; }
/// <summary>
/// The IP address to
/// </summary>
public string To { get; set; }
}
}
| 29.016667 | 85 | 0.709362 | [
"Apache-2.0"
] | Bit-Quill/opensearch-net | src/Osc/Aggregations/Bucket/IpRange/IpRangeBucket.cs | 1,741 | C# |
#if DEBUG
using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Composition
{
internal sealed class ConcurrentSingletonBag
{
private readonly ConcurrentDictionary<Key, Lazy<object>?> content = new();
public T Get<T>(Func<T> factory, [CallerMemberName] string id = "") where T : notnull
{
var key = new Key(id, typeof(T));
if (content.TryGetValue(key, out var lazy) && lazy != null)
{
var singleton = Unwrap(key, lazy);
return (T)singleton;
}
var newLazy = new Lazy<object>(() => factory());
content[key] = newLazy;
var newSingleton = Unwrap(key, newLazy);
return (T)newSingleton;
}
public async Task<T> GetAsync<T>(Func<Task<T>> factory, [CallerMemberName] string id = "") where T : notnull
{
var key = new Key(id, typeof(T));
if (content.TryGetValue(key, out var lazy) && lazy != null)
{
return await WaitAsync<T>(key, lazy).ConfigureAwait(false);
}
var newLazy = new Lazy<object>(factory);
var storedLazy = content.AddOrUpdate(
key,
newLazy,
(_, existingValue) => existingValue ?? newLazy
);
return await WaitAsync<T>(key, storedLazy).ConfigureAwait(false);
}
private object Unwrap(Key key, Lazy<object> lazy)
{
try
{
return lazy.Value;
}
catch
{
content.TryUpdate(key, null, lazy);
throw;
}
}
private async Task<T> WaitAsync<T>(Key key, Lazy<object> lazy)
{
var task = (Task<T>)Unwrap(key, lazy);
try
{
return await task.ConfigureAwait(false);
}
catch
{
content.TryUpdate(key, null, lazy);
throw;
}
}
}
}
#endif | 29.733333 | 117 | 0.483408 | [
"MIT"
] | pepelev/Composition | src/Composition/ConcurrentSingletonBag.cs | 2,232 | C# |
namespace Merchello.Web.Validation.Tasks
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Merchello.Core;
using Merchello.Core.Models;
using Merchello.Web.Models.ContentEditing;
using Merchello.Web.Workflow.CustomerItemCache;
using Umbraco.Core;
using Umbraco.Core.Logging;
/// <summary>
/// Validates that product pricing in Merchello has not been changed.
/// </summary>
/// <remarks>
/// Note: for multi-currency sites, you should place the extended data key (merchLineItemAllowsValidation = false)
/// into the line item extended data so that this task
/// does not reset the price to that set in the back office
/// </remarks>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
internal class ValidateProductPriceTask : CustomerItemCacheValidatationTaskBase<ValidationResult<CustomerItemCacheBase>>
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidateProductPriceTask"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The merchello context.
/// </param>
/// <param name="enableDataModifiers">
/// The enable data modifiers.
/// </param>
public ValidateProductPriceTask(IMerchelloContext merchelloContext, bool enableDataModifiers)
: base(merchelloContext, enableDataModifiers)
{
}
/// <summary>
/// Performs the task of validating the pricing information.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The <see cref="Attempt"/>.
/// </returns>
public override Attempt<ValidationResult<CustomerItemCacheBase>> PerformTask(ValidationResult<CustomerItemCacheBase> value)
{
var visitor = new ProductPricingValidationVisitor(Merchello);
value.Validated.Accept(visitor);
if (visitor.InvalidPrices.Any())
{
foreach (var result in visitor.InvalidPrices.ToArray())
{
var lineItem = result.Key;
var quantity = lineItem.Quantity;
var name = lineItem.Name;
var removedEd = lineItem.ExtendedData.AsEnumerable();
value.Validated.RemoveItem(lineItem.Sku);
var extendedData = new ExtendedDataCollection();
ProductVariantDisplay variant;
if (result.Value is ProductDisplay)
{
var product = result.Value as ProductDisplay;
variant = product.AsMasterVariantDisplay();
}
else
{
variant = result.Value as ProductVariantDisplay;
}
if (variant == null)
{
var nullReference = new NullReferenceException("ProductVariantDisplay cannot be null");
LogHelper.Error<ValidateProductPriceTask>("Exception occurred when attempting to adjust pricing information", nullReference);
throw nullReference;
}
extendedData.AddProductVariantValues(variant);
extendedData.MergeDataModifierLogs(variant);
extendedData.MergeDataModifierLogs(variant);
// preserve any custom extended data values
foreach (var val in removedEd.Where(val => !extendedData.ContainsKey(val.Key)))
{
extendedData.SetValue(val.Key, val.Value);
}
var price = variant.OnSale ? extendedData.GetSalePriceValue() : extendedData.GetPriceValue();
var keys = lineItem.ExtendedData.Keys.Where(x => extendedData.Keys.Any(y => y != x));
foreach (var k in keys)
{
extendedData.SetValue(k, lineItem.ExtendedData.GetValue(k));
}
value.Validated.AddItem(string.IsNullOrEmpty(name) ? variant.Name : name, variant.Sku, quantity, price, extendedData);
value.Messages.Add("Price updated for " + variant.Sku + " to " + price);
}
value.Validated.Save();
}
return Attempt<ValidationResult<CustomerItemCacheBase>>.Succeed(value);
}
}
} | 42.669643 | 165 | 0.564344 | [
"MIT"
] | HiteshMah-Jan/Merchello | src/Merchello.Web/Validation/Tasks/ValidateProductPriceTask.cs | 4,781 | 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("05ParseTags")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05ParseTags")]
[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("1df31188-e61c-4d8d-81e8-5b274de17cc8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.702703 | 84 | 0.744803 | [
"MIT"
] | TsvetanMilanov/TelerikAcademyHW | 02.CSharpPartTwo/06_StringsAndTextProcessing/StringsAndTextProcessing/05ParseTags/Properties/AssemblyInfo.cs | 1,398 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace TicketerApi.Migrations
{
public partial class InitialMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}
| 34.5 | 91 | 0.519022 | [
"MIT"
] | hamyul/Ticketer | TicketerApi/Migrations/20220307052054_InitialMigration.cs | 1,106 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using NuGet.Shared;
namespace NuGet.Frameworks
{
#if NUGET_FRAMEWORKS_INTERNAL
internal
#else
public
#endif
class FrameworkRangeComparer : IEqualityComparer<FrameworkRange>
{
public FrameworkRangeComparer()
{
}
public bool Equals(FrameworkRange x, FrameworkRange y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (ReferenceEquals(x, null)
|| ReferenceEquals(y, null))
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(x.FrameworkIdentifier, y.FrameworkIdentifier) &&
NuGetFramework.Comparer.Equals(x.Min, y.Min) && NuGetFramework.Comparer.Equals(x.Max, y.Max)
&& x.IncludeMin == y.IncludeMin && x.IncludeMax == y.IncludeMax;
}
public int GetHashCode(FrameworkRange obj)
{
if (ReferenceEquals(obj, null))
{
return 0;
}
var combiner = new HashCodeCombiner();
combiner.AddStringIgnoreCase(obj.FrameworkIdentifier);
combiner.AddObject(obj.Min);
combiner.AddObject(obj.Max);
combiner.AddObject(obj.IncludeMin);
combiner.AddObject(obj.IncludeMax);
return combiner.CombinedHash;
}
}
}
| 27.87931 | 111 | 0.587508 | [
"Apache-2.0"
] | 0xced/NuGet.Client | src/NuGet.Core/NuGet.Frameworks/comparers/FrameworkRangeComparer.cs | 1,617 | C# |
using System.Resources;
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("Geofence.Plugin.Abstractions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Geofence.Plugin.Abstractions")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")]
| 35.83871 | 84 | 0.747975 | [
"MIT"
] | JTOne123/xamarin-plugins | Geofence/Geofence/Geofence.Plugin.Abstractions/Properties/AssemblyInfo.cs | 1,114 | C# |
namespace System
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate,
Inherited = false)]
public sealed class ObsoleteAttribute : Attribute
{
public ObsoleteAttribute()
{
Message = null;
IsError = false;
}
public ObsoleteAttribute(string? message)
{
Message = message;
IsError = false;
}
public ObsoleteAttribute(string? message, bool error)
{
Message = message;
IsError = error;
}
public string? Message { get; }
public bool IsError { get; }
public string? DiagnosticId { get; set; }
public string? UrlFormat { get; set; }
}
} | 28.588235 | 198 | 0.608025 | [
"MIT"
] | nifanfa/BootTo.NET | Corlib/System/ObsoleteAttribute.cs | 972 | C# |
using System;
namespace FindTheDuplicateNumber
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine(2 == new Solution().FindDuplicate(new[] {1, 3, 4, 2, 2}));
Console.WriteLine(3 == new Solution().FindDuplicate(new[] {3, 1, 3, 4, 2}));
}
}
}
public class Solution
{
public int FindDuplicate(int[] nums)
{
var tortoise = nums[0];
var hare = nums[0];
do
{
tortoise = nums[tortoise];
hare = nums[nums[hare]];
} while (tortoise != hare);
var ptr1 = nums[0];
var ptr2 = tortoise;
while (ptr1 != ptr2)
{
ptr1 = nums[ptr1];
ptr2 = nums[ptr2];
}
return ptr1;
}
} | 21.74359 | 89 | 0.465802 | [
"MIT"
] | thenitro/leet-code-problems | FindTheDuplicateNumber/FindTheDuplicateNumber/Program.cs | 850 | C# |
using System.Reflection;
using SquawkBus.Distributor.Plugins;
namespace SquawkBus.Distributor.Configuration
{
public class PluginConfig
{
public string? AssemblyPath { get; set; }
public string? AssemblyName { get; set; }
public string? TypeName { get; set; }
public string[]? Args { get; set; }
public override string ToString() => $"{nameof(AssemblyPath)}=\"{AssemblyPath}\",{nameof(AssemblyName)}=\"{AssemblyName}\",{nameof(TypeName)}=\"{TypeName}\",{nameof(Args)}={string.Join(",", Args ?? new string[0])}";
public T? Construct<T>() where T : class
{
var type = LoadType();
if (type == null)
throw new ApplicationException("Failed to get type");
return (T?)Activator.CreateInstance(type, new[] { Args });
}
private Type? LoadType()
{
if (TypeName == null)
throw new ArgumentNullException(nameof(TypeName), "The type name must be specified");
if (AssemblyName == null)
throw new ArgumentNullException(nameof(TypeName), "The assembly name must be specified");
if (string.IsNullOrWhiteSpace(AssemblyPath))
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var assembly = assemblies.First(x => x.GetName().Name == AssemblyName);
var type = assembly.GetType(TypeName);
return type;
}
else
{
var loadContext = new PluginLoadContext(AssemblyPath);
var assembly = loadContext.LoadFromAssemblyName(new AssemblyName(AssemblyName));
var type = assembly.GetType(TypeName);
return type;
}
}
}
} | 38.489362 | 223 | 0.572692 | [
"Apache-2.0"
] | SquawkBus/SquawkBus | src/SquawkBus.Distributor/Configuration/PluginConfig.cs | 1,809 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
using UnityEngine.Windows.WebCam;
using Debug = UnityEngine.Debug;
public class CaptureManager : MonoBehaviour, IMixedRealityGestureHandler
{
[SerializeField] private MixedRealityInputAction validateAction;
[SerializeField] private MixedRealityInputAction cancelAction;
private bool activeWithoutBackground;
private bool activeWithBackground;
private GameObject withoutBackgroundIcon;
private GameObject withBackgroundIcon;
private Camera camera;
private PhotoCapture photoCaptureObject;
[SerializeField] private GameObject infoTooltip;
[SerializeField] private PaintActionsManager actionsManager;
// Start is called before the first frame update
void Start()
{
camera = Camera.main;
activeWithoutBackground = false;
activeWithBackground = false;
withoutBackgroundIcon = GameObject.Find("CaptureWithoutBackground").transform.Find("BackPlate").gameObject;
withBackgroundIcon = GameObject.Find("CaptureWithBackground").transform.Find("BackPlate").gameObject;
infoTooltip.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
public void ToggleCaptureWithBackground()
{
if (activeWithBackground)
{
DeactivateCaptureWithBackground();
}
else
{
if (activeWithoutBackground)
{
DeactivateCaptureWithoutBackground();
}
ActivateCaptureWithBackground();
}
}
private void ActivateCaptureWithBackground()
{
CoreServices.InputSystem.RegisterHandler<IMixedRealityGestureHandler>(this);
ToggleIcon(withBackgroundIcon, true);
activeWithBackground = true;
infoTooltip.SetActive(true);
actionsManager.ToggleManipulators(false);
}
public void DeactivateCaptureWithBackground()
{
CoreServices.InputSystem.UnregisterHandler<IMixedRealityGestureHandler>(this);
ToggleIcon(withBackgroundIcon, false);
activeWithBackground = false;
infoTooltip.SetActive(false);
actionsManager.ToggleManipulators(true);
}
private void OnPhotoCaptureCreated(PhotoCapture captureObject)
{
Resolution cameraResolution =
PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
photoCaptureObject = captureObject;
CameraParameters cameraParameters = new CameraParameters();
cameraParameters.hologramOpacity = 1.0f;
cameraParameters.cameraResolutionWidth = cameraResolution.width;
cameraParameters.cameraResolutionHeight = cameraResolution.height;
cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
captureObject.StartPhotoModeAsync(cameraParameters, OnPhotoModeStarted);
}
private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
{
if (result.success)
{
var tempFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
var filePath = Path.Combine(Application.persistentDataPath, tempFileName);
var tempFilePathAndName = filePath;
try
{
HideUI();
infoTooltip.SetActive(false);
photoCaptureObject.TakePhotoAsync(filePath, PhotoCaptureFileOutputFormat.PNG, captureResult =>
{
ShowUI();
if (result.success)
{
photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
#if !UNITY_EDITOR && UNITY_WINRT_10_0
var cameraRollFolder = Windows.Storage.KnownFolders.CameraRoll.Path;
File.Move(tempFilePathAndName, Path.Combine(cameraRollFolder, tempFileName));
#endif
}
} );
}
catch (System.ArgumentException e)
{
Debug.LogError("System.ArgumentException:\n" + e.Message);
}
}
else
{
Debug.LogError("Unable to start photo mode!");
}
}
void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
photoCaptureObject.Dispose();
photoCaptureObject = null;
DeactivateCaptureWithBackground();
}
public void CaptureWithBackground()
{
PhotoCapture.CreateAsync(true, OnPhotoCaptureCreated);
}
public void ToggleCaptureWithoutBackground()
{
if (activeWithoutBackground)
{
DeactivateCaptureWithoutBackground();
}
else
{
if (activeWithBackground)
{
DeactivateCaptureWithBackground();
}
ActivateCaptureWithoutBackground();
}
}
private void ActivateCaptureWithoutBackground()
{
CoreServices.InputSystem.RegisterHandler<IMixedRealityGestureHandler>(this);
ToggleIcon(withoutBackgroundIcon, true);
activeWithoutBackground = true;
infoTooltip.SetActive(true);
actionsManager.ToggleManipulators(false);
}
public void DeactivateCaptureWithoutBackground()
{
CoreServices.InputSystem.UnregisterHandler<IMixedRealityGestureHandler>(this);
ToggleIcon(withoutBackgroundIcon, false);
activeWithoutBackground = false;
infoTooltip.SetActive(false);
actionsManager.ToggleManipulators(true);
}
public void CaptureWithoutBackground()
{
var renderTexture = new RenderTexture(1920, 1080, 24);
camera.targetTexture = renderTexture;
var image = new Texture2D(camera.targetTexture.width, camera.targetTexture.height, TextureFormat.RGB24, false);
HideUI();
infoTooltip.SetActive(false);
camera.Render();
ShowUI();
RenderTexture.active = camera.targetTexture;
image.ReadPixels(new Rect(0, 0, camera.targetTexture.width, camera.targetTexture.height), 0, 0);
RenderTexture.active = null;
camera.targetTexture = null;
Destroy(renderTexture);
var bytes = image.EncodeToPNG();
var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
var filePath = Path.Combine(Application.persistentDataPath, fileName);
File.WriteAllBytes(filePath, bytes);
#if !UNITY_EDITOR && UNITY_WINRT_10_0
var cameraRollFolder = Windows.Storage.KnownFolders.CameraRoll.Path;
File.Move(filePath, Path.Combine(cameraRollFolder, fileName));
#endif
DeactivateCaptureWithoutBackground();
}
private void ToggleIcon(GameObject icon, bool activated)
{
icon.SetActive(activated);
}
private void SetLayerRecursively(GameObject obj, int layer)
{
obj.layer = layer;
foreach (Transform child in obj.transform)
{
SetLayerRecursively(child.gameObject, layer);
}
}
public void OnGestureStarted(InputEventData eventData)
{
if (eventData.MixedRealityInputAction == validateAction)
{
if (activeWithBackground)
{
CaptureWithBackground();
}
else
{
CaptureWithoutBackground();
}
}
else if (eventData.MixedRealityInputAction == cancelAction)
{
if (activeWithBackground)
{
DeactivateCaptureWithBackground();
}
else
{
DeactivateCaptureWithoutBackground();
}
}
}
private void HideUI()
{
var mainMenu = GameObject.Find("MainMenu");
var cursor = GameObject.FindWithTag("Cursor");
SetLayerRecursively(mainMenu, 8);
SetLayerRecursively(cursor, 8);
}
private void ShowUI()
{
var mainMenu = GameObject.Find("MainMenu");
var cursor = GameObject.FindWithTag("Cursor");
SetLayerRecursively(mainMenu, 9);
SetLayerRecursively(cursor, 0);
}
public void OnGestureUpdated(InputEventData eventData)
{
}
public void OnGestureCompleted(InputEventData eventData)
{
}
public void OnGestureCanceled(InputEventData eventData)
{
}
}
| 30.802817 | 119 | 0.629287 | [
"MIT"
] | enzo-bonnot/ARDrawing | Assets/Scripts/Capture/CaptureManager.cs | 8,750 | C# |
//-----------------------------------------------------------------------
// <copyright file="GremlinScenarioTests.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Scenarios
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Azure.Cosmos.CosmosElements;
using Microsoft.Azure.Cosmos.CosmosElements.Numbers;
using Microsoft.Azure.Cosmos.Json;
using Microsoft.Azure.Cosmos.Tests;
using Microsoft.Azure.Documents;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for CosmosDB Gremlin use case scenarios of CosmosElement and JsonNavigator interfaces.
/// </summary>
[TestClass]
public abstract class GremlinScenarioTests
{
private const string PartitionKeyPropertyName = "myPartitionKey";
/// <summary>
/// Gremlin keywords for use in creating scenario Json document structure.
/// </summary>
private static class GremlinKeywords
{
internal const string KW_DOC_ID = "id";
internal const string KW_EDGE_LABEL = "label";
internal const string KW_EDGE_SINKV = "_sink";
internal const string KW_EDGE_SINKV_LABEL = "_sinkLabel";
internal const string KW_EDGE_SINKV_PARTITION = "_sinkPartition";
internal const string KW_EDGEDOC_IDENTIFIER = "_isEdge";
internal const string KW_EDGEDOC_ISPKPROPERTY = "_isPkEdgeProperty";
internal const string KW_EDGEDOC_VERTEXID = "_vertexId";
internal const string KW_EDGEDOC_VERTEXLABEL = "_vertexLabel";
internal const string KW_PROPERTY_ID = "id";
internal const string KW_PROPERTY_VALUE = "_value";
internal const string KW_PROPERTY_META = "_meta";
internal const string KW_VERTEX_LABEL = "label";
}
internal abstract JsonSerializationFormat SerializationFormat { get; }
/// <summary>
/// Test read path for Gremlin edge documents by:
/// - Creating a serialized edge document using eager <see cref="CosmosElement"/>s.
/// - Navigating and verifying the structure and values of the serialized edge document using lazy <see cref="CosmosElement"/>s.
/// </summary>
[TestMethod]
public virtual void SerializeAndDeserializeGremlinEdgeDocument()
{
this.SerializeAndDeserializeEdgeDocumentTest(this.SerializationFormat);
}
/// <summary>
/// Test read path for Gremlin vertex documents by:
/// - Creating a serialized vertex document using eager <see cref="CosmosElement"/>s.
/// - Navigating and verifying structure and values of the serialized vertex document using lazy <see cref="CosmosElement"/>s.
/// </summary>
[TestMethod]
public virtual void SerializeAndDeserializeGremlinVertexDocument()
{
this.SerializeAndDeserializeVertexDocumentTest(this.SerializationFormat);
}
/// <summary>
/// Test write path for Gremlin vertex documents by:
/// - Creating a serialized vertex document using eager <see cref="CosmosElement"/>s.
/// - Navigating the serialized vertex document using lazy <see cref="CosmosElement"/>s.
/// - Assembling a modified vertex document structure using a mix of lazy and eager <see cref="CosmosElement"/>s.
/// - Serializing and verifying the contents of the modified vertex document.
/// </summary>
[TestMethod]
public virtual void DeserializeModifyAndSerializeVertexDocument()
{
this.DeserializeModifyAndSerializeVertexDocumentTest(this.SerializationFormat);
}
/// <summary>
/// Test getting the internal <see cref="CosmosElement"/>s directly from a <see cref="QueryResponse{T}"/> without re-serializing them.
/// </summary>
[TestMethod]
public virtual void GetCosmosElementsFromQueryResponse()
{
this.GetCosmosElementsFromQueryResponseTest(this.SerializationFormat);
}
/// <summary>
/// Test getting other re-serialized objects besides CosmosElement from a <see cref="QueryResponse{T}"/>.
/// </summary>
[TestMethod]
public virtual void GetDeserializedObjectsFromQueryResponse()
{
this.GetDeserializedObjectsFromQueryResponseTest(this.SerializationFormat);
}
internal void SerializeAndDeserializeEdgeDocumentTest(JsonSerializationFormat jsonSerializationFormat)
{
// Constants to use for vertex document property key/values
const string idName = "id";
const string idValue = "e_0";
const string pkValue = "pk_0";
const string labelName = "label";
const string labelValue = "l_0";
const string vertexIdValue = "v_0";
const string vertexLabelValue = "l_1";
const string sinkIdValue = "v_1";
const string sinkLabelValue = "l_2";
const string sinkPartitionValue = "pk_1";
const bool isEdgeValue = true;
const bool isPkEdgePropertyValue = true;
const string boolName = "myBool";
const bool boolValue = true;
const string intName = "myInteger";
const int intValue = 12345;
const string longName = "myLong";
const long longValue = 67890L;
const string floatName = "myFloatingPoint";
const float floatValue = 123.4f;
const string doubleName = "myDouble";
const double doubleValue = 56.78;
const string stringName = "myString";
const string stringValue = "str_0";
Dictionary<string, CosmosElement> edgeDocumentProperties = new Dictionary<string, CosmosElement>()
{
{ idName, CosmosString.Create(idValue) },
{ GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
{ labelName, CosmosString.Create(labelValue) },
{ GremlinKeywords.KW_EDGEDOC_VERTEXID, CosmosString.Create(vertexIdValue) },
{ GremlinKeywords.KW_EDGEDOC_VERTEXLABEL, CosmosString.Create(vertexLabelValue) },
{ GremlinKeywords.KW_EDGE_SINKV, CosmosString.Create(sinkIdValue) },
{ GremlinKeywords.KW_EDGE_SINKV_LABEL, CosmosString.Create(sinkLabelValue) },
{ GremlinKeywords.KW_EDGE_SINKV_PARTITION, CosmosString.Create(sinkPartitionValue) },
{ GremlinKeywords.KW_EDGEDOC_IDENTIFIER, CosmosBoolean.Create(isEdgeValue) },
{ GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY, CosmosBoolean.Create(isPkEdgePropertyValue) },
{ boolName, CosmosBoolean.Create(boolValue) },
{ intName, CosmosNumber64.Create(intValue) },
{ longName, CosmosNumber64.Create(longValue) },
{ floatName, CosmosNumber64.Create(floatValue) },
{ doubleName, CosmosNumber64.Create(doubleValue) },
{ stringName, CosmosString.Create(stringValue) },
};
CosmosObject edgeEagerObject = CosmosObject.Create(edgeDocumentProperties);
// Serialize the edge object into a document using the specified serialization format
IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);
edgeEagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> jsonResult = jsonWriter.GetResult();
Assert.IsTrue(jsonResult.Length > 0, "IJsonWriter result data is empty.");
// Navigate into the serialized edge document using lazy CosmosElements
CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);
// Validate the expected edge document structure/values
// Root edge document object
CosmosObject edgeLazyObject = rootLazyElement as CosmosObject;
Assert.IsNotNull(edgeLazyObject, $"Edge document root is not {nameof(CosmosObject)}.");
Assert.AreEqual(edgeDocumentProperties.Count, edgeLazyObject.Count);
// Edge system document properties
CosmosString idLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, idName);
Assert.AreEqual(idValue, idLazyString.Value);
CosmosString pkLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);
Assert.AreEqual(pkValue, pkLazyString.Value);
CosmosString labelLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, labelName);
Assert.AreEqual(labelValue, labelLazyString.Value);
CosmosString vertexIdLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXID);
Assert.AreEqual(vertexIdValue, vertexIdLazyString.Value);
CosmosString vertexLabelLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXLABEL);
Assert.AreEqual(vertexLabelValue, vertexLabelLazyString.Value);
CosmosString sinkIdLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV);
Assert.AreEqual(sinkIdValue, sinkIdLazyString.Value);
CosmosString sinkLabelLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_LABEL);
Assert.AreEqual(sinkLabelValue, sinkLabelLazyString.Value);
CosmosString sinkPartitionLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_PARTITION);
Assert.AreEqual(sinkPartitionValue, sinkPartitionLazyString.Value);
CosmosBoolean isEdgeLazyBool = this.GetAndAssertObjectProperty<CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_IDENTIFIER);
Assert.AreEqual(isEdgeValue, isEdgeLazyBool.Value);
CosmosBoolean isPkEdgePropertyLazyBool = this.GetAndAssertObjectProperty<CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY);
Assert.AreEqual(isPkEdgePropertyValue, isPkEdgePropertyLazyBool.Value);
// Edge user properties
CosmosBoolean boolValueLazyBool = this.GetAndAssertObjectProperty<CosmosBoolean>(edgeLazyObject, boolName);
Assert.AreEqual(boolValue, boolValueLazyBool.Value);
CosmosNumber intValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(edgeLazyObject, intName);
Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
Assert.IsTrue(intValueLazyNumber.Value.IsInteger);
Assert.AreEqual((long)intValue, intValueLazyNumber.Value);
CosmosNumber longValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(edgeLazyObject, longName);
Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
Assert.IsTrue(intValueLazyNumber.Value.IsInteger);
Assert.AreEqual(longValue, longValueLazyNumber.Value);
CosmosNumber floatValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(edgeLazyObject, floatName);
Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
Assert.IsTrue(floatValueLazyNumber.Value.IsDouble);
Assert.AreEqual((double)floatValue, floatValueLazyNumber.Value);
CosmosNumber doubleValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(edgeLazyObject, doubleName);
Assert.IsTrue(intValueLazyNumber is CosmosNumber64);
Assert.IsTrue(doubleValueLazyNumber.Value.IsDouble);
Assert.AreEqual((double)doubleValue, doubleValueLazyNumber.Value);
CosmosString stringValueLazyString = this.GetAndAssertObjectProperty<CosmosString>(edgeLazyObject, stringName);
Assert.AreEqual(stringValue, stringValueLazyString.Value);
}
internal void SerializeAndDeserializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
{
// Constants to use for vertex document property key/values
const string idName = "id";
const string idValue = "v_0";
const string pkValue = "pk_0";
const string labelName = "label";
const string labelValue = "l_0";
const string boolName = "myBool";
const string boolId = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
const bool boolValue = true;
const string intName = "myInteger";
const string intId = "7546f541-a003-4e69-a25c-608372ed1321";
const int intValue = 12345;
const string longId = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
const long longValue = 67890L;
const string floatName = "myFloatingPoint";
const string floatId = "98d27280-70ee-4edd-8461-7633a328539a";
const float floatValue = 123.4f;
const string doubleId = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
const double doubleValue = 56.78;
const string stringName = "myString";
const string stringId = "6bb8ae5b-19ca-450e-b369-922a34c02729";
const string stringValue = "str_0";
const string metaProperty0Name = "myMetaProperty0";
const string metaProperty0Value = "m_0";
const string metaProperty1Name = "myMetaProperty1";
const int metaProperty1Value = 123;
// Compose the vertex document using eager CosmosElements
Dictionary<string, CosmosElement> vertexDocumentProperties = new Dictionary<string, CosmosElement>()
{
{ idName, CosmosString.Create(idValue) },
{ GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
{ labelName, CosmosString.Create(labelValue) },
{
boolName,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(boolId), CosmosBoolean.Create(boolValue)),
}
)
},
{
intName,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(intId), CosmosNumber64.Create(intValue)),
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(longId), CosmosNumber64.Create(longValue)),
}
)
},
{
floatName,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(floatId), CosmosNumber64.Create(floatValue)),
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(doubleId), CosmosNumber64.Create(doubleValue)),
}
)
},
{
stringName,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(
CosmosString.Create(stringId),
CosmosString.Create(stringValue),
Tuple.Create<string, CosmosElement>(metaProperty0Name, CosmosString.Create(metaProperty0Value)),
Tuple.Create<string, CosmosElement>(metaProperty1Name, CosmosNumber64.Create(metaProperty1Value))),
}
)
},
};
CosmosObject vertexEagerObject = CosmosObject.Create(vertexDocumentProperties);
// Serialize the vertex object into a document using the specified serialization format
IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);
vertexEagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> jsonResult = jsonWriter.GetResult();
Assert.IsTrue(jsonResult.Length > 0, "IJsonWriter result data is empty.");
// Navigate into the serialized vertex document using lazy CosmosElements
CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);
// Validate the expected vertex document structure/values
// Root vertex document object
CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;
Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
Assert.AreEqual(vertexDocumentProperties.Count, vertexLazyObject.Count);
// Vertex system document properties
CosmosString idLazyString = this.GetAndAssertObjectProperty<CosmosString>(vertexLazyObject, idName);
Assert.AreEqual(idValue, idLazyString.Value);
CosmosString pkLazyString = this.GetAndAssertObjectProperty<CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);
Assert.AreEqual(pkValue, pkLazyString.Value);
CosmosString labelLazyString = this.GetAndAssertObjectProperty<CosmosString>(vertexLazyObject, labelName);
Assert.AreEqual(labelValue, labelLazyString.Value);
// Vertex user properties
CosmosArray boolLazyArray = this.GetAndAssertObjectProperty<CosmosArray>(vertexLazyObject, boolName);
Assert.AreEqual(1, boolLazyArray.Count);
// Bool value(s)
CosmosObject boolValue0LazyObject = this.GetAndAssertArrayValue<CosmosObject>(boolLazyArray, 0);
CosmosString boolValue0IdLazyString = this.GetAndAssertObjectProperty<CosmosString>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);
Assert.AreEqual(boolId, boolValue0IdLazyString.Value);
CosmosBoolean boolValue0ValueLazyBool = this.GetAndAssertObjectProperty<CosmosBoolean>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);
Assert.AreEqual(boolValue, boolValue0ValueLazyBool.Value);
CosmosArray intLazyArray = this.GetAndAssertObjectProperty<CosmosArray>(vertexLazyObject, intName);
Assert.AreEqual(2, intLazyArray.Count);
// Integer value(s)
CosmosObject intValue0LazyObject = this.GetAndAssertArrayValue<CosmosObject>(intLazyArray, 0);
CosmosString intValue0IdLazyString = this.GetAndAssertObjectProperty<CosmosString>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);
Assert.AreEqual(intId, intValue0IdLazyString.Value);
CosmosNumber intValue0ValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);
Assert.IsTrue(intValue0ValueLazyNumber is CosmosNumber64);
Assert.IsTrue(intValue0ValueLazyNumber.Value.IsInteger);
Assert.AreEqual((long)intValue, intValue0ValueLazyNumber.Value);
CosmosObject intValue1LazyObject = this.GetAndAssertArrayValue<CosmosObject>(intLazyArray, 1);
CosmosString intValue1IdLazyString = this.GetAndAssertObjectProperty<CosmosString>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);
Assert.AreEqual(longId, intValue1IdLazyString.Value);
CosmosNumber intValue1ValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);
Assert.IsTrue(intValue1ValueLazyNumber is CosmosNumber64);
Assert.IsTrue(intValue1ValueLazyNumber.Value.IsInteger);
Assert.AreEqual(longValue, intValue1ValueLazyNumber.Value);
// Floating point value(s)
CosmosArray floatLazyArray = this.GetAndAssertObjectProperty<CosmosArray>(vertexLazyObject, floatName);
Assert.AreEqual(2, floatLazyArray.Count);
CosmosObject floatValue0LazyObject = this.GetAndAssertArrayValue<CosmosObject>(floatLazyArray, 0);
CosmosString floatValue0IdLazyString = this.GetAndAssertObjectProperty<CosmosString>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);
Assert.AreEqual(floatId, floatValue0IdLazyString.Value);
CosmosNumber floatValue0ValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);
Assert.IsTrue(floatValue0ValueLazyNumber is CosmosNumber64);
Assert.IsTrue(floatValue0ValueLazyNumber.Value.IsDouble);
Assert.AreEqual((double)floatValue, floatValue0ValueLazyNumber.Value);
CosmosObject floatValue1LazyObject = this.GetAndAssertArrayValue<CosmosObject>(floatLazyArray, 1);
CosmosString floatValue1IdLazyString = this.GetAndAssertObjectProperty<CosmosString>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);
Assert.AreEqual(doubleId, floatValue1IdLazyString.Value);
CosmosNumber floatValue1ValueLazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);
Assert.IsTrue(floatValue1ValueLazyNumber is CosmosNumber64);
Assert.IsTrue(floatValue1ValueLazyNumber.Value.IsDouble);
Assert.AreEqual(doubleValue, floatValue1ValueLazyNumber.Value);
// String value(s)
CosmosArray stringLazyArray = this.GetAndAssertObjectProperty<CosmosArray>(vertexLazyObject, stringName);
Assert.AreEqual(1, stringLazyArray.Count);
CosmosObject stringValue0LazyObject = this.GetAndAssertArrayValue<CosmosObject>(stringLazyArray, 0);
CosmosString stringValue0IdLazyString = this.GetAndAssertObjectProperty<CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);
Assert.AreEqual(stringId, stringValue0IdLazyString.Value);
CosmosString stringValue0ValueLazyString = this.GetAndAssertObjectProperty<CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);
Assert.AreEqual(stringValue, stringValue0ValueLazyString.Value);
// String value meta-properties
CosmosObject stringValue0MetaLazyObject = this.GetAndAssertObjectProperty<CosmosObject>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_META);
Assert.AreEqual(2, stringValue0MetaLazyObject.Count);
CosmosString stringValue0MetaValue0LazyString = this.GetAndAssertObjectProperty<CosmosString>(stringValue0MetaLazyObject, metaProperty0Name);
Assert.AreEqual(metaProperty0Value, stringValue0MetaValue0LazyString.Value);
CosmosNumber stringValue0MetaValue1LazyNumber = this.GetAndAssertObjectProperty<CosmosNumber>(stringValue0MetaLazyObject, metaProperty1Name);
Assert.IsTrue(stringValue0MetaValue1LazyNumber is CosmosNumber64);
Assert.IsTrue(stringValue0MetaValue1LazyNumber.Value.IsInteger);
Assert.AreEqual((long)metaProperty1Value, stringValue0MetaValue1LazyNumber.Value);
}
internal void DeserializeModifyAndSerializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
{
// Constants to use for vertex document property key/values
const string idName = "id";
const string idValue = "v_0";
const string pkValue = "pk_0";
const string labelName = "label";
const string labelValue = "l_0";
const string property1Name = "p_0";
const string property1Value1Id = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
const string property1Value1 = "p_0_v_0";
const string property1Value2Id = "7546f541-a003-4e69-a25c-608372ed1321";
const long property1Value2 = 1234;
const string property2Name = "p_1";
const string property2Value1Id = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
const double property2Value1 = 34.56;
const string property3Name = "p_2";
const string property3Value1Id = "98d27280-70ee-4edd-8461-7633a328539a";
const bool property3Value1 = true;
const string property4Name = "p_3";
const string property4Value1Id = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
const string property4Value1 = "p_3_v_0";
// Compose the initial vertex document using eager CosmosElements
Dictionary<string, CosmosElement> initialVertexDocumentProperties = new Dictionary<string, CosmosElement>()
{
{ idName, CosmosString.Create(idValue) },
{ GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
{ labelName, CosmosString.Create(labelValue) },
{
property1Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value1Id), CosmosString.Create(property1Value1)),
}
)
},
{
property2Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
}
)
},
{
property3Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property3Value1Id), CosmosBoolean.Create(property3Value1)),
}
)
},
};
CosmosObject initialVertexEagerObject = CosmosObject.Create(initialVertexDocumentProperties);
// Serialize the initial vertex object into a document using the specified serialization format
IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);
initialVertexEagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> initialJsonWriterResult = jsonWriter.GetResult();
Assert.IsTrue(initialJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");
// Navigate into the serialized vertex document using lazy CosmosElements
CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(initialJsonWriterResult);
// Root vertex document object
CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;
Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
Assert.AreEqual(initialVertexDocumentProperties.Count, vertexLazyObject.Count);
CosmosString idLazyString = this.GetAndAssertObjectProperty<CosmosString>(vertexLazyObject, idName);
CosmosString pkLazyString = this.GetAndAssertObjectProperty<CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);
CosmosString labelLazyString = this.GetAndAssertObjectProperty<CosmosString>(vertexLazyObject, labelName);
CosmosArray property2Array = this.GetAndAssertObjectProperty<CosmosArray>(vertexLazyObject, property2Name);
// Compose a new vertex document using a combination of lazy and eager CosmosElements
Dictionary<string, CosmosElement> modifiedVertexDocumentProperties = new Dictionary<string, CosmosElement>()
{
{ idName, idLazyString },
{ GremlinScenarioTests.PartitionKeyPropertyName, pkLazyString },
{ labelName, labelLazyString },
// Property 1 is modified with a new value
{
property1Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
}
)
},
// Property 2 is unmodified
{ property2Name, property2Array },
// Property 3 is deleted
// Property 4 is newly added
{
property4Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
}
)
},
};
CosmosObject modifiedVertexEagerObject = CosmosObject.Create(modifiedVertexDocumentProperties);
// Serialize the modified vertex object into a document using the specified serialization format
jsonWriter = JsonWriter.Create(jsonSerializationFormat);
modifiedVertexEagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> modifiedJsonWriterResult = jsonWriter.GetResult();
Assert.IsTrue(modifiedJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");
// Compose an expected vertex document using eager CosmosElements
Dictionary<string, CosmosElement> expectedVertexDocumentProperties = new Dictionary<string, CosmosElement>()
{
{ idName, CosmosString.Create(idValue) },
{ GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
{ labelName, CosmosString.Create(labelValue) },
{
property1Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
}
)
},
{
property2Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
}
)
},
{
property4Name,
CosmosArray.Create(
new CosmosElement[]
{
this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
}
)
},
};
CosmosObject expectedVertexEagerObject = CosmosObject.Create(expectedVertexDocumentProperties);
// Serialize the initial vertex object into a document using the specified serialization format
jsonWriter = JsonWriter.Create(jsonSerializationFormat);
expectedVertexEagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> expectedJsonWriterResult = jsonWriter.GetResult();
Assert.IsTrue(expectedJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");
// Verify that the modified serialized document matches the expected serialized document
Assert.IsTrue(modifiedJsonWriterResult.Span.SequenceEqual(expectedJsonWriterResult.Span));
}
internal void GetCosmosElementsFromQueryResponseTest(JsonSerializationFormat jsonSerializationFormat)
{
// Constants to use for vertex document property key/values
const string vertex1Id = "v_0";
const string vertex2Id = "v_1";
const string vertex1Label = "l_0";
const string vertex2Label = "l_1";
const string vertex1PkValue = "pk_0";
const string vertex2PkValue = "pk_1";
const string property1Name = "p_0";
const string vertex1Property1Value = "v_0_p_0_v_0";
const string vertex2Property1Value = "v_1_p_0_v_0";
const string property2Name = "p_1";
const double vertex1Property2Value = 12.34;
const long vertex2Property2Value = 5678;
// Compose two initial vertex documents using eager CosmosElements
CosmosObject initialVertex1EagerObject = this.CreateVertexDocument(
vertex1Id,
vertex1Label,
GremlinScenarioTests.PartitionKeyPropertyName,
vertex1PkValue,
new Tuple<string, IEnumerable<object>>[]
{
Tuple.Create<string, IEnumerable<object>>(property1Name, new object[] { vertex1Property1Value }),
Tuple.Create<string, IEnumerable<object>>(property2Name, new object[] { vertex1Property2Value }),
});
CosmosObject initialVertex2EagerObject = this.CreateVertexDocument(
vertex2Id,
vertex2Label,
GremlinScenarioTests.PartitionKeyPropertyName,
vertex2PkValue,
new Tuple<string, IEnumerable<object>>[]
{
Tuple.Create<string, IEnumerable<object>>(property1Name, new object[] { vertex2Property1Value }),
Tuple.Create<string, IEnumerable<object>>(property2Name, new object[] { vertex2Property2Value }),
});
// Serialize the initial vertex object into a document using the specified serialization format
IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);
initialVertex1EagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> vertex1JsonWriterResult = jsonWriter.GetResult();
Assert.IsTrue(vertex1JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");
jsonWriter = JsonWriter.Create(jsonSerializationFormat);
initialVertex2EagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> vertex2JsonWriterResult = jsonWriter.GetResult();
Assert.IsTrue(vertex2JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");
// Navigate into the serialized vertex documents using lazy CosmosElements
CosmosElement vertex1LazyObject = CosmosElement.CreateFromBuffer(vertex1JsonWriterResult);
CosmosElement vertex2LazyObject = CosmosElement.CreateFromBuffer(vertex2JsonWriterResult);
// Create a CosmosElement-typed QueryResponse backed by the vertex document CosmosElements
CosmosArray vertexArray = CosmosArray.Create(
new CosmosElement[]
{
vertex1LazyObject,
vertex2LazyObject,
});
QueryResponse queryResponse = QueryResponse.CreateSuccess(
vertexArray,
count: 2,
responseLengthBytes: vertex1JsonWriterResult.Length + vertex2JsonWriterResult.Length,
serializationOptions: null,
responseHeaders: CosmosQueryResponseMessageHeaders.ConvertToQueryHeaders(
sourceHeaders: null,
resourceType: ResourceType.Document,
containerRid: GremlinScenarioTests.CreateRandomString(10)),
diagnostics: new CosmosDiagnosticsContextCore());
QueryResponse<CosmosElement> cosmosElementQueryResponse =
QueryResponse<CosmosElement>.CreateResponse<CosmosElement>(
queryResponse,
MockCosmosUtil.Serializer);
// Assert that we are directly returned the lazy CosmosElements that we created earlier
List<CosmosElement> responseCosmosElements = new List<CosmosElement>(cosmosElementQueryResponse.Resource);
Assert.AreEqual(vertexArray.Count, responseCosmosElements.Count);
Assert.AreSame(vertex1LazyObject, responseCosmosElements[0]);
Assert.AreSame(vertex2LazyObject, responseCosmosElements[1]);
}
internal void GetDeserializedObjectsFromQueryResponseTest(JsonSerializationFormat jsonSerializationFormat)
{
// Constants to use for vertex document property key/values
const string vertex1Id = "v_0";
const string vertex2Id = "v_1";
const string vertex1Label = "l_0";
const string vertex2Label = "l_1";
const string vertex1PkValue = "pk_0";
const string vertex2PkValue = "pk_1";
const string property1Name = "p_0";
const string vertex1Property1Value = "v_0_p_0_v_0";
const string vertex2Property1Value = "v_1_p_0_v_0";
const string property2Name = "p_1";
const double vertex1Property2Value = 12.34;
const long vertex2Property2Value = 5678;
// Compose two initial vertex documents using eager CosmosElements
CosmosObject initialVertex1EagerObject = this.CreateVertexDocument(
vertex1Id,
vertex1Label,
GremlinScenarioTests.PartitionKeyPropertyName,
vertex1PkValue,
new Tuple<string, IEnumerable<object>>[]
{
Tuple.Create<string, IEnumerable<object>>(property1Name, new object[] { vertex1Property1Value }),
Tuple.Create<string, IEnumerable<object>>(property2Name, new object[] { vertex1Property2Value }),
});
CosmosObject initialVertex2EagerObject = this.CreateVertexDocument(
vertex2Id,
vertex2Label,
GremlinScenarioTests.PartitionKeyPropertyName,
vertex2PkValue,
new Tuple<string, IEnumerable<object>>[]
{
Tuple.Create<string, IEnumerable<object>>(property1Name, new object[] { vertex2Property1Value }),
Tuple.Create<string, IEnumerable<object>>(property2Name, new object[] { vertex2Property2Value }),
});
// Serialize the initial vertex object into a document using the specified serialization format
IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);
initialVertex1EagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> vertex1JsonWriterResult = jsonWriter.GetResult();
Assert.IsTrue(vertex1JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");
jsonWriter = JsonWriter.Create(jsonSerializationFormat);
initialVertex2EagerObject.WriteTo(jsonWriter);
ReadOnlyMemory<byte> vertex2JsonWriterResult = jsonWriter.GetResult();
Assert.IsTrue(vertex2JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");
// Navigate into the serialized vertex documents using lazy CosmosElements
CosmosElement vertex1LazyObject = CosmosElement.CreateFromBuffer(vertex1JsonWriterResult);
CosmosElement vertex2LazyObject = CosmosElement.CreateFromBuffer(vertex2JsonWriterResult);
// Create a dynamically-typed QueryResponse backed by the vertex document CosmosElements
CosmosArray vertexArray = CosmosArray.Create(
new CosmosElement[]
{
vertex1LazyObject,
vertex2LazyObject,
});
QueryResponse queryResponse = QueryResponse.CreateSuccess(
vertexArray,
count: 2,
responseLengthBytes: vertex1JsonWriterResult.Length + vertex2JsonWriterResult.Length,
serializationOptions: null,
responseHeaders: CosmosQueryResponseMessageHeaders.ConvertToQueryHeaders(
sourceHeaders: null,
resourceType: ResourceType.Document,
containerRid: GremlinScenarioTests.CreateRandomString(10)),
diagnostics: new CosmosDiagnosticsContextCore());
QueryResponse<dynamic> cosmosElementQueryResponse =
QueryResponse<dynamic>.CreateResponse<dynamic>(
queryResponse,
MockCosmosUtil.Serializer);
// Assert that other objects (anything besides the lazy CosmosElements that we created earlier) are deserialized
// from the backing CosmosElement contents rather than being directly returned as CosmosElements
List<dynamic> responseCosmosElements = new List<dynamic>(cosmosElementQueryResponse.Resource);
Assert.AreEqual(vertexArray.Count, responseCosmosElements.Count);
Assert.AreNotSame(vertex1LazyObject, responseCosmosElements[0]);
Assert.AreNotSame(vertex2LazyObject, responseCosmosElements[1]);
}
private CosmosObject CreateVertexDocument(string id, string label, string pkName, string pkValue, IEnumerable<Tuple<string, IEnumerable<object>>> userProperties)
{
Dictionary<string, CosmosElement> vertexDocumentProperties = new Dictionary<string, CosmosElement>()
{
{ GremlinKeywords.KW_DOC_ID, CosmosString.Create(id) },
{ GremlinKeywords.KW_VERTEX_LABEL, CosmosString.Create(label) },
};
if (!string.IsNullOrEmpty(pkName) && !string.IsNullOrEmpty(pkValue))
{
vertexDocumentProperties.Add(pkName, CosmosString.Create(pkValue));
}
foreach (Tuple<string, IEnumerable<object>> userProperty in userProperties)
{
List<CosmosElement> singleValues = new List<CosmosElement>();
foreach (object userPropertyValue in userProperty.Item2)
{
string propertyId = Guid.NewGuid().ToString();
singleValues.Add(
this.CreateVertexPropertySingleComplexValue(
CosmosString.Create(propertyId),
this.CreateVertexPropertyPrimitiveValueElement(userPropertyValue)));
}
}
return CosmosObject.Create(vertexDocumentProperties);
}
private CosmosElement CreateVertexPropertySingleComplexValue(
CosmosString propertyIdElement,
CosmosElement propertyValueElement,
params Tuple<string, CosmosElement>[] metaPropertyPairs)
{
// Vertex complex property value
Dictionary<string, CosmosElement> propertyValueMembers = new Dictionary<string, CosmosElement>()
{
{ GremlinKeywords.KW_PROPERTY_ID, propertyIdElement },
{ GremlinKeywords.KW_PROPERTY_VALUE, propertyValueElement },
};
// (Optional) Meta-property object for the property value
if (metaPropertyPairs.Length > 0)
{
CosmosObject metaElement = CosmosObject.Create(
metaPropertyPairs.ToDictionary(pair => pair.Item1, pair => pair.Item2));
propertyValueMembers.Add(GremlinKeywords.KW_PROPERTY_META, metaElement);
}
return CosmosObject.Create(propertyValueMembers);
}
private CosmosElement CreateVertexPropertyPrimitiveValueElement(object value)
{
switch (value)
{
case bool boolValue:
return CosmosBoolean.Create(boolValue);
case double doubleValue:
return CosmosNumber64.Create(doubleValue);
case float floatValue:
return CosmosNumber64.Create(floatValue);
case int intValue:
return CosmosNumber64.Create(intValue);
case long longValue:
return CosmosNumber64.Create(longValue);
case string stringValue:
return CosmosString.Create(stringValue);
default:
throw new AssertFailedException($"Invalid Gremlin property value object type: {value.GetType().Name}.");
}
}
private static string CreateRandomString(int stringLength)
{
Assert.IsTrue(stringLength > 0, $"Random string length ({stringLength}) must be a positive value");
const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789=";
Random rand = new Random();
StringBuilder sb = new StringBuilder(stringLength);
for (int i = 0; i < stringLength; i++)
{
sb.Append(validChars[rand.Next(validChars.Length)]);
}
return sb.ToString();
}
private T GetAndAssertObjectProperty<T>(CosmosObject cosmosObject, string propertyName)
where T : CosmosElement
{
Assert.IsTrue(cosmosObject.TryGetValue(propertyName, out CosmosElement lazyElement), $"Object does not contain the {propertyName} property.");
T lazyPropertyValue = lazyElement as T;
Assert.IsNotNull(lazyPropertyValue, $"Object property {propertyName} is not {typeof(T).Name}.");
return lazyPropertyValue;
}
private T GetAndAssertArrayValue<T>(CosmosArray cosmosArray, int index)
where T : CosmosElement
{
T boolValue1LazyValue = cosmosArray[index] as T;
Assert.IsNotNull(boolValue1LazyValue, $"Array value at position {index} is not {typeof(T).Name}.");
return boolValue1LazyValue;
}
}
}
| 54.213705 | 169 | 0.646407 | [
"MIT"
] | Liphi/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/Scenarios/GremlinScenarioTests.cs | 46,680 | 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 Focus.Properties {
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", "15.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("Focus.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon AppIconblk {
get {
object obj = ResourceManager.GetObject("AppIconblk", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon AppIconwht {
get {
object obj = ResourceManager.GetObject("AppIconwht", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Focus.
/// </summary>
internal static string AppName {
get {
return ResourceManager.GetString("AppName", resourceCulture);
}
}
}
}
| 42.032258 | 172 | 0.572013 | [
"MIT"
] | timvw74/Focus | Focus/Properties/Resources.Designer.cs | 3,911 | C# |
using NUnit.Framework;
using CodeWars;
namespace CodeWarsTests
{
[TestFixture]
public class YourOrderTests
{
[Test, Description("Sample Tests")]
public void SampleTest()
{
Assert.AreEqual("Thi1s is2 3a T4est", YourOrder.Order("is2 Thi1s T4est 3a"));
Assert.AreEqual("Fo1r the2 g3ood 4of th5e pe6ople", YourOrder.Order("4of Fo1r pe6ople g3ood th5e the2"));
Assert.AreEqual("", YourOrder.Order(""));
}
}
} | 28.764706 | 117 | 0.621677 | [
"MIT"
] | a-kozhanov/codewars-csharp | CodeWarsTests/6kyu/YourOrderTests.cs | 491 | C# |
// File generated from our OpenAPI spec
namespace Stripe.TestHelpers
{
using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class TestClockCreateOptions : BaseOptions
{
/// <summary>
/// The initial frozen time for this test clock.
/// </summary>
[JsonProperty("frozen_time")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime? FrozenTime { get; set; }
/// <summary>
/// The name for this test clock.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
}
}
| 25.958333 | 56 | 0.600321 | [
"Apache-2.0"
] | Gofundraise/stripe-dotnet | src/Stripe.net/Services/TestHelpers/TestClocks/TestClockCreateOptions.cs | 623 | C# |
namespace PayStuffWeb.WindsorSupport
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Http.Dependencies;
using Castle.MicroKernel;
[DebuggerStepThrough]
internal class DependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
{
private readonly IKernel kernel;
public DependencyResolver(IKernel kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new DependencyScope(kernel);
}
public object GetService(Type type)
{
return kernel.HasComponent(type) ? kernel.Resolve(type) : null;
}
public IEnumerable<object> GetServices(Type type)
{
return kernel.ResolveAll(type).Cast<object>();
}
public void Dispose()
{
}
}
} | 25.025641 | 89 | 0.588115 | [
"MIT"
] | caloggins/PayStuff | src/PayStuffWeb/WindsorSupport/DependencyResolver.cs | 978 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Portal : MonoBehaviour {
public GameObject exit;
public GameObject pointer;
public bool inUse;
// Use this for initialization
void Start () {
pointer.SetActive(false);
bool inUse = false;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other)
//void OnCollisionEnter(Collision other)
{
Debug.Log("Trigger Enter");
GameObject player = other.gameObject;
var mouse = player.GetComponent<Mouse>();
var mouseStatus = player.GetComponent<MouseTeleport>();
if (mouse && mouse.isLocalPlayer && mouseStatus && !mouseStatus.isTeleporting)
{
mouseStatus.isTeleporting = true;
inUse = true;
var exitStatus = exit.GetComponent<Portal>();
player.transform.position = exit.transform.position;
player.transform.rotation = exit.transform.rotation;
}
}
void OnTriggerExit(Collider other)
//void OnCollisionEnter(Collision other)
{
Debug.Log("Trigger Exit");
GameObject player = other.gameObject;
var mouse = player.GetComponent<Mouse>();
var mouseStatus = player.GetComponent<MouseTeleport>();
var exitStatus = exit.GetComponent<Portal>();
if (mouse && mouse.isLocalPlayer && mouseStatus && mouseStatus.isTeleporting && exitStatus && exitStatus.inUse)
{
mouseStatus.isTeleporting = false;
exitStatus.inUse = false;
}
}
}
| 26.258065 | 119 | 0.632678 | [
"MIT"
] | ajmwagar/roachcoach | Assets/Scripts/Portal.cs | 1,630 | C# |
using Android.Views;
namespace Polkovnik.DroidInjector
{
/// <summary>
/// Injector.
/// DO NOT PASS METHODS OF THIS CLASS AS DELEGATES!
/// </summary>
public sealed class Injector
{
/// <summary>
/// Call this method only in types derived from Activity.
/// Starts resolving views.
/// This method will be replaced with generated method in activity.
/// </summary>
public static void InjectViews()
{
throw new InjectorException($"Method {nameof(InjectViews)} must be removed at runtime. Check if Fody is working.");
}
/// <summary>
/// Starts resolving views.
/// This method will be replaced with generated method in activity.
/// </summary>
/// <param name="view">View.</param>
public static void InjectViews(View view)
{
throw new InjectorException($"Method {nameof(InjectViews)} must be removed at runtime. Check if Fody is working.");
}
/// <summary>
/// Call this method only in types derived from Activity.
/// Starts binding view events.
/// This method will be replaced with generated method in activity.
/// </summary>
public static void BindViewEvents()
{
throw new InjectorException($"Method {nameof(BindViewEvents)} must be removed at runtime. Check if Fody is working.");
}
/// <summary>
/// Starts binding view events.
/// This method will be replaced with generated method in activity.
/// </summary>
/// <param name="view">View.</param>
public static void BindViewEvents(View view)
{
throw new InjectorException($"Method {nameof(BindViewEvents)} must be removed at runtime. Check if Fody is working.");
}
/// <summary>
/// Starts resolving menu items.
/// This method will be replaced with generated method in activity.
/// </summary>
/// <param name="menu">Menu.</param>
public static void InjectMenuItems(IMenu menu)
{
throw new InjectorException($"Method {nameof(InjectMenuItems)} must be removed at runtime. Check if Fody is working.");
}
}
} | 37.360656 | 131 | 0.597631 | [
"Apache-2.0"
] | MAX-POLKOVNIK/DroidInjector | Polkovnik.DroidInjector/Injector.cs | 2,281 | C# |
// Reference from Maarten Balliauw, https://blog.maartenballiauw.be/post/2017/08/01/building-a-scheduled-cache-updater-in-aspnet-core-2.html
using System;
using NCrontab;
namespace ZimaHrm.Core.Infrastructure.ScheduledTasks
{
public class SchedulerTaskWrapper
{
public CrontabSchedule Schedule { get; set; }
public IScheduledTask Task { get; set; }
public DateTime LastRunTime { get; set; }
public DateTime NextRunTime { get; set; }
public void Increment()
{
LastRunTime = NextRunTime;
NextRunTime = Schedule.GetNextOccurrence(NextRunTime);
}
public bool ShouldRun(DateTime currentTime)
{
return NextRunTime < currentTime && LastRunTime != NextRunTime;
}
}
}
| 26.5 | 141 | 0.65283 | [
"Apache-2.0"
] | Dakicksoft/ZimaHrm | ZimaHrm.Infrastructure/ScheduledTasks/SchedulerTaskWrapper.cs | 797 | C# |
using Microsoft.Extensions.Logging;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Dafny.LanguageServer.Language.Symbols {
/// <summary>
/// Symbol resolver that utilizes dafny-lang to resolve the symbols.
/// </summary>
/// <remarks>
/// dafny-lang makes use of static members and assembly loading. Since thread-safety of this is not guaranteed,
/// this resolver serializes all invocations.
/// </remarks>
public class DafnyLangSymbolResolver : ISymbolResolver {
private readonly ILogger _logger;
private readonly SemaphoreSlim _resolverMutex = new SemaphoreSlim(1);
public DafnyLangSymbolResolver(ILogger<DafnyLangSymbolResolver> logger) {
_logger = logger;
}
public async Task<CompilationUnit> ResolveSymbolsAsync(TextDocumentItem textDocument, Dafny.Program program, CancellationToken cancellationToken) {
int parserErrors = GetErrorCount(program);
if(parserErrors > 0) {
_logger.LogTrace("document {} had {} parser errors, skipping symbol resolution", textDocument.Uri, parserErrors);
return new CompilationUnit(program);
}
// TODO The resolution requires mutual exclusion since it sets static variables of classes like Microsoft.Dafny.Type.
// Although, the variables are marked "ThreadStatic" - thus it might not be necessary. But there might be
// other classes as well.
await _resolverMutex.WaitAsync(cancellationToken);
try {
if(!RunDafnyResolver(textDocument, program)) {
// We cannot proceeed without a successful resolution. Due to the contracts in dafny-lang, we cannot
// access a property without potential contract violations. For example, a variable may have an
// unresolved type represented by null. However, the contract prohibits the use of the type property
// because it must not be null.
return new CompilationUnit(program);
}
} finally {
_resolverMutex.Release();
}
return new SymbolDeclarationResolver(_logger, cancellationToken).ProcessProgram(program);
}
private static int GetErrorCount(Dafny.Program program) {
return program.reporter.AllMessages[ErrorLevel.Error].Count;
}
private bool RunDafnyResolver(TextDocumentItem document, Dafny.Program program) {
var resolver = new Resolver(program);
resolver.ResolveProgram(program);
int resolverErrors = GetErrorCount(program);
if(resolverErrors > 0) {
_logger.LogDebug("encountered {} errors while resolving {}", resolverErrors, document.Uri);
return false;
}
return true;
}
private class SymbolDeclarationResolver {
private readonly ILogger _logger;
private readonly CancellationToken _cancellationToken;
public SymbolDeclarationResolver(ILogger logger, CancellationToken cancellationToken) {
_logger = logger;
_cancellationToken = cancellationToken;
}
public CompilationUnit ProcessProgram(Dafny.Program program) {
_cancellationToken.ThrowIfCancellationRequested();
var compilationUnit = new CompilationUnit(program);
// program.CompileModules would probably more suitable here, since we want the symbols of the System module as well.
// However, it appears that the AST of program.CompileModules does not hold the correct location of the nodes - at least of the declarations.
foreach(var module in program.Modules()) {
compilationUnit.Modules.Add(ProcessModule(compilationUnit, module));
}
compilationUnit.Modules.Add(ProcessModule(compilationUnit, program.BuiltIns.SystemModule));
return compilationUnit;
}
private ModuleSymbol ProcessModule(Symbol scope, ModuleDefinition moduleDefinition) {
_cancellationToken.ThrowIfCancellationRequested();
var moduleSymbol = new ModuleSymbol(scope, moduleDefinition);
foreach(var declaration in moduleDefinition.TopLevelDecls) {
var topLevelSymbol = ProcessTopLevelDeclaration(moduleSymbol, declaration);
if(topLevelSymbol != null) {
moduleSymbol.Declarations.Add(topLevelSymbol);
}
}
return moduleSymbol;
}
private Symbol? ProcessTopLevelDeclaration(ModuleSymbol moduleSymbol, TopLevelDecl topLevelDeclaration) {
_cancellationToken.ThrowIfCancellationRequested();
switch(topLevelDeclaration) {
case ClassDecl classDeclaration:
return ProcessClass(moduleSymbol, classDeclaration);
case LiteralModuleDecl literalModuleDeclaration:
return ProcessModule(moduleSymbol, literalModuleDeclaration.ModuleDef);
case ValuetypeDecl valueTypeDeclaration:
return ProcessValueType(moduleSymbol, valueTypeDeclaration);
default:
_logger.LogWarning("encountered unknown top level declaration {} of type {}", topLevelDeclaration.Name, topLevelDeclaration.GetType());
return null;
}
}
private ClassSymbol ProcessClass(Symbol scope, ClassDecl classDeclaration) {
_cancellationToken.ThrowIfCancellationRequested();
var classSymbol = new ClassSymbol(scope, classDeclaration);
foreach(var member in classDeclaration.Members) {
var memberSymbol = ProcessClassMember(classSymbol, member);
if(memberSymbol != null) {
// TODO When respecting all possible class members, this should never be null.
classSymbol.Members.Add(memberSymbol);
}
}
return classSymbol;
}
private ValueTypeSymbol ProcessValueType(Symbol scope, ValuetypeDecl valueTypeDecarlation) {
_cancellationToken.ThrowIfCancellationRequested();
return new ValueTypeSymbol(scope, valueTypeDecarlation);
}
private Symbol? ProcessClassMember(ClassSymbol scope, MemberDecl memberDeclaration) {
_cancellationToken.ThrowIfCancellationRequested();
switch(memberDeclaration) {
case Function function:
return ProcessFunction(scope, function);
case Method method:
// TODO handle the constructors explicitely? The constructor is a sub-class of Method.
return ProcessMethod(scope, method);
case Field field:
return ProcessField(scope, field);
default:
// TODO The last missing member is AmbiguousMemberDecl which is created by the resolver.
// When is this class exactly used?
_logger.LogWarning("encountered unknown class member declaration {}", memberDeclaration.GetType());
return null;
}
}
private FunctionSymbol ProcessFunction(Symbol scope, Function function) {
_cancellationToken.ThrowIfCancellationRequested();
var functionSymbol = new FunctionSymbol(scope, function);
foreach(var parameter in function.Formals) {
functionSymbol.Parameters.Add(ProcessFormal(scope, parameter));
}
return functionSymbol;
}
private MethodSymbol ProcessMethod(Symbol scope, Method method) {
_cancellationToken.ThrowIfCancellationRequested();
var methodSymbol = new MethodSymbol(scope, method);
foreach(var parameter in method.Ins) {
methodSymbol.Parameters.Add(ProcessFormal(scope, parameter));
}
foreach(var result in method.Outs) {
methodSymbol.Returns.Add(ProcessFormal(scope, result));
}
ProcessAndRegisterMethodBody(methodSymbol, method.Body);
return methodSymbol;
}
private void ProcessAndRegisterMethodBody(MethodSymbol methodSymbol, BlockStmt? blockStatement) {
if(blockStatement == null) {
return;
}
var rootBlock = new ScopeSymbol(methodSymbol, blockStatement);
var localVisitor = new LocalVariableDeclarationVisitor(_logger, rootBlock);
localVisitor.Resolve(blockStatement);
methodSymbol.Block = rootBlock;
}
private FieldSymbol ProcessField(Symbol scope, Field field) {
_cancellationToken.ThrowIfCancellationRequested();
return new FieldSymbol(scope, field);
}
private VariableSymbol ProcessFormal(Symbol scope, Formal formal) {
_cancellationToken.ThrowIfCancellationRequested();
return new VariableSymbol(scope, formal);
}
}
private class LocalVariableDeclarationVisitor : SyntaxTreeVisitor {
private readonly ILogger _logger;
private ScopeSymbol _block;
public LocalVariableDeclarationVisitor(ILogger logger, ScopeSymbol rootBlock) {
// TODO support cancellation
_logger = logger;
_block = rootBlock;
}
public void Resolve(BlockStmt blockStatement) {
// The base is directly visited to avoid doubly nesting the root block of the method.
base.Visit(blockStatement);
}
public override void VisitUnknown(object node, Boogie.IToken token) {
_logger.LogWarning("encountered unknown syntax node of type {} in {}@({},{})", node.GetType(), Path.GetFileName(token.filename), token.line, token.col);
}
public override void Visit(BlockStmt blockStatement) {
var oldBlock = _block;
_block = new ScopeSymbol(_block, blockStatement);
oldBlock.Symbols.Add(_block);
base.Visit(blockStatement);
_block = oldBlock;
}
public override void Visit(LocalVariable localVariable) {
_block.Symbols.Add(new VariableSymbol(_block, localVariable));
}
}
}
}
| 43.227679 | 160 | 0.699473 | [
"MIT"
] | DafnyVSCode/language-server-csharp | Source/DafnyLS/Language/Symbols/DafnyLangSymbolResolver.cs | 9,685 | 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.
*/
namespace Apache.Ignite.Core.Cache
{
/// <summary>
/// Cache entry interface.
/// </summary>
/// <typeparam name="TK">Key type.</typeparam>
/// <typeparam name="TV">Value type.</typeparam>
public interface ICacheEntry<out TK, out TV>
{
/// <summary>
/// Gets the key.
/// </summary>
TK Key { get; }
/// <summary>
/// Gets the value.
/// </summary>
TV Value { get; }
}
}
| 33.447368 | 75 | 0.659323 | [
"CC0-1.0"
] | 10088/ignite | modules/platforms/dotnet/Apache.Ignite.Core/Cache/ICacheEntry.cs | 1,271 | C# |
//
// Copyright (c) LightBuzz Software.
// All rights reserved.
//
// http://lightbuzz.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Based on: http://www.codeproject.com/Articles/17425/A-Vector-Type-for-C by R Potter
//
using System;
namespace LightBuzz.Vitruvius
{
/// <summary>
/// Represents a displacement in 3-D space.
/// </summary>
public struct Vector3
{
#region Constants
/// <summary>
/// A vector with the minimum double values.
/// </summary>
public static readonly Vector3 MinValue = new Vector3(double.MinValue, double.MinValue, double.MinValue);
/// <summary>
/// A vector with the maximum double values.
/// </summary>
public static readonly Vector3 MaxValue = new Vector3(double.MaxValue, double.MaxValue, double.MaxValue);
/// <summary>
/// A vector with Epsilon values.
/// </summary>
public static readonly Vector3 Epsilon = new Vector3(double.Epsilon, double.Epsilon, double.Epsilon);
/// <summary>
/// A vector with zero values.
/// </summary>
public static readonly Vector3 Zero = new Vector3(0.0, 0.0, 0.0);
#endregion
#region Members
/// <summary>
/// Gets or sets the X component of this vector.
/// </summary>
public double X;
/// <summary>
/// Gets or sets the Y component of this vector.
/// </summary>
public double Y;
/// <summary>
/// Gets or sets the Z component of this vector.
/// </summary>
public double Z;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of Vector3 with the specified initial values.
/// </summary>
/// <param name="x">Value of the X coordinate of the new vector.</param>
/// <param name="y">Value of the Y coordinate of the new vector.</param>
/// <param name="z">Value of the Z coordinate of the new vector.</param>
public Vector3(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the length (or magnitude) of this vector.
/// </summary>
public double Length
{
get
{
return Math.Sqrt(X * X + Y * Y + Z * Z);
}
}
/// <summary>
/// Gets the square of the length of this vector.
/// </summary>
public double LengthSquared
{
get
{
return X * X + Y * Y + Z * Z;
}
}
#endregion
#region Public methods
/// <summary>
/// Adds two vectors and returns the result as a Vector structure.
/// </summary>
/// <param name="vector1">The first vector to add.</param>
/// <param name="vector2">The second vector to add.</param>
/// <returns>The sum of vector1 and vector2.</returns>
public static Vector3 Add(Vector3 vector1, Vector3 vector2)
{
vector1.X += vector2.X;
vector1.Y += vector2.Y;
vector1.Z += vector2.Z;
return vector1;
}
/// <summary>
/// Subtracts the specified vector from another specified vector.
/// </summary>
/// <param name="vector1">The vector from which vector2 is subtracted.</param>
/// <param name="vector2">The vector to subtract from vector1.</param>
/// <returns>The difference between vector1 and vector2.</returns>
public static Vector3 Subtract(Vector3 vector1, Vector3 vector2)
{
Vector3 vector;
vector.X = vector1.X - vector2.X;
vector.Y = vector1.Y - vector2.Y;
vector.Z = vector1.Z - vector2.Z;
return vector;
}
/// <summary>
/// Multiplies the specified scalar by the specified vector and returns the resulting vector.
/// </summary>
/// <param name="scalar">The scalar to multiply.</param>
/// <param name="vector">The vector to multiply.</param>
/// <returns>The result of multiplying scalar and vector.</returns>
public static Vector3 Multiply(double scalar, Vector3 vector)
{
vector.X *= scalar;
vector.Y *= scalar;
vector.Z *= scalar;
return vector;
}
/// <summary>
/// Divides the specified vector by the specified scalar and returns the result as a Vector.
/// </summary>
/// <param name="vector">The vector structure to divide.</param>
/// <param name="scalar">The amount by which vector is divided.</param>
/// <returns>The result of dividing vector by scalar.</returns>
public static Vector3 Divide(Vector3 vector, double scalar)
{
vector.X /= scalar;
vector.Y /= scalar;
vector.Z /= scalar;
return vector;
}
/// <summary>
/// Negates the values of X, Y, and Z on this vector.
/// </summary>
public void Negate()
{
X = -X;
Y = -Y;
Z = -Z;
}
/// <summary>
/// Compares two vectors for equality.
/// </summary>
/// <param name="value">The vector to compare with this vector.</param>
/// <returns>True if value has the same X and Y values as this vector; otherwise, false.</returns>
public bool Equals(Vector3 value)
{
return X == value.X && Y == value.Y && Z == value.Z;
}
/// <summary>
/// Compares the two specified vectors for equality.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>True if t he X and Y components of vector1 and vector2 are equal; otherwise, false.</returns>
public static bool Equals(Vector3 vector1, Vector3 vector2)
{
return vector1.Equals(vector2);
}
/// <summary>
/// Calculates the Dot Product of the specified vectors.
/// </summary>
/// <param name="vector1">The first vector to evaluate.</param>
/// <param name="vector2">The second vector to evaluate.</param>
/// <returns>The calculated Dot Product.</returns>
public static double DotProduct(Vector3 vector1, Vector3 vector2)
{
return (vector1.X * vector2.X) + (vector1.Y * vector2.Y) + (vector1.Z * vector2.Z);
}
/// <summary>
/// Calculates the Cross Product of the specified vectors
/// </summary>
/// <param name="vector1">The first vector to evaluate.</param>
/// <param name="vector2">The second vector to evaluate.</param>
/// <returns>The calculated Cross Product.</returns>
public static Vector3 CrossProduct(Vector3 vector1, Vector3 vector2)
{
Vector3 vector;
vector.X = (vector1.Y * vector2.Z) - (vector1.Z * vector2.Y);
vector.Y = (vector1.Z * vector2.X) - (vector1.X * vector2.Z);
vector.Z = (vector1.X * vector2.Y) - (vector1.Y * vector2.X);
return vector;
}
/// <summary>
/// Calculates the distance of the specified vectors in 3D space.
/// </summary>
/// <param name="vector1">The first vector to evaluate.</param>
/// <param name="vector2">The second vector to evaluate.</param>
/// <returns>The distance between vector1 and vector2.</returns>
public static double Distance(Vector3 vector1, Vector3 vector2)
{
return Math.Sqrt(
(vector1.X - vector2.X) * (vector1.X - vector2.X) +
(vector1.Y - vector2.Y) * (vector1.Y - vector2.Y) +
(vector1.Z - vector2.Z) * (vector1.Z - vector2.Z)
);
}
/// <summary>
/// Calculates the distance btween the current and the specified vector in the 3D space.
/// </summary>
/// <param name="other">The vector to evaluate.</param>
/// <returns>The distance between the vectors.</returns>
public double Distance(Vector3 other)
{
return Distance(this, other);
}
/// <summary>
/// Calculates the angle, expressed in degrees, between the two specified vectors.
/// </summary>
/// <param name="vector1">The first vector to evaluate.</param>
/// <param name="vector2">The second vector to evaluate.</param>
/// <returns>The angle, in degrees, between vector1 and vector2.</returns>
public static double Angle(Vector3 vector1, Vector3 vector2)
{
vector1.Normalize();
vector2.Normalize();
double cosinus = DotProduct(vector1, vector2);
double angle = (Math.Acos(cosinus) * (180.0 / Math.PI));
if (double.IsNaN(angle) || double.IsInfinity(angle))
{
return 0.0;
}
Vector3 normal = CrossProduct(vector1, vector2);
if (normal.Z < 0.0)
{
angle = 360.0 - angle;
}
return angle;
}
/// <summary>
/// Normalizes this vector (a normalized vector maintains its direction but its Length becomes 1).
/// </summary>
public void Normalize()
{
double length = Length;
if (length != 0)
{
double inv = 1 / length;
X *= inv;
Y *= inv;
Z *= inv;
}
}
/// <summary>
/// Calculates the interpolated vector of the specified vectors and the specified fraction.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <param name="fraction">The control fraction (a number between 0 and 1).</param>
/// <returns>The interpolation vector.</returns>
public static Vector3 Interpolate(Vector3 vector1, Vector3 vector2, double fraction)
{
if (fraction > 0 && fraction < 1)
{
Vector3 vector;
vector.X = vector1.X * (1 - fraction) + vector2.X * fraction;
vector.Y = vector1.Y * (1 - fraction) + vector2.Y * fraction;
vector.Z = vector1.Z * (1 - fraction) + vector2.Z * fraction;
return vector;
}
return Vector3.Zero;
}
/// <summary>
/// Calculates the interpolated vector of the current vector, the specified vector and the specified fraction.
/// </summary>
/// <param name="vector">The specified vector.</param>
/// <param name="fraction">The control fraction (a number between 0 and 1).</param>
/// <returns>The interpolation vector.</returns>
public Vector3 Interpolate(Vector3 vector, double fraction)
{
return Interpolate(this, vector, fraction);
}
/// <summary>
/// Compares two vectors and returns the one with the maximum length.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>The vector with the maximum length.</returns>
public static Vector3 Max(Vector3 vector1, Vector3 vector2)
{
if (vector1 >= vector2)
{
return vector1;
}
return vector2;
}
/// <summary>
/// Compares this vector with the the specified one and returns the one with the maximum length.
/// </summary>
/// <param name="value">The vector to compare.</param>
/// <returns>The vector with the maximum length.</returns>
public Vector3 Max(Vector3 value)
{
return Max(this, value);
}
/// <summary>
/// Compares two vectors and returns the one with the minimum length.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>The vector with the minimum length.</returns>
public static Vector3 Min(Vector3 vector1, Vector3 vector2)
{
if (vector1 <= vector2)
{
return vector1;
}
return vector2;
}
/// <summary>
/// Compares this vector with the the specified one and returns the one with the minimum length.
/// </summary>
/// <param name="value">The vector to compare.</param>
/// <returns>The vector with the minimum length.</returns>
public Vector3 Min(Vector3 value)
{
return Min(this, value);
}
/// <summary>
/// Rotates the specified vector around the X axis by the given degrees (Euler rotation around X).
/// </summary>
/// <param name="value">The vector to rotate.</param>
/// <param name="degree">The number of the degrees to rotate.</param>
/// <returns>The rotated vector.</returns>
public static Vector3 Pitch(Vector3 value, double degree)
{
Vector3 vector;
vector.X = value.X;
vector.Y = (value.Y * Math.Cos(degree)) - (value.Z * Math.Sin(degree));
vector.Z = (value.Y * Math.Sin(degree)) + (value.Z * Math.Cos(degree));
return vector;
}
/// <summary>
/// Rotates this vector around the X axis by the given degrees (Euler rotation around X).
/// </summary>
/// <param name="degree">The number of the degrees to rotate.</param>
public void Pitch(double degree)
{
this = Pitch(this, degree);
}
/// <summary>
/// Rotates the specified vector around the Y axis by the given degrees (Euler rotation around Y).
/// </summary>
/// <param name="value">The vector to rotate.</param>
/// <param name="degree">The number of the degrees to rotate.</param>
/// <returns>The rotated vector.</returns>
public static Vector3 Yaw(Vector3 value, double degree)
{
Vector3 vector;
vector.X = (value.Z * Math.Sin(degree)) + (value.X * Math.Cos(degree));
vector.Y = value.Y;
vector.Z = (value.Z * Math.Cos(degree)) - (value.X * Math.Sin(degree));
return vector;
}
/// <summary>
/// Rotates this vector around the Y axis by the given degrees (Euler rotation around Y).
/// </summary>
/// <param name="degree">The number of the degrees to rotate.</param>
public void Yaw(double degree)
{
this = Yaw(this, degree);
}
/// <summary>
/// Rotates the specified vector around the Z axis by the given degrees (Euler rotation around Z).
/// </summary>
/// <param name="value">The vector to rotate.</param>
/// <param name="degree">The number of the degrees to rotate.</param>
/// <returns>The rotated vector.</returns>
public static Vector3 Roll(Vector3 value, double degree)
{
Vector3 vector;
vector.X = (value.X * Math.Cos(degree)) - (value.Y * Math.Sin(degree));
vector.Y = (value.X * Math.Sin(degree)) + (value.Y * Math.Cos(degree));
vector.Z = value.Z;
return vector;
}
/// <summary>
/// Rotates this vector around the Z axis by the given degrees (Euler rotation around Z).
/// </summary>
/// <param name="degree">The number of the degrees to rotate.</param>
public void Roll(double degree)
{
this = Roll(this, degree);
}
/// <summary>
/// Compares the length of this vector with the length of the specified object.
/// </summary>
/// <param name="other">The object to compare.</param>
/// <returns>A positive number if the length of this vector is greater than the other's. A negative number if it's smaller. Zero otherwise.</returns>
public int CompareTo(object other)
{
return this.CompareTo((Vector3)other);
}
/// <summary>
/// Compares the length of this vector with the length of the specified one.
/// </summary>
/// <param name="other">The vector to compare.</param>
/// <returns>A positive number if the length of this vector is greater than the other's. A negative number if it's smaller. Zero otherwise.</returns>
public int CompareTo(Vector3 other)
{
if (this < other)
{
return -1;
}
else if (this > other)
{
return 1;
}
return 0;
}
#endregion
#region Overrides
/// <summary>
/// Compares two vectors for equality.
/// </summary>
/// <param name="obj">The cast vector to compare with this vector.</param>
/// <returns>True if value has the same X and Y values as this vector; otherwise, false.</returns>
public override bool Equals(object obj)
{
if (obj is Vector3)
{
return this.Equals((Vector3)obj);
}
return false;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code for this instance.</returns>
public override int GetHashCode()
{
// Perform field-by-field XOR of HashCodes
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
/// <summary>
/// Creates a string representation of this vector based on the current culture.
/// </summary>
/// <returns>A string representation of this vector.</returns>
public override string ToString()
{
return string.Format("X: {0}, Y: {1}, Z: {2}", X, Y, Z);
}
#endregion
#region Operator overloading
/// <summary>
/// Adds two vectors and returns the result as a vector.
/// </summary>
/// <param name="vector1">The first vector to add.</param>
/// <param name="vector2">The second vector to add.</param>
/// <returns>The sum of vector1 and vector2.</returns>
public static Vector3 operator +(Vector3 vector1, Vector3 vector2)
{
return Add(vector1, vector2);
}
/// <summary>
/// Subtracts one specified vector from another.
/// </summary>
/// <param name="vector1">The vector from which vector2 is subtracted.</param>
/// <param name="vector2">The vector to subtract from vector1.</param>
/// <returns>The difference between vector1 and vector2.</returns>
public static Vector3 operator -(Vector3 vector1, Vector3 vector2)
{
return Subtract(vector1, vector2);
}
/// <summary>
/// Operator -Vector (unary negation).
/// </summary>
/// <param name="vector">Vector being negated.</param>
/// <returns>Negation of the given vector.</returns>
public static Vector3 operator -(Vector3 vector)
{
return new Vector3(-vector.X, -vector.Y, -vector.Z);
}
/// <summary>
/// Multiplies the specified scalar by the specified vector and returns the resulting vector.
/// </summary>
/// <param name="scalar">The scalar to multiply.</param>
/// <param name="vector">The vector to multiply.</param>
/// <returns>The result of multiplying scalar and vector.</returns>
public static Vector3 operator *(double scalar, Vector3 vector)
{
return Multiply(scalar, vector);
}
/// <summary>
/// Divides the specified vector by the specified scalar and returns the resulting vector.
/// </summary>
/// <param name="vector">The vector to divide.</param>
/// <param name="scalar">The scalar by which vector will be divided.</param>
/// <returns>The result of dividing vector by scalar.</returns>
public static Vector3 operator /(Vector3 vector, double scalar)
{
return Divide(vector, scalar);
}
/// <summary>
/// Compares two vectors for equality.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>True if the X and Y components of vector1 and vector2 are equal; otherwise, false.</returns>
public static bool operator ==(Vector3 vector1, Vector3 vector2)
{
return vector1.Equals(vector2);
}
/// <summary>
/// Compares two vectors for inequality.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>True if the X and Y components of vector1 and vector2 are different; otherwise, false.</returns>
public static bool operator !=(Vector3 vector1, Vector3 vector2)
{
return !vector1.Equals(vector2);
}
/// <summary>
/// Compares the lengths of two vectors.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>True if the length of vector1 is smaller than the length of vector2; otherwise, false.</returns>
public static bool operator <(Vector3 vector1, Vector3 vector2)
{
return vector1.Length < vector2.Length;
}
/// <summary>
/// Compares the lengths of two vectors.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>True if the length of vector1 is smaller or equal than the length of vector2; otherwise, false.</returns>
public static bool operator <=(Vector3 vector1, Vector3 vector2)
{
return vector1.Length <= vector2.Length;
}
/// <summary>
/// Compares the lengths of two vectors.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>True if the length of vector1 is greater than the length of vector2; otherwise, false</returns>
public static bool operator >(Vector3 vector1, Vector3 vector2)
{
return vector1.Length > vector2.Length;
}
/// <summary>
/// Compares the lengths of two vectors.
/// </summary>
/// <param name="vector1">The first vector to compare.</param>
/// <param name="vector2">The second vector to compare.</param>
/// <returns>True if the length of vector1 is greater or equal than the length of vector2; otherwise, false</returns>
public static bool operator >=(Vector3 vector1, Vector3 vector2)
{
return vector1.Length >= vector2.Length;
}
#endregion
}
}
| 37.184638 | 157 | 0.566457 | [
"Apache-2.0"
] | LightBuzz/Vitruvius | Kinect v2/WinRT/LightBuzz.Vitruvius/Core/Vector3.cs | 25,176 | C# |
// Decompiled with JetBrains decompiler
// Type: BlueStacks.Common.ExtendedWebClient
// Assembly: HD-Common, Version=4.250.0.1070, Culture=neutral, PublicKeyToken=null
// MVID: 7033AB66-5028-4A08-B35C-D9B2B424A68A
// Assembly location: C:\Program Files\BlueStacks\HD-Common.dll
using System;
using System.Net;
namespace BlueStacks.Common
{
public class ExtendedWebClient : WebClient
{
private int mTimeout;
public ExtendedWebClient(int timeout)
{
this.mTimeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest webRequest = base.GetWebRequest(address);
webRequest.Timeout = this.mTimeout;
return webRequest;
}
}
}
| 24.482759 | 82 | 0.726761 | [
"MIT"
] | YehudaEi/Bluestacks-source-code | src/HD-Common/BlueStacks/Common/ExtendedWebClient.cs | 712 | C# |
using System;
using System.Drawing;
using System.Linq;
using System.Text;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Drawing.Layout;
using PdfSharp.Pdf;
using PDFSharpTest.Console.Models;
using TheArtOfDev.HtmlRenderer.PdfSharp;
namespace PDFSharpTest.Console
{
class Program
{
/// <summary>
/// Page width value that PDFSharp uses by default.
/// Test decoration calculates dimensions using PDFSharp defaults as well.
/// TODO: Abstract away
/// </summary>
const float pageW = 595f;
/// <summary>
/// Page height value that PDFSharp uses by default.
/// Test decoration calculates dimensions using PDFSharp defaults as well.
/// TODO: Abstract away
/// </summary>
const float pageH = 842f;
static void Main(string[] args)
{
foo2();
}
private static void foo1()
{
var debug = true;
// Get the test
var test = GetATestModel();
// Validate: There are pages to print
if (test.TestPages == null || test.TestPages.Count == 0) return;
// Shorthand notation for test decoration
var d = test.TestDecoration;
// Calculate middle margin
var middleMargin = (pageW - test.TestPages[0].TestColumns.Count * d.ColumnW - 2 * d.SideMargin) / (test.TestPages[0].TestColumns.Count - 1);
// Validate: Middle margin is not negative
if (middleMargin < 0) return;
// Validate: Bottom margin is not negative
if (pageH - d.TopMargin - d.ColumnH < 0) return;
// Text properties
var questionOrderFont = new XFont(d.FontFamily, d.QuestionNumberFontSize, XFontStyle.Regular);
var questionOrderColor = XBrushes.MediumPurple;
var font = new XFont(d.FontFamily, d.FontSize, XFontStyle.Regular);
var textColor = XBrushes.Black;
// Register encoding provider. This is necessary for the PDFSharp to work properly.
// Reference: https://youtu.be/C-yMypr_TdY
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
// Create doc
var document = new PdfDocument();
// For each page
test.TestPages.ForEach(testPage =>
{
// Add page
var page = document.AddPage();
// Define necessary stuff
var graphics = XGraphics.FromPdfPage(page);
var textFormatter = new XTextFormatter(graphics);
// Draw top margin
if (debug)
graphics.DrawRectangle(XPens.Blue,
0,
0,
page.Width,
d.TopMargin);
// Draw bottom margin
if (debug)
graphics.DrawRectangle(XPens.Blue,
0,
d.TopMargin + d.ColumnH,
page.Width,
page.Height - (d.TopMargin + d.ColumnH));
// Calculate X coordinates of columns
var columnXs = testPage.TestColumns
.Select((tc, index) => d.BiasedMarginLeft + d.SideMargin + index * (d.ColumnW + middleMargin))
.ToList();
// Draw columns
if (debug)
columnXs.ForEach(columnX =>
{
graphics.DrawRectangle(XPens.Orange,
columnX,
d.TopMargin,
d.ColumnW,
d.ColumnH);
});
// Draw middle line
graphics.DrawLine(XPens.Black,
pageW / 2,
d.TopMargin,
pageW / 2,
d.TopMargin + d.ColumnH);
// For each column
for (int i = 0; i < testPage.TestColumns.Count; i++)
{
for (int j = 0; j < testPage.TestColumns[i].McQuestions.Count; j++)
{
// Type question order
var questionOrderRect = new XRect(
columnXs[i],
d.TopMargin + j * 200,
d.QuestionOrderAreaWidth,
200);
textFormatter.DrawString($"{j + 1}{d.QuestionNumberAppendix}", questionOrderFont, questionOrderColor, questionOrderRect, XStringFormats.TopLeft);
// Type question prompt
var questionPromptRect = new XRect(
columnXs[i] + d.QuestionOrderAreaWidth,
d.TopMargin + j * 200,
d.ColumnW - d.QuestionOrderAreaWidth,
100);
textFormatter.DrawString(testPage.TestColumns[i].McQuestions[j].Prompt, font, textColor, questionPromptRect, XStringFormats.TopLeft);
for (int k = 0; k < testPage.TestColumns[i].McQuestions[j].QuestionOptions.Count; k++)
{
// Type question option prompt
var optionPromptRect = new XRect(
columnXs[i] + d.QuestionOrderAreaWidth,
d.TopMargin + j * 200 + 100 + k * 20,
d.ColumnW - d.QuestionOrderAreaWidth,
20);
var optionText = $"{OptionPretext(d.OptionStyle, k)}{d.OptionAppendix} {testPage.TestColumns[i].McQuestions[j].QuestionOptions[k].Prompt}";
textFormatter.DrawString(optionText, font, textColor, optionPromptRect, XStringFormats.TopLeft);
}
}
//var imagePath = "image.png";
//graphics.DrawImage(XImage.FromFile(imagePath), columnXs[i] + 1, d.TopMargin + 100, d.ColumnW - 2, d.ColumnW - 2);
}
});
// Save PDF
document.Save("HelloWorld.pdf");
}
private static void foo2()
{
//Bitmap bitmap = new Bitmap(1200, 1800);
//Graphics g = Graphics.FromImage(bitmap);
//HtmlRenderer.HtmlContainer c = new HtmlRenderer.HtmlContainer();
//c.SetHtml("<html><body style='font-size:20px'>Whatever</body></html>");
//c.PerformPaint(g);
//PdfDocument doc = new PdfDocument();
//PdfPage page = new PdfPage();
//XImage img = XImage.FromGdiPlusImage(bitmap);
//doc.Pages.Add(page);
//XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
//xgr.DrawImage(img, 0, 0);
//doc.Save(@"C:\test.pdf");
//doc.Close();
//var doc = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf("<html><body style='font-size:20px'>Whatever</body></html>", PageSize.A4);
//PdfPage page = new PdfPage();
////XImage img = XImage.FromGdiPlusImage(bitmap);
//doc.Pages.Add(page);
////XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
////xgr.DrawImage(img, 0, 0);
//doc.Save("test.pdf");
//doc.Close();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
string htmlString = System.IO.File.ReadAllText(@"D:\CodeWorkspace\C# projects\Sandbox and tutorials\PDFSharpTest\PDFSharpTest.Console\test_design.html");
//string htmlString = "<h1>Document</h1> <p>This is an HTML document which is converted to a pdf file.</p>";
PdfDocument pdfDocument = PdfGenerator.GeneratePdf(htmlString, PageSize.A4);
pdfDocument.Save("HTMLtoPDFDocument.pdf");
}
private static TestModel GetATestModel()
{
return new TestModel
{
Name = "Test 1",
TestDecoration = new TestDecorationModel
{
Name = "Awesome Decorations",
ColumnNumber = 2,
TopMargin = 100,
SideMargin = 40,
ColumnW = 235,
ColumnH = 680,
QuestionOrderAreaWidth = 20,
BiasedMarginLeft = 0,
MinWhiteSpaceBetweenQuestions = 25,
LeaveSpaceToColumnEnd = false,
FontFamily = "Verdana",
FontSize = 13,
QuestionNumberFontSize = 13,
QuestionNumberColor = "000000",
QuestionNumberAppendix = ".",
OptionStyle = OptionStyle.RomanNumerals,
OptionAppendix = ")",
},
TestPages = Enumerable.Range(0, 3).Select(_ => new TestPageModel
{
TestColumns = Enumerable.Range(0, 2).Select(_ => new TestColumnModel
{
McQuestions = Enumerable.Range(0, 2).Select(_ => new McQuestionModel
{
Prompt = "Alice is a very smart girl. One day, Alice wanted to eat apples but she didn't have any apples. She decided to buy some apples. Alice looked for an apple shop.",
Height = 0,
NumberOfOptions = 5,
CorrectOption = 0,
OptionsPerRow = 5,
QuestionOptions = Enumerable.Range(0, 4).Select(optionOrder => new QuestionOptionModel
{
Prompt = $"Option {optionOrder + 1}",
}).ToList()
}).ToList(),
}).ToList(),
}).ToList(),
};
}
private static string OptionPretext(OptionStyle style, int optionIndex)
{
return style switch
{
OptionStyle.UppercaseLetters => optionIndex switch
{
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
5 => "F",
6 => "G",
7 => "H",
8 => "I",
9 => "J",
_ => throw new ArgumentOutOfRangeException(nameof(optionIndex), optionIndex, null),
},
OptionStyle.LowercaseLetters => optionIndex switch
{
0 => "a",
1 => "b",
2 => "c",
3 => "d",
4 => "e",
5 => "f",
6 => "g",
7 => "h",
8 => "i",
9 => "j",
_ => throw new ArgumentOutOfRangeException(nameof(optionIndex), optionIndex, null),
},
OptionStyle.NumbersFrom1 => (optionIndex + 1).ToString(),
OptionStyle.RomanNumerals => optionIndex switch
{
0 => "I",
1 => "II",
2 => "III",
3 => "IV",
4 => "V",
5 => "VI",
6 => "VII",
7 => "VIII",
8 => "IX",
9 => "X",
_ => throw new ArgumentOutOfRangeException(nameof(optionIndex), optionIndex, null),
},
OptionStyle.TrueFalse => optionIndex % 2 == 0 ? "True" : "False",
OptionStyle.CheckBox => "☐",
_ => throw new ArgumentOutOfRangeException(nameof(style), style, null)
};
}
}
}
| 40.794613 | 199 | 0.466656 | [
"MIT"
] | m-azyoksul/PDFSharpTest | PDFSharpTest.Console/Program.cs | 12,120 | C# |
//-----------------------------------------------------------------------
// <copyright file="DaemonMsgCreateSerializerSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Linq.Expressions;
using Akka.Actor;
using Akka.Configuration;
using Akka.Remote.Serialization;
using Akka.Routing;
using Akka.TestKit;
using Xunit;
namespace Akka.Remote.Tests.Serialization
{
public class DaemonMsgCreateSerializerSpec : AkkaSpec
{
class MyActor : UntypedActor
{
protected override void OnReceive(object message)
{
}
}
private readonly Akka.Serialization.Serialization _ser;
private readonly IActorRef _supervisor;
public DaemonMsgCreateSerializerSpec()
: base(@"
akka.actor.provider = remote
akka.remote.dot-netty.tcp {
hostname = 127.0.0.1
port = 0
}
")
{
_ser = Sys.Serialization;
_supervisor = Sys.ActorOf(Props.Create<MyActor>(), "supervisor");
}
[Fact]
public void Serialization_must_resolve_DaemonMsgCreateSerializer()
{
_ser.FindSerializerForType(typeof(DaemonMsgCreate)).GetType().ShouldBe(typeof(DaemonMsgCreateSerializer));
}
[Fact]
public void Serialization_must_serialize_and_deserialize_DaemonMsgCreate_with_FromClassCreator()
{
VerifySerialization(new DaemonMsgCreate(Props.Create<MyActor>(), new Deploy(), "foo", _supervisor));
}
[Fact]
public void Serialization_must_serialize_and_deserialize_DaemonMsgCreate_with_function_creator()
{
VerifySerialization(new DaemonMsgCreate(Props.Create(() => new MyActor()), new Deploy(), "foo", _supervisor));
}
[Fact]
public void Serialization_must_serialize_and_deserialize_DaemonMsgCreate_with_Deploy_and_RouterConfig()
{
var decider = Decider.From(
Directive.Escalate);
var supervisorStrategy = new OneForOneStrategy(3, TimeSpan.FromSeconds(10), decider);
var deploy1 = new Deploy("path1",
ConfigurationFactory.ParseString("a=1"),
new RoundRobinPool(5, null, supervisorStrategy, null),
new RemoteScope(new Address("akka", "Test", "host1", 1921)),
"mydispatcher");
var deploy2 = new Deploy("path2",
ConfigurationFactory.ParseString("a=2"),
FromConfig.Instance,
new RemoteScope(new Address("akka", "Test", "host2", 1922)),
Deploy.NoDispatcherGiven);
VerifySerialization(new DaemonMsgCreate(Props.Create<MyActor>().WithDispatcher("my-disp").WithDeploy(deploy1), deploy2, "foo", _supervisor));
}
#region Helper methods
private void VerifySerialization(DaemonMsgCreate msg)
{
var daemonMsgSerializer = _ser.FindSerializerFor(msg);
var binary = daemonMsgSerializer.ToBinary(msg);
var actual = (DaemonMsgCreate) _ser.Deserialize(binary, daemonMsgSerializer.Identifier, typeof (DaemonMsgCreate));
AssertDaemonMsgCreate(msg, actual);
}
private void AssertDaemonMsgCreate(DaemonMsgCreate expected, DaemonMsgCreate actual)
{
Assert.Equal(expected.Props.GetType(), actual.Props.GetType());
Assert.Equal(expected.Props.Arguments.Length, actual.Props.Arguments.Length);
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
actual.Props.Arguments.Zip(expected.Props.Arguments, (g, e) =>
{
if (e is Expression)
{
}
else
{
Assert.Equal(g, e);
}
return g;
});
Assert.Equal(expected.Props.Deploy,actual.Props.Deploy);
Assert.Equal(expected.Deploy, actual.Deploy);
Assert.Equal(expected.Path, actual.Path);
Assert.Equal(expected.Supervisor, actual.Supervisor);
}
#endregion
}
}
| 37.066116 | 153 | 0.591304 | [
"Apache-2.0"
] | Bogdan-Rotund/akka.net | src/core/Akka.Remote.Tests/Serialization/DaemonMsgCreateSerializerSpec.cs | 4,487 | 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 CN.MACH.AI.UI.Controls.WPF.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;
}
}
}
}
| 35.645161 | 151 | 0.570136 | [
"Apache-2.0"
] | xinghe3/DataTracer | CN.MACH.AI.UI.Controls.WPF/Properties/Settings.Designer.cs | 1,107 | C# |
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Definitions.Italian;
using Microsoft.Recognizers.Text.DateTime.Utilities;
namespace Microsoft.Recognizers.Text.DateTime.Italian
{
public class ItalianDateParserConfiguration : BaseDateTimeOptionsConfiguration, IDateParserConfiguration
{
private const RegexOptions RegexFlags = RegexOptions.Singleline | RegexOptions.ExplicitCapture;
public ItalianDateParserConfiguration(ICommonDateTimeParserConfiguration config)
: base(config)
{
DateTokenPrefix = DateTimeDefinitions.DateTokenPrefix;
IntegerExtractor = config.IntegerExtractor;
OrdinalExtractor = config.OrdinalExtractor;
CardinalExtractor = config.CardinalExtractor;
NumberParser = config.NumberParser;
DurationExtractor = config.DurationExtractor;
DateExtractor = config.DateExtractor;
DurationParser = config.DurationParser;
DateRegexes = new ItalianDateExtractorConfiguration(this).DateRegexList;
OnRegex = ItalianDateExtractorConfiguration.OnRegex;
SpecialDayRegex = ItalianDateExtractorConfiguration.SpecialDayRegex;
SpecialDayWithNumRegex = ItalianDateExtractorConfiguration.SpecialDayWithNumRegex;
NextRegex = ItalianDateExtractorConfiguration.NextDateRegex;
ThisRegex = ItalianDateExtractorConfiguration.ThisRegex;
LastRegex = ItalianDateExtractorConfiguration.LastDateRegex;
UnitRegex = ItalianDateExtractorConfiguration.DateUnitRegex;
WeekDayRegex = ItalianDateExtractorConfiguration.WeekDayRegex;
StrictWeekDay = ItalianDateExtractorConfiguration.StrictWeekDay;
MonthRegex = ItalianDateExtractorConfiguration.MonthRegex;
WeekDayOfMonthRegex = ItalianDateExtractorConfiguration.WeekDayOfMonthRegex;
ForTheRegex = ItalianDateExtractorConfiguration.ForTheRegex;
WeekDayAndDayOfMothRegex = ItalianDateExtractorConfiguration.WeekDayAndDayOfMothRegex;
WeekDayAndDayRegex = ItalianDateExtractorConfiguration.WeekDayAndDayRegex;
RelativeMonthRegex = ItalianDateExtractorConfiguration.RelativeMonthRegex;
StrictRelativeRegex = ItalianDateExtractorConfiguration.StrictRelativeRegex;
YearSuffix = ItalianDateExtractorConfiguration.YearSuffix;
RelativeWeekDayRegex = ItalianDateExtractorConfiguration.RelativeWeekDayRegex;
BeforeAfterRegex = ItalianDateExtractorConfiguration.BeforeAfterRegex;
// @TODO move to config
RelativeDayRegex = new Regex(DateTimeDefinitions.RelativeDayRegex, RegexFlags);
NextPrefixRegex = new Regex(DateTimeDefinitions.NextPrefixRegex, RegexFlags);
PreviousPrefixRegex = new Regex(DateTimeDefinitions.PreviousPrefixRegex, RegexFlags);
UpcomingPrefixRegex = new Regex(DateTimeDefinitions.UpcomingPrefixRegex, RegexFlags);
PastPrefixRegex = new Regex(DateTimeDefinitions.PastPrefixRegex, RegexFlags);
DayOfMonth = config.DayOfMonth;
DayOfWeek = config.DayOfWeek;
MonthOfYear = config.MonthOfYear;
Numbers = config.Numbers;
CardinalMap = config.CardinalMap;
UnitMap = config.UnitMap;
UtilityConfiguration = config.UtilityConfiguration;
SameDayTerms = DateTimeDefinitions.SameDayTerms.ToImmutableList();
PlusOneDayTerms = DateTimeDefinitions.PlusOneDayTerms.ToImmutableList();
PlusTwoDayTerms = DateTimeDefinitions.PlusTwoDayTerms.ToImmutableList();
MinusOneDayTerms = DateTimeDefinitions.MinusOneDayTerms.ToImmutableList();
MinusTwoDayTerms = DateTimeDefinitions.MinusTwoDayTerms.ToImmutableList();
}
public string DateTokenPrefix { get; }
public IExtractor IntegerExtractor { get; }
public IExtractor OrdinalExtractor { get; }
public IExtractor CardinalExtractor { get; }
public IParser NumberParser { get; }
public IDateTimeExtractor DurationExtractor { get; }
public IDateExtractor DateExtractor { get; }
public IDateTimeParser DurationParser { get; }
public IImmutableDictionary<string, string> UnitMap { get; }
public IEnumerable<Regex> DateRegexes { get; }
public Regex OnRegex { get; }
public Regex SpecialDayRegex { get; }
public Regex SpecialDayWithNumRegex { get; }
public Regex NextRegex { get; }
public Regex ThisRegex { get; }
public Regex LastRegex { get; }
public Regex UnitRegex { get; }
public Regex WeekDayRegex { get; }
public Regex StrictWeekDay { get; }
public Regex MonthRegex { get; }
public Regex WeekDayOfMonthRegex { get; }
public Regex ForTheRegex { get; }
public Regex WeekDayAndDayOfMothRegex { get; }
public Regex WeekDayAndDayRegex { get; }
public Regex RelativeMonthRegex { get; }
public Regex StrictRelativeRegex { get; }
public Regex YearSuffix { get; }
public Regex RelativeWeekDayRegex { get; }
public Regex RelativeDayRegex { get; }
public Regex NextPrefixRegex { get; }
public Regex PreviousPrefixRegex { get; }
public Regex UpcomingPrefixRegex { get; }
public Regex PastPrefixRegex { get; }
public Regex BeforeAfterRegex { get; }
public IImmutableDictionary<string, int> DayOfMonth { get; }
public IImmutableDictionary<string, int> DayOfWeek { get; }
public IImmutableDictionary<string, int> MonthOfYear { get; }
public IImmutableDictionary<string, int> Numbers { get; }
public IImmutableDictionary<string, int> CardinalMap { get; }
public IImmutableList<string> SameDayTerms { get; }
public IImmutableList<string> PlusOneDayTerms { get; }
public IImmutableList<string> MinusOneDayTerms { get; }
public IImmutableList<string> PlusTwoDayTerms { get; }
public IImmutableList<string> MinusTwoDayTerms { get; }
bool IDateParserConfiguration.CheckBothBeforeAfter => DateTimeDefinitions.CheckBothBeforeAfter;
public IDateTimeUtilityConfiguration UtilityConfiguration { get; }
public int GetSwiftMonthOrYear(string text)
{
var trimmedText = text.Trim();
var swift = 0;
if (NextPrefixRegex.IsMatch(trimmedText))
{
swift = 1;
}
if (PreviousPrefixRegex.IsMatch(trimmedText))
{
swift = -1;
}
return swift;
}
public bool IsCardinalLast(string text)
{
var trimmedText = text.Trim();
return PreviousPrefixRegex.IsMatch(trimmedText);
}
public string Normalize(string text)
{
return text;
}
}
}
| 37.436842 | 108 | 0.68649 | [
"MIT"
] | Tao2301230/Recognizers-Text | .NET/Microsoft.Recognizers.Text.DateTime/Italian/Parsers/ItalianDateParserConfiguration.cs | 7,115 | C# |
using System.Resources;
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("Krypton Outlook Grid")]
[assembly: AssemblyDescription("KryptonDataGridView with multi sorting and multi grouping abilities")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("JDH Software, Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV)")]
[assembly: AssemblyProduct("Krypton Outlook Grid")]
[assembly: AssemblyCopyright("Copyright © JDH Software 2013-2018 - 2020. Then modifications by Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV) 2018 - 2020. 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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2a10c696-45ad-48aa-8ead-2cb322672972")]
// 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("5.470.725.0")]
[assembly: AssemblyFileVersion("5.470.725.0")]
[assembly: NeutralResourcesLanguage("en-GB")]
| 44.1 | 189 | 0.757937 | [
"BSD-3-Clause"
] | Smurf-IV/Krypton-Toolkit-Suite-Extended-NET-4.7 | Source/Krypton Toolkit Suite Extended/Componentisation/Krypton Outlook Grid/Properties/AssemblyInfo.cs | 1,767 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SerialPortW
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//启用可视样式
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//显示窗口
Application.Run(new SerialPortW());
}
}
}
| 20.73913 | 65 | 0.551363 | [
"Apache-2.0"
] | TonySudo/SerialPort_Performance | SerialPortW/Program.cs | 519 | C# |
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace FScruiser.XF.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyNavigationView : NavigationPage
{
public MyNavigationView()
{
InitializeComponent();
}
}
} | 21.071429 | 58 | 0.664407 | [
"CC0-1.0"
] | FMSC-Measurements/NatCruise | src/FScruiser.Xamarin/Views/MyNavigationView.xaml.cs | 297 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.