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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using Edge.Tokens;
using System;
using System.Collections.Generic;
namespace Edge.Tests
{
public class MockEdgeLexer : ILexer
{
private IEnumerable<IToken> tokens;
public MockEdgeLexer()
{
}
public MockEdgeLexer(IEnumerable<IToken> tokens)
{
this.tokens = tokens;
}
public IEnumerable<IToken> Tokenize(string text)
{
return tokens;
}
public IEnumerable<IToken> Tokens
{
get
{
return tokens;
}
set
{
tokens = value;
}
}
}
}
| 16.116279 | 56 | 0.463203 | [
"Apache-2.0"
] | sys27/Edge | Edge.Tests/MockEdgeLexer.cs | 695 | C# |
using System;
using System.Collections.Generic;
namespace UniRx.Operators
{
// needs to more improvement
internal class ConcatObservable<T> : OperatorObservableBase<T>
{
readonly IEnumerable<IObservable<T>> sources;
public ConcatObservable(IEnumerable<IObservable<T>> sources)
: base(true)
{
this.sources = sources;
}
public IObservable<T> Combine(IEnumerable<IObservable<T>> combineSources)
{
return new ConcatObservable<T>(CombineSources(this.sources, combineSources));
}
static IEnumerable<IObservable<T>> CombineSources(IEnumerable<IObservable<T>> first, IEnumerable<IObservable<T>> second)
{
foreach (IObservable<T> item in first)
{
yield return item;
}
foreach (IObservable<T> item in second)
{
yield return item;
}
}
protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel)
{
return new Concat(this, observer, cancel).Run();
}
class Concat : OperatorObserverBase<T, T>
{
readonly ConcatObservable<T> parent;
readonly object gate = new object();
bool isDisposed;
IEnumerator<IObservable<T>> e;
SerialDisposable subscription;
Action nextSelf;
public Concat(ConcatObservable<T> parent, IObserver<T> observer, IDisposable cancel)
: base(observer, cancel)
{
this.parent = parent;
}
public IDisposable Run()
{
isDisposed = false;
e = parent.sources.GetEnumerator();
subscription = new SerialDisposable();
IDisposable schedule = Scheduler.DefaultSchedulers.TailRecursion.Schedule(RecursiveRun);
return StableCompositeDisposable.Create(schedule, subscription, Disposable.Create(() =>
{
lock (gate)
{
this.isDisposed = true;
this.e.Dispose();
}
}));
}
void RecursiveRun(Action self)
{
lock (gate)
{
this.nextSelf = self;
if (isDisposed) return;
IObservable<T> current = default(IObservable<T>);
bool hasNext = false;
Exception ex = default(Exception);
try
{
hasNext = e.MoveNext();
if (hasNext)
{
current = e.Current;
if (current == null) throw new InvalidOperationException("sequence is null.");
}
else
{
e.Dispose();
}
}
catch (Exception exception)
{
ex = exception;
e.Dispose();
}
if (ex != null)
{
try { observer.OnError(ex); }
finally { Dispose(); }
return;
}
if (!hasNext)
{
try { observer.OnCompleted(); }
finally { Dispose(); }
return;
}
IObservable<T> source = current;
SingleAssignmentDisposable d = new SingleAssignmentDisposable();
subscription.Disposable = d;
d.Disposable = source.Subscribe(this);
}
}
public override void OnNext(T value)
{
base.observer.OnNext(value);
}
public override void OnError(Exception error)
{
try { observer.OnError(error); }
finally { Dispose(); }
}
public override void OnCompleted()
{
this.nextSelf();
}
}
}
}
| 30.839161 | 128 | 0.442177 | [
"MIT"
] | dotmos/uGameFramework | Unity/Assets/GameFramework/Modules/UniRx/Scripts/Operators/Concat.cs | 4,412 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using gis_final.Models;
namespace gis_final.Controllers
{
public class TagsController : Controller
{
private readonly YasharDbContext _context;
public TagsController(YasharDbContext context)
{
_context = context;
}
// GET: Tags
public async Task<IActionResult> Index()
{
return View(await _context.Tags.ToListAsync());
}
// GET: Tags/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var tag = await _context.Tags
.FirstOrDefaultAsync(m => m.Id == id);
if (tag == null)
{
return NotFound();
}
return View(tag);
}
// GET: Tags/Create
public IActionResult Create()
{
return View();
}
// POST: Tags/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Title,Id")] Tag tag)
{
if (ModelState.IsValid)
{
_context.Add(tag);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(tag);
}
// GET: Tags/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var tag = await _context.Tags.FindAsync(id);
if (tag == null)
{
return NotFound();
}
return View(tag);
}
// POST: Tags/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Title,Id")] Tag tag)
{
if (id != tag.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(tag);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TagExists(tag.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(tag);
}
// GET: Tags/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var tag = await _context.Tags
.FirstOrDefaultAsync(m => m.Id == id);
if (tag == null)
{
return NotFound();
}
return View(tag);
}
// POST: Tags/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var tag = await _context.Tags.FindAsync(id);
_context.Tags.Remove(tag);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool TagExists(int id)
{
return _context.Tags.Any(e => e.Id == id);
}
}
}
| 27.137255 | 104 | 0.478565 | [
"MIT"
] | YAVATAN-Official/oop_final | gis_final/Controllers/TagsController.cs | 4,154 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using YamlDotNet;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.RepresentationModel;
namespace HalfShot.MagnetHS.DataTransformer
{
public class YAMLDataTransformer : IDataTransformer
{
public string ConvertToString(object obj)
{
var serializer = new SerializerBuilder().Build();
return serializer.Serialize(obj);
}
public T FromStream<T>(TextReader stream)
{
var deserializer = new Deserializer();
return deserializer.Deserialize<T>(stream);
}
public T FromString<T>(string data)
{
var deserializer = new Deserializer();
return deserializer.Deserialize<T>(data);
}
public byte[] ToBytes(object obj)
{
return Encoding.UTF8.GetBytes(ConvertToString(obj));
}
public Stream ToStream(object obj)
{
var serializer = new SerializerBuilder().Build();
var memoryStream = new MemoryStream();
var writer = new StreamWriter(memoryStream);
serializer.Serialize(writer, obj);
writer.Flush();
return memoryStream;
}
}
}
| 27.270833 | 64 | 0.614209 | [
"MIT"
] | Half-Shot/MagnetHS | HalfShot.MagnetHS/DataTransformer/YAMLDataTransformer.cs | 1,311 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Java.Interop.Tools.Cecil;
using Java.Interop.Tools.Diagnostics;
using Java.Interop.Tools.TypeNameMappings;
namespace Java.Interop.Tools.JavaCallableWrappers
{
public class JavaTypeScanner
{
public Action<TraceLevel, string> Logger { get; private set; }
public bool ErrorOnCustomJavaObject { get; set; }
readonly TypeDefinitionCache cache;
[Obsolete ("Use the TypeDefinitionCache overload for better performance.")]
public JavaTypeScanner (Action<TraceLevel, string> logger)
: this (logger, cache: null)
{ }
public JavaTypeScanner (Action<TraceLevel, string> logger, TypeDefinitionCache cache)
{
if (logger == null)
throw new ArgumentNullException (nameof (logger));
Logger = logger;
this.cache = cache ?? new TypeDefinitionCache ();
}
public List<TypeDefinition> GetJavaTypes (IEnumerable<string> assemblies, IAssemblyResolver resolver)
{
var javaTypes = new List<TypeDefinition> ();
foreach (var assembly in assemblies) {
var assm = resolver.GetAssembly (assembly);
foreach (ModuleDefinition md in assm.Modules) {
foreach (TypeDefinition td in md.Types) {
AddJavaTypes (javaTypes, td);
}
}
}
return javaTypes;
}
void AddJavaTypes (List<TypeDefinition> javaTypes, TypeDefinition type)
{
if (type.IsSubclassOf ("Java.Lang.Object", cache) || type.IsSubclassOf ("Java.Lang.Throwable", cache)) {
// For subclasses of e.g. Android.App.Activity.
javaTypes.Add (type);
} else if (type.IsClass && !type.IsSubclassOf ("System.Exception", cache) && type.ImplementsInterface ("Android.Runtime.IJavaObject", cache)) {
var level = ErrorOnCustomJavaObject ? TraceLevel.Error : TraceLevel.Warning;
var prefix = ErrorOnCustomJavaObject ? "error" : "warning";
Logger (
level,
$"{prefix} XA4212: Type `{type.FullName}` implements `Android.Runtime.IJavaObject` but does not inherit `Java.Lang.Object` or `Java.Lang.Throwable`. This is not supported.");
return;
}
if (!type.HasNestedTypes)
return;
foreach (TypeDefinition nested in type.NestedTypes)
AddJavaTypes (javaTypes, nested);
}
[Obsolete ("Use the TypeDefinitionCache overload for better performance.")]
public static bool ShouldSkipJavaCallableWrapperGeneration (TypeDefinition type) =>
ShouldSkipJavaCallableWrapperGeneration (type, cache: null);
public static bool ShouldSkipJavaCallableWrapperGeneration (TypeDefinition type, TypeDefinitionCache cache)
{
if (JavaNativeTypeManager.IsNonStaticInnerClass (type, cache))
return true;
foreach (var r in type.GetCustomAttributes (typeof (global::Android.Runtime.RegisterAttribute))) {
if (JavaCallableWrapperGenerator.ToRegisterAttribute (r).DoNotGenerateAcw) {
return true;
}
}
return false;
}
[Obsolete ("Use the TypeDefinitionCache overload for better performance.")]
public static List<TypeDefinition> GetJavaTypes (IEnumerable<string> assemblies, IAssemblyResolver resolver, Action<string, object []> log) =>
GetJavaTypes (assemblies, resolver, log, cache: null);
// Returns all types for which we need to generate Java delegate types.
public static List<TypeDefinition> GetJavaTypes (IEnumerable<string> assemblies, IAssemblyResolver resolver, Action<string, object []> log, TypeDefinitionCache cache)
{
Action<TraceLevel, string> l = (level, value) => log ("{0}", new string [] { value });
return new JavaTypeScanner (l, cache).GetJavaTypes (assemblies, resolver);
}
}
}
| 35.576923 | 180 | 0.720811 | [
"MIT"
] | dellis1972/Java.Interop | src/Java.Interop.Tools.JavaCallableWrappers/Java.Interop.Tools.JavaCallableWrappers/JavaTypeScanner.cs | 3,702 | C# |
using System.Collections;
using UnityEngine;
using System.Linq;
namespace TowerDefense
{
[AddComponentMenu("TOWER DEFENSE/Tower Agent")]
[RequireComponent(typeof(NavMeshObstacle))]
[RequireComponent(typeof(Renderer))]
public class TowerAgent : MonoBehaviour, ITowerHandler
{
private TowerSettings m_settings;
private Renderer m_renderer;
private float m_cooldownTime;
[SerializeField] private LayerMask m_creepMask;
[SerializeField] private Transform m_weapon;
void Update()
{
if (Time.time - m_cooldownTime > (int)m_settings.Speed)
{
var colliders = Physics.OverlapSphere(transform.position, m_settings.Range, m_creepMask.value);
if (colliders.Length > 0)
{
var target = colliders.Aggregate((h1, h2) =>
Vector3.Distance(h1.transform.position, transform.position) <
Vector3.Distance(h2.transform.position, transform.position) ?
h1 : h2);
if (target != null && target.IsCreep())
{
m_cooldownTime = Time.time;
LevelManager.TowerShotPooling.SpawnShot (m_weapon.position, m_weapon.rotation, m_settings.Damage, target.transform);
}
}
}
}
void OnMouseDown()
{
LevelManager.SetTower (this, true);
}
void OnDrawGizmos()
{
if (m_settings == null) return;
Gizmos.color = Color.white;
Gizmos.DrawWireSphere (transform.position, m_settings.Range);
}
public void Setup(Vector3 position, Quaternion rotation, TowerSettings settings)
{
transform.localPosition = position;
transform.localRotation = rotation;
m_settings = settings;
if (m_renderer == null) m_renderer = GetComponent<Renderer> ();
m_renderer.sharedMaterial = m_settings.Race;
m_cooldownTime = Time.time;
}
#region ITowerHandler implementation
public TowerSettings Settings { get { return m_settings; } }
#endregion
}
} | 26.216216 | 122 | 0.677835 | [
"MIT"
] | joaokucera/unity-tower-defense | src/Assets/Tower Defense/Scripts/TowerAgent.cs | 1,942 | 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.Collections.Generic;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.TestModels.ManyToManyModel;
using Microsoft.EntityFrameworkCore.TestUtilities;
namespace Microsoft.EntityFrameworkCore
{
public class ManyToManyTrackingSqliteTest
: ManyToManyTrackingTestBase<ManyToManyTrackingSqliteTest.ManyToManyTrackingSqliteFixture>
{
public ManyToManyTrackingSqliteTest(ManyToManyTrackingSqliteFixture fixture) : base(fixture)
{ }
protected override void UseTransaction(
DatabaseFacade facade,
IDbContextTransaction transaction
) => facade.UseTransaction(transaction.GetDbTransaction());
public class ManyToManyTrackingSqliteFixture : ManyToManyTrackingFixtureBase
{
protected override ITestStoreFactory TestStoreFactory =>
SqliteTestStoreFactory.Instance;
protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context)
{
base.OnModelCreating(modelBuilder, context);
modelBuilder
.Entity<JoinOneSelfPayload>()
.Property(e => e.Payload)
.HasDefaultValueSql("CURRENT_TIMESTAMP");
modelBuilder
.SharedTypeEntity<Dictionary<string, object>>("JoinOneToThreePayloadFullShared")
.IndexerProperty<string>("Payload")
.HasDefaultValue("Generated");
modelBuilder
.Entity<JoinOneToThreePayloadFull>()
.Property(e => e.Payload)
.HasDefaultValue("Generated");
}
}
}
}
| 39.77551 | 111 | 0.664956 | [
"Apache-2.0"
] | belav/efcore | test/EFCore.Sqlite.FunctionalTests/ManyToManyTrackingSqliteTest.cs | 1,951 | 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;
namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
private static Action<ILogger, string, Exception> _authSchemeAuthenticated;
private static Action<ILogger, string, Exception> _authSchemeNotAuthenticated;
private static Action<ILogger, string, string, Exception> _authSchemeNotAuthenticatedWithFailure;
private static Action<ILogger, string, Exception> _authSchemeSignedIn;
private static Action<ILogger, string, Exception> _authSchemeSignedOut;
private static Action<ILogger, string, Exception> _authSchemeChallenged;
private static Action<ILogger, string, Exception> _authSchemeForbidden;
private static Action<ILogger, string, Exception> _userAuthorizationFailed;
private static Action<ILogger, string, Exception> _userAuthorizationSucceeded;
private static Action<ILogger, string, Exception> _userPrincipalMerged;
private static Action<ILogger, string, Exception> _remoteAuthenticationError;
private static Action<ILogger, Exception> _signInHandled;
private static Action<ILogger, Exception> _signInSkipped;
private static Action<ILogger, string, Exception> _correlationPropertyNotFound;
private static Action<ILogger, string, Exception> _correlationCookieNotFound;
private static Action<ILogger, string, string, Exception> _unexpectedCorrelationCookieValue;
static LoggingExtensions()
{
_userAuthorizationSucceeded = LoggerMessage.Define<string>(
eventId: 1,
logLevel: LogLevel.Information,
formatString: "Authorization was successful for user: {UserName}.");
_userAuthorizationFailed = LoggerMessage.Define<string>(
eventId: 2,
logLevel: LogLevel.Information,
formatString: "Authorization failed for user: {UserName}.");
_userPrincipalMerged = LoggerMessage.Define<string>(
eventId: 3,
logLevel: LogLevel.Information,
formatString: "HttpContext.User merged via AutomaticAuthentication from authenticationScheme: {AuthenticationScheme}.");
_remoteAuthenticationError = LoggerMessage.Define<string>(
eventId: 4,
logLevel: LogLevel.Information,
formatString: "Error from RemoteAuthentication: {ErrorMessage}.");
_signInHandled = LoggerMessage.Define(
eventId: 5,
logLevel: LogLevel.Debug,
formatString: "The SigningIn event returned Handled.");
_signInSkipped = LoggerMessage.Define(
eventId: 6,
logLevel: LogLevel.Debug,
formatString: "The SigningIn event returned Skipped.");
_authSchemeNotAuthenticatedWithFailure = LoggerMessage.Define<string, string>(
eventId: 7,
logLevel: LogLevel.Information,
formatString: "{AuthenticationScheme} was not authenticated. Failure message: {FailureMessage}");
_authSchemeAuthenticated = LoggerMessage.Define<string>(
eventId: 8,
logLevel: LogLevel.Information,
formatString: "AuthenticationScheme: {AuthenticationScheme} was successfully authenticated.");
_authSchemeNotAuthenticated = LoggerMessage.Define<string>(
eventId: 9,
logLevel: LogLevel.Debug,
formatString: "AuthenticationScheme: {AuthenticationScheme} was not authenticated.");
_authSchemeSignedIn = LoggerMessage.Define<string>(
eventId: 10,
logLevel: LogLevel.Information,
formatString: "AuthenticationScheme: {AuthenticationScheme} signed in.");
_authSchemeSignedOut = LoggerMessage.Define<string>(
eventId: 11,
logLevel: LogLevel.Information,
formatString: "AuthenticationScheme: {AuthenticationScheme} signed out.");
_authSchemeChallenged = LoggerMessage.Define<string>(
eventId: 12,
logLevel: LogLevel.Information,
formatString: "AuthenticationScheme: {AuthenticationScheme} was challenged.");
_authSchemeForbidden = LoggerMessage.Define<string>(
eventId: 13,
logLevel: LogLevel.Information,
formatString: "AuthenticationScheme: {AuthenticationScheme} was forbidden.");
_correlationPropertyNotFound = LoggerMessage.Define<string>(
eventId: 14,
logLevel: LogLevel.Warning,
formatString: "{CorrelationProperty} state property not found.");
_correlationCookieNotFound = LoggerMessage.Define<string>(
eventId: 15,
logLevel: LogLevel.Warning,
formatString: "'{CorrelationCookieName}' cookie not found.");
_unexpectedCorrelationCookieValue = LoggerMessage.Define<string, string>(
eventId: 16,
logLevel: LogLevel.Warning,
formatString: "The correlation cookie value '{CorrelationCookieName}' did not match the expected value '{CorrelationCookieValue}'.");
}
public static void AuthenticationSchemeAuthenticated(this ILogger logger, string authenticationScheme)
{
_authSchemeAuthenticated(logger, authenticationScheme, null);
}
public static void AuthenticationSchemeNotAuthenticated(this ILogger logger, string authenticationScheme)
{
_authSchemeNotAuthenticated(logger, authenticationScheme, null);
}
public static void AuthenticationSchemeNotAuthenticatedWithFailure(this ILogger logger, string authenticationScheme, string failureMessage)
{
_authSchemeNotAuthenticatedWithFailure(logger, authenticationScheme, failureMessage, null);
}
public static void AuthenticationSchemeSignedIn(this ILogger logger, string authenticationScheme)
{
_authSchemeSignedIn(logger, authenticationScheme, null);
}
public static void AuthenticationSchemeSignedOut(this ILogger logger, string authenticationScheme)
{
_authSchemeSignedOut(logger, authenticationScheme, null);
}
public static void AuthenticationSchemeChallenged(this ILogger logger, string authenticationScheme)
{
_authSchemeChallenged(logger, authenticationScheme, null);
}
public static void AuthenticationSchemeForbidden(this ILogger logger, string authenticationScheme)
{
_authSchemeForbidden(logger, authenticationScheme, null);
}
public static void UserAuthorizationSucceeded(this ILogger logger, string userName)
{
_userAuthorizationSucceeded(logger, userName, null);
}
public static void UserAuthorizationFailed(this ILogger logger, string userName)
{
_userAuthorizationFailed(logger, userName, null);
}
public static void UserPrinicpalMerged(this ILogger logger, string authenticationScheme)
{
_userPrincipalMerged(logger, authenticationScheme, null);
}
public static void RemoteAuthenticationError(this ILogger logger, string errorMessage)
{
_remoteAuthenticationError(logger, errorMessage, null);
}
public static void SigninHandled(this ILogger logger)
{
_signInHandled(logger, null);
}
public static void SigninSkipped(this ILogger logger)
{
_signInSkipped(logger, null);
}
public static void CorrelationPropertyNotFound(this ILogger logger, string correlationPrefix)
{
_correlationPropertyNotFound(logger, correlationPrefix, null);
}
public static void CorrelationCookieNotFound(this ILogger logger, string cookieName)
{
_correlationCookieNotFound(logger, cookieName, null);
}
public static void UnexpectedCorrelationCookieValue(this ILogger logger, string cookieName, string cookieValue)
{
_unexpectedCorrelationCookieValue(logger, cookieName, cookieValue, null);
}
}
}
| 48.659091 | 148 | 0.667562 | [
"Apache-2.0"
] | FastSecurity1/fast | src/Microsoft.AspNetCore.Authentication/LoggingExtensions.cs | 8,566 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BugTracker.Controllers
{
public class MainController : Controller
{
//
// GET: /Main/
public ActionResult Index()
{
return View();
}
}
}
| 16.285714 | 45 | 0.55848 | [
"Apache-2.0"
] | nik-sergeson/bsuir-informatics-labs | 5term/IGI/BugTracker/BugTracker/Controllers/MainController.cs | 344 | C# |
using Bing.Biz.OAuthLogin.Core;
namespace Bing.Biz.OAuthLogin.Baidu.Configs
{
/// <summary>
/// 百度授权配置
/// </summary>
public class BaiduAuthorizationConfig : AuthorizationConfigBase
{
/// <summary>
/// 初始化一个<see cref="BaiduAuthorizationConfig"/>类型的实例
/// </summary>
public BaiduAuthorizationConfig()
{
AuthorizationUrl = "https://openapi.baidu.com/oauth/2.0/authorize";
AccessTokenUrl = "https://openapi.baidu.com/oauth/2.0/token";
}
}
}
| 26.8 | 79 | 0.606343 | [
"MIT"
] | bing-framework/Bing.NetCode | components/src/Bing.Biz.OAuthLogin/Baidu/Configs/BaiduAuthorizationConfig.cs | 570 | C# |
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Schema;
namespace Microsoft.Bot.Samples.Echo.AspNetCore
{
public class EchoBot : IBot
{
public EchoBot() { }
public async Task OnTurn(ITurnContext context)
{
switch (context.Activity.Type)
{
// Note: This Sample is soon to be deleted. I've added in some easy testing here
// for now, although we do need a better solution for testing the BotFrameworkConnector in the
// near future
case ActivityTypes.Message:
await context.SendActivity($"You sent '{context.Activity.Text}'");
if (context.Activity.Text.ToLower() == "getmembers")
{
BotFrameworkAdapter b = (BotFrameworkAdapter)context.Adapter;
var members = await b.GetConversationMembers(context);
await context.SendActivity($"Members Found: {members.Count} ");
foreach ( var m in members)
{
await context.SendActivity($"Member Id: {m.Id} Name: {m.Name} Role: {m.Role}");
}
}
else if (context.Activity.Text.ToLower() == "getactivitymembers")
{
BotFrameworkAdapter b = (BotFrameworkAdapter)context.Adapter;
var members = await b.GetActivityMembers(context);
await context.SendActivity($"Members Found: {members.Count} ");
foreach (var m in members)
{
await context.SendActivity($"Member Id: {m.Id} Name: {m.Name} Role: {m.Role}");
}
}
else if (context.Activity.Text.ToLower() == "getconversations")
{
BotFrameworkAdapter b = (BotFrameworkAdapter)context.Adapter;
var conversations = await b.GetConversations(context);
await context.SendActivity($"Conversations Found: {conversations.Conversations.Count} ");
foreach (var m in conversations.Conversations)
{
await context.SendActivity($"Conversation Id: {m.Id} Member Count: {m.Members.Count}");
}
}
break;
case ActivityTypes.ConversationUpdate:
foreach (var newMember in context.Activity.MembersAdded)
{
if (newMember.Id != context.Activity.Recipient.Id)
{
await context.SendActivity("Hello and welcome to the echo bot.");
}
}
break;
}
}
}
}
| 45.820896 | 143 | 0.486645 | [
"MIT"
] | geffzhang/botbuilder-dotnet | samples/Microsoft.Bot.Samples.EchoBot-AspNetCore/EchoBot.cs | 3,072 | C# |
using DomainFramework.Core;
using System;
using System.Collections.Generic;
using System.Linq;
namespace EmployeeWithSpouse.EmployeeBoundedContext
{
public class SaveEmployeeCommandAggregate : CommandAggregate<Employee>
{
public SaveEmployeeCommandAggregate() : base(new DomainFramework.DataAccess.RepositoryContext(EmployeeWithSpouseConnectionClass.GetConnectionName()))
{
}
public SaveEmployeeCommandAggregate(SaveEmployeeInputDto employee, EntityDependency[] dependencies = null) : base(new DomainFramework.DataAccess.RepositoryContext(EmployeeWithSpouseConnectionClass.GetConnectionName()))
{
Initialize(employee, dependencies);
}
public override void Initialize(IInputDataTransferObject employee, EntityDependency[] dependencies)
{
Initialize((SaveEmployeeInputDto)employee, dependencies);
}
private void Initialize(SaveEmployeeInputDto employee, EntityDependency[] dependencies)
{
RegisterCommandRepositoryFactory<Employee>(() => new EmployeeCommandRepository());
RegisterCommandRepositoryFactory<Person>(() => new PersonCommandRepository());
var marriedToDependency = (Person)dependencies?.SingleOrDefault()?.Entity;
RootEntity = new Employee
{
Id = employee.EmployeeId,
HireDate = employee.HireDate,
Name = employee.Name,
MarriedToPersonId = (marriedToDependency != null) ? marriedToDependency.Id : employee.MarriedToPersonId,
CellPhone = (employee.CellPhone != null) ? new PhoneNumber
{
AreaCode = employee.CellPhone.AreaCode,
Exchange = employee.CellPhone.Exchange,
Number = employee.CellPhone.Number
} : null
};
Enqueue(new SaveEntityCommandOperation<Employee>(RootEntity, dependencies));
Enqueue(new DeleteLinksCommandOperation<Employee>(RootEntity, "UnlinkSpouseFromPerson"));
if (employee.Spouse != null)
{
ILinkedAggregateCommandOperation operation;
var spouse = employee.Spouse;
if (spouse is PersonInputDto)
{
operation = new AddLinkedAggregateCommandOperation<Employee, SavePersonCommandAggregate, PersonInputDto>(
RootEntity,
(PersonInputDto)spouse,
new EntityDependency[]
{
new EntityDependency
{
Entity = RootEntity,
Selector = "Spouse"
}
}
);
Enqueue(operation);
}
else
{
throw new NotImplementedException();
}
Enqueue(new UpdateEntityCommandOperation<Employee>(RootEntity, new EntityDependency[]
{
new EntityDependency
{
Entity = operation.CommandAggregate.RootEntity,
Selector = "Spouse"
}
}));
}
}
}
} | 37.877778 | 226 | 0.559695 | [
"MIT"
] | jgonte/DomainFramework | DomainFramework.Tests/EmployeeWithSpouse/EmployeeBoundedContext/CommandAggregates/SaveEmployeeCommandAggregate.cs | 3,409 | C# |
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using DapperExtensions;
using GFramework.core.domainEntities;
using GFramework.core.querying;
using $safeprojectname$.mappers;
namespace $safeprojectname$.querying
{
public class GenericQueryingService<T> : IQueryingService<T> where T : class, IEntity
{
SqlConnection conn;
public GenericQueryingService()
{
DapperExtensions.DapperExtensions.SetMappingAssemblies(new[] { typeof(CustomerMapper).Assembly });
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["QueryDb"].ConnectionString);
}
public IList<T> GetAll()
{
var list = conn.GetList<T>();
return (IList<T>)list;
}
public T GetSingle(object Id)
{
var entity = conn.Get<T>(Id);
return entity;
}
}
}
| 25.833333 | 110 | 0.647312 | [
"MIT"
] | gtejeda/GFramework.visual.studio.starter.template | GFramework.data/querying/GenericQueryingService.cs | 932 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RaLisp.StdLib
{
public class Let : IFunction
{
public string Name
{
get
{
return "let";
}
}
public object Execute(IDictionary<string, object> context, params object[] parameters)
{
var value = parameters[1].Evaluate(context);
context.Set((parameters[0] as Variable).Name, value);
return value;
}
}
}
| 21.37037 | 94 | 0.559792 | [
"MIT"
] | richorama/RaLisp | RaLisp/StdLib/Let.cs | 579 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Compute.V20180930.Outputs
{
/// <summary>
/// The source image used for creating the disk.
/// </summary>
[OutputType]
public sealed class ImageDiskReferenceResponse
{
/// <summary>
/// A relative uri containing either a Platform Image Repository or user image reference.
/// </summary>
public readonly string Id;
/// <summary>
/// If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image to use. For OS disks, this field is null.
/// </summary>
public readonly int? Lun;
[OutputConstructor]
private ImageDiskReferenceResponse(
string id,
int? lun)
{
Id = id;
Lun = lun;
}
}
}
| 29.282051 | 172 | 0.62697 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Compute/V20180930/Outputs/ImageDiskReferenceResponse.cs | 1,142 | C# |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by Brian Nelson 2016. *
* See license in repo for more information *
* https://github.com/sharpHDF/sharpHDF *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
namespace sharpHDF.Library.Enums
{
public enum Hdf5DataTypes
{
Int8,
Int16,
Int32,
Int64,
UInt8,
UInt16,
UInt32,
UInt64,
Single,
Double,
String
}
}
| 28.043478 | 79 | 0.313178 | [
"MIT"
] | Hakan77/sharpHDF | src/sharpHDF/Enums/Hdf5DataTypes.cs | 647 | C# |
using System;
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Microsoft.Extensions.Logging;
using MithrilShards.Core.Crypto;
using MithrilShards.Core.Network;
using MithrilShards.Core.Network.Protocol;
using MithrilShards.Core.Network.Protocol.Serialization;
namespace MithrilShards.Network.Legacy
{
/// <summary>
/// Class to handle the common bitcoin-like protocol.
/// Bitcoin protocol is composed of these fields
/// Size |Description|Data Type | Comments
/// 4 | magic |uint32_t | Magic value indicating message origin network, and used to seek to next message when stream state is unknown
/// 12 | command |char[12] | ASCII string identifying the packet content, NULL padded (non-NULL padding results in packet rejected)
/// 4 | command |uint32_t | Length of payload in number of bytes
/// 4 | command |uint32_t | First 4 bytes of sha256(sha256(payload))
/// ? | command |uchar[] | The actual data
/// </summary>
public class NetworkMessageDecoder
{
readonly ILogger<NetworkMessageDecoder> logger;
readonly INetworkDefinition chainDefinition;
readonly INetworkMessageSerializerManager networkMessageSerializerManager;
private IPeerContext peerContext = null!;//set by SetPeerContext
public ConnectionContextData ContextData { get; }
public NetworkMessageDecoder(ILogger<NetworkMessageDecoder> logger,
INetworkDefinition chainDefinition,
INetworkMessageSerializerManager networkMessageSerializerManager,
ConnectionContextData contextData)
{
this.logger = logger;
this.chainDefinition = chainDefinition;
this.networkMessageSerializerManager = networkMessageSerializerManager;
this.ContextData = contextData;
}
internal void SetPeerContext(IPeerContext peerContext)
{
this.peerContext = peerContext;
}
public bool TryParseMessage(in ReadOnlySequence<byte> input, out SequencePosition consumed, out SequencePosition examined, [MaybeNullWhen(false)] out INetworkMessage message)
{
var reader = new SequenceReader<byte>(input);
if (this.TryReadHeader(ref reader))
{
// now try to read the payload
if (reader.Remaining >= this.ContextData.PayloadLength)
{
ReadOnlySequence<byte> payload = input.Slice(reader.Position, this.ContextData.PayloadLength);
//check checksum
ReadOnlySpan<byte> checksum = HashGenerator.DoubleSha256(payload.ToArray()).Slice(0, 4);
if (this.ContextData.Checksum != BitConverter.ToUInt32(checksum))
{
throw new ProtocolViolationException("Invalid checksum.");
}
//we consumed and examined everything, no matter if the message was a known message or not
examined = consumed = payload.End;
this.ContextData.ResetFlags();
string commandName = this.ContextData.GetCommandName();
if (this.networkMessageSerializerManager
.TryDeserialize(commandName, ref payload, this.peerContext.NegotiatedProtocolVersion.Version, this.peerContext, out message))
{
this.peerContext.Metrics.Received(this.ContextData.GetTotalMessageLength());
return true;
}
else
{
this.logger.LogWarning("Deserializer for message '{Command}' not found.", commandName);
message = new UnknownMessage(commandName, payload.ToArray());
this.peerContext.Metrics.Wasted(this.ContextData.GetTotalMessageLength());
return true;
}
}
}
// not enough data do read the full payload, so mark as examined the whole reader but let consumed just consume the expected payload length.
consumed = reader.Position;
examined = input.End;
message = default!;
return false;
}
private bool TryReadHeader(ref SequenceReader<byte> reader)
{
if (!this.ContextData.MagicNumberRead)
{
if (!this.TryReadMagicNumber(ref reader))
{
return false;
}
}
if (!this.ContextData.CommandRead)
{
if (!this.TryReadCommand(ref reader))
{
return false;
}
}
if (!this.ContextData.PayloadLengthRead)
{
if (!this.TryReadPayloadLenght(ref reader))
{
return false;
}
}
if (!this.ContextData.ChecksumRead)
{
if (!this.TryReadChecksum(ref reader))
{
return false;
}
}
return true;
}
/// <summary>
/// Tries to read the magic number from the buffer.
/// It keep advancing till it has been found or end of buffer is reached.
/// <paramref name="reader"/> advance up to the read magic number or, if not found it goes further trying to find a subset of it.
/// In case a partial magic number has been found before reaching the end of the buffer, reader rewinds to the position of the first
/// byte of the magic number that has been found.
/// </summary>
/// <param name="reader">The reader.</param>
/// <remarks>When returns false, reader may be not to the end of the buffer in case a partial magic number lies at the end of the buffer.</remarks>
/// <returns>true if the magic number has been full read, false otherwise (not enough bytes to read)</returns>
private bool TryReadMagicNumber(ref SequenceReader<byte> reader)
{
long prevRemaining = reader.Remaining;
// advance to the first byte of the magic number.
while (reader.TryAdvanceTo(this.ContextData.FirstMagicNumberByte, advancePastDelimiter: false))
{
//TODO: compare sequence of bytes instead of reading an int
if (reader.TryReadLittleEndian(out int magicRead))
{
if (magicRead == this.ContextData.MagicNumber)
{
this.ContextData.MagicNumberRead = true;
return true;
}
else
{
reader.Rewind(3);
//TODO check this logic
this.peerContext.Metrics.Wasted(reader.Remaining - prevRemaining);
return false;
}
}
else
{
this.peerContext.Metrics.Wasted(reader.Remaining - prevRemaining);
return false;
}
}
// didn't found the first magic byte so can advance up to the end
reader.Advance(reader.Remaining);
this.peerContext.Metrics.Wasted(reader.Remaining);
return false;
}
/// <summary>
/// Tries to read the command from the buffer fetching the next SIZE_COMMAND bytes.
/// <paramref name="reader"/> doesn't advance if failing, otherwise it advance by <see cref="SIZE_COMMAND"/>
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>true if the command has been read, false otherwise (not enough bytes to read)</returns>
private bool TryReadCommand(ref SequenceReader<byte> reader)
{
if (reader.Remaining >= ConnectionContextData.SIZE_COMMAND)
{
ReadOnlySequence<byte> commandReader = reader.Sequence.Slice(reader.Position, ConnectionContextData.SIZE_COMMAND);
this.ContextData.SetCommand(commandReader.ToArray());
reader.Advance(ConnectionContextData.SIZE_COMMAND);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Tries to read the payload length from the buffer.
/// <paramref name="reader"/> doesn't advance if failing, otherwise it advance by <see cref="SIZE_PAYLOAD_LENGTH"/>
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>true if the payload length has been read, false otherwise (not enough bytes to read)</returns>
private bool TryReadPayloadLenght(ref SequenceReader<byte> reader)
{
if (reader.TryReadLittleEndian(out int payloadLengthBytes))
{
this.ContextData.PayloadLength = (uint)payloadLengthBytes;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Tries to read the checksum from the buffer.
/// <paramref name="reader"/> doesn't advance if failing, otherwise it advance by <see cref="SIZE_CHECKSUM"/>
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>true if the checksum has been read, false otherwise (not enough bytes to read)</returns>
private bool TryReadChecksum(ref SequenceReader<byte> reader)
{
if (reader.TryReadLittleEndian(out int checksumBytes))
{
this.ContextData.Checksum = (uint)checksumBytes;
return true;
}
else
{
return false;
}
}
}
public class InvalidNetworkMessageException : Exception
{
public InvalidNetworkMessageException() { }
public InvalidNetworkMessageException(string message) : base(message) { }
public InvalidNetworkMessageException(string message, Exception inner) : base(message, inner) { }
protected InvalidNetworkMessageException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
}
| 40.270161 | 180 | 0.611895 | [
"MIT"
] | MithrilMan/MithrilShards | src/MithrilShards.P2P/NetworkMessageDecoder.cs | 9,989 | C# |
/*
* Copyright 2019 Douglas Kaip
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using NUnit.Framework;
using com.CIMthetics.CSharpSECSTools.SECSItems;
namespace SECSItemTests
{
[TestFixture()]
public class I2ArraySECSItemTests
{
[Test()]
public void Test01 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x02, 255, 255 };
short expectedOutput = -1;
I2SECSItem secsItem = new I2SECSItem (input, 0);
Assert.IsTrue (secsItem.GetValue () == expectedOutput);
}
[Test()]
public void Test02 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x02, 128, 0 };
short expectedOutput = -32768;
I2SECSItem secsItem = new I2SECSItem (input, 0);
Assert.IsTrue (secsItem.GetValue () == expectedOutput);
}
[Test()]
public void Test03 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x02, 0, 0 };
short expectedOutput = 0;
I2SECSItem secsItem = new I2SECSItem (input, 0);
Assert.IsTrue (secsItem.GetValue () == expectedOutput);
}
[Test()]
public void Test04 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x02, 0, 1 };
short expectedOutput = 1;
I2SECSItem secsItem = new I2SECSItem (input, 0);
Assert.IsTrue (secsItem.GetValue () == expectedOutput);
}
[Test()]
public void Test05 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x02, 127, 255 };
short expectedOutput = 32767;
I2SECSItem secsItem = new I2SECSItem (input, 0);
Assert.IsTrue (secsItem.GetValue () == expectedOutput);
}
[Test()]
public void Test06 ()
{
short expectedOutput = 32767;
I2SECSItem secsItem = new I2SECSItem (expectedOutput);
Assert.IsTrue (secsItem.GetValue () == expectedOutput);
}
[Test()]
public void Test07 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x02, 255, 255 };
I2SECSItem secsItem = new I2SECSItem (input, 0);
Assert.IsTrue (secsItem.GetSECSItemFormatCode () == SECSItemFormatCode.I2);
}
[Test()]
public void Test08 ()
{
short expectedOutput = 32767;
I2SECSItem secsItem = new I2SECSItem (expectedOutput);
Assert.IsTrue (secsItem.GetSECSItemFormatCode () == SECSItemFormatCode.I2);
}
[Test()]
public void Test09 ()
{
byte [] expectedResult = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x02, 127, 255 };
I2SECSItem secsItem = new I2SECSItem ((short)32767);
Assert.AreEqual (secsItem.ToRawSECSItem (), expectedResult);
}
[Test()]
public void Test10 ()
{
byte [] expectedResult = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x02), 0, 0x02, 127, 255 };
I2SECSItem secsItem = new I2SECSItem ((short)32767, SECSItemNumLengthBytes.TWO);
Assert.AreEqual (secsItem.ToRawSECSItem (), expectedResult);
}
[Test()]
public void Test11 ()
{
byte [] expectedResult = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x03), 0, 0, 0x02, 127, 255 };
I2SECSItem secsItem = new I2SECSItem ((short)32767, SECSItemNumLengthBytes.THREE);
Assert.AreEqual (secsItem.ToRawSECSItem (), expectedResult);
}
[Test()]
public void Test12 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x00 };
var exception = Assert.Catch (() => new I2ArraySECSItem (input, 0));
Assert.IsInstanceOf<ArgumentOutOfRangeException> (exception);
Assert.IsTrue (exception.Message.Contains ("Illegal data length of: 0 payload length must be a non-zero multiple of 2."));
}
[Test()]
public void Test13 ()
{
byte [] input = { (byte)((SECSItemFormatCodeFunctions.GetNumberFromSECSItemFormatCode (SECSItemFormatCode.I2) << 2) | 0x01), 0x03 };
var exception = Assert.Catch (() => new I2ArraySECSItem (input, 0));
Assert.IsInstanceOf<ArgumentOutOfRangeException> (exception);
Assert.IsTrue (exception.Message.Contains ("Illegal data length of: 3 payload length must be a non-zero multiple of 2."));
}
[Test()]
public void Test14 ()
{
I2SECSItem secsItem = new I2SECSItem ((short)32767);
Assert.IsTrue (secsItem.ToString ().Equals ("Format:I2 Value: 32767"));
}
[Test()]
public void Test15 ()
{
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
I2SECSItem secsItem2 = new I2SECSItem ((short)32767);
Assert.IsTrue (secsItem1.Equals (secsItem2));
}
[Test()]
public void Test16 ()
{
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
I2SECSItem secsItem2 = new I2SECSItem ((short)-32768);
Assert.IsFalse (secsItem1.Equals (secsItem2));
}
[Test()]
public void Test17 ()
{
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
I2SECSItem secsItem2 = null;
Assert.IsFalse (secsItem1.Equals (secsItem2));
}
[Test()]
public void Test18 ()
{
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
Assert.IsTrue (secsItem1.Equals (secsItem1));
}
[Test()]
public void Test19 ()
{
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
SECSItem secsItem2 = null;
Assert.IsFalse (secsItem1.Equals (secsItem2));
}
[Test()]
public void Test20 ()
{
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
Object secsItem2 = new F8SECSItem (2.141592D);
Assert.IsFalse (secsItem1.Equals (secsItem2));
}
[Test()]
public void Test21 ()
{
Assert.IsTrue (true);
/*
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
Assert.IsTrue (secsItem1.GetHashCode () == 32798);
*/
}
[Test()]
public void Test22 ()
{
I2SECSItem secsItem1 = new I2SECSItem ((short)32767);
I2SECSItem secsItem2 = new I2SECSItem ((short)32767);
Assert.IsTrue (secsItem1.GetHashCode () == secsItem2.GetHashCode ());
}
}
}
| 36.359091 | 169 | 0.589949 | [
"Apache-2.0"
] | dkaip/CSharpSECSTools | SECSItemTests/I2ArraySECSItemTests.cs | 8,001 | C# |
using PokemonAdventureGame.Types;
using PokemonAdventureGame.Enums;
using Xunit;
namespace PokemonAdventureGame.Tests.Types
{
public class WaterTypeEffectTests
{
private readonly Type WaterType = Type.WATER;
[Fact]
public void WaterAgainstFireShouldBeSuperEffective()
{
TypeEffect typeEffect = TypeComparer.GetMoveEffectivenessBasedOnPokemonType(WaterType, Enums.Type.FIRE);
Assert.Equal(TypeEffect.SUPER_EFFECTIVE, typeEffect);
}
[Fact]
public void WaterAgainstGrassShouldBeNotVeryEffective()
{
TypeEffect typeEffect = TypeComparer.GetMoveEffectivenessBasedOnPokemonType(WaterType, Enums.Type.GRASS);
Assert.Equal(TypeEffect.NOT_VERY_EFFECTIVE, typeEffect);
}
[Fact]
public void WaterAgainstGroundShouldBeSuperEffective()
{
TypeEffect typeEffect = TypeComparer.GetMoveEffectivenessBasedOnPokemonType(WaterType, Enums.Type.GROUND);
Assert.Equal(TypeEffect.SUPER_EFFECTIVE, typeEffect);
}
[Fact]
public void WaterAgainstRockShouldBeSuperEffective()
{
TypeEffect typeEffect = TypeComparer.GetMoveEffectivenessBasedOnPokemonType(WaterType, Enums.Type.ROCK);
Assert.Equal(TypeEffect.SUPER_EFFECTIVE, typeEffect);
}
[Fact]
public void WaterAgainstDragonShouldBeNotVeryEffective()
{
TypeEffect typeEffect = TypeComparer.GetMoveEffectivenessBasedOnPokemonType(WaterType, Enums.Type.DRAGON);
Assert.Equal(TypeEffect.NOT_VERY_EFFECTIVE, typeEffect);
}
}
} | 36.173913 | 118 | 0.689303 | [
"MIT"
] | JustAn0therDev/PokemonAdventureGame | PokemonAdventureGame.Tests/PokemonAdventureGame.Tests/Types/WaterTypeEffectTests.cs | 1,664 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Tricentis.TCAPIObjects.Objects;
using WseToApiMigrationAddOn.Helper;
using WseToApiMigrationAddOn.Parser;
using WseToApiMigrationAddOn.Shared;
namespace WseToApiMigrationAddOn.Importer {
public class CommunicateWithWebServiceArtifactMigratorBack : IMigrator {
#region Delegates
delegate ApiModule Search(TCObject rootComponentFolder, WseTestStepParser testStepParser);
#endregion
#region Public Methods and Operators
public void CreateApiModulesAndTestSteps(TCObject rootComponentFolder,
XModule wseModule,
ModuleType moduleType) {
foreach (var teststep in CommonUtilities.GetFilteredWseTestSteps(rootComponentFolder, wseModule.TestSteps)) {
try {
var requestSpecializationModule = teststep.TestStepValues
.FirstOrDefault(
x => x.Name == "Request"
&& (x.SpecializationModule.Name
!= "Web service request data in JSON Resource"
&& x.SpecializationModule.Name
!= "Web service request data in XML Resource"
))
?.SpecializationModule;
var responseSpecializationModule = teststep.TestStepValues
.FirstOrDefault(
x => x.Name == "Response"
&& (x.SpecializationModule.Name
!= "Web service response data in JSON Resource"
&& x.SpecializationModule.Name
!= "Web service response data in XML Resource"
))
?.SpecializationModule;
if (responseSpecializationModule == null && requestSpecializationModule == null) return;
string correlationId = Guid.NewGuid().ToString();
var testStepParser = new WseTestStepParser(moduleType);
testStepParser.Parse(teststep, requestSpecializationModule, responseSpecializationModule);
ApiModule requestApiModule;
ApiModule responseApiModule;
ApiModule apiModule = null;
switch (moduleType) {
case ModuleType.CommunicatewithWebserviceRestJson
when !string.IsNullOrEmpty(testStepParser.Endpoint):
case ModuleType.CommunicatewithWebservice
when !string.IsNullOrEmpty(CommonUtilities.GetSoapAction(testStepParser.Headers)):
apiModule = SearchApiModuleByScanTag(rootComponentFolder,
testStepParser,
requestSpecializationModule,
responseSpecializationModule,
SearchRequestModule);
break;
}
if (apiModule == null) {
var apiModuleFolder =
new FolderStructureHandler().CreateFolderForWseModules(
rootComponentFolder,
requestSpecializationModule ?? responseSpecializationModule);
requestApiModule =
ApiModuleCreator.CreateRequestModule(apiModuleFolder,
requestSpecializationModule == null
? responseSpecializationModule.Name
: requestSpecializationModule.Name,
testStepParser,
correlationId,
ScanTag.GetRequestScanTag(testStepParser));
string responseModuleName = requestSpecializationModule == null
? responseSpecializationModule.Name
: requestSpecializationModule.Name;
responseApiModule =
ApiModuleCreator.CreateResponseModule(apiModuleFolder,
$"{responseModuleName} Response",
testStepParser,
correlationId,
ScanTag.GetResponseScanTag(testStepParser));
}
else {
requestApiModule = apiModule;
responseApiModule = SearchApiModuleByScanTag(rootComponentFolder,
testStepParser,
requestSpecializationModule,
responseSpecializationModule,
SearchResponseModule);
}
FileLogger.Instance.Debug(
$"Completed migration for WSE Module : '{wseModule.Name}' NodePath:'{wseModule.NodePath}'");
WseTestStepImporter wseTestStepMigrator = new WseTestStepImporter();
wseTestStepMigrator.MigrateTestSteps(rootComponentFolder,
requestApiModule,
responseApiModule,
new List<XTestStep>() { teststep },
moduleType);
}
catch (Exception e) {
FileLogger.Instance.Error(e);
}
}
}
#endregion
#region Methods
private static ApiModule SearchApiModuleByScanTag(TCObject rootComponentFolder,
WseTestStepParser testStepParser,
XModule requestSpecializationModule,
XModule responseSpecializationModule,
Search search) {
ApiModule apiModule;
var folderToSearchIn =
requestSpecializationModule?.ParentFolder ?? responseSpecializationModule?.ParentFolder;
if (folderToSearchIn != null) {
apiModule = search(folderToSearchIn, testStepParser);
if (apiModule != null) return apiModule;
}
apiModule = search(rootComponentFolder, testStepParser);
return apiModule;
}
private static ApiModule SearchRequestModule(TCObject rootComponentFolder, WseTestStepParser testStepParser) {
return ScanTag.SearchModuleByScanTag(rootComponentFolder, ScanTag.GetRequestScanTag(testStepParser));
}
private ApiModule SearchResponseModule(TCObject rootComponentFolder, WseTestStepParser testStepParser) {
return ScanTag.SearchModuleByScanTag(rootComponentFolder, ScanTag.GetResponseScanTag(testStepParser));
}
#endregion
}
} | 60.068027 | 127 | 0.425595 | [
"MIT"
] | Tricentis/WSEToAPIMigrator | src/WseToApiMigrationAddOn/CommunicateWithWebServiceArtifactMigratorBackup.cs | 8,832 | C# |
using System;
using CalorieCounter.Factories.Contracts;
using CalorieCounter.Models.Contracts;
using CalorieCounter.UnitTests.Builders;
using CalorieCounterEngine.Contracts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace CalorieCounter.UnitTests.CalorieCounterEngineTests.EngineTests
{
[TestClass]
public class AddActivityCommand_Should
{
[TestMethod]
public void CallCreateActivityWithCorrectArguments_WithCorrectInput()
{
var jsonSerializerMock = new Mock<IJsonSerializer>();
var dailyIntakeMock = new Mock<IDailyIntake>();
jsonSerializerMock.Setup(x => x.GetDailyIntake()).Returns(dailyIntakeMock.Object);
var activityFactoryMock = new Mock<IActivityFactory>();
var activityType = ActivityType.cardio;
var time = 123;
var activityMock = new Mock<IActivity>();
activityFactoryMock.Setup(x => x.CreateActivity(time, activityType)).Returns(activityMock.Object);
var args = new object[] {activityType.ToString(), time};
var engine = new EngineBuilder().WithJsonSerializer(jsonSerializerMock.Object)
.WithActivityFactory(activityFactoryMock.Object).Build();
engine.AddActivityCommand.Execute(args);
activityFactoryMock.Verify(x => x.CreateActivity(time, activityType), Times.Once);
}
[TestMethod]
public void CallAddActivityWithCorrectArguments_WithCorrectInput()
{
var jsonSerializerMock = new Mock<IJsonSerializer>();
var dailyIntakeMock = new Mock<IDailyIntake>();
jsonSerializerMock.Setup(x => x.GetDailyIntake()).Returns(dailyIntakeMock.Object);
var activityFactoryMock = new Mock<IActivityFactory>();
var activityType = ActivityType.cardio;
var time = 123;
var activityMock = new Mock<IActivity>();
activityFactoryMock.Setup(x => x.CreateActivity(time, activityType)).Returns(activityMock.Object);
var args = new object[] {activityType.ToString(), time};
var engine = new EngineBuilder().WithJsonSerializer(jsonSerializerMock.Object)
.WithActivityFactory(activityFactoryMock.Object).Build();
engine.AddActivityCommand.Execute(args);
dailyIntakeMock.Verify(x => x.AddActivity(activityMock.Object), Times.Once);
}
[TestMethod]
public void CallSave_WithCorrectInput()
{
var jsonSerializerMock = new Mock<IJsonSerializer>();
var dailyIntakeMock = new Mock<IDailyIntake>();
jsonSerializerMock.Setup(x => x.GetDailyIntake()).Returns(dailyIntakeMock.Object);
var activityFactoryMock = new Mock<IActivityFactory>();
var activityType = ActivityType.cardio;
var time = 123;
var activityMock = new Mock<IActivity>();
activityFactoryMock.Setup(x => x.CreateActivity(time, activityType)).Returns(activityMock.Object);
var args = new object[] {activityType.ToString(), time};
var engine = new EngineBuilder().WithJsonSerializer(jsonSerializerMock.Object)
.WithActivityFactory(activityFactoryMock.Object).Build();
engine.AddActivityCommand.Execute(args);
jsonSerializerMock.Verify(x => x.SaveDailyIntake(dailyIntakeMock.Object), Times.Once);
}
[TestMethod]
public void ThrowsArgumentOutOfRangeException_WhenTimeIsNegative()
{
var jsonSerializerMock = new Mock<IJsonSerializer>();
var dailyIntakeMock = new Mock<IDailyIntake>();
jsonSerializerMock.Setup(x => x.GetDailyIntake()).Returns(dailyIntakeMock.Object);
var activityFactoryMock = new Mock<IActivityFactory>();
var activityType = ActivityType.cardio;
var time = -123;
var activityMock = new Mock<IActivity>();
activityFactoryMock.Setup(x => x.CreateActivity(time, activityType)).Returns(activityMock.Object);
var args = new object[] {activityType.ToString(), time};
var engine = new EngineBuilder().WithJsonSerializer(jsonSerializerMock.Object)
.WithActivityFactory(activityFactoryMock.Object).Build();
Assert.ThrowsException<ArgumentOutOfRangeException>(() => engine.AddActivityCommand.Execute(args));
}
[TestMethod]
public void ThrowsArgumentException_WhenActivityTypeIsWrong()
{
var jsonSerializerMock = new Mock<IJsonSerializer>();
var dailyIntakeMock = new Mock<IDailyIntake>();
jsonSerializerMock.Setup(x => x.GetDailyIntake()).Returns(dailyIntakeMock.Object);
var activityFactoryMock = new Mock<IActivityFactory>();
var activityType = ActivityType.strength;
var time = 123;
var activityMock = new Mock<IActivity>();
activityFactoryMock.Setup(x => x.CreateActivity(time, activityType)).Returns(activityMock.Object);
var args = new object[] {"incorrect activity type", time};
var engine = new EngineBuilder().WithJsonSerializer(jsonSerializerMock.Object)
.WithActivityFactory(activityFactoryMock.Object).Build();
Assert.ThrowsException<ArgumentException>(() => engine.AddActivityCommand.Execute(args));
}
}
} | 50.444444 | 111 | 0.665749 | [
"MIT"
] | alekhristov/TelerikAcademyAlpha | TeamProjects/HQC & UnitTesting/CalorieCounter/CalorieCounter.UnitTests/CalorieCounterEngineTests/EngineTests/AddActivityCommand_Should.cs | 5,450 | C# |
using LuaInterface;
using System;
using UnityEngine;
namespace LuaFramework
{
public class PanelManager : Manager
{
private Transform parent;
private Transform Parent
{
get
{
if (this.parent == null)
{
GameObject gameObject = GameObject.Find("UGUI Root/UICanvas");
if (gameObject != null)
{
this.parent = gameObject.get_transform();
}
}
return this.parent;
}
}
public void CreatePanel(string name, LuaFunction func = null)
{
}
}
}
| 15.6875 | 67 | 0.643426 | [
"MIT"
] | corefan/tianqi_src | src/LuaFramework/PanelManager.cs | 502 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Automation;
namespace SHInspect.Models
{
public class Element
{
public Element()
{
Children = new List<Element>();
}
public string Name { get; set; }
public string AutomationId { get; set; }
public string Text { get; set; }
public ControlType ControlType { get; set; }
public List<Element> Children { get; }
}
}
| 22.318182 | 52 | 0.602851 | [
"MIT"
] | Streets-Heaver/SHInspect | SHInspect/Models/Element.cs | 493 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.SpectatorView
{
internal class CameraService : ComponentBroadcasterService<CameraService, CameraObserver>
{
public static readonly ShortID ID = new ShortID("CAM");
public override ShortID GetID() { return ID; }
private void Start()
{
StateSynchronizationSceneManager.Instance.RegisterService(this, new ComponentBroadcasterDefinition<CameraBroadcaster>(typeof(Camera)));
}
}
}
| 33.45 | 148 | 0.705531 | [
"MIT"
] | Bhaskers-Blu-Org2/MixedReality-SpectatorView | src/SpectatorView.Unity/Assets/SpectatorView/Scripts/StateSynchronization/NetworkedComponents/Camera/CameraService.cs | 671 | C# |
using CryptoExchange.Net.Converters;
using Switcheo.Net.Objects;
using System.Collections.Generic;
namespace Switcheo.Net.Converters
{
public class MakeStatusConverter : BaseConverter<MakeStatus>
{
public MakeStatusConverter() : this(true) { }
public MakeStatusConverter(bool quotes) : base(quotes) { }
protected override Dictionary<MakeStatus, string> Mapping => new Dictionary<MakeStatus, string>()
{
{ MakeStatus.Pending, "pending" },
{ MakeStatus.Confirming, "confirming" },
{ MakeStatus.Success, "success" },
{ MakeStatus.Cancelling, "cancelling" },
{ MakeStatus.Cancelled, "cancelled" },
{ MakeStatus.Expired, "expired" }
};
}
}
| 33.130435 | 105 | 0.635171 | [
"MIT"
] | Switcheo/Switcheo.Net | Switcheo.Net/Converters/MakeStatusConverter.cs | 764 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString")]
public class Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString : aws.IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString
{
}
}
| 49.25 | 307 | 0.901861 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString.cs | 591 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Rest;
using Discord.WebSocket;
namespace DiscordLobby
{
class UCJoinPortal
{
public ulong ChannelId { get; set; }
public ulong ServerId { get; set; }
public List<UCChannel> Channels { get; set; } = new List<UCChannel>();
}
class UCChannel
{
public ulong ChannelId { get; set; }
public string Bio { get; set; }
public List<UCPermission> Permissions { get; set; } = new List<UCPermission>();
public UCPermission DefaultPermissions { get; set; }
}
class UCPermission
{
public ulong UserId { get; set; }
public int AllowValue { get; set; }
public int DenyValue { get; set; }
}
}
| 25.424242 | 87 | 0.634088 | [
"MIT"
] | AZonee/DiscordLobby | GameLobby/UCClasses.cs | 841 | C# |
using System.ComponentModel.DataAnnotations;
namespace Book.Configuration.Dto
{
public class ChangeUiThemeInput
{
[Required]
[StringLength(32)]
public string Theme { get; set; }
}
}
| 18.333333 | 45 | 0.65 | [
"MIT"
] | yangcs2016/phoneBooks | aspnet-core/src/Book.Application/Configuration/Dto/ChangeUiThemeInput.cs | 222 | C# |
namespace PolarConverter.JSWeb.Models
{
public enum Sport
{
Biking,
Running,
Other
}
} | 13.666667 | 38 | 0.544715 | [
"MIT"
] | goldnarms/PolarConverter | src/PolarConverter.JSWeb/Models/Sport.cs | 125 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.Devices
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class SceneModeControl
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IReadOnlyList<global::Windows.Media.Devices.CaptureSceneMode> SupportedModes
{
get
{
throw new global::System.NotImplementedException("The member IReadOnlyList<CaptureSceneMode> SceneModeControl.SupportedModes is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Media.Devices.CaptureSceneMode Value
{
get
{
throw new global::System.NotImplementedException("The member CaptureSceneMode SceneModeControl.Value is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.Media.Devices.SceneModeControl.SupportedModes.get
// Forced skipping of method Windows.Media.Devices.SceneModeControl.Value.get
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Foundation.IAsyncAction SetValueAsync( global::Windows.Media.Devices.CaptureSceneMode sceneMode)
{
throw new global::System.NotImplementedException("The member IAsyncAction SceneModeControl.SetValueAsync(CaptureSceneMode sceneMode) is not implemented in Uno.");
}
#endif
}
}
| 38.707317 | 165 | 0.759924 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Devices/SceneModeControl.cs | 1,587 | C# |
using UnityEngine;
using UnityEngine.Assertions;
public class MedicineBottle : GeneralItem {
#region fields
public LiquidContainer Container { get; private set; }
#endregion
protected override void Start() {
base.Start();
// objectType = ObjectType.Medicine;
Container = LiquidContainer.FindLiquidContainer(transform);
Assert.IsNotNull(Container);
}
}
| 24.941176 | 68 | 0.662736 | [
"MIT"
] | kivik-beep/farmasia-vr | Assets/Scripts/Objects/Equipment/MedicineBottle.cs | 426 | C# |
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using static WalletWasabi.Http.Constants;
namespace WalletWasabi.Http.Models
{
// https://tools.ietf.org/html/rfc7230#section-3.1.1
// request-line = method SP request-target SP HTTP-version CRLF
public class RequestLine : StartLine
{
public RequestLine(HttpMethod method, Uri uri, HttpProtocol protocol) : base(protocol)
{
Method = method;
// https://tools.ietf.org/html/rfc7230#section-2.7.1
// A sender MUST NOT generate an "http" URI with an empty host identifier.
if (string.IsNullOrEmpty(uri.DnsSafeHost))
{
throw new HttpRequestException("Host identifier is empty.");
}
URI = uri;
}
public HttpMethod Method { get; }
public Uri URI { get; }
public override string ToString()
{
return $"{Method.Method}{SP}{URI.AbsolutePath}{URI.Query}{SP}{Protocol}{CRLF}";
}
public static RequestLine Parse(string requestLineString)
{
try
{
var parts = GetParts(requestLineString);
var methodString = parts[0];
var uri = new Uri(parts[1]);
var protocolString = parts[2];
var method = new HttpMethod(methodString);
var protocol = new HttpProtocol(protocolString);
return new RequestLine(method, uri, protocol);
}
catch (Exception ex)
{
throw new NotSupportedException($"Invalid {nameof(RequestLine)}.", ex);
}
}
}
}
| 25.125 | 88 | 0.694385 | [
"MIT"
] | 2pac1/WalletWasabi | WalletWasabi/Http/Models/RequestLine.cs | 1,407 | C# |
//using System;
//using System.Linq.Expressions;
//using Topics.Radical.Linq;
//using Topics.Radical.Validation;
//namespace Topics.Radical.Design
//{
// public interface ILivePropertyBuilder<T, TValue>
// {
// }
//}
| 17.615385 | 54 | 0.68559 | [
"MIT"
] | pdeligia/nekara-artifact | TSVD/Radical/src/net35/Radical.Design/Property Builders/ILivePropertyBuilder.cs | 231 | C# |
namespace playing_with_rapidapi.Models
{
public class WeatherByZipCode
{
public string City { get; set; } = string.Empty;
public string State { get; set; } = string.Empty;
public decimal TempF { get; set; }
public decimal TempC { get; set; }
public string Weather { get; set; } = string.Empty;
public decimal WindMPH { get; set; }
public string WindDir { get; set; } = string.Empty;
public decimal RelativeHumidity { get; set; }
public decimal VisibilityMiles { get; set; }
public string Code { get; set; } = string.Empty;
public decimal Credits { get; set; }
}
}
| 36.888889 | 59 | 0.608434 | [
"MIT"
] | solthoth/playing-with-rapidapi | src/Models/WeatherByZipCode.cs | 664 | 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 System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
using Moq;
using Xunit;
namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
{
public class ProjectStateTest : WorkspaceTestBase
{
public ProjectStateTest()
{
HostProject = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_2_0, TestProjectData.SomeProject.RootNamespace);
HostProjectWithConfigurationChange = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0, TestProjectData.SomeProject.RootNamespace);
ProjectWorkspaceState = new ProjectWorkspaceState(new[]
{
TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly").Build(),
}, default);
SomeTagHelpers = new List<TagHelperDescriptor>();
SomeTagHelpers.Add(TagHelperDescriptorBuilder.Create("Test1", "TestAssembly").Build());
Documents = new HostDocument[]
{
TestProjectData.SomeProjectFile1,
TestProjectData.SomeProjectFile2,
// linked file
TestProjectData.AnotherProjectNestedFile3,
};
Text = SourceText.From("Hello, world!");
TextLoader = () => Task.FromResult(TextAndVersion.Create(Text, VersionStamp.Create()));
}
private HostDocument[] Documents { get; }
private HostProject HostProject { get; }
private HostProject HostProjectWithConfigurationChange { get; }
private ProjectWorkspaceState ProjectWorkspaceState { get; }
private TestTagHelperResolver TagHelperResolver { get; set; }
private List<TagHelperDescriptor> SomeTagHelpers { get; }
private Func<Task<TextAndVersion>> TextLoader { get; }
private SourceText Text { get; }
protected override void ConfigureWorkspaceServices(List<IWorkspaceService> services)
{
TagHelperResolver = new TestTagHelperResolver();
services.Add(TagHelperResolver);
}
protected override void ConfigureProjectEngine(RazorProjectEngineBuilder builder)
{
builder.SetImportFeature(new TestImportProjectFeature());
}
[Fact]
public void ProjectState_ConstructedNew()
{
// Arrange
// Act
var state = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
// Assert
Assert.Empty(state.Documents);
Assert.NotEqual(VersionStamp.Default, state.Version);
}
[Fact]
public void ProjectState_AddHostDocument_ToEmpty()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
// Act
var state = original.WithAddedHostDocument(Documents[0], DocumentState.EmptyLoader);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Collection(
state.Documents.OrderBy(kvp => kvp.Key),
d => Assert.Same(Documents[0], d.Value.HostDocument));
Assert.NotEqual(original.DocumentCollectionVersion, state.DocumentCollectionVersion);
}
[Fact] // When we first add a document, we have no way to read the text, so it's empty.
public async Task ProjectState_AddHostDocument_DocumentIsEmpty()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
// Act
var state = original.WithAddedHostDocument(Documents[0], DocumentState.EmptyLoader);
// Assert
var text = await state.Documents[Documents[0].FilePath].GetTextAsync();
Assert.Equal(0, text.Length);
}
[Fact]
public void ProjectState_AddHostDocument_ToProjectWithDocuments()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithAddedHostDocument(Documents[0], DocumentState.EmptyLoader);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Collection(
state.Documents.OrderBy(kvp => kvp.Key),
d => Assert.Same(Documents[2], d.Value.HostDocument),
d => Assert.Same(Documents[0], d.Value.HostDocument),
d => Assert.Same(Documents[1], d.Value.HostDocument));
Assert.NotEqual(original.DocumentCollectionVersion, state.DocumentCollectionVersion);
}
[Fact]
public void ProjectState_AddHostDocument_TracksImports()
{
// Arrange
// Act
var state = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(TestProjectData.SomeProjectFile1, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectFile2, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectNestedFile3, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.AnotherProjectNestedFile4, DocumentState.EmptyLoader);
// Assert
Assert.Collection(
state.ImportsToRelatedDocuments.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal(TestProjectData.SomeProjectImportFile.TargetPath, kvp.Key);
Assert.Equal(
new string[]
{
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
},
kvp.Value.OrderBy(f => f));
},
kvp =>
{
Assert.Equal(TestProjectData.SomeProjectNestedImportFile.TargetPath, kvp.Key);
Assert.Equal(
new string[]
{
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
},
kvp.Value.OrderBy(f => f));
});
}
[Fact]
public void ProjectState_AddHostDocument_TracksImports_AddImportFile()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(TestProjectData.SomeProjectFile1, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectFile2, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectNestedFile3, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.AnotherProjectNestedFile4, DocumentState.EmptyLoader);
// Act
var state = original
.WithAddedHostDocument(TestProjectData.AnotherProjectImportFile, DocumentState.EmptyLoader);
// Assert
Assert.Collection(
state.ImportsToRelatedDocuments.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal(TestProjectData.SomeProjectImportFile.TargetPath, kvp.Key);
Assert.Equal(
new string[]
{
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
},
kvp.Value.OrderBy(f => f));
},
kvp =>
{
Assert.Equal(TestProjectData.SomeProjectNestedImportFile.TargetPath, kvp.Key);
Assert.Equal(
new string[]
{
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
},
kvp.Value.OrderBy(f => f));
});
}
[Fact]
public void ProjectState_AddHostDocument_RetainsComputedState()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
// Act
var state = original.WithAddedHostDocument(Documents[0], DocumentState.EmptyLoader);
// Assert
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
Assert.Same(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.Equal(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.Same(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
Assert.Same(original.Documents[Documents[2].FilePath], state.Documents[Documents[2].FilePath]);
}
[Fact]
public void ProjectState_AddHostDocument_DuplicateNoops()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithAddedHostDocument(new HostDocument(Documents[1].FilePath, "SomePath.cshtml"), DocumentState.EmptyLoader);
// Assert
Assert.Same(original, state);
}
[Fact]
public async Task ProjectState_WithChangedHostDocument_Loader()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithChangedHostDocument(Documents[1], TextLoader);
// Assert
Assert.NotEqual(original.Version, state.Version);
var text = await state.Documents[Documents[1].FilePath].GetTextAsync();
Assert.Same(Text, text);
Assert.Equal(original.DocumentCollectionVersion, state.DocumentCollectionVersion);
}
[Fact]
public async Task ProjectState_WithChangedHostDocument_Snapshot()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithChangedHostDocument(Documents[1], Text, VersionStamp.Create());
// Assert
Assert.NotEqual(original.Version, state.Version);
var text = await state.Documents[Documents[1].FilePath].GetTextAsync();
Assert.Same(Text, text);
Assert.Equal(original.DocumentCollectionVersion, state.DocumentCollectionVersion);
}
[Fact]
public void ProjectState_WithChangedHostDocument_Loader_RetainsComputedState()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
// Act
var state = original.WithChangedHostDocument(Documents[1], TextLoader);
// Assert
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
Assert.Same(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.Equal(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
}
[Fact]
public void ProjectState_WithChangedHostDocument_Snapshot_RetainsComputedState()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
// Act
var state = original.WithChangedHostDocument(Documents[1], Text, VersionStamp.Create());
// Assert
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
Assert.Same(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.Equal(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
}
[Fact]
public void ProjectState_WithChangedHostDocument_Loader_NotFoundNoops()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithChangedHostDocument(Documents[0], TextLoader);
// Assert
Assert.Same(original, state);
}
[Fact]
public void ProjectState_WithChangedHostDocument_Snapshot_NotFoundNoops()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithChangedHostDocument(Documents[0], Text, VersionStamp.Create());
// Assert
Assert.Same(original, state);
}
[Fact]
public void ProjectState_RemoveHostDocument_FromProjectWithDocuments()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithRemovedHostDocument(Documents[1]);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Collection(
state.Documents.OrderBy(kvp => kvp.Key),
d => Assert.Same(Documents[2], d.Value.HostDocument));
Assert.NotEqual(original.DocumentCollectionVersion, state.DocumentCollectionVersion);
}
[Fact]
public void ProjectState_RemoveHostDocument_TracksImports()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(TestProjectData.SomeProjectFile1, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectFile2, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectNestedFile3, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.AnotherProjectNestedFile4, DocumentState.EmptyLoader);
// Act
var state = original.WithRemovedHostDocument(TestProjectData.SomeProjectNestedFile3);
// Assert
Assert.Collection(
state.ImportsToRelatedDocuments.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal(TestProjectData.SomeProjectImportFile.TargetPath, kvp.Key);
Assert.Equal(
new string[]
{
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
},
kvp.Value.OrderBy(f => f));
},
kvp =>
{
Assert.Equal(TestProjectData.SomeProjectNestedImportFile.TargetPath, kvp.Key);
Assert.Equal(
new string[]
{
TestProjectData.AnotherProjectNestedFile4.FilePath,
},
kvp.Value.OrderBy(f => f));
});
}
[Fact]
public void ProjectState_RemoveHostDocument_TracksImports_RemoveAllDocuments()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(TestProjectData.SomeProjectFile1, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectFile2, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.SomeProjectNestedFile3, DocumentState.EmptyLoader)
.WithAddedHostDocument(TestProjectData.AnotherProjectNestedFile4, DocumentState.EmptyLoader);
// Act
var state = original
.WithRemovedHostDocument(TestProjectData.SomeProjectFile1)
.WithRemovedHostDocument(TestProjectData.SomeProjectFile2)
.WithRemovedHostDocument(TestProjectData.SomeProjectNestedFile3)
.WithRemovedHostDocument(TestProjectData.AnotherProjectNestedFile4);
// Assert
Assert.Empty(state.Documents);
Assert.Empty(state.ImportsToRelatedDocuments);
}
[Fact]
public void ProjectState_RemoveHostDocument_RetainsComputedState()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
// Act
var state = original.WithRemovedHostDocument(Documents[2]);
// Assert
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
Assert.Same(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.Equal(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.Same(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
}
[Fact]
public void ProjectState_RemoveHostDocument_NotFoundNoops()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Act
var state = original.WithRemovedHostDocument(Documents[0]);
// Assert
Assert.Same(original, state);
}
[Fact]
public void ProjectState_WithHostProject_ConfigurationChange_UpdatesConfigurationState()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ConfigurationVersion;
TagHelperResolver.TagHelpers = SomeTagHelpers;
// Act
var state = original.WithHostProject(HostProjectWithConfigurationChange);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Same(HostProjectWithConfigurationChange, state.HostProject);
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ConfigurationVersion;
Assert.NotSame(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.NotEqual(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
Assert.NotSame(original.Documents[Documents[2].FilePath], state.Documents[Documents[2].FilePath]);
Assert.NotEqual(original.DocumentCollectionVersion, state.DocumentCollectionVersion);
}
[Fact]
public void ProjectState_WithHostProject_RootNamespaceChange_UpdatesConfigurationState()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
var hostProjectWithRootNamespaceChange = new HostProject(
original.HostProject.FilePath,
original.HostProject.Configuration,
"ChangedRootNamespace");
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ConfigurationVersion;
TagHelperResolver.TagHelpers = SomeTagHelpers;
// Act
var state = original.WithHostProject(hostProjectWithRootNamespaceChange);
// Assert
Assert.NotSame(original, state);
}
[Fact]
public void ProjectState_WithHostProject_NoConfigurationChange_Noops()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
// Act
var state = original.WithHostProject(HostProject);
// Assert
Assert.Same(original, state);
}
[Fact]
public void ProjectState_WithHostProject_CallsConfigurationChangeOnDocumentState()
{
// Arrange
var callCount = 0;
var documents = ImmutableDictionary.CreateBuilder<string, DocumentState>(FilePathComparer.Instance);
documents[Documents[1].FilePath] = TestDocumentState.Create(Workspace.Services, Documents[1], onConfigurationChange: () => callCount++);
documents[Documents[2].FilePath] = TestDocumentState.Create(Workspace.Services, Documents[2], onConfigurationChange: () => callCount++);
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original.Documents = documents.ToImmutable();
// Act
var state = original.WithHostProject(HostProjectWithConfigurationChange);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Same(HostProjectWithConfigurationChange, state.HostProject);
Assert.Equal(2, callCount);
}
[Fact]
public void ProjectState_WithHostProject_ResetsImportedDocuments()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original = original.WithAddedHostDocument(TestProjectData.SomeProjectFile1, DocumentState.EmptyLoader);
// Act
var state = original.WithHostProject(HostProjectWithConfigurationChange);
// Assert
var importMap = Assert.Single(state.ImportsToRelatedDocuments);
var documentFilePath = Assert.Single(importMap.Value);
Assert.Equal(TestProjectData.SomeProjectFile1.FilePath, documentFilePath);
}
[Fact]
public void ProjectState_WithProjectWorkspaceState_Removed()
{
// Arrange
var emptyProjectWorkspaceState = new ProjectWorkspaceState(Array.Empty<TagHelperDescriptor>(), default);
var original = ProjectState.Create(Workspace.Services, HostProject, emptyProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
// Act
var state = original.WithProjectWorkspaceState(null);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Null(state.ProjectWorkspaceState);
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
// The configuration didn't change, and the tag helpers didn't actually change
Assert.Same(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.NotEqual(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
Assert.NotSame(original.Documents[Documents[2].FilePath], state.Documents[Documents[2].FilePath]);
}
[Fact]
public void ProjectState_WithProjectWorkspaceState_Added()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, null)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
var newProjectWorkspaceState = ProjectWorkspaceState.Default;
// Act
var state = original.WithProjectWorkspaceState(newProjectWorkspaceState);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Same(newProjectWorkspaceState, state.ProjectWorkspaceState);
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
// The configuration didn't change, and the tag helpers didn't actually change
Assert.Same(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.NotEqual(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
}
[Fact]
public void ProjectState_WithProjectWorkspaceState_Changed()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
var changed = new ProjectWorkspaceState(ProjectWorkspaceState.TagHelpers, LanguageVersion.CSharp6);
// Act
var state = original.WithProjectWorkspaceState(changed);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Same(changed, state.ProjectWorkspaceState);
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
// The C# language version changed, and the tag helpers didn't change
Assert.NotSame(original.ProjectEngine, state.ProjectEngine);
Assert.Same(originalTagHelpers, actualTagHelpers);
Assert.NotEqual(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
Assert.NotSame(original.Documents[Documents[2].FilePath], state.Documents[Documents[2].FilePath]);
}
[Fact]
public void ProjectState_WithProjectWorkspaceState_Changed_TagHelpersChanged()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
var changed = new ProjectWorkspaceState(Array.Empty<TagHelperDescriptor>(), default);
// Now create some tag helpers
TagHelperResolver.TagHelpers = SomeTagHelpers;
// Act
var state = original.WithProjectWorkspaceState(changed);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Same(changed, state.ProjectWorkspaceState);
var actualTagHelpers = state.TagHelpers;
var actualProjectWorkspaceStateVersion = state.ProjectWorkspaceStateVersion;
// The configuration didn't change, but the tag helpers did
Assert.Same(original.ProjectEngine, state.ProjectEngine);
Assert.NotEqual(originalTagHelpers, actualTagHelpers);
Assert.NotEqual(originalProjectWorkspaceStateVersion, actualProjectWorkspaceStateVersion);
Assert.Equal(state.Version, actualProjectWorkspaceStateVersion);
Assert.NotSame(original.Documents[Documents[1].FilePath], state.Documents[Documents[1].FilePath]);
Assert.NotSame(original.Documents[Documents[2].FilePath], state.Documents[Documents[2].FilePath]);
}
[Fact]
public void ProjectState_WithProjectWorkspaceState_IdenticalState_Caches()
{
// Arrange
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState)
.WithAddedHostDocument(Documents[2], DocumentState.EmptyLoader)
.WithAddedHostDocument(Documents[1], DocumentState.EmptyLoader);
// Force init
var originalTagHelpers = original.TagHelpers;
var originalProjectWorkspaceStateVersion = original.ProjectWorkspaceStateVersion;
var changed = new ProjectWorkspaceState(original.TagHelpers, original.CSharpLanguageVersion);
// Now create some tag helpers
TagHelperResolver.TagHelpers = SomeTagHelpers;
// Act
var state = original.WithProjectWorkspaceState(changed);
// Assert
Assert.Same(original, state);
}
[Fact]
public void ProjectState_WithProjectWorkspaceState_CallsWorkspaceProjectChangeOnDocumentState()
{
// Arrange
var callCount = 0;
var documents = ImmutableDictionary.CreateBuilder<string, DocumentState>(FilePathComparer.Instance);
documents[Documents[1].FilePath] = TestDocumentState.Create(Workspace.Services, Documents[1], onProjectWorkspaceStateChange: () => callCount++);
documents[Documents[2].FilePath] = TestDocumentState.Create(Workspace.Services, Documents[2], onProjectWorkspaceStateChange: () => callCount++);
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original.Documents = documents.ToImmutable();
var changed = new ProjectWorkspaceState(Array.Empty<TagHelperDescriptor>(), default);
// Act
var state = original.WithProjectWorkspaceState(changed);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Equal(2, callCount);
}
[Fact]
public void ProjectState_WhenImportDocumentAdded_CallsImportsChanged()
{
// Arrange
var callCount = 0;
var document1 = TestProjectData.SomeProjectFile1;
var document2 = TestProjectData.SomeProjectFile2;
var document3 = TestProjectData.SomeProjectNestedFile3;
var document4 = TestProjectData.AnotherProjectNestedFile4;
var documents = ImmutableDictionary.CreateBuilder<string, DocumentState>(FilePathComparer.Instance);
documents[document1.FilePath] = TestDocumentState.Create(Workspace.Services, document1, onImportsChange: () => callCount++);
documents[document2.FilePath] = TestDocumentState.Create(Workspace.Services, document2, onImportsChange: () => callCount++);
documents[document3.FilePath] = TestDocumentState.Create(Workspace.Services, document3, onImportsChange: () => callCount++);
documents[document4.FilePath] = TestDocumentState.Create(Workspace.Services, document4, onImportsChange: () => callCount++);
var importsToRelatedDocuments = ImmutableDictionary.CreateBuilder<string, ImmutableArray<string>>(FilePathComparer.Instance);
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath));
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectNestedImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath));
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original.Documents = documents.ToImmutable();
original.ImportsToRelatedDocuments = importsToRelatedDocuments.ToImmutable();
// Act
var state = original.WithAddedHostDocument(TestProjectData.AnotherProjectImportFile, DocumentState.EmptyLoader);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Equal(4, callCount);
}
[Fact]
public void ProjectState_WhenImportDocumentAdded_CallsImportsChanged_Nested()
{
// Arrange
var callCount = 0;
var document1 = TestProjectData.SomeProjectFile1;
var document2 = TestProjectData.SomeProjectFile2;
var document3 = TestProjectData.SomeProjectNestedFile3;
var document4 = TestProjectData.AnotherProjectNestedFile4;
var documents = ImmutableDictionary.CreateBuilder<string, DocumentState>(FilePathComparer.Instance);
documents[document1.FilePath] = TestDocumentState.Create(Workspace.Services, document1, onImportsChange: () => callCount++);
documents[document2.FilePath] = TestDocumentState.Create(Workspace.Services, document2, onImportsChange: () => callCount++);
documents[document3.FilePath] = TestDocumentState.Create(Workspace.Services, document3, onImportsChange: () => callCount++);
documents[document4.FilePath] = TestDocumentState.Create(Workspace.Services, document4, onImportsChange: () => callCount++);
var importsToRelatedDocuments = ImmutableDictionary.CreateBuilder<string, ImmutableArray<string>>(FilePathComparer.Instance);
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath));
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectNestedImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath));
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original.Documents = documents.ToImmutable();
original.ImportsToRelatedDocuments = importsToRelatedDocuments.ToImmutable();
// Act
var state = original.WithAddedHostDocument(TestProjectData.AnotherProjectNestedImportFile, DocumentState.EmptyLoader);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Equal(2, callCount);
}
[Fact]
public void ProjectState_WhenImportDocumentChangedTextLoader_CallsImportsChanged()
{
// Arrange
var callCount = 0;
var document1 = TestProjectData.SomeProjectFile1;
var document2 = TestProjectData.SomeProjectFile2;
var document3 = TestProjectData.SomeProjectNestedFile3;
var document4 = TestProjectData.AnotherProjectNestedFile4;
var document5 = TestProjectData.AnotherProjectNestedImportFile;
var documents = ImmutableDictionary.CreateBuilder<string, DocumentState>(FilePathComparer.Instance);
documents[document1.FilePath] = TestDocumentState.Create(Workspace.Services, document1, onImportsChange: () => callCount++);
documents[document2.FilePath] = TestDocumentState.Create(Workspace.Services, document2, onImportsChange: () => callCount++);
documents[document3.FilePath] = TestDocumentState.Create(Workspace.Services, document3, onImportsChange: () => callCount++);
documents[document4.FilePath] = TestDocumentState.Create(Workspace.Services, document4, onImportsChange: () => callCount++);
documents[document5.FilePath] = TestDocumentState.Create(Workspace.Services, document5, onImportsChange: () => callCount++);
var importsToRelatedDocuments = ImmutableDictionary.CreateBuilder<string, ImmutableArray<string>>(FilePathComparer.Instance);
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.AnotherProjectNestedImportFile.FilePath));
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectNestedImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath));
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original.Documents = documents.ToImmutable();
original.ImportsToRelatedDocuments = importsToRelatedDocuments.ToImmutable();
// Act
var state = original.WithChangedHostDocument(document5, DocumentState.EmptyLoader);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Equal(2, callCount);
}
[Fact]
public void ProjectState_WhenImportDocumentChangedSnapshot_CallsImportsChanged()
{
// Arrange
var callCount = 0;
var document1 = TestProjectData.SomeProjectFile1;
var document2 = TestProjectData.SomeProjectFile2;
var document3 = TestProjectData.SomeProjectNestedFile3;
var document4 = TestProjectData.AnotherProjectNestedFile4;
var document5 = TestProjectData.AnotherProjectNestedImportFile;
var documents = ImmutableDictionary.CreateBuilder<string, DocumentState>(FilePathComparer.Instance);
documents[document1.FilePath] = TestDocumentState.Create(Workspace.Services, document1, onImportsChange: () => callCount++);
documents[document2.FilePath] = TestDocumentState.Create(Workspace.Services, document2, onImportsChange: () => callCount++);
documents[document3.FilePath] = TestDocumentState.Create(Workspace.Services, document3, onImportsChange: () => callCount++);
documents[document4.FilePath] = TestDocumentState.Create(Workspace.Services, document4, onImportsChange: () => callCount++);
documents[document5.FilePath] = TestDocumentState.Create(Workspace.Services, document5, onImportsChange: () => callCount++);
var importsToRelatedDocuments = ImmutableDictionary.CreateBuilder<string, ImmutableArray<string>>(FilePathComparer.Instance);
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.AnotherProjectNestedImportFile.FilePath));
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectNestedImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath));
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original.Documents = documents.ToImmutable();
original.ImportsToRelatedDocuments = importsToRelatedDocuments.ToImmutable();
// Act
var state = original.WithChangedHostDocument(document5, Text, VersionStamp.Create());
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Equal(2, callCount);
}
[Fact]
public void ProjectState_WhenImportDocumentRemoved_CallsImportsChanged()
{
// Arrange
var callCount = 0;
var document1 = TestProjectData.SomeProjectFile1;
var document2 = TestProjectData.SomeProjectFile2;
var document3 = TestProjectData.SomeProjectNestedFile3;
var document4 = TestProjectData.AnotherProjectNestedFile4;
var document5 = TestProjectData.AnotherProjectNestedImportFile;
var documents = ImmutableDictionary.CreateBuilder<string, DocumentState>(FilePathComparer.Instance);
documents[document1.FilePath] = TestDocumentState.Create(Workspace.Services, document1, onImportsChange: () => callCount++);
documents[document2.FilePath] = TestDocumentState.Create(Workspace.Services, document2, onImportsChange: () => callCount++);
documents[document3.FilePath] = TestDocumentState.Create(Workspace.Services, document3, onImportsChange: () => callCount++);
documents[document4.FilePath] = TestDocumentState.Create(Workspace.Services, document4, onImportsChange: () => callCount++);
documents[document5.FilePath] = TestDocumentState.Create(Workspace.Services, document5, onImportsChange: () => callCount++);
var importsToRelatedDocuments = ImmutableDictionary.CreateBuilder<string, ImmutableArray<string>>(FilePathComparer.Instance);
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectFile1.FilePath,
TestProjectData.SomeProjectFile2.FilePath,
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath,
TestProjectData.AnotherProjectNestedImportFile.FilePath));
importsToRelatedDocuments.Add(
TestProjectData.SomeProjectNestedImportFile.TargetPath,
ImmutableArray.Create(
TestProjectData.SomeProjectNestedFile3.FilePath,
TestProjectData.AnotherProjectNestedFile4.FilePath));
var original = ProjectState.Create(Workspace.Services, HostProject, ProjectWorkspaceState);
original.Documents = documents.ToImmutable();
original.ImportsToRelatedDocuments = importsToRelatedDocuments.ToImmutable();
// Act
var state = original.WithRemovedHostDocument(document5);
// Assert
Assert.NotEqual(original.Version, state.Version);
Assert.Equal(2, callCount);
}
private class TestDocumentState : DocumentState
{
public static TestDocumentState Create(
HostWorkspaceServices services,
HostDocument hostDocument,
Func<Task<TextAndVersion>> loader = null,
Action onTextChange = null,
Action onTextLoaderChange = null,
Action onConfigurationChange = null,
Action onImportsChange = null,
Action onProjectWorkspaceStateChange = null)
{
return new TestDocumentState(
services,
hostDocument,
null,
null,
loader,
onTextChange,
onTextLoaderChange,
onConfigurationChange,
onImportsChange,
onProjectWorkspaceStateChange);
}
private readonly Action _onTextChange;
private readonly Action _onTextLoaderChange;
private readonly Action _onConfigurationChange;
private readonly Action _onImportsChange;
private readonly Action _onProjectWorkspaceStateChange;
private TestDocumentState(
HostWorkspaceServices services,
HostDocument hostDocument,
SourceText text,
VersionStamp? version,
Func<Task<TextAndVersion>> loader,
Action onTextChange,
Action onTextLoaderChange,
Action onConfigurationChange,
Action onImportsChange,
Action onProjectWorkspaceStateChange)
: base(services, hostDocument, text, version, loader)
{
_onTextChange = onTextChange;
_onTextLoaderChange = onTextLoaderChange;
_onConfigurationChange = onConfigurationChange;
_onImportsChange = onImportsChange;
_onProjectWorkspaceStateChange = onProjectWorkspaceStateChange;
}
public override DocumentState WithText(SourceText sourceText, VersionStamp version)
{
_onTextChange?.Invoke();
return base.WithText(sourceText, version);
}
public override DocumentState WithTextLoader(Func<Task<TextAndVersion>> loader)
{
_onTextLoaderChange?.Invoke();
return base.WithTextLoader(loader);
}
public override DocumentState WithConfigurationChange()
{
_onConfigurationChange?.Invoke();
return base.WithConfigurationChange();
}
public override DocumentState WithImportsChange()
{
_onImportsChange?.Invoke();
return base.WithImportsChange();
}
public override DocumentState WithProjectWorkspaceStateChange()
{
_onProjectWorkspaceStateChange?.Invoke();
return base.WithProjectWorkspaceStateChange();
}
}
}
}
| 46.688789 | 182 | 0.648527 | [
"Apache-2.0"
] | Pilchie/aspnetcore-tooling | src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs | 52,060 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace JoergIsAGeek.Workshop.Enterprise.WebApplicationAuth.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
}
}
| 26.071429 | 95 | 0.791781 | [
"MIT"
] | joergkrause/mvc2ng | JoergIsAGeek.Workshop.Enterprise.WebApplicationAuth/Models/ApplicationUser.cs | 367 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2019 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.Exceptions;
namespace Senparc.Weixin.HttpUtility.Tests
{
[TestClass]
public class GetTest
{
[TestMethod]
public void DownloadTest()
{
var url = "https://sdk.weixin.senparc.com/images/v2/ewm_01.png";
using (FileStream fs = new FileStream(string.Format("qr-{0}.jpg", SystemTime.Now.Ticks), FileMode.OpenOrCreate))
{
Senparc.CO2NET.HttpUtility.Get.Download(url, fs);//下载
fs.Flush();//直接保存,无需处理指针
}
using (MemoryStream ms = new MemoryStream())
{
Senparc.CO2NET.HttpUtility.Get.Download(url, ms);//下载
ms.Seek(0, SeekOrigin.Begin);//将指针放到流的开始位置
string base64Img = Convert.ToBase64String(ms.ToArray());//输出图片base64编码
Console.WriteLine(base64Img);
}
}
[TestMethod]
public void GetJsonTest()
{
return; //已经通过,但需要连接远程测试,太耗时,常规测试时暂时忽略。 TODO:迁移到 CO2NET
{
var url = "http://apistore.baidu.com/microservice/cityinfo?cityname=苏州";
var result = Senparc.CO2NET.HttpUtility.Get.GetJson<dynamic>(url);
Assert.IsNotNull(result);
Assert.AreEqual(0, result["errNum"]);
Assert.AreEqual("苏州", result["retData"]["cityName"]);
Console.WriteLine(result.GetType());
}
{
var url =
Config.ApiMpHost + "/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
try
{
//这里因为参数错误,系统会返回错误信息
WxJsonResult resultFail = Senparc.CO2NET.HttpUtility.Get.GetJson<WxJsonResult>(url);
Assert.Fail(); //上一步就应该已经抛出异常
}
catch (ErrorJsonResultException ex)
{
//实际返回的信息(错误信息)
Assert.AreEqual(ex.JsonResult.errcode, ReturnCode.不合法的APPID);
}
}
}
[TestMethod]
public void GetJsonAsyncTest()
{
//return;//已经通过,但需要连接远程测试,太耗时,常规测试时暂时忽略。
var url =
Config.ApiMpHost + "/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
var t1 = Task.Factory.StartNew(async delegate { await Run(url); });
var t2 = Task.Factory.StartNew(delegate { Run(url); });
var t3 = Task.Factory.StartNew(delegate { Run(url); });
var t4 = Task.Factory.StartNew(delegate { Run(url); });
Console.WriteLine("Waiting...");
Task.WaitAll(t1, t2, t3, t4);
}
private async Task Run(string url)
{
Console.WriteLine("Start Task.CurrentId:{0},Time:{1}", Task.CurrentId, SystemTime.Now.Ticks);
try
{
//这里因为参数错误,系统会返回错误信息
WxJsonResult resultFail = await Senparc.CO2NET.HttpUtility.Get.GetJsonAsync<WxJsonResult>(url);
Assert.Fail(); //上一步就应该已经抛出异常
}
catch (ErrorJsonResultException ex)
{
//实际返回的信息(错误信息)
Assert.AreEqual(ex.JsonResult.errcode, ReturnCode.不合法的APPID);
Console.WriteLine("End Task.CurrentId:{0},Time:{1}", Task.CurrentId, SystemTime.Now.Ticks);
}
}
}
}
| 36.233871 | 124 | 0.574672 | [
"Apache-2.0"
] | 370041597/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.WeixinTests/Utilities/HttpUtility/GetTests.cs | 4,891 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mocean.Voice.McObj
{
public class Collect : AbstractMc
{
public string EventUrl { set => this.requestData["event-url"] = value; get => this.requestData["event-url"].ToString(); }
public int Min { set => this.requestData["min"] = value; get => (int)this.requestData["min"]; }
public int Max { set => this.requestData["max"] = value; get => (int)this.requestData["max"]; }
public string Terminators { set => this.requestData["terminators"] = value; get => this.requestData["terminators"].ToString(); }
public int Timeout { set => this.requestData["timeout"] = value; get => (int)this.requestData["timeout"]; }
public Collect() : this(new Dictionary<string, object>())
{
}
public Collect(Dictionary<string, object> parameter) : base(parameter)
{
}
protected override List<string> RequiredKey()
{
return new List<string>
{
"event-url", "min", "max", "timeout"
};
}
protected override string Action()
{
return "collect";
}
}
}
| 32.461538 | 136 | 0.587678 | [
"MIT"
] | MoceanAPI/mocean-sdk-dotnet | Mocean/Voice/McObj/Collect.cs | 1,268 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Cunning_Linguist
{
public class Linguist
{
private Dictionary<string, int> _words;
public Linguist()
{
_words = ReadWordsFromFile("wordlist.txt");
Score();
}
public void Process(string[] FixedLetters, string GoodLetters, string BadLetters)
{
var fixedLettersString = string.Join("", FixedLetters);
foreach (var word in _words)
{
_words[word.Key] = 1;
}
if (string.IsNullOrWhiteSpace(GoodLetters) && string.IsNullOrWhiteSpace(BadLetters) && string.IsNullOrWhiteSpace(fixedLettersString))
{
Score();
return;
}
var knownTokens = GoodLetters.ToLower().OrderBy(x => x).Distinct().ToList();
var badTokens = BadLetters.ToLower().OrderBy(x => x).Distinct().Where(w => !knownTokens.Contains(w)).ToList();
foreach (var token in badTokens)
{
foreach (var word in _words.Where(w => w.Value > 0))
{
if (word.Key.Contains(token))
{
_words[word.Key] = 0;
}
}
}
foreach (var token in knownTokens)
{
foreach (var word in _words.Where(w => w.Value > 0))
{
if (!word.Key.Contains(token))
{
_words[word.Key] = 0;
}
}
}
for (int i = 0; i < 5; i++)
{
if (string.IsNullOrEmpty(FixedLetters[i]))
{
continue;
}
foreach (var word in _words.Where(w => w.Value > 0))
{
var wordToken = word.Key[i].ToString();
if (wordToken != FixedLetters[i])
{
_words[word.Key] = 0;
}
else
{
_words[word.Key] = 1;
}
}
}
Score();
}
private void Score()
{
var words = _words.Where(w => w.Value > 0).ToList();
var tokenScores = new Dictionary<char, int>();
foreach (var word in words)
{
foreach (var token in word.Key)
{
if (tokenScores.ContainsKey(token))
{
tokenScores[token]++;
}
else
{
tokenScores[token] = 1;
}
}
}
foreach (var word in words)
{
var wordScore = 1;
var usedTokens = "";
foreach (var token in word.Key)
{
if (!usedTokens.Contains(token))
{
wordScore += tokenScores[token];
usedTokens += token;
}
}
_words[word.Key] = wordScore;
}
}
public string GetSuggestedWord()
{
var remainingWords = _words.Where(w => w.Value > 0).OrderByDescending(w => w.Value).ToList();
if (remainingWords.Count == 0)
{
return "None!";
}
else
{
return remainingWords[0].Key;
}
}
public string GetAllSuggestedWords()
{
return string.Join(", ", _words.Where(w => w.Value > 0).OrderByDescending(w => w.Value).Skip(1).Select(w => w.Key));
}
private Dictionary<string, int> ReadWordsFromFile(string fileName)
{
var words = File.ReadAllLines(fileName);
var dictionary = new Dictionary<string, int>();
foreach (var word in words)
{
dictionary[word] = 1;
}
return dictionary;
}
}
} | 28.751678 | 145 | 0.408964 | [
"MIT"
] | Tzarnal/Cunning-Linguist | Linguist.cs | 4,286 | C# |
using PiRhoSoft.Utilities.Editor;
using UnityEngine;
using UnityEngine.UIElements;
namespace PiRhoSoft.Utilities.Samples
{
public class SliderCodeSample : CodeSample
{
public override void Create(VisualElement root)
{
var ratingSlider = new SliderFloatField("Rating", -10, 10);
ratingSlider.value = 0;
ratingSlider.RegisterValueChangedCallback(evt => Debug.Log($"Rating changed to {evt.newValue}"));
root.Add(ratingSlider);
var rangeSlider = new MinMaxSliderField("Range", -100, 100);
rangeSlider.value = new Vector2(ratingSlider.Minimum, ratingSlider.Maximum);
rangeSlider.RegisterValueChangedCallback(evt => { ratingSlider.Minimum = evt.newValue.x; ratingSlider.Maximum = evt.newValue.y; });
root.Add(rangeSlider);
}
}
}
| 33 | 134 | 0.753623 | [
"MIT"
] | janmikusch/PiRhoUtilities | Assets/PiRhoUtilities/Samples/PiRhoUtilitySamples/Scripts/Editor/Slider/SliderCodeSample.cs | 761 | C# |
// Copyright (c) Jeroen van Pienbroek. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using AdvancedInputFieldPlugin;
using UnityEngine;
using UnityEngine.UI;
namespace AdvancedInputFieldSamples
{
public class LoginView: MonoBehaviour
{
private ScrollRect scrollRect;
private AdvancedInputField emailInput;
private AdvancedInputField passwordInput;
private Button loginButton;
public string Email { get { return emailInput.Text; } }
public string Password { get { return passwordInput.Text; } }
private void Awake()
{
scrollRect = transform.Find("ScrollView").GetComponent<ScrollRect>();
Transform centerGroup = scrollRect.content.Find("CenterGroup");
emailInput = centerGroup.Find("Email").GetComponentInChildren<AdvancedInputField>();
passwordInput = centerGroup.Find("Password").GetComponentInChildren<AdvancedInputField>();
loginButton = centerGroup.Find("LoginButton").GetComponentInChildren<Button>();
}
private void OnEnable()
{
scrollRect.verticalNormalizedPosition = 1;
emailInput.Clear();
passwordInput.Clear();
loginButton.interactable = false;
}
public void EnableLoginButton()
{
loginButton.interactable = true;
}
public void DisableLoginButton()
{
loginButton.interactable = false;
}
public void ShowPassword()
{
passwordInput.VisiblePassword = true;
}
public void HidePassword()
{
passwordInput.VisiblePassword = false;
}
}
}
| 26.155172 | 101 | 0.748846 | [
"MIT"
] | Yunatan/AdvancedInputField | Assets/AdvancedInputField/Samples/Scripts/LoginView.cs | 1,519 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ClientScriptManager.Account {
public partial class AddPhoneNumber {
/// <summary>
/// ErrorMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ErrorMessage;
/// <summary>
/// PhoneNumber control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox PhoneNumber;
}
}
| 32.647059 | 84 | 0.501802 | [
"MIT"
] | donstany/Sand_Box | ClientScriptManager/Account/AddPhoneNumber.aspx.designer.cs | 1,112 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using EnterpriseLibrary.Common.Configuration;
using EnterpriseLibrary.TransientFaultHandling.Bvt.Tests.TestObjects;
using EnterpriseLibrary.TransientFaultHandling.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace EnterpriseLibrary.TransientFaultHandling.Bvt.Tests.Sql
{
[TestClass]
public class SqlDatabaseTransientErrorDetectionStrategyFixture
{
private readonly string connectionString = ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString;
private SystemConfigurationSource configurationSource;
private RetryPolicyConfigurationSettings retryPolicySettings;
private RetryManager retryManager;
[TestInitialize]
public void Initialize()
{
this.configurationSource = new SystemConfigurationSource();
this.retryPolicySettings = RetryPolicyConfigurationSettings.GetRetryPolicySettings(this.configurationSource);
this.retryManager = retryPolicySettings.BuildRetryManager();
}
[TestCleanup]
public void Cleanup()
{
if (this.configurationSource != null)
{
this.configurationSource.Dispose();
}
}
[TestMethod]
public void RetriesWhenSqlExceptionIsThrownWithTransportLevelError()
{
int executeCount = 0;
try
{
var retryPolicy = this.retryManager.GetRetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");
retryPolicy.ExecuteAction(() =>
{
executeCount++;
var ex = SqlExceptionCreator.CreateSqlException("A transport-level error has occurred when sending the request to the server", 10053);
throw ex;
});
Assert.Fail("Should have thrown SqlException");
}
catch (SqlException)
{ }
catch (Exception)
{
Assert.Fail("Should have thrown SqlException");
}
Assert.AreEqual(6, executeCount);
}
[TestMethod]
public void RetriesWhenSqlExceptionIsThrownWithNetworkLevelError()
{
int executeCount = 0;
try
{
var retryPolicy = this.retryManager.GetRetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");
retryPolicy.ExecuteAction(() =>
{
executeCount++;
var ex = SqlExceptionCreator.CreateSqlException("A network-related or instance-specific error occurred while establishing a connection to SQL Server.", 10054);
throw ex;
});
Assert.Fail("Should have thrown SqlException");
}
catch (SqlException)
{ }
catch (Exception)
{
Assert.Fail("Should have thrown SqlException");
}
Assert.AreEqual(6, executeCount);
}
[TestMethod]
public void DoesNotRetryWhenSqlExceptionIsThrownWithSqlQueryError()
{
int executeCount = 0;
try
{
var retryPolicy = this.retryManager.GetRetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");
retryPolicy.ExecuteAction(() =>
{
executeCount++;
var ex = SqlExceptionCreator.CreateSqlException("ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.", 104);
throw ex;
});
Assert.Fail("Should have thrown SqlException");
}
catch (SqlException)
{ }
catch (Exception)
{
Assert.Fail("Should have thrown SqlException");
}
Assert.AreEqual(1, executeCount);
}
[TestMethod]
public void RetriesWhenTimeoutExceptionIsThrown()
{
int executeCount = 0;
try
{
var retryPolicy = this.retryManager.GetRetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");
retryPolicy.ExecuteAction(() =>
{
executeCount++;
throw new TimeoutException();
});
Assert.Fail("Should have thrown TimeoutException");
}
catch (TimeoutException)
{ }
catch (Exception)
{
Assert.Fail("Should have thrown TimeoutException");
}
Assert.AreEqual(6, executeCount);
}
[TestMethod]
public void RetriesWhenEntityExceptionIsThrownWithTimeoutExceptionAsInnerException()
{
int executeCount = 0;
try
{
var retryPolicy = this.retryManager.GetRetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");
retryPolicy.ExecuteAction(() =>
{
executeCount++;
throw new EntityException("Sample Error", new TimeoutException("Connection Timed out"));
});
Assert.Fail("Should have thrown EntityException");
}
catch (EntityException ex)
{
Assert.IsInstanceOfType(ex.InnerException, typeof(TimeoutException));
}
catch (Exception)
{
Assert.Fail("Should have thrown EntityException");
}
Assert.AreEqual(6, executeCount);
}
}
}
| 34.32 | 187 | 0.573094 | [
"Apache-2.0"
] | EnterpriseLibrary/transient-fault-handling-application-block | BVT/TransientFaultHandling.BVT/Sql/SqlDatabaseTransientErrorDetectionStrategyFixture.cs | 6,008 | C# |
using CSESoftware.Repository.SqlBulkRepositoryCore.TestDatabase;
using CSESoftware.Repository.SqlBulkRepositoryCore.TestProject.Setup;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace CSESoftware.Repository.SqlBulkRepositoryCore.TestProject
{
public class UpdateTests : BaseTest
{
[Fact]
public async Task UpdateGenderTest()
{
const string gender = "Passion Fruit";
var trees = await TreeStartUpAsync();
var operationValues = trees.Select(x => new { x.Id, Gender = gender }).ToList();
await Repository.BulkUpdateAsync(new FamilyTree(), operationValues);
var returnValues = await GetUpdatedTreeValuesAsync(operationValues);
Assert.NotNull(returnValues);
Assert.NotEmpty(returnValues);
foreach (var tree in trees)
{
Assert.True(returnValues.ContainsKey(tree.Id));
Assert.Equal(gender, returnValues[tree.Id].Gender);
}
await TearDownAsync(trees);
}
[Fact]
public async Task UpdateIsAliveTest()
{
var trees = await TreeStartUpAsync();
var operationValues = trees.Select(x => new { x.Id, IsAlive = false }).ToList();
await Repository.BulkUpdateAsync(new FamilyTree(), operationValues);
var returnValues = await GetUpdatedTreeValuesAsync(operationValues);
Assert.NotNull(returnValues);
Assert.NotEmpty(returnValues);
foreach (var tree in trees)
{
Assert.True(returnValues.ContainsKey(tree.Id));
Assert.False(returnValues[tree.Id].IsAlive);
}
await TearDownAsync(trees);
}
[Fact]
public async Task UpdateBirthdateTest()
{
var birthdate = DateTime.UtcNow - TimeSpan.FromDays(4721);
var trees = await TreeStartUpAsync();
var operationValues = trees.Select(x => new { x.Id, Birthdate = birthdate }).ToList();
await Repository.BulkUpdateAsync(new FamilyTree(), operationValues);
var returnValues = await GetUpdatedTreeValuesAsync(operationValues);
Assert.NotNull(returnValues);
Assert.NotEmpty(returnValues);
foreach (var tree in trees)
{
Assert.True(returnValues.ContainsKey(tree.Id));
Assert.Equal(birthdate, returnValues[tree.Id].Birthdate);
}
await TearDownAsync(trees);
}
[Fact]
public async Task UpdateFatherIdTest()
{
var fatherId = Guid.NewGuid();
var father = new FamilyTree { Id = fatherId };
var trees = await TreeStartUpAsync(father);
var operationValues = trees.Select(x => new { x.Id, FatherId = fatherId }).ToList();
await Repository.BulkUpdateAsync(new FamilyTree(), operationValues);
var returnValues = await GetUpdatedTreeValuesAsync(operationValues);
Assert.NotNull(returnValues);
Assert.NotEmpty(returnValues);
foreach (var tree in trees)
{
Assert.True(returnValues.ContainsKey(tree.Id));
Assert.Equal(fatherId, returnValues[tree.Id].FatherId);
}
await TearDownAsync(trees);
}
[Fact]
public async Task UpdateMismatchedColumnTest()
{
const string name = "Bob's Home";
var homes = await HomeStartUpAsync();
var operationValues = homes.Select(x => new { x.Id, Name = name }).ToList();
await Repository.BulkUpdateAsync(new FamilyHome(), operationValues);
var returnValues = await GetUpdatedHomeValuesAsync(operationValues);
Assert.NotNull(returnValues);
Assert.NotEmpty(returnValues);
foreach (var home in homes)
{
Assert.True(returnValues.ContainsKey(home.Id));
Assert.Contains(name, returnValues[home.Id].Name);
}
await TearDownAsync(homes);
}
[Fact]
public async Task UpdateMismatchedColumnTest_WithIdColumnName()
{
const string address = "1918 Burbank";
var homes = await HomeStartUpAsync();
var operationValues = homes.Select(x => new { HomeId = x.Id, Address = address }).ToList();
await Repository.BulkUpdateAsync(new FamilyHome(), operationValues);
var returnValues = await GetUpdatedHomeValuesAsync(operationValues);
Assert.NotNull(returnValues);
Assert.NotEmpty(returnValues);
foreach (var home in homes)
{
Assert.True(returnValues.ContainsKey(home.Id));
Assert.Contains(address, returnValues[home.Id].Address);
}
await TearDownAsync(homes);
}
[Fact]
public async Task UpdateMismatchedColumnTest_WithUpdateColumnName()
{
const string address = "1918 Burbank";
var homes = await HomeStartUpAsync();
var operationValues = homes.Select(x => new { HomeId = x.Id, Home_Address = address }).ToList();
await Repository.BulkUpdateAsync(new FamilyHome(), operationValues);
var returnValues = await GetUpdatedHomeValuesAsync(operationValues);
Assert.NotNull(returnValues);
Assert.NotEmpty(returnValues);
foreach (var home in homes)
{
Assert.True(returnValues.ContainsKey(home.Id));
Assert.Contains(address, returnValues[home.Id].Address);
}
await TearDownAsync(homes);
}
private async Task<List<FamilyTree>> TreeStartUpAsync(FamilyTree father = null)
{
var trees = DataProvider.GetSimpleTrees(100);
if (father != null) trees.Add(father);
await Repository.BulkCreateAsync(trees);
return trees;
}
private async Task<Dictionary<Guid, FamilyTree>> GetUpdatedTreeValuesAsync<TObject>(
IReadOnlyCollection<TObject> operationValues)
{
var returnValues = await Repository.BulkSelectAsync(new FamilyTree(), operationValues);
return returnValues.ToDictionary(x => x.Id, x => x);
}
private async Task<List<FamilyHome>> HomeStartUpAsync()
{
var homes = DataProvider.GetSimpleHomes(100);
await Repository.BulkCreateAsync(homes);
return homes;
}
private async Task<Dictionary<Guid, FamilyHome>> GetUpdatedHomeValuesAsync<TObject>(
IReadOnlyCollection<TObject> operationValues)
{
var returnValues = await Repository.BulkSelectAsync(new FamilyHome(), operationValues);
return returnValues.ToDictionary(x => x.Id, x => x);
}
}
}
| 36.828125 | 108 | 0.602461 | [
"Apache-2.0"
] | CSESoftwareInc/Repository.SqlBulkRepositoryCore | src/CSESoftware.Repository.SqlBulkRepositoryCore.TestProject/UpdateTests.cs | 7,073 | C# |
using Esquio.UI.Api.Infrastructure.Data.DbContexts;
using Esquio.UI.Api.Shared.Models.Statistics.Plot;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
namespace Esquio.UI.Api.Scenarios.Statistics.Plot
{
public class PlotStatisticsRequestHandler
: IRequestHandler<PlotStatisticsRequest, PlotStatisticsResponse>
{
private readonly StoreDbContext _store;
private readonly ILogger<PlotStatisticsRequestHandler> _logger;
public PlotStatisticsRequestHandler(StoreDbContext store, ILogger<PlotStatisticsRequestHandler> logger)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<PlotStatisticsResponse> Handle(PlotStatisticsRequest request, CancellationToken cancellationToken)
{
using (var command = _store.Database.GetDbConnection().CreateCommand())
{
command.CommandText =
@$"
DECLARE @END DATETIME2 = GETDATE();
DECLARE @START DATETIME2 = DATEADD(HOUR, -24, @END);
WITH CTE_Dates AS
(
SELECT @START AS cte_date
UNION ALL
SELECT DATEADD(SECOND, 30, cte_date) AS cte_date
FROM CTE_Dates
WHERE cte_date <= @END
)
SELECT CTE_Dates.cte_date as {nameof(PlotPointStatisticsResponse.Date)}, COUNT(Metrics.Id) AS {nameof(PlotPointStatisticsResponse.Value)}
FROM CTE_Dates
LEFT JOIN Metrics
ON Metrics.[DateTime] BETWEEN cte_date AND DATEADD(SECOND, 30, cte_date)
GROUP BY cte_date
OPTION (MAXRECURSION 10000)
";
command.CommandType = CommandType.Text;
await command.Connection.OpenAsync();
using (var reader = await command.ExecuteReaderAsync(CommandBehavior.CloseConnection, cancellationToken))
{
var response = new PlotStatisticsResponse();
var points = new List<PlotPointStatisticsResponse>(capacity: 1200); //points over 12 hours each 30 seconds aprox
while (await reader.ReadAsync(cancellationToken))
{
var item = new PlotPointStatisticsResponse()
{
Date = reader.GetDateTime(reader.GetOrdinal(nameof(PlotPointStatisticsResponse.Date))),
Value = reader.GetInt32(reader.GetOrdinal(nameof(PlotPointStatisticsResponse.Value))),
};
points.Add(item);
}
response.Points = points;
return response;
}
}
}
}
}
| 38.118421 | 138 | 0.63583 | [
"Apache-2.0"
] | andrew-flatters-bliss/Esquio | src/Esquio.UI.Api/Scenarios/Statistics/Plot/PlotStatisticsRequestHandler.cs | 2,899 | C# |
namespace DotNetInterceptTester.My_System.IO.StreamReader
{
public class ReadLine_System_IO_StreamReader
{
public static bool _ReadLine_System_IO_StreamReader( )
{
//Parameters
//ReturnType/Value
System.String returnVal_Real = null;
System.String returnVal_Intercepted = null;
//Exception
Exception exception_Real = null;
Exception exception_Intercepted = null;
InterceptionMaintenance.disableInterception( );
try
{
returnValue_Real = System.IO.StreamReader.ReadLine();
}
catch( Exception e )
{
exception_Real = e;
}
InterceptionMaintenance.enableInterception( );
try
{
returnValue_Intercepted = System.IO.StreamReader.ReadLine();
}
catch( Exception e )
{
exception_Intercepted = e;
}
Return ( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
}
}
}
| 20.468085 | 127 | 0.676715 | [
"MIT"
] | SecurityInnovation/Holodeck | Test/Automation/DotNetInterceptTester/DotNetInterceptTester/System.IO.StreamReader.ReadLine().cs | 962 | C# |
using System.Collections.Generic;
using static LiteDB.Constants;
namespace LiteDB.Engine
{
/// <summary>
/// Implement basic document loader based on data service/bson reader
/// </summary>
internal class DatafileLookup : IDocumentLookup
{
protected readonly DataService _data;
protected readonly bool _utcDate;
protected readonly HashSet<string> _fields;
public DatafileLookup(DataService data, bool utcDate, HashSet<string> fields)
{
_data = data;
_utcDate = utcDate;
_fields = fields;
}
public virtual BsonDocument Load(IndexNode node)
{
ENSURE(node.DataBlock != PageAddress.Empty, "data block must be a valid block address");
return this.Load(node.DataBlock);
}
public virtual BsonDocument Load(PageAddress rawId)
{
using (var reader = new BufferReader(_data.Read(rawId), _utcDate))
{
var doc = reader.ReadDocument(_fields);
doc.RawId = rawId;
return doc;
}
}
}
} | 27.780488 | 100 | 0.592625 | [
"MIT"
] | 5118234/LiteDB | LiteDB/Engine/Query/Lookup/DatafileLookup.cs | 1,141 | C# |
using UnityEngine;
using System.Collections;
public class PipeCurvedOpened : PipeBehaviour {
// -------------------------------------------------------------------------------------
// Variables.
// -------------------------------------------------------------------------------------
private float minPosition = 0.1f;
private int density = 0; // Current density level.
private int densityMax = 0; // Maximum density of obstacles allowed.
private int unlocks = 0; // Determines which obstacles are unlocked.
private int random;
private float tempPosition = 0f;
private float tempRotation = 0f;
private int lastObstacle;
private float lastRotation;
public GameObject obsPC2;
public GameObject obsPC5;
public GameObject obsPC6;
private GameObject[] obstacles;
private int[] densities;
private float[] sizes;
private int[] indexes;
// -------------------------------------------------------------------------------------
// Upon creation, initialize the obstacles.
// -------------------------------------------------------------------------------------
void Awake(){
curved = true;
opened = true;
obstacles = new GameObject[3];
densities = new int[3];
sizes = new float[3];
indexes = new int[3];
obstacles[0] = obsPC2; densities[0] = 10; sizes[0] = 0.15f; indexes[0] = 1; // Should be put in a matrix, just sayin...
obstacles[1] = obsPC5; densities[1] = 75; sizes[1] = 0.3f; indexes[1] = 4;
obstacles[2] = obsPC6; densities[2] = 60; sizes[2] = 0.3f; indexes[2] = 5;
StartCoroutine(spawn(this.getObstaclesPool));
}
// -------------------------------------------------------------------------------------
// Obstacle strategy.
// -------------------------------------------------------------------------------------
private IEnumerator spawn(ObstaclesPooling obstaclesPool){
// Compute maximum density allowed based on the current speed (speed up => less obstacles).
densityMax = getDensity();
// Determine which obstacles are unlocked (based on distance travelled, progressively introduces obstacles).
unlocks = GameConfiguration.Instance.thresholdIndex > 4 ? 3 : GameConfiguration.Instance.thresholdIndex;
// Spawn strategy.
while(density < densityMax && minPosition < .8f){ // Synchronize progressive introduction of obstacles.
// Select obstacle and position.
random = (int) (Random.Range(0f, Mathf.Clamp(unlocks, 0, 3)));
switch (random){
case 0:
tempRotation = 90;
sizes[0] = Random.Range(.1f, .25f);
break;
case 1:
minPosition += .05f;
break;
default:
minPosition += .1f;
break;
}
// Spawn obstacle.
StartCoroutine(spawnObstacle(obstaclesPool, this, indexes[random], minPosition, new Vector3(0f, 0f, tempRotation)));
// Update strategy factors.
density += densities[random];
minPosition += sizes[random];
}
yield return null;
}
}
| 31.311828 | 124 | 0.563187 | [
"CC0-1.0"
] | ThomasRouvinez/InfiniteRacer | Assets/Scripts/Navigation/PipeCurvedOpened.cs | 2,914 | C# |
using OneSet.ViewModels;
using Xamarin.Forms;
namespace OneSet.Views
{
public class BasePage<T> : ContentPage where T : BaseViewModel
{
public T ViewModel { get; set; }
}
}
| 17.727273 | 66 | 0.666667 | [
"MIT"
] | vasileiossam/One-Set-To-Failure | OneSet/Views/BasePage.cs | 197 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d3d12umddi.h(12820,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct D3D12DDI_VIDEO_ENCODER_CODEC_PICTURE_CONTROL_SUPPORT_H264_0080_2
{
public uint MaxL0ReferencesForP;
public uint MaxL0ReferencesForB;
public uint MaxL1ReferencesForB;
public uint MaxLongTermReferences;
public uint MaxDPBCapacity;
}
}
| 31 | 91 | 0.72296 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/D3D12DDI_VIDEO_ENCODER_CODEC_PICTURE_CONTROL_SUPPORT_H264_0080_2.cs | 529 | C# |
using Homuai.Communication.Error;
using Homuai.Exception;
using Homuai.Exception.ExceptionsBase;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
namespace Homuai.Api.Filter
{
public class ExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if (context.Exception is HomuaiException)
HandleProjectException(context);
else
ThrowUnknowError(context);
}
private static void HandleProjectException(ExceptionContext context)
{
if (context.Exception is InvalidLoginException)
ThrowUnauthorized(context);
else
ThrowBadRequest(context);
}
private static void ThrowBadRequest(ExceptionContext context)
{
ErrorOnValidationException validacaoException = (ErrorOnValidationException)context.Exception;
context.Result = new BadRequestObjectResult(new ErrorJson(validacaoException.ErrorMensages));
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
private static void ThrowUnauthorized(ExceptionContext context)
{
context.Result = new UnauthorizedObjectResult(new ErrorJson(new List<string> { context.Exception.Message }));
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
private static void ThrowUnknowError(ExceptionContext context)
{
context.Result = new ObjectResult(new ErrorJson(new List<string> { ResourceTextException.UNKNOWN_ERROR }));
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
}
| 38 | 121 | 0.684211 | [
"Unlicense"
] | welissonArley/Homuai | scr/Backend/Homuai.Api/Filter/ExceptionFilter.cs | 1,788 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Data.SqlClient;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Relational;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Xunit;
namespace Microsoft.Data.Entity.SqlServer.Tests
{
public class SqlServerConnectionTest
{
[Fact]
public void Creates_SQL_Server_connection_string()
{
using (var connection = new SqlServerConnection(CreateConfiguration(), new ConnectionStringResolver(null)))
{
Assert.IsType<SqlConnection>(connection.DbConnection);
}
}
[Fact]
public void Can_create_master_connection_string()
{
using (var connection = new SqlServerConnection(CreateConfiguration(), new ConnectionStringResolver(null)))
{
using (var master = connection.CreateMasterConnection())
{
Assert.Equal(@"Data Source=""(localdb)11.0"";Initial Catalog=master;Integrated Security=True", master.ConnectionString);
}
}
}
public static DbContextConfiguration CreateConfiguration()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddEntityFramework().AddSqlServer();
return new DbContext(serviceCollection.BuildServiceProvider(),
new DbContextOptions()
.UseSqlServer("Server=(localdb)\v11.0;Database=SqlServerConnectionTest;Trusted_Connection=True;"))
.Configuration;
}
}
}
| 38.446809 | 141 | 0.66021 | [
"Apache-2.0"
] | MikaelEliasson/EntityFramework | test/EntityFramework.SqlServer.Tests/SqlServerConnectionTest.cs | 1,807 | C# |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993] for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
namespace System.Windows.Automation.Peers
{
/// <summary>
/// Exposes AutoCompleteBox types to UI Automation.
/// </summary>
/// <QualityBand>Stable</QualityBand>
public sealed class AutoCompleteBoxAutomationPeer : FrameworkElementAutomationPeer, IValueProvider, IExpandCollapseProvider, ISelectionProvider
{
/// <summary>
/// The name reported as the core class name.
/// </summary>
private const string AutoCompleteBoxClassNameCore = "AutoCompleteBox";
/// <summary>
/// Gets the AutoCompleteBox that owns this
/// AutoCompleteBoxAutomationPeer.
/// </summary>
private AutoCompleteBox OwnerAutoCompleteBox
{
get { return (AutoCompleteBox)Owner; }
}
/// <summary>
/// Gets a value indicating whether the UI automation provider allows
/// more than one child element to be selected concurrently.
/// </summary>
/// <remarks>
/// This API supports the .NET Framework infrastructure and is not
/// intended to be used directly from your code.
/// </remarks>
/// <value>True if multiple selection is allowed; otherwise, false.</value>
bool ISelectionProvider.CanSelectMultiple
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the UI automation provider
/// requires at least one child element to be selected.
/// </summary>
/// <remarks>
/// This API supports the .NET Framework infrastructure and is not
/// intended to be used directly from your code.
/// </remarks>
/// <value>True if selection is required; otherwise, false.</value>
bool ISelectionProvider.IsSelectionRequired
{
get { return false; }
}
/// <summary>
/// Initializes a new instance of the AutoCompleteBoxAutomationPeer
/// class.
/// </summary>
/// <param name="owner">
/// The AutoCompleteBox that is associated with this
/// AutoCompleteBoxAutomationPeer.
/// </param>
public AutoCompleteBoxAutomationPeer(AutoCompleteBox owner)
: base(owner)
{
}
/// <summary>
/// Gets the control type for the AutoCompleteBox that is associated
/// with this AutoCompleteBoxAutomationPeer. This method is called by
/// GetAutomationControlType.
/// </summary>
/// <returns>ComboBox AutomationControlType.</returns>
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.ComboBox;
}
/// <summary>
/// Gets the name of the AutoCompleteBox that is associated with this
/// AutoCompleteBoxAutomationPeer. This method is called by
/// GetClassName.
/// </summary>
/// <returns>The name AutoCompleteBox.</returns>
protected override string GetClassNameCore()
{
return AutoCompleteBoxClassNameCore;
}
/// <summary>
/// Gets the control pattern for the AutoCompleteBox that is associated
/// with this AutoCompleteBoxAutomationPeer.
/// </summary>
/// <param name="patternInterface">The desired PatternInterface.</param>
/// <returns>The desired AutomationPeer or null.</returns>
public override object GetPattern(PatternInterface patternInterface)
{
object iface = null;
AutoCompleteBox owner = OwnerAutoCompleteBox;
if (patternInterface == PatternInterface.Value)
{
iface = this;
}
else if (patternInterface == PatternInterface.ExpandCollapse)
{
iface = this;
}
else if (owner.SelectionAdapter != null)
{
AutomationPeer peer = owner.SelectionAdapter.CreateAutomationPeer();
if (peer != null)
{
iface = peer.GetPattern(patternInterface);
}
}
if (iface == null)
{
iface = base.GetPattern(patternInterface);
}
return iface;
}
#region ExpandCollapse
/// <summary>
/// Blocking method that returns after the element has been expanded.
/// </summary>
/// <remarks>
/// This API supports the .NET Framework infrastructure and is not
/// intended to be used directly from your code.
/// </remarks>
void IExpandCollapseProvider.Expand()
{
if (!IsEnabled())
{
throw new ElementNotEnabledException();
}
OwnerAutoCompleteBox.IsDropDownOpen = true;
}
/// <summary>
/// Blocking method that returns after the element has been collapsed.
/// </summary>
/// <remarks>
/// This API supports the .NET Framework infrastructure and is not
/// intended to be used directly from your code.
/// </remarks>
void IExpandCollapseProvider.Collapse()
{
if (!IsEnabled())
{
throw new ElementNotEnabledException();
}
OwnerAutoCompleteBox.IsDropDownOpen = false;
}
/// <summary>
/// Gets an element's current Collapsed or Expanded state.
/// </summary>
/// <remarks>
/// This API supports the .NET Framework infrastructure and is not
/// intended to be used directly from your code.
/// </remarks>
ExpandCollapseState IExpandCollapseProvider.ExpandCollapseState
{
get
{
return OwnerAutoCompleteBox.IsDropDownOpen ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed;
}
}
/// <summary>
/// Raises the ExpandCollapse automation event.
/// </summary>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
internal void RaiseExpandCollapseAutomationEvent(bool oldValue, bool newValue)
{
RaisePropertyChangedEvent(
ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty,
oldValue ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed,
newValue ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed);
}
#endregion ExpandCollapse
#region ValueProvider
/// <summary>
/// Sets the value of a control.
/// </summary>
/// <param name="value">The value to set. The provider is responsible
/// for converting the value to the appropriate data type.</param>
void IValueProvider.SetValue(string value)
{
OwnerAutoCompleteBox.Text = value;
}
/// <summary>
/// Gets a value indicating whether the value of a control is
/// read-only.
/// </summary>
/// <value>True if the value is read-only; false if it can be modified.</value>
bool IValueProvider.IsReadOnly
{
get
{
return !OwnerAutoCompleteBox.IsEnabled;
}
}
/// <summary>
/// Gets the value of the control.
/// </summary>
/// <value>The value of the control.</value>
string IValueProvider.Value
{
get
{
return OwnerAutoCompleteBox.Text ?? string.Empty;
}
}
#endregion
/// <summary>
/// Gets the collection of child elements of the AutoCompleteBox that
/// are associated with this AutoCompleteBoxAutomationPeer. This method
/// is called by GetChildren.
/// </summary>
/// <returns>
/// A collection of automation peer elements, or an empty collection
/// if there are no child elements.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Required by automation")]
protected override List<AutomationPeer> GetChildrenCore()
{
List<AutomationPeer> children = new List<AutomationPeer>();
AutoCompleteBox owner = OwnerAutoCompleteBox;
// TextBox part.
TextBox textBox = owner.TextBox;
if (textBox != null)
{
AutomationPeer peer = FrameworkElementAutomationPeer.CreatePeerForElement(textBox);
if (peer != null)
{
children.Insert(0, peer);
}
}
// Include SelectionAdapter's children.
if (owner.SelectionAdapter != null)
{
AutomationPeer selectionAdapterPeer = owner.SelectionAdapter.CreateAutomationPeer();
if (selectionAdapterPeer != null)
{
List<AutomationPeer> listChildren = selectionAdapterPeer.GetChildren();
if (listChildren != null)
{
foreach (AutomationPeer child in listChildren)
{
children.Add(child);
}
}
}
}
return children;
}
/// <summary>
/// Retrieves a UI automation provider for each child element that is
/// selected.
/// </summary>
/// <returns>An array of UI automation providers.</returns>
/// <remarks>
/// This API supports the .NET Framework infrastructure and is not
/// intended to be used directly from your code.
/// </remarks>
IRawElementProviderSimple[] ISelectionProvider.GetSelection()
{
if (OwnerAutoCompleteBox.SelectionAdapter != null)
{
object selectedItem = OwnerAutoCompleteBox.SelectionAdapter.SelectedItem;
if (selectedItem != null)
{
UIElement uie = selectedItem as UIElement;
if (uie != null)
{
AutomationPeer peer = FrameworkElementAutomationPeer.CreatePeerForElement(uie);
if (peer != null)
{
return new IRawElementProviderSimple[] { ProviderFromPeer(peer) };
}
}
}
}
return new IRawElementProviderSimple[] { };
}
}
} | 35.86859 | 147 | 0.561255 | [
"MIT"
] | danielhidalgojunior/zrageadminpanel | WpfToolkit/Input/AutoCompleteBox/System/Windows/Automation/Peers/AutoCompleteBoxAutomationPeer.cs | 11,193 | C# |
#if NETSTANDARD || NETFRAMEWORK
using Annex.Collections;
using NUnit.Framework;
using Shouldly;
using System;
using System.Collections.Generic;
namespace Annex.Test.Collections
{
public sealed class DictionaryExtensions_GetValueOrDefaultTest
{
[Test, AutoDomainData]
public void DefaultNullThisThrowsArgumentNullException(object key) =>
Should.Throw<ArgumentNullException>(() =>
default(IDictionary<object, object>).GetValueOrDefault(key))
.ParamName.ShouldBe("this");
[Test, AutoDomainData]
public void DefaultNullKeyThrowsArgumentNullException(IDictionary<object, object> sut) =>
Should.Throw<ArgumentNullException>(() => sut.GetValueOrDefault(null))
.ParamName.ShouldBe("key");
[Test, AutoDomainData]
public void DefaultExistingKeyReturnsValue(object key, object value) =>
new Dictionary<object, object> { { key, value } }
.GetValueOrDefault(key)
.ShouldBe(value);
[Test, AutoDomainData]
public void DefaultNoKeyReturnsDefaultValue(object key) =>
new Dictionary<object, object>()
.GetValueOrDefault(key)
.ShouldBeNull();
[Test, AutoDomainData]
public void NullThisThrowsArgumentNullException(object key, object defaultValue) =>
Should.Throw<ArgumentNullException>(() =>
default(IDictionary<object, object>).GetValueOrDefault(key, defaultValue))
.ParamName.ShouldBe("this");
[Test, AutoDomainData]
public void NullKeyThrowsArgumentNullException(IDictionary<object, object> sut, object defaultValue) =>
Should.Throw<ArgumentNullException>(() => sut.GetValueOrDefault(null, defaultValue))
.ParamName.ShouldBe("key");
[Test, AutoDomainData]
public void ExistingKeyReturnsValue(object key, object value, object defaultValue) =>
new Dictionary<object, object> { { key, value } }
.GetValueOrDefault(key, defaultValue)
.ShouldBe(value);
[Test, AutoDomainData]
public void NoKeyReturnsDefaultValue(object key, object defaultValue) =>
new Dictionary<object, object>()
.GetValueOrDefault(key, defaultValue)
.ShouldBe(defaultValue);
}
}
#endif
| 40.05 | 111 | 0.647108 | [
"MIT"
] | gtbuchanan/annex-net | test/Annex.Test/Collections/DictionaryExtensions_GetValueOrDefaultTest.cs | 2,403 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Specialized;
using System.Net;
using Newtonsoft.Json;
using QuantConnect.Configuration;
using QuantConnect.Logging;
using QuantConnect.Packets;
using RestSharp;
package com.quantconnect.lean.Messaging
{
/**
* Provides a common transmit method for utilizing the QC streaming API
*/
public static class StreamingApi
{
/**
* Gets a flag indicating whether or not the streaming api is enabled
*/
public static final boolean IsEnabled = Config.GetBool( "send-via-api");
// Client for sending asynchronous requests.
private static final RestClient Client = new RestClient( "http://streaming.quantconnect.com");
/**
* Send a message to the QuantConnect Chart Streaming API.
*/
* @param userId User Id
* @param apiToken API token for authentication
* @param packet Packet to transmit
public static void Transmit(int userId, String apiToken, Packet packet) {
try
{
tx = JsonConvert.SerializeObject(packet);
if( tx.Length > 10000) {
Log.Trace( "StreamingApi.Transmit(): Packet too long: " + packet.GetType());
return;
}
if( userId == 0) {
Log.Error( "StreamingApi.Transmit(): UserId is not set. Check your config.json file 'job-user-id' property.");
return;
}
if( apiToken.equals( "") {
Log.Error( "StreamingApi.Transmit(): API Access token not set. Check your config.json file 'api-access-token' property.");
return;
}
request = new RestRequest();
request.AddParameter( "uid", userId);
request.AddParameter( "token", apiToken);
request.AddParameter( "tx", tx);
Client.ExecuteAsyncPost(request, (response, handle) =>
{
try
{
result = JsonConvert.DeserializeObject<Response>(response.Content);
if( result.Type.equals( "error") {
Log.Error(new Exception(result.Message), "PacketType: " + packet.Type);
}
}
catch
{
Log.Error( "StreamingApi.Client.ExecuteAsyncPost(): Error deserializing JSON content.");
}
}, "POST");
}
catch (Exception err) {
Log.Error(err, "PacketType: " + packet.Type);
}
}
/**
* Response object from the Streaming API.
*/
private class Response
{
/**
* Class of response from the streaming api.
*/
* success or error
public String Type;
/**
* Message description of the error or success state.
*/
public String Message;
}
}
} | 37.057692 | 142 | 0.558381 | [
"Apache-2.0"
] | aricooperman/jLean | orig-src/Messaging/StreamingApi.cs | 3,856 | C# |
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using NadekoBot.Common.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Modules.Xp.Common;
using NadekoBot.Modules.Xp.Services;
using NadekoBot.Core.Services;
using NadekoBot.Core.Services.Database.Models;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Xp
{
public partial class Xp : NadekoTopLevelModule<XpService>
{
private readonly DiscordSocketClient _client;
private readonly DbService _db;
public Xp(DiscordSocketClient client, DbService db)
{
_client = client;
_db = db;
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Experience([Remainder]IUser user = null)
{
user = user ?? Context.User;
await Context.Channel.TriggerTypingAsync().ConfigureAwait(false);
var (img, fmt) = await _service.GenerateXpImageAsync((IGuildUser)user).ConfigureAwait(false);
using (img)
{
await Context.Channel.SendFileAsync(img, $"{Context.Guild.Id}_{user.Id}_xp.{fmt.FileExtensions.FirstOrDefault()}")
.ConfigureAwait(false);
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public Task XpLevelUpRewards(int page = 1)
{
page--;
if (page < 0 || page > 100)
return Task.CompletedTask;
var embed = new EmbedBuilder()
.WithTitle(GetText("level_up_rewards"))
.WithOkColor();
var rewards = _service.GetRoleRewards(Context.Guild.Id)
.OrderBy(x => x.Level)
.Select(x =>
{
var str = Context.Guild.GetRole(x.RoleId)?.ToString();
if (str != null)
str = GetText("role_reward", Format.Bold(str));
return (x.Level, RoleStr: str);
})
.Where(x => x.RoleStr != null)
.Concat(_service.GetCurrencyRewards(Context.Guild.Id)
.OrderBy(x => x.Level)
.Select(x => (x.Level, Format.Bold(x.Amount + Bc.BotConfig.CurrencySign))))
.GroupBy(x => x.Level)
.OrderBy(x => x.Key)
.Skip(page * 15)
.Take(15)
.ForEach(x => embed.AddField(GetText("level_x", x.Key), string.Join("\n", x.Select(y => y.Item2)), true));
if (!rewards.Any())
return Context.Channel.EmbedAsync(embed.WithDescription(GetText("no_level_up_rewards")));
return Context.Channel.EmbedAsync(embed);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireUserPermission(GuildPermission.ManageRoles)]
[RequireContext(ContextType.Guild)]
public async Task XpRoleReward(int level, [Remainder] IRole role = null)
{
if (level < 1)
return;
_service.SetRoleReward(Context.Guild.Id, level, role?.Id);
if (role == null)
await ReplyConfirmLocalized("role_reward_cleared", level).ConfigureAwait(false);
else
await ReplyConfirmLocalized("role_reward_added", level, Format.Bold(role.ToString())).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task XpCurrencyReward(int level, int amount = 0)
{
if (level < 1 || amount < 0)
return;
_service.SetCurrencyReward(Context.Guild.Id, level, amount);
if (amount == 0)
await ReplyConfirmLocalized("cur_reward_cleared", level, Bc.BotConfig.CurrencySign).ConfigureAwait(false);
else
await ReplyConfirmLocalized("cur_reward_added", level, Format.Bold(amount + Bc.BotConfig.CurrencySign)).ConfigureAwait(false);
}
public enum NotifyPlace
{
Server = 0,
Guild = 0,
Global = 1,
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task XpNotify(XpNotificationType type = XpNotificationType.Dm)
{
NotifyPlace place = NotifyPlace.Guild;
if (place == NotifyPlace.Guild)
await _service.ChangeNotificationType(Context.User.Id, Context.Guild.Id, type).ConfigureAwait(false);
//else
//await _service.ChangeNotificationType(Context.User, type).ConfigureAwait(false);
await ReplyConfirmLocalized("notify_type_changed").ConfigureAwait(false);
}
public enum Server { Server };
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task XpExclude(Server _)
{
var ex = _service.ToggleExcludeServer(Context.Guild.Id);
await ReplyConfirmLocalized((ex ? "excluded" : "not_excluded"), Format.Bold(Context.Guild.ToString())).ConfigureAwait(false);
}
public enum Role { Role };
[NadekoCommand, Usage, Description, Aliases]
[RequireUserPermission(GuildPermission.ManageRoles)]
[RequireContext(ContextType.Guild)]
public async Task XpExclude(Role _, [Remainder] IRole role)
{
var ex = _service.ToggleExcludeRole(Context.Guild.Id, role.Id);
await ReplyConfirmLocalized((ex ? "excluded" : "not_excluded"), Format.Bold(role.ToString())).ConfigureAwait(false);
}
public enum Channel { Channel };
[NadekoCommand, Usage, Description, Aliases]
[RequireUserPermission(GuildPermission.ManageChannels)]
[RequireContext(ContextType.Guild)]
public async Task XpExclude(Channel _, [Remainder] ITextChannel channel = null)
{
if (channel == null)
channel = (ITextChannel)Context.Channel;
var ex = _service.ToggleExcludeChannel(Context.Guild.Id, channel.Id);
await ReplyConfirmLocalized((ex ? "excluded" : "not_excluded"), Format.Bold(channel.ToString())).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task XpExclusionList()
{
var serverExcluded = _service.IsServerExcluded(Context.Guild.Id);
var roles = _service.GetExcludedRoles(Context.Guild.Id)
.Select(x => Context.Guild.GetRole(x)?.Name)
.Where(x => x != null);
var chans = (await Task.WhenAll(_service.GetExcludedChannels(Context.Guild.Id)
.Select(x => Context.Guild.GetChannelAsync(x)))
.ConfigureAwait(false))
.Where(x => x != null)
.Select(x => x.Name);
var embed = new EmbedBuilder()
.WithTitle(GetText("exclusion_list"))
.WithDescription((serverExcluded ? GetText("server_is_excluded") : GetText("server_is_not_excluded")))
.AddField(GetText("excluded_roles"), roles.Any() ? string.Join("\n", roles) : "-", false)
.AddField(GetText("excluded_channels"), chans.Any() ? string.Join("\n", chans) : "-", false)
.WithOkColor();
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public Task XpLeaderboard(int page = 1)
{
if (--page < 0 || page > 100)
return Task.CompletedTask;
return Context.SendPaginatedConfirmAsync(page, (curPage) =>
{
var users = _service.GetUserXps(Context.Guild.Id, curPage);
var embed = new EmbedBuilder()
.WithTitle(GetText("server_leaderboard"))
.WithFooter(GetText("page", curPage + 1))
.WithOkColor();
if (!users.Any())
return embed.WithDescription("-");
else
{
for (int i = 0; i < users.Length; i++)
{
var levelStats = LevelStats.FromXp(users[i].Xp + users[i].AwardedXp);
var user = ((SocketGuild)Context.Guild).GetUser(users[i].UserId);
var userXpData = users[i];
var awardStr = "";
if (userXpData.AwardedXp > 0)
awardStr = $"(+{userXpData.AwardedXp})";
else if (userXpData.AwardedXp < 0)
awardStr = $"({userXpData.AwardedXp.ToString()})";
embed.AddField(
$"#{(i + 1 + curPage * 9)} {(user?.ToString() ?? users[i].UserId.ToString())}",
$"{GetText("level_x", levelStats.Level)} - {levelStats.TotalXp}xp {awardStr}");
}
return embed;
}
}, 1000, 10, addPaginatedFooter: false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task XpGlobalLeaderboard(int page = 1)
{
if (--page < 0 || page > 100)
return;
var users = _service.GetUserXps(page);
var embed = new EmbedBuilder()
.WithTitle(GetText("global_leaderboard"))
.WithOkColor();
if (!users.Any())
embed.WithDescription("-");
else
{
for (int i = 0; i < users.Length; i++)
{
var user = users[i];
embed.AddField(
$"#{(i + 1 + page * 9)} {(user.ToString())}",
$"{GetText("level_x", LevelStats.FromXp(users[i].TotalXp).Level)} - {users[i].TotalXp}xp");
}
}
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task XpAdd(int amount, ulong userId)
{
if (amount == 0)
return;
_service.AddXp(userId, Context.Guild.Id, amount);
var usr = ((SocketGuild)Context.Guild).GetUser(userId)?.ToString()
?? userId.ToString();
await ReplyConfirmLocalized("modified", Format.Bold(usr), Format.Bold(amount.ToString())).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.Administrator)]
public Task XpAdd(int amount, [Remainder] IGuildUser user)
=> XpAdd(amount, user.Id);
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task XpTemplateReload()
{
_service.ReloadXpTemplate();
await Task.Delay(1000).ConfigureAwait(false);
await ReplyConfirmLocalized("template_reloaded").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task AddCard(IRole role, int image, [Remainder]string name)
{
_service.XpCardAdd(name, role.Id, image);
await ReplyConfirmLocalized("template_added").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task DelCard([Remainder]string name)
{
_service.XpCardDel(name);
await ReplyConfirmLocalized("template_deleted").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task AllCards()
{
var xpCards = _service.AllXpCard();
await Context.SendPaginatedConfirmAsync(0, (page) =>
{
var embed = new EmbedBuilder()
.WithOkColor()
.WithAuthor(name: GetText("all_templates"))
.WithDescription(string.Join("\n", xpCards
.Skip(page * 20)
.Take(20)
.Select(x =>
{
return $"**{x.Name}**";
})));
return embed;
}, 100, 20, false).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task SetCard([Remainder]string name)
{
using (var uow = _db.UnitOfWork)
{
var user = Context.User as IGuildUser;
if (name == "default")
{
_service.XpCardSetDefault(user.Id);
await ReplyConfirmLocalized("template_default", name).ConfigureAwait(false);
}
else
if (name == "Club")
{
var club = uow.Clubs.GetByMember(user.Id);
if (club.roleId == 0 || club.XpImageUrl == "")
{
await ReplyErrorLocalized("template_club_none").ConfigureAwait(false);
}
else
if (user.RoleIds.Contains(club.roleId))
{
_service.XpCardSetClub(user.Id, club.roleId);
await ReplyConfirmLocalized("template_set", name).ConfigureAwait(false);
}
else
{
await ReplyErrorLocalized("template_error", club.roleId).ConfigureAwait(false);
}
}
else
{
ulong roleId = uow.XpCards.GetXpCardRoleId(name);
if (roleId == 0)
{
await ReplyErrorLocalized("template_none").ConfigureAwait(false);
}
else
if (user.RoleIds.Contains(roleId))
{
_service.XpCardSet(user.Id, name);
await ReplyConfirmLocalized("template_set", name).ConfigureAwait(false);
}
else
{
await ReplyErrorLocalized("template_error", roleId).ConfigureAwait(false);
}
}
}
}
}
}
| 39.22108 | 142 | 0.539621 | [
"MIT"
] | ArhangelAgrail/AnileneBot | NadekoBot.Core/Modules/Xp/Xp.cs | 15,259 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AppContinuum
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
| 32.368421 | 123 | 0.645528 | [
"Apache-2.0"
] | sulmanraja/appcon2 | Applications/AppContinuum/Startup.cs | 1,232 | C# |
namespace JustGestures.WizardItems
{
partial class UC_W_activation
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lbl_typeOfWnd = new System.Windows.Forms.Label();
this.cB_wndHandle = new System.Windows.Forms.ComboBox();
this.nUD_deactivateTimeout = new System.Windows.Forms.NumericUpDown();
this.cB_sensitiveZone = new System.Windows.Forms.ComboBox();
this.lbl_deactivationTimeout = new System.Windows.Forms.Label();
this.lbl_sensitiveZone = new System.Windows.Forms.Label();
this.gB_gestureActivation = new System.Windows.Forms.GroupBox();
this.panel_control_prg = new System.Windows.Forms.Panel();
this.gB_description2 = new System.Windows.Forms.GroupBox();
this.rTB_controlPrg = new System.Windows.Forms.RichTextBox();
this.panel4 = new System.Windows.Forms.Panel();
this.panel_zone_and_timeout = new System.Windows.Forms.Panel();
this.gB_description1 = new System.Windows.Forms.GroupBox();
this.rTB_zoneTimeout = new System.Windows.Forms.RichTextBox();
this.panel2 = new System.Windows.Forms.Panel();
((System.ComponentModel.ISupportInitialize)(this.nUD_deactivateTimeout)).BeginInit();
this.gB_gestureActivation.SuspendLayout();
this.panel_control_prg.SuspendLayout();
this.gB_description2.SuspendLayout();
this.panel4.SuspendLayout();
this.panel_zone_and_timeout.SuspendLayout();
this.gB_description1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// lbl_typeOfWnd
//
this.lbl_typeOfWnd.AutoSize = true;
this.lbl_typeOfWnd.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl_typeOfWnd.Location = new System.Drawing.Point(13, 14);
this.lbl_typeOfWnd.Name = "lbl_typeOfWnd";
this.lbl_typeOfWnd.Size = new System.Drawing.Size(198, 13);
this.lbl_typeOfWnd.TabIndex = 16;
this.lbl_typeOfWnd.Text = "Control Program/Window which is";
//
// cB_wndHandle
//
this.cB_wndHandle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cB_wndHandle.FormattingEnabled = true;
this.cB_wndHandle.Location = new System.Drawing.Point(266, 11);
this.cB_wndHandle.Name = "cB_wndHandle";
this.cB_wndHandle.Size = new System.Drawing.Size(142, 21);
this.cB_wndHandle.TabIndex = 17;
//
// nUD_deactivateTimeout
//
this.nUD_deactivateTimeout.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.nUD_deactivateTimeout.Location = new System.Drawing.Point(266, 34);
this.nUD_deactivateTimeout.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.nUD_deactivateTimeout.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.nUD_deactivateTimeout.Name = "nUD_deactivateTimeout";
this.nUD_deactivateTimeout.Size = new System.Drawing.Size(142, 20);
this.nUD_deactivateTimeout.TabIndex = 15;
this.nUD_deactivateTimeout.Value = new decimal(new int[] {
350,
0,
0,
0});
//
// cB_sensitiveZone
//
this.cB_sensitiveZone.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cB_sensitiveZone.FormattingEnabled = true;
this.cB_sensitiveZone.Location = new System.Drawing.Point(266, 7);
this.cB_sensitiveZone.Name = "cB_sensitiveZone";
this.cB_sensitiveZone.Size = new System.Drawing.Size(142, 21);
this.cB_sensitiveZone.TabIndex = 14;
//
// lbl_deactivationTimeout
//
this.lbl_deactivationTimeout.AutoSize = true;
this.lbl_deactivationTimeout.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl_deactivationTimeout.Location = new System.Drawing.Point(13, 36);
this.lbl_deactivationTimeout.Name = "lbl_deactivationTimeout";
this.lbl_deactivationTimeout.Size = new System.Drawing.Size(161, 13);
this.lbl_deactivationTimeout.TabIndex = 13;
this.lbl_deactivationTimeout.Text = "Deactivation Timeout in ms";
//
// lbl_sensitiveZone
//
this.lbl_sensitiveZone.AutoSize = true;
this.lbl_sensitiveZone.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl_sensitiveZone.Location = new System.Drawing.Point(13, 10);
this.lbl_sensitiveZone.Name = "lbl_sensitiveZone";
this.lbl_sensitiveZone.Size = new System.Drawing.Size(92, 13);
this.lbl_sensitiveZone.TabIndex = 12;
this.lbl_sensitiveZone.Text = "Sensitive Zone";
//
// gB_gestureActivation
//
this.gB_gestureActivation.Controls.Add(this.panel_control_prg);
this.gB_gestureActivation.Controls.Add(this.panel_zone_and_timeout);
this.gB_gestureActivation.Dock = System.Windows.Forms.DockStyle.Fill;
this.gB_gestureActivation.Location = new System.Drawing.Point(0, 0);
this.gB_gestureActivation.Name = "gB_gestureActivation";
this.gB_gestureActivation.Size = new System.Drawing.Size(548, 378);
this.gB_gestureActivation.TabIndex = 18;
this.gB_gestureActivation.TabStop = false;
this.gB_gestureActivation.Text = "Gesture Activation";
//
// panel_control_prg
//
this.panel_control_prg.Controls.Add(this.gB_description2);
this.panel_control_prg.Controls.Add(this.panel4);
this.panel_control_prg.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel_control_prg.Location = new System.Drawing.Point(3, 230);
this.panel_control_prg.Name = "panel_control_prg";
this.panel_control_prg.Size = new System.Drawing.Size(542, 145);
this.panel_control_prg.TabIndex = 20;
//
// gB_description2
//
this.gB_description2.Controls.Add(this.rTB_controlPrg);
this.gB_description2.Dock = System.Windows.Forms.DockStyle.Fill;
this.gB_description2.Location = new System.Drawing.Point(0, 43);
this.gB_description2.Name = "gB_description2";
this.gB_description2.Size = new System.Drawing.Size(542, 102);
this.gB_description2.TabIndex = 1;
this.gB_description2.TabStop = false;
this.gB_description2.Text = "Description";
//
// rTB_controlPrg
//
this.rTB_controlPrg.BackColor = System.Drawing.SystemColors.Control;
this.rTB_controlPrg.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rTB_controlPrg.Dock = System.Windows.Forms.DockStyle.Fill;
this.rTB_controlPrg.Location = new System.Drawing.Point(3, 16);
this.rTB_controlPrg.Name = "rTB_controlPrg";
this.rTB_controlPrg.ReadOnly = true;
this.rTB_controlPrg.Size = new System.Drawing.Size(536, 83);
this.rTB_controlPrg.TabIndex = 0;
this.rTB_controlPrg.Text = "";
//
// panel4
//
this.panel4.Controls.Add(this.lbl_typeOfWnd);
this.panel4.Controls.Add(this.cB_wndHandle);
this.panel4.Dock = System.Windows.Forms.DockStyle.Top;
this.panel4.Location = new System.Drawing.Point(0, 0);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(542, 43);
this.panel4.TabIndex = 0;
//
// panel_zone_and_timeout
//
this.panel_zone_and_timeout.Controls.Add(this.gB_description1);
this.panel_zone_and_timeout.Controls.Add(this.panel2);
this.panel_zone_and_timeout.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_zone_and_timeout.Location = new System.Drawing.Point(3, 16);
this.panel_zone_and_timeout.Name = "panel_zone_and_timeout";
this.panel_zone_and_timeout.Size = new System.Drawing.Size(542, 214);
this.panel_zone_and_timeout.TabIndex = 19;
//
// gB_description1
//
this.gB_description1.Controls.Add(this.rTB_zoneTimeout);
this.gB_description1.Dock = System.Windows.Forms.DockStyle.Fill;
this.gB_description1.Location = new System.Drawing.Point(0, 63);
this.gB_description1.Name = "gB_description1";
this.gB_description1.Size = new System.Drawing.Size(542, 151);
this.gB_description1.TabIndex = 17;
this.gB_description1.TabStop = false;
this.gB_description1.Text = "Description";
//
// rTB_zoneTimeout
//
this.rTB_zoneTimeout.BackColor = System.Drawing.SystemColors.Control;
this.rTB_zoneTimeout.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rTB_zoneTimeout.Dock = System.Windows.Forms.DockStyle.Fill;
this.rTB_zoneTimeout.Location = new System.Drawing.Point(3, 16);
this.rTB_zoneTimeout.Name = "rTB_zoneTimeout";
this.rTB_zoneTimeout.ReadOnly = true;
this.rTB_zoneTimeout.Size = new System.Drawing.Size(536, 132);
this.rTB_zoneTimeout.TabIndex = 0;
this.rTB_zoneTimeout.Text = "";
//
// panel2
//
this.panel2.Controls.Add(this.lbl_sensitiveZone);
this.panel2.Controls.Add(this.cB_sensitiveZone);
this.panel2.Controls.Add(this.lbl_deactivationTimeout);
this.panel2.Controls.Add(this.nUD_deactivateTimeout);
this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(542, 63);
this.panel2.TabIndex = 16;
//
// UC_W_activation
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.gB_gestureActivation);
this.Name = "UC_W_activation";
this.Size = new System.Drawing.Size(548, 378);
((System.ComponentModel.ISupportInitialize)(this.nUD_deactivateTimeout)).EndInit();
this.gB_gestureActivation.ResumeLayout(false);
this.panel_control_prg.ResumeLayout(false);
this.gB_description2.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
this.panel_zone_and_timeout.ResumeLayout(false);
this.gB_description1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label lbl_typeOfWnd;
private System.Windows.Forms.ComboBox cB_wndHandle;
private System.Windows.Forms.NumericUpDown nUD_deactivateTimeout;
private System.Windows.Forms.ComboBox cB_sensitiveZone;
private System.Windows.Forms.Label lbl_deactivationTimeout;
private System.Windows.Forms.Label lbl_sensitiveZone;
private System.Windows.Forms.GroupBox gB_gestureActivation;
private System.Windows.Forms.Panel panel_control_prg;
private System.Windows.Forms.GroupBox gB_description2;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel_zone_and_timeout;
private System.Windows.Forms.GroupBox gB_description1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.RichTextBox rTB_controlPrg;
private System.Windows.Forms.RichTextBox rTB_zoneTimeout;
}
}
| 49.97786 | 182 | 0.621234 | [
"MIT"
] | mdzurenko/just-gestures | JustGestures/WizardItems/UC_W_activation.Designer.cs | 13,546 | C# |
// 《Learning Hard 学习笔记》代码
// http://www.ituring.com.cn/book/1604
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace LambdaExpression1
{
class Program
{
static void Main(string[] args)
{
// Lambda表达式的演变过程
// 下面是C# 1中创建委托实例的代码
Func<string, int> delegatetest1 = new Func<string, int>(Callbackmethod);
// C# 2中用匿名方法来创建委托实例,此时就不需要额外定义回调方法Callbackmethod
Func<string, int> delegatetest2 = delegate(string text)
{
return text.Length;
};
// C# 3中使用Lambda表达式来创建委托实例
Func<string, int> delegatetest3 = (string text) => text.Length;
// 可以省略参数类型string,把上面代码再简化为:
Func<string, int> delegatetest4 = (text) => text.Length;
// 此时可以把圆括号也省略,简化为:
Func<string, int> delegatetest = text => text.Length;
// 调用委托
Console.WriteLine("使用Lambda表达式返回字符串的长度为: " + delegatetest("learning hard"));
Console.Read();
}
// 回调方法
private static int Callbackmethod(string text)
{
return text.Length;
}
}
}
namespace LambdaExpression2
{
class Program
{
static void Main(string[] args)
{
// 新建一个button实例
Button button1 = new Button() {Text = "点击我"};
// C# 2中使用匿名方法来订阅事件
button1.Click += delegate(object sender, EventArgs e)
{
ReportEvent("Click事件", sender, e);
};
button1.KeyPress += delegate(object sender, KeyPressEventArgs e)
{
ReportEvent("KeyPress事件,即键盘按下事件", sender, e);
};
// C# 3Lambda表达式方式来订阅事件
button1.Click += (sender, e) => ReportEvent("Click事件", sender, e);
button1.KeyPress += (sender, e) => ReportEvent("KeyPress事件,即键盘按下事件", sender, e);
// C# 3中使用对象初始化器
Form form = new Form { Name = "在控制台中创建的窗体", AutoSize = true, Controls = { button1 } };
// 运行窗体
Application.Run(form);
}
// 记录事件的回调方法
private static void ReportEvent(string title, object sender, EventArgs e)
{
Console.WriteLine("发生的事件为:{0}", title);
Console.WriteLine("发生事件的对象为:{0}", sender);
Console.WriteLine("发生事件参数为: {0}", e.GetType());
Console.WriteLine();
Console.WriteLine();
}
} | 29.465116 | 98 | 0.544199 | [
"MIT"
] | imba-tjd/CSharp-Code-Repository | Sample/LambdaExpression.cs | 3,008 | C# |
using System;
using HotChocolate.Language;
using HotChocolate.Types;
using Snapshooter.Xunit;
using Xunit;
namespace HotChocolate.Data.Filters.Expressions
{
public class QueryableFilterVisitorEnumTests
: FilterVisitorTestBase
{
[Fact]
public void Create_EnumEqual_Expression()
{
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { eq: BAR }}");
ExecutorBuilder? tester = CreateProviderTester(new FooFilterInput());
// act
Func<Foo, bool>? func = tester.Build<Foo>(value);
// assert
var a = new Foo { BarEnum = FooEnum.BAR };
Assert.True(func(a));
var b = new Foo { BarEnum = FooEnum.BAZ };
Assert.False(func(b));
}
[Fact]
public void Create_EnumNotEqual_Expression()
{
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { neq: BAR }}");
ExecutorBuilder? tester = CreateProviderTester(new FooFilterInput());
// act
Func<Foo, bool>? func = tester.Build<Foo>(value);
// assert
var a = new Foo { BarEnum = FooEnum.BAZ };
Assert.True(func(a));
var b = new Foo { BarEnum = FooEnum.BAR };
Assert.False(func(b));
}
[Fact]
public void Create_EnumIn_Expression()
{
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { in: [BAZ, QUX] }}");
ExecutorBuilder? tester = CreateProviderTester(new FooFilterInput());
// act
Func<Foo, bool>? func = tester.Build<Foo>(value);
// assert
var a = new Foo { BarEnum = FooEnum.BAZ };
Assert.True(func(a));
var b = new Foo { BarEnum = FooEnum.BAR };
Assert.False(func(b));
}
[Fact]
public void Create_EnumNotIn_Expression()
{
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { nin: [BAZ, QUX] }}");
ExecutorBuilder? tester = CreateProviderTester(new FooFilterInput());
// act
Func<Foo, bool>? func = tester.Build<Foo>(value);
// assert
var a = new Foo { BarEnum = FooEnum.BAR };
Assert.True(func(a));
var b = new Foo { BarEnum = FooEnum.BAZ };
Assert.False(func(b));
}
[Fact]
public void Create_NullableEnumEqual_Expression()
{
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { eq: BAR }}");
ExecutorBuilder? tester = CreateProviderTester(new FooNullableFilterInput());
// act
Func<FooNullable, bool>? func = tester.Build<FooNullable>(value);
// assert
var a = new FooNullable { BarEnum = FooEnum.BAR };
Assert.True(func(a));
var b = new FooNullable { BarEnum = FooEnum.BAZ };
Assert.False(func(b));
var c = new FooNullable { BarEnum = null };
Assert.False(func(c));
}
[Fact]
public void Create_NullableEnumNotEqual_Expression()
{
// arrange
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { neq: BAR }}");
ExecutorBuilder? tester = CreateProviderTester(new FooNullableFilterInput());
// act
Func<FooNullable, bool>? func = tester.Build<FooNullable>(value);
// assert
var a = new FooNullable { BarEnum = FooEnum.BAZ };
Assert.True(func(a));
var b = new FooNullable { BarEnum = FooEnum.BAR };
Assert.False(func(b));
var c = new FooNullable { BarEnum = null };
Assert.True(func(c));
}
[Fact]
public void Create_NullableEnumIn_Expression()
{
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { in: [BAZ, QUX] }}");
ExecutorBuilder? tester = CreateProviderTester(new FooNullableFilterInput());
// act
Func<FooNullable, bool>? func = tester.Build<FooNullable>(value);
// assert
var a = new FooNullable { BarEnum = FooEnum.BAZ };
Assert.True(func(a));
var b = new FooNullable { BarEnum = FooEnum.BAR };
Assert.False(func(b));
var c = new FooNullable { BarEnum = null };
Assert.False(func(c));
}
[Fact]
public void Create_NullableEnumNotIn_Expression()
{
// arrange
IValueNode? value = Utf8GraphQLParser.Syntax.ParseValueLiteral(
"{ barEnum: { nin: [BAZ, QUX] }}");
ExecutorBuilder? tester = CreateProviderTester(new FooNullableFilterInput());
// act
Func<FooNullable, bool>? func = tester.Build<FooNullable>(value);
// assert
var a = new FooNullable { BarEnum = FooEnum.BAR };
Assert.True(func(a));
var b = new FooNullable { BarEnum = FooEnum.BAZ };
Assert.False(func(b));
var c = new FooNullable { BarEnum = null };
Assert.True(func(c));
}
[Fact]
public void Overwrite_Enum_Filter_Type_With_Attribute()
{
// arrange
// act
ISchema schema = CreateSchema(new FilterInputType<EntityWithTypeAttribute>());
// assert
schema.ToString().MatchSnapshot();
}
public class Foo
{
public FooEnum BarEnum { get; set; }
}
public class FooNullable
{
public FooEnum? BarEnum { get; set; }
}
public enum FooEnum
{
FOO,
BAR,
BAZ,
QUX
}
public class FooFilterInput
: FilterInputType<Foo>
{
}
public class FooNullableFilterInput
: FilterInputType<FooNullable>
{
}
public class EntityWithTypeAttribute
{
[GraphQLType(typeof(IntType))]
public short? BarEnum { get; set; }
}
public class Entity
{
public short? BarEnum { get; set; }
}
}
} | 29.165217 | 90 | 0.522063 | [
"MIT"
] | Asshiah/hotchocolate | src/HotChocolate/Data/test/Data.Filters.Tests/Expression/QueryableFilterVisitorEnumTests.cs | 6,710 | C# |
namespace Lpp.Dns.Data.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Lpp.Dns.Data.DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
CommandTimeout = Int32.MaxValue;
}
protected override void Seed(Lpp.Dns.Data.DataContext context)
{
}
}
}
| 25.454545 | 93 | 0.630357 | [
"Apache-2.0"
] | Missouri-BMI/popmednet | Lpp.Dns.Data/Migrations/Configuration.cs | 560 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DBreeze;
using DBreeze.DataTypes;
using NBitcoin;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Utilities;
namespace Stratis.Bitcoin.Base
{
public interface IChainRepository : IDisposable
{
Task LoadAsync(ConcurrentChain chain);
Task SaveAsync(ConcurrentChain chain);
}
public class ChainRepository : IChainRepository
{
/// <summary>Access to DBreeze database.</summary>
private readonly DBreezeEngine dbreeze;
private BlockLocator locator;
public ChainRepository(string folder)
{
Guard.NotEmpty(folder, nameof(folder));
this.dbreeze = new DBreezeEngine(folder);
}
public ChainRepository(DataFolder dataFolder)
: this(dataFolder.ChainPath)
{
}
public Task LoadAsync(ConcurrentChain chain)
{
Guard.Assert(chain.Tip == chain.Genesis);
Task task = Task.Run(() =>
{
using (DBreeze.Transactions.Transaction transaction = this.dbreeze.GetTransaction())
{
transaction.ValuesLazyLoadingIsOn = false;
ChainedBlock tip = null;
Row<int, BlockHeader> firstRow = transaction.Select<int, BlockHeader>("Chain", 0);
if (!firstRow.Exists)
return;
BlockHeader previousHeader = firstRow.Value;
Guard.Assert(previousHeader.GetHash(NetworkOptions.TemporaryOptions) == chain.Genesis.HashBlock); // can't swap networks
foreach (Row<int, BlockHeader> row in transaction.SelectForwardSkip<int, BlockHeader>("Chain", 1))
{
if ((tip != null) && (previousHeader.HashPrevBlock != tip.HashBlock))
break;
tip = new ChainedBlock(previousHeader, row.Value.HashPrevBlock, tip);
previousHeader = row.Value;
}
if (previousHeader != null)
tip = new ChainedBlock(previousHeader, previousHeader.GetHash(NetworkOptions.TemporaryOptions), tip);
if (tip == null)
return;
this.locator = tip.GetLocator();
chain.SetTip(tip);
}
});
return task;
}
public Task SaveAsync(ConcurrentChain chain)
{
Guard.NotNull(chain, nameof(chain));
Task task = Task.Run(() =>
{
using (DBreeze.Transactions.Transaction transaction = this.dbreeze.GetTransaction())
{
ChainedBlock fork = this.locator == null ? null : chain.FindFork(this.locator);
ChainedBlock tip = chain.Tip;
ChainedBlock toSave = tip;
List<ChainedBlock> blocks = new List<ChainedBlock>();
while (toSave != fork)
{
blocks.Add(toSave);
toSave = toSave.Previous;
}
// DBreeze is faster on ordered insert.
IOrderedEnumerable<ChainedBlock> orderedChainedBlocks = blocks.OrderBy(b => b.Height);
foreach (ChainedBlock block in orderedChainedBlocks)
{
transaction.Insert("Chain", block.Height, block.Header);
}
this.locator = tip.GetLocator();
transaction.Commit();
}
});
return task;
}
/// <inheritdoc />
public void Dispose()
{
this.dbreeze?.Dispose();
}
}
}
| 32.545455 | 140 | 0.524632 | [
"MIT"
] | MIPPL/StratisBitcoinFullNode | src/Stratis.Bitcoin/Base/ChainRepository.cs | 3,940 | C# |
using System;
using System.Windows.Forms;
namespace CarRentalFormsRestHost
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
} | 23.894737 | 65 | 0.592511 | [
"MIT"
] | TeknikhogskolanGothenburg/WCFMorgan | CarRentalFormsRestHost/Program.cs | 456 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace TollByRsu.Model
{
public class CommIO_PcRsu_Tcp : CommIO_PcRsu
{
#region constructor
public CommIO_PcRsu_Tcp()
{
_s = new Socket(SocketType.Stream, ProtocolType.Tcp);
}
#endregion
#region dada
private Socket _s;
public Socket sClient { get { return _s; } }
//RSU地址 IP地址+端口号;默认为192.168.9.159:21003
private IPAddress _TheIpAddress = IPAddress.Parse("192.168.9.159");
public IPAddress TheIpAddress
{
get { return _TheIpAddress; }
set { if (value == _TheIpAddress) return; _TheIpAddress = value; }
}
private int _ThePort = 21003;
public int ThePort
{
get { return _ThePort; }
set { if (value == _ThePort) return; _ThePort = value; }
}
#endregion
public override string DisplayName
{
get
{
return "TCP/IP";
}
}
public override void Conn()
{
if (_s.Connected) { throw new Exception("already connected, please disconn first"); }
_s = new Socket(SocketType.Stream, ProtocolType.Tcp);
_s.Connect(TheIpAddress, ThePort);
}
public override void DisConn()
{
if (_s.Connected)
{
//_s.Disconnect(false);
//_s.Dispose();
_s.Close();
}
}
public override bool IsConn
{
get
{
return sClient.Connected;
}
}
public override int SendTimeOut
{
get
{
return _s.SendTimeout;
}
set
{
_s.SendTimeout = value;
}
}
public override int ReceiveTimeOut
{
get
{
return _s.ReceiveTimeout;
}
set
{
_s.ReceiveTimeout = value;
}
}
private byte[] _recvBuffer = new byte[1024];
public override void Receive(out byte[] buffer)
{
int n = _s.Receive(_recvBuffer);
base.PcRsuFrameUp(_recvBuffer, 0, n, out buffer);
}
public override void Send(byte[] sendBuff, int index, int count)
{
byte[] dest;
base.PcRsuFrameDown(sendBuff, index, count, out dest);
if (dest == null) return;
_s.Send(dest);
}
public override void ClearReceiveBuffer()
{
return;
}
}
}
| 22.359375 | 97 | 0.486373 | [
"MIT"
] | sqf-ice/toll_by_rsu | TollByRsu/TollByRsu/Model/CommIO_PcRsu_Tcp.cs | 2,888 | C# |
namespace BaristaLabs.Skrapr.Extensions
{
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dom = ChromeDevTools.DOM;
/// <summary>
/// Contains common helper methods for the DOM Adapter.
/// </summary>
public static class DOMAdapterExtensions
{
/// <summary>
/// Returns the box model for the given node id.
/// </summary>
/// <param name="domAdapter"></param>
/// <param name="nodeId"></param>
/// <returns></returns>
public static async Task<Dom.BoxModel> GetBoxModel(this Dom.DOMAdapter domAdapter, long nodeId)
{
var result = await domAdapter.Session.DOM.GetBoxModel(new Dom.GetBoxModelCommand
{
NodeId = nodeId
});
if (result == null)
return null;
return result.Model;
}
/// <summary>
/// Returns the document node.
/// </summary>
/// <param name="domAdapter"></param>
/// <param name="depth"></param>
/// <param name="pierce"></param>
/// <returns></returns>
public static async Task<Dom.Node> GetDocument(this Dom.DOMAdapter domAdapter, long depth = 1, bool pierce = false)
{
var response = await domAdapter.Session.SendCommand<Dom.GetDocumentCommand, Dom.GetDocumentCommandResponse>(new Dom.GetDocumentCommand
{
Depth = depth,
Pierce = pierce
});
return response.Root;
}
/// <summary>
/// Gets the highlight object corresponding to the node id
/// </summary>
/// <remarks>
/// It doesn't appear that this api is all that reliable. Often it reports nodeids cannot be found, also
/// the objects that it returns are 1 px in width/height.
/// </remarks>
/// <param name="domAdapter"></param>
/// <param name="nodeId"></param>
/// <returns></returns>
public static async Task<HighlightObject> GetHighlightObjectForTest(this Dom.DOMAdapter domAdapter, long nodeId)
{
var highlightNode = await domAdapter.Session.DOM.GetHighlightObjectForTest(new Dom.GetHighlightObjectForTestCommand
{
NodeId = nodeId
});
var data = highlightNode.Highlight as JObject;
if (data == null)
throw new InvalidOperationException($"No Highlight Object was returned for nodeId {nodeId}");
return data.ToObject<HighlightObject>();
}
/// <summary>
/// Returns the node id for the given css selector. Value will be less than 1 if selector does not correspond to a dom element.
/// </summary>
/// <param name="cssSelector"></param>
/// <returns></returns>
public static async Task<long> GetNodeIdForSelector(this Dom.DOMAdapter domAdapter, string cssSelector)
{
var document = await domAdapter.Session.DOM.GetDocument();
var domElement = await domAdapter.Session.DOM.QuerySelector(new Dom.QuerySelectorCommand
{
NodeId = document.NodeId,
Selector = cssSelector
});
return domElement.NodeId;
}
}
public class HighlightObject
{
[JsonProperty("displayAsMaterial")]
public bool DisplayAsMaterial
{
get;
set;
}
[JsonProperty("elementInfo")]
public HighlightObjectElementInfo ElementInfo
{
get;
set;
}
[JsonProperty("paths")]
public IList<HighlightObjectPath> Paths
{
get;
set;
}
[JsonProperty("showRulers")]
public bool ShowRulers
{
get;
set;
}
[JsonProperty("showExtensionLines")]
public bool ShowExtensionLines
{
get;
set;
}
/// <summary>
/// Gets the delta between this object being onscreen.
/// </summary>
/// <param name="pageDimensions"></param>
/// <returns></returns>
public Tuple<double, double> GetOnscreenDelta(PageDimensions pageDimensions)
{
var contentPath = Paths.FirstOrDefault(p => p.Name == "content");
var contentPathPoints = contentPath.GetQuad();
var targetClickRect = new Dom.Rect
{
X = contentPathPoints[0], // Relative X
Y = contentPathPoints[1], // Relative Y.
Width = ElementInfo.NodeWidth,
Height = ElementInfo.NodeHeight
};
var currentViewPort = new Dom.Rect
{
X = pageDimensions.ScrollX,
Y = pageDimensions.ScrollY,
Width = pageDimensions.WindowWidth,
Height = pageDimensions.WindowHeight
};
double deltaX, deltaY;
if (Math.Abs(targetClickRect.X) > pageDimensions.ScrollX &&
((Math.Abs(targetClickRect.X) + targetClickRect.Width) < (pageDimensions.ScrollX + pageDimensions.WindowWidth)))
deltaX = 0;
else
deltaX = targetClickRect.X;
if (Math.Abs(targetClickRect.Y) > pageDimensions.ScrollY &&
((Math.Abs(targetClickRect.Y) + targetClickRect.Height) < (pageDimensions.ScrollY + pageDimensions.WindowHeight)))
deltaY = 0;
else
deltaY = -(targetClickRect.Y);
return new Tuple<double, double>(deltaX, deltaY);
}
}
public class HighlightObjectElementInfo
{
[JsonProperty("tagName")]
public string TagName
{
get;
set;
}
[JsonProperty("idValue")]
public string IdValue
{
get;
set;
}
[JsonProperty("className")]
public string ClassName
{
get;
set;
}
[JsonProperty("nodeWidth")]
public double NodeWidth
{
get;
set;
}
[JsonProperty("nodeHeight")]
public double NodeHeight
{
get;
set;
}
}
public class HighlightObjectPath
{
[JsonProperty("fillColor")]
public string FillColor
{
get;
set;
}
[JsonProperty("name")]
public string Name
{
get;
set;
}
[JsonProperty("outlineColor")]
public string OutlineColor
{
get;
set;
}
[JsonProperty("path")]
public string[] Path
{
get;
set;
}
public double[] GetQuad()
{
var result = new List<double>();
foreach (var item in Path)
{
//Ignore the "M/L/Z" tokens for now..?
if (double.TryParse(item, out double itemDouble))
{
result.Add(itemDouble);
}
}
return result.ToArray();
}
public long[] GetLong()
{
var result = new List<long>();
foreach (var item in Path)
{
//Ignore the "M/L/Z" tokens for now..?
if (long.TryParse(item, out long itemLong))
{
result.Add(itemLong);
}
}
return result.ToArray();
}
}
}
| 28.143885 | 146 | 0.515082 | [
"MIT"
] | BaristaLabs/BaristaLabs.Skrapr | src/BaristaLabs.Skrapr.Core/Extensions/DOMAdapterExtensions.cs | 7,826 | C# |
//-----------------------------------------------------------------------
// <copyright file="TestProbeSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System.Collections.Generic;
using Akka.Actor;
using Xunit;
namespace Akka.TestKit.Tests.TestActorRefTests
{
public class TestProbeSpec : AkkaSpec
{
[Fact]
public void TestProbe_should_equal_underlying_Ref()
{
var p = CreateTestProbe();
p.Equals(p.Ref).ShouldBeTrue();
p.Ref.Equals(p).ShouldBeTrue();
var hs = new HashSet<IActorRef> {p, p.Ref};
hs.Count.ShouldBe(1);
}
/// <summary>
/// Should be able to receive a <see cref="Terminated"/> message from a <see cref="TestProbe"/>
/// if we're deathwatching it and it terminates.
/// </summary>
[Fact]
public void TestProbe_should_send_Terminated_when_killed()
{
var p = CreateTestProbe();
Watch(p);
Sys.Stop(p);
ExpectTerminated(p);
}
/// <summary>
/// If we deathwatch the underlying actor ref or TestProbe itself, it shouldn't matter.
///
/// They should be equivalent either way.
/// </summary>
[Fact]
public void TestProbe_underlying_Ref_should_be_equivalent_to_TestProbe()
{
var p = CreateTestProbe();
Watch(p.Ref);
Sys.Stop(p);
ExpectTerminated(p);
}
/// <summary>
/// Should be able to receive a <see cref="Terminated"/> message from a <see cref="TestProbe.Ref"/>
/// if we're deathwatching it and it terminates.
/// </summary>
[Fact]
public void TestProbe_underlying_Ref_should_send_Terminated_when_killed()
{
var p = CreateTestProbe();
Watch(p.Ref);
Sys.Stop(p.Ref);
ExpectTerminated(p.Ref);
}
}
}
| 32.940299 | 107 | 0.531038 | [
"Apache-2.0"
] | IgorFedchenko/akka.net | src/core/Akka.TestKit.Tests/TestActorRefTests/TestProbeSpec.cs | 2,209 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MSBDataSlave.Schema;
using MSBDataSlave.Data;
using SeaQuail.Data;
namespace SeaQuail_DiagramTool.Model
{
[SchemaHintTable(TableName = "DiagramUser")]
public class DGUser : DGBase<DGUser>
{
#region Properties
[SchemaHintColumn(Length = 250, Nullable = true)]
public string Name
{
get { return GetField("Name").AsString; }
set { SetField("Name", value); }
}
[SchemaHintColumn(Length = 250, Nullable = true)]
public string ExternalID
{
get { return GetField("ExternalID").AsString; }
set { SetField("ExternalID", value); }
}
#endregion
public static DGUser ByExternalID(string id)
{
List<DGUser> user = Select(new ORMCond("ExternalID", SQRelationOperators.Equal, id));
if (user.Count > 0)
{
return user[0];
}
return null;
}
public static DGUser ByName(string name)
{
List<DGUser> user = Select(new ORMCond("Name", SQRelationOperators.Equal, name));
if (user.Count > 0)
{
return user[0];
}
return null;
}
}
}
| 25.433962 | 97 | 0.549703 | [
"MIT"
] | gjcampbell/seaquail-legacy | sourceCode/SeaQuail_DiagramTool/Model/DGUser.cs | 1,350 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Modix.Data.Models.Core;
using Modix.Data.Repositories;
using Modix.Data.Test.TestData;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace Modix.Data.Test.Repositories
{
public class DesignatedChannelMappingRepositoryTests
{
#region Test Context
private static (ModixContext, DesignatedChannelMappingRepository) BuildTestContext()
{
var modixContext = TestDataContextFactory.BuildTestDataContext(x =>
{
x.Users.AddRange(Users.Entities.Clone());
x.GuildUsers.AddRange(GuildUsers.Entities.Clone());
x.GuildChannels.AddRange(GuildChannels.Entities.Clone());
x.DesignatedChannelMappings.AddRange(DesignatedChannelMappings.Entities.Clone());
x.ConfigurationActions.AddRange(ConfigurationActions.Entities.Where(y => !(y.DesignatedChannelMappingId is null)).Clone());
});
var uut = new DesignatedChannelMappingRepository(modixContext);
return (modixContext, uut);
}
#endregion Test Context
#region Constructor() Tests
[Test]
public void Constructor_Always_InvokesBaseConstructor()
{
(var modixContext, var uut) = BuildTestContext();
uut.ModixContext.ShouldBeSameAs(modixContext);
}
#endregion Constructor() Tests
#region BeginCreateTransactionAsync() Tests
[Test]
[NonParallelizable]
public async Task BeginCreateTransactionAsync_CreateTransactionIsInProgress_WaitsForCompletion()
{
(var modixContext, var uut) = BuildTestContext();
var existingTransaction = await uut.BeginCreateTransactionAsync();
var result = uut.BeginCreateTransactionAsync();
result.IsCompleted.ShouldBeFalse();
existingTransaction.Dispose();
(await result).Dispose();
}
[Test]
[NonParallelizable]
public async Task BeginCreateTransactionAsync_CreateTransactionIsNotInProgress_ReturnsImmediately()
{
(var modixContext, var uut) = BuildTestContext();
var result = uut.BeginCreateTransactionAsync();
result.IsCompleted.ShouldBeTrue();
(await result).Dispose();
}
[Test]
[NonParallelizable]
public async Task BeginCreateTransactionAsync_DeleteTransactionIsInProgress_ReturnsImmediately()
{
(var modixContext, var uut) = BuildTestContext();
var deleteTransaction = await uut.BeginDeleteTransactionAsync();
var result = uut.BeginCreateTransactionAsync();
result.IsCompleted.ShouldBeTrue();
deleteTransaction.Dispose();
(await result).Dispose();
}
[Test]
[NonParallelizable]
public async Task BeginCreateTransactionAsync_Always_TransactionIsForContextDatabase()
{
(var modixContext, var uut) = BuildTestContext();
var database = Substitute.ForPartsOf<DatabaseFacade>(modixContext);
modixContext.Database.Returns(database);
using (var transaction = await uut.BeginCreateTransactionAsync()) { }
await database.ShouldHaveReceived(1)
.BeginTransactionAsync();
}
#endregion BeginCreateTransactionAsync() Tests
#region BeginDeleteTransactionAsync() Tests
[Test]
[NonParallelizable]
public async Task BeginDeleteTransactionAsync_DeleteTransactionIsInProgress_WaitsForCompletion()
{
(var modixContext, var uut) = BuildTestContext();
var existingTransaction = await uut.BeginDeleteTransactionAsync();
var result = uut.BeginDeleteTransactionAsync();
result.IsCompleted.ShouldBeFalse();
existingTransaction.Dispose();
(await result).Dispose();
}
[Test]
[NonParallelizable]
public async Task BeginDeleteTransactionAsync_DeleteTransactionIsNotInProgress_ReturnsImmediately()
{
(var modixContext, var uut) = BuildTestContext();
var result = uut.BeginDeleteTransactionAsync();
result.IsCompleted.ShouldBeTrue();
(await result).Dispose();
}
[Test]
[NonParallelizable]
public async Task BeginDeleteTransactionAsync_CreateTransactionIsInProgress_ReturnsImmediately()
{
(var modixContext, var uut) = BuildTestContext();
var createTransaction = await uut.BeginCreateTransactionAsync();
var result = uut.BeginDeleteTransactionAsync();
result.IsCompleted.ShouldBeTrue();
createTransaction.Dispose();
(await result).Dispose();
}
[Test]
[NonParallelizable]
public async Task BeginDeleteTransactionAsync_Always_TransactionIsForContextDatabase()
{
(var modixContext, var uut) = BuildTestContext();
var database = Substitute.ForPartsOf<DatabaseFacade>(modixContext);
modixContext.Database.Returns(database);
using (var transaction = await uut.BeginDeleteTransactionAsync()) { }
await database.ShouldHaveReceived(1)
.BeginTransactionAsync();
}
#endregion BeginDeleteTransactionAsync() Tests
#region CreateAsync() Tests
[Test]
public async Task CreateAsync_DataIsNull_DoesNotUpdateDesignatedChannelMappingsAndThrowsException()
{
(var modixContext, var uut) = BuildTestContext();
await Should.ThrowAsync<ArgumentNullException>(uut.CreateAsync(null));
modixContext.DesignatedChannelMappings
.AsQueryable()
.Select(x => x.Id)
.ShouldBe(DesignatedChannelMappings.Entities.Select(x => x.Id));
modixContext.DesignatedChannelMappings.EachShould(x => x.ShouldNotHaveChanged());
await modixContext.ShouldNotHaveReceived()
.SaveChangesAsync();
}
[TestCaseSource(nameof(DesignatedChannelMappingCreationTestCases))]
public async Task CreateAsync_DataIsNotNull_InsertsDesignatedChannelMapping(DesignatedChannelMappingCreationData data)
{
(var modixContext, var uut) = BuildTestContext();
var id = await uut.CreateAsync(data);
modixContext.DesignatedChannelMappings.ShouldContain(x => x.Id == id);
var designatedChannelMapping = modixContext.DesignatedChannelMappings.First(x => x.Id == id);
designatedChannelMapping.GuildId.ShouldBe(data.GuildId);
designatedChannelMapping.Type.ShouldBe(data.Type);
designatedChannelMapping.ChannelId.ShouldBe(data.ChannelId);
designatedChannelMapping.CreateActionId.ShouldNotBeNull();
designatedChannelMapping.DeleteActionId.ShouldBeNull();
modixContext.DesignatedChannelMappings.Where(x => x.Id != designatedChannelMapping.Id).Select(x => x.Id).ShouldBe(DesignatedChannelMappings.Entities.Select(x => x.Id));
modixContext.DesignatedChannelMappings.Where(x => x.Id != designatedChannelMapping.Id).EachShould(x => x.ShouldNotHaveChanged());
modixContext.ConfigurationActions.ShouldContain(x => x.Id == designatedChannelMapping.CreateActionId);
var createAction = modixContext.ConfigurationActions.First(x => x.Id == designatedChannelMapping.CreateActionId);
createAction.GuildId.ShouldBe(data.GuildId);
createAction.Type.ShouldBe(ConfigurationActionType.DesignatedChannelMappingCreated);
createAction.Created.ShouldBeInRange(
DateTimeOffset.Now - TimeSpan.FromSeconds(1),
DateTimeOffset.Now + TimeSpan.FromSeconds(1));
createAction.CreatedById.ShouldBe(data.CreatedById);
createAction.ClaimMappingId.ShouldBeNull();
createAction.DesignatedChannelMappingId.ShouldBe(designatedChannelMapping.Id);
createAction.DesignatedRoleMappingId.ShouldBeNull();
modixContext.ConfigurationActions.Where(x => x.Id != createAction.Id).Select(x => x.Id).ShouldBe(ConfigurationActions.Entities.Where(x => !(x.DesignatedChannelMappingId is null)).Select(x => x.Id));
modixContext.ConfigurationActions.Where(x => x.Id != createAction.Id).EachShould(x => x.ShouldNotHaveChanged());
await modixContext.ShouldHaveReceived(2)
.SaveChangesAsync();
}
#endregion CreateAsync() Tests
#region AnyAsync() Tests
[TestCaseSource(nameof(ValidSearchCriteriaTestCases))]
public async Task AnyAsync_DesignatedChannelMappingsExist_ReturnsTrue(DesignatedChannelMappingSearchCriteria criteria)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.AnyAsync(criteria);
result.ShouldBeTrue();
}
[TestCaseSource(nameof(InvalidSearchCriteriaTestCases))]
public async Task AnyAsync_DesignatedChannelMappingsDoNotExist_ReturnsFalse(DesignatedChannelMappingSearchCriteria criteria)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.AnyAsync(criteria);
result.ShouldBeFalse();
}
#endregion AnyAsync() Tests
#region SearchChannelIdsAsync() Tests
[TestCaseSource(nameof(ValidSearchCriteriaAndResultIdsTestCases))]
public async Task SearchChannelIdsAsync_DesignatedChannelMappingsExist_ReturnsMatchingIds(DesignatedChannelMappingSearchCriteria criteria, long[] resultIds)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.SearchChannelIdsAsync(criteria);
result.ShouldNotBeNull();
result.ShouldBe(resultIds.Select(x => DesignatedChannelMappings.Entities.First(y => y.Id == x).ChannelId));
}
[TestCaseSource(nameof(InvalidSearchCriteriaTestCases))]
public async Task SearchChannelIdsAsync_DesignatedChannelMappingsDoNotExist_ReturnsEmpty(DesignatedChannelMappingSearchCriteria criteria)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.SearchChannelIdsAsync(criteria);
result.ShouldNotBeNull();
result.ShouldBeEmpty();
}
#endregion SearchChannelIdsAsync() Tests
#region SearchBriefsAsync() Tests
[TestCaseSource(nameof(ValidSearchCriteriaAndResultIdsTestCases))]
public async Task SearchBriefsAsync_DesignatedChannelMappingsExist_ReturnsMatchingBriefs(DesignatedChannelMappingSearchCriteria criteria, long[] resultIds)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.SearchBriefsAsync(criteria);
result.ShouldNotBeNull();
result.Select(x => x.Id).ShouldBe(resultIds);
result.EachShould(x => x.ShouldMatchTestData());
}
[TestCaseSource(nameof(InvalidSearchCriteriaTestCases))]
public async Task SearchBriefsAsync_DesignatedChannelMappingsDoNotExist_ReturnsEmpty(DesignatedChannelMappingSearchCriteria criteria)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.SearchBriefsAsync(criteria);
result.ShouldNotBeNull();
result.ShouldBeEmpty();
}
#endregion SearchBriefsAsync() Tests
#region DeleteAsync() Tests
[TestCaseSource(nameof(ValidSearchCriteriaAndValidUserIdAndResultIdsTestCases))]
public async Task DeleteAsync_DesignatedChannelMappingsAreNotDeleted_UpdatesDesignatedChannelMappingsAndReturnsCount(DesignatedChannelMappingSearchCriteria criteria, ulong deletedById, long[] designatedChannelMappingIds)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.DeleteAsync(criteria, deletedById);
result.ShouldBe(designatedChannelMappingIds
.Where(x => DesignatedChannelMappings.Entities
.Any(y => (y.Id == x) && (y.DeleteActionId == null)))
.Count());
modixContext.DesignatedChannelMappings
.AsQueryable()
.Select(x => x.Id)
.ShouldBe(DesignatedChannelMappings.Entities.Select(x => x.Id));
modixContext.DesignatedChannelMappings
.Where(x => designatedChannelMappingIds.Contains(x.Id) && (x.DeleteActionId == null))
.EachShould(entity =>
{
var originalEntity = DesignatedChannelMappings.Entities.First(x => x.Id == entity.Id);
entity.GuildId.ShouldBe(originalEntity.GuildId);
entity.ChannelId.ShouldBe(originalEntity.ChannelId);
entity.Type.ShouldBe(originalEntity.Type);
entity.CreateActionId.ShouldBe(originalEntity.CreateActionId);
entity.DeleteActionId.ShouldNotBeNull();
modixContext.ConfigurationActions.ShouldContain(x => x.Id == entity.DeleteActionId);
var deleteAction = modixContext.ConfigurationActions.First(x => x.Id == entity.DeleteActionId);
deleteAction.GuildId.ShouldBe(entity.GuildId);
deleteAction.Type.ShouldBe(ConfigurationActionType.DesignatedChannelMappingDeleted);
deleteAction.Created.ShouldBeInRange(
DateTimeOffset.Now - TimeSpan.FromMinutes(1),
DateTimeOffset.Now + TimeSpan.FromMinutes(1));
deleteAction.CreatedById.ShouldBe(deletedById);
deleteAction.ClaimMappingId.ShouldBeNull();
deleteAction.DesignatedChannelMappingId.ShouldBe(entity.Id);
deleteAction.DesignatedRoleMappingId.ShouldBeNull();
});
modixContext.DesignatedChannelMappings
.AsEnumerable()
.Where(x => !designatedChannelMappingIds.Contains(x.Id) || DesignatedChannelMappings.Entities
.Any(y => (y.Id == x.Id) && (x.DeleteActionId == null)))
.EachShould(x => x.ShouldNotHaveChanged());
modixContext.ConfigurationActions
.AsEnumerable()
.Where(x => DesignatedChannelMappings.Entities
.Any(y => (y.DeleteActionId == x.Id) && designatedChannelMappingIds.Contains(y.Id)))
.EachShould(x => x.ShouldNotHaveChanged());
await modixContext.ShouldHaveReceived(1)
.SaveChangesAsync();
}
[TestCaseSource(nameof(InvalidSearchCriteriaAndValidUserIdTestCases))]
public async Task DeleteAsync_DesignatedChannelMappingsDoNotExist_DoesNotUpdateDesignatedChannelMappingsAndReturns0(DesignatedChannelMappingSearchCriteria criteria, ulong deletedById)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.DeleteAsync(criteria, deletedById);
result.ShouldBe(0);
modixContext.DesignatedChannelMappings
.AsQueryable()
.Select(x => x.Id)
.ShouldBe(DesignatedChannelMappings.Entities
.Select(x => x.Id));
modixContext.DesignatedChannelMappings
.EachShould(x => x.ShouldNotHaveChanged());
modixContext.ConfigurationActions
.AsQueryable()
.Select(x => x.Id)
.ShouldBe(ConfigurationActions.Entities
.Where(x => x.DesignatedChannelMappingId != null)
.Select(x => x.Id));
modixContext.ConfigurationActions
.EachShould(x => x.ShouldNotHaveChanged());
await modixContext.ShouldHaveReceived(1)
.SaveChangesAsync();
}
#endregion DeleteAsync() Tests
#region TryDeleteAsync() Tests
[TestCaseSource(nameof(ActiveDesignatedChannelMappingAndValidUserIdTestCases))]
public async Task TryDeleteAsync_DesignatedChannelMappingIsNotDeleted_UpdatesDesignatedChannelMappingAndReturnsTrue(long designatedChannelMappingId, ulong deletedById)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.TryDeleteAsync(designatedChannelMappingId, deletedById);
result.ShouldBeTrue();
modixContext.DesignatedChannelMappings
.ShouldContain(x => x.Id == designatedChannelMappingId);
var designatedChannelMapping = modixContext.DesignatedChannelMappings
.First(x => x.Id == designatedChannelMappingId);
var originalDesignatedChannelMapping = DesignatedChannelMappings.Entities
.First(x => x.Id == designatedChannelMappingId);
designatedChannelMapping.GuildId.ShouldBe(originalDesignatedChannelMapping.GuildId);
designatedChannelMapping.ChannelId.ShouldBe(originalDesignatedChannelMapping.ChannelId);
designatedChannelMapping.Type.ShouldBe(originalDesignatedChannelMapping.Type);
designatedChannelMapping.CreateActionId.ShouldBe(originalDesignatedChannelMapping.CreateActionId);
designatedChannelMapping.DeleteActionId.ShouldNotBeNull();
modixContext.DesignatedChannelMappings
.AsQueryable()
.Select(x => x.Id)
.ShouldBe(DesignatedChannelMappings.Entities
.Select(x => x.Id));
modixContext.DesignatedChannelMappings
.Where(x => x.Id != designatedChannelMappingId)
.EachShould(x => x.ShouldNotHaveChanged());
modixContext.ConfigurationActions
.ShouldContain(x => x.Id == designatedChannelMapping.DeleteActionId);
var deleteAction = modixContext.ConfigurationActions
.First(x => x.Id == designatedChannelMapping.DeleteActionId);
deleteAction.GuildId.ShouldBe(designatedChannelMapping.GuildId);
deleteAction.Type.ShouldBe(ConfigurationActionType.DesignatedChannelMappingDeleted);
deleteAction.Created.ShouldBeInRange(
DateTimeOffset.Now - TimeSpan.FromSeconds(1),
DateTimeOffset.Now + TimeSpan.FromSeconds(1));
deleteAction.CreatedById.ShouldBe(deletedById);
deleteAction.ClaimMappingId.ShouldBeNull();
deleteAction.DesignatedChannelMappingId.ShouldBe(designatedChannelMapping.Id);
deleteAction.DesignatedRoleMappingId.ShouldBeNull();
modixContext.ConfigurationActions
.Where(x => x.Id != deleteAction.Id)
.Select(x => x.Id)
.ShouldBe(ConfigurationActions.Entities
.Where(x => !(x.DesignatedChannelMappingId is null))
.Select(x => x.Id));
modixContext.ConfigurationActions
.Where(x => x.Id != deleteAction.Id)
.EachShould(x => x.ShouldNotHaveChanged());
await modixContext.ShouldHaveReceived(1)
.SaveChangesAsync();
}
[TestCaseSource(nameof(DeletedDesignatedChannelMappingAndValidUserIdTestCases))]
[TestCaseSource(nameof(InvalidDesignatedChannelMappingAndValidUserIdTestCases))]
public async Task TryDeleteAsync_DesignatedChannelMappingIsDeleted_DoesNotUpdateDesignatedChannelMappingsAndReturnsFalse(long designatedChannelMappingId, ulong deletedById)
{
(var modixContext, var uut) = BuildTestContext();
var result = await uut.TryDeleteAsync(designatedChannelMappingId, deletedById);
result.ShouldBeFalse();
modixContext.DesignatedChannelMappings
.AsQueryable()
.Select(x => x.Id)
.ShouldBe(DesignatedChannelMappings.Entities
.Select(x => x.Id));
modixContext.DesignatedChannelMappings
.EachShould(x => x.ShouldNotHaveChanged());
modixContext.ConfigurationActions
.AsQueryable()
.Select(x => x.Id)
.ShouldBe(ConfigurationActions.Entities
.Where(x => !(x.DesignatedChannelMappingId is null))
.Select(x => x.Id));
modixContext.ConfigurationActions
.EachShould(x => x.ShouldNotHaveChanged());
await modixContext.ShouldNotHaveReceived()
.SaveChangesAsync();
}
#endregion TryDeleteAsync() Tests
#region Test Data
public static readonly IEnumerable<TestCaseData> DesignatedChannelMappingCreationTestCases
= DesignatedChannelMappings.Creations
.Select(x => new TestCaseData(x)
.SetName($"{{m}}({x.GuildId}, {x.ChannelId}, {x.Type})"));
public static readonly IEnumerable<TestCaseData> ValidSearchCriteriaTestCases
= DesignatedChannelMappings.Searches
.Where(x => x.resultIds.Any())
.Select(x => new TestCaseData(x.criteria)
.SetName($"{{m}}({x.name})"));
public static readonly IEnumerable<TestCaseData> ValidSearchCriteriaAndResultIdsTestCases
= DesignatedChannelMappings.Searches
.Where(x => x.resultIds.Any())
.Select(x => new TestCaseData(x.criteria, x.resultIds)
.SetName($"{{m}}({x.name})"));
public static readonly IEnumerable<TestCaseData> ValidSearchCriteriaAndValidUserIdAndResultIdsTestCases
= DesignatedChannelMappings.Searches
.Where(x => x.resultIds.Any())
.SelectMany(x => Users.Entities
.Where(y => DesignatedChannelMappings.Entities
.Where(z => x.resultIds.Contains(z.Id))
.Select(z => z.GuildId)
.Distinct()
.All(z => GuildUsers.Entities
.Any(w => (w.UserId == y.Id) && (w.GuildId == z))))
.Select(y => new TestCaseData(x.criteria, y.Id, x.resultIds)
.SetName($"{{m}}(\"{x.name}\", {y.Id})")));
public static readonly IEnumerable<TestCaseData> InvalidSearchCriteriaTestCases
= DesignatedChannelMappings.Searches
.Where(x => !x.resultIds.Any())
.Select(x => new TestCaseData(x.criteria)
.SetName($"{{m}}({x.name})"));
public static readonly IEnumerable<TestCaseData> InvalidSearchCriteriaAndValidUserIdTestCases
= DesignatedChannelMappings.Searches
.Where(x => !x.resultIds.Any())
.SelectMany(x => Users.Entities
.Select(y => new TestCaseData(x.criteria, y.Id)
.SetName($"{{m}}(\"{x.name}\", {y.Id})")));
public static readonly IEnumerable<TestCaseData> ActiveDesignatedChannelMappingAndValidUserIdTestCases
= DesignatedChannelMappings.Entities
.Where(x => x.DeleteActionId is null)
.SelectMany(x => GuildUsers.Entities
.Where(y => y.GuildId == x.GuildId)
.Select(y => new TestCaseData(x.Id, y.UserId)));
public static readonly IEnumerable<TestCaseData> DeletedDesignatedChannelMappingAndValidUserIdTestCases
= DesignatedChannelMappings.Entities
.Where(x => !(x.DeleteActionId is null))
.SelectMany(x => GuildUsers.Entities
.Where(y => y.GuildId == x.GuildId)
.Select(y => new TestCaseData(x.Id, y.UserId)));
public static readonly IEnumerable<TestCaseData> InvalidDesignatedChannelMappingAndValidUserIdTestCases
= Enumerable.Empty<long>()
.Append(DesignatedChannelMappings.Entities
.Select(x => x.Id)
.Max() + 1)
.SelectMany(x => Users.Entities
.Select(y => new TestCaseData(x, y.Id)));
#endregion Test Data
}
}
| 42.083904 | 228 | 0.639907 | [
"MIT"
] | 333fred/MODiX | Modix.Data.Test/Repositories/DesignatedChannelMappingRepositoryTests.cs | 24,579 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/mfmediaengine.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="IMFTimedTextTrack" /> struct.</summary>
[SupportedOSPlatform("windows10.0")]
public static unsafe partial class IMFTimedTextTrackTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IMFTimedTextTrack" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IMFTimedTextTrack).GUID, Is.EqualTo(IID_IMFTimedTextTrack));
}
/// <summary>Validates that the <see cref="IMFTimedTextTrack" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IMFTimedTextTrack>(), Is.EqualTo(sizeof(IMFTimedTextTrack)));
}
/// <summary>Validates that the <see cref="IMFTimedTextTrack" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IMFTimedTextTrack).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IMFTimedTextTrack" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IMFTimedTextTrack), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IMFTimedTextTrack), Is.EqualTo(4));
}
}
}
| 35.528302 | 145 | 0.695698 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/mfmediaengine/IMFTimedTextTrackTests.cs | 1,885 | C# |
namespace PackageEditor
{
partial class AutoUpdateForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AutoUpdateForm));
this.panel1 = new System.Windows.Forms.Panel();
this.bkPanel = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.literalFinish = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnCancel = new System.Windows.Forms.Button();
this.btnBack = new System.Windows.Forms.Button();
this.btnNext = new System.Windows.Forms.Button();
this.tabWizard = new WizardPages();
this.tabEnableDisable = new System.Windows.Forms.TabPage();
this.radioDisableFeature = new System.Windows.Forms.RadioButton();
this.radioEnableFeature = new System.Windows.Forms.RadioButton();
this.label6 = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.tabGenerateXml = new System.Windows.Forms.TabPage();
this.label7 = new System.Windows.Forms.Label();
this.tbVersion = new System.Windows.Forms.TextBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.btnGenerateXml = new System.Windows.Forms.Button();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.label4 = new System.Windows.Forms.Label();
this.tabLocation = new System.Windows.Forms.TabPage();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.tbLocation = new System.Windows.Forms.TextBox();
this.tabTest = new System.Windows.Forms.TabPage();
this.label8 = new System.Windows.Forms.Label();
this.tbVersionTest = new System.Windows.Forms.TextBox();
this.textBox4 = new System.Windows.Forms.TextBox();
this.btnTest = new System.Windows.Forms.Button();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.label5 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.bkPanel.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.tabWizard.SuspendLayout();
this.tabEnableDisable.SuspendLayout();
this.tabGenerateXml.SuspendLayout();
this.tabLocation.SuspendLayout();
this.tabTest.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.bkPanel);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// bkPanel
//
resources.ApplyResources(this.bkPanel, "bkPanel");
this.bkPanel.Controls.Add(this.panel2);
this.bkPanel.Name = "bkPanel";
//
// panel2
//
resources.ApplyResources(this.panel2, "panel2");
this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel2.Controls.Add(this.literalFinish);
this.panel2.Controls.Add(this.pictureBox1);
this.panel2.Controls.Add(this.groupBox1);
this.panel2.Controls.Add(this.btnCancel);
this.panel2.Controls.Add(this.btnBack);
this.panel2.Controls.Add(this.btnNext);
this.panel2.Controls.Add(this.tabWizard);
this.panel2.Name = "panel2";
//
// literalFinish
//
resources.ApplyResources(this.literalFinish, "literalFinish");
this.literalFinish.Name = "literalFinish";
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.White;
this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnBack
//
resources.ApplyResources(this.btnBack, "btnBack");
this.btnBack.Name = "btnBack";
this.btnBack.UseVisualStyleBackColor = true;
this.btnBack.Click += new System.EventHandler(this.btnBack_Click);
//
// btnNext
//
resources.ApplyResources(this.btnNext, "btnNext");
this.btnNext.Name = "btnNext";
this.btnNext.UseVisualStyleBackColor = true;
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// tabWizard
//
this.tabWizard.Controls.Add(this.tabEnableDisable);
this.tabWizard.Controls.Add(this.tabGenerateXml);
this.tabWizard.Controls.Add(this.tabLocation);
this.tabWizard.Controls.Add(this.tabTest);
resources.ApplyResources(this.tabWizard, "tabWizard");
this.tabWizard.Name = "tabWizard";
this.tabWizard.SelectedIndex = 0;
//
// tabEnableDisable
//
this.tabEnableDisable.BackColor = System.Drawing.SystemColors.Control;
this.tabEnableDisable.Controls.Add(this.radioDisableFeature);
this.tabEnableDisable.Controls.Add(this.radioEnableFeature);
this.tabEnableDisable.Controls.Add(this.label6);
this.tabEnableDisable.Controls.Add(this.groupBox3);
this.tabEnableDisable.Controls.Add(this.label3);
resources.ApplyResources(this.tabEnableDisable, "tabEnableDisable");
this.tabEnableDisable.Name = "tabEnableDisable";
//
// radioDisableFeature
//
resources.ApplyResources(this.radioDisableFeature, "radioDisableFeature");
this.radioDisableFeature.Name = "radioDisableFeature";
this.radioDisableFeature.UseVisualStyleBackColor = true;
//
// radioEnableFeature
//
resources.ApplyResources(this.radioEnableFeature, "radioEnableFeature");
this.radioEnableFeature.Checked = true;
this.radioEnableFeature.Name = "radioEnableFeature";
this.radioEnableFeature.TabStop = true;
this.radioEnableFeature.UseVisualStyleBackColor = true;
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// groupBox3
//
resources.ApplyResources(this.groupBox3, "groupBox3");
this.groupBox3.Name = "groupBox3";
this.groupBox3.TabStop = false;
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// tabGenerateXml
//
this.tabGenerateXml.BackColor = System.Drawing.SystemColors.Control;
this.tabGenerateXml.Controls.Add(this.label7);
this.tabGenerateXml.Controls.Add(this.tbVersion);
this.tabGenerateXml.Controls.Add(this.textBox3);
this.tabGenerateXml.Controls.Add(this.btnGenerateXml);
this.tabGenerateXml.Controls.Add(this.groupBox4);
this.tabGenerateXml.Controls.Add(this.label4);
resources.ApplyResources(this.tabGenerateXml, "tabGenerateXml");
this.tabGenerateXml.Name = "tabGenerateXml";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// tbVersion
//
resources.ApplyResources(this.tbVersion, "tbVersion");
this.tbVersion.Name = "tbVersion";
//
// textBox3
//
this.textBox3.BackColor = System.Drawing.SystemColors.Control;
this.textBox3.BorderStyle = System.Windows.Forms.BorderStyle.None;
resources.ApplyResources(this.textBox3, "textBox3");
this.textBox3.Name = "textBox3";
this.textBox3.ReadOnly = true;
//
// btnGenerateXml
//
resources.ApplyResources(this.btnGenerateXml, "btnGenerateXml");
this.btnGenerateXml.Name = "btnGenerateXml";
this.btnGenerateXml.UseVisualStyleBackColor = true;
this.btnGenerateXml.Click += new System.EventHandler(this.btnGenerateXml_Click);
//
// groupBox4
//
resources.ApplyResources(this.groupBox4, "groupBox4");
this.groupBox4.Name = "groupBox4";
this.groupBox4.TabStop = false;
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// tabLocation
//
this.tabLocation.BackColor = System.Drawing.SystemColors.Control;
this.tabLocation.Controls.Add(this.groupBox2);
this.tabLocation.Controls.Add(this.label2);
this.tabLocation.Controls.Add(this.textBox2);
this.tabLocation.Controls.Add(this.label1);
this.tabLocation.Controls.Add(this.tbLocation);
resources.ApplyResources(this.tabLocation, "tabLocation");
this.tabLocation.Name = "tabLocation";
//
// groupBox2
//
resources.ApplyResources(this.groupBox2, "groupBox2");
this.groupBox2.Name = "groupBox2";
this.groupBox2.TabStop = false;
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// textBox2
//
resources.ApplyResources(this.textBox2, "textBox2");
this.textBox2.BackColor = System.Drawing.SystemColors.Control;
this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox2.Name = "textBox2";
this.textBox2.ReadOnly = true;
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// tbLocation
//
resources.ApplyResources(this.tbLocation, "tbLocation");
this.tbLocation.Name = "tbLocation";
//
// tabTest
//
this.tabTest.BackColor = System.Drawing.SystemColors.Control;
this.tabTest.Controls.Add(this.label8);
this.tabTest.Controls.Add(this.tbVersionTest);
this.tabTest.Controls.Add(this.textBox4);
this.tabTest.Controls.Add(this.btnTest);
this.tabTest.Controls.Add(this.groupBox5);
this.tabTest.Controls.Add(this.label5);
resources.ApplyResources(this.tabTest, "tabTest");
this.tabTest.Name = "tabTest";
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// tbVersionTest
//
resources.ApplyResources(this.tbVersionTest, "tbVersionTest");
this.tbVersionTest.Name = "tbVersionTest";
//
// textBox4
//
this.textBox4.BackColor = System.Drawing.SystemColors.Control;
this.textBox4.BorderStyle = System.Windows.Forms.BorderStyle.None;
resources.ApplyResources(this.textBox4, "textBox4");
this.textBox4.Name = "textBox4";
this.textBox4.ReadOnly = true;
//
// btnTest
//
resources.ApplyResources(this.btnTest, "btnTest");
this.btnTest.Name = "btnTest";
this.btnTest.UseVisualStyleBackColor = true;
this.btnTest.Click += new System.EventHandler(this.btnTest_Click);
//
// groupBox5
//
resources.ApplyResources(this.groupBox5, "groupBox5");
this.groupBox5.Name = "groupBox5";
this.groupBox5.TabStop = false;
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// AutoUpdateForm
//
this.AcceptButton = this.btnNext;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AutoUpdateForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.panel1.ResumeLayout(false);
this.bkPanel.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.tabWizard.ResumeLayout(false);
this.tabEnableDisable.ResumeLayout(false);
this.tabEnableDisable.PerformLayout();
this.tabGenerateXml.ResumeLayout(false);
this.tabGenerateXml.PerformLayout();
this.tabLocation.ResumeLayout(false);
this.tabLocation.PerformLayout();
this.tabTest.ResumeLayout(false);
this.tabTest.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel bkPanel;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnBack;
private System.Windows.Forms.Button btnNext;
private WizardPages tabWizard;
private System.Windows.Forms.TabPage tabEnableDisable;
private System.Windows.Forms.TabPage tabGenerateXml;
private System.Windows.Forms.TabPage tabLocation;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbLocation;
private System.Windows.Forms.TabPage tabTest;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.RadioButton radioDisableFeature;
private System.Windows.Forms.RadioButton radioEnableFeature;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Button btnGenerateXml;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.Button btnTest;
private System.Windows.Forms.Label literalFinish;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox tbVersion;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox tbVersionTest;
}
} | 44.769231 | 146 | 0.590511 | [
"MIT"
] | ChenallFork/cameyo | PackageEditor/AutoUpdateForm.Designer.cs | 18,044 | C# |
// SharpDevelop samples
// Copyright (c) 2007, AlphaSierraPapa
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// - Neither the name of the SharpDevelop team nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using ICSharpCode.Core;
using ICSharpCode.SharpDevelop.Gui;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace CustomPad
{
public class MyCustomPad : AbstractPadContent
{
Panel panel = new Panel();
Label testLabel = new Label();
public MyCustomPad()
{
testLabel.Text = "Hello World!";
testLabel.Location = new Point(8, 8);
panel.Controls.Add(testLabel);
}
// return type is object: both WPF and Windows Forms controls are supported
public override object Control {
get {
return panel;
}
}
}
}
| 38.517857 | 101 | 0.753825 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | samples/CustomPad/MyCustomPad.cs | 2,157 | C# |
using System;
using Microsoft.Hadoop.MapReduce;
namespace SimpleRegexFilter
{
class Program
{
static void Main(string[] args)
{
var hadoop = Hadoop.Connect();
var config = new HadoopJobConfiguration
{
InputPath = "/data/posts",
OutputFolder = "output/SimpleRegexFilter",
};
hadoop.MapReduceJob.Execute<RegexMapper>(config);
Console.ReadKey();
}
}
}
| 22.363636 | 61 | 0.542683 | [
"MIT"
] | SaschaDittmann/MapReduceSamples | MapReduceSamples/SimpleRegexFilter/Program.cs | 494 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using IdentityServer4.Models;
using System.Collections.Generic;
using IdentityServer4;
using Microsoft.Extensions.Configuration;
using N8T.Infrastructure;
namespace CoolStore.IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> Ids =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
public static IEnumerable<ApiResource> Apis =>
new []
{
new ApiResource("graph-api", "My Graph API")
};
public static IEnumerable<Client> Clients(IConfiguration config)
{
Uri webUiUri;
if (config.GetValue<bool>("noTye"))
{
webUiUri = new Uri(config.GetValue<string>("webUIUrl"));
}
else
{
webUiUri = config.GetServiceUri(Consts.WEBUI_ID);
}
return new[]
{
new Client
{
ClientId = "webui",
ClientSecrets = {new Secret("mysecret".Sha256())},
AllowedGrantTypes = GrantTypes.Code,
RequireConsent = false,
RequirePkce = true,
AllowOfflineAccess = true,
// where to redirect to after login
RedirectUris = {$"{webUiUri?.ToString().TrimEnd('/')}/signin-oidc"},
// where to redirect to after logout
PostLogoutRedirectUris = {$"{webUiUri?.ToString().TrimEnd('/')}/signout"},
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
"graph-api"
}
}
};
}
}
}
| 31.929577 | 107 | 0.519629 | [
"MIT"
] | ANgajasinghe/practical-dapr | src/Identity/CoolStore.IdentityServer/Config.cs | 2,267 | C# |
using System;
using System.Collections.Generic;
namespace LibSlyBroadcast.Extensions
{
public static class SlyBroadcastExts
{
public static DateTime ToEst(this DateTime dt)
{
var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
return TimeZoneInfo.ConvertTime(dt, est);
}
public static string ToFormattedString(this DateTime dt) => dt.ToString("yyyy-MM-dd HH:mm:ss");
public static string ToFormattedEstString(this DateTime dt) => dt.ToEst().ToFormattedString();
public static string JoinWith(this IEnumerable<object> enumerable, string s) => string.Join(s, enumerable);
}
} | 34.1 | 115 | 0.693548 | [
"MIT"
] | acaxlabs/LibSlyBroadcast | LibSlyBroadcast/SlyBroadcastExts.cs | 684 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using GalaSoft.MvvmLight.Ioc;
using MvvmDialogs;
using UwpGetImage.Views;
namespace UwpGetImage
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
SimpleIoc.Default.Register<IDialogService>(() => new DialogService());
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
//TODO: Dispose camera object.
}
}
}
| 37.12069 | 99 | 0.61333 | [
"Apache-2.0"
] | bakulev/Usb3Vision-UWP-WinUsb | UwpGetImage/App.xaml.cs | 4,308 | C# |
using System;
using System.IO;
using System.Net;
namespace RedditSharp
{
public class MultipartFormBuilder
{
public HttpWebRequest Request { get; set; }
private string Boundary { get; set; }
private MemoryStream Buffer { get; set; }
private TextWriter TextBuffer { get; set; }
public MultipartFormBuilder(HttpWebRequest request)
{
// TODO: See about regenerating the boundary when needed
Request = request;
var random = new Random();
Boundary = "----------" + CreateRandomBoundary();
request.ContentType = "multipart/form-data; boundary=" + Boundary;
Buffer = new MemoryStream();
TextBuffer = new StreamWriter(Buffer);
}
private string CreateRandomBoundary()
{
// TODO: There's probably a better way to go about this
const string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
string value = "";
var random = new Random();
for (int i = 0; i < 10; i++)
value += characters[random.Next(characters.Length)];
return value;
}
public void AddDynamic(object data)
{
var type = data.GetType();
var properties = type.GetProperties();
foreach (var property in properties)
{
var entry = Convert.ToString(property.GetValue(data, null));
AddString(property.Name, entry);
}
}
public void AddString(string name, string value)
{
TextBuffer.Write("{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
"--" + Boundary, name, value);
TextBuffer.Flush();
}
public void AddFile(string name, string filename, byte[] value, string contentType)
{
TextBuffer.Write("{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
"--" + Boundary, name, filename, contentType);
TextBuffer.Flush();
Buffer.Write(value, 0, value.Length);
Buffer.Flush();
TextBuffer.Write("\r\n");
TextBuffer.Flush();
}
public void Finish()
{
TextBuffer.Write("--" + Boundary + "--");
TextBuffer.Flush();
var stream = Request.GetRequestStream();
Buffer.Seek(0, SeekOrigin.Begin);
Buffer.WriteTo(stream);
stream.Close();
}
}
}
| 34.103896 | 130 | 0.544174 | [
"MIT"
] | BTero/RedditSharp | RedditSharp/MultipartFormBuilder.cs | 2,628 | C# |
namespace Vantage.Measurements
{
[CoreUnitType]
public interface IVolumeUnit : IUnit
{
double ToCubicMeters(double value);
double FromCubicMeters(double value);
}
}
| 18.090909 | 45 | 0.668342 | [
"MIT"
] | VantageSoftware/Vantage.Measurements | src/Vantage.Measurements/IVolumeUnit.cs | 201 | C# |
using NAudio.Wave;
using NLog;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text.RegularExpressions;
namespace AudioPass
{
/// <summary>
/// One direction audio passthrough.
/// </summary>
public class AudioPassthrough : IDisposable
{
private static readonly WaveFormat AudioFormat = new WaveFormat(44100, 2);
private static readonly TimeSpan BufferSize = TimeSpan.FromMilliseconds(50);
private const int NumberOfBuffers = 2;
private static readonly Logger Log = LogManager.GetLogger(nameof(AudioPassthrough));
private readonly BehaviorSubject<bool> _shutdownSignal = new BehaviorSubject<bool>(false);
/// <summary>
/// Initializes a new instance of the <see cref="AudioPassthrough" /> class.
/// </summary>
/// <param name="passthroughName">Name of the passthrough (presentation).</param>
/// <param name="monitorInterval">The interval for monitoring audio devices.</param>
/// <param name="recreateDelay">The delay used to avoid race conditions when devices are plugged in.</param>
/// <param name="inputDeviceName">Observable name of the input device (wildcards allowed).</param>
/// <param name="outputDeviceName">Observable name of the output device (wildcards allowed).</param>
/// <param name="volume">The volume observable. Use <c>Observable.Return(1.0f)</c> for constant value.</param>
/// <param name="scheduler">The scheduler (optional).</param>
[SuppressMessage("ReSharper", "ImplicitlyCapturedClosure")]
public AudioPassthrough(
string passthroughName,
TimeSpan monitorInterval, TimeSpan recreateDelay,
IObservable<string> inputDeviceName,
IObservable<string> outputDeviceName,
IObservable<float> volume,
IScheduler scheduler = null)
{
var inputSelector = Observable
.Interval(monitorInterval, scheduler ?? Scheduler.Default)
.TakeUntil(_shutdownSignal)
.CombineLatest(inputDeviceName.Select(WildcardMatch), (_, matcher) => matcher)
.Select(TryFindInputDeviceIndex)
.DistinctUntilChanged();
var outputSelector = Observable
.Interval(monitorInterval, scheduler ?? Scheduler.Default)
.TakeUntil(_shutdownSignal)
.CombineLatest(outputDeviceName.Select(WildcardMatch), (_, matcher) => matcher)
.Select(TryFindOutputDeviceIndex)
.DistinctUntilChanged();
var passthrough = Disposable.Empty;
inputSelector
.CombineLatest(outputSelector, (i, o) => new { input = i, output = o })
.TakeUntil(_shutdownSignal)
.Throttle(recreateDelay)
.Subscribe(
p => RecreatePassthrough(passthroughName, p.input, p.output, volume, ref passthrough),
() => passthrough.Dispose());
}
/// <summary>
/// Recreates the passthrough chain after device has been connected (or reconnected).
/// </summary>
/// <param name="passthroughName">Name of the passthrough.</param>
/// <param name="input">The input device index.</param>
/// <param name="output">The output device index.</param>
/// <param name="volume">The volume observable.</param>
/// <param name="disposable">The disposable.</param>
private static void RecreatePassthrough(
string passthroughName,
int? input, int? output,
IObservable<float> volume,
ref IDisposable disposable)
{
disposable?.Dispose();
disposable = CreatePassthrough(passthroughName, input, output, volume);
}
/// <summary>
/// Creates the passthrough.
/// </summary>
/// <param name="passthroughName">Name of the passthrough.</param>
/// <param name="input">The input device index.</param>
/// <param name="output">The output device index.</param>
/// <param name="volume">The volume observable.</param>
/// <returns>Disposable to dispose passthrough chain.</returns>
private static IDisposable CreatePassthrough(
string passthroughName,
int? input, int? output,
IObservable<float> volume)
{
if (!input.HasValue)
{
Log.Warn(
"Passthrough '{0}' has not been created as input device cannot be found",
passthroughName);
return Disposable.Empty;
}
if (!output.HasValue)
{
Log.Warn(
"Passthrough '{0}' has not been created as output device cannot be found",
passthroughName);
return Disposable.Empty;
}
var disposables = DisposableBag.Create();
try
{
// create wave in
var waveIn = disposables.Add(new WaveInEvent {
DeviceNumber = input.Value,
BufferMilliseconds = (int)BufferSize.TotalMilliseconds,
NumberOfBuffers = NumberOfBuffers,
WaveFormat = AudioFormat
});
var waveInName = WaveInEvent.GetCapabilities(waveIn.DeviceNumber).ProductName;
// create wave out
var waveOut = disposables.Add(new WaveOutEvent {
DeviceNumber = output.Value,
NumberOfBuffers = NumberOfBuffers,
});
var waveOutName = WaveOut.GetCapabilities(waveOut.DeviceNumber).ProductName;
// create volume control stream (between in and out)
var volumeStream = new VolumeWaveProvider16(new WaveInProvider(waveIn));
disposables.Add(volume.Subscribe(v => volumeStream.Volume = v));
// bind volume stream to output
waveOut.Init(volumeStream);
// start passing sound through
waveIn.StartRecording();
waveOut.Play();
Log.Info("Passthrough '{0}' between '{1}' ({3}) and '{2}' ({4}) has been established",
passthroughName,
input, output,
waveInName, waveOutName);
disposables.Add(
Disposable.Create(() => Log.Warn("Passthrough '{0}' has been disposed", passthroughName)));
return disposables;
}
catch (Exception e)
{
Log.Error("Passthrough '{0}' initialization failed", passthroughName);
Log.Error(e, "Exception");
disposables.Dispose();
return Disposable.Empty;
}
}
private static int? TryFindDeviceIndex(
int deviceCount, Func<int, string> deviceName, Func<string, bool> nameMatch)
{
try
{
return Enumerable
.Range(0, deviceCount)
.Where(i => nameMatch(deviceName(i)))
.Select(i => (int?)i)
.FirstOrDefault();
}
catch (Exception e)
{
Log.Error(e, "Failed to scan devices");
return null;
}
}
private static int? TryFindInputDeviceIndex(Func<string, bool> nameMatch)
{
return TryFindDeviceIndex(
WaveIn.DeviceCount,
i => WaveIn.GetCapabilities(i).ProductName,
nameMatch);
}
private static int? TryFindOutputDeviceIndex(Func<string, bool> nameMatch)
{
return TryFindDeviceIndex(
WaveOut.DeviceCount,
i => WaveOut.GetCapabilities(i).ProductName,
nameMatch);
}
private static Func<string, bool> WildcardMatch(string pattern)
{
if (string.IsNullOrEmpty(pattern)) return _ => false;
pattern = string.Format("^{0}$", Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".?"));
var regex = new Regex(pattern);
return text => regex.IsMatch(text);
}
public void Dispose()
{
_shutdownSignal.OnNext(true);
_shutdownSignal.OnCompleted();
}
}
} | 40.78972 | 118 | 0.566502 | [
"BSD-3-Clause"
] | MiloszKrajewski/dnug-rx | src/AudioPass/AudioPassthrough.cs | 8,731 | C# |
namespace LinFx.Extensions.AspNetCore.ExceptionHandling;
/// <summary>
/// 异常处理选项
/// </summary>
public class ExceptionHandlingOptions
{
public bool SendExceptionsDetailsToClients { get; set; } = false;
public bool SendStackTraceToClients { get; set; } = true;
}
| 22.833333 | 69 | 0.729927 | [
"MIT"
] | linfx/linfx | src/LinFx/Extensions/AspNetCore/ExceptionHandling/ExceptionHandlingOptions.cs | 288 | C# |
// Copyright 2014-2017 ClassicalSharp | Licensed under BSD-3
using System;
using ClassicalSharp.Entities;
using ClassicalSharp.GraphicsAPI;
using ClassicalSharp.Model;
using OpenTK;
using BlockID = System.UInt16;
namespace ClassicalSharp.Renderers {
public class HeldBlockRenderer : IGameComponent {
BlockID block;
Game game;
Entity held;
Matrix4 heldBlockProj;
void IGameComponent.Init(Game game) {
this.game = game;
held = new FakeHeldEntity(game);
lastBlock = game.Inventory.Selected;
Events.ProjectionChanged += ProjectionChanged;
Events.HeldBlockChanged += DoSwitchBlockAnim;
Events.BlockChanged += BlockChanged;
}
void IGameComponent.Ready(Game game) { }
void IGameComponent.Reset(Game game) { }
void IGameComponent.OnNewMap(Game game) { }
void IGameComponent.OnNewMapLoaded(Game game) { }
void IDisposable.Dispose() {
Events.ProjectionChanged -= ProjectionChanged;
Events.HeldBlockChanged -= DoSwitchBlockAnim;
Events.BlockChanged -= BlockChanged;
}
public void Render(double delta) {
if (!game.ShowBlockInHand) return;
float lastSwingY = swingY; swingY = 0;
block = game.Inventory.Selected;
game.Graphics.SetMatrixMode(MatrixType.Projection);
game.Graphics.LoadMatrix(ref heldBlockProj);
game.Graphics.SetMatrixMode(MatrixType.Modelview);
Matrix4 view = game.Graphics.View;
SetMatrix();
ResetHeldState();
DoAnimation(delta, lastSwingY);
SetBaseOffset();
if (!game.Camera.IsThirdPerson) RenderModel();
game.Graphics.View = view;
game.Graphics.SetMatrixMode(MatrixType.Projection);
game.Graphics.LoadMatrix(ref game.Graphics.Projection);
game.Graphics.SetMatrixMode(MatrixType.Modelview);
}
void RenderModel() {
game.Graphics.FaceCulling = true;
game.Graphics.Texturing = true;
game.Graphics.DepthTest = false;
IModel model;
if (BlockInfo.Draw[block] == DrawType.Gas) {
model = game.LocalPlayer.Model;
held.ModelScale = new Vector3(1.0f);
game.Graphics.AlphaTest = true;
model.RenderArm(held);
game.Graphics.AlphaTest = false;
} else {
model = game.ModelCache.Get("block");
held.ModelScale = new Vector3(0.4f);
game.Graphics.SetupAlphaState(BlockInfo.Draw[block]);
model.Render(held);
game.Graphics.RestoreAlphaState(BlockInfo.Draw[block]);
}
game.Graphics.Texturing = false;
game.Graphics.DepthTest = true;
game.Graphics.FaceCulling = false;
}
static Vector3 nOffset = new Vector3(0.56f, -0.72f, -0.72f);
static Vector3 sOffset = new Vector3(0.46f, -0.52f, -0.72f);
void SetMatrix() {
Player p = game.LocalPlayer;
Vector3 eye = Vector3.Zero; eye.Y = p.EyeHeight;
Matrix4 lookAt, m;
Matrix4.Translate(out lookAt, -eye.X, -eye.Y, -eye.Z);
Matrix4.Mult(out m, ref lookAt, ref Camera.tiltM);
game.Graphics.View = m;
}
void ResetHeldState() {
// Based off details from http://pastebin.com/KFV0HkmD (Thanks goodlyay!)
Player p = game.LocalPlayer;
Vector3 eyePos = Vector3.Zero; eyePos.Y = p.EyeHeight;
held.Position = eyePos;
held.Position.X -= Camera.bobbingHor;
held.Position.Y -= Camera.bobbingVer;
held.Position.Z -= Camera.bobbingHor;
held.HeadY = -45; held.RotY = -45;
held.HeadX = 0; held.RotX = 0;
held.ModelBlock = block;
held.SkinType = p.SkinType;
held.TextureId = p.TextureId;
held.MobTextureId = p.MobTextureId;
held.uScale = p.uScale;
held.vScale = p.vScale;
}
void SetBaseOffset() {
bool sprite = BlockInfo.Draw[block] == DrawType.Sprite;
Vector3 offset = sprite ? sOffset : nOffset;
held.Position += offset;
if (!sprite && BlockInfo.Draw[block] != DrawType.Gas) {
float height = BlockInfo.MaxBB[block].Y - BlockInfo.MinBB[block].Y;
held.Position.Y += 0.2f * (1 - height);
}
}
void ProjectionChanged() {
float fov = 70 * Utils.Deg2Rad;
float aspectRatio = (float)game.Width / game.Height;
float zNear = game.Graphics.MinZNear;
game.Graphics.CalcPerspectiveMatrix(fov, aspectRatio, zNear, game.ViewDistance, out heldBlockProj);
}
bool animating, breaking, swinging;
float swingY;
double time, period = 0.25;
BlockID lastBlock;
public void ClickAnim(bool digging) {
// TODO: timing still not quite right, rotate2 still not quite right
ResetAnim(true, digging ? 0.35 : 0.25);
swinging = false;
breaking = digging;
animating = true;
// Start place animation at bottom of cycle
if (!digging) time = period / 2;
}
void DoSwitchBlockAnim() {
if (swinging) {
// Like graph -sin(x) : x=0.5 and x=2.5 have same y values
// but increasing x causes y to change in opposite directions
if (time > period * 0.5)
time = period - time;
} else {
if (block == game.Inventory.Selected) return;
ResetAnim(false, 0.25);
animating = true;
swinging = true;
}
}
void BlockChanged(Vector3I coords, BlockID old, BlockID now) {
if (now == Block.Air) return;
ClickAnim(false);
}
void DoAnimation(double delta, float lastSwingY) {
if (!animating) return;
if (swinging || !breaking) {
double t = time / period;
swingY = -0.4f * (float)Math.Sin(t * Math.PI);
held.Position.Y += swingY;
if (swinging) {
// i.e. the block has gone to bottom of screen and is now returning back up
// at this point we switch over to the new held block.
if (swingY > lastSwingY) lastBlock = block;
block = lastBlock;
held.ModelBlock = block;
}
} else {
DigAnimation();
}
time += delta;
if (time > period) ResetAnim(true, 0.25);
}
// Based off incredible gifs from (Thanks goodlyay!)
// https://dl.dropboxusercontent.com/s/iuazpmpnr89zdgb/slowBreakTranslate.gif
// https://dl.dropboxusercontent.com/s/z7z8bset914s0ij/slowBreakRotate1.gif
// https://dl.dropboxusercontent.com/s/pdq79gkzntquld1/slowBreakRotate2.gif
// https://dl.dropboxusercontent.com/s/w1ego7cy7e5nrk1/slowBreakFull.gif
// https://github.com/UnknownShadow200/ClassicalSharp/wiki/Dig-animation-details
void DigAnimation() {
double t = time / period;
double sinHalfCircle = Math.Sin(t * Math.PI);
double sqrtLerpPI = Math.Sqrt(t) * Math.PI;
held.Position.X -= (float)(Math.Sin(sqrtLerpPI) * 0.4);
held.Position.Y += (float)(Math.Sin((sqrtLerpPI * 2)) * 0.2);
held.Position.Z -= (float)(sinHalfCircle * 0.2);
double sinHalfCircleWeird = Math.Sin(t * t * Math.PI);
held.RotY -= (float)(Math.Sin(sqrtLerpPI) * 80);
held.HeadY -= (float)(Math.Sin(sqrtLerpPI) * 80);
held.RotX += (float)(sinHalfCircleWeird * 20);
}
void ResetAnim(bool setLastHeld, double period) {
time = 0; swingY = 0;
animating = false; swinging = false;
this.period = period;
if (setLastHeld) lastBlock = game.Inventory.Selected;
}
}
/// <summary> Skeleton implementation of player entity so we can reuse block model rendering code. </summary>
class FakeHeldEntity : Entity {
public FakeHeldEntity(Game game) : base(game) {
NoShade = true;
}
public override void SetLocation(LocationUpdate update, bool interpolate) { }
public override void Tick(double delta) { }
public override void RenderModel(double deltaTime, float t) { }
public override void RenderName() { }
public override void Despawn() { }
public override PackedCol Colour() {
Player realP = game.LocalPlayer;
PackedCol col = realP.Colour();
// Adjust pitch so angle when looking straight down is 0.
float adjHeadX = realP.HeadX - 90;
if (adjHeadX < 0) adjHeadX += 360;
// Adjust colour so held block is brighter when looking straght up
float t = Math.Abs(adjHeadX - 180) / 180;
float colScale = Utils.Lerp(0.9f, 0.7f, t);
return PackedCol.Scale(col, colScale);
}
}
} | 31.063241 | 110 | 0.678076 | [
"BSD-3-Clause"
] | RMuskovets/ClassiCube | ClassicalSharp/ClassicalSharp/Rendering/HeldBlockRenderer.cs | 7,861 | C# |
using System;
using System.Collections.Generic;
namespace WebApi.Services
{
public class PropertyMapping<TSource, TDestination> : IPropertyMapping
{
public Dictionary<string, PropertyMappingValue> _mappingDictionary { get; private set; }
public PropertyMapping(Dictionary<string, PropertyMappingValue> mappingDictionary)
{
_mappingDictionary = mappingDictionary ??
throw new ArgumentNullException(nameof(mappingDictionary));
}
}
}
| 29.823529 | 96 | 0.706114 | [
"MIT"
] | olcay/dev-olcay-dir-api | Services/PropertyMapping.cs | 509 | C# |
using Chalmers.ILL.Models;
using Chalmers.ILL.Repositories;
using System;
namespace Chalmers.ILL.Services
{
public class FolioUserService : IFolioUserService
{
private readonly string path = "/users";
private readonly IFolioRepository _folioRepository;
private readonly IJsonService _jsonService;
public FolioUserService
(
IFolioRepository folioRepository,
IJsonService jsonService
)
{
_folioRepository = folioRepository;
_jsonService = jsonService;
}
public FolioUser ByUserName(string userName)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentNullException(nameof(userName));
}
var response = _folioRepository.ByQuery($"{path}?query=(username={userName})");
var users = _jsonService.DeserializeObject<FolioUserNameQuery>(response);
if (users.TotalRecords == 1)
{
return users.Users[0];
}
else if (users.TotalRecords > 1)
{
throw new FolioUserException($"Hittade flera användare med användarnamnet {userName}");
}
else
{
throw new FolioUserException($"Hittade ingen användare med användarnamnet {userName}");
}
}
}
} | 30.06383 | 103 | 0.581033 | [
"MIT"
] | ChalmersLibrary/Chillin | Chalmers.ILL/Services/FolioUserService.cs | 1,419 | C# |
using Skork.keywords;
using System.Collections.Specialized;
using System.Windows.Forms;
namespace Skork.util {
class SkorkCompile {
/// <summary>
///
/// </summary>
private StringCollection code;
/// <summary>
/// Takes a parsed string collection and
/// converts it.
/// </summary>
/// <param name="code"></param>
public SkorkCompile(StringCollection code) {
this.code = code;
//CleanCode();
SplitCode(ref this.code);
TestSplit();
}
public void Compile() {
byte returnType = 0;
foreach (string item in this.code) {
returnType = ParseCodeLine(item);
}
}
/// <summary>
/// Returns 0 if valid, 1, 2, 3 etc. invalid.
/// <para>skork s;</para>
/// <para>int i = 0;</para>
/// </summary>
/// <param name="codeLine">The code line to parse.</param>
/// <returns></returns>
private byte ParseCodeLine(string codeLine) {
SkorkKeyword sk = new SkorkKeyword();
Util u = new Util();
string line = string.Empty,
name = string.Empty;
char[] trails = { '\n', ' ' };
return 0;
}
/// <summary>
/// Attempts to remove trailing spaces and new
/// lines from code statements and condensing
/// code to the bare minimum for compiling.
/// </summary>
private void CleanCode() {
StringCollection newCode = new StringCollection();
foreach (string line in this.code) {
int pos = line.IndexOf(' ');
if (pos != -1) { // Checks if there is a space.
string subStr = line.Substring(pos, line.IndexOf(' ', pos));
MessageBox.Show(subStr);
newCode.Add(subStr);
}
}
this.code = newCode;
}
/// <summary>
/// Attempts to convert multi-line code statements
/// into one line in Skork readable format.
/// SkorkReAdAbLeFoRmat
/// </summary>
private void SplitCode(ref StringCollection code) {
StringCollection newCode = new StringCollection();
string multiLine = string.Empty; //represents a line concatonated from different lines.
foreach (string line in code) {
multiLine += line;
if (multiLine.Contains(";")) {
newCode.Add(multiLine);
multiLine = string.Empty;
}
code = newCode;
}
}
// A line is valid if it contains a keyword or variable name or comment.
// int\hi\=\5;
private string GetCodeLine(string line) {
string codeLine = string.Empty;
SkorkKeyword sk = new SkorkKeyword();
const char bs = '\\';
if (line.Contains(";")) {
foreach (string keyword in sk.Keywords) {
if (line.Contains(keyword)) {
line = line.Trim();
}
}
}
return codeLine;
}
public void TestSplit() {
foreach (string line in this.code) {
MessageBox.Show(line);
}
}
}
}
| 24.957143 | 99 | 0.480824 | [
"Apache-2.0"
] | Reapism/Skork | Skork/Skork/util/SkorkCompile.cs | 3,496 | C# |
using Microsoft.Extensions.Caching.Memory;
using NiceHash.Core.Config;
using NiceHash.Core.Exceptions;
using NiceHash.Core.Models;
using NiceHash.Core.Utils;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
namespace NiceHash.Core.Services;
public interface INiceHashService
{
Task<TResponse?> Delete<TResponse>(string url, Guid? requestId = null, CancellationToken ct = default);
Task<TResponse?> Get<TResponse>(string url, CancellationToken ct = default);
Task<TResponse?> GetAnnonymous<TResponse>(string url, CancellationToken ct);
Task<TResponse?> Post<TRequest, TResponse>(string url, TRequest payload, Guid? requestId = null, CancellationToken ct = default);
}
internal class NiceHashService : INiceHashService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfigProvider _configProvider;
private readonly IMemoryCache _memoryCache;
private string? _lastKnownServerTime = null;
public NiceHashService(IHttpClientFactory httpClientFactory, IConfigProvider configProvider, IMemoryCache memoryCache)
{
_httpClientFactory = httpClientFactory;
_configProvider = configProvider;
_memoryCache = memoryCache;
}
public async Task<TResponse?> GetAnnonymous<TResponse>(string url, CancellationToken ct)
{
NiceHashConfig config = _configProvider.GetConfig();
using HttpClient client = _httpClientFactory.CreateClient();
client.BaseAddress = config.BaseUri;
var a = await client.GetStringAsync(url, ct);
return await client.GetFromJsonAsync<TResponse>(url, ct);
}
public async Task<TResponse?> Get<TResponse>(string url, CancellationToken ct = default)
{
HttpClient client = await CreateClientWithAuth(url, "GET", null, null, ct);
return await client.GetFromJsonAsync<TResponse>(url, ct);
}
public async Task<TResponse?> Post<TRequest, TResponse>(string url, TRequest payload, Guid? requestId = null, CancellationToken ct = default)
{
string json = System.Text.Json.JsonSerializer.Serialize(payload, options: new System.Text.Json.JsonSerializerOptions
{
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
});
HttpClient client = await CreateClientWithAuth(url, "POST", requestId, json, ct);
client.DefaultRequestHeaders.Add("Accept", "application/json");
var response = await client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json"), ct);
return await response.Content.ReadFromJsonAsync<TResponse>(cancellationToken: ct);
}
public async Task<TResponse?> Delete<TResponse>(string url, Guid? requestId = null, CancellationToken ct = default)
{
HttpClient client = await CreateClientWithAuth(url, "DELETE", requestId, null, ct);
HttpResponseMessage? response = await client.DeleteAsync(url, ct);
return await response.Content.ReadFromJsonAsync<TResponse>(cancellationToken: ct);
}
/// <summary>
/// Get and cache server time.
/// </summary>
internal async Task<string?> GetServerTime(CancellationToken ct)
{
if (!_memoryCache.TryGetValue("NiceHashServerTime", out string? serverTime))
{
try
{
// Attempt to get latest server time.
var response = await GetAnnonymous<ServerTimeResponse>("/api/v2/time", ct);
// TODO: Check how often we need to update server time.
serverTime = response?.ServerTime.ToString();
if (!string.IsNullOrWhiteSpace(serverTime))
{
_lastKnownServerTime = serverTime;
// Cache only if result is valid.
_memoryCache.Set("NiceHashServerTime", serverTime, TimeSpan.FromMinutes(1));
return response?.ServerTime.ToString();
}
}
catch
{
// TODO: Log.
}
}
// Use latest server time or fallback to last known server time.
return serverTime
?? _lastKnownServerTime;
}
private async Task<HttpClient> CreateClientWithAuth(string url, string method, Guid? requestId = null, string? jsonPayload = null, CancellationToken ct = default)
{
NiceHashConfig config = _configProvider.GetConfig();
HttpClient client = _httpClientFactory.CreateClient();
client.BaseAddress = config.BaseUri;
await AddAuth(config, client.DefaultRequestHeaders, url, method, jsonPayload, ct);
if (requestId.HasValue)
{
client.DefaultRequestHeaders.Add("X-Request-Id", requestId.ToString());
}
return client;
}
private async Task AddAuth(NiceHashConfig config, HttpRequestHeaders header, string url, string method, string? payload = null, CancellationToken ct = default)
{
string serverTime = await GetServerTime(ct) ?? throw new ServerTimeException();
string nonce = Guid.NewGuid().ToString();
string digest = CryptoUtils.HashBySegments(config.ApiSecret, config.ApiKey, serverTime, nonce, config.OrganizationId, method, url, payload);
header.Add("X-Time", serverTime);
header.Add("X-Nonce", nonce);
header.Add("X-Auth", $"{config.ApiKey}:{digest}");
header.Add("X-Organization-Id", config.OrganizationId);
}
}
| 39.453237 | 166 | 0.676331 | [
"MIT"
] | jernejk/NiceHash | src/NiceHash.Core/Services/NiceHashService.cs | 5,486 | 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 System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using log4net;
using XenAdmin.Controls;
using XenAdmin.Diagnostics.Problems;
using XenAdmin.Dialogs;
using XenAdmin.Wizards.PatchingWizard.PlanActions;
using XenAPI;
using XenAdmin.Actions;
using System.Linq;
using XenAdmin.Core;
using XenAdmin.Network;
using System.Text;
using System.Diagnostics;
namespace XenAdmin.Wizards.PatchingWizard
{
public partial class PatchingWizard_AutomatedUpdatesPage : XenTabPage
{
protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public XenAdmin.Core.Updates.UpgradeSequence UpgradeSequences { get; set; }
private bool _thisPageIsCompleted = false;
public List<Problem> ProblemsResolvedPreCheck { private get; set; }
public List<Pool> SelectedPools { private get; set; }
private List<PoolPatchMapping> patchMappings = new List<PoolPatchMapping>();
public Dictionary<XenServerPatch, string> AllDownloadedPatches = new Dictionary<XenServerPatch, string>();
private List<UpdateProgressBackgroundWorker> backgroundWorkers = new List<UpdateProgressBackgroundWorker>();
public PatchingWizard_AutomatedUpdatesPage()
{
InitializeComponent();
}
public override string Text
{
get
{
return Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_TEXT;
}
}
public override string PageTitle
{
get
{
return Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_TITLE;
}
}
public override string HelpID
{
get { return ""; }
}
public override bool EnablePrevious()
{
return false;
}
private bool _nextEnabled;
public override bool EnableNext()
{
return _nextEnabled;
}
private bool _cancelEnabled;
public override bool EnableCancel()
{
return _cancelEnabled;
}
public override void PageCancelled()
{
if (!_thisPageIsCompleted)
{
backgroundWorkers.ForEach(bgw => bgw.CancelAsync());
backgroundWorkers.Clear();
}
base.PageCancelled();
}
public override void PageLeave(PageLoadedDirection direction, ref bool cancel)
{
base.PageLeave(direction, ref cancel);
}
public override void PageLoaded(PageLoadedDirection direction)
{
base.PageLoaded(direction);
if (_thisPageIsCompleted)
{
return;
}
foreach (var pool in SelectedPools)
{
var master = Helpers.GetMaster(pool.Connection);
var planActions = new List<PlanAction>();
var delayedActionsByHost = new Dictionary<Host, List<PlanAction>>();
foreach (var host in pool.Connection.Cache.Hosts)
{
delayedActionsByHost.Add(host, new List<PlanAction>());
}
var hosts = pool.Connection.Cache.Hosts;
var us = Updates.GetUpgradeSequence(pool.Connection);
Debug.Assert(us != null, "Update sequence should not be null.");
if (us != null)
{
foreach (var patch in us.UniquePatches)
{
var hostsToApply = us.Where(u => u.Value.Contains(patch)).Select(u => u.Key).ToList();
hostsToApply.Sort();
planActions.Add(new DownloadPatchPlanAction(master.Connection, patch, AllDownloadedPatches));
planActions.Add(new UploadPatchToMasterPlanAction(master.Connection, patch, patchMappings, AllDownloadedPatches));
planActions.Add(new PatchPrechecksOnMultipleHostsInAPoolPlanAction(master.Connection, patch, hostsToApply, patchMappings));
foreach (var host in hostsToApply)
{
planActions.Add(new ApplyXenServerPatchPlanAction(host, patch, patchMappings));
planActions.AddRange(GetMandatoryActionListForPatch(host, patch));
UpdateDelayedAfterPatchGuidanceActionListForHost(delayedActionsByHost[host], host, patch);
}
//clean up master at the end:
planActions.Add(new RemoveUpdateFileFromMasterPlanAction(master, patchMappings, patch));
}//patch
}
if (planActions.Count > 0)
{
var bgw = new UpdateProgressBackgroundWorker(master, planActions, delayedActionsByHost);
backgroundWorkers.Add(bgw);
}
} //foreach in SelectedMasters
foreach (var bgw in backgroundWorkers)
{
bgw.DoWork += new DoWorkEventHandler(WorkerDoWork);
bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += new ProgressChangedEventHandler(WorkerProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);
bgw.WorkerSupportsCancellation = true;
bgw.RunWorkerAsync();
}
if (backgroundWorkers.Count == 0)
{
_thisPageIsCompleted = true;
_nextEnabled = true;
OnPageUpdated();
}
}
#region automatic_mode
private List<PlanAction> doneActions = new List<PlanAction>();
private List<PlanAction> inProgressActions = new List<PlanAction>();
private List<PlanAction> errorActions = new List<PlanAction>();
private void WorkerProgressChanged(object sender, ProgressChangedEventArgs e)
{
var actionsWorker = sender as BackgroundWorker;
Program.Invoke(Program.MainWindow, () =>
{
if (!actionsWorker.CancellationPending)
{
PlanAction action = (PlanAction)e.UserState;
if (action != null)
{
if (e.ProgressPercentage == 0)
{
inProgressActions.Add(action);
}
else
{
doneActions.Add(action);
inProgressActions.Remove(action);
progressBar.Value += (int)((float)e.ProgressPercentage / (float)backgroundWorkers.Count); //extend with error handling related numbers
}
}
UpdateStatusTextBox();
}
});
}
private void UpdateStatusTextBox()
{
var sb = new StringBuilder();
foreach (var pa in doneActions)
{
if (pa.Visible)
{
sb.Append(pa);
sb.AppendLine(Messages.DONE);
}
}
foreach (var pa in errorActions)
{
sb.Append(pa);
sb.AppendLine(Messages.ERROR);
}
foreach (var pa in inProgressActions)
{
if (pa.Visible)
{
sb.Append(pa);
sb.AppendLine();
}
}
textBoxLog.Text = sb.ToString();
textBoxLog.SelectionStart = textBoxLog.Text.Length;
textBoxLog.ScrollToCaret();
}
private void WorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
var bgw = sender as UpdateProgressBackgroundWorker;
PlanAction action = null;
try
{
//running actions (non-delayed)
foreach (var a in bgw.PlanActions)
{
action = a;
if (bgw.CancellationPending)
{
doWorkEventArgs.Cancel = true;
return;
}
RunPlanAction(bgw, action);
}
// running delayed actions, but skipping the ones that should be skipped
// iterating through hosts
foreach (var kvp in bgw.DelayedActionsByHost)
{
var h = kvp.Key;
var actions = kvp.Value;
//run all restart-alike plan actions
foreach (var a in actions.Where(a => a.IsRestartRelatedPlanAction()))
{
action = a;
if (bgw.CancellationPending)
{
doWorkEventArgs.Cancel = true;
return;
}
RunPlanAction(bgw, action);
}
//run the rest
foreach (var a in actions.Where(a => !a.IsRestartRelatedPlanAction()))
{
action = a;
if (bgw.CancellationPending)
{
doWorkEventArgs.Cancel = true;
return;
}
// any non-restart-alike delayed action needs to be run if:
// - this host is pre-Ely and there isn't any restart plan action among the delayed actions, or
// - this host is Ely or above and bgw.AvoidRestartHosts contains the host's uuid (shows that live patching must have succeeded) or there isn't any restart plan action among the delayed actions
if (!Helpers.ElyOrGreater(h) && !actions.Any(pa => pa.IsRestartRelatedPlanAction())
|| Helpers.ElyOrGreater(h) && (bgw.AvoidRestartHosts != null && bgw.AvoidRestartHosts.Contains(h.uuid) || !actions.Any(pa => pa.IsRestartRelatedPlanAction())))
{
RunPlanAction(bgw, action);
}
else
{
//skip running it
action.Visible = false;
bgw.ReportProgress((int)((1.0 / (double)bgw.ActionsCount) * 100), action); //still need to report progress, mainly for the progress bar
}
}
}
}
catch (Exception e)
{
bgw.FailedWithExceptionAction = action;
errorActions.Add(action);
inProgressActions.Remove(action);
log.Error("Failed to carry out plan.", e);
log.Debug(action.Title);
doWorkEventArgs.Result = new Exception(action.Title, e);
//this pool failed, we will stop here, but try to remove update files at least
try
{
var positionOfFailedAction = bgw.PlanActions.IndexOf(action);
// can try to clean up the host after a failed PlanAction from bgw.PlanActions only
if (positionOfFailedAction != -1 && !(action is DownloadPatchPlanAction || action is UploadPatchToMasterPlanAction))
{
int pos = positionOfFailedAction;
if (!(bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction)) //can't do anything if the remove action has failed
{
while (++pos < bgw.PlanActions.Count)
{
if (bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction) //find the next remove
{
bgw.PlanActions[pos].Run();
break;
}
}
}
}
}
catch (Exception ex2)
{
//already in an error case - best effort
log.Error("Failed to clean up (this was a best effort attempt)", ex2);
}
bgw.ReportProgress(0);
}
}
private static void RunPlanAction(UpdateProgressBackgroundWorker bgw, PlanAction action)
{
InitializePlanAction(bgw, action);
bgw.ReportProgress(0, action);
action.Run();
Thread.Sleep(1000);
bgw.doneActions.Add(action);
bgw.ReportProgress((int)((1.0 / (double)bgw.ActionsCount) * 100), action);
}
private static void InitializePlanAction(UpdateProgressBackgroundWorker bgw, PlanAction action)
{
if (action is IAvoidRestartHostsAware)
{
var avoidRestartAction = action as IAvoidRestartHostsAware;
avoidRestartAction.AvoidRestartHosts = bgw.AvoidRestartHosts;
}
}
private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var bgw = (UpdateProgressBackgroundWorker)sender;
Program.Invoke(Program.MainWindow, () =>
{
if (!e.Cancelled)
{
Exception exception = e.Result as Exception;
if (exception != null)
{
//not showing exceptions in the meantime
}
//if all finished
if (backgroundWorkers.All(w => !w.IsBusy))
{
AllWorkersFinished();
ShowErrors();
_thisPageIsCompleted = true;
_cancelEnabled = false;
_nextEnabled = true;
}
}
});
OnPageUpdated();
}
private void UpdateDelayedAfterPatchGuidanceActionListForHost(List<PlanAction> delayedGuidances, Host host, XenServerPatch patch)
{
List<PlanAction> actions = GetAfterApplyGuidanceActionsForPatch(host, patch);
if (actions.Count == 0)
return;
if (!patch.GuidanceMandatory)
{
// add any action that is not already in the list
delayedGuidances.AddRange(actions.Where(a => !delayedGuidances.Any(dg => a.GetType() == dg.GetType())));
}
else
{
// remove all delayed action of the same kinds that have already been added (Because these actions are guidance-mandatory=true, therefore
// they will run immediately, making delayed ones obsolete)
delayedGuidances.RemoveAll(dg => actions.Any(ma => ma.GetType() == dg.GetType()));
}
}
private static List<PlanAction> GetAfterApplyGuidanceActionsForPatch(Host host, XenServerPatch patch)
{
List<PlanAction> actions = new List<PlanAction>();
List<XenRef<VM>> runningVMs = RunningVMs(host);
if (patch.after_apply_guidance == after_apply_guidance.restartHost)
{
actions.Add(new EvacuateHostPlanAction(host));
actions.Add(new RebootHostPlanAction(host));
actions.Add(new BringBabiesBackAction(runningVMs, host, false));
}
if (patch.after_apply_guidance == after_apply_guidance.restartXAPI)
{
actions.Add(new RestartAgentPlanAction(host));
}
if (patch.after_apply_guidance == after_apply_guidance.restartHVM)
{
actions.Add(new RebootVMsPlanAction(host, RunningHvmVMs(host)));
}
if (patch.after_apply_guidance == after_apply_guidance.restartPV)
{
actions.Add(new RebootVMsPlanAction(host, RunningPvVMs(host)));
}
return actions;
}
private List<PlanAction> GetMandatoryActionListForPatch(Host host, XenServerPatch patch)
{
var actions = new List<PlanAction>();
if (!patch.GuidanceMandatory)
return actions;
actions = GetAfterApplyGuidanceActionsForPatch(host, patch);
return actions;
}
private static List<XenRef<VM>> RunningHvmVMs(Host host)
{
List<XenRef<VM>> vms = new List<XenRef<VM>>();
foreach (VM vm in host.Connection.ResolveAll(host.resident_VMs))
{
if (!vm.IsHVM || !vm.is_a_real_vm)
continue;
vms.Add(new XenRef<VM>(vm.opaque_ref));
}
return vms;
}
private static List<XenRef<VM>> RunningPvVMs(Host host)
{
List<XenRef<VM>> vms = new List<XenRef<VM>>();
foreach (VM vm in host.Connection.ResolveAll(host.resident_VMs))
{
if (vm.IsHVM || !vm.is_a_real_vm)
continue;
vms.Add(new XenRef<VM>(vm.opaque_ref));
}
return vms;
}
private static List<XenRef<VM>> RunningVMs(Host host)
{
List<XenRef<VM>> vms = new List<XenRef<VM>>();
foreach (VM vm in host.Connection.ResolveAll(host.resident_VMs))
{
if (!vm.is_a_real_vm)
continue;
vms.Add(new XenRef<VM>(vm.opaque_ref));
}
return vms;
}
#endregion
private void ShowErrors()
{
if (ErrorMessages != null)
{
labelTitle.Text = Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_FAILED;
labelError.Text = Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_ERROR;
textBoxLog.Text += ErrorMessages;
log.ErrorFormat("Error message displayed: {0}", labelError.Text);
pictureBox1.Image = SystemIcons.Error.ToBitmap();
panel1.Visible = true;
}
}
private string ErrorMessages
{
get
{
if (errorActions.Count == 0)
return null;
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine(errorActions.Count > 1 ? Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_ERRORS_OCCURRED : Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_ERROR_OCCURRED);
foreach (var action in errorActions)
{
var exception = action.Error;
if (exception == null)
{
log.ErrorFormat("An action has failed with an empty exception. Action: {0}", action.ToString());
continue;
}
log.Error(exception);
if (exception != null && exception.InnerException != null && exception.InnerException is Failure)
{
var innerEx = exception.InnerException as Failure;
log.Error(innerEx);
sb.AppendLine(innerEx.Message);
}
else
{
sb.AppendLine(exception.Message);
}
}
return sb.ToString();
}
}
private void AllWorkersFinished()
{
labelTitle.Text = Messages.PATCHINGWIZARD_UPDATES_DONE_AUTOMATED_UPDATES_MODE;
progressBar.Value = 100;
pictureBox1.Image = null;
labelError.Text = Messages.CLOSE_WIZARD_CLICK_FINISH;
}
}
public static class Extensions
{
public static bool IsRestartRelatedPlanAction(this PlanAction a)
{
return
a is EvacuateHostPlanAction || a is RebootHostPlanAction || a is BringBabiesBackAction;
}
}
}
| 36.7872 | 218 | 0.507872 | [
"BSD-2-Clause"
] | ushamandya/xenadmin | XenAdmin/Wizards/PatchingWizard/PatchingWizard_AutomatedUpdatesPage.cs | 22,994 | C# |
// Copyright 2014 Serilog Contributors
// Based on Topshelf.Log4Net, 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.
using System;
using Serilog.Events;
using Topshelf.Logging;
namespace Serilog.Extras.Topshelf
{
class SerilogWriter : LogWriter
{
readonly ILogger _logger;
const string ObjectMessageTemplate = "{Object}";
public SerilogWriter(ILogger logger)
{
if (logger == null) throw new ArgumentNullException("logger");
_logger = logger;
}
static LogEventLevel TopshelfToSerilogLevel(LoggingLevel level)
{
if (level == LoggingLevel.All)
return LogEventLevel.Verbose;
if (level == LoggingLevel.Debug)
return LogEventLevel.Debug;
if (level == LoggingLevel.Info)
return LogEventLevel.Information;
if (level == LoggingLevel.Warn)
return LogEventLevel.Warning;
if (level == LoggingLevel.Error)
return LogEventLevel.Error;
return LogEventLevel.Fatal;
}
public void Log(LoggingLevel level, object obj)
{
_logger.Write(TopshelfToSerilogLevel(level), ObjectMessageTemplate, obj);
}
public void Log(LoggingLevel level, object obj, Exception exception)
{
_logger.Write(TopshelfToSerilogLevel(level), exception, ObjectMessageTemplate, obj);
}
public void Log(LoggingLevel level, LogWriterOutputProvider messageProvider)
{
_logger.Write(TopshelfToSerilogLevel(level), ObjectMessageTemplate, new MessageProvider(messageProvider));
}
public void LogFormat(LoggingLevel level, IFormatProvider formatProvider, string format, params object[] args)
{
_logger.Write(TopshelfToSerilogLevel(level), format, args);
}
public void LogFormat(LoggingLevel level, string format, params object[] args)
{
_logger.Write(TopshelfToSerilogLevel(level), format, args);
}
public void Debug(object obj)
{
_logger.Debug(ObjectMessageTemplate, obj);
}
public void Debug(object obj, Exception exception)
{
_logger.Debug(exception, ObjectMessageTemplate, obj);
}
public void Debug(LogWriterOutputProvider messageProvider)
{
_logger.Debug(ObjectMessageTemplate, new MessageProvider(messageProvider));
}
public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_logger.Debug(format, args);
}
public void DebugFormat(string format, params object[] args)
{
_logger.Debug(format, args);
}
public void Info(object obj)
{
_logger.Information(ObjectMessageTemplate, obj);
}
public void Info(object obj, Exception exception)
{
_logger.Information(exception, ObjectMessageTemplate, obj);
}
public void Info(LogWriterOutputProvider messageProvider)
{
_logger.Information(ObjectMessageTemplate, new MessageProvider(messageProvider));
}
public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_logger.Information(format, args);
}
public void InfoFormat(string format, params object[] args)
{
_logger.Information(format, args);
}
public void Warn(object obj)
{
_logger.Warning(ObjectMessageTemplate, obj);
}
public void Warn(object obj, Exception exception)
{
_logger.Warning(exception, ObjectMessageTemplate, obj);
}
public void Warn(LogWriterOutputProvider messageProvider)
{
_logger.Warning(ObjectMessageTemplate, new MessageProvider(messageProvider));
}
public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_logger.Warning(format, args);
}
public void WarnFormat(string format, params object[] args)
{
_logger.Warning(format, args);
}
public void Error(object obj)
{
_logger.Error(ObjectMessageTemplate, obj);
}
public void Error(object obj, Exception exception)
{
_logger.Error(exception, ObjectMessageTemplate, obj);
}
public void Error(LogWriterOutputProvider messageProvider)
{
_logger.Error(ObjectMessageTemplate, new MessageProvider(messageProvider));
}
public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_logger.Error(format, args);
}
public void ErrorFormat(string format, params object[] args)
{
_logger.Error(format, args);
}
public void Fatal(object obj)
{
_logger.Fatal(ObjectMessageTemplate, obj);
}
public void Fatal(object obj, Exception exception)
{
_logger.Fatal(exception, ObjectMessageTemplate, obj);
}
public void Fatal(LogWriterOutputProvider messageProvider)
{
_logger.Fatal(ObjectMessageTemplate, new MessageProvider(messageProvider));
}
public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_logger.Fatal(format, args);
}
public void FatalFormat(string format, params object[] args)
{
_logger.Fatal(format, args);
}
public bool IsDebugEnabled { get { return _logger.IsEnabled(LogEventLevel.Debug); } }
public bool IsInfoEnabled { get { return _logger.IsEnabled(LogEventLevel.Information); } }
public bool IsWarnEnabled { get { return _logger.IsEnabled(LogEventLevel.Warning); } }
public bool IsErrorEnabled { get { return _logger.IsEnabled(LogEventLevel.Error); } }
public bool IsFatalEnabled { get { return _logger.IsEnabled(LogEventLevel.Fatal); } }
}
}
| 33.160194 | 118 | 0.631679 | [
"Apache-2.0"
] | Mpdreamz/serilog | src/Serilog.Extras.Topshelf/Extras/Topshelf/SerilogWriter.cs | 6,831 | C# |
using SIPSorcery.GB28181.Servers.SIPMessage;
using SIPSorcery.GB28181.Sys.XML;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SIPSorcery.GB28181.Servers
{
public class GB28181Catalog
{
private static GB28181Catalog _instance;
private Dictionary<string, string> _devList;
public SIPMessageCoreService MessageCore;
public Action<Catalog> OnCatalogReceived;
public Action<NotifyCatalog> OnNotifyCatalogReceived;
/// <summary>
/// 设备列表
/// </summary>
public Dictionary<string, string> DevList
{
get { return _devList; }
}
/// <summary>
/// 以单例模式访问
/// </summary>
public static GB28181Catalog Instance
{
get
{
if (_instance == null)
{
_instance = new GB28181Catalog();
}
return _instance;
}
}
private GB28181Catalog()
{
_devList = new Dictionary<string, string>();
}
/// <summary>
/// 获取设备目录
/// </summary>
public void GetCatalog()
{
MessageCore.DeviceCatalogQuery();
}
}
}
| 22.965517 | 61 | 0.542042 | [
"BSD-2-Clause"
] | 7956968/gb28181-sip | SIPSorcery.28181/Servers.Cores/GB28181Catalog.cs | 1,368 | C# |
using DevZest.Data.CodeAnalysis;
using DevZest.Data.Presenters;
using Microsoft.CodeAnalysis;
using System.Collections;
using System.Linq;
namespace DevZest.Data.Tools
{
partial class RelationshipWindow
{
private sealed class Presenter : SimplePresenter
{
private readonly Scalar<string> _name;
private readonly Scalar<IPropertySymbol> _foreignKey;
private readonly Scalar<IPropertySymbol> _refTable;
private readonly Scalar<IEnumerable> _refTableSelection;
private readonly Scalar<string> _description;
private readonly Scalar<ForeignKeyRule> _deleteRule;
private readonly Scalar<ForeignKeyRule> _updateRule;
public Presenter(DbMapper dbMapper, IPropertySymbol dbTable, RelationshipWindow window)
{
_window = window;
_dbMapper = dbMapper;
_dbTable = dbTable;
_foreignKey = NewScalar<IPropertySymbol>().AddValidator(Extensions.ValidateRequired);
_refTable = NewScalar<IPropertySymbol>().AddValidator(Extensions.ValidateRequired);
_name = NewScalar<string>().AddValidator(Extensions.ValidateRequired).AddValidator(dbMapper.ValidateIdentifier);
_refTableSelection = NewScalar<IEnumerable>();
_description = NewScalar<string>();
_deleteRule = NewScalar(ForeignKeyRule.None);
_updateRule = NewScalar(ForeignKeyRule.None);
Show(_window._view);
}
private readonly RelationshipWindow _window;
private readonly DbMapper _dbMapper;
private readonly IPropertySymbol _dbTable;
protected override void OnValueChanged(IScalars scalars)
{
base.OnValueChanged(scalars);
if (scalars.Contains(_foreignKey))
{
var refTables = _dbMapper.GetRefTables(_dbTable, _foreignKey.Value);
_refTableSelection.Value = refTables.Select(x => new { Value = x, Display = x == _dbTable ? "_" : x.Name }).OrderBy(x => x.Display);
_refTable.EditValue(refTables.FirstOrDefault());
_name.EditValue(GetName());
}
}
private string GetName()
{
var fkName = _foreignKey.Value?.Name;
if (string.IsNullOrEmpty(fkName))
return null;
if (fkName.StartsWith("FK_"))
fkName = fkName.Substring(3);
return string.Format("FK_{0}_{1}", _dbTable.Name, fkName);
}
public void Execute(AddRelationshipDelegate addRelationship)
{
addRelationship(_name.Value, _foreignKey.Value, _refTable.Value, _description.Value, _deleteRule.Value, _updateRule.Value);
}
private IEnumerable GetRuleSelection()
{
yield return new { Value = ForeignKeyRule.None, Display = nameof(ForeignKeyRule.None) };
yield return new { Value = ForeignKeyRule.Cascade, Display = nameof(ForeignKeyRule.Cascade) };
yield return new { Value = ForeignKeyRule.SetDefault, Display = nameof(ForeignKeyRule.SetDefault) };
yield return new { Value = ForeignKeyRule.SetNull, Display = nameof(ForeignKeyRule.SetNull) };
}
protected override void BuildTemplate(TemplateBuilder builder)
{
builder
.AddBinding(_window._comboBoxForeignKey, _foreignKey.BindToComboBox(_dbMapper.GetFkSelection(_dbTable)))
.AddBinding(_window._comboBoxRefTable, _refTable.BindToComboBox(_refTableSelection))
.AddBinding(_window._textBoxName, _name.BindToTextBox())
.AddBinding(_window._textBoxDescription, _description.BindToTextBox())
.AddBinding(_window._comboBoxDeleteRule, _deleteRule.BindToComboBox(GetRuleSelection()))
.AddBinding(_window._comboBoxUpdateRule, _updateRule.BindToComboBox(GetRuleSelection()));
}
}
}
}
| 45.902174 | 152 | 0.61757 | [
"MIT"
] | DevZest/RDO.Net | src/Tools.Vsix/RelationshipWindow.Presenter.cs | 4,225 | 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Internal;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.WebUtilities
{
/// <summary>
/// Used to read an 'application/x-www-form-urlencoded' form.
/// Internally reads from a PipeReader.
/// </summary>
public class FormPipeReader
{
private const int StackAllocThreshold = 128;
private const int DefaultValueCountLimit = 1024;
private const int DefaultKeyLengthLimit = 1024 * 2;
private const int DefaultValueLengthLimit = 1024 * 1024 * 4;
// Used for UTF8/ASCII (precalculated for fast path)
// This uses C# compiler's ability to refer to static data directly. For more information see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static
private static ReadOnlySpan<byte> UTF8EqualEncoded => new byte[] { (byte)'=' };
private static ReadOnlySpan<byte> UTF8AndEncoded => new byte[] { (byte)'&' };
// Used for other encodings
private readonly byte[]? _otherEqualEncoding;
private readonly byte[]? _otherAndEncoding;
private readonly PipeReader _pipeReader;
private readonly Encoding _encoding;
/// <summary>
/// Initializes a new instance of <see cref="FormPipeReader"/>.
/// </summary>
/// <param name="pipeReader">The <see cref="PipeReader"/> to read from.</param>
public FormPipeReader(PipeReader pipeReader)
: this(pipeReader, Encoding.UTF8)
{
}
/// <summary>
/// Initializes a new instance of <see cref="FormPipeReader"/>.
/// </summary>
/// <param name="pipeReader">The <see cref="PipeReader"/> to read from.</param>
/// <param name="encoding">The <see cref="Encoding"/>.</param>
public FormPipeReader(PipeReader pipeReader, Encoding encoding)
{
// https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-warnings/syslib0001
if (encoding is Encoding { CodePage: 65000 })
{
throw new ArgumentException("UTF7 is unsupported and insecure. Please select a different encoding.");
}
_pipeReader = pipeReader;
_encoding = encoding;
if (_encoding != Encoding.UTF8 && _encoding != Encoding.ASCII)
{
_otherEqualEncoding = _encoding.GetBytes("=");
_otherAndEncoding = _encoding.GetBytes("&");
}
}
/// <summary>
/// The limit on the number of form values to allow in ReadForm or ReadFormAsync.
/// </summary>
public int ValueCountLimit { get; set; } = DefaultValueCountLimit;
/// <summary>
/// The limit on the length of form keys.
/// </summary>
public int KeyLengthLimit { get; set; } = DefaultKeyLengthLimit;
/// <summary>
/// The limit on the length of form values.
/// </summary>
public int ValueLengthLimit { get; set; } = DefaultValueLengthLimit;
/// <summary>
/// Parses an HTTP form body.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The collection containing the parsed HTTP form body.</returns>
public async Task<Dictionary<string, StringValues>> ReadFormAsync(CancellationToken cancellationToken = default)
{
KeyValueAccumulator accumulator = default;
while (true)
{
var readResult = await _pipeReader.ReadAsync(cancellationToken);
var buffer = readResult.Buffer;
if (!buffer.IsEmpty)
{
try
{
ParseFormValues(ref buffer, ref accumulator, readResult.IsCompleted);
}
catch
{
_pipeReader.AdvanceTo(buffer.Start, buffer.End);
throw;
}
}
if (readResult.IsCompleted)
{
_pipeReader.AdvanceTo(buffer.End);
if (!buffer.IsEmpty)
{
throw new InvalidOperationException("End of body before form was fully parsed.");
}
break;
}
_pipeReader.AdvanceTo(buffer.Start, buffer.End);
}
return accumulator.GetResults();
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void ParseFormValues(
ref ReadOnlySequence<byte> buffer,
ref KeyValueAccumulator accumulator,
bool isFinalBlock)
{
if (buffer.IsSingleSegment)
{
ParseFormValuesFast(buffer.FirstSpan,
ref accumulator,
isFinalBlock,
out var consumed);
buffer = buffer.Slice(consumed);
return;
}
ParseValuesSlow(ref buffer,
ref accumulator,
isFinalBlock);
}
// Fast parsing for single span in ReadOnlySequence
private void ParseFormValuesFast(ReadOnlySpan<byte> span,
ref KeyValueAccumulator accumulator,
bool isFinalBlock,
out int consumed)
{
ReadOnlySpan<byte> key;
ReadOnlySpan<byte> value;
consumed = 0;
var equalsDelimiter = GetEqualsForEncoding();
var andDelimiter = GetAndForEncoding();
while (span.Length > 0)
{
// Find the end of the key=value pair.
var ampersand = span.IndexOf(andDelimiter);
ReadOnlySpan<byte> keyValuePair;
int equals;
var foundAmpersand = ampersand != -1;
if (foundAmpersand)
{
keyValuePair = span.Slice(0, ampersand);
span = span.Slice(keyValuePair.Length + andDelimiter.Length);
consumed += keyValuePair.Length + andDelimiter.Length;
}
else
{
// We can't know that what is currently read is the end of the form value, that's only the case if this is the final block
// If we're not in the final block, then consume nothing
if (!isFinalBlock)
{
// Don't buffer indefinitely
if ((uint)span.Length > (uint)KeyLengthLimit + (uint)ValueLengthLimit)
{
ThrowKeyOrValueTooLargeException();
}
return;
}
keyValuePair = span;
span = default;
consumed += keyValuePair.Length;
}
equals = keyValuePair.IndexOf(equalsDelimiter);
if (equals == -1)
{
// Too long for the whole segment to be a key.
if (keyValuePair.Length > KeyLengthLimit)
{
ThrowKeyTooLargeException();
}
// There is no more data, this segment must be "key" with no equals or value.
key = keyValuePair;
value = default;
}
else
{
key = keyValuePair.Slice(0, equals);
if (key.Length > KeyLengthLimit)
{
ThrowKeyTooLargeException();
}
value = keyValuePair.Slice(equals + equalsDelimiter.Length);
if (value.Length > ValueLengthLimit)
{
ThrowValueTooLargeException();
}
}
var decodedKey = GetDecodedString(key);
var decodedValue = GetDecodedString(value);
AppendAndVerify(ref accumulator, decodedKey, decodedValue);
}
}
// For multi-segment parsing of a read only sequence
private void ParseValuesSlow(
ref ReadOnlySequence<byte> buffer,
ref KeyValueAccumulator accumulator,
bool isFinalBlock)
{
var sequenceReader = new SequenceReader<byte>(buffer);
ReadOnlySequence<byte> keyValuePair;
var consumed = sequenceReader.Position;
var consumedBytes = default(long);
var equalsDelimiter = GetEqualsForEncoding();
var andDelimiter = GetAndForEncoding();
while (!sequenceReader.End)
{
if (!sequenceReader.TryReadTo(out keyValuePair, andDelimiter))
{
if (!isFinalBlock)
{
// Don't buffer indefinitely
if ((uint)(sequenceReader.Consumed - consumedBytes) > (uint)KeyLengthLimit + (uint)ValueLengthLimit)
{
ThrowKeyOrValueTooLargeException();
}
break;
}
// This must be the final key=value pair
keyValuePair = buffer.Slice(sequenceReader.Position);
sequenceReader.Advance(keyValuePair.Length);
}
if (keyValuePair.IsSingleSegment)
{
ParseFormValuesFast(keyValuePair.FirstSpan, ref accumulator, isFinalBlock: true, out var segmentConsumed);
Debug.Assert(segmentConsumed == keyValuePair.FirstSpan.Length);
consumedBytes = sequenceReader.Consumed;
consumed = sequenceReader.Position;
continue;
}
var keyValueReader = new SequenceReader<byte>(keyValuePair);
ReadOnlySequence<byte> value;
if (keyValueReader.TryReadTo(out ReadOnlySequence<byte> key, equalsDelimiter))
{
if (key.Length > KeyLengthLimit)
{
ThrowKeyTooLargeException();
}
value = keyValuePair.Slice(keyValueReader.Position);
if (value.Length > ValueLengthLimit)
{
ThrowValueTooLargeException();
}
}
else
{
// Too long for the whole segment to be a key.
if (keyValuePair.Length > KeyLengthLimit)
{
ThrowKeyTooLargeException();
}
// There is no more data, this segment must be "key" with no equals or value.
key = keyValuePair;
value = default;
}
var decodedKey = GetDecodedStringFromReadOnlySequence(key);
var decodedValue = GetDecodedStringFromReadOnlySequence(value);
AppendAndVerify(ref accumulator, decodedKey, decodedValue);
consumedBytes = sequenceReader.Consumed;
consumed = sequenceReader.Position;
}
buffer = buffer.Slice(consumed);
}
private void ThrowKeyOrValueTooLargeException()
{
throw new InvalidDataException($"Form key length limit {KeyLengthLimit} or value length limit {ValueLengthLimit} exceeded.");
}
private void ThrowKeyTooLargeException()
{
throw new InvalidDataException($"Form key length limit {KeyLengthLimit} exceeded.");
}
private void ThrowValueTooLargeException()
{
throw new InvalidDataException($"Form value length limit {ValueLengthLimit} exceeded.");
}
[SkipLocalsInit]
private string GetDecodedStringFromReadOnlySequence(in ReadOnlySequence<byte> ros)
{
if (ros.IsSingleSegment)
{
return GetDecodedString(ros.FirstSpan);
}
if (ros.Length < StackAllocThreshold)
{
Span<byte> buffer = stackalloc byte[StackAllocThreshold].Slice(0, (int)ros.Length);
ros.CopyTo(buffer);
return GetDecodedString(buffer);
}
else
{
var byteArray = ArrayPool<byte>.Shared.Rent((int)ros.Length);
try
{
Span<byte> buffer = byteArray.AsSpan(0, (int)ros.Length);
ros.CopyTo(buffer);
return GetDecodedString(buffer);
}
finally
{
ArrayPool<byte>.Shared.Return(byteArray);
}
}
}
// Check that key/value constraints are met and appends value to accumulator.
private void AppendAndVerify(ref KeyValueAccumulator accumulator, string decodedKey, string decodedValue)
{
accumulator.Append(decodedKey, decodedValue);
if (accumulator.ValueCount > ValueCountLimit)
{
throw new InvalidDataException($"Form value count limit {ValueCountLimit} exceeded.");
}
}
private string GetDecodedString(ReadOnlySpan<byte> readOnlySpan)
{
if (readOnlySpan.Length == 0)
{
return string.Empty;
}
else if (_encoding == Encoding.UTF8 || _encoding == Encoding.ASCII)
{
// UrlDecoder only works on UTF8 (and implicitly ASCII)
// We need to create a Span from a ReadOnlySpan. This cast is safe because the memory is still held by the pipe
// We will also create a string from it by the end of the function.
var span = MemoryMarshal.CreateSpan(ref Unsafe.AsRef(readOnlySpan[0]), readOnlySpan.Length);
try
{
var bytes = UrlDecoder.DecodeInPlace(span, isFormEncoding: true);
span = span.Slice(0, bytes);
return _encoding.GetString(span);
}
catch (InvalidOperationException ex)
{
throw new InvalidDataException("The form value contains invalid characters.", ex);
}
}
else
{
// Slow path for Unicode and other encodings.
// Just do raw string replacement.
var decodedString = _encoding.GetString(readOnlySpan);
decodedString = decodedString.Replace('+', ' ');
return Uri.UnescapeDataString(decodedString);
}
}
private ReadOnlySpan<byte> GetEqualsForEncoding()
{
if (_encoding == Encoding.UTF8 || _encoding == Encoding.ASCII)
{
return UTF8EqualEncoded;
}
else
{
return _otherEqualEncoding;
}
}
private ReadOnlySpan<byte> GetAndForEncoding()
{
if (_encoding == Encoding.UTF8 || _encoding == Encoding.ASCII)
{
return UTF8AndEncoded;
}
else
{
return _otherAndEncoding;
}
}
}
}
| 36.968037 | 167 | 0.525445 | [
"Apache-2.0"
] | Asifshikder/aspnetcore | src/Http/WebUtilities/src/FormPipeReader.cs | 16,192 | C# |
using System;
using System.IO;
namespace CursoCSharp.Api
{
class ExemploDirectoryInfo
{
public static void Executar()
{
var dirProjeto = @"~/source/repos/CursoCSharp/CursoCSharp".ParseHome();
var dirInfo = new DirectoryInfo(dirProjeto);
if(!dirInfo.Exists)
{
dirInfo.Create();
}
Console.WriteLine("=== Arquivos ===");
var arquivos = dirInfo.GetFiles();
foreach(var arquivo in arquivos)
{
Console.WriteLine(arquivo);
}
Console.WriteLine("\n=== Diretórios ===");
var pastas = dirInfo.GetDirectories();
foreach(var pasta in pastas)
{
Console.WriteLine(pasta);
}
Console.WriteLine(dirInfo.CreationTime);
Console.WriteLine(dirInfo.FullName);
Console.WriteLine(dirInfo.Root);
Console.WriteLine(dirInfo.Parent);
}
}
}
| 27.358974 | 84 | 0.504217 | [
"MIT"
] | GabrielSA87/c-sharp-course-pt-br | Api/ExemploDirectoryInfo.cs | 1,070 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel.Contacts
{
#if false || false || false || false || false || false || false
[global::System.FlagsAttribute]
public enum ContactQuerySearchFields : uint
{
// Skipping already declared field Windows.ApplicationModel.Contacts.ContactQuerySearchFields.None
// Skipping already declared field Windows.ApplicationModel.Contacts.ContactQuerySearchFields.Name
// Skipping already declared field Windows.ApplicationModel.Contacts.ContactQuerySearchFields.Email
// Skipping already declared field Windows.ApplicationModel.Contacts.ContactQuerySearchFields.Phone
// Skipping already declared field Windows.ApplicationModel.Contacts.ContactQuerySearchFields.All
}
#endif
}
| 47.823529 | 101 | 0.811808 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Contacts/ContactQuerySearchFields.cs | 813 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gagr = Google.Api.Gax.ResourceNames;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Gaming.V1Beta
{
/// <summary>Settings for <see cref="RealmsServiceClient"/> instances.</summary>
public sealed partial class RealmsServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="RealmsServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="RealmsServiceSettings"/>.</returns>
public static RealmsServiceSettings GetDefault() => new RealmsServiceSettings();
/// <summary>Constructs a new <see cref="RealmsServiceSettings"/> object with default settings.</summary>
public RealmsServiceSettings()
{
}
private RealmsServiceSettings(RealmsServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListRealmsSettings = existing.ListRealmsSettings;
GetRealmSettings = existing.GetRealmSettings;
CreateRealmSettings = existing.CreateRealmSettings;
CreateRealmOperationsSettings = existing.CreateRealmOperationsSettings.Clone();
DeleteRealmSettings = existing.DeleteRealmSettings;
DeleteRealmOperationsSettings = existing.DeleteRealmOperationsSettings.Clone();
UpdateRealmSettings = existing.UpdateRealmSettings;
UpdateRealmOperationsSettings = existing.UpdateRealmOperationsSettings.Clone();
PreviewRealmUpdateSettings = existing.PreviewRealmUpdateSettings;
OnCopy(existing);
}
partial void OnCopy(RealmsServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RealmsServiceClient.ListRealms</c> and <c>RealmsServiceClient.ListRealmsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 1000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 10000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListRealmsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(1000), maxBackoff: sys::TimeSpan.FromMilliseconds(10000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RealmsServiceClient.GetRealm</c> and <c>RealmsServiceClient.GetRealmAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 1000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 10000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetRealmSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(1000), maxBackoff: sys::TimeSpan.FromMilliseconds(10000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RealmsServiceClient.CreateRealm</c> and <c>RealmsServiceClient.CreateRealmAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateRealmSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// Long Running Operation settings for calls to <c>RealmsServiceClient.CreateRealm</c> and
/// <c>RealmsServiceClient.CreateRealmAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings CreateRealmOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RealmsServiceClient.DeleteRealm</c> and <c>RealmsServiceClient.DeleteRealmAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteRealmSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// Long Running Operation settings for calls to <c>RealmsServiceClient.DeleteRealm</c> and
/// <c>RealmsServiceClient.DeleteRealmAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings DeleteRealmOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RealmsServiceClient.UpdateRealm</c> and <c>RealmsServiceClient.UpdateRealmAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateRealmSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// Long Running Operation settings for calls to <c>RealmsServiceClient.UpdateRealm</c> and
/// <c>RealmsServiceClient.UpdateRealmAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings UpdateRealmOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RealmsServiceClient.PreviewRealmUpdate</c> and <c>RealmsServiceClient.PreviewRealmUpdateAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 1000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 10000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings PreviewRealmUpdateSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(1000), maxBackoff: sys::TimeSpan.FromMilliseconds(10000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="RealmsServiceSettings"/> object.</returns>
public RealmsServiceSettings Clone() => new RealmsServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="RealmsServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class RealmsServiceClientBuilder : gaxgrpc::ClientBuilderBase<RealmsServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public RealmsServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public RealmsServiceClientBuilder()
{
UseJwtAccessWithScopes = RealmsServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref RealmsServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RealmsServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override RealmsServiceClient Build()
{
RealmsServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<RealmsServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<RealmsServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private RealmsServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return RealmsServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<RealmsServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return RealmsServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => RealmsServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => RealmsServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => RealmsServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>RealmsService client wrapper, for convenient use.</summary>
/// <remarks>
/// A realm is a grouping of game server clusters that are considered
/// interchangeable.
/// </remarks>
public abstract partial class RealmsServiceClient
{
/// <summary>
/// The default endpoint for the RealmsService service, which is a host of "gameservices.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "gameservices.googleapis.com:443";
/// <summary>The default RealmsService scopes.</summary>
/// <remarks>
/// The default RealmsService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="RealmsServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="RealmsServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="RealmsServiceClient"/>.</returns>
public static stt::Task<RealmsServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new RealmsServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="RealmsServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="RealmsServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="RealmsServiceClient"/>.</returns>
public static RealmsServiceClient Create() => new RealmsServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="RealmsServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="RealmsServiceSettings"/>.</param>
/// <returns>The created <see cref="RealmsServiceClient"/>.</returns>
internal static RealmsServiceClient Create(grpccore::CallInvoker callInvoker, RealmsServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
RealmsService.RealmsServiceClient grpcClient = new RealmsService.RealmsServiceClient(callInvoker);
return new RealmsServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC RealmsService client</summary>
public virtual RealmsService.RealmsServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Realm"/> resources.</returns>
public virtual gax::PagedEnumerable<ListRealmsResponse, Realm> ListRealms(ListRealmsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Realm"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListRealmsResponse, Realm> ListRealmsAsync(ListRealmsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Realm"/> resources.</returns>
public virtual gax::PagedEnumerable<ListRealmsResponse, Realm> ListRealms(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListRealms(new ListRealmsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Realm"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListRealmsResponse, Realm> ListRealmsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListRealmsAsync(new ListRealmsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Realm"/> resources.</returns>
public virtual gax::PagedEnumerable<ListRealmsResponse, Realm> ListRealms(gagr::LocationName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListRealms(new ListRealmsRequest
{
ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Realm"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListRealmsResponse, Realm> ListRealmsAsync(gagr::LocationName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListRealmsAsync(new ListRealmsRequest
{
ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Realm GetRealm(GetRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Realm> GetRealmAsync(GetRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Realm> GetRealmAsync(GetRealmRequest request, st::CancellationToken cancellationToken) =>
GetRealmAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to retrieve. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Realm GetRealm(string name, gaxgrpc::CallSettings callSettings = null) =>
GetRealm(new GetRealmRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to retrieve. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Realm> GetRealmAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
GetRealmAsync(new GetRealmRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to retrieve. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Realm> GetRealmAsync(string name, st::CancellationToken cancellationToken) =>
GetRealmAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to retrieve. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Realm GetRealm(RealmName name, gaxgrpc::CallSettings callSettings = null) =>
GetRealm(new GetRealmRequest
{
RealmName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to retrieve. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Realm> GetRealmAsync(RealmName name, gaxgrpc::CallSettings callSettings = null) =>
GetRealmAsync(new GetRealmRequest
{
RealmName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to retrieve. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Realm> GetRealmAsync(RealmName name, st::CancellationToken cancellationToken) =>
GetRealmAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Realm, OperationMetadata> CreateRealm(CreateRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> CreateRealmAsync(CreateRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> CreateRealmAsync(CreateRealmRequest request, st::CancellationToken cancellationToken) =>
CreateRealmAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>CreateRealm</c>.</summary>
public virtual lro::OperationsClient CreateRealmOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>CreateRealm</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Realm, OperationMetadata> PollOnceCreateRealm(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Realm, OperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateRealmOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>CreateRealm</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> PollOnceCreateRealmAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Realm, OperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateRealmOperationsClient, callSettings);
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="realm">
/// Required. The realm resource to be created.
/// </param>
/// <param name="realmId">
/// Required. The ID of the realm resource to be created.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Realm, OperationMetadata> CreateRealm(string parent, Realm realm, string realmId, gaxgrpc::CallSettings callSettings = null) =>
CreateRealm(new CreateRealmRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
RealmId = gax::GaxPreconditions.CheckNotNullOrEmpty(realmId, nameof(realmId)),
Realm = gax::GaxPreconditions.CheckNotNull(realm, nameof(realm)),
}, callSettings);
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="realm">
/// Required. The realm resource to be created.
/// </param>
/// <param name="realmId">
/// Required. The ID of the realm resource to be created.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> CreateRealmAsync(string parent, Realm realm, string realmId, gaxgrpc::CallSettings callSettings = null) =>
CreateRealmAsync(new CreateRealmRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
RealmId = gax::GaxPreconditions.CheckNotNullOrEmpty(realmId, nameof(realmId)),
Realm = gax::GaxPreconditions.CheckNotNull(realm, nameof(realm)),
}, callSettings);
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="realm">
/// Required. The realm resource to be created.
/// </param>
/// <param name="realmId">
/// Required. The ID of the realm resource to be created.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> CreateRealmAsync(string parent, Realm realm, string realmId, st::CancellationToken cancellationToken) =>
CreateRealmAsync(parent, realm, realmId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="realm">
/// Required. The realm resource to be created.
/// </param>
/// <param name="realmId">
/// Required. The ID of the realm resource to be created.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Realm, OperationMetadata> CreateRealm(gagr::LocationName parent, Realm realm, string realmId, gaxgrpc::CallSettings callSettings = null) =>
CreateRealm(new CreateRealmRequest
{
ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
RealmId = gax::GaxPreconditions.CheckNotNullOrEmpty(realmId, nameof(realmId)),
Realm = gax::GaxPreconditions.CheckNotNull(realm, nameof(realm)),
}, callSettings);
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="realm">
/// Required. The realm resource to be created.
/// </param>
/// <param name="realmId">
/// Required. The ID of the realm resource to be created.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> CreateRealmAsync(gagr::LocationName parent, Realm realm, string realmId, gaxgrpc::CallSettings callSettings = null) =>
CreateRealmAsync(new CreateRealmRequest
{
ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
RealmId = gax::GaxPreconditions.CheckNotNullOrEmpty(realmId, nameof(realmId)),
Realm = gax::GaxPreconditions.CheckNotNull(realm, nameof(realm)),
}, callSettings);
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name. Uses the form:
/// `projects/{project}/locations/{location}`.
/// </param>
/// <param name="realm">
/// Required. The realm resource to be created.
/// </param>
/// <param name="realmId">
/// Required. The ID of the realm resource to be created.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> CreateRealmAsync(gagr::LocationName parent, Realm realm, string realmId, st::CancellationToken cancellationToken) =>
CreateRealmAsync(parent, realm, realmId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<wkt::Empty, OperationMetadata> DeleteRealm(DeleteRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> DeleteRealmAsync(DeleteRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> DeleteRealmAsync(DeleteRealmRequest request, st::CancellationToken cancellationToken) =>
DeleteRealmAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>DeleteRealm</c>.</summary>
public virtual lro::OperationsClient DeleteRealmOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>DeleteRealm</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<wkt::Empty, OperationMetadata> PollOnceDeleteRealm(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<wkt::Empty, OperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteRealmOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>DeleteRealm</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> PollOnceDeleteRealmAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<wkt::Empty, OperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteRealmOperationsClient, callSettings);
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to delete. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<wkt::Empty, OperationMetadata> DeleteRealm(string name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRealm(new DeleteRealmRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to delete. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> DeleteRealmAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRealmAsync(new DeleteRealmRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to delete. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> DeleteRealmAsync(string name, st::CancellationToken cancellationToken) =>
DeleteRealmAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to delete. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<wkt::Empty, OperationMetadata> DeleteRealm(RealmName name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRealm(new DeleteRealmRequest
{
RealmName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to delete. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> DeleteRealmAsync(RealmName name, gaxgrpc::CallSettings callSettings = null) =>
DeleteRealmAsync(new DeleteRealmRequest
{
RealmName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="name">
/// Required. The name of the realm to delete. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> DeleteRealmAsync(RealmName name, st::CancellationToken cancellationToken) =>
DeleteRealmAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Realm, OperationMetadata> UpdateRealm(UpdateRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> UpdateRealmAsync(UpdateRealmRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> UpdateRealmAsync(UpdateRealmRequest request, st::CancellationToken cancellationToken) =>
UpdateRealmAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>UpdateRealm</c>.</summary>
public virtual lro::OperationsClient UpdateRealmOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>UpdateRealm</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Realm, OperationMetadata> PollOnceUpdateRealm(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Realm, OperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateRealmOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>UpdateRealm</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> PollOnceUpdateRealmAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Realm, OperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateRealmOperationsClient, callSettings);
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="realm">
/// Required. The realm to be updated.
/// Only fields specified in update_mask are updated.
/// </param>
/// <param name="updateMask">
/// Required. The update mask applies to the resource. For the `FieldMask`
/// definition, see
///
/// https:
/// //developers.google.com/protocol-buffers
/// // /docs/reference/google.protobuf#fieldmask
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Realm, OperationMetadata> UpdateRealm(Realm realm, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateRealm(new UpdateRealmRequest
{
Realm = gax::GaxPreconditions.CheckNotNull(realm, nameof(realm)),
UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)),
}, callSettings);
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="realm">
/// Required. The realm to be updated.
/// Only fields specified in update_mask are updated.
/// </param>
/// <param name="updateMask">
/// Required. The update mask applies to the resource. For the `FieldMask`
/// definition, see
///
/// https:
/// //developers.google.com/protocol-buffers
/// // /docs/reference/google.protobuf#fieldmask
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> UpdateRealmAsync(Realm realm, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateRealmAsync(new UpdateRealmRequest
{
Realm = gax::GaxPreconditions.CheckNotNull(realm, nameof(realm)),
UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)),
}, callSettings);
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="realm">
/// Required. The realm to be updated.
/// Only fields specified in update_mask are updated.
/// </param>
/// <param name="updateMask">
/// Required. The update mask applies to the resource. For the `FieldMask`
/// definition, see
///
/// https:
/// //developers.google.com/protocol-buffers
/// // /docs/reference/google.protobuf#fieldmask
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Realm, OperationMetadata>> UpdateRealmAsync(Realm realm, wkt::FieldMask updateMask, st::CancellationToken cancellationToken) =>
UpdateRealmAsync(realm, updateMask, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Previews patches to a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual PreviewRealmUpdateResponse PreviewRealmUpdate(PreviewRealmUpdateRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Previews patches to a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<PreviewRealmUpdateResponse> PreviewRealmUpdateAsync(PreviewRealmUpdateRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Previews patches to a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<PreviewRealmUpdateResponse> PreviewRealmUpdateAsync(PreviewRealmUpdateRequest request, st::CancellationToken cancellationToken) =>
PreviewRealmUpdateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>RealmsService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A realm is a grouping of game server clusters that are considered
/// interchangeable.
/// </remarks>
public sealed partial class RealmsServiceClientImpl : RealmsServiceClient
{
private readonly gaxgrpc::ApiCall<ListRealmsRequest, ListRealmsResponse> _callListRealms;
private readonly gaxgrpc::ApiCall<GetRealmRequest, Realm> _callGetRealm;
private readonly gaxgrpc::ApiCall<CreateRealmRequest, lro::Operation> _callCreateRealm;
private readonly gaxgrpc::ApiCall<DeleteRealmRequest, lro::Operation> _callDeleteRealm;
private readonly gaxgrpc::ApiCall<UpdateRealmRequest, lro::Operation> _callUpdateRealm;
private readonly gaxgrpc::ApiCall<PreviewRealmUpdateRequest, PreviewRealmUpdateResponse> _callPreviewRealmUpdate;
/// <summary>
/// Constructs a client wrapper for the RealmsService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="RealmsServiceSettings"/> used within this client.</param>
public RealmsServiceClientImpl(RealmsService.RealmsServiceClient grpcClient, RealmsServiceSettings settings)
{
GrpcClient = grpcClient;
RealmsServiceSettings effectiveSettings = settings ?? RealmsServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
CreateRealmOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.CreateRealmOperationsSettings);
DeleteRealmOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.DeleteRealmOperationsSettings);
UpdateRealmOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.UpdateRealmOperationsSettings);
_callListRealms = clientHelper.BuildApiCall<ListRealmsRequest, ListRealmsResponse>(grpcClient.ListRealmsAsync, grpcClient.ListRealms, effectiveSettings.ListRealmsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListRealms);
Modify_ListRealmsApiCall(ref _callListRealms);
_callGetRealm = clientHelper.BuildApiCall<GetRealmRequest, Realm>(grpcClient.GetRealmAsync, grpcClient.GetRealm, effectiveSettings.GetRealmSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetRealm);
Modify_GetRealmApiCall(ref _callGetRealm);
_callCreateRealm = clientHelper.BuildApiCall<CreateRealmRequest, lro::Operation>(grpcClient.CreateRealmAsync, grpcClient.CreateRealm, effectiveSettings.CreateRealmSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateRealm);
Modify_CreateRealmApiCall(ref _callCreateRealm);
_callDeleteRealm = clientHelper.BuildApiCall<DeleteRealmRequest, lro::Operation>(grpcClient.DeleteRealmAsync, grpcClient.DeleteRealm, effectiveSettings.DeleteRealmSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteRealm);
Modify_DeleteRealmApiCall(ref _callDeleteRealm);
_callUpdateRealm = clientHelper.BuildApiCall<UpdateRealmRequest, lro::Operation>(grpcClient.UpdateRealmAsync, grpcClient.UpdateRealm, effectiveSettings.UpdateRealmSettings).WithGoogleRequestParam("realm.name", request => request.Realm?.Name);
Modify_ApiCall(ref _callUpdateRealm);
Modify_UpdateRealmApiCall(ref _callUpdateRealm);
_callPreviewRealmUpdate = clientHelper.BuildApiCall<PreviewRealmUpdateRequest, PreviewRealmUpdateResponse>(grpcClient.PreviewRealmUpdateAsync, grpcClient.PreviewRealmUpdate, effectiveSettings.PreviewRealmUpdateSettings).WithGoogleRequestParam("realm.name", request => request.Realm?.Name);
Modify_ApiCall(ref _callPreviewRealmUpdate);
Modify_PreviewRealmUpdateApiCall(ref _callPreviewRealmUpdate);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListRealmsApiCall(ref gaxgrpc::ApiCall<ListRealmsRequest, ListRealmsResponse> call);
partial void Modify_GetRealmApiCall(ref gaxgrpc::ApiCall<GetRealmRequest, Realm> call);
partial void Modify_CreateRealmApiCall(ref gaxgrpc::ApiCall<CreateRealmRequest, lro::Operation> call);
partial void Modify_DeleteRealmApiCall(ref gaxgrpc::ApiCall<DeleteRealmRequest, lro::Operation> call);
partial void Modify_UpdateRealmApiCall(ref gaxgrpc::ApiCall<UpdateRealmRequest, lro::Operation> call);
partial void Modify_PreviewRealmUpdateApiCall(ref gaxgrpc::ApiCall<PreviewRealmUpdateRequest, PreviewRealmUpdateResponse> call);
partial void OnConstruction(RealmsService.RealmsServiceClient grpcClient, RealmsServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC RealmsService client</summary>
public override RealmsService.RealmsServiceClient GrpcClient { get; }
partial void Modify_ListRealmsRequest(ref ListRealmsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetRealmRequest(ref GetRealmRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateRealmRequest(ref CreateRealmRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteRealmRequest(ref DeleteRealmRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateRealmRequest(ref UpdateRealmRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_PreviewRealmUpdateRequest(ref PreviewRealmUpdateRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Realm"/> resources.</returns>
public override gax::PagedEnumerable<ListRealmsResponse, Realm> ListRealms(ListRealmsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListRealmsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListRealmsRequest, ListRealmsResponse, Realm>(_callListRealms, request, callSettings);
}
/// <summary>
/// Lists realms in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Realm"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListRealmsResponse, Realm> ListRealmsAsync(ListRealmsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListRealmsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListRealmsRequest, ListRealmsResponse, Realm>(_callListRealms, request, callSettings);
}
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Realm GetRealm(GetRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetRealmRequest(ref request, ref callSettings);
return _callGetRealm.Sync(request, callSettings);
}
/// <summary>
/// Gets details of a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Realm> GetRealmAsync(GetRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetRealmRequest(ref request, ref callSettings);
return _callGetRealm.Async(request, callSettings);
}
/// <summary>The long-running operations client for <c>CreateRealm</c>.</summary>
public override lro::OperationsClient CreateRealmOperationsClient { get; }
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<Realm, OperationMetadata> CreateRealm(CreateRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateRealmRequest(ref request, ref callSettings);
return new lro::Operation<Realm, OperationMetadata>(_callCreateRealm.Sync(request, callSettings), CreateRealmOperationsClient);
}
/// <summary>
/// Creates a new realm in a given project and location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<Realm, OperationMetadata>> CreateRealmAsync(CreateRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateRealmRequest(ref request, ref callSettings);
return new lro::Operation<Realm, OperationMetadata>(await _callCreateRealm.Async(request, callSettings).ConfigureAwait(false), CreateRealmOperationsClient);
}
/// <summary>The long-running operations client for <c>DeleteRealm</c>.</summary>
public override lro::OperationsClient DeleteRealmOperationsClient { get; }
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<wkt::Empty, OperationMetadata> DeleteRealm(DeleteRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteRealmRequest(ref request, ref callSettings);
return new lro::Operation<wkt::Empty, OperationMetadata>(_callDeleteRealm.Sync(request, callSettings), DeleteRealmOperationsClient);
}
/// <summary>
/// Deletes a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<wkt::Empty, OperationMetadata>> DeleteRealmAsync(DeleteRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteRealmRequest(ref request, ref callSettings);
return new lro::Operation<wkt::Empty, OperationMetadata>(await _callDeleteRealm.Async(request, callSettings).ConfigureAwait(false), DeleteRealmOperationsClient);
}
/// <summary>The long-running operations client for <c>UpdateRealm</c>.</summary>
public override lro::OperationsClient UpdateRealmOperationsClient { get; }
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<Realm, OperationMetadata> UpdateRealm(UpdateRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateRealmRequest(ref request, ref callSettings);
return new lro::Operation<Realm, OperationMetadata>(_callUpdateRealm.Sync(request, callSettings), UpdateRealmOperationsClient);
}
/// <summary>
/// Patches a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<Realm, OperationMetadata>> UpdateRealmAsync(UpdateRealmRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateRealmRequest(ref request, ref callSettings);
return new lro::Operation<Realm, OperationMetadata>(await _callUpdateRealm.Async(request, callSettings).ConfigureAwait(false), UpdateRealmOperationsClient);
}
/// <summary>
/// Previews patches to a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override PreviewRealmUpdateResponse PreviewRealmUpdate(PreviewRealmUpdateRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_PreviewRealmUpdateRequest(ref request, ref callSettings);
return _callPreviewRealmUpdate.Sync(request, callSettings);
}
/// <summary>
/// Previews patches to a single realm.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<PreviewRealmUpdateResponse> PreviewRealmUpdateAsync(PreviewRealmUpdateRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_PreviewRealmUpdateRequest(ref request, ref callSettings);
return _callPreviewRealmUpdate.Async(request, callSettings);
}
}
public partial class ListRealmsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListRealmsResponse : gaxgrpc::IPageResponse<Realm>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Realm> GetEnumerator() => Realms.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public static partial class RealmsService
{
public partial class RealmsServiceClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as
/// this client.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClient() =>
new lro::Operations.OperationsClient(CallInvoker);
}
}
}
| 57.835338 | 512 | 0.657324 | [
"Apache-2.0"
] | Mattlk13/google-cloud-dotnet | apis/Google.Cloud.Gaming.V1Beta/Google.Cloud.Gaming.V1Beta/RealmsServiceClient.g.cs | 76,921 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Identity_Razor.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 43.099548 | 122 | 0.498688 | [
"MIT"
] | chavi25/Identity_razor | Identity_Razor/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 9,527 | C# |
/*NEVER BUG*/
//
// PureMVC C# Standard
//
// Copyright(c) 2017 Saad Shams <[email protected]>
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
using System;
using System.Collections.Concurrent;
using PureMVC.Interfaces;
namespace PureMVC.Core
{
/// <summary>
/// A Singleton <c>IModel</c> implementation
/// </summary>
/// <remarks>
/// <para>In PureMVC, the <c>Model</c> class provides access to model objects (Proxies) by named lookup</para>
/// <para>The <c>Model</c> assumes these responsibilities:</para>
/// <list type="bullet">
/// <item>Maintain a cache of <c>IProxy</c> instances</item>
/// <item>Provide methods for registering, retrieving, and removing <c>IProxy</c> instances</item>
/// </list>
/// <para>
/// Your application must register <c>IProxy</c> instances
/// with the <c>Model</c>. Typically, you use an
/// <c>ICommand</c> to create and register <c>IProxy</c>
/// instances once the <c>Facade</c> has initialized the Core actors
/// </para>
/// </remarks>
/// <seealso cref="PureMVC.Patterns.Proxy"/>
/// <seealso cref="PureMVC.Interfaces.IProxy" />
public class Model: IModel
{
/// <summary>
/// Constructs and initializes a new model
/// </summary>
/// <remarks>
/// <para>
/// This <c>IModel</c> implementation is a Singleton,
/// so you should not call the constructor
/// directly, but instead call the static Singleton
/// Factory method <c>Model.getInstance(() => new Model())</c>
/// </para>
/// </remarks>
/// <exception cref="System.Exception">Thrown if instance for this Singleton key has already been constructed</exception>
public Model()
{
if (instance != null) throw new Exception(Singleton_MSG);
instance = this;
proxyMap = new ConcurrentDictionary<string, IProxy>();
InitializeModel();
}
/// <summary>
/// Initialize the Singleton <c>Model</c> instance.
/// </summary>
/// <remarks>
/// <para>
/// Called automatically by the constructor, this
/// is your opportunity to initialize the Singleton
/// instance in your subclass without overriding the
/// constructor
/// </para>
/// </remarks>
protected virtual void InitializeModel()
{
}
/// <summary>
/// <c>Model</c> Singleton Factory method.
/// </summary>
/// <param name="modelFunc">the <c>FuncDelegate</c> of the <c>IModel</c></param>
/// <returns>the instance for this Singleton key </returns>
public static IModel GetInstance(Func<IModel> modelFunc)
{
if (instance == null) {
instance = modelFunc();
}
return instance;
}
/// <summary>
/// Register an <c>IProxy</c> with the <c>Model</c>.
/// </summary>
/// <param name="proxy">proxy an <c>IProxy</c> to be held by the <c>Model</c>.</param>
public virtual void RegisterProxy(IProxy proxy)
{
proxyMap[proxy.ProxyName] = proxy;
proxy.OnRegister();
}
/// <summary>
/// Retrieve an <c>IProxy</c> from the <c>Model</c>.
/// </summary>
/// <param name="proxyName"></param>
/// <returns>the <c>IProxy</c> instance previously registered with the given <c>proxyName</c>.</returns>
public virtual IProxy RetrieveProxy(string proxyName)
{
IProxy proxy;
return proxyMap.TryGetValue(proxyName, out proxy) ? proxy : null;
}
/// <summary>
/// Remove an <c>IProxy</c> from the <c>Model</c>.
/// </summary>
/// <param name="proxyName">proxyName name of the <c>IProxy</c> instance to be removed.</param>
/// <returns>the <c>IProxy</c> that was removed from the <c>Model</c></returns>
public virtual IProxy RemoveProxy(string proxyName)
{
IProxy proxy;
if (proxyMap.TryRemove(proxyName, out proxy))
{
proxy.OnRemove();
}
return proxy;
}
/// <summary>
/// Check if a Proxy is registered
/// </summary>
/// <param name="proxyName"></param>
/// <returns>whether a Proxy is currently registered with the given <c>proxyName</c>.</returns>
public virtual bool HasProxy(string proxyName)
{
return proxyMap.ContainsKey(proxyName);
}
/// <summary>Mapping of proxyNames to IProxy instances</summary>
protected readonly ConcurrentDictionary<string, IProxy> proxyMap;
/// <summary>Singleton instance</summary>
protected static IModel instance;
/// <summary>Message Constants</summary>
protected const string Singleton_MSG = "Model Singleton already constructed!";
}
}
| 37.2 | 129 | 0.554531 | [
"MIT"
] | makoolabs/xframework | Assets/Plugins/XFramework/MVC/PureMVC/Core/Model.cs | 5,208 | C# |
namespace SRDebugger.UI.Controls.Data
{
using System;
using System.Collections.Generic;
using SRF;
using SRF.UI;
using UnityEngine;
using UnityEngine.UI;
public class NumberControl : DataBoundControl
{
private static readonly Type[] IntegerTypes =
{
typeof (int), typeof (short), typeof (byte), typeof (sbyte), typeof (uint), typeof (ushort)
};
private static readonly Type[] DecimalTypes =
{
typeof (float), typeof (double)
};
public static readonly Dictionary<Type, ValueRange> ValueRanges = new Dictionary<Type, ValueRange>
{
{typeof (int), new ValueRange {MaxValue = int.MaxValue, MinValue = int.MinValue}},
{typeof (short), new ValueRange {MaxValue = short.MaxValue, MinValue = short.MinValue}},
{typeof (byte), new ValueRange {MaxValue = byte.MaxValue, MinValue = byte.MinValue}},
{typeof (sbyte), new ValueRange {MaxValue = sbyte.MaxValue, MinValue = sbyte.MinValue}},
{typeof (uint), new ValueRange {MaxValue = uint.MaxValue, MinValue = uint.MinValue}},
{typeof (ushort), new ValueRange {MaxValue = ushort.MaxValue, MinValue = ushort.MinValue}},
{typeof (float), new ValueRange {MaxValue = float.MaxValue, MinValue = float.MinValue}},
{typeof (double), new ValueRange {MaxValue = double.MaxValue, MinValue = double.MinValue}}
};
private string _lastValue;
private Type _type;
public GameObject[] DisableOnReadOnly;
public SRNumberButton DownNumberButton;
[RequiredField] public SRNumberSpinner NumberSpinner;
[RequiredField] public Text Title;
public SRNumberButton UpNumberButton;
protected override void Start()
{
base.Start();
NumberSpinner.onEndEdit.AddListener(OnValueChanged);
}
private void OnValueChanged(string newValue)
{
try
{
var num = Convert.ChangeType(newValue, _type);
UpdateValue(num);
}
catch (Exception)
{
NumberSpinner.text = _lastValue;
}
}
protected override void OnBind(string propertyName, Type t)
{
base.OnBind(propertyName, t);
Title.text = propertyName;
if (IsIntegerType(t))
{
NumberSpinner.contentType = InputField.ContentType.IntegerNumber;
}
else if (IsDecimalType(t))
{
NumberSpinner.contentType = InputField.ContentType.DecimalNumber;
}
else
{
throw new ArgumentException("Type must be one of expected types", "t");
}
var rangeAttrib = Property.GetAttribute<SROptions.NumberRangeAttribute>();
NumberSpinner.MaxValue = GetMaxValue(t);
NumberSpinner.MinValue = GetMinValue(t);
if (rangeAttrib != null)
{
NumberSpinner.MaxValue = Math.Min(rangeAttrib.Max, NumberSpinner.MaxValue);
NumberSpinner.MinValue = Math.Max(rangeAttrib.Min, NumberSpinner.MinValue);
}
var incrementAttribute = Property.GetAttribute<SROptions.IncrementAttribute>();
if (incrementAttribute != null)
{
if (UpNumberButton != null)
{
UpNumberButton.Amount = incrementAttribute.Increment;
}
if (DownNumberButton != null)
{
DownNumberButton.Amount = -incrementAttribute.Increment;
}
}
_type = t;
NumberSpinner.interactable = !IsReadOnly;
if (DisableOnReadOnly != null)
{
foreach (var childControl in DisableOnReadOnly)
{
childControl.SetActive(!IsReadOnly);
}
}
}
protected override void OnValueUpdated(object newValue)
{
var value = Convert.ToDecimal(newValue).ToString();
if (value != _lastValue)
{
NumberSpinner.text = value;
}
_lastValue = value;
}
public override bool CanBind(Type type, bool isReadOnly)
{
return IsDecimalType(type) || IsIntegerType(type);
}
protected static bool IsIntegerType(Type t)
{
for (var i = 0; i < IntegerTypes.Length; i++)
{
if (IntegerTypes[i] == t)
{
return true;
}
}
return false;
}
protected static bool IsDecimalType(Type t)
{
for (var i = 0; i < DecimalTypes.Length; i++)
{
if (DecimalTypes[i] == t)
{
return true;
}
}
return false;
}
protected double GetMaxValue(Type t)
{
ValueRange value;
if (ValueRanges.TryGetValue(t, out value))
{
return value.MaxValue;
}
Debug.LogWarning("[NumberControl] No MaxValue stored for type {0}".Fmt(t));
return double.MaxValue;
}
protected double GetMinValue(Type t)
{
ValueRange value;
if (ValueRanges.TryGetValue(t, out value))
{
return value.MinValue;
}
Debug.LogWarning("[NumberControl] No MinValue stored for type {0}".Fmt(t));
return double.MinValue;
}
public struct ValueRange
{
public double MaxValue;
public double MinValue;
}
}
}
| 30.147208 | 106 | 0.529887 | [
"MIT"
] | 517752548/EXET | Unity/Assets/ThirdParty/StompyRobot/SRDebugger/Scripts/UI/Controls/Data/NumberControl.cs | 5,941 | C# |
// Instance generated by TankLibHelper.InstanceBuilder
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0x2CAC0A45)]
public class STU_2CAC0A45 : STUConfigVarFloatBase {
}
}
| 22.888889 | 55 | 0.757282 | [
"MIT"
] | Mike111177/OWLib | TankLib/STU/Types/STU_2CAC0A45.cs | 206 | C# |
using ARMeilleure.Decoders;
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.State;
using ARMeilleure.Translation;
using static ARMeilleure.Instructions.InstEmitAluHelper;
using static ARMeilleure.Instructions.InstEmitHelper;
using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
namespace ARMeilleure.Instructions
{
static partial class InstEmit32
{
public static void Add(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Add(n, m);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
EmitAddsCCheck(context, n, res);
EmitAddsVCheck(context, n, m, res);
}
EmitAluStore(context, res);
}
public static void Adc(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Add(n, m);
Operand carry = GetFlag(PState.CFlag);
res = context.Add(res, carry);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
EmitAdcsCCheck(context, n, res);
EmitAddsVCheck(context, n, m, res);
}
EmitAluStore(context, res);
}
public static void And(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res = context.BitwiseAnd(n, m);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
}
EmitAluStore(context, res);
}
public static void Bfc(ArmEmitterContext context)
{
OpCode32AluBf op = (OpCode32AluBf)context.CurrOp;
Operand d = GetIntA32(context, op.Rd);
Operand res = context.BitwiseAnd(d, Const(~op.DestMask));
SetIntA32(context, op.Rd, res);
}
public static void Bfi(ArmEmitterContext context)
{
OpCode32AluBf op = (OpCode32AluBf)context.CurrOp;
Operand n = GetIntA32(context, op.Rn);
Operand d = GetIntA32(context, op.Rd);
Operand part = context.BitwiseAnd(n, Const(op.SourceMask));
if (op.Lsb != 0)
{
part = context.ShiftLeft(part, Const(op.Lsb));
}
Operand res = context.BitwiseAnd(d, Const(~op.DestMask));
res = context.BitwiseOr(res, context.BitwiseAnd(part, Const(op.DestMask)));
SetIntA32(context, op.Rd, res);
}
public static void Bic(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res = context.BitwiseAnd(n, context.BitwiseNot(m));
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
}
EmitAluStore(context, res);
}
public static void Clz(ArmEmitterContext context)
{
Operand m = GetAluM(context, setCarry: false);
Operand res = context.CountLeadingZeros(m);
EmitAluStore(context, res);
}
public static void Cmp(ArmEmitterContext context)
{
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Subtract(n, m);
EmitNZFlagsCheck(context, res);
EmitSubsCCheck(context, n, res);
EmitSubsVCheck(context, n, m, res);
}
public static void Cmn(ArmEmitterContext context)
{
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Add(n, m);
EmitNZFlagsCheck(context, res);
EmitAddsCCheck(context, n, res);
EmitAddsVCheck(context, n, m, res);
}
public static void Eor(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res = context.BitwiseExclusiveOr(n, m);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
}
EmitAluStore(context, res);
}
public static void Mov(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand m = GetAluM(context);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, m);
}
EmitAluStore(context, m);
}
public static void Movt(ArmEmitterContext context)
{
OpCode32AluImm16 op = (OpCode32AluImm16)context.CurrOp;
Operand d = GetIntA32(context, op.Rd);
Operand imm = Const(op.Immediate << 16); // Immeditate value as top halfword.
Operand res = context.BitwiseAnd(d, Const(0x0000ffff));
res = context.BitwiseOr(res, imm);
EmitAluStore(context, res);
}
public static void Mul(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res = context.Multiply(n, m);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
}
EmitAluStore(context, res);
}
public static void Mvn(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand m = GetAluM(context);
Operand res = context.BitwiseNot(m);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
}
EmitAluStore(context, res);
}
public static void Orr(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res = context.BitwiseOr(n, m);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
}
EmitAluStore(context, res);
}
public static void Pkh(ArmEmitterContext context)
{
OpCode32AluRsImm op = (OpCode32AluRsImm)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res;
bool tbform = op.ShiftType == ShiftType.Asr;
if (tbform)
{
res = context.BitwiseOr(context.BitwiseAnd(n, Const(0xFFFF0000)), context.BitwiseAnd(m, Const(0xFFFF)));
}
else
{
res = context.BitwiseOr(context.BitwiseAnd(m, Const(0xFFFF0000)), context.BitwiseAnd(n, Const(0xFFFF)));
}
EmitAluStore(context, res);
}
public static void Rbit(ArmEmitterContext context)
{
Operand m = GetAluM(context);
Operand res = EmitReverseBits32Op(context, m);
EmitAluStore(context, res);
}
public static void Rev(ArmEmitterContext context)
{
Operand m = GetAluM(context);
Operand res = context.ByteSwap(m);
EmitAluStore(context, res);
}
public static void Rev16(ArmEmitterContext context)
{
Operand m = GetAluM(context);
Operand res = EmitReverseBytes16_32Op(context, m);
EmitAluStore(context, res);
}
public static void Revsh(ArmEmitterContext context)
{
Operand m = GetAluM(context);
Operand res = EmitReverseBytes16_32Op(context, m);
EmitAluStore(context, context.SignExtend16(OperandType.I32, res));
}
public static void Rsc(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Subtract(m, n);
Operand borrow = context.BitwiseExclusiveOr(GetFlag(PState.CFlag), Const(1));
res = context.Subtract(res, borrow);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
EmitSbcsCCheck(context, m, n);
EmitSubsVCheck(context, m, n, res);
}
EmitAluStore(context, res);
}
public static void Rsb(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Subtract(m, n);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
EmitSubsCCheck(context, m, res);
EmitSubsVCheck(context, m, n, res);
}
EmitAluStore(context, res);
}
public static void Sbc(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Subtract(n, m);
Operand borrow = context.BitwiseExclusiveOr(GetFlag(PState.CFlag), Const(1));
res = context.Subtract(res, borrow);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
EmitSbcsCCheck(context, n, m);
EmitSubsVCheck(context, n, m, res);
}
EmitAluStore(context, res);
}
public static void Sbfx(ArmEmitterContext context)
{
OpCode32AluBf op = (OpCode32AluBf)context.CurrOp;
var msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width.
Operand n = GetIntA32(context, op.Rn);
Operand res = context.ShiftRightSI(context.ShiftLeft(n, Const(31 - msb)), Const(31 - op.Msb));
SetIntA32(context, op.Rd, res);
}
public static void Sdiv(ArmEmitterContext context)
{
EmitDiv(context, false);
}
public static void Ssat(ArmEmitterContext context)
{
OpCode32Sat op = (OpCode32Sat)context.CurrOp;
EmitSat(context, -(1 << op.SatImm), (1 << op.SatImm) - 1);
}
public static void Ssat16(ArmEmitterContext context)
{
OpCode32Sat16 op = (OpCode32Sat16)context.CurrOp;
EmitSat16(context, -(1 << op.SatImm), (1 << op.SatImm) - 1);
}
public static void Sub(ArmEmitterContext context)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
Operand n = GetAluN(context);
Operand m = GetAluM(context, setCarry: false);
Operand res = context.Subtract(n, m);
if (op.SetFlags)
{
EmitNZFlagsCheck(context, res);
EmitSubsCCheck(context, n, res);
EmitSubsVCheck(context, n, m, res);
}
EmitAluStore(context, res);
}
public static void Sxtb(ArmEmitterContext context)
{
EmitSignExtend(context, true, 8);
}
public static void Sxtb16(ArmEmitterContext context)
{
EmitExtend16(context, true);
}
public static void Sxth(ArmEmitterContext context)
{
EmitSignExtend(context, true, 16);
}
public static void Teq(ArmEmitterContext context)
{
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res = context.BitwiseExclusiveOr(n, m);
EmitNZFlagsCheck(context, res);
}
public static void Tst(ArmEmitterContext context)
{
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand res = context.BitwiseAnd(n, m);
EmitNZFlagsCheck(context, res);
}
public static void Ubfx(ArmEmitterContext context)
{
OpCode32AluBf op = (OpCode32AluBf)context.CurrOp;
var msb = op.Lsb + op.Msb; // For this instruction, the msb is actually a width.
Operand n = GetIntA32(context, op.Rn);
Operand res = context.ShiftRightUI(context.ShiftLeft(n, Const(31 - msb)), Const(31 - op.Msb));
SetIntA32(context, op.Rd, res);
}
public static void Udiv(ArmEmitterContext context)
{
EmitDiv(context, true);
}
public static void Usat(ArmEmitterContext context)
{
OpCode32Sat op = (OpCode32Sat)context.CurrOp;
EmitSat(context, 0, op.SatImm == 32 ? (int)(~0) : (1 << op.SatImm) - 1);
}
public static void Usat16(ArmEmitterContext context)
{
OpCode32Sat16 op = (OpCode32Sat16)context.CurrOp;
EmitSat16(context, 0, (1 << op.SatImm) - 1);
}
public static void Uxtb(ArmEmitterContext context)
{
EmitSignExtend(context, false, 8);
}
public static void Uxtb16(ArmEmitterContext context)
{
EmitExtend16(context, false);
}
public static void Uxth(ArmEmitterContext context)
{
EmitSignExtend(context, false, 16);
}
private static void EmitSignExtend(ArmEmitterContext context, bool signed, int bits)
{
IOpCode32AluUx op = (IOpCode32AluUx)context.CurrOp;
Operand m = GetAluM(context);
Operand res;
if (op.RotateBits == 0)
{
res = m;
}
else
{
Operand rotate = Const(op.RotateBits);
res = context.RotateRight(m, rotate);
}
switch (bits)
{
case 8:
res = (signed) ? context.SignExtend8(OperandType.I32, res) : context.ZeroExtend8(OperandType.I32, res);
break;
case 16:
res = (signed) ? context.SignExtend16(OperandType.I32, res) : context.ZeroExtend16(OperandType.I32, res);
break;
}
if (op.Add)
{
res = context.Add(res, GetAluN(context));
}
EmitAluStore(context, res);
}
private static void EmitExtend16(ArmEmitterContext context, bool signed)
{
IOpCode32AluUx op = (IOpCode32AluUx)context.CurrOp;
Operand m = GetAluM(context);
Operand res;
if (op.RotateBits == 0)
{
res = m;
}
else
{
Operand rotate = Const(op.RotateBits);
res = context.RotateRight(m, rotate);
}
Operand low16, high16;
if (signed)
{
low16 = context.SignExtend8(OperandType.I32, res);
high16 = context.SignExtend8(OperandType.I32, context.ShiftRightUI(res, Const(16)));
}
else
{
low16 = context.ZeroExtend8(OperandType.I32, res);
high16 = context.ZeroExtend8(OperandType.I32, context.ShiftRightUI(res, Const(16)));
}
if (op.Add)
{
Operand n = GetAluN(context);
Operand lowAdd, highAdd;
if (signed)
{
lowAdd = context.SignExtend16(OperandType.I32, n);
highAdd = context.SignExtend16(OperandType.I32, context.ShiftRightUI(n, Const(16)));
}
else
{
lowAdd = context.ZeroExtend16(OperandType.I32, n);
highAdd = context.ZeroExtend16(OperandType.I32, context.ShiftRightUI(n, Const(16)));
}
low16 = context.Add(low16, lowAdd);
high16 = context.Add(high16, highAdd);
}
res = context.BitwiseOr(
context.ZeroExtend16(OperandType.I32, low16),
context.ShiftLeft(context.ZeroExtend16(OperandType.I32, high16), Const(16)));
EmitAluStore(context, res);
}
private static void EmitDiv(ArmEmitterContext context, bool unsigned)
{
Operand n = GetAluN(context);
Operand m = GetAluM(context);
Operand zero = Const(m.Type, 0);
Operand divisorIsZero = context.ICompareEqual(m, zero);
Operand lblBadDiv = Label();
Operand lblEnd = Label();
context.BranchIfTrue(lblBadDiv, divisorIsZero);
if (!unsigned)
{
// ARM64 behaviour: If Rn == INT_MIN && Rm == -1, Rd = INT_MIN (overflow).
// TODO: tests to ensure A32 works the same
Operand intMin = Const(int.MinValue);
Operand minus1 = Const(-1);
Operand nIsIntMin = context.ICompareEqual(n, intMin);
Operand mIsMinus1 = context.ICompareEqual(m, minus1);
Operand lblGoodDiv = Label();
context.BranchIfFalse(lblGoodDiv, context.BitwiseAnd(nIsIntMin, mIsMinus1));
EmitAluStore(context, intMin);
context.Branch(lblEnd);
context.MarkLabel(lblGoodDiv);
}
Operand res = unsigned
? context.DivideUI(n, m)
: context.Divide(n, m);
EmitAluStore(context, res);
context.Branch(lblEnd);
context.MarkLabel(lblBadDiv);
EmitAluStore(context, zero);
context.MarkLabel(lblEnd);
}
private static void EmitSat(ArmEmitterContext context, int intMin, int intMax)
{
OpCode32Sat op = (OpCode32Sat)context.CurrOp;
Operand n = GetIntA32(context, op.Rn);
int shift = DecodeImmShift(op.ShiftType, op.Imm5);
switch (op.ShiftType)
{
case ShiftType.Lsl:
if (shift == 32)
{
n = Const(0);
}
else
{
n = context.ShiftLeft(n, Const(shift));
}
break;
case ShiftType.Asr:
if (shift == 32)
{
n = context.ShiftRightSI(n, Const(31));
}
else
{
n = context.ShiftRightSI(n, Const(shift));
}
break;
}
Operand lblCheckLtIntMin = Label();
Operand lblNoSat = Label();
Operand lblEnd = Label();
context.BranchIfFalse(lblCheckLtIntMin, context.ICompareGreater(n, Const(intMax)));
SetFlag(context, PState.QFlag, Const(1));
SetIntA32(context, op.Rd, Const(intMax));
context.Branch(lblEnd);
context.MarkLabel(lblCheckLtIntMin);
context.BranchIfFalse(lblNoSat, context.ICompareLess(n, Const(intMin)));
SetFlag(context, PState.QFlag, Const(1));
SetIntA32(context, op.Rd, Const(intMin));
context.Branch(lblEnd);
context.MarkLabel(lblNoSat);
SetIntA32(context, op.Rd, n);
context.MarkLabel(lblEnd);
}
private static void EmitSat16(ArmEmitterContext context, int intMin, int intMax)
{
OpCode32Sat16 op = (OpCode32Sat16)context.CurrOp;
void SetD(int part, Operand value)
{
if (part == 0)
{
SetIntA32(context, op.Rd, context.ZeroExtend16(OperandType.I32, value));
}
else
{
SetIntA32(context, op.Rd, context.BitwiseOr(GetIntA32(context, op.Rd), context.ShiftLeft(value, Const(16))));
}
}
Operand n = GetIntA32(context, op.Rn);
Operand nLow = context.SignExtend16(OperandType.I32, n);
Operand nHigh = context.ShiftRightSI(n, Const(16));
for (int part = 0; part < 2; part++)
{
Operand nPart = part == 0 ? nLow : nHigh;
Operand lblCheckLtIntMin = Label();
Operand lblNoSat = Label();
Operand lblEnd = Label();
context.BranchIfFalse(lblCheckLtIntMin, context.ICompareGreater(nPart, Const(intMax)));
SetFlag(context, PState.QFlag, Const(1));
SetD(part, Const(intMax));
context.Branch(lblEnd);
context.MarkLabel(lblCheckLtIntMin);
context.BranchIfFalse(lblNoSat, context.ICompareLess(nPart, Const(intMin)));
SetFlag(context, PState.QFlag, Const(1));
SetD(part, Const(intMin));
context.Branch(lblEnd);
context.MarkLabel(lblNoSat);
SetD(part, nPart);
context.MarkLabel(lblEnd);
}
}
private static void EmitAluStore(ArmEmitterContext context, Operand value)
{
IOpCode32Alu op = (IOpCode32Alu)context.CurrOp;
EmitGenericAluStoreA32(context, op.Rd, op.SetFlags, value);
}
}
} | 29.410832 | 129 | 0.528476 | [
"MIT"
] | 4para/Ryujinx | ARMeilleure/Instructions/InstEmitAlu32.cs | 22,264 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace intigrationtests.SampleWeb.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;
public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
} | 20.578947 | 57 | 0.631714 | [
"MIT"
] | calebjenkins/FakeAuth | Tests/intigrationtests.SampleWeb/Pages/Privacy.cshtml.cs | 393 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using Dolittle.Specifications;
using Microsoft.Extensions.DependencyModel;
namespace Dolittle.Assemblies.Rules
{
/// <summary>
/// Represents a <see cref="Specification{T}">rule</see> specific to <see cref="Library">libraries</see> to filter on specific name starting with
/// </summary>
public class NameStartsWith : Specification<Library>
{
/// <summary>
/// Initializes a new instance of <see cref="NameStartsWith"/> rule
/// </summary>
/// <param name="name">Name to check if <see cref="Library"/> starts with</param>
public NameStartsWith(string name) => Predicate = library => library.Name.StartsWith(name);
}
}
| 46.272727 | 149 | 0.554028 | [
"MIT"
] | joelhoisko/DotNET.Fundamentals | Source/Assemblies/Rules/NameStartsWith.cs | 1,018 | C# |
using System.Windows;
using System.Windows.Navigation;
using Game.Input;
using Game.Process;
using Game.Utils;
using GameEngine;
namespace Game
{
public partial class MainPage
{
private IInputObserver _inputObserver;
private GameScreenController _gameScreenController;
private GameProcess _gameProcess;
private ApplicationSettings _applicationSettings;
public MainPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_applicationSettings = new ApplicationSettings();
if (_applicationSettings.Settings.UseSwipe)
{
_inputObserver = new SwipeInputObserver(this);
SwipeControl.Visibility = Visibility.Visible;
ButtonsControl.Visibility = Visibility.Collapsed;
}
else
{
_inputObserver = new InputObserver(this);
SwipeControl.Visibility = Visibility.Collapsed;
ButtonsControl.Visibility = Visibility.Visible;
}
_gameScreenController = new GameScreenController(this);
_gameProcess = CreateGameProcess();
}
private GameProcess CreateGameProcess()
{
if (_applicationSettings.HasStoredGame)
{
return new GameProcess(_inputObserver, _gameScreenController, 4, _applicationSettings.LoadGameState());
}
return new GameProcess(_inputObserver, _gameScreenController, 4);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
_applicationSettings.Save(_gameProcess);
base.OnNavigatedFrom(e);
_inputObserver.Dispose();
}
}
} | 30.258065 | 119 | 0.615139 | [
"MIT"
] | asizikov/wp-2048 | src/Game/MainPage.xaml.cs | 1,878 | C# |
Subsets and Splits