content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#pragma warning disable SA1121 // UseBuiltInTypeAlias
using System;
using CommunityToolkit.WinUI.Notifications.Adaptive.Elements;
#if WINRT
using System.Collections.Generic;
using BindableString = System.String;
#else
using BindableString = CommunityToolkit.WinUI.Notifications.BindableString;
#endif
namespace CommunityToolkit.WinUI.Notifications
{
/// <summary>
/// An adaptive text element.
/// </summary>
public sealed class AdaptiveText
: IAdaptiveChild,
IAdaptiveSubgroupChild,
ITileBindingContentAdaptiveChild,
IToastBindingGenericChild
{
#if WINRT
/// <summary>
/// Gets a dictionary of the current data bindings, where you can assign new bindings.
/// </summary>
public IDictionary<AdaptiveTextBindableProperty, string> Bindings { get; private set; } = new Dictionary<AdaptiveTextBindableProperty, string>();
#endif
/// <summary>
/// Gets or sets the text to display. Data binding support added in Creators Update,
/// only works for toast top-level text elements.
/// </summary>
public BindableString Text { get; set; }
/// <summary>
/// Gets or sets the target locale of the XML payload, specified as a BCP-47 language tags
/// such as "en-US" or "fr-FR". The locale specified here overrides any other specified
/// locale, such as that in binding or visual. If this value is a literal string,
/// this attribute defaults to the user's UI language. If this value is a string reference,
/// this attribute defaults to the locale chosen by Windows Runtime in resolving the string.
/// </summary>
public string Language { get; set; }
/// <summary>
/// Gets or sets the style that controls the text's font size, weight, and opacity.
/// Note that for Toast, the style will only take effect if the text is inside an <see cref="AdaptiveSubgroup"/>.
/// </summary>
public AdaptiveTextStyle HintStyle { get; set; }
/// <summary>
/// Gets or sets a value whether text wrapping is enabled. For Tiles, this is false by default.
/// For Toasts, this is true on top-level text elements, and false inside an <see cref="AdaptiveSubgroup"/>.
/// Note that for Toast, setting wrap will only take effect if the text is inside an
/// <see cref="AdaptiveSubgroup"/> (you can use HintMaxLines = 1 to prevent top-level text elements from wrapping).
/// </summary>
public bool? HintWrap { get; set; }
private int? _hintMaxLines;
/// <summary>
/// Gets or sets the maximum number of lines the text element is allowed to display.
/// For Tiles, this is infinity by default. For Toasts, top-level text elements will
/// have varying max line amounts (and in the Anniversary Update you can change the max lines).
/// Text on a Toast inside an <see cref="AdaptiveSubgroup"/> will behave identically to Tiles (default to infinity).
/// </summary>
public int? HintMaxLines
{
get
{
return _hintMaxLines;
}
set
{
if (value != null)
{
Element_AdaptiveText.CheckMaxLinesValue(value.Value);
}
_hintMaxLines = value;
}
}
private int? _hintMinLines;
/// <summary>
/// Gets or sets the minimum number of lines the text element must display.
/// Note that for Toast, this property will only take effect if the text is inside an <see cref="AdaptiveSubgroup"/>.
/// </summary>
public int? HintMinLines
{
get
{
return _hintMinLines;
}
set
{
if (value != null)
{
Element_AdaptiveText.CheckMinLinesValue(value.Value);
}
_hintMinLines = value;
}
}
/// <summary>
/// Gets or sets the horizontal alignment of the text. Note that for Toast, this property will
/// only take effect if the text is inside an <see cref="AdaptiveSubgroup"/>.
/// </summary>
public AdaptiveTextAlign HintAlign { get; set; }
internal Element_AdaptiveText ConvertToElement()
{
var answer = new Element_AdaptiveText()
{
Lang = Language,
Style = HintStyle,
Wrap = HintWrap,
MaxLines = HintMaxLines,
MinLines = HintMinLines,
Align = HintAlign
};
#if WINRT
answer.Text = XmlWriterHelper.GetBindingOrAbsoluteXmlValue(Bindings, AdaptiveTextBindableProperty.Text, Text);
#else
answer.Text = Text?.ToXmlString();
#endif
return answer;
}
/// <summary>
/// Returns the value of the Text property.
/// </summary>
/// <returns>The value of the Text property.</returns>
public override string ToString()
{
return Text;
}
}
} | 36.333333 | 153 | 0.598349 | [
"MIT"
] | ehtick/Uno.WindowsCommunityToolkit | CommunityToolkit.WinUI.Notifications/Adaptive/AdaptiveText.cs | 5,450 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Data;
using Vita.Entities.Utilities;
using Vita.Entities;
using Vita.Entities.Model;
namespace Vita.Entities.Logging {
// We treat DbCommandLogEntry as subtype of InfoLogEntry, so it ends up in OperationLog just like other
// info log entries.
public class DbCommandLogEntry : InfoLogEntry {
IDbCommand _command;
public double ExecutionTime;
public int RowCount;
private string _asText;
public DbCommandLogEntry(LogContext logContext, IDbCommand command, double executionTime, int rowCount)
: base (logContext, null) {
_command = command;
ExecutionTime = executionTime;
RowCount = rowCount;
}
public override Type BatchGroup => typeof(InfoLogEntry);
public override string AsText() {
if(_asText == null)
_asText = FormatEntry();
return _asText;
}
private string FormatEntry() {
switch(_command.CommandType) {
case CommandType.StoredProcedure: return FormatStoredProcEntry();
case CommandType.Text: return FormatSqlEntry();
case CommandType.TableDirect:
default:
return Util.SafeFormat("LOG: unsupported command type {0}, CommandText: {1}. ", _command.CommandType, _command.CommandText);
}
}
private string FormatStoredProcEntry() {
var fullFormat = "CALL {0} {1} -- @{2} ms {3}, {4} ";
var strParams = LoggingExtensions.FormatSqlParameters(_command.Parameters, "{1}" /*Value only*/, ", ", maxValueLen: 50);
var strRowCount = (RowCount < 0) ? string.Empty : Util.SafeFormat(", {0} row(s)", RowCount);
var strDateTime = base.CreatedOn.ToString("[yyyy/MM/dd HH:mm:ss]");
var result = Util.SafeFormat(fullFormat, _command.CommandText, strParams, ExecutionTime, strRowCount, strDateTime);
return result;
}
private string FormatSqlEntry() {
const string fullFormat = "{0} \r\n{1} -- Time {2} ms{3}, {4} \r\n"; //sql, params, exec time, row count, datetime
var fParams = string.Empty;
if (_command.Parameters.Count > 0) {
var strParams = LoggingExtensions.FormatSqlParameters(_command.Parameters, "{0}={1}", ", ", maxValueLen: 50);
fParams = Util.SafeFormat("-- Parameters: {0} \r\n", strParams);
}
var strRowCount = (RowCount < 0) ? string.Empty : Util.SafeFormat("; {0} row(s)", RowCount);
var strDateTime = base.CreatedOn.ToString("[yyyy/MM/dd HH:mm:ss]");
var result = Util.SafeFormat(fullFormat, _command.CommandText, fParams, ExecutionTime, strRowCount, strDateTime);
return result;
}
}//DbCommandLogEntry class
}
| 37.635135 | 135 | 0.677917 | [
"MIT"
] | rivantsov/vita | src/1.Framework/Vita/4.Internals/Logging/LogEntries/DbCommandLogEntry.cs | 2,787 | C# |
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace TestImplementation.ReadCookie.Controllers
{
[Authorize]
public class SecurityController : Controller
{
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction(nameof(Index));
}
}
}
| 26.458333 | 94 | 0.700787 | [
"MIT"
] | CNBoland/FormsAuthentication | samples/TestImplementation.ReadCookie/Controllers/SecurityController.cs | 637 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace System.IO
{
public static class RowConfigReaderTests
{
[MemberData(nameof(BasicTestData))]
[Theory]
public static void BasicTest(string data)
{
RowConfigReader rcr = new RowConfigReader(data);
Assert.Equal("stringVal", rcr.GetNextValue("stringKey"));
Assert.Equal(int.MaxValue, rcr.GetNextValueAsInt32("intKey"));
Assert.Equal(long.MaxValue, rcr.GetNextValueAsInt64("longKey"));
}
[MemberData(nameof(BasicTestData))]
[Theory]
public static void BasicTestWrongCase(string data)
{
// Default is Ordinal comparison. Keys with different case should not be found.
RowConfigReader rcr = new RowConfigReader(data);
string unused;
Assert.False(rcr.TryGetNextValue("stringkey", out unused));
Assert.False(rcr.TryGetNextValue("intkey", out unused));
Assert.False(rcr.TryGetNextValue("longkey", out unused));
}
[MemberData(nameof(BasicTestData))]
[Theory]
public static void BasicTestCaseInsensitive(string data)
{
// Use a case-insensitive comparer and use differently-cased keys.
RowConfigReader rcr = new RowConfigReader(data, StringComparison.OrdinalIgnoreCase);
Assert.Equal("stringVal", rcr.GetNextValue("stringkey"));
Assert.Equal(int.MaxValue, rcr.GetNextValueAsInt32("intkey"));
Assert.Equal(long.MaxValue, rcr.GetNextValueAsInt64("longkey"));
}
[MemberData(nameof(BasicTestData))]
[Theory]
public static void StaticHelper(string data)
{
Assert.Equal("stringVal", RowConfigReader.ReadFirstValueFromString(data, "stringKey"));
Assert.Equal(int.MaxValue.ToString(), RowConfigReader.ReadFirstValueFromString(data, "intKey"));
Assert.Equal(long.MaxValue.ToString(), RowConfigReader.ReadFirstValueFromString(data, "longKey"));
}
[InlineData("key")]
[InlineData(" key")]
[InlineData("key ")]
[InlineData(" key ")]
[InlineData("\tkey")]
[InlineData("key\t")]
[InlineData("\tkey\t")]
[Theory]
public static void MalformedLine(string data)
{
RowConfigReader rcr = new RowConfigReader(data);
string unused;
Assert.False(rcr.TryGetNextValue("key", out unused));
}
[Fact]
public static void KeyDoesNotStartLine()
{
string data = $"key value{Environment.NewLine} key2 value2";
RowConfigReader rcr = new RowConfigReader(data);
string unused;
Assert.False(rcr.TryGetNextValue("key2", out unused));
// Can retrieve value if key includes the preceding space.
Assert.Equal("value2", rcr.GetNextValue(" key2"));
}
[Fact]
public static void KeyContainedInValue()
{
string data = $"first keyFirstValue{Environment.NewLine}key value";
RowConfigReader rcr = new RowConfigReader(data);
Assert.Equal("value", rcr.GetNextValue("key"));
}
[MemberData(nameof(NewlineTestData))]
[Theory]
public static void NewlineTests(string data)
{
// Test strings which have newlines mixed in between data pairs.
RowConfigReader rcr = new RowConfigReader(data);
Assert.Equal("00", rcr.GetNextValue("value0"));
Assert.Equal(0, rcr.GetNextValueAsInt32("value0"));
Assert.Equal(1, rcr.GetNextValueAsInt32("value1"));
Assert.Equal("2", rcr.GetNextValue("value2"));
Assert.Equal("3", rcr.GetNextValue("value3"));
string unused;
Assert.False(rcr.TryGetNextValue("Any", out unused));
}
public static IEnumerable<object[]> BasicTestData()
{
yield return new[] { BasicData };
yield return new[] { BasicDataWithTabs };
}
private static string BasicData =>
$"stringKey stringVal{Environment.NewLine}" +
$"intKey {int.MaxValue}{Environment.NewLine}" +
$"longKey {long.MaxValue}{Environment.NewLine}";
private static string BasicDataWithTabs =>
$"stringKey\t\t\tstringVal{Environment.NewLine}" +
$"intKey\t\t{int.MaxValue}{Environment.NewLine}" +
$"longKey\t\t{long.MaxValue}{Environment.NewLine}";
public static IEnumerable<object[]> NewlineTestData()
{
yield return new[] { ConfigData };
yield return new[] { ConfigDataExtraNewlines };
yield return new[] { ConfigDataNoTrailingNewline };
}
private static string ConfigData => string.Format(
"value0 00{0}value0 0{0}value1 1{0}value2 2{0}value3 3{0}",
Environment.NewLine);
private static string ConfigDataExtraNewlines =>
$"value0 00{Newlines(5)}value0 0{Newlines(3)}value1 1{Newlines(1)}value2 2{Newlines(4)}value3 3{Newlines(6)}";
private static string ConfigDataNoTrailingNewline => string.Format(
"value0 00{0}value0 0{0}value1 1{0}value2 2{0}value3 3",
Environment.NewLine);
private static string Newlines(int count)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++)
{
sb.AppendLine();
}
return sb.ToString();
}
}
}
| 38.012987 | 122 | 0.606252 | [
"MIT"
] | 06needhamt/runtime | src/libraries/Common/tests/Tests/System/IO/RowConfigReaderTests.cs | 5,856 | C# |
using System;
using UnityEngine;
using LuaInterface;
using Object = UnityEngine.Object;
public class AnimationClipWrap
{
public static void Register(IntPtr L)
{
LuaMethod[] regs = new LuaMethod[]
{
new LuaMethod("SetCurve", SetCurve),
new LuaMethod("EnsureQuaternionContinuity", EnsureQuaternionContinuity),
new LuaMethod("ClearCurves", ClearCurves),
new LuaMethod("AddEvent", AddEvent),
new LuaMethod("New", _CreateAnimationClip),
new LuaMethod("GetClassType", GetClassType),
new LuaMethod("__eq", Lua_Eq),
};
LuaField[] fields = new LuaField[]
{
new LuaField("length", get_length, null),
new LuaField("frameRate", get_frameRate, set_frameRate),
new LuaField("wrapMode", get_wrapMode, set_wrapMode),
new LuaField("localBounds", get_localBounds, set_localBounds),
};
LuaScriptMgr.RegisterLib(L, "UnityEngine.AnimationClip", typeof(AnimationClip), regs, fields, typeof(UnityEngine.Object));
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _CreateAnimationClip(IntPtr L)
{
int count = LuaDLL.lua_gettop(L);
if (count == 0)
{
AnimationClip obj = new AnimationClip();
LuaScriptMgr.Push(L, obj);
return 1;
}
else
{
LuaDLL.luaL_error(L, "invalid arguments to method: AnimationClip.New");
}
return 0;
}
static Type classType = typeof(AnimationClip);
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetClassType(IntPtr L)
{
LuaScriptMgr.Push(L, classType);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_length(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
AnimationClip obj = (AnimationClip)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name length");
}
else
{
LuaDLL.luaL_error(L, "attempt to index length on a nil value");
}
}
LuaScriptMgr.Push(L, obj.length);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_frameRate(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
AnimationClip obj = (AnimationClip)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name frameRate");
}
else
{
LuaDLL.luaL_error(L, "attempt to index frameRate on a nil value");
}
}
LuaScriptMgr.Push(L, obj.frameRate);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_wrapMode(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
AnimationClip obj = (AnimationClip)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name wrapMode");
}
else
{
LuaDLL.luaL_error(L, "attempt to index wrapMode on a nil value");
}
}
LuaScriptMgr.Push(L, obj.wrapMode);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_localBounds(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
AnimationClip obj = (AnimationClip)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name localBounds");
}
else
{
LuaDLL.luaL_error(L, "attempt to index localBounds on a nil value");
}
}
LuaScriptMgr.Push(L, obj.localBounds);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_frameRate(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
AnimationClip obj = (AnimationClip)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name frameRate");
}
else
{
LuaDLL.luaL_error(L, "attempt to index frameRate on a nil value");
}
}
obj.frameRate = (float)LuaScriptMgr.GetNumber(L, 3);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_wrapMode(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
AnimationClip obj = (AnimationClip)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name wrapMode");
}
else
{
LuaDLL.luaL_error(L, "attempt to index wrapMode on a nil value");
}
}
obj.wrapMode = (WrapMode)LuaScriptMgr.GetNetObject(L, 3, typeof(WrapMode));
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_localBounds(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
AnimationClip obj = (AnimationClip)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name localBounds");
}
else
{
LuaDLL.luaL_error(L, "attempt to index localBounds on a nil value");
}
}
obj.localBounds = LuaScriptMgr.GetBounds(L, 3);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int SetCurve(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 5);
AnimationClip obj = (AnimationClip)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AnimationClip");
string arg0 = LuaScriptMgr.GetLuaString(L, 2);
Type arg1 = LuaScriptMgr.GetTypeObject(L, 3);
string arg2 = LuaScriptMgr.GetLuaString(L, 4);
AnimationCurve arg3 = (AnimationCurve)LuaScriptMgr.GetNetObject(L, 5, typeof(AnimationCurve));
obj.SetCurve(arg0,arg1,arg2,arg3);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int EnsureQuaternionContinuity(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 1);
AnimationClip obj = (AnimationClip)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AnimationClip");
obj.EnsureQuaternionContinuity();
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int ClearCurves(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 1);
AnimationClip obj = (AnimationClip)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AnimationClip");
obj.ClearCurves();
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int AddEvent(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 2);
AnimationClip obj = (AnimationClip)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AnimationClip");
AnimationEvent arg0 = (AnimationEvent)LuaScriptMgr.GetNetObject(L, 2, typeof(AnimationEvent));
obj.AddEvent(arg0);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Lua_Eq(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 2);
Object arg0 = LuaScriptMgr.GetLuaObject(L, 1) as Object;
Object arg1 = LuaScriptMgr.GetLuaObject(L, 2) as Object;
bool o = arg0 == arg1;
LuaScriptMgr.Push(L, o);
return 1;
}
}
| 24.633452 | 125 | 0.693008 | [
"MIT"
] | joexi/TinyGame.uLua | Assets/uLua/Source/LuaWrap/AnimationClipWrap.cs | 6,924 | C# |
namespace WebAuthn.Controllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Rsk.AspNetCore.Fido;
using Rsk.AspNetCore.Fido.Models;
using Rsk.AspNetCore.Fido.Stores;
using WebAuthn.Models;
using WebAuthn.Security;
public class HomeController : Controller
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly IFidoAuthentication _fido;
private readonly IFidoKeyStore _store;
private readonly ILogger<HomeController> _logger;
public HomeController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager, IFidoAuthentication fido, IFidoKeyStore store, ILogger<HomeController> logger)
{
_signInManager = signInManager ?? throw new ArgumentNullException(nameof(signInManager));
_userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
_fido = fido ?? throw new ArgumentNullException(nameof(fido));
_store = store ?? throw new ArgumentNullException(nameof(store));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
[TempData]
public string[] RecoveryCodes { get; set; }
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[HttpPost]
[Route("/CompleteSecurityKeyRegistration")]
public async Task<IActionResult> CompleteSecurityKeyRegistration([FromBody] FidoRegistrationResponse registrationResponse)
{
// Parsing and Validating the Registration Data
// The WebAuthn specification describes a 19-point procedure to validate the registration data.
// https://w3c.github.io/webauthn/#registering-a-new-credential
// Validates `clientDataJSON` like (challenge, origin, type, ...) and attestationObject (authData, fmt, attStmt)
var result = await _fido.CompleteRegistration(registrationResponse);
if (result.IsError)
return BadRequest(result.ErrorDescription);
var user = await _userManager.GetUserAsync(User);
if (user is null)
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
await _userManager.SetTwoFactorEnabledAsync(user, true);
if (await _userManager.CountRecoveryCodesAsync(user) == 0)
{
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
RecoveryCodes = recoveryCodes.ToArray();
}
return Ok();
}
//[HttpPost]
//[Route("/InitSecurityKeyAuthentication")]
//[ValidateAntiForgeryToken]
//public async Task<IActionResult> InitSecurityKeyAuthentication(FidoLoginModel model)
//{
// // Ensure the user has gone through the username & password screen first
// var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
// if (user is null)
// throw new InvalidOperationException($"Unable to load two-factor authentication user.");
// /*
// var credentials = (await _store.GetCredentialIdsForUser(user.Email)).ToList();
// if (!credentials.Any())
// throw new PublicKeyCredentialException("No keys registered for user");
// */
// var challenge = await _fido.InitiateAuthentication(user.Email); // model.UserId
// return View(challenge);
//}
[HttpPost]
[Route("/CompleteSecurityKeyAuthentication")]
public async Task<IActionResult> CompleteSecurityKeyAuthentication([FromBody] FidoAuthenticationResponse authenticationResponse)
{
// Parsing and Validating the Authentication Data
// After the authentication data is fully validated, the signature is verified using the public key stored in the database during registration.
// * The server retrieves the public key object associated with the user.
// * The server uses the public key to verify the signature, which was generated using the `authenticatorData` bytes and a SHA-256 hash of the `clientDataJSON`.
var result = await _fido.CompleteAuthentication(authenticationResponse);
if (result.IsError)
return BadRequest(result.ErrorDescription);
if (result.IsSuccess)
await _signInManager.TwoFactorSignInAsync(WebAuthnUserTwoFactorTokenProvider.ProviderName, string.Empty, false, false);
return Ok();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 43 | 190 | 0.659671 | [
"MIT"
] | daviddesmet/playground | src/aspnet-core-razor-pages-security-webauthn/WebAuthn/Controllers/HomeController.cs | 5,291 | C# |
using System;
using System.Diagnostics;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Math.Raw
{
/*
* Modular inversion as implemented in this class is based on the paper "Fast constant-time gcd
* computation and modular inversion" by Daniel J. Bernstein and Bo-Yin Yang.
*/
internal abstract class Mod
{
private static readonly SecureRandom RandomSource = new SecureRandom();
private const int M30 = 0x3FFFFFFF;
private const ulong M32UL = 0xFFFFFFFFUL;
public static void CheckedModOddInverse(uint[] m, uint[] x, uint[] z)
{
if (0 == ModOddInverse(m, x, z))
throw new ArithmeticException("Inverse does not exist.");
}
public static void CheckedModOddInverseVar(uint[] m, uint[] x, uint[] z)
{
if (!ModOddInverseVar(m, x, z))
throw new ArithmeticException("Inverse does not exist.");
}
public static uint Inverse32(uint d)
{
Debug.Assert((d & 1) == 1);
//int x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4
uint x = d; // d.x == 1 mod 2**3
x *= 2 - d * x; // d.x == 1 mod 2**6
x *= 2 - d * x; // d.x == 1 mod 2**12
x *= 2 - d * x; // d.x == 1 mod 2**24
x *= 2 - d * x; // d.x == 1 mod 2**48
Debug.Assert(d * x == 1);
return x;
}
public static uint ModOddInverse(uint[] m, uint[] x, uint[] z)
{
int len32 = m.Length;
Debug.Assert(len32 > 0);
Debug.Assert((m[0] & 1) != 0);
Debug.Assert(m[len32 - 1] != 0);
int bits = (len32 << 5) - Integers.NumberOfLeadingZeros((int)m[len32 - 1]);
int len30 = (bits + 29) / 30;
int[] t = new int[4];
int[] D = new int[len30];
int[] E = new int[len30];
int[] F = new int[len30];
int[] G = new int[len30];
int[] M = new int[len30];
E[0] = 1;
Encode30(bits, x, 0, G, 0);
Encode30(bits, m, 0, M, 0);
Array.Copy(M, 0, F, 0, len30);
int eta = -1;
int m0Inv32 = (int)Inverse32((uint)M[0]);
int maxDivsteps = GetMaximumDivsteps(bits);
for (int divSteps = 0; divSteps < maxDivsteps; divSteps += 30)
{
eta = Divsteps30(eta, F[0], G[0], t);
UpdateDE30(len30, D, E, t, m0Inv32, M);
UpdateFG30(len30, F, G, t);
}
int signF = F[len30 - 1] >> 31;
CNegate30(len30, signF, F);
/*
* D is in the range (-2.M, M). First, conditionally add M if D is negative, to bring it
* into the range (-M, M). Then normalize by conditionally negating (according to signF)
* and/or then adding M, to bring it into the range [0, M).
*/
CNormalize30(len30, signF, D, M);
Decode30(bits, D, 0, z, 0);
Debug.Assert(0 != Nat.LessThan(len32, z, m));
return (uint)(EqualTo(len30, F, 1) & EqualToZero(len30, G));
}
public static bool ModOddInverseVar(uint[] m, uint[] x, uint[] z)
{
int len32 = m.Length;
Debug.Assert(len32 > 0);
Debug.Assert((m[0] & 1) != 0);
Debug.Assert(m[len32 - 1] != 0);
int bits = (len32 << 5) - Integers.NumberOfLeadingZeros((int)m[len32 - 1]);
int len30 = (bits + 29) / 30;
int[] t = new int[4];
int[] D = new int[len30];
int[] E = new int[len30];
int[] F = new int[len30];
int[] G = new int[len30];
int[] M = new int[len30];
E[0] = 1;
Encode30(bits, x, 0, G, 0);
Encode30(bits, m, 0, M, 0);
Array.Copy(M, 0, F, 0, len30);
int clzG = Integers.NumberOfLeadingZeros(G[len30 - 1] | 1) - (len30 * 30 + 2 - bits);
int eta = -1 - clzG;
int lenDE = len30, lenFG = len30;
int m0Inv32 = (int)Inverse32((uint)M[0]);
int maxDivsteps = GetMaximumDivsteps(bits);
int divsteps = 0;
while (!IsZero(lenFG, G))
{
if (divsteps >= maxDivsteps)
return false;
divsteps += 30;
eta = Divsteps30Var(eta, F[0], G[0], t);
UpdateDE30(lenDE, D, E, t, m0Inv32, M);
UpdateFG30(lenFG, F, G, t);
int fn = F[lenFG - 1];
int gn = G[lenFG - 1];
int cond = (lenFG - 2) >> 31;
cond |= fn ^ (fn >> 31);
cond |= gn ^ (gn >> 31);
if (cond == 0)
{
F[lenFG - 2] |= fn << 30;
G[lenFG - 2] |= gn << 30;
--lenFG;
}
}
int signF = F[lenFG - 1] >> 31;
/*
* D is in the range (-2.M, M). First, conditionally add M if D is negative, to bring it
* into the range (-M, M). Then normalize by conditionally negating (according to signF)
* and/or then adding M, to bring it into the range [0, M).
*/
int signD = D[lenDE - 1] >> 31;
if (signD < 0)
{
signD = Add30(lenDE, D, M);
}
if (signF < 0)
{
signD = Negate30(lenDE, D);
signF = Negate30(lenFG, F);
}
Debug.Assert(0 == signF);
if (!IsOne(lenFG, F))
return false;
if (signD < 0)
{
signD = Add30(lenDE, D, M);
}
Debug.Assert(0 == signD);
Decode30(bits, D, 0, z, 0);
Debug.Assert(!Nat.Gte(len32, z, m));
return true;
}
public static uint[] Random(uint[] p)
{
int len = p.Length;
uint[] s = Nat.Create(len);
uint m = p[len - 1];
m |= m >> 1;
m |= m >> 2;
m |= m >> 4;
m |= m >> 8;
m |= m >> 16;
do
{
byte[] bytes = new byte[len << 2];
RandomSource.NextBytes(bytes);
Pack.BE_To_UInt32(bytes, 0, s);
s[len - 1] &= m;
}
while (Nat.Gte(len, s, p));
return s;
}
private static int Add30(int len30, int[] D, int[] M)
{
Debug.Assert(len30 > 0);
Debug.Assert(D.Length >= len30);
Debug.Assert(M.Length >= len30);
int c = 0, last = len30 - 1;
for (int i = 0; i < last; ++i)
{
c += D[i] + M[i];
D[i] = c & M30; c >>= 30;
}
c += D[last] + M[last];
D[last] = c; c >>= 30;
return c;
}
private static void CNegate30(int len30, int cond, int[] D)
{
Debug.Assert(len30 > 0);
Debug.Assert(D.Length >= len30);
int c = 0, last = len30 - 1;
for (int i = 0; i < last; ++i)
{
c += (D[i] ^ cond) - cond;
D[i] = c & M30; c >>= 30;
}
c += (D[last] ^ cond) - cond;
D[last] = c;
}
private static void CNormalize30(int len30, int condNegate, int[] D, int[] M)
{
Debug.Assert(len30 > 0);
Debug.Assert(D.Length >= len30);
Debug.Assert(M.Length >= len30);
int last = len30 - 1;
{
int c = 0, condAdd = D[last] >> 31;
for (int i = 0; i < last; ++i)
{
int di = D[i] + (M[i] & condAdd);
di = (di ^ condNegate) - condNegate;
c += di; D[i] = c & M30; c >>= 30;
}
{
int di = D[last] + (M[last] & condAdd);
di = (di ^ condNegate) - condNegate;
c += di; D[last] = c;
}
}
{
int c = 0, condAdd = D[last] >> 31;
for (int i = 0; i < last; ++i)
{
int di = D[i] + (M[i] & condAdd);
c += di; D[i] = c & M30; c >>= 30;
}
{
int di = D[last] + (M[last] & condAdd);
c += di; D[last] = c;
}
Debug.Assert(c >> 30 == 0);
}
}
private static void Decode30(int bits, int[] x, int xOff, uint[] z, int zOff)
{
Debug.Assert(bits > 0);
int avail = 0;
ulong data = 0L;
while (bits > 0)
{
while (avail < System.Math.Min(32, bits))
{
data |= (ulong)x[xOff++] << avail;
avail += 30;
}
z[zOff++] = (uint)data; data >>= 32;
avail -= 32;
bits -= 32;
}
}
private static int Divsteps30(int eta, int f0, int g0, int[] t)
{
int u = 1, v = 0, q = 0, r = 1;
int f = f0, g = g0;
for (int i = 0; i < 30; ++i)
{
Debug.Assert((f & 1) == 1);
Debug.Assert((u * f0 + v * g0) == f << i);
Debug.Assert((q * f0 + r * g0) == g << i);
int c1 = eta >> 31;
int c2 = -(g & 1);
int x = (f ^ c1) - c1;
int y = (u ^ c1) - c1;
int z = (v ^ c1) - c1;
g += x & c2;
q += y & c2;
r += z & c2;
c1 &= c2;
eta = (eta ^ c1) - (c1 + 1);
f += g & c1;
u += q & c1;
v += r & c1;
g >>= 1;
u <<= 1;
v <<= 1;
}
t[0] = u;
t[1] = v;
t[2] = q;
t[3] = r;
return eta;
}
private static int Divsteps30Var(int eta, int f0, int g0, int[] t)
{
int u = 1, v = 0, q = 0, r = 1;
int f = f0, g = g0, m, w, x, y, z;
int i = 30, limit, zeros;
for (; ; )
{
// Use a sentinel bit to count zeros only up to i.
zeros = Integers.NumberOfTrailingZeros(g | (-1 << i));
g >>= zeros;
u <<= zeros;
v <<= zeros;
eta -= zeros;
i -= zeros;
if (i <= 0)
break;
Debug.Assert((f & 1) == 1);
Debug.Assert((g & 1) == 1);
Debug.Assert((u * f0 + v * g0) == f << (30 - i));
Debug.Assert((q * f0 + r * g0) == g << (30 - i));
if (eta < 0)
{
eta = -eta;
x = f; f = g; g = -x;
y = u; u = q; q = -y;
z = v; v = r; r = -z;
// Handle up to 6 divsteps at once, subject to eta and i.
limit = (eta + 1) > i ? i : (eta + 1);
m = (int)((uint.MaxValue >> (32 - limit)) & 63U);
w = (f * g * (f * f - 2)) & m;
}
else
{
// Handle up to 4 divsteps at once, subject to eta and i.
limit = (eta + 1) > i ? i : (eta + 1);
m = (int)((uint.MaxValue >> (32 - limit)) & 15U);
w = f + (((f + 1) & 4) << 1);
w = (-w * g) & m;
}
g += f * w;
q += u * w;
r += v * w;
Debug.Assert((g & m) == 0);
}
t[0] = u;
t[1] = v;
t[2] = q;
t[3] = r;
return eta;
}
private static void Encode30(int bits, uint[] x, int xOff, int[] z, int zOff)
{
Debug.Assert(bits > 0);
int avail = 0;
ulong data = 0UL;
while (bits > 0)
{
if (avail < System.Math.Min(30, bits))
{
data |= (x[xOff++] & M32UL) << avail;
avail += 32;
}
z[zOff++] = (int)data & M30; data >>= 30;
avail -= 30;
bits -= 30;
}
}
private static int EqualTo(int len, int[] x, int y)
{
int d = x[0] ^ y;
for (int i = 1; i < len; ++i)
{
d |= x[i];
}
d = (int)((uint)d >> 1) | (d & 1);
return (d - 1) >> 31;
}
private static int EqualToZero(int len, int[] x)
{
int d = 0;
for (int i = 0; i < len; ++i)
{
d |= x[i];
}
d = (int)((uint)d >> 1) | (d & 1);
return (d - 1) >> 31;
}
private static int GetMaximumDivsteps(int bits)
{
return (49 * bits + (bits < 46 ? 80 : 47)) / 17;
}
private static bool IsOne(int len, int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < len; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
private static bool IsZero(int len, int[] x)
{
if (x[0] != 0)
{
return false;
}
for (int i = 1; i < len; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
private static int Negate30(int len30, int[] D)
{
Debug.Assert(len30 > 0);
Debug.Assert(D.Length >= len30);
int c = 0, last = len30 - 1;
for (int i = 0; i < last; ++i)
{
c -= D[i];
D[i] = c & M30; c >>= 30;
}
c -= D[last];
D[last] = c; c >>= 30;
return c;
}
private static void UpdateDE30(int len30, int[] D, int[] E, int[] t, int m0Inv32, int[] M)
{
Debug.Assert(len30 > 0);
Debug.Assert(D.Length >= len30);
Debug.Assert(E.Length >= len30);
Debug.Assert(M.Length >= len30);
Debug.Assert(m0Inv32 * M[0] == 1);
int u = t[0], v = t[1], q = t[2], r = t[3];
int di, ei, i, md, me, mi, sd, se;
long cd, ce;
/*
* We accept D (E) in the range (-2.M, M) and conceptually add the modulus to the input
* value if it is initially negative. Instead of adding it explicitly, we add u and/or v (q
* and/or r) to md (me).
*/
sd = D[len30 - 1] >> 31;
se = E[len30 - 1] >> 31;
md = (u & sd) + (v & se);
me = (q & sd) + (r & se);
mi = M[0];
di = D[0];
ei = E[0];
cd = (long)u * di + (long)v * ei;
ce = (long)q * di + (long)r * ei;
/*
* Subtract from md/me an extra term in the range [0, 2^30) such that the low 30 bits of the
* intermediate D/E values will be 0, allowing clean division by 2^30. The final D/E are
* thus in the range (-2.M, M), consistent with the input constraint.
*/
md -= (m0Inv32 * (int)cd + md) & M30;
me -= (m0Inv32 * (int)ce + me) & M30;
cd += (long)mi * md;
ce += (long)mi * me;
Debug.Assert(((int)cd & M30) == 0);
Debug.Assert(((int)ce & M30) == 0);
cd >>= 30;
ce >>= 30;
for (i = 1; i < len30; ++i)
{
mi = M[i];
di = D[i];
ei = E[i];
cd += (long)u * di + (long)v * ei + (long)mi * md;
ce += (long)q * di + (long)r * ei + (long)mi * me;
D[i - 1] = (int)cd & M30; cd >>= 30;
E[i - 1] = (int)ce & M30; ce >>= 30;
}
D[len30 - 1] = (int)cd;
E[len30 - 1] = (int)ce;
}
private static void UpdateFG30(int len30, int[] F, int[] G, int[] t)
{
Debug.Assert(len30 > 0);
Debug.Assert(F.Length >= len30);
Debug.Assert(G.Length >= len30);
int u = t[0], v = t[1], q = t[2], r = t[3];
int fi, gi, i;
long cf, cg;
fi = F[0];
gi = G[0];
cf = (long)u * fi + (long)v * gi;
cg = (long)q * fi + (long)r * gi;
Debug.Assert(((int)cf & M30) == 0);
Debug.Assert(((int)cg & M30) == 0);
cf >>= 30;
cg >>= 30;
for (i = 1; i < len30; ++i)
{
fi = F[i];
gi = G[i];
cf += (long)u * fi + (long)v * gi;
cg += (long)q * fi + (long)r * gi;
F[i - 1] = (int)cf & M30; cf >>= 30;
G[i - 1] = (int)cg & M30; cg >>= 30;
}
F[len30 - 1] = (int)cf;
G[len30 - 1] = (int)cg;
}
}
} | 29.839404 | 104 | 0.360595 | [
"MIT"
] | 0x070696E65/Symnity | Assets/Plugins/Symnity/Pulgins/crypto/src/math/raw/Mod.cs | 18,025 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Delivery.Models.ManageViewModels
{
public class EnableAuthenticatorViewModel
{
[Required]
[StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Text)]
[Display(Name = "Verification Code")]
public string Code { get; set; }
[BindNever]
public string SharedKey { get; set; }
[BindNever]
public string AuthenticatorUri { get; set; }
}
}
| 28 | 123 | 0.684066 | [
"MIT"
] | DmitryEkimov/Delivery | Delivery/Models/ManageViewModels/EnableAuthenticatorViewModel.cs | 730 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PharmacyNetwork.ApplicationCore.Entities;
namespace PharmacyNetwork.Web.ViewModels
{
public class PurchaseCheckViewModel
{
public Purchase Purchase { get; set; }
public IEnumerable<Check> Check { get; set; }
}
}
| 21.625 | 53 | 0.734104 | [
"MIT"
] | SH4KUR/PharmacyNetwork | src/Web/ViewModels/PurchaseCheckViewModel.cs | 348 | C# |
using System.Collections.Generic;
namespace HOPU.Models
{
/// <summary>
/// 统测列表的modeloutput model
/// </summary>
public class UnifiedTestTypeViewModel
{
public IEnumerable<CourseNameViewModel> CourseNames { get; set; }//题目类名称列表
public IEnumerable<UniteTest> UniteTests { get; set; }//统测列表
}
} | 25.769231 | 82 | 0.668657 | [
"MIT"
] | HDwoald/OnlineTest | HOPU/Models/UnifiedTestTypeViewModel.cs | 369 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ServR.Task")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServR.Task")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ca17e11-28f1-4f9e-9cc5-85f0eb8bd039")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.743001 | [
"Apache-2.0"
] | Bomret/ServR | ServR.Task/Properties/AssemblyInfo.cs | 1,396 | C# |
// <auto-generated/>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using LotusCatering.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace LotusCatering.Web.Areas.Identity.Pages.Account.Manage
{
public class SetPasswordModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public SetPasswordModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToPage("./ChangePassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var addPasswordResult = await _userManager.AddPasswordAsync(user, Input.NewPassword);
if (!addPasswordResult.Succeeded)
{
foreach (var error in addPasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your password has been set.";
return RedirectToPage();
}
}
}
| 31.789474 | 129 | 0.585762 | [
"MIT"
] | Kmalechkanov/Lotus-Catering | Src/Web/LotusCatering/Areas/Identity/Pages/Account/Manage/SetPassword.cshtml.cs | 3,022 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace DevIO.AppMvc.Models
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class ExternalLoginListViewModel
{
public string ReturnUrl { get; set; }
}
public class SendCodeViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
public string ReturnUrl { get; set; }
public bool RememberMe { get; set; }
}
public class VerifyCodeViewModel
{
[Required]
public string Provider { get; set; }
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
public string ReturnUrl { get; set; }
[Display(Name = "Remember this browser?")]
public bool RememberBrowser { get; set; }
public bool RememberMe { get; set; }
}
public class ForgotViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ResetPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Code { get; set; }
}
public class ForgotPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
}
}
| 27.530973 | 110 | 0.588235 | [
"MIT"
] | marcialwushu/AspNetMVC5 | src/MeusProdutos/DevIO.AppMvc/Models/AccountViewModels.cs | 3,113 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.UseExplicitTypeForConst
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExplicitTypeForConst), Shared]
internal sealed class UseExplicitTypeForConstCodeFixProvider : CodeFixProvider
{
private const string CS0822 = nameof(CS0822); // Implicitly-typed variables cannot be constant
[ImportingConstructor]
public UseExplicitTypeForConstCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS0822);
public override FixAllProvider GetFixAllProvider()
{
// This code fix addresses a very specific compiler error. It's unlikely there will be more than 1 of them at a time.
return null;
}
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root.FindNode(context.Span) is VariableDeclarationSyntax variableDeclaration &&
variableDeclaration.Variables.Count == 1)
{
var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
var type = semanticModel.GetTypeInfo(variableDeclaration.Type, context.CancellationToken).ConvertedType;
if (type == null || type.TypeKind == TypeKind.Error || type.IsAnonymousType)
{
return;
}
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Span, type, c)),
context.Diagnostics);
}
}
private static async Task<Document> FixAsync(
Document document, TextSpan span, ITypeSymbol type, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var variableDeclaration = (VariableDeclarationSyntax)root.FindNode(span);
var newRoot = root.ReplaceNode(variableDeclaration.Type, type.GenerateTypeSyntax(allowVar: false));
return document.WithSyntaxRoot(newRoot);
}
private sealed class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_explicit_type_instead_of_var,
createChangedDocument)
{
}
}
}
}
| 42.207792 | 130 | 0.688308 | [
"Apache-2.0"
] | HenrikWM/roslyn | src/Features/CSharp/Portable/UseExplicitTypeForConst/UseExplicitTypeForConstCodeFixProvider.cs | 3,252 | C# |
using Entities.Models;
using System.Collections.Generic;
namespace Contracts
{
public interface ICompanyRepository
{
IEnumerable<Company> GetAllCompanies(bool trackChanges);
}
}
| 18.181818 | 64 | 0.74 | [
"MIT"
] | CodeMazeBlog/multiple-databases-aspnetcore | CompanyEmployees/Contracts/ICompanyRepository.cs | 202 | 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 CMS_Website.Control_Panel {
public partial class report {
/// <summary>
/// tbxReportTitle 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 tbxReportTitle;
/// <summary>
/// RequiredFieldValidator_ReportTitle 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.RequiredFieldValidator RequiredFieldValidator_ReportTitle;
/// <summary>
/// ReportUpload 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.FileUpload ReportUpload;
/// <summary>
/// RequiredFieldValidatorFileUp 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.RequiredFieldValidator RequiredFieldValidatorFileUp;
/// <summary>
/// lableReportSataus 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.Label lableReportSataus;
/// <summary>
/// ddlReportStatus 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.DropDownList ddlReportStatus;
/// <summary>
/// saveButton 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.LinkButton saveButton;
/// <summary>
/// SuccessPanel 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.Panel SuccessPanel;
/// <summary>
/// DangerPanel 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.Panel DangerPanel;
/// <summary>
/// GridViewReport 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.GridView GridViewReport;
}
}
| 36.226415 | 110 | 0.553906 | [
"MIT"
] | sumuongit/asp-ado-cms-website-layered-architecture | CMS_Website/Control_Panel/report.aspx.designer.cs | 3,842 | C# |
namespace ThriveDevCenter.Server.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Shared;
using Shared.Models;
using Shared.Notifications;
using Utilities;
[Index(nameof(HashedBuildOutputConnectKey), IsUnique = true)]
public class CiJob : IUpdateNotifications, IContainsHashedLookUps
{
public long CiProjectId { get; set; }
public long CiBuildId { get; set; }
[AllowSortingBy]
public long CiJobId { get; set; }
public CIJobState State { get; set; } = CIJobState.Starting;
public bool Succeeded { get; set; } = false;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime? FinishedAt { get; set; }
[Required]
[AllowSortingBy]
public string JobName { get; set; }
/// <summary>
/// The podman image to use to run this job, should be in the form of "thing/image:v1"
/// </summary>
public string Image { get; set; }
/// <summary>
/// Used to allow the build server to connect back to us to communicate build logs and status
/// </summary>
[HashedLookUp]
public Guid? BuildOutputConnectKey { get; set; } = Guid.NewGuid();
public string HashedBuildOutputConnectKey { get; set; }
/// <summary>
/// Used to detect which server to release after this job is complete
/// </summary>
public long RunningOnServerId { get; set; } = -1;
/// <summary>
/// Defines if the RunningOnServerId is external or internal server ID
/// </summary>
public bool? RunningOnServerIsExternal { get; set; }
/// <summary>
/// This contains json serialized for of the cache settings for this build. This is sent to the CI executor
/// so that it can handle cache setup before cloning the repo.
/// </summary>
public string CacheSettingsJson { get; set; }
/// <summary>
/// Stores permanently which server this job was ran on
/// </summary>
public string RanOnServer { get; set; }
/// <summary>
/// Measures how long it took for the job to start running on a server after it was created
/// </summary>
public TimeSpan? TimeWaitingForServer { get; set; }
[ForeignKey("CiProjectId,CiBuildId")]
public CiBuild Build { get; set; }
public ICollection<CiJobArtifact> CiJobArtifacts { get; set; } = new HashSet<CiJobArtifact>();
public ICollection<CiJobOutputSection> CiJobOutputSections { get; set; } = new HashSet<CiJobOutputSection>();
public void SetFinishSuccess(bool success)
{
Succeeded = success;
State = CIJobState.Finished;
FinishedAt = DateTime.UtcNow;
BuildOutputConnectKey = null;
}
public async Task CreateFailureSection(ApplicationDbContext database, string content,
string sectionTitle = "Invalid configuration", long sectionId = 1)
{
var section = new CiJobOutputSection()
{
CiProjectId = CiProjectId,
CiBuildId = CiBuildId,
CiJobId = CiJobId,
CiJobOutputSectionId = sectionId,
Name = sectionTitle,
Status = CIJobSectionStatus.Failed,
Output = content
};
section.CalculateOutputLength();
await database.CiJobOutputSections.AddAsync(section);
}
/// <summary>
/// Converts the Image to the name it should have in the DevCenter's storage
/// </summary>
/// <returns>The image name</returns>
public string GetImageFileName()
{
if (string.IsNullOrEmpty(Image))
return "missing";
return Image.Replace(":v", "_v") + ".tar.xz";
}
public CIJobDTO GetDTO()
{
return new()
{
CiProjectId = CiProjectId,
CiBuildId = CiBuildId,
CiJobId = CiJobId,
CreatedAt = CreatedAt,
FinishedAt = FinishedAt,
JobName = JobName,
State = State,
Succeeded = Succeeded,
RanOnServer = RanOnServer,
TimeWaitingForServer = TimeWaitingForServer,
ProjectName = Build?.CiProject?.Name ?? CiProjectId.ToString()
};
}
public IEnumerable<Tuple<SerializedNotification, string>> GetNotifications(EntityState entityState)
{
var dto = GetDTO();
var buildNotificationsId = CiProjectId + "_" + CiBuildId;
yield return new Tuple<SerializedNotification, string>(new CIProjectBuildJobsListUpdated()
{
Type = entityState.ToChangeType(),
Item = dto
}, NotificationGroups.CIProjectBuildJobsUpdatedPrefix + buildNotificationsId);
var notificationsId = buildNotificationsId + "_" + CiJobId;
yield return new Tuple<SerializedNotification, string>(new CIJobUpdated()
{
Item = dto
}, NotificationGroups.CIProjectsBuildsJobUpdatedPrefix + notificationsId);
}
}
}
| 35.063291 | 117 | 0.588448 | [
"MIT"
] | Revolutionary-Games/ThriveDevCenter | Server/Models/CiJob.cs | 5,540 | C# |
using System;
using System.IO;
namespace CirnoLib.MPQ.CompressLib
{
// A node which is both hierachcical (parent/child) and doubly linked (next/prev)
public class LinkedNode
{
public int DecompressedValue;
public int Weight;
public LinkedNode Parent;
public LinkedNode Child0;
public LinkedNode Child1 { get => Child0.Prev; }
public LinkedNode Next;
public LinkedNode Prev;
public LinkedNode(int decompVal, int weight)
{
DecompressedValue = decompVal;
this.Weight = weight;
}
// TODO: This would be more efficient as a member of the other class
// ie avoid the recursion
public LinkedNode Insert(LinkedNode other)
{
// 'Next' should have a lower weight
// we should return the lower weight
if (other.Weight <= Weight)
{
// insert before
if (Next != null)
{
Next.Prev = other;
other.Next = Next;
}
Next = other;
other.Prev = this;
return other;
}
else
{
if (Prev == null)
{
// Insert after
other.Prev = null;
Prev = other;
other.Next = this;
}
else
{
Prev.Insert(other);
}
}
return this;
}
}
/// <summary>
/// A decompressor for MPQ's huffman compression
/// </summary>
public static class Huffman
{
private static readonly byte[][] sPrime =
{
// Compression type 0
new byte[]
{
0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
},
// Compression type 1
new byte[]
{
0x54, 0x16, 0x16, 0x0D, 0x0C, 0x08, 0x06, 0x05, 0x06, 0x05, 0x06, 0x03, 0x04, 0x04, 0x03, 0x05,
0x0E, 0x0B, 0x14, 0x13, 0x13, 0x09, 0x0B, 0x06, 0x05, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02,
0x0D, 0x07, 0x09, 0x06, 0x06, 0x04, 0x03, 0x02, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02,
0x09, 0x06, 0x04, 0x04, 0x04, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x04,
0x08, 0x03, 0x04, 0x07, 0x09, 0x05, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02,
0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02,
0x06, 0x0A, 0x08, 0x08, 0x06, 0x07, 0x04, 0x03, 0x04, 0x04, 0x02, 0x02, 0x04, 0x02, 0x03, 0x03,
0x04, 0x03, 0x07, 0x07, 0x09, 0x06, 0x04, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02,
0x0A, 0x02, 0x02, 0x03, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x03, 0x05, 0x02, 0x03,
0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01, 0x01,
0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x04, 0x04, 0x04, 0x07, 0x09, 0x08, 0x0C, 0x02,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x03,
0x04, 0x01, 0x02, 0x04, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x4B,
},
// Compression type 2
new byte[]
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x27, 0x00, 0x00, 0x23, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x06, 0x0E, 0x10, 0x04,
0x06, 0x08, 0x05, 0x04, 0x04, 0x03, 0x03, 0x02, 0x02, 0x03, 0x03, 0x01, 0x01, 0x02, 0x01, 0x01,
0x01, 0x04, 0x02, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x04, 0x01, 0x01, 0x02, 0x03, 0x03, 0x02,
0x03, 0x01, 0x03, 0x06, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x01, 0x01,
0x01, 0x29, 0x07, 0x16, 0x12, 0x40, 0x0A, 0x0A, 0x11, 0x25, 0x01, 0x03, 0x17, 0x10, 0x26, 0x2A,
0x10, 0x01, 0x23, 0x23, 0x2F, 0x10, 0x06, 0x07, 0x02, 0x09, 0x01, 0x01, 0x01, 0x01, 0x01
},
// Compression type 3
new byte[]
{
0xFF, 0x0B, 0x07, 0x05, 0x0B, 0x02, 0x02, 0x02, 0x06, 0x02, 0x02, 0x01, 0x04, 0x02, 0x01, 0x03,
0x09, 0x01, 0x01, 0x01, 0x03, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
0x05, 0x01, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x02, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01,
0x0A, 0x04, 0x02, 0x01, 0x06, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01,
0x05, 0x02, 0x03, 0x04, 0x03, 0x03, 0x03, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x03, 0x03,
0x01, 0x03, 0x01, 0x01, 0x02, 0x05, 0x01, 0x01, 0x04, 0x03, 0x05, 0x01, 0x03, 0x01, 0x03, 0x03,
0x02, 0x01, 0x04, 0x03, 0x0A, 0x06, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x02, 0x02, 0x01, 0x0A, 0x02, 0x05, 0x01, 0x01, 0x02, 0x07, 0x02, 0x17, 0x01, 0x05, 0x01, 0x01,
0x0E, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x06, 0x02, 0x01, 0x04, 0x05, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x07, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01,
0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x11,
},
// Compression type 4
new byte[]
{
0xFF, 0xFB, 0x98, 0x9A, 0x84, 0x85, 0x63, 0x64, 0x3E, 0x3E, 0x22, 0x22, 0x13, 0x13, 0x18, 0x17,
},
// Compression type 5
new byte[]
{
0xFF, 0xF1, 0x9D, 0x9E, 0x9A, 0x9B, 0x9A, 0x97, 0x93, 0x93, 0x8C, 0x8E, 0x86, 0x88, 0x80, 0x82,
0x7C, 0x7C, 0x72, 0x73, 0x69, 0x6B, 0x5F, 0x60, 0x55, 0x56, 0x4A, 0x4B, 0x40, 0x41, 0x37, 0x37,
0x2F, 0x2F, 0x27, 0x27, 0x21, 0x21, 0x1B, 0x1C, 0x17, 0x17, 0x13, 0x13, 0x10, 0x10, 0x0D, 0x0D,
0x0B, 0x0B, 0x09, 0x09, 0x08, 0x08, 0x07, 0x07, 0x06, 0x05, 0x05, 0x04, 0x04, 0x04, 0x19, 0x18
},
// Compression type 6
new byte[]
{
0xC3, 0xCB, 0xF5, 0x41, 0xFF, 0x7B, 0xF7, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xBF, 0xCC, 0xF2, 0x40, 0xFD, 0x7C, 0xF7, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x7A, 0x46
},
// Compression type 7
new byte[]
{
0xC3, 0xD9, 0xEF, 0x3D, 0xF9, 0x7C, 0xE9, 0x1E, 0xFD, 0xAB, 0xF1, 0x2C, 0xFC, 0x5B, 0xFE, 0x17,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xBD, 0xD9, 0xEC, 0x3D, 0xF5, 0x7D, 0xE8, 0x1D, 0xFB, 0xAE, 0xF0, 0x2C, 0xFB, 0x5C, 0xFF, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x70, 0x6C
},
// Compression type 8
new byte[]
{
0xBA, 0xC5, 0xDA, 0x33, 0xE3, 0x6D, 0xD8, 0x18, 0xE5, 0x94, 0xDA, 0x23, 0xDF, 0x4A, 0xD1, 0x10,
0xEE, 0xAF, 0xE4, 0x2C, 0xEA, 0x5A, 0xDE, 0x15, 0xF4, 0x87, 0xE9, 0x21, 0xF6, 0x43, 0xFC, 0x12,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xB0, 0xC7, 0xD8, 0x33, 0xE3, 0x6B, 0xD6, 0x18, 0xE7, 0x95, 0xD8, 0x23, 0xDB, 0x49, 0xD0, 0x11,
0xE9, 0xB2, 0xE2, 0x2B, 0xE8, 0x5C, 0xDD, 0x15, 0xF1, 0x87, 0xE7, 0x20, 0xF7, 0x44, 0xFF, 0x13,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x5F, 0x9E
}
};
public static byte[] Decompress(byte[] data)
{
int comptype = data[0];
if (comptype == 0)
throw new NotImplementedException("Compression type 0 is not currently supported");
LinkedNode tail = BuildList(sPrime[comptype]);
LinkedNode head = BuildTree(tail);
using (MemoryStream inputStream = new MemoryStream(data))
using (MemoryStream outputStream = new MemoryStream())
{
BitStream bitstream = new BitStream(inputStream);
int decoded;
do
{
LinkedNode node = Decode(bitstream, head);
decoded = node.DecompressedValue;
switch (decoded)
{
case 256:
break;
case 257:
int newvalue = bitstream.ReadBits(8);
outputStream.WriteByte((byte)newvalue);
tail = InsertNode(tail, newvalue);
break;
default:
outputStream.WriteByte((byte)decoded);
break;
}
} while (decoded != 256);
return outputStream.ToArray();
}
}
private static LinkedNode Decode(BitStream input, LinkedNode head)
{
LinkedNode node = head;
while (node.Child0 != null)
{
int bit = input.ReadBits(1);
if (bit == -1)
throw new Exception("Unexpected end of file");
node = bit == 0 ? node.Child0 : node.Child1;
}
return node;
}
private static LinkedNode BuildList(byte[] primeData)
{
LinkedNode root;
root = new LinkedNode(256, 1);
root = root.Insert(new LinkedNode(257, 1));
for (int i = 0; i < primeData.Length; i++)
{
if (primeData[i] != 0)
root = root.Insert(new LinkedNode(i, primeData[i]));
}
return root;
}
private static LinkedNode BuildTree(LinkedNode tail)
{
LinkedNode current = tail;
while (current != null)
{
LinkedNode child0 = current;
LinkedNode child1 = current.Prev;
if (child1 == null) break;
LinkedNode parent = new LinkedNode(0, child0.Weight + child1.Weight);
parent.Child0 = child0;
child0.Parent = parent;
child1.Parent = parent;
current.Insert(parent);
current = current.Prev.Prev;
}
return current;
}
private static LinkedNode InsertNode(LinkedNode tail, int decomp)
{
LinkedNode parent = tail;
LinkedNode result = tail.Prev; // This will be the new tail after the tree is updated
LinkedNode temp = new LinkedNode(parent.DecompressedValue, parent.Weight);
temp.Parent = parent;
LinkedNode newnode = new LinkedNode(decomp, 0);
newnode.Parent = parent;
parent.Child0 = newnode;
tail.Next = temp;
temp.Prev = tail;
newnode.Prev = temp;
temp.Next = newnode;
AdjustTree(newnode);
// TODO: For compression type 0, AdjustTree should be called
// once for every value written and only once here
AdjustTree(newnode);
return result;
}
// This increases the weight of the new node and its antecendants
// and adjusts the tree if needed
private static void AdjustTree(LinkedNode newNode)
{
LinkedNode current = newNode;
while (current != null)
{
current.Weight++;
LinkedNode insertpoint;
LinkedNode prev;
// Go backwards thru the list looking for the insertion point
insertpoint = current;
while (true)
{
prev = insertpoint.Prev;
if (prev == null) break;
if (prev.Weight >= current.Weight) break;
insertpoint = prev;
}
// No insertion point found
if (insertpoint == current)
{
current = current.Parent;
continue;
}
// The following code basicly swaps insertpoint with current
// remove insert point
if (insertpoint.Prev != null) insertpoint.Prev.Next = insertpoint.Next;
insertpoint.Next.Prev = insertpoint.Prev;
// Insert insertpoint after current
insertpoint.Next = current.Next;
insertpoint.Prev = current;
if (current.Next != null) current.Next.Prev = insertpoint;
current.Next = insertpoint;
// remove current
current.Prev.Next = current.Next;
current.Next.Prev = current.Prev;
// insert current after prev
LinkedNode temp = prev.Next;
current.Next = temp;
current.Prev = prev;
temp.Prev = current;
prev.Next = current;
// Set up parent/child links
LinkedNode currentparent = current.Parent;
LinkedNode insertparent = insertpoint.Parent;
if (currentparent.Child0 == current)
currentparent.Child0 = insertpoint;
if (currentparent != insertparent && insertparent.Child0 == insertpoint)
insertparent.Child0 = current;
current.Parent = insertparent;
insertpoint.Parent = currentparent;
current = current.Parent;
}
}
}
}
| 48.3687 | 111 | 0.521196 | [
"MIT"
] | BlacklightsC/CirnoLib | CirnoLib.MPQ/CompressLib/Huffman.cs | 18,237 | C# |
//-----------------------------------------------------------------------
// <copyright file="CardForDeckReplacer.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
#pragma warning disable SA1600 // Elements should be documented
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace ThScoreFileConverter.Models.Th123
{
// %T123DC[ww][x][yy][z]
internal class CardForDeckReplacer : IStringReplaceable
{
private static readonly string Pattern = Utils.Format(
@"%T123DC({0})({1})(\d{{2}})([NC])", Parsers.CharaParser.Pattern, Parsers.CardTypeParser.Pattern);
private readonly MatchEvaluator evaluator;
public CardForDeckReplacer(
IReadOnlyDictionary<int, Th105.ICardForDeck> systemCards,
IReadOnlyDictionary<Chara, Th105.IClearData<Chara>> clearDataDictionary,
bool hideUntriedCards)
{
if (systemCards is null)
throw new ArgumentNullException(nameof(systemCards));
if (clearDataDictionary is null)
throw new ArgumentNullException(nameof(clearDataDictionary));
this.evaluator = new MatchEvaluator(match =>
{
var chara = Parsers.CharaParser.Parse(match.Groups[1].Value);
var cardType = Parsers.CardTypeParser.Parse(match.Groups[2].Value);
var number = int.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture);
var type = match.Groups[4].Value.ToUpperInvariant();
if (chara == Chara.Oonamazu)
return match.ToString();
Th105.ICardForDeck cardForDeck;
string cardName;
if (cardType == Th105.CardType.System)
{
if (Definitions.SystemCardNameTable.TryGetValue(number - 1, out var name))
{
cardForDeck = systemCards.TryGetValue(number - 1, out var card)
? card : new Th105.CardForDeck();
cardName = name;
}
else
{
return match.ToString();
}
}
else
{
// serialNumber : 0-based
bool TryGetCharaCardIdPair(int serialNumber, out (Chara Chara, int CardId) charaCardIdPair)
{
if (Definitions.CardOrderTable.TryGetValue(chara, out var cardTypeIdDict)
&& cardTypeIdDict.TryGetValue(cardType, out var cardIds)
&& serialNumber < cardIds.Count)
{
charaCardIdPair = (chara, cardIds[serialNumber]);
return true;
}
charaCardIdPair = default;
return false;
}
if (TryGetCharaCardIdPair(number - 1, out var key)
&& Definitions.CardNameTable.TryGetValue(key, out var name))
{
cardForDeck = clearDataDictionary.TryGetValue(key.Chara, out var clearData)
&& clearData.CardsForDeck.TryGetValue(key.CardId, out var card)
? card : new Th105.CardForDeck();
cardName = name;
}
else
{
return match.ToString();
}
}
if (type == "N")
{
if (hideUntriedCards)
{
if (cardForDeck.MaxNumber <= 0)
return "??????????";
}
return cardName;
}
else
{
return Utils.ToNumberString(cardForDeck.MaxNumber);
}
});
}
public string Replace(string input) => Regex.Replace(input, Pattern, this.evaluator, RegexOptions.IgnoreCase);
}
}
| 39.821429 | 118 | 0.486547 | [
"BSD-2-Clause"
] | fossabot/ThScoreFileConverter | ThScoreFileConverter/Models/Th123/CardForDeckReplacer.cs | 4,462 | C# |
using Swisstalk.ORM.Transport;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Swisstalk.ORM.Decoding
{
public class AtomicDecoder
{
private static readonly Dictionary<Type, Func<object, object>> ConversionTable = new Dictionary<Type, Func<object, object>>()
{
{ typeof(bool), ConvertBool },
{ typeof(sbyte), ConvertSByte },
{ typeof(byte), ConvertByte },
{ typeof(short), ConvertShort },
{ typeof(ushort), ConvertUShort },
{ typeof(int), ConvertInt },
{ typeof(uint), ConvertUInt },
{ typeof(long), ConvertLong },
{ typeof(ulong), ConvertULong },
{ typeof(float), ConvertFloat },
{ typeof(double), ConvertDouble },
{ typeof(string), ConvertString },
};
public static object Decode(Packet p, Type t)
{
if (p.Payload == null)
{
return null;
}
else if (t.IsEnum)
{
return Enum.Parse(t, p.Payload.ToString());
}
else
{
return ConversionTable[t](p.Payload);
}
}
private static object ConvertBool(object obj)
{
return Convert.ToBoolean(obj, CultureInfo.InvariantCulture);
}
private static object ConvertSByte(object obj)
{
return Convert.ToSByte(obj, CultureInfo.InvariantCulture);
}
private static object ConvertByte(object obj)
{
return Convert.ToByte(obj, CultureInfo.InvariantCulture);
}
private static object ConvertShort(object obj)
{
return Convert.ToInt16(obj, CultureInfo.InvariantCulture);
}
private static object ConvertUShort(object obj)
{
return Convert.ToUInt16(obj, CultureInfo.InvariantCulture);
}
private static object ConvertInt(object obj)
{
return Convert.ToInt32(obj, CultureInfo.InvariantCulture);
}
private static object ConvertUInt(object obj)
{
return Convert.ToUInt32(obj, CultureInfo.InvariantCulture);
}
private static object ConvertLong(object obj)
{
return Convert.ToInt64(obj, CultureInfo.InvariantCulture); ;
}
private static object ConvertULong(object obj)
{
return Convert.ToUInt64(obj, CultureInfo.InvariantCulture);
}
private static object ConvertFloat(object obj)
{
return Convert.ToSingle(PatchFloatingPointToInvariantCulture(obj), CultureInfo.InvariantCulture);
}
private static object ConvertDouble(object obj)
{
return Convert.ToDouble(PatchFloatingPointToInvariantCulture(obj), CultureInfo.InvariantCulture);
}
private static object ConvertString(object obj)
{
return obj.ToString();
}
private static object PatchFloatingPointToInvariantCulture(object obj)
{
return obj.ToString().Replace("\"", string.Empty).Replace(',', '.');
}
}
}
| 30.12037 | 133 | 0.577621 | [
"MIT"
] | valentinivanov/swisstalk | code/ORM/Decoding/AtomicDecoder.cs | 3,255 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms.Automation;
using Accessibility;
using static Interop;
namespace System.Windows.Forms
{
/// <summary>
/// Provides an implementation for an object that can be inspected by an
/// accessibility application.
/// </summary>
public partial class AccessibleObject :
StandardOleMarshalObject,
IReflect,
IAccessible,
UiaCore.IAccessibleEx,
Ole32.IServiceProvider,
UiaCore.IRawElementProviderSimple,
UiaCore.IRawElementProviderFragment,
UiaCore.IRawElementProviderFragmentRoot,
UiaCore.IInvokeProvider,
UiaCore.IValueProvider,
UiaCore.IRangeValueProvider,
UiaCore.IExpandCollapseProvider,
UiaCore.IToggleProvider,
UiaCore.ITableProvider,
UiaCore.ITableItemProvider,
UiaCore.IGridProvider,
UiaCore.IGridItemProvider,
Oleaut32.IEnumVariant,
Ole32.IOleWindow,
UiaCore.ILegacyIAccessibleProvider,
UiaCore.ISelectionProvider,
UiaCore.ISelectionItemProvider,
UiaCore.IRawElementProviderHwndOverride,
UiaCore.IScrollItemProvider,
UiaCore.IMultipleViewProvider,
UiaCore.ITextProvider,
UiaCore.ITextProvider2
{
/// <summary>
/// Specifies the <see cref='IAccessible'/> interface used by this <see cref='AccessibleObject'/>.
/// </summary>
private SystemIAccessibleWrapper systemIAccessible = new SystemIAccessibleWrapper(
null /* Prevents throwing exception when call to null-value system IAccessible */);
/// <summary>
/// Specifies the <see cref='Oleaut32.IEnumVariant'/> used by this
/// <see cref='AccessibleObject'/> .
/// </summary>
private Oleaut32.IEnumVariant? systemIEnumVariant;
private Oleaut32.IEnumVariant? enumVariant;
// IOleWindow interface of the 'inner' system IAccessible object that we are wrapping
private Ole32.IOleWindow? systemIOleWindow;
// Indicates this object is being used ONLY to wrap a system IAccessible
private readonly bool systemWrapper;
private UiaTextProvider? _textProvider;
private UiaTextProvider2? _textProvider2;
// The support for the UIA Notification event begins in RS3.
// Assume the UIA Notification event is available until we learn otherwise.
// If we learn that the UIA Notification event is not available,
// controls should not attempt to raise it.
private static bool notificationEventAvailable = true;
internal const int RuntimeIDFirstItem = 0x2a;
public AccessibleObject()
{
}
// This constructor is used ONLY for wrapping system IAccessible objects
private AccessibleObject(IAccessible? iAcc)
{
systemIAccessible = new SystemIAccessibleWrapper(iAcc);
systemWrapper = true;
}
/// <summary>
/// Gets the bounds of the accessible object, in screen coordinates.
/// </summary>
public virtual Rectangle Bounds
{
get
{
// Use the system provided bounds
systemIAccessible.accLocation(out int left, out int top, out int width, out int height, NativeMethods.CHILDID_SELF);
return new Rectangle(left, top, width, height);
}
}
/// <summary>
/// Gets a description of the default action for an object.
/// </summary>
public virtual string? DefaultAction => systemIAccessible.get_accDefaultAction(NativeMethods.CHILDID_SELF);
/// <summary>
/// Gets a description of the object's visual appearance to the user.
/// </summary>
public virtual string? Description => systemIAccessible.get_accDescription(NativeMethods.CHILDID_SELF);
private Oleaut32.IEnumVariant EnumVariant => enumVariant ?? (enumVariant = new EnumVariantObject(this));
/// <summary>
/// Gets a description of what the object does or how the object is used.
/// </summary>
public virtual string? Help => systemIAccessible.get_accHelp(NativeMethods.CHILDID_SELF);
/// <summary>
/// Gets the object shortcut key or access key for an accessible object.
/// </summary>
public virtual string? KeyboardShortcut => systemIAccessible.get_accKeyboardShortcut(NativeMethods.CHILDID_SELF);
/// <summary>
/// Gets or sets the object name.
/// </summary>
public virtual string? Name
{
get => systemIAccessible.get_accName(NativeMethods.CHILDID_SELF);
set => systemIAccessible.set_accName(NativeMethods.CHILDID_SELF, value);
}
/// <summary>
/// When overridden in a derived class, gets or sets the parent of an
/// accessible object.
/// </summary>
public virtual AccessibleObject? Parent => WrapIAccessible(systemIAccessible.accParent);
/// <summary>
/// Gets the role of this accessible object.
/// </summary>
public virtual AccessibleRole Role
{
get
{
var accRole = systemIAccessible.get_accRole(NativeMethods.CHILDID_SELF);
return accRole is not null
? (AccessibleRole)accRole
: AccessibleRole.None;
}
}
/// <summary>
/// Gets the state of this accessible object.
/// </summary>
public virtual AccessibleStates State
{
get
{
var accState = systemIAccessible.get_accState(NativeMethods.CHILDID_SELF);
return accState is not null
? (AccessibleStates)accState
: AccessibleStates.None;
}
}
/// <summary>
/// Gets or sets the value of an accessible object.
/// </summary>
public virtual string? Value
{
get
{
if (systemIAccessible.IsIAccessibleCreated)
{
return systemIAccessible.get_accValue(NativeMethods.CHILDID_SELF);
}
return string.Empty;
}
set => systemIAccessible.set_accValue(NativeMethods.CHILDID_SELF, value);
}
/// <summary>
/// When overridden in a derived class, gets the accessible child
/// corresponding to the specified index.
/// </summary>
public virtual AccessibleObject? GetChild(int index) => null;
/// <summary>
/// When overridden in a derived class, gets the number of children
/// belonging to an accessible object.
/// </summary>
public virtual int GetChildCount() => -1;
/// <summary>
/// Mechanism for overriding default IEnumVariant behavior of the 'inner'
/// system accessible object (IEnumVariant is how a system accessible
/// object exposes its ordered list of child objects).
///
/// USAGE: Overridden method in derived class should return array of
/// integers representing new order to be imposed on the child accessible
/// object collection returned by the system (which we assume will be a
/// set of accessible objects that represent the child windows, in z-order).
/// Each array element contains the original z-order based rank of the
/// child window that is to appear at that position in the new ordering.
/// Note: This array could also be used to filter out unwanted child
/// windows too, if necessary (not recommended).
/// </summary>
internal virtual int[]? GetSysChildOrder() => null;
/// <summary>
/// Mechanism for overriding default IAccessible.accNavigate behavior of
/// the 'inner' system accessible object (accNavigate is how you move
/// between parent, child and sibling accessible objects).
///
/// USAGE: 'navdir' indicates navigation operation to perform, relative to
/// this accessible object.
/// If operation is unsupported, return false to allow fall-back to default
/// system behavior. Otherwise return destination object in the out
/// parameter, or null to indicate 'off end of list'.
/// </summary>
internal virtual bool GetSysChild(AccessibleNavigation navdir, out AccessibleObject? accessibleObject)
{
accessibleObject = null;
return false;
}
/// <summary>
/// When overridden in a derived class, gets the object that has the
/// keyboard focus.
/// </summary>
public virtual AccessibleObject? GetFocused()
{
// Default behavior for objects with AccessibleObject children
if (GetChildCount() >= 0)
{
int count = GetChildCount();
for (int index = 0; index < count; ++index)
{
AccessibleObject? child = GetChild(index);
Debug.Assert(child is not null, "GetChild(" + index.ToString(CultureInfo.InvariantCulture) + ") returned null!");
if (child is not null && ((child.State & AccessibleStates.Focused) != 0))
{
return child;
}
}
if ((State & AccessibleStates.Focused) != 0)
{
return this;
}
return null;
}
return WrapIAccessible(systemIAccessible.accFocus);
}
/// <summary>
/// Gets an identifier for a Help topic and the path to the Help file
/// associated with this accessible object.
/// </summary>
public virtual int GetHelpTopic(out string? fileName) =>
systemIAccessible.get_accHelpTopic(out fileName, NativeMethods.CHILDID_SELF);
/// <summary>
/// When overridden in a derived class, gets the currently selected child.
/// </summary>
public virtual AccessibleObject? GetSelected()
{
// Default behavior for objects with AccessibleObject children
if (GetChildCount() >= 0)
{
int count = GetChildCount();
for (int index = 0; index < count; ++index)
{
AccessibleObject? child = GetChild(index);
Debug.Assert(child is not null, "GetChild(" + index.ToString(CultureInfo.InvariantCulture) + ") returned null!");
if (child is not null && ((child.State & AccessibleStates.Selected) != 0))
{
return child;
}
}
if ((State & AccessibleStates.Selected) != 0)
{
return this;
}
return null;
}
return WrapIAccessible(systemIAccessible.accSelection);
}
/// <summary>
/// Return the child object at the given screen coordinates.
/// </summary>
public virtual AccessibleObject? HitTest(int x, int y)
{
// Default behavior for objects with AccessibleObject children
if (GetChildCount() >= 0)
{
int count = GetChildCount();
for (int index = 0; index < count; ++index)
{
AccessibleObject? child = GetChild(index);
Debug.Assert(child is not null, "GetChild(" + index.ToString(CultureInfo.InvariantCulture) + ") returned null!");
if (child is not null && child.Bounds.Contains(x, y))
{
return child;
}
}
return this;
}
if (systemIAccessible.IsIAccessibleCreated)
{
return WrapIAccessible(systemIAccessible.accHitTest(x, y));
}
if (Bounds.Contains(x, y))
{
return this;
}
return null;
}
internal virtual bool IsIAccessibleExSupported()
{
// Override this, in your derived class, to enable IAccessibleEx support
return false;
}
internal virtual bool IsPatternSupported(UiaCore.UIA patternId)
{
// Override this, in your derived class, if you implement UIAutomation patterns
if (patternId == UiaCore.UIA.InvokePatternId)
{
return IsInvokePatternAvailable;
}
return false;
}
internal virtual int[]? RuntimeId => null;
internal virtual int ProviderOptions
=> (int)(UiaCore.ProviderOptions.ServerSideProvider | UiaCore.ProviderOptions.UseComThreading);
internal virtual UiaCore.IRawElementProviderSimple? HostRawElementProvider => null;
internal virtual object? GetPropertyValue(UiaCore.UIA propertyID) =>
propertyID switch
{
UiaCore.UIA.IsInvokePatternAvailablePropertyId => IsInvokePatternAvailable,
UiaCore.UIA.BoundingRectanglePropertyId => Bounds,
_ => null
};
private bool IsInvokePatternAvailable
{
get
{
// MSAA Proxy determines the availability of invoke pattern based
// on Role/DefaultAction properties.
// Below code emulates the same rules.
switch (Role)
{
case AccessibleRole.MenuItem:
case AccessibleRole.Link:
case AccessibleRole.PushButton:
case AccessibleRole.ButtonDropDown:
case AccessibleRole.ButtonMenu:
case AccessibleRole.ButtonDropDownGrid:
case AccessibleRole.Clock:
case AccessibleRole.SplitButton:
return true;
case AccessibleRole.Default:
case AccessibleRole.None:
case AccessibleRole.Sound:
case AccessibleRole.Cursor:
case AccessibleRole.Caret:
case AccessibleRole.Alert:
case AccessibleRole.Client:
case AccessibleRole.Chart:
case AccessibleRole.Dialog:
case AccessibleRole.Border:
case AccessibleRole.Column:
case AccessibleRole.Row:
case AccessibleRole.HelpBalloon:
case AccessibleRole.Character:
case AccessibleRole.PageTab:
case AccessibleRole.PropertyPage:
case AccessibleRole.DropList:
case AccessibleRole.Dial:
case AccessibleRole.HotkeyField:
case AccessibleRole.Diagram:
case AccessibleRole.Animation:
case AccessibleRole.Equation:
case AccessibleRole.WhiteSpace:
case AccessibleRole.IpAddress:
case AccessibleRole.OutlineButton:
return false;
default:
return !string.IsNullOrEmpty(DefaultAction);
}
}
}
internal virtual int GetChildId() => NativeMethods.CHILDID_SELF;
internal virtual UiaCore.IRawElementProviderFragment? FragmentNavigate(UiaCore.NavigateDirection direction) => null;
internal virtual UiaCore.IRawElementProviderSimple[]? GetEmbeddedFragmentRoots() => null;
internal virtual void SetFocus()
{
}
internal virtual Rectangle BoundingRectangle => Bounds;
internal virtual UiaCore.IRawElementProviderFragmentRoot? FragmentRoot => null;
internal virtual UiaCore.IRawElementProviderFragment? ElementProviderFromPoint(double x, double y) => this;
internal virtual UiaCore.IRawElementProviderFragment? GetFocus() => null;
internal virtual void Expand()
{
}
internal virtual void Collapse()
{
}
internal virtual UiaCore.ExpandCollapseState ExpandCollapseState => UiaCore.ExpandCollapseState.Collapsed;
internal virtual void Toggle()
{
}
internal virtual UiaCore.ToggleState ToggleState => UiaCore.ToggleState.Indeterminate;
internal virtual UiaCore.IRawElementProviderSimple[]? GetRowHeaders() => null;
internal virtual UiaCore.IRawElementProviderSimple[]? GetColumnHeaders() => null;
internal virtual UiaCore.RowOrColumnMajor RowOrColumnMajor => UiaCore.RowOrColumnMajor.RowMajor;
internal virtual UiaCore.IRawElementProviderSimple[]? GetRowHeaderItems() => null;
internal virtual UiaCore.IRawElementProviderSimple[]? GetColumnHeaderItems() => null;
internal virtual UiaCore.IRawElementProviderSimple? GetItem(int row, int column) => null;
internal virtual int RowCount => -1;
internal virtual int ColumnCount => -1;
internal virtual int Row => -1;
internal virtual int Column => -1;
internal virtual int RowSpan => 1;
internal virtual int ColumnSpan => 1;
internal virtual UiaCore.IRawElementProviderSimple? ContainingGrid => null;
internal virtual void Invoke() => DoDefaultAction();
internal virtual UiaCore.ITextRangeProvider? DocumentRangeInternal => _textProvider?.DocumentRange;
internal virtual UiaCore.ITextRangeProvider[]? GetTextSelection() => _textProvider?.GetSelection();
internal virtual UiaCore.ITextRangeProvider[]? GetTextVisibleRanges() => _textProvider?.GetVisibleRanges();
internal virtual UiaCore.ITextRangeProvider? GetTextRangeFromChild(UiaCore.IRawElementProviderSimple childElement)
=> _textProvider?.RangeFromChild(childElement);
internal virtual UiaCore.ITextRangeProvider? GetTextRangeFromPoint(Point screenLocation) => _textProvider?.RangeFromPoint(screenLocation);
internal virtual UiaCore.SupportedTextSelection SupportedTextSelectionInternal
=> _textProvider?.SupportedTextSelection ?? UiaCore.SupportedTextSelection.None;
internal virtual UiaCore.ITextRangeProvider? GetTextCaretRange(out BOOL isActive)
{
isActive = BOOL.FALSE;
return _textProvider2?.GetCaretRange(out isActive);
}
internal virtual UiaCore.ITextRangeProvider? GetRangeFromAnnotation(UiaCore.IRawElementProviderSimple annotationElement) =>
_textProvider2?.RangeFromAnnotation(annotationElement);
internal virtual bool IsReadOnly => false;
internal virtual void SetValue(string? newValue)
{
Value = newValue;
}
internal virtual UiaCore.IRawElementProviderSimple? GetOverrideProviderForHwnd(IntPtr hwnd) => null;
internal virtual int GetMultiViewProviderCurrentView() => 0;
internal virtual int[]? GetMultiViewProviderSupportedViews() => Array.Empty<int>();
internal virtual string GetMultiViewProviderViewName(int viewId) => string.Empty;
internal virtual void SetMultiViewProviderCurrentView(int viewId)
{
}
internal virtual void SetValue(double newValue)
{
}
internal virtual double LargeChange => double.NaN;
internal virtual double Maximum => double.NaN;
internal virtual double Minimum => double.NaN;
internal virtual double SmallChange => double.NaN;
internal virtual double RangeValue => double.NaN;
internal virtual UiaCore.IRawElementProviderSimple[]? GetSelection() => null;
internal virtual bool CanSelectMultiple => false;
internal virtual bool IsSelectionRequired => false;
internal virtual void SelectItem()
{
}
internal virtual void AddToSelection()
{
}
internal virtual void RemoveFromSelection()
{
}
internal virtual bool IsItemSelected => false;
internal virtual UiaCore.IRawElementProviderSimple? ItemSelectionContainer => null;
/// <summary>
/// Sets the parent accessible object for the node which can be added or removed to/from hierachy nodes.
/// </summary>
/// <param name="parent">The parent accessible object.</param>
internal virtual void SetParent(AccessibleObject? parent)
{
}
/// <summary>
/// Sets the detachable child accessible object which may be added or removed to/from hierachy nodes.
/// </summary>
/// <param name="child">The child accessible object.</param>
internal virtual void SetDetachableChild(AccessibleObject? child)
{
}
unsafe HRESULT Ole32.IServiceProvider.QueryService(Guid* service, Guid* riid, IntPtr* ppvObject)
{
if (service is null || riid is null)
{
return HRESULT.E_NOINTERFACE;
}
if (ppvObject is null)
{
return HRESULT.E_POINTER;
}
if (IsIAccessibleExSupported())
{
Guid IID_IAccessibleEx = typeof(UiaCore.IAccessibleEx).GUID;
if (service->Equals(IID_IAccessibleEx) && riid->Equals(IID_IAccessibleEx))
{
// We want to return the internal, secure, object, which we don't have access here
// Return non-null, which will be interpreted in internal method, to mean returning casted object to IAccessibleEx
*ppvObject = Marshal.GetComInterfaceForObject(this, typeof(UiaCore.IAccessibleEx));
return HRESULT.S_OK;
}
}
return HRESULT.E_NOINTERFACE;
}
UiaCore.IAccessibleEx? UiaCore.IAccessibleEx.GetObjectForChild(int idChild) => null;
// This method is never called
unsafe HRESULT UiaCore.IAccessibleEx.GetIAccessiblePair(out object? ppAcc, int* pidChild)
{
if (pidChild is null)
{
ppAcc = null;
return HRESULT.E_POINTER;
}
// No need to implement this for patterns and properties
ppAcc = null;
*pidChild = 0;
return HRESULT.E_POINTER;
}
int[]? UiaCore.IAccessibleEx.GetRuntimeId() => RuntimeId;
unsafe HRESULT UiaCore.IAccessibleEx.ConvertReturnedElement(UiaCore.IRawElementProviderSimple pIn, IntPtr* ppRetValOut)
{
if (ppRetValOut == null)
{
return HRESULT.E_POINTER;
}
// No need to implement this for patterns and properties
*ppRetValOut = IntPtr.Zero;
return HRESULT.E_NOTIMPL;
}
UiaCore.ProviderOptions UiaCore.IRawElementProviderSimple.ProviderOptions => (UiaCore.ProviderOptions)ProviderOptions;
UiaCore.IRawElementProviderSimple? UiaCore.IRawElementProviderSimple.HostRawElementProvider => HostRawElementProvider;
object? UiaCore.IRawElementProviderSimple.GetPatternProvider(UiaCore.UIA patternId)
{
if (IsPatternSupported(patternId))
{
return this;
}
return null;
}
object? UiaCore.IRawElementProviderSimple.GetPropertyValue(UiaCore.UIA propertyID) => GetPropertyValue(propertyID);
object? UiaCore.IRawElementProviderFragment.Navigate(UiaCore.NavigateDirection direction) => FragmentNavigate(direction);
int[]? UiaCore.IRawElementProviderFragment.GetRuntimeId() => RuntimeId;
object[]? UiaCore.IRawElementProviderFragment.GetEmbeddedFragmentRoots() => GetEmbeddedFragmentRoots();
void UiaCore.IRawElementProviderFragment.SetFocus() => SetFocus();
UiaCore.UiaRect UiaCore.IRawElementProviderFragment.BoundingRectangle => new UiaCore.UiaRect(BoundingRectangle);
UiaCore.IRawElementProviderFragmentRoot? UiaCore.IRawElementProviderFragment.FragmentRoot => FragmentRoot;
object? UiaCore.IRawElementProviderFragmentRoot.ElementProviderFromPoint(double x, double y) => ElementProviderFromPoint(x, y);
object? UiaCore.IRawElementProviderFragmentRoot.GetFocus() => GetFocus();
string? UiaCore.ILegacyIAccessibleProvider.DefaultAction => DefaultAction;
string? UiaCore.ILegacyIAccessibleProvider.Description => Description;
string? UiaCore.ILegacyIAccessibleProvider.Help => Help;
string? UiaCore.ILegacyIAccessibleProvider.KeyboardShortcut => KeyboardShortcut;
string? UiaCore.ILegacyIAccessibleProvider.Name => Name;
uint UiaCore.ILegacyIAccessibleProvider.Role => (uint)Role;
uint UiaCore.ILegacyIAccessibleProvider.State => (uint)State;
string? UiaCore.ILegacyIAccessibleProvider.Value => Value;
int UiaCore.ILegacyIAccessibleProvider.ChildId => GetChildId();
void UiaCore.ILegacyIAccessibleProvider.DoDefaultAction() => DoDefaultAction();
IAccessible? UiaCore.ILegacyIAccessibleProvider.GetIAccessible() => AsIAccessible(this);
UiaCore.IRawElementProviderSimple[] UiaCore.ILegacyIAccessibleProvider.GetSelection()
{
if (GetSelected() is UiaCore.IRawElementProviderSimple selected)
{
return new UiaCore.IRawElementProviderSimple[] { selected };
}
return Array.Empty<UiaCore.IRawElementProviderSimple>();
}
void UiaCore.ILegacyIAccessibleProvider.Select(int flagsSelect) => Select((AccessibleSelection)flagsSelect);
void UiaCore.ILegacyIAccessibleProvider.SetValue(string szValue) => SetValue(szValue);
void UiaCore.IExpandCollapseProvider.Expand() => Expand();
void UiaCore.IExpandCollapseProvider.Collapse() => Collapse();
UiaCore.ExpandCollapseState UiaCore.IExpandCollapseProvider.ExpandCollapseState => ExpandCollapseState;
void UiaCore.IInvokeProvider.Invoke() => Invoke();
UiaCore.ITextRangeProvider? UiaCore.ITextProvider.DocumentRange => DocumentRangeInternal;
UiaCore.ITextRangeProvider[]? UiaCore.ITextProvider.GetSelection() => GetTextSelection();
UiaCore.ITextRangeProvider[]? UiaCore.ITextProvider.GetVisibleRanges() => GetTextVisibleRanges();
UiaCore.ITextRangeProvider? UiaCore.ITextProvider.RangeFromChild(UiaCore.IRawElementProviderSimple childElement) =>
GetTextRangeFromChild(childElement);
UiaCore.ITextRangeProvider? UiaCore.ITextProvider.RangeFromPoint(Point screenLocation) => GetTextRangeFromPoint(screenLocation);
UiaCore.SupportedTextSelection UiaCore.ITextProvider.SupportedTextSelection => SupportedTextSelectionInternal;
UiaCore.ITextRangeProvider? UiaCore.ITextProvider2.DocumentRange => DocumentRangeInternal;
UiaCore.ITextRangeProvider[]? UiaCore.ITextProvider2.GetSelection() => GetTextSelection();
UiaCore.ITextRangeProvider[]? UiaCore.ITextProvider2.GetVisibleRanges() => GetTextVisibleRanges();
UiaCore.ITextRangeProvider? UiaCore.ITextProvider2.RangeFromChild(UiaCore.IRawElementProviderSimple childElement) =>
GetTextRangeFromChild(childElement);
UiaCore.ITextRangeProvider? UiaCore.ITextProvider2.RangeFromPoint(Point screenLocation) => GetTextRangeFromPoint(screenLocation);
UiaCore.SupportedTextSelection UiaCore.ITextProvider2.SupportedTextSelection => SupportedTextSelectionInternal;
UiaCore.ITextRangeProvider? UiaCore.ITextProvider2.GetCaretRange(out BOOL isActive) => GetTextCaretRange(out isActive);
UiaCore.ITextRangeProvider? UiaCore.ITextProvider2.RangeFromAnnotation(UiaCore.IRawElementProviderSimple annotationElement) =>
GetRangeFromAnnotation(annotationElement);
BOOL UiaCore.IValueProvider.IsReadOnly => IsReadOnly ? BOOL.TRUE : BOOL.FALSE;
string? UiaCore.IValueProvider.Value => Value;
void UiaCore.IValueProvider.SetValue(string? newValue) => SetValue(newValue);
void UiaCore.IToggleProvider.Toggle() => Toggle();
UiaCore.ToggleState UiaCore.IToggleProvider.ToggleState => ToggleState;
object[]? UiaCore.ITableProvider.GetRowHeaders() => GetRowHeaders();
object[]? UiaCore.ITableProvider.GetColumnHeaders() => GetColumnHeaders();
UiaCore.RowOrColumnMajor UiaCore.ITableProvider.RowOrColumnMajor => RowOrColumnMajor;
object[]? UiaCore.ITableItemProvider.GetRowHeaderItems() => GetRowHeaderItems();
object[]? UiaCore.ITableItemProvider.GetColumnHeaderItems() => GetColumnHeaderItems();
object? UiaCore.IGridProvider.GetItem(int row, int column) => GetItem(row, column);
int UiaCore.IGridProvider.RowCount => RowCount;
int UiaCore.IGridProvider.ColumnCount => ColumnCount;
int UiaCore.IGridItemProvider.Row => Row;
int UiaCore.IGridItemProvider.Column => Column;
int UiaCore.IGridItemProvider.RowSpan => RowSpan;
int UiaCore.IGridItemProvider.ColumnSpan => ColumnSpan;
UiaCore.IRawElementProviderSimple? UiaCore.IGridItemProvider.ContainingGrid => ContainingGrid;
/// <summary>
/// Perform the default action
/// </summary>
void IAccessible.accDoDefaultAction(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.AccDoDefaultAction: this = " +
ToString() + ", childID = " + childID.ToString());
// If the default action is to be performed on self, do it.
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
DoDefaultAction();
return;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
child.DoDefaultAction();
return;
}
}
systemIAccessible.accDoDefaultAction(childID);
}
/// <summary>
/// Perform a hit test
/// </summary>
object? IAccessible.accHitTest(int xLeft, int yTop)
{
if (IsClientObject)
{
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.AccHitTest: this = " +
ToString());
AccessibleObject? obj = HitTest(xLeft, yTop);
if (obj is not null)
{
return AsVariant(obj);
}
}
return systemIAccessible.accHitTest(xLeft, yTop);
}
/// <summary>
/// The location of the Accessible object
/// </summary>
void IAccessible.accLocation(
out int pxLeft,
out int pyTop,
out int pcxWidth,
out int pcyHeight,
object childID)
{
pxLeft = 0;
pyTop = 0;
pcxWidth = 0;
pcyHeight = 0;
if (IsClientObject)
{
ValidateChildID(ref childID);
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.AccLocation: this = " +
ToString() + ", childID = " + childID.ToString());
// Use the Location function's return value if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
Rectangle bounds = Bounds;
pxLeft = bounds.X;
pyTop = bounds.Y;
pcxWidth = bounds.Width;
pcyHeight = bounds.Height;
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.AccLocation: Returning " +
bounds.ToString());
return;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
Rectangle bounds = child.Bounds;
pxLeft = bounds.X;
pyTop = bounds.Y;
pcxWidth = bounds.Width;
pcyHeight = bounds.Height;
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.AccLocation: Returning " +
bounds.ToString());
return;
}
}
systemIAccessible.accLocation(out pxLeft, out pyTop, out pcxWidth, out pcyHeight, childID);
}
/// <summary>
/// Navigate to another accessible object.
/// </summary>
object? IAccessible.accNavigate(int navDir, object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.AccNavigate: this = " +
ToString() + ", navdir = " + navDir.ToString(CultureInfo.InvariantCulture) + ", childID = " + childID.ToString());
// Use the Navigate function's return value if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
AccessibleObject? newObject = Navigate((AccessibleNavigation)navDir);
if (newObject is not null)
{
return AsVariant(newObject);
}
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return AsVariant(child.Navigate((AccessibleNavigation)navDir));
}
}
if (!SysNavigate(navDir, childID, out object? retObject))
{
return systemIAccessible.accNavigate(navDir, childID);
}
return retObject;
}
/// <summary>
/// Select an accessible object.
/// </summary>
void IAccessible.accSelect(int flagsSelect, object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.AccSelect: this = " +
ToString() + ", flagsSelect = " + flagsSelect.ToString(CultureInfo.InvariantCulture) + ", childID = " + childID.ToString());
// If the selection is self, do it.
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
Select((AccessibleSelection)flagsSelect); // Uses an Enum which matches SELFLAG
return;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
child.Select((AccessibleSelection)flagsSelect);
return;
}
}
systemIAccessible.accSelect(flagsSelect, childID);
}
/// <summary>
/// Performs the default action associated with this accessible object.
/// </summary>
public virtual void DoDefaultAction()
{
// By default, just does the system default action if available
systemIAccessible.accDoDefaultAction(0);
}
/// <summary>
/// Returns a child Accessible object
/// </summary>
object? IAccessible.get_accChild(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.GetAccChild: this = " +
ToString() + ", childID = " + childID.ToString());
// Return self for CHILDID_SELF
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return AsIAccessible(this);
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
// Make sure we're not returning ourselves as our own child
Debug.Assert(child != this, "An accessible object is returning itself as its own child. This can cause Accessibility client applications to stop responding.");
if (child == this)
{
return null;
}
return AsIAccessible(child);
}
}
if (systemIAccessible is null || systemIAccessible.accChildCount == 0)
{
return null;
}
// Otherwise, return the default system child for this control (if any)
return systemIAccessible.get_accChild(childID);
}
/// <summary>
/// Return the number of children
/// </summary>
int IAccessible.accChildCount
{
get
{
int childCount = -1;
if (IsClientObject)
{
childCount = GetChildCount();
}
if (childCount == -1)
{
childCount = systemIAccessible.accChildCount;
}
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.accHildCount: this = " + ToString() + ", returning " + childCount.ToString(CultureInfo.InvariantCulture));
return childCount;
}
}
/// <summary>
/// Return the default action
/// </summary>
string? IAccessible.get_accDefaultAction(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
// Return the default action property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return DefaultAction;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return child.DefaultAction;
}
}
return systemIAccessible.get_accDefaultAction(childID);
}
/// <summary>
/// Return the object or child description
/// </summary>
string? IAccessible.get_accDescription(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
// Return the description property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return Description;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return child.Description;
}
}
return systemIAccessible.get_accDescription(childID);
}
/// <summary>
/// Returns the appropriate child from the Accessible Child Collection, if available
/// </summary>
private AccessibleObject? GetAccessibleChild(object childID)
{
if (!childID.Equals(NativeMethods.CHILDID_SELF))
{
// The first child is childID == 1 (index == 0)
int index = (int)childID - 1;
if (index >= 0 && index < GetChildCount())
{
return GetChild(index);
}
}
return null;
}
/// <summary>
/// Return the object or child focus
/// </summary>
object? IAccessible.accFocus
{
get
{
if (IsClientObject)
{
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.GetAccFocus: this = " +
ToString());
AccessibleObject? obj = GetFocused();
if (obj is not null)
{
return AsVariant(obj);
}
}
return systemIAccessible.accFocus;
}
}
/// <summary>
/// Return help for this accessible object.
/// </summary>
string? IAccessible.get_accHelp(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return Help;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return child.Help;
}
}
return systemIAccessible.get_accHelp(childID);
}
/// <summary>
/// Return the object or child help topic
/// </summary>
int IAccessible.get_accHelpTopic(out string? pszHelpFile, object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return GetHelpTopic(out pszHelpFile);
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return child.GetHelpTopic(out pszHelpFile);
}
}
return systemIAccessible.get_accHelpTopic(out pszHelpFile, childID);
}
/// <summary>
/// Return the object or child keyboard shortcut
/// </summary>
string? IAccessible.get_accKeyboardShortcut(object childID)
{
return get_accKeyboardShortcutInternal(childID);
}
internal virtual string? get_accKeyboardShortcutInternal(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return KeyboardShortcut;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return child.KeyboardShortcut;
}
}
return systemIAccessible.get_accKeyboardShortcut(childID);
}
/// <summary>
/// Return the object or child name
/// </summary>
string? IAccessible.get_accName(object childID)
{
return get_accNameInternal(childID);
}
internal virtual string? get_accNameInternal(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.get_accName: this = " + ToString() +
", childID = " + childID.ToString());
// Return the name property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return Name;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return child.Name;
}
}
string? retval = systemIAccessible.get_accName(childID);
if (IsClientObject)
{
if (string.IsNullOrEmpty(retval))
{
// Name the child after its parent
retval = Name;
}
}
return retval;
}
/// <summary>
/// Return the parent object
/// </summary>
object? IAccessible.accParent
{
get
{
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.accParent: this = " + ToString());
AccessibleObject? parent = Parent;
if (parent is not null)
{
// Some debugging related tests
Debug.Assert(parent != this, "An accessible object is returning itself as its own parent. This can cause accessibility clients to stop responding.");
if (parent == this)
{
// This should prevent accessibility clients from stop responding
parent = null;
}
}
return AsIAccessible(parent);
}
}
/// <summary>
/// The role property describes an object's purpose in terms of its
/// relationship with sibling or child objects.
/// </summary>
object? IAccessible.get_accRole(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
// Return the role property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return (int)Role;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return (int)child.Role;
}
}
if (systemIAccessible is null || systemIAccessible.accChildCount == 0)
{
return null;
}
return systemIAccessible.get_accRole(childID);
}
/// <summary>
/// Return the object or child selection
/// </summary>
object? IAccessible.accSelection
{
get
{
if (IsClientObject)
{
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.GetAccSelection: this = " +
ToString());
AccessibleObject? obj = GetSelected();
if (obj is not null)
{
return AsVariant(obj);
}
}
return systemIAccessible.accSelection;
}
}
/// <summary>
/// Return the object or child state
/// </summary>
object? IAccessible.get_accState(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.GetAccState: this = " +
ToString() + ", childID = " + childID.ToString());
// Return the state property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return (int)State;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return (int)child.State;
}
}
return systemIAccessible?.get_accState(childID);
}
/// <summary>
/// Return the object or child value
/// </summary>
string? IAccessible.get_accValue(object childID)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
// Return the value property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
return Value;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
return child.Value;
}
}
return systemIAccessible.get_accValue(childID);
}
/// <summary>
/// Set the object or child name
/// </summary>
void IAccessible.set_accName(object childID, string newName)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
// Set the name property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
// Attempt to set the name property
Name = newName;
return;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
child.Name = newName;
return;
}
}
systemIAccessible?.set_accName(childID, newName);
}
/// <summary>
/// Set the object or child value
/// </summary>
void IAccessible.set_accValue(object childID, string newValue)
{
if (IsClientObject)
{
ValidateChildID(ref childID);
// Set the value property if available
if (childID.Equals(NativeMethods.CHILDID_SELF))
{
// Attempt to set the value property
Value = newValue;
return;
}
// If we have an accessible object collection, get the appropriate child
AccessibleObject? child = GetAccessibleChild(childID);
if (child is not null)
{
child.Value = newValue;
return;
}
}
systemIAccessible?.set_accValue(childID, newValue);
}
/// <summary>
/// Now that AccessibleObject is used to wrap all system-provided (OLEACC.DLL) accessible
/// objects, it needs to implement IOleWindow and pass this down to the inner object. This is
/// necessary because the OS function WindowFromAccessibleObject() walks up the parent chain
/// looking for the first object that implements IOleWindow, and uses that to get the hwnd.
///
/// But this creates a new problem for AccessibleObjects that do NOT have windows, ie. which
/// represent simple elements. To the OS, these simple elements will now appear to implement
/// IOleWindow, so it will try to get hwnds from them - which they simply cannot provide.
///
/// To work around this problem, the AccessibleObject for a simple element will delegate all
/// IOleWindow calls up the parent chain itself. This will stop at the first window-based
/// accessible object, which will be able to return an hwnd back to the OS. So we are
/// effectively 'preempting' what WindowFromAccessibleObject() would do.
/// </summary>
unsafe HRESULT Ole32.IOleWindow.GetWindow(IntPtr* phwnd)
{
// See if we have an inner object that can provide the window handle
if (systemIOleWindow is not null)
{
return systemIOleWindow.GetWindow(phwnd);
}
// Otherwise delegate to the parent object
AccessibleObject? parent = Parent;
if (parent is Ole32.IOleWindow parentWindow)
{
return parentWindow.GetWindow(phwnd);
}
// Or fail if there is no parent
if (phwnd is null)
{
return HRESULT.E_POINTER;
}
*phwnd = IntPtr.Zero;
return HRESULT.E_FAIL;
}
/// <summary>
/// See GetWindow() above for details.
/// </summary>
HRESULT Ole32.IOleWindow.ContextSensitiveHelp(BOOL fEnterMode)
{
// See if we have an inner object that can provide help
if (systemIOleWindow is not null)
{
return systemIOleWindow.ContextSensitiveHelp(fEnterMode);
}
// Otherwise delegate to the parent object
AccessibleObject? parent = Parent;
if (parent is Ole32.IOleWindow parentWindow)
{
return parentWindow.ContextSensitiveHelp(fEnterMode);
}
// Or do nothing if there is no parent
return HRESULT.S_OK;
}
/// <summary>
/// Clone this accessible object.
/// </summary>
HRESULT Oleaut32.IEnumVariant.Clone(Oleaut32.IEnumVariant[]? ppEnum) => EnumVariant.Clone(ppEnum);
/// <summary>
/// Obtain the next n children of this accessible object.
/// </summary>
unsafe HRESULT Oleaut32.IEnumVariant.Next(uint celt, IntPtr rgVar, uint* pCeltFetched)
{
return EnumVariant.Next(celt, rgVar, pCeltFetched);
}
/// <summary>
/// Resets the child accessible object enumerator.
/// </summary>
HRESULT Oleaut32.IEnumVariant.Reset() => EnumVariant.Reset();
/// <summary>
/// Skip the next n child accessible objects
/// </summary>
HRESULT Oleaut32.IEnumVariant.Skip(uint celt) => EnumVariant.Skip(celt);
/// <summary>
/// When overridden in a derived class, navigates to another object.
/// </summary>
public virtual AccessibleObject? Navigate(AccessibleNavigation navdir)
{
// Some default behavior for objects with AccessibleObject children
if (GetChildCount() >= 0)
{
switch (navdir)
{
case AccessibleNavigation.FirstChild:
return GetChild(0);
case AccessibleNavigation.LastChild:
return GetChild(GetChildCount() - 1);
case AccessibleNavigation.Previous:
case AccessibleNavigation.Up:
case AccessibleNavigation.Left:
if (Parent?.GetChildCount() > 0)
{
return null;
}
break;
case AccessibleNavigation.Next:
case AccessibleNavigation.Down:
case AccessibleNavigation.Right:
if (Parent?.GetChildCount() > 0)
{
return null;
}
break;
}
}
if (systemIAccessible.IsIAccessibleCreated)
{
if (!SysNavigate((int)navdir, NativeMethods.CHILDID_SELF, out object? retObject))
{
retObject = systemIAccessible.accNavigate((int)navdir, NativeMethods.CHILDID_SELF);
}
return WrapIAccessible(retObject);
}
return null;
}
/// <summary>
/// Selects this accessible object.
/// </summary>
public virtual void Select(AccessibleSelection flags)
{
systemIAccessible.accSelect((int)flags, 0);
}
private object? AsVariant(AccessibleObject? obj)
{
if (obj == this)
{
return NativeMethods.CHILDID_SELF;
}
return AsIAccessible(obj);
}
private IAccessible? AsIAccessible(AccessibleObject? obj)
{
if (obj is not null && obj.systemWrapper)
{
return obj.systemIAccessible.SystemIAccessibleInternal;
}
return obj;
}
/// <summary>
/// Indicates what kind of 'inner' system accessible object we are using as our fall-back
/// implementation of IAccessible (when the systemIAccessible member is not null). The inner
/// object is provided by OLEACC.DLL. Note that although the term 'id' is used, this value
/// really represents a category or type of accessible object. Ids are only unique among
/// accessible objects associated with the same window handle. Currently supported ids are...
///
/// OBJID_CLIENT - represents the window's client area (including any child windows)
/// OBJID_WINDOW - represents the window's non-client area (including caption, frame controls and scrollbars)
///
/// NOTE: When the id is OBJID_WINDOW, we short-circuit most of the virtual override behavior of
/// AccessibleObject, and turn the object into a simple wrapper around the inner system object. So
/// for a *user-defined* accessible object, that has NO inner object, its important that the id is
/// left as OBJID_CLIENT, otherwise the object will be short-circuited into a total NOP!
/// </summary>
internal int AccessibleObjectId { get; set; } = User32.OBJID.CLIENT;
/// <summary>
/// Indicates whether this accessible object represents the client area of
/// the window.
/// </summary>
internal bool IsClientObject => AccessibleObjectId == User32.OBJID.CLIENT;
/// <summary>
/// Indicates whether this accessible object represents the non-client
/// area of the window.
/// </summary>
internal bool IsNonClientObject => AccessibleObjectId == User32.OBJID.WINDOW;
internal IAccessible? GetSystemIAccessibleInternal() => systemIAccessible.SystemIAccessibleInternal;
protected void UseStdAccessibleObjects(IntPtr handle)
{
UseStdAccessibleObjects(handle, AccessibleObjectId);
}
protected void UseStdAccessibleObjects(IntPtr handle, int objid)
{
// Get a standard accessible Object
Guid IID_IAccessible = new Guid(NativeMethods.uuid_IAccessible);
object? acc = null;
int result = UnsafeNativeMethods.CreateStdAccessibleObject(
new HandleRef(this, handle),
objid,
ref IID_IAccessible,
ref acc);
// Get the IEnumVariant interface
Guid IID_IEnumVariant = typeof(Oleaut32.IEnumVariant).GUID;
object? en = null;
result = UnsafeNativeMethods.CreateStdAccessibleObject(
new HandleRef(this, handle),
objid,
ref IID_IEnumVariant,
ref en);
if (acc is not null || en is not null)
{
systemIAccessible = new SystemIAccessibleWrapper((IAccessible?)acc);
systemIEnumVariant = (Oleaut32.IEnumVariant?)en;
systemIOleWindow = (Ole32.IOleWindow?)acc;
}
}
internal void UseTextProviders(UiaTextProvider textProvider, UiaTextProvider2 textProvider2)
{
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_textProvider2 = textProvider2 ?? throw new ArgumentNullException(nameof(textProvider2));
}
/// <summary>
/// Performs custom navigation between parent/child/sibling accessible
/// objects. This is basically just a wrapper for GetSysChild(), that
/// does some of the dirty work, such as wrapping the returned object
/// in a VARIANT. Usage is similar to GetSysChild(). Called prior to
/// calling IAccessible.accNavigate on the 'inner' system accessible
/// object.
/// </summary>
private bool SysNavigate(int navDir, object childID, out object? retObject)
{
retObject = null;
// Only override system navigation relative to ourselves (since we can't interpret OLEACC child ids)
if (!childID.Equals(NativeMethods.CHILDID_SELF))
{
return false;
}
// Perform any supported navigation operation (fall back on system for unsupported navigation ops)
if (!GetSysChild((AccessibleNavigation)navDir, out AccessibleObject? newObject))
{
return false;
}
// If object found, wrap in a VARIANT. Otherwise return null for 'end of list' (OLEACC expects this)
retObject = (newObject is null) ? null : AsVariant(newObject);
// Tell caller not to fall back on system behavior now
return true;
}
/// <summary>
/// Make sure that the childID is valid.
/// </summary>
internal void ValidateChildID(ref object childID)
{
// An empty childID is considered to be the same as CHILDID_SELF.
// Some accessibility programs pass null into our functions, so we
// need to convert them here.
if (childID is null)
{
childID = NativeMethods.CHILDID_SELF;
}
else if (childID.Equals((int)HRESULT.DISP_E_PARAMNOTFOUND))
{
childID = 0;
}
else if (!(childID is int))
{
// AccExplorer seems to occasionally pass in objects instead of an int ChildID.
childID = 0;
}
}
private AccessibleObject? WrapIAccessible(object? iacc)
{
if (!(iacc is IAccessible accessible))
{
return null;
}
// Check to see if this object already wraps iacc
if (systemIAccessible.SystemIAccessibleInternal == iacc)
{
return this;
}
return new AccessibleObject(accessible);
}
/// <summary>
/// Return the requested method if it is implemented by the Reflection object. The
/// match is based upon the name and DescriptorInfo which describes the signature
/// of the method.
/// </summary>
MethodInfo? IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers)
=> typeof(IAccessible).GetMethod(name, bindingAttr, binder, types, modifiers);
/// <summary>
/// Return the requested method if it is implemented by the Reflection object. The
/// match is based upon the name of the method. If the object implementes multiple methods
/// with the same name an AmbiguousMatchException is thrown.
/// </summary>
MethodInfo? IReflect.GetMethod(string name, BindingFlags bindingAttr)
=> typeof(IAccessible).GetMethod(name, bindingAttr);
MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
=> typeof(IAccessible).GetMethods(bindingAttr);
/// <summary>
/// Return the requestion field if it is implemented by the Reflection
/// object. The match is based upon a name. There cannot be more than
/// a single field with a name.
/// </summary>
FieldInfo? IReflect.GetField(string name, BindingFlags bindingAttr)
=> typeof(IAccessible).GetField(name, bindingAttr);
FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
=> typeof(IAccessible).GetFields(bindingAttr);
/// <summary>
/// Return the property based upon name. If more than one property has
/// the given name an AmbiguousMatchException will be thrown. Returns
/// null if no property is found.
/// </summary>
PropertyInfo? IReflect.GetProperty(string name, BindingFlags bindingAttr)
=> typeof(IAccessible).GetProperty(name, bindingAttr);
/// <summary>
/// Return the property based upon the name and Descriptor info describing
/// the property indexing. Return null if no property is found.
/// </summary>
PropertyInfo? IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers)
=> typeof(IAccessible).GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
/// <summary>
/// Returns an array of PropertyInfos for all the properties defined on
/// the Reflection object.
/// </summary>
PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
=> typeof(IAccessible).GetProperties(bindingAttr);
/// <summary>
/// Return an array of members which match the passed in name.
/// </summary>
MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
=> typeof(IAccessible).GetMember(name, bindingAttr);
/// <summary>
/// Return an array of all of the members defined for this object.
/// </summary>
MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
=> typeof(IAccessible).GetMembers(bindingAttr);
/// <summary>
/// Description of the Binding Process.
/// We must invoke a method that is accessable and for which the provided
/// parameters have the most specific match. A method may be called if
/// 1. The number of parameters in the method declaration equals the number of
/// arguments provided to the invocation
/// 2. The type of each argument can be converted by the binder to the
/// type of the type of the parameter.
///
/// The binder will find all of the matching methods. These method are found based
/// upon the type of binding requested (MethodInvoke, Get/Set Properties). The set
/// of methods is filtered by the name, number of arguments and a set of search modifiers
/// defined in the Binder.
///
/// After the method is selected, it will be invoked. Accessability is checked
/// at that point. The search may be control which set of methods are searched based
/// upon the accessibility attribute associated with the method.
///
/// The BindToMethod method is responsible for selecting the method to be invoked.
/// For the default binder, the most specific method will be selected.
///
/// This will invoke a specific member...
/// @exception If <var>invokeAttr</var> is CreateInstance then all other
/// Access types must be undefined. If not we throw an ArgumentException.
/// @exception If the <var>invokeAttr</var> is not CreateInstance then an
/// ArgumentException when <var>name</var> is null.
/// @exception ArgumentException when <var>invokeAttr</var> does not specify the type
/// @exception ArgumentException when <var>invokeAttr</var> specifies both get and set of
/// a property or field.
/// @exception ArgumentException when <var>invokeAttr</var> specifies property set and
/// invoke method.
/// </summary>
object? IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters)
{
if (args?.Length == 0)
{
MemberInfo[] member = typeof(IAccessible).GetMember(name);
if (member is not null && member.Length > 0 && member[0] is PropertyInfo)
{
MethodInfo? getMethod = ((PropertyInfo)member[0]).GetGetMethod();
if (getMethod is not null && getMethod.GetParameters().Length > 0)
{
args = new object[getMethod.GetParameters().Length];
for (int i = 0; i < args.Length; i++)
{
args[i] = NativeMethods.CHILDID_SELF;
}
}
}
}
return typeof(IAccessible).InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
/// <summary>
/// Return the underlying Type that represents the IReflect Object. For
/// expando object, this is the (Object) IReflectInstance.GetType().
/// For Type object it is this.
/// </summary>
Type IReflect.UnderlyingSystemType => typeof(IAccessible);
UiaCore.IRawElementProviderSimple? UiaCore.IRawElementProviderHwndOverride.GetOverrideProviderForHwnd(IntPtr hwnd)
=> GetOverrideProviderForHwnd(hwnd);
int UiaCore.IMultipleViewProvider.CurrentView => GetMultiViewProviderCurrentView();
int[]? UiaCore.IMultipleViewProvider.GetSupportedViews() => GetMultiViewProviderSupportedViews();
string? UiaCore.IMultipleViewProvider.GetViewName(int viewId) => GetMultiViewProviderViewName(viewId);
void UiaCore.IMultipleViewProvider.SetCurrentView(int viewId) => SetMultiViewProviderCurrentView(viewId);
BOOL UiaCore.IRangeValueProvider.IsReadOnly => IsReadOnly ? BOOL.TRUE : BOOL.FALSE;
double UiaCore.IRangeValueProvider.LargeChange => LargeChange;
double UiaCore.IRangeValueProvider.Maximum => Maximum;
double UiaCore.IRangeValueProvider.Minimum => Minimum;
double UiaCore.IRangeValueProvider.SmallChange => SmallChange;
double UiaCore.IRangeValueProvider.Value => RangeValue;
void UiaCore.IRangeValueProvider.SetValue(double value) => SetValue(value);
object[]? UiaCore.ISelectionProvider.GetSelection() => GetSelection();
BOOL UiaCore.ISelectionProvider.CanSelectMultiple => CanSelectMultiple ? BOOL.TRUE : BOOL.FALSE;
BOOL UiaCore.ISelectionProvider.IsSelectionRequired => IsSelectionRequired ? BOOL.TRUE : BOOL.FALSE;
void UiaCore.ISelectionItemProvider.Select() => SelectItem();
void UiaCore.ISelectionItemProvider.AddToSelection() => AddToSelection();
void UiaCore.ISelectionItemProvider.RemoveFromSelection() => RemoveFromSelection();
BOOL UiaCore.ISelectionItemProvider.IsSelected => IsItemSelected ? BOOL.TRUE : BOOL.FALSE;
UiaCore.IRawElementProviderSimple? UiaCore.ISelectionItemProvider.SelectionContainer => ItemSelectionContainer;
/// <summary>
/// Raises the UIA Notification event.
/// The event is available starting with Windows 10, version 1709.
/// </summary>
/// <param name="notificationKind">The type of notification</param>
/// <param name="notificationProcessing">Indicates how to process notifications</param>
/// <param name="notificationText">Notification text</param>
/// <returns>
/// True if operation succeeds.
/// False if the underlying windows infrastructure is not available or the operation had failed.
/// Use Marshal.GetLastWin32Error for details.
/// </returns>
public bool RaiseAutomationNotification(AutomationNotificationKind notificationKind, AutomationNotificationProcessing notificationProcessing, string notificationText)
{
if (!notificationEventAvailable)
{
return false;
}
try
{
// The activityId can be any string. It cannot be null. It is not used currently.
HRESULT result = UiaCore.UiaRaiseNotificationEvent(
this,
notificationKind,
notificationProcessing,
notificationText,
string.Empty);
return result == HRESULT.S_OK;
}
catch (EntryPointNotFoundException)
{
// The UIA Notification event is not available, so don't attempt to raise it again.
notificationEventAvailable = false;
return false;
}
}
/// <summary>
/// Raises the LiveRegionChanged UIA event.
/// This method must be overridden in derived classes that support the UIA live region feature.
/// </summary>
/// <returns>True if operation succeeds, False otherwise.</returns>
public virtual bool RaiseLiveRegionChanged()
{
throw new NotSupportedException(SR.AccessibleObjectLiveRegionNotSupported);
}
internal virtual bool RaiseAutomationEvent(UiaCore.UIA eventId)
{
if (UiaCore.UiaClientsAreListening().IsTrue())
{
HRESULT result = UiaCore.UiaRaiseAutomationEvent(this, eventId);
return result == HRESULT.S_OK;
}
return false;
}
internal virtual bool RaiseAutomationPropertyChangedEvent(UiaCore.UIA propertyId, object oldValue, object newValue)
{
if (UiaCore.UiaClientsAreListening().IsTrue())
{
HRESULT result = UiaCore.UiaRaiseAutomationPropertyChangedEvent(this, propertyId, oldValue, newValue);
return result == HRESULT.S_OK;
}
return false;
}
internal virtual bool InternalRaiseAutomationNotification(AutomationNotificationKind notificationKind, AutomationNotificationProcessing notificationProcessing, string notificationText)
{
if (UiaCore.UiaClientsAreListening().IsTrue())
{
return RaiseAutomationNotification(notificationKind, notificationProcessing, notificationText);
}
return notificationEventAvailable;
}
internal bool RaiseStructureChangedEvent(UiaCore.StructureChangeType structureChangeType, int[] runtimeId)
{
if (UiaCore.UiaClientsAreListening().IsTrue())
{
HRESULT result = UiaCore.UiaRaiseStructureChangedEvent(this, structureChangeType, runtimeId, runtimeId is null ? 0 : runtimeId.Length);
return result == HRESULT.S_OK;
}
return false;
}
void UiaCore.IScrollItemProvider.ScrollIntoView() => ScrollIntoView();
internal virtual void ScrollIntoView()
{
Debug.Fail($"{nameof(ScrollIntoView)}() is not overriden");
}
}
}
| 38.512744 | 205 | 0.580284 | [
"MIT"
] | JeremyKuhne/winforms | src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs | 77,066 | C# |
namespace nHydrate.Generator.Forms
{
partial class SQLForm
{
/// <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(SQLForm));
this.panel1 = new System.Windows.Forms.Panel();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdOK = new System.Windows.Forms.Button();
this.txtSQL = new System.Windows.Forms.RichTextBox();
this.panel2 = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.lblLine100 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.cmdCancel);
this.panel1.Controls.Add(this.cmdOK);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 446);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(645, 36);
this.panel1.TabIndex = 0;
//
// cmdCancel
//
this.cmdCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cmdCancel.Location = new System.Drawing.Point(561, 8);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.Size = new System.Drawing.Size(75, 23);
this.cmdCancel.TabIndex = 2;
this.cmdCancel.Text = "Cancel";
this.cmdCancel.UseVisualStyleBackColor = true;
this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
//
// cmdOK
//
this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOK.Location = new System.Drawing.Point(481, 8);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(75, 23);
this.cmdOK.TabIndex = 1;
this.cmdOK.Text = "OK";
this.cmdOK.UseVisualStyleBackColor = true;
this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
//
// txtSQL
//
this.txtSQL.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtSQL.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtSQL.Location = new System.Drawing.Point(8, 71);
this.txtSQL.MaxLength = 2000000;
this.txtSQL.Name = "txtSQL";
this.txtSQL.Size = new System.Drawing.Size(628, 369);
this.txtSQL.TabIndex = 0;
this.txtSQL.Text = "";
//
// panel2
//
this.panel2.BackColor = System.Drawing.SystemColors.Window;
this.panel2.Controls.Add(this.lblLine100);
this.panel2.Controls.Add(this.label1);
this.panel2.Controls.Add(this.pictureBox1);
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(645, 65);
this.panel2.TabIndex = 71;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(91, 18);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(219, 13);
this.label1.TabIndex = 68;
this.label1.Text = "Enter the SQL for the selected object";
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(8, 8);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(48, 48);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 5;
this.pictureBox1.TabStop = false;
//
// lblLine100
//
this.lblLine100.BackColor = System.Drawing.Color.DarkGray;
this.lblLine100.Dock = System.Windows.Forms.DockStyle.Bottom;
this.lblLine100.Location = new System.Drawing.Point(0, 63);
this.lblLine100.Name = "lblLine100";
this.lblLine100.Size = new System.Drawing.Size(645, 2);
this.lblLine100.TabIndex = 70;
//
// SQLForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cmdCancel;
this.ClientSize = new System.Drawing.Size(645, 482);
this.Controls.Add(this.panel2);
this.Controls.Add(this.txtSQL);
this.Controls.Add(this.panel1);
this.MaximizeBox = false;
this.MinimumSize = new System.Drawing.Size(657, 363);
this.Name = "SQLForm";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "SQL";
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button cmdCancel;
private System.Windows.Forms.Button cmdOK;
private System.Windows.Forms.RichTextBox txtSQL;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label lblLine100;
}
} | 40.807229 | 157 | 0.687186 | [
"MIT"
] | giannik/nHydrate | Source/nHydrate.Generator/Forms/SQLForm.Designer.cs | 6,774 | 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 System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace IdentityDemo.IdentityService.Device
{
[Authorize]
[SecurityHeaders]
public class DeviceController : Controller
{
private readonly IDeviceFlowInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IResourceStore _resourceStore;
private readonly IEventService _events;
private readonly ILogger<DeviceController> _logger;
public DeviceController(
IDeviceFlowInteractionService interaction,
IClientStore clientStore,
IResourceStore resourceStore,
IEventService eventService,
ILogger<DeviceController> logger)
{
_interaction = interaction;
_clientStore = clientStore;
_resourceStore = resourceStore;
_events = eventService;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> Index([FromQuery(Name = "user_code")] string userCode)
{
if (string.IsNullOrWhiteSpace(userCode)) return View("UserCodeCapture");
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return View("Error");
vm.ConfirmUserCode = true;
return View("UserCodeConfirmation", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserCodeCapture(string userCode)
{
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return View("Error");
return View("UserCodeConfirmation", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Callback(DeviceAuthorizationInputModel model)
{
if (model == null) throw new ArgumentNullException(nameof(model));
var result = await ProcessConsent(model);
if (result.HasValidationError) return View("Error");
return View("Success");
}
private async Task<ProcessConsentResult> ProcessConsent(DeviceAuthorizationInputModel model)
{
var result = new ProcessConsentResult();
var request = await _interaction.GetAuthorizationContextAsync(model.UserCode);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested));
}
// user clicked 'yes' - validate the data
else if (model.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.HandleRequestAsync(model.UserCode, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.ClientId = request.ClientId;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.UserCode, model);
}
return result;
}
private async Task<DeviceAuthorizationViewModel> BuildViewModelAsync(string userCode, DeviceAuthorizationInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(userCode);
if (request != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
{
return CreateConsentViewModel(userCode, model, client, resources);
}
else
{
_logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y));
}
}
else
{
_logger.LogError("Invalid client id: {0}", request.ClientId);
}
}
return null;
}
private DeviceAuthorizationViewModel CreateConsentViewModel(string userCode, DeviceAuthorizationInputModel model, Client client, Resources resources)
{
var vm = new DeviceAuthorizationViewModel
{
UserCode = userCode,
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ClientName = client.ClientName ?? client.ClientId,
ClientUrl = client.ClientUri,
ClientLogoUrl = client.LogoUri,
AllowRememberConsent = client.AllowRememberConsent
};
vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new[]
{
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
} | 39.370213 | 198 | 0.583766 | [
"MIT"
] | daxnet/identity-demo | services/IdentityDemo.IdentityService/Controllers/Device/DeviceController.cs | 9,252 | C# |
using System;
using System.Globalization;
using System.Security.Claims;
using System.Security.Principal;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Extensions making it easier to get the user name/user id claims off of an identity
/// </summary>
public static class IdentityExtensions
{
/// <summary>
/// Return the user name using the UserNameClaimType
/// </summary>
/// <param name="identity"></param>
/// <returns></returns>
public static string GetUserName(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
return ci.FindFirstValue(ClaimsIdentity.DefaultNameClaimType);
}
return null;
}
/// <summary>
/// Return the user id using the UserIdClaimType
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="identity"></param>
/// <returns></returns>
public static T GetUserId<T>(this IIdentity identity) where T : IConvertible
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
var id = ci.FindFirstValue(ClaimTypes.NameIdentifier);
if (id != null)
{
return (T)Convert.ChangeType(id, typeof(T), CultureInfo.InvariantCulture);
}
}
return default(T);
}
/// <summary>
/// Return the user id using the UserIdClaimType
/// </summary>
/// <param name="identity"></param>
/// <returns></returns>
public static string GetUserId(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
return ci.FindFirstValue(ClaimTypes.NameIdentifier);
}
return null;
}
/// <summary>
/// Return the claim value for the first claim with the specified type if it exists, null otherwise
/// </summary>
/// <param name="identity"></param>
/// <param name="claimType"></param>
/// <returns></returns>
public static string FindFirstValue(this ClaimsIdentity identity, string claimType)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var claim = identity.FindFirst(claimType);
return claim != null ? claim.Value : null;
}
}
} | 33.703297 | 112 | 0.501467 | [
"MIT"
] | Sinoprise/ASP.NET-Identity | src/Microsoft.AspNet.Identity.Core/Extensions/IdentityExtensions.cs | 3,069 | C# |
using System;
using System.Numerics;
namespace VoxelPizza.Client
{
public class Transform
{
private Vector3 _position;
private Quaternion _rotation = Quaternion.Identity;
private Vector3 _scale = Vector3.One;
public Vector3 Position { get => _position; set { _position = value; TransformChanged?.Invoke(this); } }
public Quaternion Rotation { get => _rotation; set { _rotation = value; TransformChanged?.Invoke(this); } }
public Vector3 Scale { get => _scale; set { _scale = value; TransformChanged?.Invoke(this); } }
public event Action<Transform>? TransformChanged;
public Vector3 Forward => Vector3.Transform(-Vector3.UnitZ, _rotation);
public void Set(Vector3 position, Quaternion rotation, Vector3 scale)
{
_position = position;
_rotation = rotation;
_scale = scale;
TransformChanged?.Invoke(this);
}
public Matrix4x4 GetTransformMatrix()
{
return Matrix4x4.CreateScale(_scale)
* Matrix4x4.CreateFromQuaternion(_rotation)
* Matrix4x4.CreateTranslation(Position);
}
}
}
| 33.25 | 115 | 0.634085 | [
"MIT"
] | TechnologicalPizza/VoxelPizza | VoxelPizza.Client/Transform.cs | 1,199 | C# |
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using AutoMapper;
using EasyCaching.Core;
using Adnc.Maint.Application.Dtos;
using Adnc.Infr.Common.Extensions;
using Adnc.Infr.Common.Helper;
using Adnc.Maint.Core.CoreServices;
using Adnc.Maint.Core.Entities;
using Adnc.Core.Shared.IRepositories;
using Adnc.Application.Shared.Services;
using Adnc.Application.Shared;
namespace Adnc.Maint.Application.Services
{
public class DictAppService : AppService, IDictAppService
{
private readonly IMapper _mapper;
private readonly IEfRepository<SysDict> _dictRepository;
private readonly IMaintManagerService _maintManagerService;
private readonly IHybridCachingProvider _cache;
public DictAppService(IMapper mapper
, IEfRepository<SysDict> dictRepository
, IMaintManagerService maintManagerService
, IHybridProviderFactory hybridProviderFactory)
{
_mapper = mapper;
_dictRepository = dictRepository;
_maintManagerService = maintManagerService;
_cache = hybridProviderFactory.GetHybridCachingProvider(EasyCachingConsts.HybridCaching);
}
public async Task Delete(long Id)
{
//await _dictRepository.UpdateRangeAsync(d => (d.ID == Id) || (d.Pid == Id), d => new SysDict { IsDeleted = true });
await _dictRepository.DeleteRangeAsync(d => (d.ID == Id) || (d.Pid == Id));
}
public async Task<List<DictDto>> GetList(DictSearchDto searchDto)
{
var result = new List<DictDto>();
Expression<Func<DictDto, bool>> whereCondition = x => true;
if (searchDto.Name.IsNotNullOrWhiteSpace())
{
whereCondition = whereCondition.And(x => x.Name.Contains(searchDto.Name));
}
var dicts = (await this.GetAllFromCache()).Where(whereCondition.Compile()).OrderBy(d => d.Num).ToList();
if (dicts.Any())
{
result = dicts.Where(d => d.Pid == 0).OrderBy(d => d.Num).ToList();
foreach (var item in result)
{
var subDict = dicts.Where(d => d.Pid == item.ID).OrderBy(d => d.Num).Select(d => $"{d.Num}:{d.Name}");
item.Detail = string.Join(";", subDict);
}
}
return result;
}
public async Task Save(DictSaveInputDto saveDto)
{
//add
if (saveDto.ID == 0)
{
//long Id = new Snowflake(1, 1).NextId();
long Id = IdGenerater.GetNextId();
var subDicts = GetSubDicts(Id, saveDto.DictValues);
await _dictRepository.InsertRangeAsync(subDicts.Append(new SysDict { ID = Id, Pid = 0, Name = saveDto.DictName, Tips = saveDto.Tips,Num="0" }));
}
//update
else
{
var dict = new SysDict { Name = saveDto.DictName, Tips = saveDto.Tips, ID = saveDto.ID, Pid = 0 };
var subDicts = GetSubDicts(saveDto.ID, saveDto.DictValues);
await _maintManagerService.UpdateDicts(dict, subDicts);
}
}
public async Task<DictDto> Get(long id)
{
var dictDto = (await this.GetAllFromCache()).Where(x => x.ID == id).FirstOrDefault();
if (dictDto == null)
{
var errorModel = new ErrorModel(HttpStatusCode.NotFound, "没有找到");
throw new BusinessException(errorModel);
}
dictDto.Children = (await this.GetAllFromCache()).Where(x => x.Pid == dictDto.ID).ToList();
return dictDto;
}
//public async Task<DictDto> GetInculdeSubs(long id)
//{
// return (await this.GetAllFromCache()).Where(x => x.ID == id || x.Pid == id).OrderBy(x => x.ID).ThenBy(x => x.Num).FirstOrDefault();
//}
private async Task<List<DictDto>> GetAllFromCache()
{
var cahceValue = await _cache.GetAsync(EasyCachingConsts.DictListCacheKey, async () =>
{
var allDicts = await _dictRepository.GetAll().ToListAsync();
return _mapper.Map<List<DictDto>>(allDicts);
}, TimeSpan.FromSeconds(EasyCachingConsts.OneYear));
return cahceValue.Value;
}
private List<SysDict> GetSubDicts(long pid, string dictValues)
{
List<SysDict> subDicts = new List<SysDict>();
if (!string.IsNullOrWhiteSpace(dictValues))
{
//var snowflake = new Snowflake(1, 1);
var values = dictValues.Split(";", StringSplitOptions.RemoveEmptyEntries);
subDicts = values.Select((s,Index) => new SysDict
{
//ID = snowflake.NextId()
ID = IdGenerater.GetNextId()
,
Pid = pid
,
Name = s.Split(":", StringSplitOptions.RemoveEmptyEntries)[1]
,
Num = s.Split(":", StringSplitOptions.RemoveEmptyEntries)[0]
}).ToList();
}
return subDicts;
}
}
}
| 38.390071 | 160 | 0.569555 | [
"MIT"
] | dotNetTreasury/Adnc | src/ServerApi/Portal/Adnc.Maint/Adnc.Maint.Application/Services/Dict/DictAppService.cs | 5,423 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.NewtonsoftJson;
using GraphQL.Validation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SimpleInjector;
namespace CoreSharp.GraphQL.AspNetCore
{
public class GraphQLMiddleware<TSchema> : IMiddleware
where TSchema : CqrsSchema
{
private const string JsonContentType = "application/json";
private const string GraphQLContentType = "application/graphql";
private const string FormUrlEncodedContentType = "application/x-www-form-urlencoded";
private readonly Container _container;
private readonly ILogger<GraphQLMiddleware<TSchema>> _logger;
private readonly TSchema _schema;
private readonly IComplexityConfigurationFactory _complexityConfigurationFactory;
private readonly IUserContextBuilder _userContextBuilder;
public GraphQLMiddleware(
Container container,
ILogger<GraphQLMiddleware<TSchema>> logger,
TSchema schema, IComplexityConfigurationFactory complexityConfigurationFactory,
IUserContextBuilder userContextBuilder)
{
_container = container;
_logger = logger;
_schema = schema;
_complexityConfigurationFactory = complexityConfigurationFactory;
_userContextBuilder = userContextBuilder;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (context.WebSockets.IsWebSocketRequest)
{
await next(context);
return;
}
// Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/
var httpRequest = context.Request;
var gqlRequest = new GraphQLRequest();
var documentWriter = new DocumentWriter(_schema.GetJsonSerializerSettings());
if (HttpMethods.IsGet(httpRequest.Method) || (HttpMethods.IsPost(httpRequest.Method) && httpRequest.Query.ContainsKey(GraphQLRequest.QueryKey)))
{
ExtractGraphQLRequestFromQueryString(httpRequest.Query, gqlRequest);
}
else if (HttpMethods.IsPost(httpRequest.Method))
{
if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader))
{
await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: value '{httpRequest.ContentType}' could not be parsed.");
return;
}
switch (mediaTypeHeader.MediaType)
{
case JsonContentType:
gqlRequest = Deserialize<GraphQLRequest>(httpRequest.Body);
break;
case GraphQLContentType:
gqlRequest.Query = await ReadAsStringAsync(httpRequest.Body);
break;
case FormUrlEncodedContentType:
var formCollection = await httpRequest.ReadFormAsync();
ExtractGraphQLRequestFromPostBody(formCollection, gqlRequest);
break;
default:
await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: non-supported media type. Must be of '{JsonContentType}', '{GraphQLContentType}', or '{FormUrlEncodedContentType}'. See: http://graphql.org/learn/serving-over-http/.");
return;
}
}
IEnumerable<IValidationRule> validationRules;
try
{
validationRules = _container.GetAllInstances<IValidationRule>();
}
catch (Exception ex)
{
_logger.LogError(ex.Message, ex);
validationRules = new IValidationRule[0];
}
var executer = new DocumentExecuter();
var result = await executer.ExecuteAsync(x =>
{
x.Schema = _schema;
x.OperationName = gqlRequest.OperationName;
x.Query = gqlRequest.Query;
x.Inputs = gqlRequest.GetInputs();
x.UserContext = _userContextBuilder.BuildContext();
x.ValidationRules = validationRules.Concat(DocumentValidator.CoreRules);
x.CancellationToken = context.RequestAborted;
x.ComplexityConfiguration = _complexityConfigurationFactory.GetComplexityConfiguration();
});
if (result.Errors?.Any(x => x.Code == "auth-required") == true && context.Response.Headers.ContainsKey("Token-Expired"))
{
await WriteUnauthorizedResponseAsync(context, documentWriter, result);
}
else
{
await WriteResponseAsync(context, documentWriter, result);
}
}
private Task WriteBadRequestResponseAsync(HttpContext context, IDocumentWriter writer, string errorMessage)
{
var result = new ExecutionResult()
{
Errors = new ExecutionErrors()
{
new ExecutionError(errorMessage)
}
};
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return writer.WriteAsync(context.Response.Body, result);
}
private static Task WriteUnauthorizedResponseAsync(HttpContext context, IDocumentWriter writer, ExecutionResult result)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return writer.WriteAsync(context.Response.Body, result);
}
private static Task WriteResponseAsync(HttpContext context, IDocumentWriter writer, ExecutionResult result)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.OK;
return writer.WriteAsync(context.Response.Body, result);
}
private static T Deserialize<T>(Stream s)
{
using (var reader = new StreamReader(s))
using (var jsonReader = new JsonTextReader(reader))
{
return new JsonSerializer().Deserialize<T>(jsonReader);
}
}
private static async Task<string> ReadAsStringAsync(Stream s)
{
using (var reader = new StreamReader(s))
{
return await reader.ReadToEndAsync();
}
}
private static void ExtractGraphQLRequestFromQueryString(IQueryCollection qs, GraphQLRequest gqlRequest)
{
gqlRequest.Query = qs.TryGetValue(GraphQLRequest.QueryKey, out var queryValues) ? queryValues[0] : null;
gqlRequest.Variables = qs.TryGetValue(GraphQLRequest.VariablesKey, out var variablesValues) ? JObject.Parse(variablesValues[0]) : null;
gqlRequest.OperationName = qs.TryGetValue(GraphQLRequest.OperationNameKey, out var operationNameValues) ? operationNameValues[0] : null;
}
private static void ExtractGraphQLRequestFromPostBody(IFormCollection fc, GraphQLRequest gqlRequest)
{
gqlRequest.Query = fc.TryGetValue(GraphQLRequest.QueryKey, out var queryValues) ? queryValues[0] : null;
gqlRequest.Variables = fc.TryGetValue(GraphQLRequest.VariablesKey, out var variablesValue) ? JObject.Parse(variablesValue[0]) : null;
gqlRequest.OperationName = fc.TryGetValue(GraphQLRequest.OperationNameKey, out var operationNameValues) ? operationNameValues[0] : null;
}
}
// ReSharper disable once UnusedType.Global
public static class GraphQLMiddlewareExtensions
{
public static IApplicationBuilder UseGraphQL<TSchema>(this IApplicationBuilder builder)
where TSchema : CqrsSchema
{
return builder.UseMiddleware<GraphQLMiddleware<TSchema>>();
}
}
}
| 42.611111 | 285 | 0.630556 | [
"MIT"
] | cime/CoreSharp | CoreSharp.GraphQL.AspNetCore/GraphQLMiddleware.cs | 8,437 | C# |
[assembly: Xamarin.Forms.Dependency(typeof(Barbershop.iOS.Implementations.Localize))]
namespace Barbershop.iOS.Implementations
{
using System.Globalization;
using System.Threading;
using Foundation;
using Helpers;
using Interfaces;
public class Localize : ILocalize
{
public CultureInfo GetCurrentCultureInfo()
{
var netLanguage = "en";
if (NSLocale.PreferredLanguages.Length > 0)
{
var pref = NSLocale.PreferredLanguages[0];
netLanguage = iOSToDotnetLanguage(pref);
}
// this gets called a lot - try/catch can be expensive so consider caching or something
System.Globalization.CultureInfo ci = null;
try
{
ci = new System.Globalization.CultureInfo(netLanguage);
}
catch (CultureNotFoundException e1)
{
// iOS locale not valid .NET culture (eg. "en-ES" : English in Spain)
// fallback to first characters, in this case "en"
try
{
var fallback = ToDotnetFallbackLanguage(new PlatformCulture(netLanguage));
ci = new System.Globalization.CultureInfo(fallback);
}
catch (CultureNotFoundException e2)
{
// iOS language not valid .NET culture, falling back to English
ci = new System.Globalization.CultureInfo("en");
}
}
return ci;
}
public void SetLocale(CultureInfo ci)
{
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
string iOSToDotnetLanguage(string iOSLanguage)
{
var netLanguage = iOSLanguage;
//certain languages need to be converted to CultureInfo equivalent
switch (iOSLanguage)
{
case "ms-MY": // "Malaysian (Malaysia)" not supported .NET culture
case "ms-SG": // "Malaysian (Singapore)" not supported .NET culture
netLanguage = "ms"; // closest supported
break;
case "gsw-CH": // "Schwiizertüütsch (Swiss German)" not supported .NET culture
netLanguage = "de-CH"; // closest supported
break;
// add more application-specific cases here (if required)
// ONLY use cultures that have been tested and known to work
}
return netLanguage;
}
string ToDotnetFallbackLanguage(PlatformCulture platCulture)
{
var netLanguage = platCulture.LanguageCode; // use the first part of the identifier (two chars, usually);
switch (platCulture.LanguageCode)
{
case "pt":
netLanguage = "pt-PT"; // fallback to Portuguese (Portugal)
break;
case "gsw":
netLanguage = "de-CH"; // equivalent to German (Switzerland) for this app
break;
// add more application-specific cases here (if required)
// ONLY use cultures that have been tested and known to work
}
return netLanguage;
}
}
} | 38.573034 | 117 | 0.540344 | [
"Apache-2.0"
] | jodaga1992/Barbershop | Barbershop/Barbershop.iOS/Implementations/Localize.cs | 3,437 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using FirebirdSql.Data.FirebirdClient;
namespace OMeta.Firebird
{
public class FirebirdColumns : Columns
{
public FirebirdColumns()
{
}
internal DataColumn f_TypeName = null;
internal DataColumn f_TypeNameComplete = null;
override internal void LoadForTable()
{
try
{
FbConnection cn = new FirebirdSql.Data.FirebirdClient.FbConnection(this._dbRoot.ConnectionString);
cn.Open();
DataTable metaData = cn.GetSchema("Columns", new string[] { null, null, this.Table.Name });
DataColumn c;
if (!metaData.Columns.Contains("IS_AUTO_KEY")) { c = metaData.Columns.Add("IS_AUTO_KEY", typeof(Boolean)); c.DefaultValue = false; }
if (!metaData.Columns.Contains("AUTO_KEY_SEED")) { c = metaData.Columns.Add("AUTO_KEY_SEED"); c.DefaultValue = 0; }
if (!metaData.Columns.Contains("AUTO_KEY_INCREMENT")) { c = metaData.Columns.Add("AUTO_KEY_INCREMENT"); c.DefaultValue = 0; }
if (!metaData.Columns.Contains("AUTO_KEY_SEQUENCE")) { c = metaData.Columns.Add("AUTO_KEY_SEQUENCE"); c.DefaultValue = string.Empty; }
PopulateArray(metaData);
LoadExtraData(cn, this.Table.Name, "T");
cn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
override internal void LoadForView()
{
try
{
FbConnection cn = new FirebirdSql.Data.FirebirdClient.FbConnection(this._dbRoot.ConnectionString);
cn.Open();
DataTable metaData = cn.GetSchema("Columns", new string[] {null, null, this.View.Name});
PopulateArray(metaData);
LoadExtraData(cn, this.View.Name, "V");
cn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
private void LoadExtraData(FbConnection cn, string name, string type)
{
try
{
int dialect = 1;
object o = null;
short scale = 0;
try
{
FbConnectionStringBuilder cnString = new FbConnectionStringBuilder(cn.ConnectionString);
dialect = cnString.Dialect;
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
// AutoKey Data
Dictionary<string, object[]> autoKeyFields = new Dictionary<string, object[]>();
DataTable triggers = cn.GetSchema("Triggers", new string[] {null, null, name});
foreach (DataRow row in triggers.Rows)
{
int isSystemTrigger = Convert.ToInt32(row["IS_SYSTEM_TRIGGER"]);
int isInactive = Convert.ToInt32(row["IS_INACTIVE"]);
int triggerType = Convert.ToInt32(row["TRIGGER_TYPE"]);
if ((isSystemTrigger == 0) && (isInactive == 0) && (triggerType == 1))
{
string source = row["SOURCE"].ToString();
int end = 0;
do
{
string field = null, generatorName = string.Empty;
int tmp, increment = 1, seed = 0;
end = source.IndexOf("gen_id(", end, StringComparison.CurrentCultureIgnoreCase);
if (end >= 0)
{
string s = source.Substring(0, end);
int start = s.LastIndexOf(".");
if (start >= 0 && start < end)
{
field = s.Substring(start).Trim(' ', '.', '=').ToUpper();
}
int end2 = source.IndexOf(")", end);
string s2 = source.Substring(0, end2);
int start2 = s2.LastIndexOf(",");
if (start2 >= 0 && start2 < end2)
{
if (int.TryParse(s2.Substring(start2 + 1).Trim(' ', ','), out tmp))
increment = tmp;
s2 = s2.Substring(0, start2);
generatorName = s2.Substring(end + 7).Trim();
}
if (field != null)
{
autoKeyFields[field] = new object[] { increment, seed, generatorName };
}
end += 7;
}
} while (end != -1);
}
}
string select = "select r.rdb$field_name, f.rdb$field_scale AS SCALE, f.rdb$computed_source AS IsComputed, f.rdb$field_type as FTYPE, f.rdb$field_sub_type AS SUBTYPE, f.rdb$dimensions AS DIM from rdb$relation_fields r, rdb$types t, rdb$fields f where r.rdb$relation_name='" + name + "' and f.rdb$field_name=r.rdb$field_source and t.rdb$field_name='RDB$FIELD_TYPE' and f.rdb$field_type=t.rdb$type order by r.rdb$field_position;";
// Column Data
FbDataAdapter adapter = new FbDataAdapter(select, cn);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
// Dimension Data
string dimSelect = "select r.rdb$field_name AS Name , d.rdb$dimension as DIM, d.rdb$lower_bound as L, d.rdb$upper_bound as U from rdb$fields f, rdb$field_dimensions d, rdb$relation_fields r where r.rdb$relation_name='" + name + "' and f.rdb$field_name = d.rdb$field_name and f.rdb$field_name=r.rdb$field_source order by d.rdb$dimension;";
FbDataAdapter dimAdapter = new FbDataAdapter(dimSelect, cn);
DataTable dimTable = new DataTable();
dimAdapter.Fill(dimTable);
if(this._array.Count > 0)
{
Column col = this._array[0] as Column;
f_TypeName = new DataColumn("TYPE_NAME", typeof(string));
col._row.Table.Columns.Add(f_TypeName);
f_TypeNameComplete = new DataColumn("TYPE_NAME_COMPLETE", typeof(string));
col._row.Table.Columns.Add(f_TypeNameComplete);
this.f_IsComputed = new DataColumn("IS_COMPUTED", typeof(bool));
col._row.Table.Columns.Add(f_IsComputed);
short ftype = 0;
short dim = 0;
DataRowCollection rows = dataTable.Rows;
int count = this._array.Count;
Column c = null;
for( int index = 0; index < count; index++)
{
c = (Column)this[index];
if (autoKeyFields.ContainsKey(c.Name.ToUpper()))
{
c._row["IS_AUTO_KEY"] = true;
c._row["AUTO_KEY_INCREMENT"] = autoKeyFields[c.Name][0];
c._row["AUTO_KEY_SEED"] = autoKeyFields[c.Name][1];
c._row["AUTO_KEY_SEQUENCE"] = autoKeyFields[c.Name][2];
}
if(!c._row.IsNull("DOMAIN_NAME"))
{
// Special Hack, if there is a domain
c._row["TYPE_NAME"] = c._row["DOMAIN_NAME"] as string;
c._row["TYPE_NAME_COMPLETE"] = c._row["DOMAIN_NAME"] as string;
o = rows[index]["IsComputed"];
if(o != DBNull.Value)
{
c._row["IS_COMPUTED"] = true;
}
scale = (short)rows[index]["SCALE"];
if(scale < 0)
{
c._row["NUMERIC_SCALE"] = Math.Abs(scale);
}
continue;
}
try
{
string bigint = c._row["COLUMN_DATA_TYPE"] as string;
if(bigint.ToUpper() == "BIGINT")
{
c._row["TYPE_NAME"] = "BIGINT";
c._row["TYPE_NAME_COMPLETE"] = "BIGINT";
continue;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
// public const int blr_text = 14;
// public const int blr_text2 = 15;
// public const int blr_short = 7;
// public const int blr_long = 8;
// public const int blr_quad = 9;
// public const int blr_int64 = 16;
// public const int blr_float = 10;
// public const int blr_double = 27;
// public const int blr_d_float = 11;
// public const int blr_timestamp = 35;
// public const int blr_varying = 37;
// public const int blr_varying2 = 38;
// public const int blr_blob = 261;
// public const int blr_cstring = 40;
// public const int blr_cstring2 = 41;
// public const int blr_blob_id = 45;
// public const int blr_sql_date = 12;
// public const int blr_sql_time = 13;
// Step 1: DataTypeName
ftype = (short)rows[index]["FTYPE"];
switch(ftype)
{
case 7:
c._row["TYPE_NAME"] = "SMALLINT";
break;
case 8:
c._row["TYPE_NAME"] = "INTEGER";
break;
case 9:
c._row["TYPE_NAME"] = "QUAD";
break;
case 10:
c._row["TYPE_NAME"] = "FLOAT";
break;
case 11:
c._row["TYPE_NAME"] = "DOUBLE PRECISION";
break;
case 12:
c._row["TYPE_NAME"] = "DATE";
break;
case 13:
c._row["TYPE_NAME"] = "TIME";
break;
case 14:
c._row["TYPE_NAME"] = "CHAR";
break;
case 16:
c._row["TYPE_NAME"] = "NUMERIC";
break;
case 27:
c._row["TYPE_NAME"] = "DOUBLE PRECISION";
break;
case 35:
if(dialect > 2)
{
c._row["TYPE_NAME"] = "TIMESTAMP";
}
else
{
c._row["TYPE_NAME"] = "DATE";
}
break;
case 37:
c._row["TYPE_NAME"] = "VARCHAR";
break;
case 40:
c._row["TYPE_NAME"] = "CSTRING";
break;
case 261:
short subtype = (short)rows[index]["SUBTYPE"];
switch(subtype)
{
case 0:
c._row["TYPE_NAME"] = "BLOB(BINARY)";
break;
case 1:
c._row["TYPE_NAME"] = "BLOB(TEXT)";
break;
default:
c._row["TYPE_NAME"] = "BLOB(UNKNOWN)";
break;
}
break;
}
scale = (short)rows[index]["SCALE"];
if(scale < 0)
{
c._row["TYPE_NAME"] = "NUMERIC";
c._row["NUMERIC_SCALE"] = Math.Abs(scale);
}
o = rows[index]["IsComputed"];
if(o != DBNull.Value)
{
c._row["IS_COMPUTED"] = true;
}
// Step 2: DataTypeNameComplete
string s = c._row["TYPE_NAME"] as string;
switch(s)
{
case "VARCHAR":
case "CHAR":
c._row["TYPE_NAME_COMPLETE"] = s + "(" + c.CharacterMaxLength + ")";
break;
case "NUMERIC":
switch((int)c._row["COLUMN_SIZE"])
{
case 2:
c._row["TYPE_NAME_COMPLETE"] = s + "(4, " + c.NumericScale.ToString() + ")";
break;
case 4:
c._row["TYPE_NAME_COMPLETE"] = s + "(9, " + c.NumericScale.ToString() + ")";
break;
case 8:
c._row["TYPE_NAME_COMPLETE"] = s + "(15, " + c.NumericScale.ToString() + ")";
break;
default:
c._row["TYPE_NAME_COMPLETE"] = "NUMERIC(18,0)";
break;
}
break;
case "BLOB(TEXT)":
case "BLOB(BINARY)":
c._row["TYPE_NAME_COMPLETE"] = "BLOB";
break;
default:
c._row["TYPE_NAME_COMPLETE"] = s;
break;
}
s = c._row["TYPE_NAME_COMPLETE"] as string;
dim = 0;
o = rows[index]["DIM"];
if(o != DBNull.Value)
{
dim = (short)o;
}
if(dim > 0)
{
dimTable.DefaultView.RowFilter = "Name = '" + c.Name + "'";
dimTable.DefaultView.Sort = "DIM";
string a = "[";
bool bFirst = true;
foreach(DataRowView vrow in dimTable.DefaultView)
{
DataRow row = vrow.Row;
if(!bFirst) a += ",";
a += row["L"].ToString() + ":" + row["U"].ToString();
bFirst = false;
}
a += "]";
c._row["TYPE_NAME_COMPLETE"] = s + a;
c._row["TYPE_NAME"] = c._row["TYPE_NAME"] + ":A";
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
}
}
| 30.038647 | 444 | 0.505227 | [
"MIT"
] | kiler398/OMeta | src/OpenMetaData/Firebird/Columns.cs | 12,436 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace ContactManager
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} | 26.217391 | 100 | 0.568823 | [
"Apache-2.0"
] | Microsoft-Web/HOL-ASPNETWebAPI | Source/Ex01-ReadOnlyWebAPI/End/ContactManager/App_Start/RouteConfig.cs | 605 | C# |
using BlazorFluentUI.Themes.Default;
using BlazorFluentUI.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace BlazorFluentUI
{
public class ThemeProvider
{
private ITheme _theme;
public ICollection<Theme> ThemeComponents { get; set; }
public ITheme Theme { get => _theme; }
public event EventHandler<ThemeChangedArgs>? ThemeChanged;
public ThemeProvider()
{
ThemeComponents = new HashSet<Theme>();
_theme = CreateTheme();
ThemeChanged?.Invoke(this, new ThemeChangedArgs(_theme));
}
public void UpdateTheme(IPalette palette)
{
_theme = CreateTheme(palette);
foreach (Theme? comp in ThemeComponents)
{
comp.UpdateTheme();
}
ThemeChanged?.Invoke(this, new ThemeChangedArgs(_theme));
}
/// <summary>
/// Override that allows modification of the SemanticColors instead of completely allowing the default palette->semanticColor conversions.
/// Necessary for some dark mode conversions... i.e. MenuBackground is white in light mode but has drop shadow. Dark mode menu can't be black (reverse) because there is no drop shadow.
/// </summary>
/// <param name="palette"></param>
/// <param name="semanticColorOverrides"></param>
/// <param name="semanticTextColorOverrides"></param>
public void UpdateTheme(IPalette palette, ISemanticColors semanticColorOverrides, ISemanticTextColors semanticTextColorOverrides)
{
_theme = CreateTheme(palette);
//foreach (var prop in typeof(ISemanticColors).GetProperties())
//{
// if (prop.GetValue(semanticColorOverrides) != null)
// {
// prop.SetValue(_theme.SemanticColors, prop.GetValue(semanticColorOverrides));
// }
//}
semanticColorOverrides.CopyTo(_theme.SemanticColors!);
//foreach (var prop in typeof(ISemanticTextColors).GetProperties())
//{
// if (prop.GetValue(semanticTextColorOverrides) != null)
// {
// prop.SetValue(_theme.SemanticTextColors, prop.GetValue(semanticTextColorOverrides));
// }
//}
semanticTextColorOverrides.CopyTo(_theme.SemanticTextColors!);
foreach (Theme? comp in ThemeComponents)
{
comp.UpdateTheme();
}
ThemeChanged?.Invoke(this, new ThemeChangedArgs(_theme));
}
private static ITheme CreateTheme(IPalette? palette = null)
{
Theme? theme = new();
theme.Palette = palette ?? new DefaultPalette();
theme.SemanticColors = MakeSemanticColorsFromPalette(theme.Palette, false);
theme.SemanticTextColors = MakeSemanticTextColorsFromPalette(theme.Palette, false);
theme.FontStyle = new FontStyle() { FontSize = new DefaultFontSize(), FontWeight = new DefaultFontWeight(), IconFontSize = new DefaultIconFontSize() };
theme.CommonStyle = new DefaultCommonStyle();
theme.ZIndex = new DefaultZIndex();
theme.Effects = new DefaultEffects();
theme.Depths = new DefaultDepths();
theme.Animation = new DefaultAnimation();
return theme;
}
private static ISemanticColors MakeSemanticColorsFromPalette(IPalette palette, bool isInverted)
{
return new SemanticColors()
{
BodyBackground = palette.White,
BodyBackgroundHovered = palette.NeutralLighter,
BodyBackgroundChecked = palette.NeutralLight,
BodyStandoutBackground = palette.NeutralLighterAlt,
BodyFrameBackground = palette.White,
BodyFrameDivider = palette.NeutralLight,
BodyDivider = palette.NeutralLight,
DisabledBorder = palette.NeutralTertiaryAlt,
FocusBorder = palette.NeutralSecondary,
VariantBorder = palette.NeutralLight,
VariantBorderHovered = palette.NeutralTertiary,
DefaultStateBackground = palette.NeutralLighterAlt,
// BUTTONS
ButtonBackground = palette.White,
ButtonBackgroundChecked = palette.NeutralTertiaryAlt,
ButtonBackgroundHovered = palette.NeutralLighter,
ButtonBackgroundCheckedHovered = palette.NeutralLight,
ButtonBackgroundPressed = palette.NeutralLight,
ButtonBackgroundDisabled = palette.NeutralLighter,
ButtonBorder = palette.NeutralSecondaryAlt,
ButtonBorderDisabled = palette.NeutralLighter,
PrimaryButtonBackground = palette.ThemePrimary,
PrimaryButtonBackgroundHovered = palette.ThemeDarkAlt,
PrimaryButtonBackgroundPressed = palette.ThemeDark,
PrimaryButtonBackgroundDisabled = palette.NeutralLighter,
PrimaryButtonBorder = "transparent",
AccentButtonBackground = palette.Accent,
// INPUTS
InputBorder = palette.NeutralSecondary,
InputBorderHovered = palette.NeutralPrimary,
InputBackground = palette.White,
InputBackgroundChecked = palette.ThemePrimary,
InputBackgroundCheckedHovered = palette.ThemeDark,
InputPlaceholderBackgroundChecked = palette.ThemeLighter,
InputForegroundChecked = palette.White,
InputIcon = palette.ThemePrimary,
InputIconHovered = palette.ThemeDark,
InputIconDisabled = palette.NeutralTertiary,
InputFocusBorderAlt = palette.ThemePrimary,
SmallInputBorder = palette.NeutralSecondary,
DisabledBackground = palette.NeutralLighter,
// LISTS
ListBackground = palette.White,
ListItemBackgroundHovered = palette.NeutralLighter,
ListItemBackgroundChecked = palette.NeutralLight,
ListItemBackgroundCheckedHovered = palette.NeutralQuaternaryAlt,
ListHeaderBackgroundHovered = palette.NeutralLighter,
ListHeaderBackgroundPressed = palette.NeutralLight,
// MENUS
MenuBackground = palette.White,
MenuDivider = palette.NeutralTertiaryAlt,
MenuIcon = palette.ThemePrimary,
MenuHeader = palette.ThemePrimary,
MenuItemBackgroundHovered = palette.NeutralLighter,
MenuItemBackgroundPressed = palette.NeutralLight,
ErrorBackground = !isInverted ? "rgba(245, 135, 145, .2)" : "rgba(232, 17, 35, .5)",
BlockingBackground = !isInverted ? "rgba(250, 65, 0, .2)" : "rgba(234, 67, 0, .5)",
WarningBackground = !isInverted ? "rgba(255, 200, 10, .2)" : "rgba(255, 251, 0, .6)",
WarningHighlight = !isInverted ? "#ffb900" : "#fff100",
SuccessBackground = !isInverted ? "rgba(95, 210, 85, .2)" : "rgba(186, 216, 10, .4)",
};
}
private static ISemanticTextColors MakeSemanticTextColorsFromPalette(IPalette palette, bool isInverted)
{
return new SemanticTextColors()
{
BodyText = palette.NeutralPrimary,
BodyTextChecked = palette.Black,
BodySubtext = palette.NeutralSecondary,
DisabledBodyText = palette.NeutralTertiary,
DisabledBodySubtext = palette.NeutralTertiaryAlt,
// LINKS
ActionLink = palette.NeutralPrimary,
ActionLinkHovered = palette.NeutralDark,
Link = palette.ThemePrimary,
LinkHovered = palette.ThemeDarker,
// BUTTONS
ButtonText = palette.NeutralPrimary,
ButtonTextHovered = palette.NeutralDark,
ButtonTextChecked = palette.NeutralDark,
ButtonTextCheckedHovered = palette.Black,
ButtonTextPressed = palette.NeutralDark,
ButtonTextDisabled = palette.NeutralTertiary,
PrimaryButtonText = palette.White,
PrimaryButtonTextHovered = palette.White,
PrimaryButtonTextPressed = palette.White,
PrimaryButtonTextDisabled = palette.NeutralQuaternary,
AccentButtonText = palette.White,
// INPUTS
InputText = palette.NeutralPrimary,
InputTextHovered = palette.NeutralDark,
InputPlaceholderText = palette.NeutralSecondary,
DisabledText = palette.NeutralTertiary,
DisabledSubtext = palette.NeutralQuaternary,
// LISTS
ListText = palette.NeutralPrimary,
// MENUS
MenuItemText = palette.NeutralPrimary,
MenuItemTextHovered = palette.NeutralDark,
ErrorText = !isInverted ? palette.RedDark : "#ff5f5f",
WarningText = !isInverted ? "#333333" : "#ffffff",
SuccessText = !isInverted ? "#107C10" : "#92c353"
};
}
}
}
| 44.788732 | 193 | 0.600105 | [
"MIT"
] | BlazorFluentUI/BlazorFluentUI | src/BlazorFluentUI.CoreComponents/Theme/ThemeProvider.cs | 9,542 | C# |
using System;
namespace CSharpGL
{
internal class OpenGL32Library : IDisposable
{
public static readonly OpenGL32Library Instance = new OpenGL32Library();
private OpenGL32Library()
{
libPtr = Win32.LoadLibrary(Win32.opengl32);
}
/// <summary>
/// glLibrary = Win32.LoadLibrary(OpenGL32);
/// </summary>
internal readonly IntPtr libPtr;
public override string ToString()
{
return string.Format("OpenGL32 Library Address: {0}", libPtr);
}
#region IDisposable
/// <summary>
///
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
///
/// </summary>
~OpenGL32Library()
{
this.Dispose(false);
}
private bool disposedValue;
private void Dispose(bool disposing)
{
if (this.disposedValue == false)
{
if (disposing)
{
// Dispose managed resources.
}
// Dispose unmanaged resources.
Win32.FreeLibrary(libPtr);
}
this.disposedValue = true;
}
#endregion IDisposable
}
} | 21.777778 | 80 | 0.485423 | [
"MIT"
] | AugusZhan/CSharpGL | CSharpGL.Windows/Win32API/Win32.OpenGL32Library.cs | 1,374 | C# |
/*
* Copyright (c) 2006, Clutch, Inc.
* Original Author: Jeff Cesnik
* 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.
* - Neither the name of the openmetaverse.org 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 System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
namespace OpenMetaverse
{
/// <summary>
/// Base UDP server
/// </summary>
public abstract class OpenSimUDPBase
{
private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// This method is called when an incoming packet is received
/// </summary>
/// <param name="buffer">Incoming packet buffer</param>
public abstract void PacketReceived(UDPPacketBuffer buffer);
/// <summary>UDP port to bind to in server mode</summary>
protected int m_udpPort;
/// <summary>Local IP address to bind to in server mode</summary>
protected IPAddress m_localBindAddress;
/// <summary>UDP socket, used in either client or server mode</summary>
private Socket m_udpSocket;
public static Object m_udpBuffersPoolLock = new Object();
public static UDPPacketBuffer[] m_udpBuffersPool = new UDPPacketBuffer[1000];
public static int m_udpBuffersPoolPtr = -1;
/// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary>
public bool IsRunningInbound { get; private set; }
/// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary>
/// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks>
public bool IsRunningOutbound { get; private set; }
/// <summary>
/// Number of UDP receives.
/// </summary>
public int UdpReceives { get; private set; }
/// <summary>
/// Number of UDP sends
/// </summary>
public int UdpSends { get; private set; }
/// <summary>
/// Number of receives over which to establish a receive time average.
/// </summary>
private readonly static int s_receiveTimeSamples = 500;
/// <summary>
/// Current number of samples taken to establish a receive time average.
/// </summary>
private int m_currentReceiveTimeSamples;
/// <summary>
/// Cumulative receive time for the sample so far.
/// </summary>
private int m_receiveTicksInCurrentSamplePeriod;
/// <summary>
/// The average time taken for each require receive in the last sample.
/// </summary>
public float AverageReceiveTicksForLastSamplePeriod { get; private set; }
public int Port
{
get { return m_udpPort; }
}
#region PacketDropDebugging
/// <summary>
/// For debugging purposes only... random number generator for dropping
/// outbound packets.
/// </summary>
private Random m_dropRandomGenerator = new Random();
/// <summary>
/// For debugging purposes only... parameters for a simplified
/// model of packet loss with bursts, overall drop rate should
/// be roughly 1 - m_dropLengthProbability / (m_dropProbabiliy + m_dropLengthProbability)
/// which is about 1% for parameters 0.0015 and 0.15
/// </summary>
private double m_dropProbability = 0.0030;
private double m_dropLengthProbability = 0.15;
private bool m_dropState = false;
/// <summary>
/// For debugging purposes only... parameters to control the time
/// duration over which packet loss bursts can occur, if no packets
/// have been sent for m_dropResetTicks milliseconds, then reset the
/// state of the packet dropper to its default.
/// </summary>
private int m_dropLastTick = 0;
private int m_dropResetTicks = 500;
/// <summary>
/// Debugging code used to simulate dropped packets with bursts
/// </summary>
private bool DropOutgoingPacket()
{
double rnum = m_dropRandomGenerator.NextDouble();
// if the connection has been idle for awhile (more than m_dropResetTicks) then
// reset the state to the default state, don't continue a burst
int curtick = Util.EnvironmentTickCount();
if (Util.EnvironmentTickCountSubtract(curtick, m_dropLastTick) > m_dropResetTicks)
m_dropState = false;
m_dropLastTick = curtick;
// if we are dropping packets, then the probability of dropping
// this packet is the probability that we stay in the burst
if (m_dropState)
{
m_dropState = (rnum < (1.0 - m_dropLengthProbability)) ? true : false;
}
else
{
m_dropState = (rnum < m_dropProbability) ? true : false;
}
return m_dropState;
}
#endregion PacketDropDebugging
/// <summary>
/// Default constructor
/// </summary>
/// <param name="bindAddress">Local IP address to bind the server to</param>
/// <param name="port">Port to listening for incoming UDP packets on</param>
/// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param>
public OpenSimUDPBase(IPAddress bindAddress, int port)
{
m_localBindAddress = bindAddress;
m_udpPort = port;
// for debugging purposes only, initializes the random number generator
// used for simulating packet loss
// m_dropRandomGenerator = new Random();
}
~OpenSimUDPBase()
{
if(m_udpSocket !=null)
try { m_udpSocket.Close(); } catch { }
}
public UDPPacketBuffer GetNewUDPBuffer(IPEndPoint remoteEndpoint)
{
lock (m_udpBuffersPoolLock)
{
if (m_udpBuffersPoolPtr >= 0)
{
UDPPacketBuffer buf = m_udpBuffersPool[m_udpBuffersPoolPtr];
m_udpBuffersPool[m_udpBuffersPoolPtr] = null;
m_udpBuffersPoolPtr--;
buf.RemoteEndPoint = remoteEndpoint;
return buf;
}
}
return new UDPPacketBuffer(remoteEndpoint);
}
public void FreeUDPBuffer(UDPPacketBuffer buf)
{
lock (m_udpBuffersPoolLock)
{
if (m_udpBuffersPoolPtr < 999)
{
buf.RemoteEndPoint = null;
buf.DataLength = 0;
m_udpBuffersPoolPtr++;
m_udpBuffersPool[m_udpBuffersPoolPtr] = buf;
}
}
}
/// <summary>
/// Start inbound UDP packet handling.
/// </summary>
/// <param name="recvBufferSize">The size of the receive buffer for
/// the UDP socket. This value is passed up to the operating system
/// and used in the system networking stack. Use zero to leave this
/// value as the default</param>
/// <param name="asyncPacketHandling">Set this to true to start
/// receiving more packets while current packet handler callbacks are
/// still running. Setting this to false will complete each packet
/// callback before the next packet is processed</param>
/// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag
/// on the socket to get newer versions of Windows to behave in a sane
/// manner (not throwing an exception when the remote side resets the
/// connection). This call is ignored on Mono where the flag is not
/// necessary</remarks>
public virtual void StartInbound(int recvBufferSize)
{
if (!IsRunningInbound)
{
m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop");
const int SIO_UDP_CONNRESET = -1744830452;
IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
m_udpSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
try
{
if (m_udpSocket.Ttl < 128)
{
m_udpSocket.Ttl = 128;
}
}
catch (SocketException)
{
m_log.Debug("[UDPBASE]: Failed to increase default TTL");
}
try
{
// This udp socket flag is not supported under mono,
// so we'll catch the exception and continue
// Try does not protect some mono versions on mac
if(Util.IsWindows())
{
m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
}
else
{
m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
}
}
catch
{
m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
}
// On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment
// we never want two regions to listen on the same port as they cannot demultiplex each other's messages,
// leading to a confusing bug.
// By default, Windows does not allow two sockets to bind to the same port.
//
// Unfortunately, this also causes a crashed sim to leave the socket in a state
// where it appears to be in use but is really just hung from the old process
// crashing rather than closing it. While this protects agains misconfiguration,
// allowing crashed sims to be started up again right away, rather than having to
// wait 2 minutes for the socket to clear is more valuable. Commented 12/13/2016
// m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
if (recvBufferSize != 0)
m_udpSocket.ReceiveBufferSize = recvBufferSize;
m_udpSocket.Bind(ipep);
if (m_udpPort == 0)
m_udpPort = ((IPEndPoint)m_udpSocket.LocalEndPoint).Port;
IsRunningInbound = true;
// kick off an async receive. The Start() method will return, the
// actual receives will occur asynchronously and will be caught in
// AsyncEndRecieve().
AsyncBeginReceive();
}
}
/// <summary>
/// Start outbound UDP packet handling.
/// </summary>
public virtual void StartOutbound()
{
m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
IsRunningOutbound = true;
}
public virtual void StopInbound()
{
if (IsRunningInbound)
{
m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
IsRunningInbound = false;
m_udpSocket.Close();
}
}
public virtual void StopOutbound()
{
m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
IsRunningOutbound = false;
}
private void AsyncBeginReceive()
{
if (!IsRunningInbound)
return;
UDPPacketBuffer buf = GetNewUDPBuffer(new IPEndPoint(IPAddress.Any, 0)); // we need a fresh one here, for now at least
try
{
// kick off an async read
m_udpSocket.BeginReceiveFrom(
buf.Data,
0,
buf.Data.Length,
SocketFlags.None,
ref buf.RemoteEndPoint,
AsyncEndReceive,
buf);
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.ConnectionReset)
{
m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
bool salvaged = false;
while (!salvaged)
{
try
{
m_udpSocket.BeginReceiveFrom(
buf.Data,
0,
buf.Data.Length,
SocketFlags.None,
ref buf.RemoteEndPoint,
AsyncEndReceive,
buf);
salvaged = true;
}
catch (SocketException) { }
catch (ObjectDisposedException) { return; }
}
m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
}
}
catch (Exception e)
{
m_log.Error(
string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
}
}
private void AsyncEndReceive(IAsyncResult iar)
{
// Asynchronous receive operations will complete here through the call
// to AsyncBeginReceive
if (IsRunningInbound)
{
UdpReceives++;
try
{
// get the buffer that was created in AsyncBeginReceive
// this is the received data
UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
int startTick = Util.EnvironmentTickCount();
// get the length of data actually read from the socket, store it with the
// buffer
buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
// call the abstract method PacketReceived(), passing the buffer that
// has just been filled from the socket read.
PacketReceived(buffer);
// If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler)
// then a particular stat may be inaccurate due to a race condition. We won't worry about this
// since this should be rare and won't cause a runtime problem.
if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
{
AverageReceiveTicksForLastSamplePeriod
= (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
m_receiveTicksInCurrentSamplePeriod = 0;
m_currentReceiveTimeSamples = 0;
}
else
{
m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
m_currentReceiveTimeSamples++;
}
}
catch (SocketException se)
{
m_log.Error(
string.Format(
"[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ",
UdpReceives, se.ErrorCode),
se);
}
catch (Exception e)
{
m_log.Error(
string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
}
finally
{
AsyncBeginReceive();
}
}
}
/* not in use
public void AsyncBeginSend(UDPPacketBuffer buf)
{
// if (IsRunningOutbound)
// {
// This is strictly for debugging purposes to simulate dropped
// packets when testing throttles & retransmission code
// if (DropOutgoingPacket())
// return;
try
{
m_udpSocket.BeginSendTo(
buf.Data,
0,
buf.DataLength,
SocketFlags.None,
buf.RemoteEndPoint,
AsyncEndSend,
buf);
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
// }
}
void AsyncEndSend(IAsyncResult result)
{
try
{
// UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
m_udpSocket.EndSendTo(result);
UdpSends++;
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
}
*/
public void SyncSend(UDPPacketBuffer buf)
{
if(buf.RemoteEndPoint == null)
return; // already expired
try
{
m_udpSocket.SendTo(
buf.Data,
0,
buf.DataLength,
SocketFlags.None,
buf.RemoteEndPoint
);
UdpSends++;
}
catch (SocketException e)
{
m_log.WarnFormat("[UDPBASE]: sync send SocketException {0} {1}", buf.RemoteEndPoint, e.Message);
}
catch (ObjectDisposedException) { }
}
}
}
| 38.835938 | 136 | 0.539529 | [
"BSD-3-Clause"
] | ausesims/opensim | OpenSim/Region/ClientStack/Linden/UDP/OpenSimUDPBase.cs | 19,884 | C# |
#region Using directives
using System.Data;
using Moq;
using NBi.NUnit.Builder;
using NBi.NUnit.Query;
using NBi.Xml.Constraints;
using NBi.Xml.Items;
using NBi.Xml.Systems;
using NUnit.Framework;
using NBi.Core.ResultSet.Resolver;
using NBi.Core.ResultSet;
using NBi.Core.Query;
using NBi.Core.Injection;
using NBi.Extensibility.Query;
#endregion
namespace NBi.Testing.Unit.NUnit.Builder
{
[TestFixture]
public class QueryFasterThanBuilderTest
{
#region SetUp & TearDown
//Called only at instance creation
[TestFixtureSetUp]
public void SetupMethods()
{
}
//Called only at instance destruction
[TestFixtureTearDown]
public void TearDownMethods()
{
}
//Called before each test
[SetUp]
public void SetupTest()
{
}
//Called after each test
[TearDown]
public void TearDownTest()
{
}
#endregion
[Test]
public void GetConstraint_Build_CorrectConstraint()
{
var sutXmlStubFactory = new Mock<ExecutionXml>();
var itemXmlStubFactory = new Mock<QueryableXml>();
itemXmlStubFactory.Setup(i => i.GetQuery()).Returns("query");
sutXmlStubFactory.Setup(s => s.Item).Returns(itemXmlStubFactory.Object);
var sutXml = sutXmlStubFactory.Object;
sutXml.Item = itemXmlStubFactory.Object;
var ctrXml = new FasterThanXml();
var builder = new ExecutionFasterThanBuilder();
builder.Setup(sutXml, ctrXml, null, null, new ServiceLocator());
builder.Build();
var ctr = builder.GetConstraint();
Assert.That(ctr, Is.InstanceOf<FasterThanConstraint>());
}
[Test]
public void GetSystemUnderTest_Build_CorrectIResultSetService()
{
var sutXmlStubFactory = new Mock<ExecutionXml>();
var itemXmlStubFactory = new Mock<QueryableXml>();
itemXmlStubFactory.Setup(i => i.GetQuery()).Returns("query");
sutXmlStubFactory.Setup(s => s.Item).Returns(itemXmlStubFactory.Object);
var sutXml = sutXmlStubFactory.Object;
sutXml.Item = itemXmlStubFactory.Object;
var ctrXml = new FasterThanXml();
var builder = new ExecutionFasterThanBuilder();
builder.Setup(sutXml, ctrXml, null, null, new ServiceLocator());
builder.Build();
var sut = builder.GetSystemUnderTest();
Assert.That(sut, Is.InstanceOf<IQuery>());
}
}
}
| 29.857143 | 85 | 0.596246 | [
"Apache-2.0"
] | CoolsJoris/NBi | NBi.Testing/Unit/NUnit/Builder/QueryFasterThanBuilderTest.cs | 2,719 | C# |
namespace mCubed.LineupGenerator.Services
{
public enum NewsStatus
{
Breaking = 1,
Recent,
None
}
}
| 11.9 | 43 | 0.647059 | [
"MIT"
] | nickp10/mcubed-lineup-insight-generator | mCubed.LineupGenerator/Services/NewsStatus.cs | 121 | C# |
using Gov.Lclb.Cllb.Interfaces.Models;
using Gov.Lclb.Cllb.Public.Models;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Xunit;
namespace Gov.Lclb.Cllb.Public.Test
{
public class EstablishmentTests : ApiIntegrationTestBaseWithLogin
{
public EstablishmentTests(CustomWebApplicationFactory<Startup> factory)
: base(factory)
{ }
const string service = "establishments";
//[Fact]
public async System.Threading.Tasks.Task TestNoAccessToAnonymousUser()
{
string id = "SomeRandomId";
// first confirm we are not logged in
await GetCurrentUserIsUnauthorized();
// try a random GET, should return unauthorized
var request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
var response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string _discard = await response.Content.ReadAsStringAsync();
}
//[Fact]
public async System.Threading.Tasks.Task TestCRUD()
{
string initialName = "InitialName";
string changedName = "ChangedName";
var loginUser = randomNewUserName("NewLoginUser", 6);
var strId = await LoginAndRegisterAsNewUser(loginUser);
// C - Create
var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);
ViewModels.Establishment viewmodel_adoxio_establishment = new ViewModels.Establishment()
{
Name = initialName
};
string jsonString = JsonConvert.SerializeObject(viewmodel_adoxio_establishment);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
ViewModels.Establishment responseViewModel = JsonConvert.DeserializeObject<ViewModels.Establishment>(jsonString);
// name should match.
Assert.Equal(initialName, responseViewModel.Name);
Guid id = new Guid(responseViewModel.id);
// R - Read
request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
jsonString = await response.Content.ReadAsStringAsync();
responseViewModel = JsonConvert.DeserializeObject<ViewModels.Establishment>(jsonString);
Assert.Equal(initialName, responseViewModel.Name);
// U - Update
ViewModels.Establishment patchModel = new ViewModels.Establishment()
{
Name = changedName
};
request = new HttpRequestMessage(HttpMethod.Put, "/api/" + service + "/" + id)
{
Content = new StringContent(JsonConvert.SerializeObject(patchModel), Encoding.UTF8, "application/json")
};
response = await _client.SendAsync(request);
jsonString = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
// verify that the update persisted.
request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
jsonString = await response.Content.ReadAsStringAsync();
responseViewModel = JsonConvert.DeserializeObject<ViewModels.Establishment>(jsonString);
Assert.Equal(changedName, responseViewModel.Name);
// D - Delete
request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// second delete should return a 404.
request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
await LogoutAndCleanupTestUser(strId);
}
}
}
| 39.467213 | 125 | 0.620768 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-public-app-test/EstablishmentTests.cs | 4,815 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Archichect.Rendering.TextWriting;
using Archichect.Transforming.PathFinding;
namespace Archichect.Tests {
[TestClass, ExcludeFromCodeCoverage]
public class TestFlatPathWriterWithPathMarker : AbstractWriterTest {
[TestInitialize]
public void TestInitialize() {
new GlobalContext().ResetAll();
}
private Dependency CreateDependency(WorkingGraph graph, Item from, Item to, string pathMarker, bool isStart, bool isEnd, bool isMatchedByCountMatch, bool isLoopBack) {
Dependency d = FromTo(graph, from, to);
d.MarkPathElement(pathMarker, 0, isStart: isStart, isEnd: isEnd, isMatchedByCountSymbol: isMatchedByCountMatch,
isLoopBack: isLoopBack);
return d;
}
[TestMethod]
public void TestSimpleFlatPathWriterForOnePath() {
var gc = new GlobalContext { IgnoreCase = true };
WorkingGraph graph = gc.CurrentGraph;
ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)");
var pathMarker = "P0";
Item a = graph.CreateItem(t3, "a:aa:aaa".Split(':'));
a.MarkPathElement(pathMarker, 0, isStart: false, isEnd: false, isMatchedByCountSymbol: false, isLoopBack: false);
Item b = graph.CreateItem(t3, "b:bb:bbb".Split(':'));
b.SetMarker(pathMarker, 1);
var d = CreateDependency(graph, a, b, pathMarker, true, true, false, false);
Dependency[] dependencies = { d };
using (var s = new MemoryStream()) {
var w = new FlatPathWriter();
w.RenderToStreamForUnitTests(gc, dependencies, s, "P*");
string result = Encoding.ASCII.GetString(s.ToArray());
Assert.AreEqual(@"-- P0
a:aa:aaa
b:bb:bbb $", result.Trim());
}
}
[TestMethod]
public void TestSimplePathSearchAndFlatPathWriterForOnePath() {
ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)");
var gc = new GlobalContext();
WorkingGraph graph = gc.CurrentGraph;
var a = graph.CreateItem(t3, "a:aa:aaa".Split(':'));
var b = graph.CreateItem(t3, "b:bb:bbb".Split(':'));
var dependencies = new[] {
FromTo(graph, a, b),
};
string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A"));
Assert.AreEqual(@"-- A0
T3:a:aa:aaa'A0
T3:b:bb:bbb'A $", result.Trim());
}
private static string FindPathsAndWriteFlat(GlobalContext gc, IEnumerable<Dependency> dependencies, string markerPrefix, string transformOptions) {
var pm = new OLDPathMarker();
pm.Configure(gc, "", false);
var transformedDependencies = new List<Dependency>();
pm.Transform(gc, dependencies, transformOptions, transformedDependencies, s => null);
string result;
using (var s = new MemoryStream()) {
var w = new FlatPathWriter();
w.RenderToStreamForUnitTests(gc, transformedDependencies, s, $"{markerPrefix}* -sm");
result = Encoding.ASCII.GetString(s.ToArray());
}
return result;
}
private static string CreateDefaultOptions(string markerPrefix, int maxPathLength = 5) {
return ($"{{ {OLDPathMarker.AddIndexedMarkerOption} {markerPrefix} " +
$"{OLDPathMarker.PathOptions.MaxPathLengthOption} {maxPathLength} " +
$"{OLDPathMarker.PathOptions.CountItemAnchorOption} a: " +
$"{OLDPathMarker.PathOptions.MultipleItemAnchorOption} ~c: }}").Replace(" ", Environment.NewLine);
}
[TestMethod]
public void TestSimpleFlatPathWriterForNoPath() {
ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)");
var gc = new GlobalContext();
WorkingGraph graph = gc.CurrentGraph;
var a = graph.CreateItem(t3, "a:aa:aaa".Split(':'));
var c = graph.CreateItem(t3, "c:cc:ccc".Split(':'));
var dependencies = new[] { FromTo(graph, a, c) };
string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A"));
Assert.AreEqual("", result.Trim());
}
[TestMethod]
public void TestSimpleFlatPathWriter() {
var gc = new GlobalContext();
IEnumerable<Dependency> dependencies = new OLDPathMarker().CreateSomeTestDependencies(gc.CurrentGraph);
string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A"));
Assert.AreEqual(@"-- A0
T3:a:aa:aaa'A0+A1+A2+A3
T3:b:bb:bbb'A $
T3:c:cc:ccc'A
T3:d:dd:ddd'A $
T3:e:ee:eee'A $
T3:f:ff:fff'A $
-- A1
T3:a:aa:aaa'A0+A1+A2+A3
T3:b:bb:bbb'A $
T3:c:cc:ccc'A
T3:d:dd:ddd'A $
<= T3:b:bb:bbb'A $
-- A2
T3:a:aa:aaa'A0+A1+A2+A3
T3:b:bb:bbb'A $
T3:g:gg:ggg'A $
-- A3
T3:a:aa:aaa'A0+A1+A2+A3
T3:h:hh:hhh'A $
T3:g:gg:ggg'A $", result.Trim());
}
[TestMethod]
public void TestLimitedFlatPathWriter() {
var gc = new GlobalContext();
IEnumerable<Dependency> dependencies = new OLDPathMarker().CreateSomeTestDependencies(gc.CurrentGraph);
string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A", 4));
Assert.AreEqual(@"-- A0
T3:a:aa:aaa'A0+A1+A2+A3
T3:b:bb:bbb'A $
T3:c:cc:ccc'A
T3:d:dd:ddd'A $
T3:e:ee:eee'A $
-- A1
T3:a:aa:aaa'A0+A1+A2+A3
T3:b:bb:bbb'A $
T3:c:cc:ccc'A
T3:d:dd:ddd'A $
<= T3:b:bb:bbb'A $
-- A2
T3:a:aa:aaa'A0+A1+A2+A3
T3:b:bb:bbb'A $
T3:g:gg:ggg'A $
-- A3
T3:a:aa:aaa'A0+A1+A2+A3
T3:h:hh:hhh'A $
T3:g:gg:ggg'A $", result.Trim());
}
[TestMethod]
public void TestSimpleFlatPathWriterForYPath() {
ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)");
var gc = new GlobalContext();
WorkingGraph graph = gc.CurrentGraph;
var a = graph.CreateItem(t3, "a:aa:aaa".Split(':'));
var b = graph.CreateItem(t3, "b:bb:bbb".Split(':'));
var c = graph.CreateItem(t3, "c:cc:ccc".Split(':'));
var d = graph.CreateItem(t3, "d:dd:ddd".Split(':'));
var dependencies = new[] {
FromTo(graph, a, b),
FromTo(graph, b, c),
FromTo(graph, b ,d),
};
string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A"));
Assert.AreEqual(@"-- A0
T3:a:aa:aaa'A0
T3:b:bb:bbb'A $
T3:d:dd:ddd'A $", result.Trim());
}
[TestMethod]
public void TestOldCountPaths() {
ItemType xy = ItemType.New("NL(Name:Layer)");
var gc = new GlobalContext();
WorkingGraph graph = gc.CurrentGraph;
Item a = graph.CreateItem(xy, "a", "1");
Item b = graph.CreateItem(xy, "b", "2");
Item c = graph.CreateItem(xy, "c", "2");
Item d = graph.CreateItem(xy, "d", "3");
Item e = graph.CreateItem(xy, "e", "4");
Item f = graph.CreateItem(xy, "f", "4");
Item g = graph.CreateItem(xy, "g", "5");
Dependency[] dependencies = {
FromTo(graph, a, b),
FromTo(graph, a, c),
FromTo(graph, b, d),
FromTo(graph, c, d),
FromTo(graph, d, e),
FromTo(graph, d, f),
FromTo(graph, e, g),
FromTo(graph, f, g)
};
string o = FindPathsAndWriteFlat(gc, dependencies, "A", "{ -im A -pi a -ci 2 -pi g }".Replace(" ", Environment.NewLine));
Console.WriteLine(o);
Assert.IsTrue(o.Contains("b:2 #"));
Assert.IsTrue(o.Contains("c:2 #"));
Assert.IsTrue(o.Contains("d:3'A=2"));
Assert.IsTrue(o.Contains("e:4'A=2"));
Assert.IsTrue(o.Contains("g:5'A=2 $"));
}
}
} | 34.598326 | 175 | 0.572258 | [
"Apache-2.0"
] | hmmueller/Archichect | src/Archichect.Tests/TestFlatPathWriterWithPathMarker.cs | 8,269 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Albion.Model.Buildings;
using Albion.Model.Data;
using Albion.Model.Items.Categories;
using Albion.Model.Items.Profits;
using Albion.Model.Items.Requirements;
using Albion.Model.Managers;
namespace Albion.Model.Items
{
public class CommonItem : BaseCostableEntity
{
public static readonly HashSet<ShopCategory> SimpleItems = new HashSet<ShopCategory>
{
Model.Items.Categories.ShopCategory.Accessories,
// Model.Items.Categories.ShopCategory.Consumables,
Model.Items.Categories.ShopCategory.Armor,
Model.Items.Categories.ShopCategory.Melee,
Model.Items.Categories.ShopCategory.Ranged,
Model.Items.Categories.ShopCategory.Magic
};
public static readonly HashSet<ShopSubCategory> BaseResourceItems = new HashSet<ShopSubCategory>
{
Model.Items.Categories.ShopSubCategory.Wood,
Model.Items.Categories.ShopSubCategory.Rock,
Model.Items.Categories.ShopSubCategory.Ore,
Model.Items.Categories.ShopSubCategory.Fiber,
Model.Items.Categories.ShopSubCategory.Hide,
};
public int QualityLevel { get; }
private readonly FastBuyRequirement _fastBuyRequirement;
private readonly LongBuyRequirement _longBuyRequirement;
private BaseRequirement _requirement;
public CommonItem(BaseResorcedRequirement[] craftingRequirements,
ItemMarket itemMarket,
CraftBuilding craftingBuilding,
int qualityLevel,
ITownManager buyTownManager,
ITownManager sellTownManager
)
{
QualityLevel = qualityLevel;
CraftingRequirements = craftingRequirements;
IsArtefacted = CraftingRequirements.SelectMany(x => x.Resources)
.Any(r => r.Item.ShopCategory == ShopCategory.Artefacts || r.Item.ShopCategory == ShopCategory.Token);
CraftingBuilding = craftingBuilding;
ItemMarket = itemMarket;
_longBuyRequirement = new LongBuyRequirement(buyTownManager);
_fastBuyRequirement = new FastBuyRequirement(buyTownManager);
LongSellProfit = new LongSellProfit(this, sellTownManager);
FastSellProfit = new FastSellProfit(this, sellTownManager);
BmFastSellProfit = new BmFastSellProfit(this);
BmLongSellProfit = new BmLongSellProfit(this);
CostCalcOptions.Instance.Changed += RequirementsOnUpdated;
CostCalcOptions.Instance.ProfitsChanged += ProfitsOnUpdated;
}
public FastSellProfit FastSellProfit { get; }
public BmFastSellProfit BmFastSellProfit { get; }
public BmLongSellProfit BmLongSellProfit { get; }
public SalvageProfit SalvageProfit { get; private set; }
public LongSellProfit LongSellProfit { get; }
public IEnumerable<object> Components => Profits.Cast<object>().Concat(Requirements);
private IEnumerable<BaseRequirement> FullRequirements
{
get
{
yield return _fastBuyRequirement;
yield return _longBuyRequirement;
foreach (var cr in CraftingRequirements) yield return cr;
}
}
public IEnumerable<BaseRequirement> Requirements
{
get
{
yield return _fastBuyRequirement;
yield return _longBuyRequirement;
if (IsCraftable)
foreach (var cr in CraftingRequirements) yield return cr;
}
}
public IEnumerable<BaseProfit> Profits
{
get
{
if (SalvageProfit != null) yield return SalvageProfit;
yield return BmFastSellProfit;
yield return BmLongSellProfit;
yield return FastSellProfit;
yield return LongSellProfit;
}
}
private IEnumerable<BaseRequirement> RequirementsAutoMin
{
get
{
if (!CostCalcOptions.Instance.IsCraftDisabled)
if (IsCraftable)
if (!(CostCalcOptions.Instance.IsDisableCraftResources && IsResource))
{
if (CostCalcOptions.Instance.IsDisableUpgrade)
foreach (var cr in CraftingRequirements.OfType<CraftingRequirement>()) yield return cr;
else
foreach (var cr in CraftingRequirements) yield return cr;
if (CostCalcOptions.Instance.IsItemsOnlyCraft && IsItem) yield break;
}
yield return _fastBuyRequirement;
if (!CostCalcOptions.Instance.IsLongBuyDisabled
|| CostCalcOptions.Instance.IsArtefactsLongBuyEnabled && ShopCategory == ShopCategory.Artefacts
|| CostCalcOptions.Instance.IsBaseResourcesLongBuyEnabled && IsBaseResourceItem && Enchant == 0
)
yield return _longBuyRequirement;
}
}
private IEnumerable<BaseProfit> ProfitsAutoMin
{
get
{
if (!CostCalcOptions.Instance.IsSalvageDisabled)
if (SalvageProfit != null)
yield return SalvageProfit;
if (!CostCalcOptions.Instance.IsBmDisabled)
{
yield return BmFastSellProfit;
if (!CostCalcOptions.Instance.IsLongSellDisabled)
yield return BmLongSellProfit;
}
yield return FastSellProfit;
if (!CostCalcOptions.Instance.IsLongSellDisabled)
yield return LongSellProfit;
}
}
public int MemId { get; set; }
public ItemMarket ItemMarket { get; }
#region For UI
public TreeProps TreeProps { get; } = new TreeProps {IsExpanded = false};
#endregion
public BaseRequirement Requirement
{
get => _requirement;
set
{
Cost = value.Cost;
if (_requirement != value)
{
_requirement = value;
RaisePropertyChanged();
}
RequirementUpdated?.Invoke();
}
}
public bool IsArtefacted { get; }
public void Init()
{
if (IsSalvageable &&
//!IsResource &&
CraftingRequirements.Length > 0 && CraftingRequirements[0].Resources.Length > 0)
SalvageProfit = new SalvageProfit(this);
foreach (var cr in Profits)
//cr.SetItem(this);
cr.Updated += ProfitsOnUpdated;
foreach (var cr in FullRequirements)
{
cr.SetItem(this);
cr.Updated += RequirementsOnUpdated;
}
RequirementsOnUpdated();
}
private void ProfitsOnUpdated()
{
var max = long.MinValue;
BaseProfit maxItem = null;
foreach (var item in Profits)
{
item.TreeProps.IsSelected = false;
//item.TreeProps.IsExpanded = false;
}
foreach (var item in ProfitsAutoMin)
{
if (max < item.Income)
{
max = item.Income;
maxItem = item;
}
}
if (maxItem != null)
{
maxItem.TreeProps.IsSelected = true;
//maxItem.TreeProps.IsExpanded = true;
}
}
private void RequirementsOnUpdated()
{
var min = long.MaxValue;
BaseRequirement minItem = null;
foreach (var item in Requirements)
{
item.TreeProps.IsSelected = false;
//item.TreeProps.IsExpanded = false;
}
foreach (var item in RequirementsAutoMin)
{
if (min > item.Cost && item.Cost > 0)
{
min = item.Cost;
minItem = item;
}
}
if (minItem != null)
minItem.TreeProps.IsSelected = true;
else
Cost = 0;
}
public event Action RequirementUpdated;
#region Profitt
private BaseProfit _profitt;
public BaseProfit Profitt
{
get => _profitt;
set
{
if (_profitt == value) return;
if (_profitt != null) _profitt.Updated -= ProfittOnUpdated;
_profitt = value;
if (_profitt != null) _profitt.Updated += ProfittOnUpdated;
RaisePropertyChanged();
ProfittOnUpdated();
}
}
private void ProfittOnUpdated()
{
ProfitUpdated?.Invoke();
}
public event Action ProfitUpdated;
#endregion
public CommonItem[] QualityLevels { get; set; }
public bool IsResource => ShopCategory == ShopCategory.Resources;
public bool IsBaseResourceItem => BaseResourceItems.Contains(ShopSubCategory);
public bool IsItem => SimpleItems.Contains(ShopCategory);
#region From Config
#if DEBUG
public object Debug { get; set; }
#endif
public string Id { get; set; }
public ShopCategory ShopCategory { get; set; }
public ShopSubCategory ShopSubCategory { get; set; }
public CraftBuilding CraftingBuilding { get; }
public int ItemPower { get; set; }
public int Tir { get; set; }
public int Enchant { get; set; }
public string Name { get; set; }
public string FullName => QualityLevel > 1 ? $"{Tir}.{Enchant}.{QualityLevel} {Name}" : $"{Tir}.{Enchant} {Name}";
public BaseResorcedRequirement[] CraftingRequirements { get; set; }
public double ItemValue { get; set; }
public bool IsSalvageable { get; set; }
public bool IsCraftable { get; set; }
public double ItemFame { get; set; }
public override string ToString()
{
return Id;
}
#endregion
}
} | 33.736842 | 123 | 0.540883 | [
"MIT"
] | masterdidoo/albion-helper | Albion.Model/Items/CommonItem.cs | 10,899 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
//
// Microsoft Cognitive Services (formerly Project Oxford) GitHub:
// https://github.com/Microsoft/Cognitive-SpeakerRecognition-Windows
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
namespace Microsoft.ProjectOxford.SpeakerRecognition.Contract.Identification
{
/// <summary>
/// An object encapsulating the location of an identification/enrollment request processed by the service
/// </summary>
public class OperationLocation
{
/// <summary>
/// The Url to query enrollment/identification operation status
/// </summary>
public string Url { get; set; }
}
} | 40.2 | 109 | 0.739303 | [
"MIT"
] | Bhaskers-Blu-Org2/Cognitive-SpeakerRecognition-Windows | ClientLibrary/Contract/Identification/OperationLocation.cs | 2,012 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V6301 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")]
public partial class UKCT_MT144039UK02PertinentInformation2Finding {
private IINPfITuuidmandatory idField;
private string classCodeField;
private string moodCodeField;
private static System.Xml.Serialization.XmlSerializer serializer;
public UKCT_MT144039UK02PertinentInformation2Finding() {
this.classCodeField = "OBS";
this.moodCodeField = "EVN";
}
public IINPfITuuidmandatory id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string classCode {
get {
return this.classCodeField;
}
set {
this.classCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string moodCode {
get {
return this.moodCodeField;
}
set {
this.moodCodeField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT144039UK02PertinentInformation2Finding));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current UKCT_MT144039UK02PertinentInformation2Finding object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an UKCT_MT144039UK02PertinentInformation2Finding object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output UKCT_MT144039UK02PertinentInformation2Finding object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out UKCT_MT144039UK02PertinentInformation2Finding obj, out System.Exception exception) {
exception = null;
obj = default(UKCT_MT144039UK02PertinentInformation2Finding);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out UKCT_MT144039UK02PertinentInformation2Finding obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static UKCT_MT144039UK02PertinentInformation2Finding Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((UKCT_MT144039UK02PertinentInformation2Finding)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current UKCT_MT144039UK02PertinentInformation2Finding object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an UKCT_MT144039UK02PertinentInformation2Finding object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output UKCT_MT144039UK02PertinentInformation2Finding object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out UKCT_MT144039UK02PertinentInformation2Finding obj, out System.Exception exception) {
exception = null;
obj = default(UKCT_MT144039UK02PertinentInformation2Finding);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out UKCT_MT144039UK02PertinentInformation2Finding obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static UKCT_MT144039UK02PertinentInformation2Finding LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this UKCT_MT144039UK02PertinentInformation2Finding object
/// </summary>
public virtual UKCT_MT144039UK02PertinentInformation2Finding Clone() {
return ((UKCT_MT144039UK02PertinentInformation2Finding)(this.MemberwiseClone()));
}
#endregion
}
}
| 44.764192 | 1,358 | 0.59643 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V6301/Generated/UKCT_MT144039UK02PertinentInformation2Finding.cs | 10,251 | C# |
public static class ListDirectoryRecursively
{
static void Main(string[] args)
{
string path = args[0];
ListRecursively(path);
}
/// <summary>
/// This function lists all files and subdirectories of a folder recursively.
/// </summary>
/// <param name="path">The path for the parent folder.</param>
private static void ListRecursively(string path)
{
try
{
// If the folder is not empty, check out its content.
if (Directory.GetFileSystemEntries(path).Length > 0)
{
// Lists all files and directories in a folder.
for (int i = 0; i < Directory.GetFileSystemEntries(path).Length; i++)
{
string fPath = Directory.GetFileSystemEntries(path)[i];
Console.WriteLine(fPath);
// If the currently selected element is a folder, perform the same steps on it.
if (Directory.Exists(fPath))
{
ListRecursively(fPath);
}
}
}
} catch (UnauthorizedAccessException)
{
Console.WriteLine("Cannot access directory");
}
}
}
| 30.238095 | 100 | 0.525197 | [
"MIT"
] | nordic16/code-snippets | C#/Files/ListFilesRecursively.cs | 1,272 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codeartifact-2018-09-22.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CodeArtifact.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeArtifact.Model.Internal.MarshallTransformations
{
/// <summary>
/// CopyPackageVersions Request Marshaller
/// </summary>
public class CopyPackageVersionsRequestMarshaller : IMarshaller<IRequest, CopyPackageVersionsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((CopyPackageVersionsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CopyPackageVersionsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeArtifact");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-09-22";
request.HttpMethod = "POST";
if (publicRequest.IsSetDestinationRepository())
request.Parameters.Add("destination-repository", StringUtils.FromString(publicRequest.DestinationRepository));
if (publicRequest.IsSetDomain())
request.Parameters.Add("domain", StringUtils.FromString(publicRequest.Domain));
if (publicRequest.IsSetDomainOwner())
request.Parameters.Add("domain-owner", StringUtils.FromString(publicRequest.DomainOwner));
if (publicRequest.IsSetFormat())
request.Parameters.Add("format", StringUtils.FromString(publicRequest.Format));
if (publicRequest.IsSetNamespace())
request.Parameters.Add("namespace", StringUtils.FromString(publicRequest.Namespace));
if (publicRequest.IsSetPackage())
request.Parameters.Add("package", StringUtils.FromString(publicRequest.Package));
if (publicRequest.IsSetSourceRepository())
request.Parameters.Add("source-repository", StringUtils.FromString(publicRequest.SourceRepository));
request.ResourcePath = "/v1/package/versions/copy";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAllowOverwrite())
{
context.Writer.WritePropertyName("allowOverwrite");
context.Writer.Write(publicRequest.AllowOverwrite);
}
if(publicRequest.IsSetIncludeFromUpstream())
{
context.Writer.WritePropertyName("includeFromUpstream");
context.Writer.Write(publicRequest.IncludeFromUpstream);
}
if(publicRequest.IsSetVersionRevisions())
{
context.Writer.WritePropertyName("versionRevisions");
context.Writer.WriteObjectStart();
foreach (var publicRequestVersionRevisionsKvp in publicRequest.VersionRevisions)
{
context.Writer.WritePropertyName(publicRequestVersionRevisionsKvp.Key);
var publicRequestVersionRevisionsValue = publicRequestVersionRevisionsKvp.Value;
context.Writer.Write(publicRequestVersionRevisionsValue);
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetVersions())
{
context.Writer.WritePropertyName("versions");
context.Writer.WriteArrayStart();
foreach(var publicRequestVersionsListValue in publicRequest.Versions)
{
context.Writer.Write(publicRequestVersionsListValue);
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
request.UseQueryString = true;
return request;
}
private static CopyPackageVersionsRequestMarshaller _instance = new CopyPackageVersionsRequestMarshaller();
internal static CopyPackageVersionsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CopyPackageVersionsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.5 | 153 | 0.613485 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeArtifact/Generated/Model/Internal/MarshallTransformations/CopyPackageVersionsRequestMarshaller.cs | 6,318 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.UnitTests;
using Xunit;
#nullable disable
namespace Microsoft.Build.Tasks.UnitTests
{
public sealed class TelemetryTaskTests
{
[Fact]
public void TelemetryTaskSendsEvents()
{
MockEngine engine = new MockEngine();
Telemetry telemetryTask = new Telemetry
{
BuildEngine = engine,
EventName = "My event name",
};
bool retVal = telemetryTask.Execute();
Assert.True(retVal);
Assert.Contains(telemetryTask.EventName, engine.Log);
}
[Fact]
public void TelemetryTaskSendsEventsWithProperties()
{
const string propertyName = "9B7DA92A89914E2CA1D88DCEB9DAAD72";
const string propertyValue = "68CB99868F2843B3B75230C1A0BFE358";
MockEngine engine = new MockEngine();
Telemetry telemetryTask = new Telemetry
{
BuildEngine = engine,
EventName = "My event name",
EventData = $"{propertyName}={propertyValue}",
};
bool retVal = telemetryTask.Execute();
Assert.True(retVal);
Assert.Contains(propertyName, engine.Log);
Assert.Contains(propertyValue, engine.Log);
}
[Fact]
public void TelemetryTaskInvalidEventData()
{
MockEngine engine = new MockEngine();
Telemetry telemetryTask = new Telemetry
{
BuildEngine = engine,
EventName = "My event name",
EventData = $"Property1=Value1;Property2",
};
bool retVal = telemetryTask.Execute();
Assert.False(retVal);
Assert.Contains($"The property \"Property2\" in the telemetry event data property list \"{telemetryTask.EventData}\" is malformed.", engine.Log);
}
/// <summary>
/// Verifies that when there are duplicate property names specified that the last one wins.
/// </summary>
[Fact]
public void TelemetryTaskDuplicateEventDataProperty()
{
MockEngine engine = new MockEngine();
Telemetry telemetryTask = new Telemetry
{
BuildEngine = engine,
EventName = "My event name",
EventData = $"Property1=EE2493A167D24F00996DE7C8E769EAE6;Property1=4ADE3D2622CA400B8B95A039DF540037",
};
bool retVal = telemetryTask.Execute();
Assert.True(retVal);
// Should not contain the first value
//
Assert.DoesNotContain("EE2493A167D24F00996DE7C8E769EAE6", engine.Log);
// Should contain the second value
//
Assert.Contains("4ADE3D2622CA400B8B95A039DF540037", engine.Log);
}
}
}
| 30.078431 | 157 | 0.576271 | [
"MIT"
] | AlexanderSemenyak/msbuild | src/Tasks.UnitTests/TelemetryTaskTests.cs | 3,070 | C# |
using System;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace dotnet21
{
public class Hello
{
[LambdaSerializer(typeof(JsonSerializer))]
public async Task<Object> Handler(Object request)
{
return new
{
statusCode = 200,
body = "Hello world!",
headers = new Dictionary<string, string> {
{"Content-Type", "text/plain"}
}
};
}
}
}
| 22.807692 | 58 | 0.536256 | [
"MIT"
] | FieryCod/holy-lambda | benchmarks/holy-lambda-vs-other-runtimes/csharp/Hello.cs | 593 | C# |
using System;
namespace _02._Multiplication_Table
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
for (int k = 1; k <= 10; k++)
{
Console.WriteLine($"{i} * {k} = {i * k}");
}
}
}
}
}
| 19 | 62 | 0.34349 | [
"MIT"
] | GeorgiGradev/SoftUni | 01. Programming Basics/07.1. Nested Loops - Lab/02. Multiplication Table/Program.cs | 363 | C# |
using Clypeus.Data.Model.Medicinals;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace Clypeus.Data.Model.Configurations.Medicinals
{
public class OrganismsConfiguration : IEntityTypeConfiguration<Organisms>
{
public void Configure(EntityTypeBuilder<Organisms> entity)
{
entity.ToTable("Organisms", "Medicinals");
entity.HasKey(e =>e.Id);
entity.Property(e => e.Code)
.IsRequired()
.HasMaxLength(25)
.IsUnicode(false);
entity.Property(e => e.Description)
.HasMaxLength(150)
.IsUnicode(false);
entity.Property(e => e.Species)
.HasMaxLength(125)
.IsUnicode(false);
entity.Property(e => e.Inserted).HasColumnType("datetime");
entity.Property(e => e.Updated).HasColumnType("datetime");
entity.HasOne(d => d.OrganismGenus)
.WithMany(p => p.Organisms)
.HasForeignKey(d => d.OrganismGenusId)
.HasConstraintName("FK_Organisms_ToOrganismTypes");
entity.HasOne(d => d.OrganismKingdom)
.WithMany(p => p.Organisms)
.HasForeignKey(d => d.OrganismKingdomId)
.HasConstraintName("FK_Organisms_ToOrganismKingdom");
entity.HasOne(d => d.OrganismPhylum)
.WithMany(p => p.Organisms)
.HasForeignKey(d => d.OrganismPhylumId)
.HasConstraintName("FK_Organisms_ToOrganismPhylum");
entity.HasOne(d => d.OrganismFamily)
.WithMany(p => p.Organisms)
.HasForeignKey(d => d.OrganismFamilyId)
.HasConstraintName("FK_Organisms_ToOrganismFamily");
entity.HasOne(d => d.OrganismClass)
.WithMany(p => p.Organisms)
.HasForeignKey(d => d.OrganismClassId)
.HasConstraintName("FK_Organisms_ToOrganismClass");
entity.HasOne(d => d.OrganismOrder)
.WithMany(p => p.Organisms)
.HasForeignKey(d => d.OrganismOrderId)
.HasConstraintName("FK_Organisms_ToOrganismOrder");
}
}
}
| 34 | 77 | 0.594723 | [
"MIT"
] | Clypeus/ClypeusInfectionManagementSystem | MAIN/Clypeus/Clypeus.Data.Model/Configurations/MedicinalConfigurations/OrganismsConfiguration.cs | 2,314 | C# |
namespace TwitchLib.Events.Services.LiveStreamMonitor
{
#region using directives
using System;
using System.Collections.Generic;
using Enums;
#endregion
/// <summary>Class representing event args for OnChannelMonitorStarted event.</summary>
public class OnStreamMonitorStartedArgs : EventArgs
{
/// <summary>Event property representing channel the service is currently monitoring.</summary>
public List<string> Channels;
/// <summary>Event property representing how channels IDs are represented.</summary>
public StreamIdentifierType IdentifierType;
/// <summary>Event property representing seconds between queries to Twitch Api.</summary>
public int CheckIntervalSeconds;
}
}
| 38.15 | 103 | 0.726081 | [
"MIT"
] | NoStudioDude/TwitchLib-1 | TwitchLib/Events/Services/LiveStreamMonitor/OnStreamMonitorStartedArgs.cs | 765 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using BuildXL.Cache.ContentStore.Hashing;
namespace BuildXL.Cache.ContentStore.Distributed
{
/// <summary>
/// A wrapper for content hashes and their respective size and locations.
/// </summary>
public class ContentHashWithSizeAndLocations : IEquatable<ContentHashWithSizeAndLocations>
{
/// <summary>
/// Locations where the content hash will be found. A null list means the only location is the local machine and a populated list holds remote locations.
/// </summary>
/// TODO: change the comment. It is stale. (bug 1365340)
public readonly IReadOnlyList<MachineLocation> Locations;
/// <summary>
/// The content hash for the specified locations.
/// </summary>
public readonly ContentHash ContentHash;
/// <summary>
/// The size of the content hash's file.
/// </summary>
public readonly long Size;
/// <summary>
/// Initializes a new instance of the <see cref="ContentHashWithSizeAndLocations"/> class.
/// </summary>
public ContentHashWithSizeAndLocations(ContentHash contentHash, long size = -1, IReadOnlyList<MachineLocation> locations = null)
{
ContentHash = contentHash;
Size = size;
Locations = locations;
}
/// <inheritdoc />
public override string ToString()
{
return $"[ContentHash={ContentHash.ToShortString()} Size={Size} LocationCount={Locations?.Count}]";
}
/// <inheritdoc />
public bool Equals(ContentHashWithSizeAndLocations other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Locations.SequenceEqual(other.Locations) == true && ContentHash.Equals(other.ContentHash) && Size == other.Size;
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (obj is null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((ContentHashWithSizeAndLocations) obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
var hashCode = Locations.SequenceHashCode();
hashCode = (hashCode * 397) ^ ContentHash.GetHashCode();
hashCode = (hashCode * 397) ^ Size.GetHashCode();
return hashCode;
}
}
/// <nodoc />
public static bool operator ==(ContentHashWithSizeAndLocations left, ContentHashWithSizeAndLocations right)
{
return Equals(left, right);
}
/// <nodoc />
public static bool operator !=(ContentHashWithSizeAndLocations left, ContentHashWithSizeAndLocations right)
{
return !Equals(left, right);
}
}
}
| 32.266055 | 162 | 0.548479 | [
"MIT"
] | breidikl/BuildXL | Public/Src/Cache/ContentStore/Distributed/ContentLocations/ContentHashWithSizeAndLocations.cs | 3,517 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using HotelCalifornia.Backend.Domain.Entities;
namespace HotelCalifornia.Backend.Database.Mappings
{
public class BookingsConfiguration: IEntityTypeConfiguration<Bookings>
{
public void Configure(EntityTypeBuilder<Bookings> AModelBuilder)
{
AModelBuilder.Property(ABookings => ABookings.Id).ValueGeneratedOnAdd();
AModelBuilder
.HasOne(ABookings => ABookings.Room)
.WithMany(ARooms => ARooms.Bookings)
.HasForeignKey(ABookings => ABookings.RoomId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Bookings_Rooms");
}
}
} | 36.571429 | 84 | 0.684896 | [
"MIT"
] | TomaszKandula/HotelCalifornia | HotelCalifornia.Backend/HotelCalifornia.Backend.Database/Mappings/BookingsConfiguration.cs | 768 | C# |
using System.ComponentModel.DataAnnotations.Schema;
namespace TNO.Entities;
[Table("content_action")]
public class ContentAction : AuditColumns, IEquatable<ContentAction>
{
#region Properties
[Column("content_id")]
public long ContentId { get; set; }
public virtual Content? Content { get; set; }
[Column("action_id")]
public int ActionId { get; set; }
public virtual Action? Action { get; set; }
[Column("value")]
public string Value { get; set; } = "";
#endregion
#region Constructors
protected ContentAction() { }
public ContentAction(Content content, Action action, string value)
{
this.ContentId = content?.Id ?? throw new ArgumentNullException(nameof(content));
this.Content = content;
this.ActionId = action?.Id ?? throw new ArgumentNullException(nameof(action));
this.Action = action;
this.Value = value ?? throw new ArgumentNullException(nameof(value));
}
public ContentAction(long contentId, int actionId, string value)
{
this.ContentId = contentId;
this.ActionId = actionId;
this.Value = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Methods
public bool Equals(ContentAction? other)
{
if (other == null) return false;
return this.ContentId == other.ContentId && this.ActionId == other.ActionId;
}
public override bool Equals(object? obj) => Equals(obj as ContentAction);
public override int GetHashCode() => (this.ContentId, this.ActionId).GetHashCode();
#endregion
}
| 29.740741 | 89 | 0.666874 | [
"Apache-2.0"
] | Fosol/TNO | libs/net/entities/ContentAction.cs | 1,606 | C# |
using System;
using System.Management;
public static class HardwareInfo
{
/// <summary>
/// Retrieving Processor Id.
/// </summary>
/// <returns></returns>
///
public static String GetProcessorId()
{
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
String Id = String.Empty;
foreach (ManagementObject mo in moc)
{
Id = mo.Properties["processorID"].Value.ToString();
break;
}
return Id;
}
/// <summary>
/// Retrieving HDD Serial No.
/// </summary>
/// <returns></returns>
public static String GetHDDSerialNo()
{
ManagementClass mangnmt = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection mcol = mangnmt.GetInstances();
string result = "";
foreach (ManagementObject strt in mcol)
{
result += Convert.ToString(strt["VolumeSerialNumber"]);
}
return result;
}
/// <summary>
/// Retrieving System MAC Address.
/// </summary>
/// <returns></returns>
public static string GetMACAddress()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
string MACAddress = string.Empty;
foreach (ManagementObject mo in moc)
{
if (string.IsNullOrEmpty(MACAddress))
{
if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
}
mo.Dispose();
}
MACAddress = MACAddress.Replace(":", "");
return MACAddress;
}
/// <summary>
/// Retrieving Motherboard Manufacturer.
/// </summary>
/// <returns></returns>
public static string GetBoardMaker()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BaseBoard");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("Manufacturer").ToString();
}
catch { }
}
return "Board Maker: Unknown";
}
/// <summary>
/// Retrieving Motherboard Product Id.
/// </summary>
/// <returns></returns>
public static string GetBoardProductId()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BaseBoard");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("Product").ToString();
}
catch { }
}
return "Product: Unknown";
}
/// <summary>
/// Retrieving CD-DVD Drive Path.
/// </summary>
/// <returns></returns>
public static string GetCdRomDrive()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_CDROMDrive");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("Drive").ToString();
}
catch { }
}
return "CD ROM Drive Letter: Unknown";
}
/// <summary>
/// Retrieving BIOS Maker.
/// </summary>
/// <returns></returns>
public static string GetBIOSmaker()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("Manufacturer").ToString();
}
catch { }
}
return "BIOS Maker: Unknown";
}
/// <summary>
/// Retrieving BIOS Serial No.
/// </summary>
/// <returns></returns>
public static string GetBIOSserNo()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("SerialNumber").ToString();
}
catch { }
}
return "BIOS Serial Number: Unknown";
}
/// <summary>
/// Retrieving BIOS Caption.
/// </summary>
/// <returns></returns>
public static string GetBIOScaption()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("Caption").ToString();
}
catch { }
}
return "BIOS Caption: Unknown";
}
/// <summary>
/// Retrieving System Account Name.
/// </summary>
/// <returns></returns>
public static string GetAccountName()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_UserAccount");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("Name").ToString();
}
catch { }
}
return "User Account Name: Unknown";
}
/// <summary>
/// Retrieving Physical Ram Memory.
/// </summary>
/// <returns></returns>
public static long GetPhysicalMemory()
{
ManagementScope oMs = new ManagementScope();
ObjectQuery oQuery = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
ManagementObjectCollection oCollection = oSearcher.Get();
long MemSize = 0;
long mCap = 0;
// In case more than one Memory sticks are installed
foreach (ManagementObject obj in oCollection)
{
mCap = Convert.ToInt64(obj["Capacity"]);
MemSize += mCap;
}
return (MemSize / 1024) / 1024;
}
/// <summary>
/// Retrieving No of Ram Slot on Motherboard.
/// </summary>
/// <returns></returns>
public static string GetNoRamSlots()
{
int MemSlots = 0;
ManagementScope oMs = new ManagementScope();
ObjectQuery oQuery2 = new ObjectQuery("SELECT MemoryDevices FROM Win32_PhysicalMemoryArray");
ManagementObjectSearcher oSearcher2 = new ManagementObjectSearcher(oMs, oQuery2);
ManagementObjectCollection oCollection2 = oSearcher2.Get();
foreach (ManagementObject obj in oCollection2)
{
MemSlots = Convert.ToInt32(obj["MemoryDevices"]);
}
return MemSlots.ToString();
}
//Get CPU Temprature.
/// <summary>
/// method for retrieving the CPU Manufacturer
/// using the WMI class
/// </summary>
/// <returns>CPU Manufacturer</returns>
public static string GetCPUManufacturer()
{
string cpuMan = String.Empty;
//create an instance of the Managemnet class with the
//Win32_Processor class
ManagementClass mgmt = new ManagementClass("Win32_Processor");
//create a ManagementObjectCollection to loop through
ManagementObjectCollection objCol = mgmt.GetInstances();
//start our loop for all processors found
foreach (ManagementObject obj in objCol)
{
if (cpuMan == String.Empty)
{
// only return manufacturer from first CPU
cpuMan = obj.Properties["Manufacturer"].Value.ToString();
}
}
return cpuMan;
}
/// <summary>
/// method to retrieve the CPU's current
/// clock speed using the WMI class
/// </summary>
/// <returns>Clock speed</returns>
public static int GetCPUCurrentClockSpeed()
{
int cpuClockSpeed = 0;
//create an instance of the Managemnet class with the
//Win32_Processor class
ManagementClass mgmt = new ManagementClass("Win32_Processor");
//create a ManagementObjectCollection to loop through
ManagementObjectCollection objCol = mgmt.GetInstances();
//start our loop for all processors found
foreach (ManagementObject obj in objCol)
{
if (cpuClockSpeed == 0)
{
// only return cpuStatus from first CPU
cpuClockSpeed = Convert.ToInt32(obj.Properties["CurrentClockSpeed"].Value.ToString());
}
}
//return the status
return cpuClockSpeed;
}
/// <summary>
/// method to retrieve the network adapters
/// default IP gateway using WMI
/// </summary>
/// <returns>adapters default IP gateway</returns>
public static string GetDefaultIPGateway()
{
//create out management class object using the
//Win32_NetworkAdapterConfiguration class to get the attributes
//of the network adapter
ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
//create our ManagementObjectCollection to get the attributes with
ManagementObjectCollection objCol = mgmt.GetInstances();
string gateway = String.Empty;
//loop through all the objects we find
foreach (ManagementObject obj in objCol)
{
if (gateway == String.Empty) // only return MAC Address from first card
{
//grab the value from the first network adapter we find
//you can change the string to an array and get all
//network adapters found as well
//check to see if the adapter's IPEnabled
//equals true
if ((bool)obj["IPEnabled"] == true)
{
gateway = obj["DefaultIPGateway"].ToString();
}
}
//dispose of our object
obj.Dispose();
}
//replace the ":" with an empty space, this could also
//be removed if you wish
gateway = gateway.Replace(":", "");
//return the mac address
return gateway;
}
/// <summary>
/// Retrieve CPU Speed.
/// </summary>
/// <returns></returns>
public static long GetCpuSpeedInGHz()
{
long GHz = 0;
using (ManagementClass mc = new ManagementClass("Win32_Processor"))
{
foreach (ManagementObject mo in mc.GetInstances())
{
GHz = (UInt32)mo.Properties["CurrentClockSpeed"].Value;
break;
}
}
return GHz;
}
/// <summary>
/// Retrieve CPU Speed.
/// </summary>
/// <returns></returns>
public static int GetCpuCount()
{
return Environment.ProcessorCount;
}
/// <summary>
/// Retrieving Current Language
/// </summary>
/// <returns></returns>
public static string GetCurrentLanguage()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return wmi.GetPropertyValue("CurrentLanguage").ToString();
}
catch { }
}
return "BIOS Maker: Unknown";
}
/// <summary>
/// Retrieving Current Language.
/// </summary>
/// <returns></returns>
public static string GetOSInformation()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return ((string)wmi["Caption"]).Trim() + ", " + (string)wmi["Version"] + ", " + (string)wmi["OSArchitecture"];
}
catch { }
}
return "BIOS Maker: Unknown";
}
/// <summary>
/// Retrieving Processor Information.
/// </summary>
/// <returns></returns>
public static String GetProcessorInformation()
{
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
String info = String.Empty;
foreach (ManagementObject mo in moc)
{
string name = (string)mo["Name"];
name = name.Replace("(TM)", "™").Replace("(tm)", "™").Replace("(R)", "®").Replace("(r)", "®").Replace("(C)", "©").Replace("(c)", "©").Replace(" ", " ").Replace(" ", " ");
info = name + ", " + (string)mo["Caption"] + ", " + (string)mo["SocketDesignation"];
//mo.Properties["Name"].Value.ToString();
//break;
}
return info;
}
/// <summary>
/// Retrieving Computer Name.
/// </summary>
/// <returns></returns>
public static String GetComputerName()
{
ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
ManagementObjectCollection moc = mc.GetInstances();
String info = String.Empty;
foreach (ManagementObject mo in moc)
{
info = (string)mo["Name"];
//mo.Properties["Name"].Value.ToString();
//break;
}
return info;
}
} | 29.618421 | 186 | 0.567748 | [
"Apache-2.0"
] | pierrehub2b/windowsdriver | record/HardwareInfo.cs | 13,516 | C# |
// Copyright (c) 2021 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT license. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using AuthPermissions.DataLayer.Classes.SupportTypes;
namespace AuthPermissions.SetupCode;
/// <summary>
/// Class used to define users with their roles and tenant
/// </summary>
public class BulkLoadUserWithRolesTenant
{
/// <summary>
/// This defines a user in your application
/// </summary>
/// <param name="email">Unique email</param>
/// <param name="userName">name to help the admin team to work out who the user is</param>
/// <param name="roleNamesCommaDelimited">A string containing a comma delimited set of auth roles that the user</param>
/// <param name="userId">If null, then you must register a <see cref="IFindUserInfoService"/> to provide a lookup of the UserId</param>
/// <param name="uniqueUserName">A string that is unique for each user, e.g. email. If not provided then uses the userName</param>
/// <param name="tenantNameForDataKey">Optional: The unique name of your multi-tenant that this user is linked to</param>
public BulkLoadUserWithRolesTenant(string email, string userName, string roleNamesCommaDelimited,
string userId = null,
string uniqueUserName = null, string tenantNameForDataKey = null)
{
UserId = userId; //Can be null
Email = email ?? throw new ArgumentNullException(nameof(email));
UserName = userName ?? email;
RoleNamesCommaDelimited = roleNamesCommaDelimited ??
throw new ArgumentNullException(nameof(roleNamesCommaDelimited));
UniqueUserName = uniqueUserName ?? UserName;
TenantNameForDataKey = tenantNameForDataKey;
}
/// <summary>
/// This is what AuthPermissions needs to create a new AuthP User
/// You can set the userId directly or if you leave it as null then you must provide <see cref="IFindUserInfoService"/>
/// which will interrogate the authentication provider for the UserId
/// </summary>
public string UserId { get; }
/// <summary>
/// Contains a name to help the admin team to work out who the user is
/// </summary>
public string Email { get; }
/// <summary>
/// Contains a name to help the admin team to work out who the user is
/// </summary>
[MaxLength(AuthDbConstants.UserNameSize)]
public string UserName { get; }
/// <summary>
/// This contains a string that is unique for each user, e.g. email
/// </summary>
public string UniqueUserName { get; }
/// <summary>
/// This contains the Tenant name. Used to provide the user with a multi-tenant data key
/// </summary>
public string TenantNameForDataKey { get; }
/// <summary>
/// List of role names in a comma delimited list
/// </summary>
public string RoleNamesCommaDelimited { get; }
/// <summary>
/// Useful when debugging
/// </summary>
/// <returns></returns>
public override string ToString()
{
return $"{nameof(UserId)}: {UserId ?? "null"}, {nameof(Email)}: {Email}, {nameof(UserName)}: {UserName ?? "null"}, " +
$"{nameof(TenantNameForDataKey)}: {TenantNameForDataKey ?? "null"}, {nameof(RoleNamesCommaDelimited)}: {RoleNamesCommaDelimited ?? "null"}";
}
} | 43.64557 | 155 | 0.673724 | [
"MIT"
] | JonPSmith/AuthPermissions.AspNetCore | AuthPermissions/SetupCode/BulkLoadUserWithRolesTenant.cs | 3,450 | C# |
/*
* Copyright 2019-2020 Robbyxp1 @ github.com
*
*
* 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 GLOFC.Utils;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
namespace GLOFC.GL4.Shaders.Fragment
{
/// <summary>
/// This namespace contains pipeline fragment shaders.
/// </summary>
internal static class NamespaceDoc { } // just for documentation purposes
/// <summary>
/// Pipeline shader, texture shader,
/// renders an texture ARB dependent either on primitive number/2 (so to be used with a triangle strip) or image id in location 2
/// With alphablending and discard if transparent
/// </summary>
public class GLPLFragmentShaderBindlessTexture : GLShaderPipelineComponentShadersBase
{
/// <summary> Offset of texture in object, 0-1 </summary>
public Vector2 TexOffset { get; set; } = Vector2.Zero; // set to animate.
/// <summary>
/// Constructor
/// Requires:
/// location 0 : vs_texturecoordinate : vec2 of texture co-ord
/// location 3 : flat in wvalue for opacity control (if enabled by usealphablending)
/// location 4 : image id (if useprimidover2=false)
/// uniform binding config: ARB bindless texture handles, int 64s
/// location 24 : uniform of texture offset (written by start automatically)
/// </summary>
/// <param name="arbblock">Binding number of ARB Block</param>
/// <param name="usealphablending">Alpha blend on/off</param>
/// <param name="discardiftransparent">Discard if pixel is low intensity</param>
/// <param name="useprimidover2">Use primitive/2 as texture object number, else use location 4</param>
public GLPLFragmentShaderBindlessTexture(int arbblock, bool usealphablending = false, bool discardiftransparent = false, bool useprimidover2 = true)
{
CompileLink(ShaderType.FragmentShader, Code(arbblock), out string unused,
constvalues: new object[] { "usewvalue", usealphablending, "discardiftransparent", discardiftransparent, "useprimidover2", useprimidover2 });
}
/// <summary> Shader start </summary>
public override void Start(GLMatrixCalc c)
{
GL.ProgramUniform2(Id, 24, TexOffset);
}
private string Code(int arbblock)
{
return
@"
#version 450 core
#extension GL_ARB_bindless_texture : require
layout (location=0) in vec2 vs_textureCoordinate;
layout (location=3) flat in float wvalue;
layout (location = 4) in VS_IN
{
flat int imageno;
} vs_in;
layout (binding = " + arbblock.ToStringInvariant() + @", std140) uniform TEXTURE_BLOCK
{
sampler2D tex[256];
};
layout (location = 24) uniform vec2 offset;
out vec4 color;
const bool usewvalue = false;
const bool discardiftransparent = false;
const bool useprimidover2 = true;
void main(void)
{
int objno = useprimidover2 ? gl_PrimitiveID/2 : vs_in.imageno;
color = texture(tex[objno], vs_textureCoordinate+offset); // vs_texture coords normalised 0 to 1.0f
// color = vec4(1,0,0,1);
if ( discardiftransparent && color.w < 0.0001)
discard;
else if ( usewvalue)
color.w *= wvalue;
}
";
}
}
}
| 38.264706 | 166 | 0.651806 | [
"Apache-2.0"
] | OpenTK-Foundation-Classes/OFC | OFC/GL4/Shaders/Fragment/ShadersFragmentBindless.cs | 3,804 | C# |
using AutoMapper;
using Abp.Authorization;
using Abp.Authorization.Roles;
using AFX.Authorization.Roles;
namespace AFX.Roles.Dto
{
public class RoleMapProfile : Profile
{
public RoleMapProfile()
{
// Role and permission
CreateMap<Permission, string>().ConvertUsing(r => r.Name);
CreateMap<RolePermissionSetting, string>().ConvertUsing(r => r.Name);
CreateMap<CreateRoleDto, Role>().ForMember(x => x.Permissions, opt => opt.Ignore());
CreateMap<RoleDto, Role>().ForMember(x => x.Permissions, opt => opt.Ignore());
}
}
}
| 29.428571 | 96 | 0.627832 | [
"MIT"
] | CAH-FlyChen/AFX | aspnet-core/src/AFX.Application/Roles/Dto/RoleMapProfile.cs | 620 | C# |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Tls
{
public abstract class TlsProtocol
: TlsCloseable
{
/*
* Our Connection states
*/
protected const short CS_START = 0;
protected const short CS_CLIENT_HELLO = 1;
protected const short CS_SERVER_HELLO = 2;
protected const short CS_SERVER_SUPPLEMENTAL_DATA = 3;
protected const short CS_SERVER_CERTIFICATE = 4;
protected const short CS_CERTIFICATE_STATUS = 5;
protected const short CS_SERVER_KEY_EXCHANGE = 6;
protected const short CS_CERTIFICATE_REQUEST = 7;
protected const short CS_SERVER_HELLO_DONE = 8;
protected const short CS_CLIENT_SUPPLEMENTAL_DATA = 9;
protected const short CS_CLIENT_CERTIFICATE = 10;
protected const short CS_CLIENT_KEY_EXCHANGE = 11;
protected const short CS_CERTIFICATE_VERIFY = 12;
protected const short CS_CLIENT_FINISHED = 13;
protected const short CS_SERVER_SESSION_TICKET = 14;
protected const short CS_SERVER_FINISHED = 15;
protected const short CS_END = 16;
/*
* Different modes to handle the known IV weakness
*/
protected const short ADS_MODE_1_Nsub1 = 0; // 1/n-1 record splitting
protected const short ADS_MODE_0_N = 1; // 0/n record splitting
protected const short ADS_MODE_0_N_FIRSTONLY = 2; // 0/n record splitting on first data fragment only
/*
* Queues for data from some protocols.
*/
private ByteQueue mApplicationDataQueue = new ByteQueue(0);
private ByteQueue mAlertQueue = new ByteQueue(2);
private ByteQueue mHandshakeQueue = new ByteQueue(0);
// private ByteQueue mHeartbeatQueue = new ByteQueue();
/*
* The Record Stream we use
*/
internal RecordStream mRecordStream;
protected SecureRandom mSecureRandom;
private TlsStream mTlsStream = null;
private volatile bool mClosed = false;
private volatile bool mFailedWithError = false;
private volatile bool mAppDataReady = false;
private volatile bool mAppDataSplitEnabled = true;
private volatile int mAppDataSplitMode = ADS_MODE_1_Nsub1;
private byte[] mExpectedVerifyData = null;
protected TlsSession mTlsSession = null;
protected SessionParameters mSessionParameters = null;
protected SecurityParameters mSecurityParameters = null;
protected Certificate mPeerCertificate = null;
protected int[] mOfferedCipherSuites = null;
protected byte[] mOfferedCompressionMethods = null;
protected IDictionary mClientExtensions = null;
protected IDictionary mServerExtensions = null;
protected short mConnectionState = CS_START;
protected bool mResumedSession = false;
protected bool mReceivedChangeCipherSpec = false;
protected bool mSecureRenegotiation = false;
protected bool mAllowCertificateStatus = false;
protected bool mExpectSessionTicket = false;
protected bool mBlocking = true;
protected ByteQueueStream mInputBuffers = null;
protected ByteQueueStream mOutputBuffer = null;
public TlsProtocol(Stream stream, SecureRandom secureRandom)
: this(stream, stream, secureRandom)
{
}
public TlsProtocol(Stream input, Stream output, SecureRandom secureRandom)
{
this.mRecordStream = new RecordStream(this, input, output);
this.mSecureRandom = secureRandom;
}
public TlsProtocol(SecureRandom secureRandom)
{
this.mBlocking = false;
this.mInputBuffers = new ByteQueueStream();
this.mOutputBuffer = new ByteQueueStream();
this.mRecordStream = new RecordStream(this, mInputBuffers, mOutputBuffer);
this.mSecureRandom = secureRandom;
}
protected abstract TlsContext Context { get; }
internal abstract AbstractTlsContext ContextAdmin { get; }
protected abstract TlsPeer Peer { get; }
protected virtual void HandleAlertMessage(byte alertLevel, byte alertDescription)
{
Peer.NotifyAlertReceived(alertLevel, alertDescription);
if (alertLevel == AlertLevel.warning)
{
HandleAlertWarningMessage(alertDescription);
}
else
{
HandleFailure();
throw new TlsFatalAlertReceived(alertDescription);
}
}
protected virtual void HandleAlertWarningMessage(byte alertDescription)
{
/*
* RFC 5246 7.2.1. The other party MUST respond with a close_notify alert of its own
* and close down the connection immediately, discarding any pending writes.
*/
if (alertDescription == AlertDescription.close_notify)
{
if (!mAppDataReady)
throw new TlsFatalAlert(AlertDescription.handshake_failure);
HandleClose(false);
}
}
protected virtual void HandleChangeCipherSpecMessage()
{
}
protected virtual void HandleClose(bool user_canceled)
{
if (!mClosed)
{
this.mClosed = true;
if (user_canceled && !mAppDataReady)
{
RaiseAlertWarning(AlertDescription.user_canceled, "User canceled handshake");
}
RaiseAlertWarning(AlertDescription.close_notify, "Connection closed");
mRecordStream.SafeClose();
if (!mAppDataReady)
{
CleanupHandshake();
}
}
}
protected virtual void HandleException(byte alertDescription, string message, Exception cause)
{
if (!mClosed)
{
RaiseAlertFatal(alertDescription, message, cause);
HandleFailure();
}
}
protected virtual void HandleFailure()
{
this.mClosed = true;
this.mFailedWithError = true;
/*
* RFC 2246 7.2.1. The session becomes unresumable if any connection is terminated
* without proper close_notify messages with level equal to warning.
*/
// TODO This isn't quite in the right place. Also, as of TLS 1.1 the above is obsolete.
InvalidateSession();
mRecordStream.SafeClose();
if (!mAppDataReady)
{
CleanupHandshake();
}
}
protected abstract void HandleHandshakeMessage(byte type, MemoryStream buf);
protected virtual void ApplyMaxFragmentLengthExtension()
{
if (mSecurityParameters.maxFragmentLength >= 0)
{
if (!MaxFragmentLength.IsValid((byte)mSecurityParameters.maxFragmentLength))
throw new TlsFatalAlert(AlertDescription.internal_error);
int plainTextLimit = 1 << (8 + mSecurityParameters.maxFragmentLength);
mRecordStream.SetPlaintextLimit(plainTextLimit);
}
}
protected virtual void CheckReceivedChangeCipherSpec(bool expected)
{
if (expected != mReceivedChangeCipherSpec)
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
protected virtual void CleanupHandshake()
{
if (this.mExpectedVerifyData != null)
{
Arrays.Fill(this.mExpectedVerifyData, (byte)0);
this.mExpectedVerifyData = null;
}
this.mSecurityParameters.Clear();
this.mPeerCertificate = null;
this.mOfferedCipherSuites = null;
this.mOfferedCompressionMethods = null;
this.mClientExtensions = null;
this.mServerExtensions = null;
this.mResumedSession = false;
this.mReceivedChangeCipherSpec = false;
this.mSecureRenegotiation = false;
this.mAllowCertificateStatus = false;
this.mExpectSessionTicket = false;
}
protected virtual void BlockForHandshake()
{
if (mBlocking)
{
while (this.mConnectionState != CS_END)
{
if (this.mClosed)
{
// NOTE: Any close during the handshake should have raised an exception.
throw new TlsFatalAlert(AlertDescription.internal_error);
}
SafeReadRecord();
}
}
}
protected virtual void CompleteHandshake()
{
try
{
this.mConnectionState = CS_END;
this.mAlertQueue.Shrink();
this.mHandshakeQueue.Shrink();
this.mRecordStream.FinaliseHandshake();
this.mAppDataSplitEnabled = !TlsUtilities.IsTlsV11(Context);
/*
* If this was an initial handshake, we are now ready to send and receive application data.
*/
if (!mAppDataReady)
{
this.mAppDataReady = true;
if (mBlocking)
{
this.mTlsStream = new TlsStream(this);
}
}
if (this.mTlsSession != null)
{
if (this.mSessionParameters == null)
{
this.mSessionParameters = new SessionParameters.Builder()
.SetCipherSuite(this.mSecurityParameters.CipherSuite)
.SetCompressionAlgorithm(this.mSecurityParameters.CompressionAlgorithm)
.SetExtendedMasterSecret(this.mSecurityParameters.IsExtendedMasterSecret)
.SetMasterSecret(this.mSecurityParameters.MasterSecret)
.SetPeerCertificate(this.mPeerCertificate)
.SetPskIdentity(this.mSecurityParameters.PskIdentity)
.SetSrpIdentity(this.mSecurityParameters.SrpIdentity)
// TODO Consider filtering extensions that aren't relevant to resumed sessions
.SetServerExtensions(this.mServerExtensions)
.Build();
this.mTlsSession = new TlsSessionImpl(this.mTlsSession.SessionID, this.mSessionParameters);
}
ContextAdmin.SetResumableSession(this.mTlsSession);
}
Peer.NotifyHandshakeComplete();
}
finally
{
CleanupHandshake();
}
}
protected internal void ProcessRecord(byte protocol, byte[] buf, int off, int len)
{
/*
* Have a look at the protocol type, and add it to the correct queue.
*/
switch (protocol)
{
case ContentType.alert:
{
mAlertQueue.AddData(buf, off, len);
ProcessAlertQueue();
break;
}
case ContentType.application_data:
{
if (!mAppDataReady)
throw new TlsFatalAlert(AlertDescription.unexpected_message);
mApplicationDataQueue.AddData(buf, off, len);
ProcessApplicationDataQueue();
break;
}
case ContentType.change_cipher_spec:
{
ProcessChangeCipherSpec(buf, off, len);
break;
}
case ContentType.handshake:
{
if (mHandshakeQueue.Available > 0)
{
mHandshakeQueue.AddData(buf, off, len);
ProcessHandshakeQueue(mHandshakeQueue);
}
else
{
ByteQueue tmpQueue = new ByteQueue(buf, off, len);
ProcessHandshakeQueue(tmpQueue);
int remaining = tmpQueue.Available;
if (remaining > 0)
{
mHandshakeQueue.AddData(buf, off + len - remaining, remaining);
}
}
break;
}
//case ContentType.heartbeat:
//{
// if (!mAppDataReady)
// throw new TlsFatalAlert(AlertDescription.unexpected_message);
// // TODO[RFC 6520]
// //mHeartbeatQueue.AddData(buf, offset, len);
// //ProcessHeartbeat();
// break;
//}
default:
// Record type should already have been checked
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
private void ProcessHandshakeQueue(ByteQueue queue)
{
while (queue.Available >= 4)
{
/*
* We need the first 4 bytes, they contain type and length of the message.
*/
byte[] beginning = new byte[4];
queue.Read(beginning, 0, 4, 0);
byte type = TlsUtilities.ReadUint8(beginning, 0);
int length = TlsUtilities.ReadUint24(beginning, 1);
int totalLength = 4 + length;
/*
* Check if we have enough bytes in the buffer to read the full message.
*/
if (queue.Available < totalLength)
break;
/*
* RFC 2246 7.4.9. The value handshake_messages includes all handshake messages
* starting at client hello up to, but not including, this finished message.
* [..] Note: [Also,] Hello Request messages are omitted from handshake hashes.
*/
if (HandshakeType.hello_request != type)
{
if (HandshakeType.finished == type)
{
CheckReceivedChangeCipherSpec(true);
TlsContext ctx = Context;
if (this.mExpectedVerifyData == null
&& ctx.SecurityParameters.MasterSecret != null)
{
this.mExpectedVerifyData = CreateVerifyData(!ctx.IsServer);
}
}
else
{
CheckReceivedChangeCipherSpec(mConnectionState == CS_END);
}
queue.CopyTo(mRecordStream.HandshakeHashUpdater, totalLength);
}
queue.RemoveData(4);
MemoryStream buf = queue.ReadFrom(length);
/*
* Now, parse the message.
*/
HandleHandshakeMessage(type, buf);
}
}
private void ProcessApplicationDataQueue()
{
/*
* There is nothing we need to do here.
*
* This function could be used for callbacks when application data arrives in the future.
*/
}
private void ProcessAlertQueue()
{
while (mAlertQueue.Available >= 2)
{
/*
* An alert is always 2 bytes. Read the alert.
*/
byte[] alert = mAlertQueue.RemoveData(2, 0);
byte alertLevel = alert[0];
byte alertDescription = alert[1];
HandleAlertMessage(alertLevel, alertDescription);
}
}
/**
* This method is called, when a change cipher spec message is received.
*
* @throws IOException If the message has an invalid content or the handshake is not in the correct
* state.
*/
private void ProcessChangeCipherSpec(byte[] buf, int off, int len)
{
for (int i = 0; i < len; ++i)
{
byte message = TlsUtilities.ReadUint8(buf, off + i);
if (message != ChangeCipherSpec.change_cipher_spec)
throw new TlsFatalAlert(AlertDescription.decode_error);
if (this.mReceivedChangeCipherSpec
|| mAlertQueue.Available > 0
|| mHandshakeQueue.Available > 0)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
mRecordStream.ReceivedReadCipherSpec();
this.mReceivedChangeCipherSpec = true;
HandleChangeCipherSpecMessage();
}
}
protected internal virtual int ApplicationDataAvailable()
{
return mApplicationDataQueue.Available;
}
/**
* Read data from the network. The method will return immediately, if there is still some data
* left in the buffer, or block until some application data has been read from the network.
*
* @param buf The buffer where the data will be copied to.
* @param offset The position where the data will be placed in the buffer.
* @param len The maximum number of bytes to read.
* @return The number of bytes read.
* @throws IOException If something goes wrong during reading data.
*/
protected internal virtual int ReadApplicationData(byte[] buf, int offset, int len)
{
if (len < 1)
return 0;
while (mApplicationDataQueue.Available == 0)
{
if (this.mClosed)
{
if (this.mFailedWithError)
throw new IOException("Cannot read application data on failed TLS connection");
if (!mAppDataReady)
throw new InvalidOperationException("Cannot read application data until initial handshake completed.");
return 0;
}
SafeReadRecord();
}
len = System.Math.Min(len, mApplicationDataQueue.Available);
mApplicationDataQueue.RemoveData(buf, offset, len, 0);
return len;
}
protected virtual void SafeCheckRecordHeader(byte[] recordHeader)
{
try
{
mRecordStream.CheckRecordHeader(recordHeader);
}
catch (TlsFatalAlert e)
{
HandleException(e.AlertDescription, "Failed to read record", e);
throw e;
}
catch (IOException e)
{
HandleException(AlertDescription.internal_error, "Failed to read record", e);
throw e;
}
catch (Exception e)
{
HandleException(AlertDescription.internal_error, "Failed to read record", e);
throw new TlsFatalAlert(AlertDescription.internal_error, e);
}
}
protected virtual void SafeReadRecord()
{
try
{
if (mRecordStream.ReadRecord())
return;
if (!mAppDataReady)
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
catch (TlsFatalAlertReceived e)
{
// Connection failure already handled at source
throw e;
}
catch (TlsFatalAlert e)
{
HandleException(e.AlertDescription, "Failed to read record", e);
throw e;
}
catch (IOException e)
{
HandleException(AlertDescription.internal_error, "Failed to read record", e);
throw e;
}
catch (Exception e)
{
HandleException(AlertDescription.internal_error, "Failed to read record", e);
throw new TlsFatalAlert(AlertDescription.internal_error, e);
}
HandleFailure();
throw new TlsNoCloseNotifyException();
}
protected virtual void SafeWriteRecord(byte type, byte[] buf, int offset, int len)
{
try
{
mRecordStream.WriteRecord(type, buf, offset, len);
}
catch (TlsFatalAlert e)
{
HandleException(e.AlertDescription, "Failed to write record", e);
throw e;
}
catch (IOException e)
{
HandleException(AlertDescription.internal_error, "Failed to write record", e);
throw e;
}
catch (Exception e)
{
HandleException(AlertDescription.internal_error, "Failed to write record", e);
throw new TlsFatalAlert(AlertDescription.internal_error, e);
}
}
/**
* Send some application data to the remote system.
* <p/>
* The method will handle fragmentation internally.
*
* @param buf The buffer with the data.
* @param offset The position in the buffer where the data is placed.
* @param len The length of the data.
* @throws IOException If something goes wrong during sending.
*/
protected internal virtual void WriteData(byte[] buf, int offset, int len)
{
if (this.mClosed)
throw new IOException("Cannot write application data on closed/failed TLS connection");
while (len > 0)
{
/*
* RFC 5246 6.2.1. Zero-length fragments of Application data MAY be sent as they are
* potentially useful as a traffic analysis countermeasure.
*
* NOTE: Actually, implementations appear to have settled on 1/n-1 record splitting.
*/
if (this.mAppDataSplitEnabled)
{
/*
* Protect against known IV attack!
*
* DO NOT REMOVE THIS CODE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE.
*/
switch (mAppDataSplitMode)
{
case ADS_MODE_0_N:
SafeWriteRecord(ContentType.application_data, TlsUtilities.EmptyBytes, 0, 0);
break;
case ADS_MODE_0_N_FIRSTONLY:
this.mAppDataSplitEnabled = false;
SafeWriteRecord(ContentType.application_data, TlsUtilities.EmptyBytes, 0, 0);
break;
case ADS_MODE_1_Nsub1:
default:
SafeWriteRecord(ContentType.application_data, buf, offset, 1);
++offset;
--len;
break;
}
}
if (len > 0)
{
// Fragment data according to the current fragment limit.
int toWrite = System.Math.Min(len, mRecordStream.GetPlaintextLimit());
SafeWriteRecord(ContentType.application_data, buf, offset, toWrite);
offset += toWrite;
len -= toWrite;
}
}
}
protected virtual void SetAppDataSplitMode(int appDataSplitMode)
{
if (appDataSplitMode < ADS_MODE_1_Nsub1 || appDataSplitMode > ADS_MODE_0_N_FIRSTONLY)
throw new ArgumentException("Illegal appDataSplitMode mode: " + appDataSplitMode, "appDataSplitMode");
this.mAppDataSplitMode = appDataSplitMode;
}
protected virtual void WriteHandshakeMessage(byte[] buf, int off, int len)
{
if (len < 4)
throw new TlsFatalAlert(AlertDescription.internal_error);
byte type = TlsUtilities.ReadUint8(buf, off);
if (type != HandshakeType.hello_request)
{
mRecordStream.HandshakeHashUpdater.Write(buf, off, len);
}
int total = 0;
do
{
// Fragment data according to the current fragment limit.
int toWrite = System.Math.Min(len - total, mRecordStream.GetPlaintextLimit());
SafeWriteRecord(ContentType.handshake, buf, off + total, toWrite);
total += toWrite;
}
while (total < len);
}
/// <summary>The secure bidirectional stream for this connection</summary>
/// <remarks>Only allowed in blocking mode.</remarks>
public virtual Stream Stream
{
get
{
if (!mBlocking)
throw new InvalidOperationException("Cannot use Stream in non-blocking mode! Use OfferInput()/OfferOutput() instead.");
return this.mTlsStream;
}
}
/**
* Should be called in non-blocking mode when the input data reaches EOF.
*/
public virtual void CloseInput()
{
if (mBlocking)
throw new InvalidOperationException("Cannot use CloseInput() in blocking mode!");
if (mClosed)
return;
if (mInputBuffers.Available > 0)
throw new EndOfStreamException();
if (!mAppDataReady)
throw new TlsFatalAlert(AlertDescription.handshake_failure);
throw new TlsNoCloseNotifyException();
}
/**
* Equivalent to <code>OfferInput(input, 0, input.length)</code>
* @see TlsProtocol#OfferInput(byte[], int, int)
* @param input The input buffer to offer
* @throws IOException If an error occurs while decrypting or processing a record
*/
public virtual void OfferInput(byte[] input)
{
OfferInput(input, 0, input.Length);
}
/**
* Offer input from an arbitrary source. Only allowed in non-blocking mode.<br/>
* <br/>
* This method will decrypt and process all records that are fully available.
* If only part of a record is available, the buffer will be retained until the
* remainder of the record is offered.<br/>
* <br/>
* If any records containing application data were processed, the decrypted data
* can be obtained using {@link #readInput(byte[], int, int)}. If any records
* containing protocol data were processed, a response may have been generated.
* You should always check to see if there is any available output after calling
* this method by calling {@link #getAvailableOutputBytes()}.
* @param input The input buffer to offer
* @param inputOff The offset within the input buffer that input begins
* @param inputLen The number of bytes of input being offered
* @throws IOException If an error occurs while decrypting or processing a record
*/
public virtual void OfferInput(byte[] input, int inputOff, int inputLen)
{
if (mBlocking)
throw new InvalidOperationException("Cannot use OfferInput() in blocking mode! Use Stream instead.");
if (mClosed)
throw new IOException("Connection is closed, cannot accept any more input");
mInputBuffers.Write(input, inputOff, inputLen);
// loop while there are enough bytes to read the length of the next record
while (mInputBuffers.Available >= RecordStream.TLS_HEADER_SIZE)
{
byte[] recordHeader = new byte[RecordStream.TLS_HEADER_SIZE];
mInputBuffers.Peek(recordHeader);
int totalLength = TlsUtilities.ReadUint16(recordHeader, RecordStream.TLS_HEADER_LENGTH_OFFSET) + RecordStream.TLS_HEADER_SIZE;
if (mInputBuffers.Available < totalLength)
{
// not enough bytes to read a whole record
SafeCheckRecordHeader(recordHeader);
break;
}
SafeReadRecord();
if (mClosed)
{
if (mConnectionState != CS_END)
{
// NOTE: Any close during the handshake should have raised an exception.
throw new TlsFatalAlert(AlertDescription.internal_error);
}
break;
}
}
}
/**
* Gets the amount of received application data. A call to {@link #readInput(byte[], int, int)}
* is guaranteed to be able to return at least this much data.<br/>
* <br/>
* Only allowed in non-blocking mode.
* @return The number of bytes of available application data
*/
public virtual int GetAvailableInputBytes()
{
if (mBlocking)
throw new InvalidOperationException("Cannot use GetAvailableInputBytes() in blocking mode! Use ApplicationDataAvailable() instead.");
return ApplicationDataAvailable();
}
/**
* Retrieves received application data. Use {@link #getAvailableInputBytes()} to check
* how much application data is currently available. This method functions similarly to
* {@link InputStream#read(byte[], int, int)}, except that it never blocks. If no data
* is available, nothing will be copied and zero will be returned.<br/>
* <br/>
* Only allowed in non-blocking mode.
* @param buffer The buffer to hold the application data
* @param offset The start offset in the buffer at which the data is written
* @param length The maximum number of bytes to read
* @return The total number of bytes copied to the buffer. May be less than the
* length specified if the length was greater than the amount of available data.
*/
public virtual int ReadInput(byte[] buffer, int offset, int length)
{
if (mBlocking)
throw new InvalidOperationException("Cannot use ReadInput() in blocking mode! Use Stream instead.");
return ReadApplicationData(buffer, offset, System.Math.Min(length, ApplicationDataAvailable()));
}
/**
* Offer output from an arbitrary source. Only allowed in non-blocking mode.<br/>
* <br/>
* After this method returns, the specified section of the buffer will have been
* processed. Use {@link #readOutput(byte[], int, int)} to get the bytes to
* transmit to the other peer.<br/>
* <br/>
* This method must not be called until after the handshake is complete! Attempting
* to call it before the handshake is complete will result in an exception.
* @param buffer The buffer containing application data to encrypt
* @param offset The offset at which to begin reading data
* @param length The number of bytes of data to read
* @throws IOException If an error occurs encrypting the data, or the handshake is not complete
*/
public virtual void OfferOutput(byte[] buffer, int offset, int length)
{
if (mBlocking)
throw new InvalidOperationException("Cannot use OfferOutput() in blocking mode! Use Stream instead.");
if (!mAppDataReady)
throw new IOException("Application data cannot be sent until the handshake is complete!");
WriteData(buffer, offset, length);
}
/**
* Gets the amount of encrypted data available to be sent. A call to
* {@link #readOutput(byte[], int, int)} is guaranteed to be able to return at
* least this much data.<br/>
* <br/>
* Only allowed in non-blocking mode.
* @return The number of bytes of available encrypted data
*/
public virtual int GetAvailableOutputBytes()
{
if (mBlocking)
throw new InvalidOperationException("Cannot use GetAvailableOutputBytes() in blocking mode! Use Stream instead.");
return mOutputBuffer.Available;
}
/**
* Retrieves encrypted data to be sent. Use {@link #getAvailableOutputBytes()} to check
* how much encrypted data is currently available. This method functions similarly to
* {@link InputStream#read(byte[], int, int)}, except that it never blocks. If no data
* is available, nothing will be copied and zero will be returned.<br/>
* <br/>
* Only allowed in non-blocking mode.
* @param buffer The buffer to hold the encrypted data
* @param offset The start offset in the buffer at which the data is written
* @param length The maximum number of bytes to read
* @return The total number of bytes copied to the buffer. May be less than the
* length specified if the length was greater than the amount of available data.
*/
public virtual int ReadOutput(byte[] buffer, int offset, int length)
{
if (mBlocking)
throw new InvalidOperationException("Cannot use ReadOutput() in blocking mode! Use Stream instead.");
return mOutputBuffer.Read(buffer, offset, length);
}
protected virtual void InvalidateSession()
{
if (this.mSessionParameters != null)
{
this.mSessionParameters.Clear();
this.mSessionParameters = null;
}
if (this.mTlsSession != null)
{
this.mTlsSession.Invalidate();
this.mTlsSession = null;
}
}
protected virtual void ProcessFinishedMessage(MemoryStream buf)
{
if (mExpectedVerifyData == null)
throw new TlsFatalAlert(AlertDescription.internal_error);
byte[] verify_data = TlsUtilities.ReadFully(mExpectedVerifyData.Length, buf);
AssertEmpty(buf);
/*
* Compare both checksums.
*/
if (!Arrays.ConstantTimeAreEqual(mExpectedVerifyData, verify_data))
{
/*
* Wrong checksum in the finished message.
*/
throw new TlsFatalAlert(AlertDescription.decrypt_error);
}
}
protected virtual void RaiseAlertFatal(byte alertDescription, string message, Exception cause)
{
Peer.NotifyAlertRaised(AlertLevel.fatal, alertDescription, message, cause);
byte[] alert = new byte[] { AlertLevel.fatal, alertDescription };
try
{
mRecordStream.WriteRecord(ContentType.alert, alert, 0, 2);
}
catch (Exception)
{
// We are already processing an exception, so just ignore this
}
}
protected virtual void RaiseAlertWarning(byte alertDescription, string message)
{
Peer.NotifyAlertRaised(AlertLevel.warning, alertDescription, message, null);
byte[] alert = new byte[] { AlertLevel.warning, alertDescription };
SafeWriteRecord(ContentType.alert, alert, 0, 2);
}
protected virtual void SendCertificateMessage(Certificate certificate)
{
if (certificate == null)
{
certificate = Certificate.EmptyChain;
}
if (certificate.IsEmpty)
{
TlsContext context = Context;
if (!context.IsServer)
{
ProtocolVersion serverVersion = Context.ServerVersion;
if (serverVersion.IsSsl)
{
string errorMessage = serverVersion.ToString() + " client didn't provide credentials";
RaiseAlertWarning(AlertDescription.no_certificate, errorMessage);
return;
}
}
}
HandshakeMessage message = new HandshakeMessage(HandshakeType.certificate);
certificate.Encode(message);
message.WriteToRecordStream(this);
}
protected virtual void SendChangeCipherSpecMessage()
{
byte[] message = new byte[] { 1 };
SafeWriteRecord(ContentType.change_cipher_spec, message, 0, message.Length);
mRecordStream.SentWriteCipherSpec();
}
protected virtual void SendFinishedMessage()
{
byte[] verify_data = CreateVerifyData(Context.IsServer);
HandshakeMessage message = new HandshakeMessage(HandshakeType.finished, verify_data.Length);
message.Write(verify_data, 0, verify_data.Length);
message.WriteToRecordStream(this);
}
protected virtual void SendSupplementalDataMessage(IList supplementalData)
{
HandshakeMessage message = new HandshakeMessage(HandshakeType.supplemental_data);
WriteSupplementalData(message, supplementalData);
message.WriteToRecordStream(this);
}
protected virtual byte[] CreateVerifyData(bool isServer)
{
TlsContext context = Context;
string asciiLabel = isServer ? ExporterLabel.server_finished : ExporterLabel.client_finished;
byte[] sslSender = isServer ? TlsUtilities.SSL_SERVER : TlsUtilities.SSL_CLIENT;
byte[] hash = GetCurrentPrfHash(context, mRecordStream.HandshakeHash, sslSender);
return TlsUtilities.CalculateVerifyData(context, asciiLabel, hash);
}
/**
* Closes this connection.
*
* @throws IOException If something goes wrong during closing.
*/
public virtual void Close()
{
HandleClose(true);
}
protected internal virtual void Flush()
{
mRecordStream.Flush();
}
public virtual bool IsClosed
{
get { return mClosed; }
}
protected virtual short ProcessMaxFragmentLengthExtension(IDictionary clientExtensions, IDictionary serverExtensions,
byte alertDescription)
{
short maxFragmentLength = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(serverExtensions);
if (maxFragmentLength >= 0)
{
if (!MaxFragmentLength.IsValid((byte)maxFragmentLength)
|| (!this.mResumedSession && maxFragmentLength != TlsExtensionsUtilities
.GetMaxFragmentLengthExtension(clientExtensions)))
{
throw new TlsFatalAlert(alertDescription);
}
}
return maxFragmentLength;
}
protected virtual void RefuseRenegotiation()
{
/*
* RFC 5746 4.5 SSLv3 clients that refuse renegotiation SHOULD use a fatal
* handshake_failure alert.
*/
if (TlsUtilities.IsSsl(Context))
throw new TlsFatalAlert(AlertDescription.handshake_failure);
RaiseAlertWarning(AlertDescription.no_renegotiation, "Renegotiation not supported");
}
/**
* Make sure the InputStream 'buf' now empty. Fail otherwise.
*
* @param buf The InputStream to check.
* @throws IOException If 'buf' is not empty.
*/
protected internal static void AssertEmpty(MemoryStream buf)
{
if (buf.Position < buf.Length)
throw new TlsFatalAlert(AlertDescription.decode_error);
}
protected internal static byte[] CreateRandomBlock(bool useGmtUnixTime, IRandomGenerator randomGenerator)
{
byte[] result = new byte[32];
randomGenerator.NextBytes(result);
if (useGmtUnixTime)
{
TlsUtilities.WriteGmtUnixTime(result, 0);
}
return result;
}
protected internal static byte[] CreateRenegotiationInfo(byte[] renegotiated_connection)
{
return TlsUtilities.EncodeOpaque8(renegotiated_connection);
}
protected internal static void EstablishMasterSecret(TlsContext context, TlsKeyExchange keyExchange)
{
byte[] pre_master_secret = keyExchange.GeneratePremasterSecret();
try
{
context.SecurityParameters.masterSecret = TlsUtilities.CalculateMasterSecret(context, pre_master_secret);
}
finally
{
// TODO Is there a way to ensure the data is really overwritten?
/*
* RFC 2246 8.1. The pre_master_secret should be deleted from memory once the
* master_secret has been computed.
*/
if (pre_master_secret != null)
{
Arrays.Fill(pre_master_secret, (byte)0);
}
}
}
/**
* 'sender' only relevant to SSLv3
*/
protected internal static byte[] GetCurrentPrfHash(TlsContext context, TlsHandshakeHash handshakeHash, byte[] sslSender)
{
IDigest d = handshakeHash.ForkPrfHash();
if (sslSender != null && TlsUtilities.IsSsl(context))
{
d.BlockUpdate(sslSender, 0, sslSender.Length);
}
return DigestUtilities.DoFinal(d);
}
protected internal static IDictionary ReadExtensions(MemoryStream input)
{
if (input.Position >= input.Length)
return null;
byte[] extBytes = TlsUtilities.ReadOpaque16(input);
AssertEmpty(input);
MemoryStream buf = new MemoryStream(extBytes, false);
// Integer -> byte[]
IDictionary extensions = Platform.CreateHashtable();
while (buf.Position < buf.Length)
{
int extension_type = TlsUtilities.ReadUint16(buf);
byte[] extension_data = TlsUtilities.ReadOpaque16(buf);
/*
* RFC 3546 2.3 There MUST NOT be more than one extension of the same type.
*/
if (extensions.Contains(extension_type))
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
extensions.Add(extension_type, extension_data);
}
return extensions;
}
protected internal static IList ReadSupplementalDataMessage(MemoryStream input)
{
byte[] supp_data = TlsUtilities.ReadOpaque24(input);
AssertEmpty(input);
MemoryStream buf = new MemoryStream(supp_data, false);
IList supplementalData = Platform.CreateArrayList();
while (buf.Position < buf.Length)
{
int supp_data_type = TlsUtilities.ReadUint16(buf);
byte[] data = TlsUtilities.ReadOpaque16(buf);
supplementalData.Add(new SupplementalDataEntry(supp_data_type, data));
}
return supplementalData;
}
protected internal static void WriteExtensions(Stream output, IDictionary extensions)
{
MemoryStream buf = new MemoryStream();
/*
* NOTE: There are reports of servers that don't accept a zero-length extension as the last
* one, so we write out any zero-length ones first as a best-effort workaround.
*/
WriteSelectedExtensions(buf, extensions, true);
WriteSelectedExtensions(buf, extensions, false);
byte[] extBytes = buf.ToArray();
TlsUtilities.WriteOpaque16(extBytes, output);
}
protected internal static void WriteSelectedExtensions(Stream output, IDictionary extensions, bool selectEmpty)
{
foreach (int extension_type in extensions.Keys)
{
byte[] extension_data = (byte[])extensions[extension_type];
if (selectEmpty == (extension_data.Length == 0))
{
TlsUtilities.CheckUint16(extension_type);
TlsUtilities.WriteUint16(extension_type, output);
TlsUtilities.WriteOpaque16(extension_data, output);
}
}
}
protected internal static void WriteSupplementalData(Stream output, IList supplementalData)
{
MemoryStream buf = new MemoryStream();
foreach (SupplementalDataEntry entry in supplementalData)
{
int supp_data_type = entry.DataType;
TlsUtilities.CheckUint16(supp_data_type);
TlsUtilities.WriteUint16(supp_data_type, buf);
TlsUtilities.WriteOpaque16(entry.Data, buf);
}
byte[] supp_data = buf.ToArray();
TlsUtilities.WriteOpaque24(supp_data, output);
}
protected internal static int GetPrfAlgorithm(TlsContext context, int ciphersuite)
{
bool isTLSv12 = TlsUtilities.IsTlsV12(context);
switch (ciphersuite)
{
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
{
if (isTLSv12)
{
return PrfAlgorithm.tls_prf_sha256;
}
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
{
if (isTLSv12)
{
return PrfAlgorithm.tls_prf_sha384;
}
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
{
if (isTLSv12)
{
return PrfAlgorithm.tls_prf_sha384;
}
return PrfAlgorithm.tls_prf_legacy;
}
default:
{
if (isTLSv12)
{
return PrfAlgorithm.tls_prf_sha256;
}
return PrfAlgorithm.tls_prf_legacy;
}
}
}
internal class HandshakeMessage
: MemoryStream
{
internal HandshakeMessage(byte handshakeType)
: this(handshakeType, 60)
{
}
internal HandshakeMessage(byte handshakeType, int length)
: base(length + 4)
{
TlsUtilities.WriteUint8(handshakeType, this);
// Reserve space for length
TlsUtilities.WriteUint24(0, this);
}
internal void Write(byte[] data)
{
Write(data, 0, data.Length);
}
internal void WriteToRecordStream(TlsProtocol protocol)
{
// Patch actual length back in
long length = Length - 4;
TlsUtilities.CheckUint24(length);
this.Position = 1;
TlsUtilities.WriteUint24((int)length, this);
#if PORTABLE
byte[] buf = ToArray();
int bufLen = buf.Length;
#else
byte[] buf = GetBuffer();
int bufLen = (int)Length;
#endif
protocol.WriteHandshakeMessage(buf, 0, bufLen);
Platform.Dispose(this);
}
}
}
}
| 40.371981 | 149 | 0.57389 | [
"MIT"
] | WamWooWam/Unicord.Legacy | Libraries/BouncyCastle.Crypto/src/crypto/tls/TlsProtocol.cs | 58,501 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using System.Management;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.SPOT.Debugger
{
public class UsbStream : AsyncFileStream
{
// discovery keys
static public readonly string InquiriesInterface = "InquiriesInterface";
static public readonly string DriverVersion = "DriverVersion";
// mandatory property keys
static public readonly string DeviceHash = "DeviceHash";
static public readonly string DisplayName = "DisplayName";
// optional property keys
static public readonly string Manufacturer = "Manufacturer";
static public readonly string Product = "Product";
static public readonly string SerialNumber = "SerialNumber";
static public readonly string VendorId = "VendorId";
static public readonly string ProductId = "ProductId";
internal const int c_DeviceStringBufferSize = 260;
static internal Hashtable s_textProperties = new Hashtable();
static internal Hashtable s_digitProperties = new Hashtable();
static UsbStream()
{
}
internal UsbStream(string port)
: base(port, System.IO.FileShare.None)
{
}
protected static void RetrieveProperties(string hash, ref PortDefinition pd, UsbStream s)
{
IDictionaryEnumerator dict;
dict = s_textProperties.GetEnumerator();
while(dict.MoveNext())
{
pd.Properties.Add(dict.Key, s.RetrieveStringFromDevice((int)dict.Value));
}
dict = s_digitProperties.GetEnumerator();
while(dict.MoveNext())
{
pd.Properties.Add(dict.Key, s.RetrieveIntegerFromDevice((int)dict.Value));
}
}
protected unsafe string RetrieveStringFromDevice(int controlCode)
{
int code = Native.ControlCode(Native.FILE_DEVICE_UNKNOWN, controlCode, Native.METHOD_BUFFERED, Native.FILE_ANY_ACCESS);
string data;
int read;
byte[] buffer = new byte[c_DeviceStringBufferSize];
fixed (byte* p = buffer)
{
if(!Native.DeviceIoControl(m_handle.DangerousGetHandle(), code, null, 0, p, buffer.Length, out read, null) || (read <= 0))
{
data = null;
}
else
{
if(read > (c_DeviceStringBufferSize - 2))
{
read = c_DeviceStringBufferSize - 2;
}
p[read] = 0;
p[read + 1] = 0;
data = new string((char*)p);
}
}
return data;
}
protected unsafe int RetrieveIntegerFromDevice(int controlCode)
{
int code = Native.ControlCode(Native.FILE_DEVICE_UNKNOWN, controlCode, Native.METHOD_BUFFERED, Native.FILE_ANY_ACCESS);
int read;
int digits = 0;
if(!Native.DeviceIoControl(m_handle.DangerousGetHandle(), code, null, 0, (byte*)&digits, sizeof(int), out read, null) || (read <= 0))
{
digits = -1;
}
return digits;
}
}
}
| 30 | 200 | 0.639601 | [
"Apache-2.0"
] | fburel/Monkey.Robotics | Source/Xamarin Studio Microframework Add-in/Add-In Project/Debugger/UsbStream.cs | 3,510 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2018 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
/*----------------------------------------------------------------
Copyright (C) 2018 Senparc
文件名:Register.cs
文件功能描述:注册小程序信息
创建标识:Senparc - 20170302
修改标识:Senparc - 20180802
修改描述:添加自动 根据 SenparcWeixinSetting 注册 RegisterWxOpenAccount() 方法
----------------------------------------------------------------*/
using Senparc.Weixin.Exceptions;
using Senparc.CO2NET.RegisterServices;
using System;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.WxOpen
{
/// <summary>
/// 注册小程序
/// </summary>
public static class Register
{
/// <summary>
/// 注册小程序信息
/// </summary>
/// <param name="registerService">RegisterService</param>
/// <param name="appId">微信公众号后台的【开发】>【基本配置】中的“AppID(应用ID)”</param>
/// <param name="appSecret">微信公众号后台的【开发】>【基本配置】中的“AppSecret(应用密钥)”</param>
/// <param name="name">标记AccessToken名称(如微信公众号名称),帮助管理员识别</param>
/// <returns></returns>
[Obsolete("请统一使用Senparc.Weixin.MP.Register.RegisterMpAccount()方法进行注册!")]
public static IRegisterService RegisterWxOpenAccount(this IRegisterService registerService, string appId, string appSercet, string name = null)
{
throw new WeixinException("请统一使用Senparc.Weixin.MP.Register.RegisterMpAccount()方法进行注册!");
}
/// <summary>
/// 根据 SenparcWeixinSetting 自动注册小程序信息
/// </summary>
/// <param name="registerService">RegisterService</param>
/// <param name="weixinSettingForWxOpen">SenparcWeixinSetting</param>
/// <param name="name">统一标识,如果为null,则使用 SenparcWeixinSetting.ItemKey </param>
/// <returns></returns>
public static IRegisterService RegisterWxOpenAccount(this IRegisterService registerService, ISenparcWeixinSettingForWxOpen weixinSettingForWxOpen, string name = null)
{
AccessTokenContainer.Register(weixinSettingForWxOpen.WxOpenAppId, weixinSettingForWxOpen.WxOpenAppSecret, name ?? weixinSettingForWxOpen.ItemKey);
return registerService;
}
}
}
| 38.948052 | 174 | 0.644215 | [
"Apache-2.0"
] | 253437873/WeiXinMPSDK | src/Senparc.Weixin.WxOpen/src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Register.cs | 3,349 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace CloudflareWorkersKvExplorer.Website
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.388889 | 76 | 0.644647 | [
"MIT"
] | aozd4v/cloudflare-workers-kv-explorer | src/CloudflareWorkersKvExplorer.Website/Program.cs | 441 | C# |
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Cimbalino.Phone.Toolkit.Services;
using IF.Lastfm.Core.Api;
using IF.Lastfm.Core.Objects;
using IF.Lastfm.Demo.Apollo.TestPages.ViewModels;
namespace IF.Lastfm.Demo.Apollo.ViewModels.UserApi
{
public class RecentStationsTestViewModel : BaseViewModel
{
private LastAuth _lastAuth;
private bool _inProgress;
private PageProgress _stationPageProgress;
private ObservableCollection<LastStation> _stations;
#region Properties
public LastAuth Auth
{
get { return _lastAuth; }
set
{
if (Equals(value, _lastAuth))
{
return;
}
_lastAuth = value;
OnPropertyChanged();
}
}
public bool InProgress
{
get { return _inProgress; }
set
{
if (value.Equals(_inProgress))
{
return;
}
_inProgress = value;
OnPropertyChanged();
}
}
public ObservableCollection<LastStation> Stations
{
get { return _stations; }
set
{
if (Equals(value, _stations)) return;
_stations = value;
OnPropertyChanged();
}
}
#endregion
public RecentStationsTestViewModel()
{
_stationPageProgress = new PageProgress();
Stations = new ObservableCollection<LastStation>();
}
public async Task NavigatedTo()
{
await Authenticate();
}
private async Task Authenticate()
{
var appsettings = new ApplicationSettingsService();
var apikey = appsettings.Get<string>("apikey");
var apisecret = appsettings.Get<string>("apisecret");
var username = appsettings.Get<string>("username");
var pass = appsettings.Get<string>("pass");
var auth = new LastAuth(apikey, apisecret);
InProgress = true;
await auth.GetSessionTokenAsync(username, pass);
InProgress = false;
Auth = auth;
}
public async Task GetRecentStations()
{
if (!_stationPageProgress.CanGoToNextPage())
{
return;
}
InProgress = true;
var userApi = new Core.Api.UserApi(Auth);
var response = await userApi.GetRecentStations(Auth.UserSession.Username, _stationPageProgress.ExpectedPage, 5);
_stationPageProgress.PageLoaded(response.Success);
if (response.Success)
{
foreach (var s in response.Content)
{
Stations.Add(s);
}
}
_stationPageProgress.TotalPages = response.TotalPages;
InProgress = false;
}
}
} | 25.950413 | 124 | 0.519745 | [
"MIT"
] | PCurd/lastfm | src/IF.Lastfm.Demo.Apollo/ViewModels/UserApi/RecentStationsTestViewModel.cs | 3,140 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FaturamentoWF
{
public class Produto
{
public int ID { get; set; }
public string Nome { get; set; }
public double Preco { get; set; }
public string Tipo { get; set; }
public int Quantidade { get; set; }
public Produto(string nome, double preco, string tipo, int id)
{
Nome = nome;
Preco = preco;
Tipo = tipo;
ID = id;
}
}
}
| 22.192308 | 70 | 0.559792 | [
"MIT"
] | rafaelmmayer/Controle-de-Vendas | FaturamentoWF/Produto.cs | 579 | C# |
using NUnit.Framework;
namespace CoCSharp.Test.Data.AssetProviders
{
[TestFixture]
public class CsvDataTableAssetProviderTests
{
}
}
| 13.818182 | 47 | 0.723684 | [
"MIT"
] | FICTURE7/CoCSharp | tests/Data/AssetProviders/CsvDataTableAssetProviderTests.cs | 154 | C# |
#if !UNITY_WSA && !UNITY_WP8
using System;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using PlayFab.SharedModels;
#if !DISABLE_PLAYFABCLIENT_API
using PlayFab.ClientModels;
#endif
namespace PlayFab.Internal
{
public class PlayFabWebRequest : ITransportPlugin
{
/// <summary>
/// Disable encryption certificate validation within PlayFabWebRequest using this request.
/// This is not generally recommended.
/// As of early 2018:
/// None of the built-in Unity mechanisms validate the certificate, using .Net 3.5 equivalent runtime
/// It is also not currently feasible to provide a single cross platform solution that will correctly validate a certificate.
/// The Risk:
/// All Unity HTTPS mechanisms are vulnerable to Man-In-The-Middle attacks.
/// The only more-secure option is to define a custom CustomCertValidationHook, specifically tailored to the platforms you support,
/// which validate the cert based on a list of trusted certificate providers. This list of providers must be able to update itself, as the
/// base certificates for those providers will also expire and need updating on a regular basis.
/// </summary>
public static void SkipCertificateValidation()
{
var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true
ServicePointManager.ServerCertificateValidationCallback = rcvc;
certValidationSet = true;
}
/// <summary>
/// Provide PlayFabWebRequest with a custom ServerCertificateValidationCallback which can be used to validate the PlayFab encryption certificate.
/// Please do not:
/// - Hard code the current PlayFab certificate information - The PlayFab certificate updates itself on a regular schedule, and your game will fail and require a republish to fix
/// - Hard code a list of static certificate authorities - Any single exported list of certificate authorities will become out of date, and have the same problem when the CA cert expires
/// Real solution:
/// - A mechanism where a valid certificate authority list can be securely downloaded and updated without republishing the client when existing certificates expire.
/// </summary>
public static System.Net.Security.RemoteCertificateValidationCallback CustomCertValidationHook
{
set
{
ServicePointManager.ServerCertificateValidationCallback = value;
certValidationSet = true;
}
}
private static readonly Queue<Action> ResultQueueTransferThread = new Queue<Action>();
private static readonly Queue<Action> ResultQueueMainThread = new Queue<Action>();
private static readonly List<CallRequestContainer> ActiveRequests = new List<CallRequestContainer>();
private static bool certValidationSet = false;
private static Thread _requestQueueThread;
private static readonly object _ThreadLock = new object();
private static readonly TimeSpan ThreadKillTimeout = TimeSpan.FromSeconds(60);
private static DateTime _threadKillTime = DateTime.UtcNow + ThreadKillTimeout; // Kill the thread after 1 minute of inactivity
private static bool _isApplicationPlaying;
private static int _activeCallCount;
private static string _unityVersion;
private bool _isInitialized = false;
public bool IsInitialized { get { return _isInitialized; } }
public void Initialize()
{
SetupCertificates();
_isApplicationPlaying = true;
_unityVersion = Application.unityVersion;
_isInitialized = true;
}
public void OnDestroy()
{
_isApplicationPlaying = false;
lock (ResultQueueTransferThread)
{
ResultQueueTransferThread.Clear();
}
lock (ActiveRequests)
{
ActiveRequests.Clear();
}
lock (_ThreadLock)
{
_requestQueueThread = null;
}
}
private void SetupCertificates()
{
// These are performance Optimizations for HttpWebRequests.
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.Expect100Continue = false;
if (!certValidationSet)
{
Debug.LogWarning("PlayFab API calls will likely fail because you have not set up a HttpWebRequest certificate validation mechanism");
Debug.LogWarning("Please set a validation callback into PlayFab.Internal.PlayFabWebRequest.CustomCertValidationHook, or set PlayFab.Internal.PlayFabWebRequest.SkipCertificateValidation()");
}
}
/// <summary>
/// This disables certificate validation, if it's been activated by a customer via SkipCertificateValidation()
/// </summary>
private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
public void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This needs to be improved to use a decent thread-pool, but it can be improved invisibly later
var newThread = new Thread(() => SimpleHttpsWorker("GET", fullUrl, null, successCallback, errorCallback));
newThread.Start();
}
public void SimplePutCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This needs to be improved to use a decent thread-pool, but it can be improved invisibly later
var newThread = new Thread(() => SimpleHttpsWorker("PUT", fullUrl, payload, successCallback, errorCallback));
newThread.Start();
}
public void SimplePostCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This needs to be improved to use a decent thread-pool, but it can be improved invisibly later
var newThread = new Thread(() => SimpleHttpsWorker("POST", fullUrl, payload, successCallback, errorCallback));
newThread.Start();
}
private void SimpleHttpsWorker(string httpMethod, string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This should also use a pooled HttpWebRequest object, but that too can be improved invisibly later
var httpRequest = (HttpWebRequest)WebRequest.Create(fullUrl);
httpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion;
httpRequest.Method = httpMethod;
httpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive;
httpRequest.Timeout = PlayFabSettings.RequestTimeout;
httpRequest.AllowWriteStreamBuffering = false;
httpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout;
if (payload != null)
{
httpRequest.ContentLength = payload.LongLength;
using (var stream = httpRequest.GetRequestStream())
{
stream.Write(payload, 0, payload.Length);
}
}
try
{
var response = httpRequest.GetResponse();
byte[] output = null;
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
output = new byte[response.ContentLength];
responseStream.Read(output, 0, output.Length);
}
}
successCallback(output);
}
catch (WebException webException)
{
try
{
using (var responseStream = webException.Response.GetResponseStream())
{
if (responseStream != null)
using (var stream = new StreamReader(responseStream))
errorCallback(stream.ReadToEnd());
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void MakeApiCall(object reqContainerObj)
{
CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj;
reqContainer.HttpState = HttpRequestState.Idle;
lock (ActiveRequests)
{
ActiveRequests.Insert(0, reqContainer);
}
ActivateThreadWorker();
}
private static void ActivateThreadWorker()
{
lock (_ThreadLock)
{
if (_requestQueueThread != null)
{
return;
}
_requestQueueThread = new Thread(WorkerThreadMainLoop);
_requestQueueThread.Start();
}
}
private static void WorkerThreadMainLoop()
{
try
{
bool active;
lock (_ThreadLock)
{
// Kill the thread after 1 minute of inactivity
_threadKillTime = DateTime.UtcNow + ThreadKillTimeout;
}
List<CallRequestContainer> localActiveRequests = new List<CallRequestContainer>();
do
{
//process active requests
lock (ActiveRequests)
{
localActiveRequests.AddRange(ActiveRequests);
ActiveRequests.Clear();
_activeCallCount = localActiveRequests.Count;
}
var activeCalls = localActiveRequests.Count;
for (var i = activeCalls - 1; i >= 0; i--) // We must iterate backwards, because we remove at index i in some cases
{
switch (localActiveRequests[i].HttpState)
{
case HttpRequestState.Error:
localActiveRequests.RemoveAt(i); break;
case HttpRequestState.Idle:
Post(localActiveRequests[i]); break;
case HttpRequestState.Sent:
if (localActiveRequests[i].HttpRequest.HaveResponse) // Else we'll try again next tick
ProcessHttpResponse(localActiveRequests[i]);
break;
case HttpRequestState.Received:
ProcessJsonResponse(localActiveRequests[i]);
localActiveRequests.RemoveAt(i);
break;
}
}
#region Expire Thread.
// Check if we've been inactive
lock (_ThreadLock)
{
var now = DateTime.UtcNow;
if (activeCalls > 0 && _isApplicationPlaying)
{
// Still active, reset the _threadKillTime
_threadKillTime = now + ThreadKillTimeout;
}
// Kill the thread after 1 minute of inactivity
active = now <= _threadKillTime;
if (!active)
{
_requestQueueThread = null;
}
// This thread will be stopped, so null this now, inside lock (_threadLock)
}
#endregion
Thread.Sleep(1);
} while (active);
}
catch (Exception e)
{
Debug.LogException(e);
_requestQueueThread = null;
}
}
private static void Post(CallRequestContainer reqContainer)
{
try
{
reqContainer.HttpRequest = (HttpWebRequest)WebRequest.Create(reqContainer.FullUrl);
reqContainer.HttpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion;
reqContainer.HttpRequest.SendChunked = false;
// Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's.
reqContainer.HttpRequest.Proxy = null;
foreach (var pair in reqContainer.RequestHeaders)
reqContainer.HttpRequest.Headers.Add(pair.Key, pair.Value);
reqContainer.HttpRequest.ContentType = "application/json";
reqContainer.HttpRequest.Method = "POST";
reqContainer.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive;
reqContainer.HttpRequest.Timeout = PlayFabSettings.RequestTimeout;
reqContainer.HttpRequest.AllowWriteStreamBuffering = false;
reqContainer.HttpRequest.Proxy = null;
reqContainer.HttpRequest.ContentLength = reqContainer.Payload.LongLength;
reqContainer.HttpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout;
//Debug.Log("Get Stream");
// Get Request Stream and send data in the body.
using (var stream = reqContainer.HttpRequest.GetRequestStream())
{
//Debug.Log("Post Stream");
stream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
//Debug.Log("After Post stream");
}
reqContainer.HttpState = HttpRequestState.Sent;
}
catch (WebException e)
{
reqContainer.JsonResponse = ResponseToString(e.Response) ?? e.Status + ": WebException making http request to: " + reqContainer.FullUrl;
var enhancedError = new WebException(reqContainer.JsonResponse, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
catch (Exception e)
{
reqContainer.JsonResponse = "Unhandled exception in Post : " + reqContainer.FullUrl;
var enhancedError = new Exception(reqContainer.JsonResponse, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
private static void ProcessHttpResponse(CallRequestContainer reqContainer)
{
try
{
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
#endif
// Get and check the response
var httpResponse = (HttpWebResponse)reqContainer.HttpRequest.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
reqContainer.JsonResponse = ResponseToString(httpResponse);
}
if (httpResponse.StatusCode != HttpStatusCode.OK || string.IsNullOrEmpty(reqContainer.JsonResponse))
{
reqContainer.JsonResponse = reqContainer.JsonResponse ?? "No response from server";
QueueRequestError(reqContainer);
return;
}
else
{
// Response Recieved Successfully, now process.
}
reqContainer.HttpState = HttpRequestState.Received;
}
catch (Exception e)
{
var msg = "Unhandled exception in ProcessHttpResponse : " + reqContainer.FullUrl;
reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg;
var enhancedError = new Exception(msg, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
/// <summary>
/// Set the reqContainer into an error state, and queue it to invoke the ErrorCallback for that request
/// </summary>
private static void QueueRequestError(CallRequestContainer reqContainer)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData); // Decode the server-json error
reqContainer.HttpState = HttpRequestState.Error;
lock (ResultQueueTransferThread)
{
//Queue The result callbacks to run on the main thread.
ResultQueueTransferThread.Enqueue(() =>
{
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
if (reqContainer.ErrorCallback != null)
reqContainer.ErrorCallback(reqContainer.Error);
});
}
}
private static void ProcessJsonResponse(CallRequestContainer reqContainer)
{
try
{
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
var httpResult = serializer.DeserializeObject<HttpResponseObject>(reqContainer.JsonResponse);
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
#endif
//This would happen if playfab returned a 500 internal server error or a bad json response.
if (httpResult == null || httpResult.code != 200)
{
QueueRequestError(reqContainer);
return;
}
reqContainer.JsonResponse = serializer.SerializeObject(httpResult.data);
reqContainer.DeserializeResultJson(); // Assigns Result with a properly typed object
reqContainer.ApiResult.Request = reqContainer.ApiRequest;
reqContainer.ApiResult.CustomData = reqContainer.CustomData;
if(_isApplicationPlaying)
{
PlayFabHttp.instance.OnPlayFabApiResult(reqContainer);
}
#if !DISABLE_PLAYFABCLIENT_API
lock (ResultQueueTransferThread)
{
ResultQueueTransferThread.Enqueue(() => { PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult, reqContainer.settings, reqContainer.instanceApi); });
}
#endif
lock (ResultQueueTransferThread)
{
//Queue The result callbacks to run on the main thread.
ResultQueueTransferThread.Enqueue(() =>
{
#if PLAYFAB_REQUEST_TIMING
reqContainer.Stopwatch.Stop();
reqContainer.Timing.MainThreadRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
PlayFabHttp.SendRequestTiming(reqContainer.Timing);
#endif
try
{
PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
reqContainer.InvokeSuccessCallback();
}
catch (Exception e)
{
Debug.LogException(e); // Log the user's callback exception back to them without halting PlayFabHttp
}
});
}
}
catch (Exception e)
{
var msg = "Unhandled exception in ProcessJsonResponse : " + reqContainer.FullUrl;
reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg;
var enhancedError = new Exception(msg, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
public void Update()
{
lock (ResultQueueTransferThread)
{
while (ResultQueueTransferThread.Count > 0)
{
var actionToQueue = ResultQueueTransferThread.Dequeue();
ResultQueueMainThread.Enqueue(actionToQueue);
}
}
while (ResultQueueMainThread.Count > 0)
{
var finishedRequest = ResultQueueMainThread.Dequeue();
finishedRequest();
}
}
private static string ResponseToString(WebResponse webResponse)
{
if (webResponse == null)
return null;
try
{
using (var responseStream = webResponse.GetResponseStream())
{
if (responseStream == null)
return null;
using (var stream = new StreamReader(responseStream))
{
return stream.ReadToEnd();
}
}
}
catch (WebException webException)
{
try
{
using (var responseStream = webException.Response.GetResponseStream())
{
if (responseStream == null)
return null;
using (var stream = new StreamReader(responseStream))
{
return stream.ReadToEnd();
}
}
}
catch (Exception e)
{
Debug.LogException(e);
return null;
}
}
catch (Exception e)
{
Debug.LogException(e);
return null;
}
}
public int GetPendingMessages()
{
var count = 0;
lock (ActiveRequests)
count += ActiveRequests.Count + _activeCallCount;
lock (ResultQueueTransferThread)
count += ResultQueueTransferThread.Count;
return count;
}
}
}
#endif
| 42.798521 | 257 | 0.557096 | [
"MIT"
] | 101Bunker/1017 | Assets/PlayFabSDK/Shared/Internal/PlayFabHttp/PlayFabWebRequest.cs | 23,154 | C# |
// Copyright (c) 2021 homuler
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
using Mediapipe;
using NUnit.Framework;
namespace Tests
{
public class CalculatorGraphTest
{
private const string _ValidConfigText = @"node {
calculator: ""PassThroughCalculator""
input_stream: ""in""
output_stream: ""out1""
}
node {
calculator: ""PassThroughCalculator""
input_stream: ""out1""
output_stream: ""out""
}
input_stream: ""in""
output_stream: ""out""
";
#region Constructor
[Test]
public void Ctor_ShouldInstantiateCalculatorGraph_When_CalledWithNoArguments()
{
Assert.DoesNotThrow(() =>
{
var graph = new CalculatorGraph();
graph.Dispose();
});
}
[Test]
public void Ctor_ShouldInstantiateCalculatorGraph_When_CalledWithConfigText()
{
using (var graph = new CalculatorGraph(_ValidConfigText))
{
var config = graph.Config();
Assert.AreEqual(config.InputStream[0], "in");
Assert.AreEqual(config.OutputStream[0], "out");
}
}
#endregion
#region #isDisposed
[Test]
public void IsDisposed_ShouldReturnFalse_When_NotDisposedYet()
{
using (var graph = new CalculatorGraph())
{
Assert.False(graph.isDisposed);
}
}
[Test]
public void IsDisposed_ShouldReturnTrue_When_AlreadyDisposed()
{
var graph = new CalculatorGraph();
graph.Dispose();
Assert.True(graph.isDisposed);
}
#endregion
#region #Initialize
[Test]
public void Initialize_ShouldReturnOk_When_CalledWithConfig_And_ConfigIsNotSet()
{
using (var graph = new CalculatorGraph())
{
using (var status = graph.Initialize(CalculatorGraphConfig.Parser.ParseFromTextFormat(_ValidConfigText)))
{
Assert.True(status.Ok());
}
var config = graph.Config();
Assert.AreEqual(config.InputStream[0], "in");
Assert.AreEqual(config.OutputStream[0], "out");
}
}
[Test]
public void Initialize_ShouldReturnInternalError_When_CalledWithConfig_And_ConfigIsSet()
{
using (var graph = new CalculatorGraph(_ValidConfigText))
{
using (var status = graph.Initialize(CalculatorGraphConfig.Parser.ParseFromTextFormat(_ValidConfigText)))
{
Assert.AreEqual(status.Code(), Status.StatusCode.Internal);
}
}
}
[Test]
public void Initialize_ShouldReturnOk_When_CalledWithConfigAndSidePacket_And_ConfigIsNotSet()
{
using (var sidePacket = new SidePacket())
{
sidePacket.Emplace("flag", new BoolPacket(true));
using (var graph = new CalculatorGraph())
{
var config = CalculatorGraphConfig.Parser.ParseFromTextFormat(_ValidConfigText);
using (var status = graph.Initialize(config, sidePacket))
{
Assert.True(status.Ok());
}
}
}
}
[Test]
public void Initialize_ShouldReturnInternalError_When_CalledWithConfigAndSidePacket_And_ConfigIsSet()
{
using (var sidePacket = new SidePacket())
{
sidePacket.Emplace("flag", new BoolPacket(true));
using (var graph = new CalculatorGraph(_ValidConfigText))
{
var config = CalculatorGraphConfig.Parser.ParseFromTextFormat(_ValidConfigText);
using (var status = graph.Initialize(config, sidePacket))
{
Assert.AreEqual(status.Code(), Status.StatusCode.Internal);
}
}
}
}
#endregion
#region lifecycle
[Test]
public void LifecycleMethods_ShouldControlGraphLifeCycle()
{
using (var graph = new CalculatorGraph(_ValidConfigText))
{
Assert.True(graph.StartRun().Ok());
Assert.False(graph.GraphInputStreamsClosed());
Assert.True(graph.WaitUntilIdle().Ok());
Assert.True(graph.CloseAllPacketSources().Ok());
Assert.True(graph.GraphInputStreamsClosed());
Assert.True(graph.WaitUntilDone().Ok());
Assert.False(graph.HasError());
}
}
[Test]
public void Cancel_ShouldCancelGraph()
{
using (var graph = new CalculatorGraph(_ValidConfigText))
{
Assert.True(graph.StartRun().Ok());
graph.Cancel();
Assert.AreEqual(graph.WaitUntilDone().Code(), Status.StatusCode.Cancelled);
}
}
#endregion
}
}
| 26.727811 | 113 | 0.64224 | [
"MIT"
] | 62-26Nonny/MuscleLand | Packages/com.github.homuler.mediapipe/Tests/EditMode/Framework/CalculatorGraphTest.cs | 4,517 | C# |
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE in the project root for license information.
using graph_tutorial.Models;
using System.Collections.Generic;
using System.Web.Mvc;
namespace graph_tutorial.Controllers
{
public abstract class BaseController : Controller
{
protected void Flash(string message, string debug=null)
{
var alerts = TempData.ContainsKey(Alert.AlertKey) ?
(List<Alert>)TempData[Alert.AlertKey] :
new List<Alert>();
alerts.Add(new Alert
{
Message = message,
Debug = debug
});
TempData[Alert.AlertKey] = alerts;
}
}
} | 29.88 | 138 | 0.607764 | [
"MIT"
] | abebatista/msgraph-training-aspnetmvcapp | Demos/01-create-app/graph-tutorial/Controllers/BaseController.cs | 749 | C# |
// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
/// <summary>
/// Looks up an alias (identifier in front of :: operator).
/// </summary>
/// <remarks>
/// The member lookup performed by the :: operator is handled
/// by <see cref="MemberTypeOrNamespaceReference"/>.
/// </remarks>
public class AliasNamespaceReference : ITypeOrNamespaceReference
{
readonly UsingScope parentUsingScope;
readonly string identifier;
public AliasNamespaceReference(string identifier, UsingScope parentUsingScope)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
this.identifier = identifier;
this.parentUsingScope = parentUsingScope;
}
public ResolveResult DoResolve(ITypeResolveContext context)
{
CSharpResolver r = new CSharpResolver(context);
r.UsingScope = parentUsingScope;
return r.ResolveAlias(identifier);
}
public NamespaceResolveResult ResolveNamespace(ITypeResolveContext context)
{
return DoResolve(context) as NamespaceResolveResult;
}
public IType Resolve(ITypeResolveContext context)
{
return SharedTypes.UnknownType;
}
public override string ToString()
{
return identifier + "::";
}
}
}
| 28.038462 | 108 | 0.74417 | [
"MIT"
] | arturek/ILSpy | NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/AliasNamespaceReference.cs | 1,460 | C# |
using System;
using System.Collections.Generic;
using Ultraviolet.Core;
namespace Ultraviolet.Graphics.Graphics3D
{
/// <summary>
/// Represents a collection of 3D primitives and associated rendering state.
/// </summary>
public sealed class ModelMesh
{
/// <summary>
/// Initializes a new instance of the <see cref="ModelMesh"/> class.
/// </summary>
/// <param name="logicalIndex">The logical index of the mesh within its parent model.</param>
/// <param name="name">The mesh's name.</param>
/// <param name="geometries">The mesh's list of geometries.</param>
public ModelMesh(Int32 logicalIndex, String name, IList<ModelMeshGeometry> geometries)
{
this.LogicalIndex = logicalIndex;
this.Name = name;
this.Geometries = new ModelMeshGeometryCollection(geometries);
}
/// <summary>
/// Gets the logical index of the mesh within its parent model.
/// </summary>
public Int32 LogicalIndex { get; }
/// <summary>
/// Gets the mesh's name.
/// </summary>
public String Name { get; }
/// <summary>
/// Gets the <see cref="Model"/> that contains this mesh.
/// </summary>
public Model ParentModel { get; private set; }
/// <summary>
/// Gets the <see cref="ModelScene"/> that contains this mesh.
/// </summary>
public ModelScene ParentModelScene { get; private set; }
/// <summary>
/// Gets the <see cref="ModelNode"/> that contains this mesh.
/// </summary>
public ModelNode ParentModelNode { get; private set; }
/// <summary>
/// Gets the mesh's collection of geometries.
/// </summary>
public ModelMeshGeometryCollection Geometries { get; }
/// <summary>
/// Sets the mesh's parent model.
/// </summary>
/// <param name="parent">The mesh's parent model.</param>
internal void SetParentModel(Model parent)
{
Contract.Require(parent, nameof(parent));
if (this.ParentModel != null)
throw new InvalidOperationException(UltravioletStrings.ModelParentLinkAlreadyExists);
this.ParentModel = parent;
}
/// <summary>
/// Sets the mesh's parent scene.
/// </summary>
/// <param name="parent">The mesh's parent scene.</param>
internal void SetParentModelScene(ModelScene parent)
{
Contract.Require(parent, nameof(parent));
if (this.ParentModelScene != null)
throw new InvalidOperationException(UltravioletStrings.ModelParentLinkAlreadyExists);
this.ParentModelScene = parent;
}
/// <summary>
/// Sets the mesh's parent node.
/// </summary>
/// <param name="parent">The mesh's parent node.</param>
internal void SetParentModelNode(ModelNode parent)
{
Contract.Require(parent, nameof(parent));
if (this.ParentModelNode != null)
throw new InvalidOperationException(UltravioletStrings.ModelParentLinkAlreadyExists);
this.ParentModelNode = parent;
}
}
} | 34.010309 | 101 | 0.586844 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet/Shared/Graphics/Graphics3D/ModelMesh.cs | 3,301 | C# |
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
//using Microsoft.ProjectOxford.Vision;
//using Microsoft.ProjectOxford.Vision.Contract;
using Plugin.Media;
//using Plugin.TextToSpeech;
using Plugin.Media.Abstractions;
using Xamarin.Forms;
namespace ASampleApp.ViewModel
{
public class TextToSpeechViewModel : BaseViewModel
{
#region Fields
//int _isInternetConnectionInUseCount;
string _spokenTextLabelText;
//string _activityIndicatorLabelText;
//bool _isActivityIndicatorDisplayed;
bool _isInternetConnectionInUse;
Command _takePictureButtonCommand;
Image _dogImage;
#endregion
#region Events
//public event EventHandler OCRFailed;
//public event EventHandler SpellCheckFailed;
public event EventHandler NoCameraDetected;
//public event EventHandler InvalidComputerVisionAPIKey;
//public event EventHandler InternetConnectionUnavailable;
#endregion
#region Properties
public Command TakePictureButtonCommand => _takePictureButtonCommand ??
(_takePictureButtonCommand = new Command(async () => await ExecuteTakePictureButtonCommand()));
public bool IsInternetConnectionInUse
{
get => _isInternetConnectionInUse;
set => SetProperty(ref _isInternetConnectionInUse, value);
}
public string SpokenTextLabelText
{
get => _spokenTextLabelText;
set => SetProperty(ref _spokenTextLabelText, value);
}
public Image DogImage
{
get => _dogImage;
set => SetProperty(ref _dogImage, value);
}
//public string ActivityIndicatorLabelText
//{
// get => _activityIndicatorLabelText;
// set => SetProperty(ref _activityIndicatorLabelText, value);
//}
//public bool IsActivityIndicatorDisplayed
//{
// get => _isActivityIndicatorDisplayed;
// set => SetProperty(ref _isActivityIndicatorDisplayed, value);
//}
#endregion
#region Methods
async Task ExecuteTakePictureButtonCommand()
{
SpokenTextLabelText = string.Empty;
await ExecuteNewPictureWorkflow();
}
async Task ExecuteNewPictureWorkflow()
{
var mediaFile = await GetMediaFileFromCamera(Guid.NewGuid().ToString());
if (mediaFile == null)
{
OnDisplayNoCameraDetected();
return;
}
//Need to display media file in page!!>>>
//var ocrResults = await GetOcrResultsFromMediaFile(mediaFile);
//if (ocrResults == null)
//{
// OnOCRFailed();
// return;
//}
//var listOfStringsFromOcrResults = GetTextFromOcrResults(ocrResults);
//var spellCheckedlistOfStringsFromOcrResults = await GetSpellCheckedStringList(listOfStringsFromOcrResults);
//if (spellCheckedlistOfStringsFromOcrResults == null)
//{
// OnSpellCheckFailed();
// return;
//}
//SpeakText(spellCheckedlistOfStringsFromOcrResults);
}
async Task<MediaFile> GetMediaFileFromCamera(string photoName)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
return null;
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
Directory = "XamSpeak",
Name = photoName,
PhotoSize = PhotoSize.Small,
DefaultCamera = CameraDevice.Rear,
});
Image tempImage = new Image();
tempImage.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
this.DogImage = tempImage;
// 1 = 1;
return file;
}
//async Task<OcrResults> GetOcrResultsFromMediaFile(MediaFile mediaFile)
//{
//ActivateActivityIndicator("Reading Text");
//try
//{
//var visionClient = new VisionServiceClient(CognitiveServicesConstants.ComputerVisionAPIKey);
// var ocrResults = await visionClient.RecognizeTextAsync(ConverterHelpers.ConvertMediaFileToStream(mediaFile, false));
// return ocrResults;
// }
// catch (Exception e)
// {
// DebugHelpers.PrintException(e);
// if ((e is ClientException) && ((ClientException)e).HttpStatus == 0)
// OnInvalidComputerVisionAPIKey();
// else
// OnInternetConnectionUnavailable();
// return null;
// }
// finally
// {
// DeactivateActivityIndicator();
// }
//}
//List<string> GetTextFromOcrResults(OcrResults ocrResults)
//{
// var ocrModelList = new List<OcrTextLocationModel>();
// foreach (Region region in ocrResults.Regions)
// {
// foreach (Line line in region.Lines)
// {
// var lineStringBuilder = new StringBuilder();
// foreach (Word word in line.Words)
// {
// lineStringBuilder.Append(word.Text);
// lineStringBuilder.Append(" ");
// }
// ocrModelList.Add(new OcrTextLocationModel(lineStringBuilder.ToString(), line.Rectangle.Top, line.Rectangle.Left));
// }
// }
// return CreateStringFromOcrModelList(ocrModelList);
//}
//List<string> CreateStringFromOcrModelList(List<OcrTextLocationModel> ocrModelList)
//{
// var stringList = new List<string>();
// var stringBuilder = new StringBuilder();
// var maximumTop = ocrModelList.OrderBy(x => x.Top).FirstOrDefault().Top;
// var sortedOcrModelList = ocrModelList.OrderBy(x => x.Top).ThenBy(x => x.Left).ToList();
// var previousTop = 0.0;
// foreach (OcrTextLocationModel ocrModel in sortedOcrModelList)
// {
// var percentageBelowPreviousOcrModel = (ocrModel.Top - previousTop) / maximumTop;
// if (percentageBelowPreviousOcrModel <= 0.01)
// {
// stringBuilder.Append(" ");
// stringBuilder.Append($"{ocrModel.Text}");
// }
// else
// {
// if (!string.IsNullOrEmpty(stringBuilder.ToString()))
// stringList.Add(stringBuilder.ToString());
// stringBuilder.Clear();
// stringBuilder.Append($"{ocrModel.Text}");
// }
// previousTop = ocrModel.Top;
// if (sortedOcrModelList.LastOrDefault().Equals(ocrModel))
// stringList.Add(stringBuilder.ToString());
// }
// return stringList;
//}
//async Task<List<string>> GetSpellCheckedStringList(List<string> stringList)
//{
//ActivateActivityIndicator("Performing Spell Check");
//int listIndex = 0;
//var correctedLineItemList = new List<string>();
//try
//{
// foreach (string lineItem in stringList)
// {
// correctedLineItemList.Add(lineItem);
// var misspelledWordList = await HttpHelpers.SpellCheckString(lineItem);
// if (misspelledWordList == null)
// return null;
// foreach (var misspelledWord in misspelledWordList)
// {
// var firstSuggestion = misspelledWord.Suggesstions.FirstOrDefault();
// double.TryParse(firstSuggestion?.ConfidenceScore, out double confidenceScore);
// if (confidenceScore > 0.80)
// {
// var correctedLineItem = correctedLineItemList[listIndex].Replace(misspelledWord.MisspelledWord, firstSuggestion?.Suggestion);
// correctedLineItemList[listIndex] = correctedLineItem;
// }
// }
// listIndex++;
// }
//}
//finally
//{
// DeactivateActivityIndicator();
//}
//return correctedLineItemList;
//}
//void SpeakText(List<string> textList)
//{
// var stringBuilder = new StringBuilder();
// foreach (var lineOfText in textList)
// {
// stringBuilder.AppendLine(lineOfText);
// SpokenTextLabelText = stringBuilder.ToString();
// CrossTextToSpeech.Current.Speak(lineOfText, true);
// }
//}
//void ActivateActivityIndicator(string activityIndicatorLabelText)
//{
// IsInternetConnectionInUse = ++_isInternetConnectionInUseCount > 0;
// IsActivityIndicatorDisplayed = true;
// ActivityIndicatorLabelText = activityIndicatorLabelText;
//}
//void DeactivateActivityIndicator()
//{
// IsInternetConnectionInUse = --_isInternetConnectionInUseCount != 0;
// IsActivityIndicatorDisplayed = false;
// ActivityIndicatorLabelText = default(string);
//}
void OnDisplayNoCameraDetected() =>
NoCameraDetected?.Invoke(this, EventArgs.Empty);
//void OnOCRFailed() =>
// OCRFailed?.Invoke(this, EventArgs.Empty);
//void OnSpellCheckFailed() =>
// SpellCheckFailed?.Invoke(this, EventArgs.Empty);
//void OnInvalidComputerVisionAPIKey() =>
//InvalidComputerVisionAPIKey?.Invoke(this, EventArgs.Empty);
//void OnInternetConnectionUnavailable() =>
//InternetConnectionUnavailable?.Invoke(this, EventArgs.Empty);
#endregion
//#region Classes
//class OcrTextLocationModel
//{
// public OcrTextLocationModel(string text, int top, int left)
// {
// Text = text;
// Top = top;
// Left = left;
// }
// public string Text { get; }
// public double Top { get; }
// public double Left { get; }
//}
//#endregion
}
} | 32.014652 | 134 | 0.690275 | [
"MIT"
] | jCho23/ASampleApp-JAAC | ASampleApp/ASampleApp/ViewModel/TextToSpeechViewModel.cs | 8,742 | C# |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace RakNet {
using System;
using System.Runtime.InteropServices;
public class OnFileStruct : IDisposable {
private HandleRef swigCPtr;
protected bool swigCMemOwn;
internal OnFileStruct(IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new HandleRef(this, cPtr);
}
internal static HandleRef getCPtr(OnFileStruct obj) {
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
~OnFileStruct() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
RakNetPINVOKE.delete_OnFileStruct(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
}
}
private bool fileDataIsCached = false;
private byte[] fileDataCache;
public uint fileIndex {
set {
RakNetPINVOKE.OnFileStruct_fileIndex_set(swigCPtr, value);
}
get {
uint ret = RakNetPINVOKE.OnFileStruct_fileIndex_get(swigCPtr);
return ret;
}
}
public string fileName {
set {
RakNetPINVOKE.OnFileStruct_fileName_set(swigCPtr, value);
}
get {
string ret = RakNetPINVOKE.OnFileStruct_fileName_get(swigCPtr);
return ret;
}
}
public byte[] fileData {
set
{
fileDataCache=value;
fileDataIsCached = true;
SetFileData (value, value.Length);
}
get
{
byte[] returnArray;
if (!fileDataIsCached)
{
IntPtr cPtr = RakNetPINVOKE.OnFileStruct_fileData_get (swigCPtr);
int len = (int) byteLengthOfThisFile;
if (len<=0)
{
return null;
}
returnArray = new byte[len];
byte[] marshalArray = new byte[len];
Marshal.Copy(cPtr, marshalArray, 0, len);
marshalArray.CopyTo(returnArray, 0);
fileDataCache = returnArray;
fileDataIsCached = true;
}
else
{
returnArray = fileDataCache;
}
return returnArray;
}
}
public uint byteLengthOfThisFile {
set {
RakNetPINVOKE.OnFileStruct_byteLengthOfThisFile_set(swigCPtr, value);
}
get {
uint ret = RakNetPINVOKE.OnFileStruct_byteLengthOfThisFile_get(swigCPtr);
return ret;
}
}
public uint bytesDownloadedForThisFile {
set {
RakNetPINVOKE.OnFileStruct_bytesDownloadedForThisFile_set(swigCPtr, value);
}
get {
uint ret = RakNetPINVOKE.OnFileStruct_bytesDownloadedForThisFile_get(swigCPtr);
return ret;
}
}
public ushort setID {
set {
RakNetPINVOKE.OnFileStruct_setID_set(swigCPtr, value);
}
get {
ushort ret = RakNetPINVOKE.OnFileStruct_setID_get(swigCPtr);
return ret;
}
}
public uint numberOfFilesInThisSet {
set {
RakNetPINVOKE.OnFileStruct_numberOfFilesInThisSet_set(swigCPtr, value);
}
get {
uint ret = RakNetPINVOKE.OnFileStruct_numberOfFilesInThisSet_get(swigCPtr);
return ret;
}
}
public uint byteLengthOfThisSet {
set {
RakNetPINVOKE.OnFileStruct_byteLengthOfThisSet_set(swigCPtr, value);
}
get {
uint ret = RakNetPINVOKE.OnFileStruct_byteLengthOfThisSet_get(swigCPtr);
return ret;
}
}
public uint bytesDownloadedForThisSet {
set {
RakNetPINVOKE.OnFileStruct_bytesDownloadedForThisSet_set(swigCPtr, value);
}
get {
uint ret = RakNetPINVOKE.OnFileStruct_bytesDownloadedForThisSet_get(swigCPtr);
return ret;
}
}
public FileListNodeContext context {
set {
RakNetPINVOKE.OnFileStruct_context_set(swigCPtr, FileListNodeContext.getCPtr(value));
}
get {
IntPtr cPtr = RakNetPINVOKE.OnFileStruct_context_get(swigCPtr);
FileListNodeContext ret = (cPtr == IntPtr.Zero) ? null : new FileListNodeContext(cPtr, false);
return ret;
}
}
public SystemAddress senderSystemAddress {
set {
RakNetPINVOKE.OnFileStruct_senderSystemAddress_set(swigCPtr, SystemAddress.getCPtr(value));
}
get {
IntPtr cPtr = RakNetPINVOKE.OnFileStruct_senderSystemAddress_get(swigCPtr);
SystemAddress ret = (cPtr == IntPtr.Zero) ? null : new SystemAddress(cPtr, false);
return ret;
}
}
public RakNetGUID senderGuid {
set {
RakNetPINVOKE.OnFileStruct_senderGuid_set(swigCPtr, RakNetGUID.getCPtr(value));
}
get {
IntPtr cPtr = RakNetPINVOKE.OnFileStruct_senderGuid_get(swigCPtr);
RakNetGUID ret = (cPtr == IntPtr.Zero) ? null : new RakNetGUID(cPtr, false);
return ret;
}
}
public OnFileStruct() : this(RakNetPINVOKE.new_OnFileStruct(), true) {
}
private void SetFileData(byte[] inByteArray, int numBytes) {
RakNetPINVOKE.OnFileStruct_SetFileData(swigCPtr, inByteArray, numBytes);
}
}
}
| 27.039024 | 101 | 0.607974 | [
"BSD-2-Clause"
] | noblewhale/NATPunchthroughClient | Assets/Plugins/SwigFiles/OnFileStruct.cs | 5,543 | C# |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.WritingSystems
{
public partial class WSAddDuplicateMoreButtonBar : UserControl
{
WritingSystemSetupModel _model;
public WSAddDuplicateMoreButtonBar()
{
InitializeComponent();
CreateMoreButtonImage();
}
public void BindToModel(WritingSystemSetupModel model)
{
Debug.Assert(model != null);
if (_model != null)
{
_model.SelectionChanged -= ModelSelectionChanged;
_model.CurrentItemUpdated -= OnCurrentItemUpdated;
}
_model = model;
SetButtonStatus();
_model.SelectionChanged += ModelSelectionChanged;
_model.CurrentItemUpdated += OnCurrentItemUpdated;
Disposed += OnDisposed;
}
private void OnCurrentItemUpdated(object sender, EventArgs e)
{
SetButtonStatus();
}
void OnDisposed(object sender, EventArgs e)
{
if (_model != null)
{
_model.SelectionChanged -= ModelSelectionChanged;
_model.CurrentItemUpdated -= OnCurrentItemUpdated;
}
}
private void CreateMoreButtonImage()
{
Bitmap downArrow = new Bitmap(11, 6);
Graphics g = Graphics.FromImage(downArrow);
g.FillRectangle(Brushes.Transparent, 0, 0, 11, 5);
g.FillPolygon(Brushes.Black, new[] { new Point(0, 0), new Point(10, 0), new Point(5, 5) });
_moreButton.Image = downArrow;
}
private void ModelSelectionChanged(object sender, EventArgs e)
{
SetButtonStatus();
}
private void SetButtonStatus()
{
if (_model == null)
return;
bool enabled = _model.HasCurrentSelection;
_exportMenuItem.Enabled = enabled;
_duplicateMenuItem.Enabled = enabled;
if(enabled)
{
var label = _model.CurrentDefinition == null ? "" : _model.CurrentDefinition.ListLabel;
_duplicateMenuItem.Text = string.Format("Add New Language by Copying {0}", label);
_deleteMenuItem.Text = string.Format("Delete {0}...", label);
_exportMenuItem.Text = string.Format("Save a Copy of the {0} LDML file...", label);
}
_deleteMenuItem.Enabled = enabled;
}
private void MoreButtonClick(object sender, EventArgs e)
{
// Popup context menu
_contextMenu.Show(_moreButton, 0, 0);
}
private void AddButtonClick(object sender, EventArgs e)
{
_model.AddNew();
}
private void DuplicateButtonClick(object sender, EventArgs e)
{
_model.DuplicateCurrent();
}
private void DeleteMenuClick(object sender, EventArgs e)
{
_model.DeleteCurrent();
}
private void ImportMenuClick(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "LDML files (*.ldml;*.xml)|*.ldml;*.xml|All files (*.*)|*.*";
dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dialog.RestoreDirectory = true;
if (dialog.ShowDialog(this) == DialogResult.OK)
{
_model.ImportFile(dialog.FileName);
}
}
private void ExportMenuClick(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog ();
dialog.Filter = "LDML files (*.ldml;*.xml)|*.ldml;*.xml|All files (*.*)|*.*";
dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dialog.RestoreDirectory = true;
if (dialog.ShowDialog (this) == DialogResult.OK)
{
_model.ExportCurrentWritingSystemAsFile(dialog.FileName);
}
}
}
}
| 26.761905 | 94 | 0.708482 | [
"MIT"
] | marksvc/libpalaso | PalasoUIWindowsForms/WritingSystems/WSAddDuplicateMoreButtonBar.cs | 3,372 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CallLogTracker.utility
{
public class Utility
{
/// <summary>
/// Formats a number in bytes to the next closest size representation and appends its suffix to the end.
/// </summary>
/// <param name="bytes">The bytes to format</param>
/// <returns>The number formatted with its suffix.</returns>
public static string FormatSize(long bytes)
{
string[] suffixes = { "Bytes", "KB", "MB", "GB", "TB", "PB" };
int counter = 0;
decimal number = bytes;
while (Math.Round(number / 1024) >= 1)
{
number /= 1024;
counter++;
}
return string.Format("{0:n2} {1}", number, suffixes[counter]);
}
}
}
| 28.3125 | 112 | 0.550773 | [
"Apache-2.0"
] | tlit-baytown/CallLogTracker | CallLogTracker/utility/Utility.cs | 908 | C# |
using ProMama.ViewModels.Inicio;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ProMama.Views.Inicio
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NovaSenhaView : ContentPage
{
public NovaSenhaView()
{
InitializeComponent();
BindingContext = new NovaSenhaViewModel();
}
}
} | 22.176471 | 54 | 0.668435 | [
"Apache-2.0"
] | agharium/ProMama | ProMama/ProMama/Views/Inicio/NovaSenhaView.xaml.cs | 379 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BankProject.Entity
{
public class MainSector
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public override string ToString()
{
if (string.IsNullOrWhiteSpace(this.Code))
{
return string.Empty;
}
return string.Format("{0}-{1}-{2}", this.Code, this.Name, this.ShortName);
}
}
} | 22.25 | 87 | 0.53451 | [
"Apache-2.0",
"BSD-3-Clause"
] | nguyenppt/1pubcreditnew | DesktopModules/TrainingCoreBanking/BankProject/Entity/MainSector.cs | 625 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.10
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
namespace Noesis
{
public enum FontWeight {
Thin = 100,
ExtraLight = 200,
UltraLight = 200,
Light = 300,
SemiLight = 350,
Normal = 400,
Regular = 400,
Medium = 500,
DemiBold = 600,
SemiBold = 600,
Bold = 700,
ExtraBold = 800,
UltraBold = 800,
Black = 900,
Heavy = 900,
ExtraBlack = 950,
UltraBlack = 950
}
}
| 20.85 | 81 | 0.502398 | [
"MIT"
] | CodingJinxx/gameoff2020 | Gameoff2020/Assets/NoesisGUI/Plugins/API/Proxies/FontWeight.cs | 834 | C# |
namespace MyBlazorApp.Features.Counters
{
using BlazorState;
internal partial class CounterState : State<CounterState>
{
public int Count { get; private set; }
public CounterState() { }
/// <summary>
/// Set the Initial State
/// </summary>
public override void Initialize() => Count = 3;
}
}
| 19.294118 | 59 | 0.646341 | [
"Unlicense"
] | mikeyoshino/MyBlazorApp | Source/Client/Features/Counter/CounterState.cs | 328 | C# |
//Found this online, modified it
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CanvasTextOutline : MonoBehaviour
{
public float pixelSize = 1, sortingOrder;
public int cloneCount = 8;
public Color outlineColor = Color.black;
public bool scaleLocally = false;
public int doubleResolution = 1024;
public bool squareAlign = false;
public bool updateAttributes;
private Text text;
private RectTransform rectTransform;
private Text[] childTexts;
private RectTransform[] childRectTransforms;
void Start()
{
text = GetComponent<Text>();
rectTransform = GetComponent<RectTransform>();
if (cloneCount != 8)
squareAlign = false;
childTexts = new Text[cloneCount];
childRectTransforms = new RectTransform[cloneCount];
for (int i = 0; i < cloneCount; i++)
{
GameObject outline = new GameObject("Text Outline", typeof(Text));
//Renderer otherMeshRenderer = outline.GetComponent<Renderer>();
//otherMeshRenderer.material = new Material(textRenderer.material);
//otherMeshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
//otherMeshRenderer.receiveShadows = false;
//otherMeshRenderer.sortingLayerID = textRenderer.sortingLayerID;
//otherMeshRenderer.sortingLayerName = textRenderer.sortingLayerName;
//otherMeshRenderer.sortingOrder = textRenderer.sortingOrder;
//childMeshRenderers[i] = otherMeshRenderer;
childTexts[i] = outline.GetComponent<Text>();
RectTransform outlineTransform = outline.GetComponent<RectTransform>();
outlineTransform.SetParent(transform.parent == null ? transform : transform.parent);
outlineTransform.sizeDelta = rectTransform.sizeDelta;
outlineTransform.transform.localScale = transform.localScale;
childRectTransforms[i] = outlineTransform;
outlineTransform.anchorMax = rectTransform.anchorMax;
outlineTransform.anchorMin = rectTransform.anchorMax;
outlineTransform.pivot = rectTransform.pivot;
updateAttributes = true;
}
//Transform parent = transform.parent;
//Vector3 holdPosition = transform.localPosition;
rectTransform.SetAsLastSibling();
//transform.localPosition = holdPosition;
}
public void LateUpdate()
{
if (text == null)
return;
Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
outlineColor.a = text.color.a * text.color.a;
for (int i = 0; i < childTexts.Length; i++)
{
Text other = childTexts[i];
other.text = text.text;
other.fontSize = text.fontSize;
if (updateAttributes)
{
other.color = outlineColor;
other.alignment = text.alignment;
//other.anchor = text.anchor;
//other.characterSize = text.characterSize;
other.font = text.font;
other.fontStyle = text.fontStyle;
//other.richText = text.richText;
//other.tabSize = text.tabSize;
other.lineSpacing = text.lineSpacing;
//other.offsetZ = text.offsetZ;
other.gameObject.layer = gameObject.layer;
}
RectTransform childTransform = childRectTransforms[i];
childTransform.sizeDelta = rectTransform.sizeDelta;
//bool doublePixel = resolutionDependant && (Screen.width > doubleResolution || Screen.height > doubleResolution);
//Vector3 pixelOffset = GetOffset(i) * (doublePixel ? 2.0f * getFunctionalPixelSize() : getFunctionalPixelSize());
//Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint +
// (pixelOffset * ((float)Screen.currentResolution.width / 1400f)));
float fixedPixelWorldSize = (10f * (4f / 3f)) / 1152f;
Vector3 worldPoint = (GetOffset(i) * getFunctionalPixelSize() * fixedPixelWorldSize);
//if (scaleLocally)
// worldPoint.Scale(transform.parent.lossyScale);
worldPoint += transform.position;
other.transform.position = worldPoint + new Vector3(0f, 0f, .001f);
other.transform.localScale = transform.localScale;
other.transform.rotation = transform.rotation;
//Renderer otherMeshRenderer = childMeshRenderers[i];
//otherMeshRenderer.sortingLayerID = textRenderer.sortingLayerID;
//otherMeshRenderer.sortingLayerName = textRenderer.sortingLayerName;
}
}
public Text[] getChildTexts()
{
return childTexts;
}
float getFunctionalPixelSize()
{
return pixelSize;// * 5f / Camera.main.orthographicSize;
}
Vector3 GetOffset(int i)
{
if (squareAlign)
{
//Debug.Log(i % 2 == 0 ? 1f : Mathf.Sqrt(2f));
return MathHelper.getVector2FromAngle(360f * ((float)i / (float)cloneCount), i % 2 == 0 ? 1f : Mathf.Sqrt(2f));
}
else
return MathHelper.getVector2FromAngle(360f * ((float)i / (float)cloneCount), 1f);
}
} | 38.056738 | 126 | 0.625792 | [
"MIT"
] | Trif4/NitoriWare | Assets/Scripts/UI/CanvasTextOutline.cs | 5,368 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("4.DancingBits")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("4.DancingBits")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c1a4bd79-4bf2-4422-898d-957ecfb06521")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.744103 | [
"MIT"
] | Steffkn/TelerikAcademy | Programming/BGCoder Exams/2011-2012/C# Fundamentals 2011-2012/TA @ 7 Dec 2011 Morning/4.DancingBits/Properties/AssemblyInfo.cs | 1,402 | 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.V20210301.Inputs
{
/// <summary>
/// The parameters of a managed disk.
/// </summary>
public sealed class ManagedDiskParametersArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the customer managed disk encryption set resource id for the managed disk.
/// </summary>
[Input("diskEncryptionSet")]
public Input<Inputs.DiskEncryptionSetParametersArgs>? DiskEncryptionSet { get; set; }
/// <summary>
/// Resource Id
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Specifies the storage account type for the managed disk. Managed OS disk storage account type can only be set when you create the scale set. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk.
/// </summary>
[Input("storageAccountType")]
public InputUnion<string, Pulumi.AzureNative.Compute.V20210301.StorageAccountTypes>? StorageAccountType { get; set; }
public ManagedDiskParametersArgs()
{
}
}
}
| 35.243902 | 237 | 0.660208 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Compute/V20210301/Inputs/ManagedDiskParametersArgs.cs | 1,445 | C# |
using System;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
namespace Checkk.Exceptions
{
public class InvariantException : Exception
{
private readonly string _message;
protected InvariantException(string message)
{
_message = message;
}
protected static string Niceify(Expression body)
{
var regex = new Regex("value\\(.+?\\)\\.");
return regex.Replace(body.ToString(), "");
}
protected virtual string AutoMessage
{
get { return null; }
}
public override string Message
{
get
{
return string.IsNullOrEmpty(_message)
? AutoMessage
: _message;
}
}
}
} | 23.222222 | 56 | 0.523923 | [
"Apache-2.0"
] | becdetat/check | src/Checkk/Exceptions/InvariantException.cs | 836 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
namespace Workday.HumanResources
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Language_Ability_Profile_DataType : INotifyPropertyChanged
{
private Language_Ability_TypeObjectType language_Ability_Type_ReferenceField;
private Language_ProficiencyObjectType language_Proficiency_ReferenceField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement(Order = 0)]
public Language_Ability_TypeObjectType Language_Ability_Type_Reference
{
get
{
return this.language_Ability_Type_ReferenceField;
}
set
{
this.language_Ability_Type_ReferenceField = value;
this.RaisePropertyChanged("Language_Ability_Type_Reference");
}
}
[XmlElement(Order = 1)]
public Language_ProficiencyObjectType Language_Proficiency_Reference
{
get
{
return this.language_Proficiency_ReferenceField;
}
set
{
this.language_Proficiency_ReferenceField = value;
this.RaisePropertyChanged("Language_Proficiency_Reference");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 26.566667 | 136 | 0.784818 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.HumanResources/Language_Ability_Profile_DataType.cs | 1,594 | C# |
using System.Globalization;
namespace MiniExcelLibs
{
public interface IConfiguration { }
public abstract class Configuration : IConfiguration
{
public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture;
}
}
| 23.454545 | 81 | 0.689922 | [
"Apache-2.0"
] | 0xced/MiniExcel | src/MiniExcel/IConfiguration.cs | 260 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using VkNet.Enums.SafetyEnums;
using VkNet.Model;
using VkNet.Model.RequestParams.Ads;
namespace VkNet.Abstractions
{
/// <summary>
/// Асинхронные методы для работы со стеной пользователя.
/// </summary>
public interface IAdsCategoryAsync
{
/// <summary>
/// Добавляет администраторов и/или наблюдателей в рекламный кабинет.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "data">
/// Сериализованный JSON-массив объектов, описывающих добавляемых администраторов. Описание объектов user_specification см. ниже. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив значений - ответов на каждый запрос в массиве data. Соответствующее значение в выходном массиве равно true, если администратор успешно добавлен, и false в другом случае.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.addOfficeUsers
/// </remarks>
Task<ReadOnlyCollection<object>> AddOfficeUsersAsync(long accountId, string data);
/// <summary>
/// Проверяет ссылку на рекламируемый объект.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "linkType">
/// Вид рекламируемого объекта:
/// community — сообщество;
/// post — запись в сообществе;
/// application — приложение ВКонтакте;
/// video — видеозапись;
/// site — внешний сайт.
/// обязательный параметр, строка
/// </param>
/// <param name = "linkUrl">
/// Ссылка на рекламируемый объект. обязательный параметр, строка
/// </param>
/// <param name = "campaignId">
/// Id кампании, в которой будет создаваться объявление. целое число
/// </param>
/// <returns>
/// Возвращается структура со следующими полями:
/// status — статус ссылки:
/// allowed — ссылку допустимо использовать в рекламных объявлениях;
/// disallowed — ссылку недопустимо использовать для указанного вида рекламируемого объекта;
/// in_progress — ссылка проверяется, необходимо немного подождать.
/// description (если status равен disallowed, необязательное поле) — описание причины недопустимости использования ссылки.
/// redirect_url (если конечная ссылка отличается от исходной и если status равен allowed) — конечная ссылка.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.checkLink
/// </remarks>
Task<LinkStatus> CheckLinkAsync(long accountId, AdsLinkType linkType, string linkUrl, long? campaignId = null);
/// <summary>
/// Создает рекламные объявления.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "data">
/// Сериализованный JSON-массив объектов, описывающих создаваемые объявления. Описание объектов ad_specification см. ниже.
/// Пример значения data: [{
/// "campaign_id": 123456,
/// "ad_format": 1,
/// "cost_type": 0,
/// "cpc": 2.00,
/// "category1_id" : 5,
/// "title": "Test Title",
/// "link_url" : "https://mysite.com",
/// "name": "My ad"
/// }] обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив объектов - ответов на каждый запрос в массиве data. Соответствующий объект в выходном массиве имеет свойство id, соответствующее id созданного объявления (или 0 в случае неудачи), а также, возможно, поля error_code и error_desc, описывающие ошибку, при ее возникновении. Наличие одновременно ненулевого id и error_code говорит о том, что объявление было создано, однако, возможно, не все параметры установлены (например, объявление не запущено).
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.createAds
/// </remarks>
Task<ReadOnlyCollection<object>> CreateAdsAsync(long accountId, string data);
/// <summary>
/// Создает рекламные кампании.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "data">
/// Сериализованный JSON-массив объектов, описывающих создаваемые кампании. Описание объектов campaign_specification см. ниже. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на запросы в массиве data. Соответствующий объект в выходном массиве содержит id созданной кампании (ноль в случае неудачи), и поля error_code и error_desc в случае возникновения ошибки. Ненулевой id и наличие error_code 602 говорит о том, что кампания создана, но, возможно, некоторые поля не были ей присвоены по причине их некорректности.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.createCampaigns
/// </remarks>
Task<ReadOnlyCollection<object>> CreateCampaignsAsync(long accountId, string data);
/// <summary>
/// Создаёт клиентов рекламного агентства.
/// </summary>
/// <param name = "accountId">
/// Id рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "data">
/// Сериализованный JSON-массив объектов, описывающих создаваемые кампании. Описание объектов client_specification см. ниже. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на запросы в массиве data. Соответствующий объект в выходном массиве содержит id созданного клиента (ноль в случае неудачи), и поля error_code и error_desc в случае возникновения ошибки. Ненулевой id и наличие error_code 602 говорит о том, что клиент создан, но, возможно, некоторые поля не были ему присвоены по причине их некорректности.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.createClients
/// </remarks>
Task<ReadOnlyCollection<object>> CreateClientsAsync(long accountId, string data);
/// <summary>
/// Создаёт запрос на поиск похожей аудитории.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "sourceType">
/// Тип источника исходной аудитории. На данный момент может принимать единственное значение retargeting_group. строка, обязательный параметр
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// идентификатор клиента, для которого будет создаваться аудитория. целое число
/// </param>
/// <param name = "retargetingGroupId">
/// Только для источника типа retargeting_group: идентификатор аудитории ретаргетинга.
/// </param>
/// <returns>
/// Поле request_id, в котором указан идентификатор созданного запроса на поиск похожей аудитории.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.createLookalikeRequest
/// </remarks>
Task<object> CreateLookalikeRequestAsync(long accountId, string sourceType, long? clientId = null,
object retargetingGroupId = null);
/// <summary>
/// Создает аудиторию для ретаргетинга рекламных объявлений на пользователей, которые посетили сайт рекламодателя (просмотрели информации о товаре, зарегистрировались и т.д.).
/// </summary>
/// <param name = "createTargetGroupParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Возвращает объект со следующими полями:
/// id — идентификатор аудитории.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.createTargetGroup
/// </remarks>
Task<object> CreateTargetGroupAsync(CreateTargetGroupParams createTargetGroupParams);
/// <summary>
/// Создаёт пиксель ретаргетинга.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "name">
/// Название пикселя — строка до 64 символов. обязательный параметр, строка
/// </param>
/// <param name = "domain">
/// Домен сайта, на котором будет размещен пиксель. строка
/// </param>
/// <param name = "categoryId">
/// Идентификатор категории сайта, на котором будет размещен пиксель. Для получения списка возможных идентификаторов следует использовать метод ads.getSuggestions (раздел interest_categories_v2). обязательный параметр, целое число
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого будет создаваться пиксель. целое число
/// </param>
/// <returns>
/// Возвращает объект со следующими полями:
/// id — идентификатор пикселя
/// pixel — код для размещения на сайте рекламодателя
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.createTargetPixel
/// </remarks>
Task<object> CreateTargetPixelAsync(long accountId, string name, string domain, long categoryId, long? clientId = null);
/// <summary>
/// Архивирует рекламные объявления.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "ids">
/// Сериализованный JSON-массив, содержащий идентификаторы объявлений. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на каждый запрос. Каждый ответ является либо 0, что означает успешное удаление, либо код ошибки.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.deleteAds
/// </remarks>
Task<ReadOnlyCollection<object>> DeleteAdsAsync(long accountId, string ids);
/// <summary>
/// Архивирует рекламные кампании.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "ids">
/// Сериализованный JSON-массив, содержащий id удаляемых кампаний. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на каждый запрос. Каждый ответ является либо 0, что означает успешное удаление, либо код ошибки.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.deleteCampaigns
/// </remarks>
Task<ReadOnlyCollection<object>> DeleteCampaignsAsync(long accountId, string ids);
/// <summary>
/// Архивирует клиентов рекламного агентства.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "ids">
/// Сериализованный JSON-массив, содержащий id удаляемых клиентов. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на каждый запрос. Каждый ответ является либо 0, что означает успешное удаление, либо код ошибки.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.deleteClients
/// </remarks>
Task<ReadOnlyCollection<object>> DeleteClientsAsync(long accountId, string ids);
/// <summary>
/// Удаляет аудиторию ретаргетинга.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "targetGroupId">
/// Идентификатор аудитории. обязательный параметр, целое число
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого будет удаляться аудитория. целое число
/// </param>
/// <returns>
/// В случае успеха метод возвратит 1.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.deleteTargetGroup
/// </remarks>
Task<bool> DeleteTargetGroupAsync(long accountId, long targetGroupId, long? clientId = null);
/// <summary>
/// Удаляет пиксель ретаргетинга.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "targetPixelId">
/// Идентификатор пикселя. обязательный параметр, целое число
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого будет удаляться пиксель. целое число
/// </param>
/// <returns>
/// В случае успеха метод возвратит 1.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.deleteTargetPixel
/// </remarks>
Task<bool> DeleteTargetPixelAsync(long accountId, long targetPixelId, long? clientId = null);
/// <summary>
/// Возвращает список рекламных кабинетов.
/// </summary>
/// <returns>
/// Возвращает массив объектов, описывающих рекламные кабинеты. Каждый объект содержит следующие поля:
/// account_id
/// integerидентификатор рекламного кабинета. account_type
/// stringтип рекламного кабинета. Возможные значения:
/// general — обычный;
/// agency — агентский. account_status
/// integer, [0,1]статус рекламного кабинета. Возможные значения:
/// 1 — активен;
/// 0 — неактивен. access_role
/// stringправа пользователя в рекламном кабинете. Возможные значения:
/// admin — главный администратор;
/// manager — администратор;
/// reports — наблюдатель.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getAccounts
/// </remarks>
Task<ReadOnlyCollection<AdsAccount>> GetAccountsAsync();
/// <summary>
/// Возвращает список рекламных объявлений.
/// </summary>
/// <param name = "getAdsParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Возвращает массив объектов, описывающих объявления. Каждый объект содержит следующие поля:
/// id
/// integerидентификатор объявления. campaign_id
/// integerидентификатор кампании. ad_format
/// integerформат объявления. Возможные значения:
/// 1 — изображение и текст;
/// 2 — большое изображение;
/// 3 — эксклюзивный формат;
/// 4 — продвижение сообществ или приложений, квадратное изображение;
/// 5 — приложение в новостной ленте (устаревший);
/// 6 — мобильное приложение;
/// 9 — запись в сообществе. cost_type
/// integer, [0,1]тип оплаты. Возможные значения:
/// 0 — оплата за переходы;
/// 1 — оплата за показы. cpc
/// integer(если cost_type = 0) цена за переход в копейках. cpm
/// integer(если cost_type = 1) цена за 1000 показов в копейках. impressions_limit
/// integer(если задано) ограничение количества показов данного объявления на одного пользователя. Может присутствовать для некоторых форматов объявлений, для которых разрешена установка точного значения. impressions_limited
/// integer, [1](если задано) признак того, что количество показов объявления на одного пользователя ограничено. Может присутствовать для некоторых объявлений, для которых разрешена установка ограничения, но не разрешена установка точного значения. 1 — не более 100 показов на одного пользователя. ad_platform(если значение применимо к данному формату объявления) рекламные площадки, на которых будет показываться объявление. Возможные значения:
/// (если ad_format равен 1)
/// 0 — ВКонтакте и сайты-партнёры;
/// 1 — только ВКонтакте.
/// (если ad_format равен 9)
/// all — все площадки;
/// desktop — полная версия сайта;
/// mobile — мобильный сайт и приложения. ad_platform_no_wall
/// integer, [1]1 — для объявления задано ограничение «Не показывать на стенах сообществ». all_limit
/// integerобщий лимит объявления в рублях. 0 — лимит не задан. category1_id
/// integerID тематики или подраздела тематики объявления. См. ads.getCategories. category2_id
/// integerID тематики или подраздела тематики объявления. Дополнительная тематика. status
/// integerстатус объявления. Возможные значения:
/// 0 — объявление остановлено;
/// 1 — объявление запущено;
/// 2 — объявление удалено. name
/// stringназвание объявления. approved
/// integerстатус модерации объявления. Возможные значения:
/// 0 — объявление не проходило модерацию;
/// 1 — объявление ожидает модерации;
/// 2 — объявление одобрено;
/// 3 — объявление отклонено. video
/// integer, [1]1 — объявление является видеорекламой. disclaimer_medical
/// integer, [1]1 — включено отображение предупреждения:
/// «Есть противопоказания. Требуется консультация специалиста.» disclaimer_specialist
/// integer, [1]1 — включено отображение предупреждения:
/// «Необходима консультация специалистов.» disclaimer_supplements
/// integer, [1]1 — включено отображение предупреждения:
/// «БАД. Не является лекарственным препаратом.» events_retargeting_groups
/// arrayТолько для ad_format = 9. Описание событий, собираемых в группы ретаргетинга. Массив объектов, где ключом является id группы ретаргетинга, а значением - массив событий. Допустимые значений для событий:
/// 1 — просмотр промопоста;
/// 2 — переход по ссылке или переход в сообщество;
/// 3 — переход в сообщество;
/// 4 — подписка на сообщество;
/// 5 — отписка от новостей сообщества;
/// 6 — скрытие или жалоба;
/// 10 — запуск видео;
/// 11 — досмотр видео до 3с;
/// 12 — досмотр видео до 25%;
/// 13 — досмотр видео до 50%;
/// 14 — досмотр видео до 75%;
/// 15 — досмотр видео до 100%;
/// 20 — лайк продвигаемой записи;
/// 21 — репост продвигаемой записи.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getAds
/// </remarks>
Task<ReadOnlyCollection<Ad>> GetAdsAsync(GetAdsParams getAdsParams);
/// <summary>
/// Возвращает описания внешнего вида рекламных объявлений.
/// </summary>
/// <param name = "getAdsLayoutParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Возвращает массив объектов, описывающих объявления. Каждый объект содержит следующие поля:
/// id
/// integer>идентификатор объявления. campaign_id
/// integer>нтификатор кампании. ad_format
/// integerформат объявления. Возможные значения:
/// 1 — изображение и текст;
/// 2 — большое изображение;
/// 3 — эксклюзивный формат;
/// 4 — продвижение сообществ или приложений, квадратное изображение;
/// 5 — приложение в новостной ленте (устаревший);
/// 6 — мобильное приложение;
/// 7 — специальный формат приложений;
/// 8 — специальный формат сообществ;
/// 9 — запись в сообществе;
/// 10 — витрина приложений. cost_type
/// integer, [0,1]тип оплаты. Возможные значения:
/// 0 — оплата за переходы;
/// 1 — оплата за показы. video
/// integer, [1]1 — объявление является видеорекламой. title
/// stringзаголовок объявления. description
/// stringописание объявления. link_url
/// stringссылка на рекламируемый объект. link_domain
/// stringдомен рекламируемого сайта. preview_link
/// stringссылка, перейдя по которой можно просмотреть рекламное объявление так, как оно выглядит на сайте. Ссылка доступна в течение 30 минут после выполнения метода ads.getAdsLayout. image_src
/// stringurl изображения объявления. image_src_2x
/// stringurl изображения двойного разрешения.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getAdsLayout
/// </remarks>
Task<Uri> GetAdsLayoutAsync(GetAdsLayoutParams getAdsLayoutParams);
/// <summary>
/// Возвращает параметры таргетинга рекламных объявлений
/// </summary>
/// <param name = "getAdsTargetingParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Возвращает массив объектов - описаний таргетинга объявлений.
/// Отрицательные id в поле cities означают id регионов, взятых с обратным знаком.
/// Поле count содержит размер целевой аудитории на момент сохранения объявления.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getAdsTargeting
/// </remarks>
Task<ReadOnlyCollection<object>> GetAdsTargetingAsync(GetAdsTargetingParams getAdsTargetingParams);
/// <summary>
/// Возвращает текущий бюджет рекламного кабинета.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <returns>
/// Возвращает единственное число — оставшийся бюджет в указанном рекламном кабинете.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getBudget
/// </remarks>
Task<object> GetBudgetAsync(long accountId);
/// <summary>
/// Возвращает список кампаний рекламного кабинета.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "campaignIds">
/// Фильтр выводимых рекламных кампаний.
/// Сериализованный JSON-массив, содержащий id кампаний. Выводиться будут только кампании, присутствующие в campaign_ids и являющиеся кампаниями указанного рекламного кабинета. Если параметр равен строке null, то выводиться будут все кампании. строка
/// </param>
/// <param name = "clientId">
/// Обязателен для рекламных агентств, в остальных случаях не используется. Идентификатор клиента, у которого запрашиваются рекламные кампании. целое число
/// </param>
/// <param name = "includeDeleted">
/// Флаг, задающий необходимость вывода архивных объявлений.
/// 0 — выводить только активные кампании;
/// 1 — выводить все кампании.
/// флаг, может принимать значения 1 или 0
/// </param>
/// <returns>
/// Возвращает массив объектов campaign, каждый из которых содержит следующие поля:
/// id — идентификатор кампании
/// type — тип кампании
/// normal — обычная кампания, в которой можно создавать любые объявления, кроме мобильной рекламы и записей в сообществе
/// vk_apps_managed — кампания, в которой можно рекламировать только администрируемые Вами приложения и у которой есть отдельный бюджет
/// mobile_apps — кампания, в которой можно рекламировать только мобильные приложения
/// promoted_posts — кампания, в которой можно рекламировать только записи в сообществе
/// name — название кампании
/// status — статус кампании
/// 0 — кампания остановлена
/// 1 — кампания запущена
/// 2 — кампания удалена
/// day_limit — дневной лимит кампании в рублях
/// 0 — лимит не задан
/// all_limit — общий лимит кампании в рублях
/// 0 — лимит не задан
/// start_time — время запуска кампании в формате unixtime
/// 0 — время не задано
/// stop_time — время остановки кампании в формате unixtime
/// 0 — время не задано
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getCampaigns
/// </remarks>
Task<ReadOnlyCollection<AdsCampaign>> GetCampaignsAsync(long accountId, IEnumerable<long> campaignIds, long? clientId = null,
bool? includeDeleted = null);
/// <summary>
/// Позволяет получить возможные тематики рекламных объявлений.
/// </summary>
/// <param name = "lang">
/// Язык, на котором нужно вернуть результаты. Список поддерживаемых языков Вы можете найти на странице Запросы к API. строка
/// </param>
/// <returns>
/// После успешного выполнения возвращает два массива объектов — v1 и v2, каждый из которых содержит объекты, описывающие тематики в следующем формате:
/// id — идентификатор тематики;
/// name — название тематики;
/// subcategories[subcategory] (если есть хотя бы один подраздел) — список подразделов. Массив объектов, каждый из которых содержит следующие поля:
/// id — идентификатор подраздела;
/// name — название подраздела.
/// Массив v1 включает устаревшие тематики. Актуальный список содержится в массиве v2.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getCategories
/// </remarks>
Task<ReadOnlyCollection<object>> GetCategoriesAsync(string lang);
/// <summary>
/// Возвращает список клиентов рекламного агентства.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <returns>
/// Возвращает массив объектов client — клиентов агентства с номером account_id, каждый из которых содержит следующие поля:
/// id — идентификатор клиента;
/// name — название клиента;
/// day_limit — дневной лимит клиента в рублях;
/// all_limit — общий лимит клиента в рублях.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getClients
/// </remarks>
Task<ReadOnlyCollection<object>> GetClientsAsync(long accountId);
/// <summary>
/// Возвращает демографическую статистику по рекламным объявлениям или кампаниям.
/// </summary>
/// <param name = "getDemographicsParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Каждый запрашиваемый объект имеет следующие поля:
/// id — id объекта из параметра ids
/// type — тип объекта из параметра ids_type
/// stats — список структур описывающих статистику объекта за один временной период (конкретный временной период присутствует в списке, если по нему есть какая-то статистика)
/// Структура в списке stats имеет следующие поля:
/// day (если period равен day) — день в формате YYYY-MM-DD
/// month (если period равен month) — месяц в формате YYYY-MM
/// overall (если period равен overall) — 1
/// sex — список структур, описывающих статистику по полу
/// age — список структур, описывающих статистику по возрасту
/// sex_age — список структур, описывающих статистику по полу и возрасту
/// cities — список структур, описывающих статистику по городам
/// Структура в списках sex, age, sex_age, cities имеет следующие поля:
/// impressions_rate — часть аудитории, просмотревшая объявление, от 0 до 1
/// clicks_rate — часть аудитории, кликнувшая по объявлению, от 0 до 1
/// value — значение демографического показателя, имеет разные возможные значения для разных показателей
/// sex (f — женщины, m — мужчины)
/// age — один из следующих промежутков: 12-18, 18-21, 21-24, 24-27, 27-30, 30-35, 35-45, 45-100
/// sex_age — комбинация значений sex и age, разделённых точкой с запятой, пример: m;21-24
/// cities — id города или other для остальных городов
/// name — наглядное название значения указанного в value (только для городов)
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getDemographics
/// </remarks>
Task<ReadOnlyCollection<object>> GetDemographicsAsync(GetDemographicsParams getDemographicsParams);
/// <summary>
/// Возвращает информацию о текущем состоянии счетчика — количество оставшихся запусков методов и время до следующего обнуления счетчика в секундах.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <returns>
/// Возвращает объект, содержащий следующие поля:
/// left — количество оставшихся методов;
/// refresh — время до следующего обновления в секундах.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getFloodStats
/// </remarks>
Task<object> GetFloodStatsAsync(long accountId);
/// <summary>
/// Возвращает список запросов на поиск похожей аудитории.
/// </summary>
/// <param name = "getLookalikeRequestsParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Если limit не равен 0, то возвращается объект с двумя полями:
///
/// count — количество запросов на поиск похожей аудитории в данном кабинете.
/// items — список объектов-запросов на поиск похожей аудитории запрошенного размера с запрошенным сдвигом.
/// При limit равном 0, возвращается только поле count.
/// Описание запроса на поиск похожей аудитории – объект со следующими полями:
/// id — идентификатор запроса на поиск похожей аудитории. Является уникальным только в рамках конкретного кабинета (клиента в случае агентства).
/// create_time — timestamp даты создания запроса.
/// update_time — timestamp даты последнего обновления статуса запроса.
/// status — текущий статус запроса, может принимать следующие значения: search_in_progress, search_done, search_failed, save_in_progress, save_done, save_failed.
/// scheduled_delete_time — timestamp даты запланированного удаления запроса.
/// source_type — тип источника исходной аудитории для поиска похожей аудитории. Может принимать только значение retargeting_group.
/// source_retargeting_group_id — при source_type равном retargeting_group в данном поле указан идентификатор аудитории ретаргетинга с исходной аудиторией.
/// source_name — имя источника исходной аудитории. При source_type равном retargeting_group в данном поле указано название аудитории ретаргетинга на момент создания запроса.
/// audience_count — размер исходной аудитории.
/// save_audience_levels — Список доступных размеров аудитории для сохранения. Присутствует только после успешного поиска похожей аудитории. Поля:
/// level — используется в качестве параметра level в ads.saveLookalikeRequestResult
/// audience_count — размер похожей аудитории в данной опции.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getLookalikeRequests
/// </remarks>
Task<ReadOnlyCollection<object>> GetLookalikeRequestsAsync(GetLookalikeRequestsParams getLookalikeRequestsParams);
/// <summary>
/// Возвращает список администраторов и наблюдателей рекламного кабинета.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <returns>
/// Возвращает массив объектов - описаний пользователей рекламного кабинета. Каждый объект содержит массив описаний прав доступа к конкретным клиентам. Описание содержит два поля: client_id — id клиента и role — строка admin, manager или reports. Для admin client_id не указывается.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getOfficeUsers
/// </remarks>
Task<ReadOnlyCollection<object>> GetOfficeUsersAsync(long accountId);
/// <summary>
/// Возвращает подробную статистику по охвату рекламных записей из объявлений и кампаний для продвижения записей сообщества.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "idsType">
/// Тип запрашиваемых объектов, которые перечислены в параметре ids:
/// ad — объявления;
/// campaign — кампании.
/// обязательный параметр, строка
/// </param>
/// <param name = "ids">
/// Перечисленные через запятую id запрашиваемых объявлений или кампаний, в зависимости от того, что указано в параметре ids_type. Максимум 100 объектов. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив объектов, описывающих охват. Каждый объект содержит следующие поля:
/// id
/// integerID объекта из параметра ids. reach_subscribers
/// integerохват подписчиков. reach_total
/// integerсуммарный охват. links
/// integerпереходы по ссылке. to_group
/// integerпереходы в сообщество. join_group
/// integerвступления в сообщество. report
/// integerколичество жалоб на запись. hide
/// integerколичество скрытий записи. unsubscribe
/// integerколичество отписавшихся участников. video_views_start*
/// integerколичество стартов просмотра видео. video_views_3s*
/// integerколичество досмотров видео до 3 секунд. video_views_25p*
/// integerколичество досмотров видео до 25 процентов. video_views_50p*
/// integerколичество досмотров видео до 50 процентов. video_views_75p*
/// integerколичество досмотров видео до 75 процентов. video_views_100p*
/// integerколичество досмотров видео до 100 процентов.
/// * — поля с данными по статистике видео возвращаются только для объявлений или кампаний с видео, созданных после 26 января 2017 года.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getPostsReach
/// </remarks>
Task<ReadOnlyCollection<object>> GetPostsReachAsync(long accountId, string idsType, string ids);
/// <summary>
/// Возвращает причину, по которой указанному объявлению было отказано в прохождении премодерации.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "adId">
/// Идентификатор рекламного объявления. обязательный параметр, целое число
/// </param>
/// <returns>
/// Возвращает объект, который может содержать поле comment, содержащее текстовый комментарий модератора, и/или массив rules, содержащий описание нарушенных объявлением правил. Ответ обязательно содержит хотя бы одно из полей comment или rules. Каждый элемент массива rules состоит из поля title (текстового пояснения) и массива paragraphs, каждый элемент которого содержит отдельный пункт правил. Элементы массива paragraphs могут содержать простую html-разметку.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getRejectionReason
/// </remarks>
Task<ReadOnlyCollection<object>> GetRejectionReasonAsync(long accountId, long adId);
/// <summary>
/// Возвращает статистику показателей эффективности по рекламным объявлениям, кампаниям, клиентам или всему кабинету.
/// </summary>
/// <param name = "getStatisticsParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Каждый запрашиваемый объект имеет следующие поля:
/// id — id объекта из параметра ids
/// type — тип объекта из параметра ids_type
/// stats — список структур описывающих статистику объекта за один временной период (конкретный временной период присутствует в списке, если по нему есть какая-то статистика)
/// Структура в списке stats имеет следующие поля:
/// day (если period равен day) — день в формате YYYY-MM-DD
/// month (если period равен month) — день в формате YYYY-MM
/// overall (если period равен overall) — 1
/// spent — потраченные средства
/// impressions — просмотры
/// clicks — клики
/// reach (если ids_type равен ad или campaign и period равен day или month) — охват
/// video_views (если ids_type равен ad) — просмотры видеоролика (для видеорекламы)
/// video_views_half (если ids_type равен ad) — просмотры половины видеоролика (для видеорекламы)
/// video_views_full (если ids_type равен ad) — просмотры целого видеоролика (для видеорекламы)
/// video_clicks_site (если ids_type равен ad) — переходы на сайт рекламодателя из видеорекламы (для видеорекламы)
/// join_rate (если ids_type равен ad или campaign) — вступления в группу, событие, подписки на публичную страницу или установки приложения (только если в объявлении указана прямая ссылка на соответствующую страницу ВКонтакте)
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getStatistics
/// </remarks>
Task<ReadOnlyCollection<object>> GetStatisticsAsync(GetStatisticsParams getStatisticsParams);
/// <summary>
/// Возвращает набор подсказок для различных параметров таргетинга.
/// </summary>
/// <param name = "getSuggestionsParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Возвращает список объектов (подсказок), удовлетворяющих запросу.
/// Для разделов countries, positions, interest_categories, religions, user_devices, user_os, user_browsers ответ возвращается в виде массива объектов со следующими полями:
/// id — идентификатор объекта
/// name — название объекта
/// Для раздела regions ответ возвращается в виде массива объектов со следующими полями:
/// id — идентификатор региона
/// name — название региона
/// type (необязательное) — название типа региона (область, автономный округ, край)
/// Для разделов cities, districts, streets ответ возвращается в виде массива объектов со следующими полями:
/// id — идентификатор объекта
/// name — название объекта
/// parent — название города или страны, в котором находится объект
/// Для раздела schools ответ возвращается в виде массива объектов со следующими полями:
/// id — идентификатор учебного заведения
/// name — название учебного заведения
/// desc — полное название учебного заведения
/// type — тип учебного заведения
/// school — школа
/// university — университет
/// faculty — факультет
/// chair — кафедра
/// parent — название города, в котором находится учебное заведение
/// Для раздела interests ответ возвращается в виде массива строк.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getSuggestions
/// </remarks>
Task<ReadOnlyCollection<object>> GetSuggestionsAsync(GetSuggestionsParams getSuggestionsParams);
/// <summary>
/// Возвращает список аудиторий ретаргетинга.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого находятся аудитории. целое число
/// </param>
/// <param name = "extended">
/// Если 1, в результатах будет указан код для размещения на сайте.
/// Устаревший параметр. Используется только для старых групп ретаргетинга, которые пополнялись без помощи пикселя. Для новых аудиторий его следует опускать. флаг, может принимать значения 1 или 0
/// </param>
/// <returns>
/// Возвращает массив объектов, описывающих группы ретаргетинга. Каждый объект содержит следующие поля:
/// id (integer) — идентификатор аудитории;
/// name (string) — название аудитории ретаргетинга;
/// last_updated (integer) — дата и время последнего пополнения аудитории в формате Unixtime;
/// is_audience (integer, 1) — 1, если группа является аудиторией (т.е.может быть пополнена при помощи пикселя);
/// is_shared (integer, 1) — 1, если группа является копией (см. метод ads.shareTargetGroup);
/// audience_count (integer) — приблизительное количество пользователей, входящих в аудиторию;
/// lifetime (integer) — количество дней, через которое пользователи, добавляемые в аудиторию ретаргетинга, будут автоматически исключены из неё;
/// file_source (integer, 1) — признак пополнения аудитории через файл;
/// api_source (integer, 1) — признак пополнения аудитории через метод ads.importTargetContacts;
/// lookalike_source (integer, 1) — признак аудитории, полученной при помощи Look-a-Like.
/// pixel (string) — код для размещения на сайте рекламодателя. Возвращается, если параметр extended = 1 (только для старых групп).
/// domain (string) — домен сайта, где размещен код учета пользователей (только для старых групп).
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getTargetGroups
/// </remarks>
Task<ReadOnlyCollection<object>> GetTargetGroupsAsync(long accountId, long? clientId = null, bool? extended = null);
/// <summary>
/// Возвращает список пикселей ретаргетинга.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого находятся пиксели. целое число
/// </param>
/// <returns>
/// Возвращает массив объектов, каждый из которых содержит следующие поля:
/// target_pixel_id (integer) — идентификатор пикселя;
/// name (string) — название пикселя;
/// last_updated (integer) — дата и время последнего использования пикселя в формате Unixtime;
/// domain (string) — домен сайта, где размещен пиксель;
/// category_id (integer) — идентификатор категории сайта, где размещён пиксель (см. раздел interest_categories метода ads.getSuggestions);
/// pixel (string) — код для размещения на сайте рекламодателя.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getTargetPixels
/// </remarks>
Task<ReadOnlyCollection<object>> GetTargetPixelsAsync(long accountId, long? clientId = null);
/// <summary>
/// Возвращает размер целевой аудитории таргетинга, а также рекомендованные значения CPC и CPM.
/// </summary>
/// <param name = "getTargetingStatsParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// Возвращает объект, описывающий целевую аудиторию и содержащий следующие поля:
/// audience_count (integer) — размер целевой аудитории
/// recommended_cpc (number) — рекомендованная цена для объявлений за клики, указана в рублях с копейками в дробной части.
/// recommended_cpm (number)— рекомендованная цена для объявлений за показы, указана в рублях с копейками в дробной части.
/// Обратите внимание, минимальный размер целевой аудитории — 100 человек. Если заданным критериям соответствует меньшее количество пользователей, размер аудитории будет считаться равным нулю.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getTargetingStats
/// </remarks>
Task<object> GetTargetingStatsAsync(GetTargetingStatsParams getTargetingStatsParams);
/// <summary>
/// Возвращает URL-адрес для загрузки фотографии рекламного объявления.
/// </summary>
/// <param name = "adFormat">
/// Формат объявления:
/// 1 — изображение и текст;
/// 2 — большое изображение;
/// 3 — эксклюзивный формат;
/// 4 — продвижение сообществ или приложений, квадратное изображение;
/// 5 — приложение в новостной ленте (устаревший);
/// 6 — мобильное приложение;
/// 9 — запись в сообществе.
/// обязательный параметр, целое число
/// </param>
/// <returns>
/// Возвращает url-адрес для загрузки изображения.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getUploadURl
/// </remarks>
Task<Uri> GetUploadUrlAsync(long adFormat);
/// <summary>
/// Возвращает URL-адрес для загрузки видеозаписи рекламного объявления.
/// </summary>
/// <returns>
/// Возвращает url-адрес для загрузки видеоролика.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.getVideoUploadURl
/// </remarks>
Task<Uri> GetVideoUploadUrlAsync();
/// <summary>
/// Импортирует список контактов рекламодателя для учета зарегистрированных во ВКонтакте пользователей в аудитории ретаргетинга.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "targetGroupId">
/// Идентификатор аудитории таргетинга. обязательный параметр, целое число
/// </param>
/// <param name = "contacts">
/// Список телефонов, email адресов или идентификаторов пользователей, указанных через запятую. Также принимаются их MD5-хеши. обязательный параметр, строка
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого находится аудитория. целое число
/// </param>
/// <returns>
/// Возвращает количество обработанных контактов.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.importTargetContacts
/// </remarks>
Task<object> ImportTargetContactsAsync(long accountId, long targetGroupId, string contacts, long? clientId = null);
/// <summary>
/// Удаляет администраторов и/или наблюдателей из рекламного кабинета.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "ids">
/// Сериализованный JSON-массив, содержащий id удаляемых администраторов. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив значений - ответов на каждый запрос в массиве data. Соответствующее значение в выходном массиве равно true, если администратор успешно удален, и false в другом случае.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.removeOfficeUsers
/// </remarks>
Task<ReadOnlyCollection<object>> RemoveOfficeUsersAsync(long accountId, string ids);
/// <summary>
/// Принимает запрос на исключение контактов рекламодателя из аудитории ретаргетинга.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "targetGroupId">
/// Идентификатор аудитории таргетинга. обязательный параметр, целое число
/// </param>
/// <param name = "contacts">
/// Список телефонов, email адресов или идентификаторов пользователей, указанных через запятую. Также принимаются их MD5-хеши. обязательный параметр, строка
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого находится аудитория. целое число
/// </param>
/// <returns>
/// Возвращает 1 в случае успешного принятия заявки на исключение аудитории.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.removeTargetContacts
/// </remarks>
Task<bool> RemoveTargetContactsAsync(long accountId, long targetGroupId, string contacts, long? clientId = null);
/// <summary>
/// Сохраняет результат поиска похожей аудитории.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "requestId">
/// Идентификатор запроса на поиск похожей аудитории. Получить список всех запросов на поиск похожей аудитории для данного кабинета можно с помощью ads.getLookalikeRequests обязательный параметр, целое число
/// </param>
/// <param name = "level">
/// Уровень конкретного размера похожей аудитории для сохранения. Получить список всех доступных размеров аудиторий можно с помощью ads.getLookalikeRequests. обязательный параметр, целое число
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// идентификатор клиента, для которого будут сохраняться аудитория. целое число
/// </param>
/// <returns>
/// Возвращает объект с полями:
///
/// retargeting_group_id – идентификатор группы ретаргетинга, в которую будет сохранена запрошенная похожая аудитория.
/// audience_count – размер запрошенной похожей аудитории.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.saveLookalikeRequestResult
/// </remarks>
Task<object> SaveLookalikeRequestResultAsync(long accountId, long requestId, long level, long? clientId = null);
/// <summary>
/// Предоставляет доступ к аудитории ретаргетинга другому рекламному кабинету. В результате выполнения метода возвращается идентификатор аудитории для указанного кабинета.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "targetGroupId">
/// Идентификатор исходной аудитории. обязательный параметр, целое число
/// </param>
/// <param name = "clientId">
/// Только для рекламных агентств.
/// id клиента, в рекламном кабинете которого находится исходная аудитория. целое число
/// </param>
/// <param name = "shareWithClientId">
/// Id клиента, рекламному кабинету которого необходимо предоставить доступ к аудитории. целое число
/// </param>
/// <returns>
/// Возвращает объект со следующими полями:
/// id — идентификатор аудитории.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.shareTargetGroup
/// </remarks>
Task<object> ShareTargetGroupAsync(long accountId, long targetGroupId, long? clientId = null, long? shareWithClientId = null);
/// <summary>
/// Редактирует рекламные объявления.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "data">
/// Сериализованный JSON-массив объектов, описывающих изменения в объявлениях. Описание объектов ad_edit_specification см. ниже обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на каждый запрос в массиве data. Соответствующий объект в выходном массиве содержит идентификатор изменяемого объявления и, в случае возникновения ошибки, поля error_code и error_desc.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.updateAds
/// </remarks>
Task<ReadOnlyCollection<object>> UpdateAdsAsync(long accountId, string data);
/// <summary>
/// Редактирует рекламные кампании.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "data">
/// Сериализованный JSON-массив объектов, описывающих изменения в кампаниях. Описание объектов campaign_mod_specification см. ниже. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на каждый запрос в массиве data. Соответствующий объект в выходном массиве содержит идентификатор изменяемого клиента и, в случае возникновения ошибки, поля error_code и error_desc.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.updateCampaigns
/// </remarks>
Task<ReadOnlyCollection<object>> UpdateCampaignsAsync(long accountId, string data);
/// <summary>
/// Редактирует клиентов рекламного агентства.
/// </summary>
/// <param name = "accountId">
/// Идентификатор рекламного кабинета. обязательный параметр, целое число
/// </param>
/// <param name = "data">
/// Сериализованный JSON-массив объектов, описывающих изменения в клиентах. Описание объектов client_mod_specification см. ниже. обязательный параметр, строка
/// </param>
/// <returns>
/// Возвращает массив ответов на каждый запрос в массиве data. Соответствующий объект в выходном массиве содержит id изменяемого клиента и, в случае возникновения ошибки, поля error_code и error_desc.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.updateClients
/// </remarks>
Task<ReadOnlyCollection<object>> UpdateClientsAsync(long accountId, string data);
/// <summary>
/// Редактирует аудиторию ретаргетинга.
/// </summary>
/// <param name = "updateTargetGroupParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// В случае успеха метод возвратит 1.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.updateTargetGroup
/// </remarks>
Task<bool> UpdateTargetGroupAsync(UpdateTargetGroupParams updateTargetGroupParams);
/// <summary>
/// Редактирует пиксель ретаргетинга.
/// </summary>
/// <param name = "updateTargetPixelParams">
/// Входные параметры запроса.
/// </param>
/// <returns>
/// После успешного выполнения возвращает 1.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте http://vk.com/dev/ads.updateTargetPixel
/// </remarks>
Task<bool> UpdateTargetPixelAsync(UpdateTargetPixelParams updateTargetPixelParams);
}
} | 48.04878 | 469 | 0.718704 | [
"MIT"
] | Azrael141/vk | VkNet/Abstractions/Category/Async/IAdsCategoryAsync.cs | 75,663 | C# |
using System;
namespace Ledger
{
internal static class ConsoleHelper
{
public static void PrintError(string message)
{
using (new ColoredConsole(ConsoleColor.Red))
Console.WriteLine(message);
}
}
}
| 18.785714 | 56 | 0.596958 | [
"MIT"
] | soheilpro/Ledger | Sources/Ledger/ConsoleHelper.cs | 263 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Dominion.Rules.CardTypes;
namespace Dominion.Rules
{
public static class MyExtensions
{
public static void Times(this int count, Action action)
{
if (action != null)
{
for (int i = 1; i <= count; i++)
action();
}
}
public static IEnumerable<T> Items<T>(this int count, Func<T> builder)
{
if (builder == null)
yield break;
for (int i = 1; i <= count; i++)
yield return builder();
}
public static IEnumerable<T> Items<T>(this int count, Func<int, T> builder)
{
if (builder == null)
yield break;
for (int i = 1; i <= count; i++)
yield return builder(i);
}
public static IEnumerable<T> WithDistinctTypes<T>(this IEnumerable<T> input)
{
return input.Distinct(new SameTypeEqualityComparer<T>());
}
public static bool AllSame<T,T2>(this IEnumerable<T> items, Func<T, T2> selector)
{
return items.Select(selector).Distinct().Count() < 2;
}
}
} | 27.93617 | 90 | 0.492003 | [
"MIT"
] | cardidemonaco/Dominion | Dominion.Rules/MyExtensions.cs | 1,313 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECS.Model
{
/// <summary>
/// The details of a capacity provider strategy. A capacity provider strategy can be set
/// when using the <a>RunTask</a> or <a>CreateCluster</a> APIs or as the default capacity
/// provider strategy for a cluster with the <a>CreateCluster</a> API.
///
///
/// <para>
/// Only capacity providers that are already associated with a cluster and have an <code>ACTIVE</code>
/// or <code>UPDATING</code> status can be used in a capacity provider strategy. The <a>PutClusterCapacityProviders</a>
/// API is used to associate a capacity provider with a cluster.
/// </para>
///
/// <para>
/// If specifying a capacity provider that uses an Auto Scaling group, the capacity provider
/// must already be created. New Auto Scaling group capacity providers can be created
/// with the <a>CreateCapacityProvider</a> API operation.
/// </para>
///
/// <para>
/// To use a Fargate capacity provider, specify either the <code>FARGATE</code> or <code>FARGATE_SPOT</code>
/// capacity providers. The Fargate capacity providers are available to all accounts and
/// only need to be associated with a cluster to be used in a capacity provider strategy.
/// </para>
/// </summary>
public partial class CapacityProviderStrategyItem
{
private int? _base;
private string _capacityProvider;
private int? _weight;
/// <summary>
/// Gets and sets the property Base.
/// <para>
/// The <i>base</i> value designates how many tasks, at a minimum, to run on the specified
/// capacity provider. Only one capacity provider in a capacity provider strategy can
/// have a <i>base</i> defined. If no value is specified, the default value of <code>0</code>
/// is used.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=100000)]
public int Base
{
get { return this._base.GetValueOrDefault(); }
set { this._base = value; }
}
// Check to see if Base property is set
internal bool IsSetBase()
{
return this._base.HasValue;
}
/// <summary>
/// Gets and sets the property CapacityProvider.
/// <para>
/// The short name of the capacity provider.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string CapacityProvider
{
get { return this._capacityProvider; }
set { this._capacityProvider = value; }
}
// Check to see if CapacityProvider property is set
internal bool IsSetCapacityProvider()
{
return this._capacityProvider != null;
}
/// <summary>
/// Gets and sets the property Weight.
/// <para>
/// The <i>weight</i> value designates the relative percentage of the total number of
/// tasks launched that should use the specified capacity provider. The <code>weight</code>
/// value is taken into consideration after the <code>base</code> value, if defined, is
/// satisfied.
/// </para>
///
/// <para>
/// If no <code>weight</code> value is specified, the default value of <code>0</code>
/// is used. When multiple capacity providers are specified within a capacity provider
/// strategy, at least one of the capacity providers must have a weight value greater
/// than zero and any capacity providers with a weight of <code>0</code> will not be used
/// to place tasks. If you specify multiple capacity providers in a strategy that all
/// have a weight of <code>0</code>, any <code>RunTask</code> or <code>CreateService</code>
/// actions using the capacity provider strategy will fail.
/// </para>
///
/// <para>
/// An example scenario for using weights is defining a strategy that contains two capacity
/// providers and both have a weight of <code>1</code>, then when the <code>base</code>
/// is satisfied, the tasks will be split evenly across the two capacity providers. Using
/// that same logic, if you specify a weight of <code>1</code> for <i>capacityProviderA</i>
/// and a weight of <code>4</code> for <i>capacityProviderB</i>, then for every one task
/// that is run using <i>capacityProviderA</i>, four tasks would use <i>capacityProviderB</i>.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=1000)]
public int Weight
{
get { return this._weight.GetValueOrDefault(); }
set { this._weight = value; }
}
// Check to see if Weight property is set
internal bool IsSetWeight()
{
return this._weight.HasValue;
}
}
} | 40.479167 | 123 | 0.625665 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/ECS/Generated/Model/CapacityProviderStrategyItem.cs | 5,829 | C# |
//-----------------------------------------------------------------------------
// Runtime: 80ms
// Memory Usage: 22.9 MB
// Link: https://leetcode.com/submissions/detail/356457712/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
public class _060_PermutationSequence
{
public string GetPermutation(int n, int k)
{
var nums = new List<int>();
var group = 1;
for (int i = 1; i <= n; i++)
{
nums.Add(i);
group *= i;
}
if (k > group) return "";
k = k > 0 ? k - 1 : 0;
var result = new StringBuilder();
var index = -1;
while (n > 0)
{
group /= n;
index = k / group;
result.Append(nums[index]);
nums.RemoveAt(index);
k = k % group;
n--;
}
return result.ToString();
}
}
}
| 24.954545 | 79 | 0.362477 | [
"MIT"
] | BigEggStudy/LeetCode-CS | LeetCode/0051-0100/060-PermutationSequence.cs | 1,098 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using App.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace App.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ConfirmEmailModel : PageModel
{
private readonly UserManager<User> _userManager;
public ConfirmEmailModel(UserManager<User> userManager)
{
_userManager = userManager;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";
return Page();
}
}
}
| 29.979167 | 119 | 0.637248 | [
"MIT"
] | RB-Labs/HMC | App/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs | 1,441 | C# |
namespace DailyWallpainter.UI
{
partial class frmWorking
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.label1 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(12, 41);
this.progressBar1.MarqueeAnimationSpeed = 30;
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(385, 11);
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
this.progressBar1.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(30, 21);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(346, 12);
this.label1.TabIndex = 1;
this.label1.Text = "Daily Wallpainter를 설치하는 중입니다. 잠시만 기다려주세요...";
//
// pictureBox1
//
this.pictureBox1.Image = global::DailyWallpainter.Properties.Resources.wait16;
this.pictureBox1.Location = new System.Drawing.Point(12, 18);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(17, 18);
this.pictureBox1.TabIndex = 2;
this.pictureBox1.TabStop = false;
//
// frmWorking
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(409, 66);
this.ControlBox = false;
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.progressBar1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "frmWorking";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = " ";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox pictureBox1;
}
} | 40.358696 | 107 | 0.582548 | [
"BSD-3-Clause"
] | iamxail/DailyWallpainter | DailyWallpainter/UI/frmWorking.Designer.cs | 3,751 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.Batch.Inputs
{
public sealed class AccountIdentityArgs : Pulumi.ResourceArgs
{
[Input("identityIds")]
private InputList<string>? _identityIds;
/// <summary>
/// Specifies a list of user assigned identity ids. Required if `type` is `UserAssigned`.
/// </summary>
public InputList<string> IdentityIds
{
get => _identityIds ?? (_identityIds = new InputList<string>());
set => _identityIds = value;
}
/// <summary>
/// The Principal ID for the Service Principal associated with the system assigned identity of this Batch Account.
/// </summary>
[Input("principalId")]
public Input<string>? PrincipalId { get; set; }
/// <summary>
/// The Tenant ID for the Service Principal associated with the system assigned identity of this Batch Account.
/// </summary>
[Input("tenantId")]
public Input<string>? TenantId { get; set; }
/// <summary>
/// The identity type of the Batch Account. Possible values are `SystemAssigned` and `UserAssigned`.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
public AccountIdentityArgs()
{
}
}
}
| 33.08 | 122 | 0.619105 | [
"ECL-2.0",
"Apache-2.0"
] | ScriptBox99/pulumi-azure | sdk/dotnet/Batch/Inputs/AccountIdentityArgs.cs | 1,654 | 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>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client.LocationCFValuePartialBuilder;
public static class LocationCFValuePartialExtensions
{
public static Partial<LocationCFValue> WithLocation(this Partial<LocationCFValue> it)
=> it.AddFieldName("location");
public static Partial<LocationCFValue> WithLocation(this Partial<LocationCFValue> it, Func<Partial<TDLocation>, Partial<TDLocation>> partialBuilder)
=> it.AddFieldName("location", partialBuilder(new Partial<TDLocation>(it)));
}
| 34.619048 | 152 | 0.69945 | [
"Apache-2.0"
] | JetBrains/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Partials/LocationCFValuePartialBuilder.generated.cs | 1,454 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace NDExt.Utils
{
public static class FileUtil
{
/// <summary>
/// ディレクトリを削除して作成しなおします。
/// </summary>
/// <param name="path"></param>
public static void RecreateDirectory(string path)
{
DeleteDirectory(path);
CreateDirectory(path);
}
/// <summary>
/// ファイルを削除します。
/// </summary>
/// <param name="path"></param>
public static void DeleteFile(string path)
{
if ( File.Exists(path))
{
try {
File.Delete(path);
} catch
{
// do nothing
}
}
}
/// <summary>
/// ディレクトリを作成します。
/// </summary>
/// <param name="path"></param>
public static void CreateDirectory(string path)
{
var ext = GetExtension(path);
var dirPath = string.IsNullOrEmpty(ext) ? path : Path.GetDirectoryName(path);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
}
/// <summary>
/// ディレクトリにファイルをコピーします。
/// </summary>
/// <param name="source"></param>
/// <param name="searchPattern"></param>
/// <param name="dest"></param>
public static void CopyFiles(string source,string searchPattern,string dest)
{
var files = Directory.EnumerateFiles(source, searchPattern);
foreach ( var file in files)
{
var destFileName = Path.GetFileName(file);
try
{
File.Copy(file, Path.Combine(dest, destFileName), true);
}
catch
{
// do nothing
}
}
}
/// <summary>
/// 拡張子を取得します
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetExtension(string path)
{
var ret = "";
for (; ; )
{
var ext = Path.GetExtension(path);
if (string.IsNullOrEmpty(ext))
break;
path = path.Substring(0, path.Length - ext.Length);
ret = ext + ret;
}
return ret;
}
/// <summary>
/// ディレクトリを削除します。
/// </summary>
/// <param name="path"></param>
/// <param name="shouldRootDelete"></param>
public static void DeleteDirectory(string path, bool shouldRootDelete = true)
{
if (!Directory.Exists(path)) return;
var deleteDirectories = Directory.GetDirectories(path).ToList();
deleteDirectories.ForEach(d => DeleteDirectory(d));
if (!shouldRootDelete) return;
try
{
Directory.Delete(path, true);
}
catch (IOException)
{
Directory.Delete(path, true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(path, true);
}
}
/// <summary>
/// ディレクトリをコピーします。
/// </summary>
/// <param name="sourceFolder"></param>
/// <param name="destFolder"></param>
public static void CopyDirectory(string sourceFolder, string destFolder)
{
// コピー元、コピー先が存在しない場合は何もしない
if (string.IsNullOrEmpty(sourceFolder) || string.IsNullOrEmpty(destFolder)) return;
// コピー元フォルダが存在しない場合は何もしない
if (!Directory.Exists(sourceFolder)) return;
// コピー先フォルダが存在しない場合は新規作成
if (!Directory.Exists(destFolder))
{
Directory.CreateDirectory(destFolder);
}
// ファイルをコピー
var files = Directory.GetFiles(sourceFolder);
foreach (var file in files)
{
var fileName = Path.GetFileName(file);
var copyTarget = Path.Combine(destFolder, fileName);
File.Copy(file, copyTarget, true);
}
// フォルダを再帰的にコピー
var folders = Directory.GetDirectories(sourceFolder);
foreach (var folder in folders)
{
var copyTarget = Path.Combine(destFolder, Path.GetFileName(folder));
CopyDirectory(folder, copyTarget);
}
}
}
}
| 27.964286 | 95 | 0.47914 | [
"MIT"
] | denso-create/NextDesign-NDExt | src/NDExt/Utils/FileUtil.cs | 5,070 | C# |
using System;
using DbKeeperNet.Engine;
namespace DbKeeperNet.Extensions.Pgsql.Checkers
{
public class PgsqlDatabaseServiceViewChecker : PgsqlDatabaseServiceCheckerBase, IDatabaseServiceViewChecker
{
public PgsqlDatabaseServiceViewChecker(IDatabaseService databaseService)
: base(databaseService)
{
}
public bool Exists(string name)
{
if (String.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
string[] restrictions = new string[3];
restrictions[2] = name;
return RetrieveSchemaInformationAndReturnTrueIfRowExists(@"Views", restrictions);
}
}
} | 27.192308 | 111 | 0.664781 | [
"BSD-3-Clause"
] | DbKeeperNet/DbKeeperNet | DbKeeperNet.Extensions.Pgsql/Checkers/PgsqlDatabaseServiceViewChecker.cs | 709 | C# |
using System.Collections.Generic;
using System.ComponentModel.Composition;
using ZeraSystems.CodeNanite.Expansion;
using ZeraSystems.CodeStencil.Contracts;
namespace ZeraSystems.CodeNanite.WebAPI
{
/// <summary>
/// There are 10 elements in the String Array used by the
/// 0 - This is the name of the publisher
/// 1 - This is the title of the Code Nanite
/// 2 - This is the description
/// 3 - Version Number
/// 4 - Label of the Code Nanite
/// 5 - Namespace
/// 6 - Release Date
/// 7 - Name to use for Expander Label
/// 9 - RESERVED
/// 10 - RESERVED
/// </summary>
[Export(typeof(ICodeStencilCodeNanite))]
[CodeStencilCodeNanite(new[]
{
"Zera Systems Inc.",
"Api Model Generator",
"Generates Api Data Models",
"1.0",
"CreateApiModels",
"ZeraSystems.CodeNanite.WebAPI",
"04/16/2019",
"CREATE_API_MODELS",
"1",
"",
""
})]
public partial class CreateApiModels : ExpansionBase, ICodeStencilCodeNanite
{
public string Input { get; set; }
public string Output { get; set; }
public int Counter { get; set; }
public List<string> OutputList { get; set; }
public List<ISchemaItem> SchemaItem { get; set; }
public List<IExpander> Expander { get; set; }
public List<string> InputList { get; set; }
public void ExecutePlugin()
{
Initializer(SchemaItem, Expander);
MainFunction();
Output = ExpandedText.ToString();
}
}
} | 29.833333 | 80 | 0.590317 | [
"MIT"
] | codetstencil/zerasystems.stencils | webapi/src/ApiModels/CreateApiModels.cs | 1,613 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Castle.Core.Resource;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using EdFi.Ods.Common.Conventions;
using EdFi.Ods.Common.Extensions;
using EdFi.Ods.Common.Models.Resource;
namespace EdFi.Ods.Common.Models.Domain
{
public static class EntityExtensions
{
private static string[] PredefinedProperties =
{
"Id",
"CreateDate",
"LastModifiedDate"
};
/// <summary>
/// Returns the core name of the domain model entity if it is a core entity extension, otherwise the entity name.
/// </summary>
/// <param name="entity">A domain model entity</param>
/// <returns>The core name of the domain model entity if it is a core entity extension, otherwise the entity name.</returns>
public static string ResolvedEdFiEntityName(this Entity entity)
{
return entity.ResolvedEdFiEntity()
.Name;
}
/// <summary>
/// Returns the core name of the domain model entity if it is a core entity extension, otherwise the entity.
/// </summary>
/// <param name="entity">A domain model entity</param>
/// <returns>The core domain model entity if it is a core entity extension, otherwise the entity.</returns>
public static Entity ResolvedEdFiEntity(this Entity entity)
{
return entity.EdFiStandardEntity ?? entity;
}
/// <summary>
/// Returns the entity's schema name represented in proper-case form.
/// </summary>
/// <param name="entity">The Entity to be evaluated.</param>
/// <returns>The proper-case representation of the entity's schema.</returns>
public static string SchemaProperCaseName(this Entity entity)
{
return entity.DomainModel.SchemaNameMapProvider
.GetSchemaMapByPhysicalName(entity.Schema)
.ProperCaseName;
}
/// <summary>
/// Gets the URI segment representation of an aggregate root entity's schema.
/// </summary>
/// <param name="entity">The aggregate root <see cref="Entity" /> whose URI segment schema name is to be obtained.</param>
/// <returns>The URI segment representation of the schema.</returns>
public static string SchemaUriSegment(this Entity entity)
{
if (!entity.IsAggregateRoot)
{
throw new Exception("URI segments are only applicable to aggregate root entities.");
}
return entity.DomainModel.SchemaNameMapProvider
.GetSchemaMapByPhysicalName(entity.Schema)
.UriSegment;
}
/// <summary>
/// Gets the namespace qualified full name of the NHibernate Entity for
/// the given DomainModel entity.
/// </summary>
/// <param name="entity">A domain model entity</param>
/// <param name="properCaseName">Proper case name associated with entity</param>
/// <param name="classNameSuffix">And specialized suffix that should be added to the class name based on the caller's context.</param>
/// <returns>Namespace qualified full name of the NHibernate Entity</returns>
public static string EntityTypeFullName(this Entity entity, string properCaseName, string classNameSuffix = "")
{
return String.Format(
"{0}.{1}{2}",
AggregateNamespace(entity, properCaseName),
entity.IsEntityExtension
? entity.Name
: entity.ResolvedEdFiEntityName(),
classNameSuffix);
}
/// <summary>
/// Provides the NHibernate Entity Aggregate namespace for the aggregate of the provided domain entity.
/// </summary>
/// <param name="entity">A domain model entity</param>
/// <param name="properCaseName">Proper case name associated with entity</param>
/// <returns>NHibernate Entity Aggregate namespace for the aggregate of the provided domain entity</returns>
public static string AggregateNamespace(this Entity entity, string properCaseName)
{
return Namespaces.Entities.NHibernate.GetAggregateNamespace(
entity.Aggregate.Name,
properCaseName,
entity.IsExtensionEntity);
}
/// <summary>
/// Provides the complete list of extensions for the provided entity.
/// </summary>
/// <param name="entity">A domain model entity</param>
/// <returns>Complete list of extensions for the provided entity.</returns>
public static IEnumerable<Entity> GetAllExtensions(this Entity entity) => entity.Extensions
.Concat(
entity.AggregateExtensionChildren.Select(
a => a.OtherEntity))
.Concat(
entity.AggregateExtensionOneToOnes.Select(
a => a.OtherEntity));
/// <summary>
/// Check if entity is abstract and requires no composite id
/// </summary>
/// <remarks>
/// Classes with composite ids must not be abstract because
/// "...a persistent object is its own identifier. There is no convenient "handle" other than the object itself.
/// You must instantiate an instance of the persistent class itself and populate its identifier properties..."
/// "NHibernate - Relational Persistence for Idiomatic .NET", http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-compositeid
/// </remarks>
/// <param name="entity">A domain model entity</param>
/// <returns></returns>
public static bool IsAbstractRequiringNoCompositeId(this Entity entity) => entity.IsAbstract && entity.Identifier.Properties.Count == 1;
/// <summary>
/// Checks if the entity is a descriptor
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static bool IsDescriptorBaseEntity(this Entity entity)
=> entity.FullName.Equals(new FullName(EdFiConventions.PhysicalSchemaName, "Descriptor"));
/// <summary>
/// Indicates whether the supplied <see cref="Entity"/> has a discriminator.
/// </summary>
/// <param name="entity">The <see cref="Entity"/> that is being inspected.</param>
/// <returns><b>true</b> if the type has a discriminator; otherwise <b>false</b>.</returns>
public static bool HasDiscriminator(this Entity entity)
{
// Non-aggregate root entities do not have discriminators (they cannot be derived)
if (!entity.IsAggregateRoot)
return false;
// The discriminator will always be on the root of the type hierarchy (derived classes will not have a discriminator)
if (entity.IsDerived)
return false;
// Ed-Fi descriptors cannot be derived
if (entity.IsDescriptorBaseEntity())
return false;
// SchoolYearType is also not derivable
if (entity.FullName.Equals(new FullName(EdFiConventions.PhysicalSchemaName, "SchoolYearType")))
return false;
return true;
}
/// <summary>
/// Indicates whether the specified entity can be the target of a reference in the API resource models.
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static bool IsReferenceable(this Entity entity)
{
// Only aggregate roots can be referenced
if (!entity.IsAggregateRoot)
return false;
// Descriptors cannot be referenced (they are referenced in the API using URI values)
if (entity.IsDescriptorEntity || entity.IsDescriptorBaseEntity())
return false;
return true;
}
/// <summary>
/// Gets the associations that reference other aggregate roots (excluding descriptors).
/// </summary>
/// <param name="entity">The entity whose associations are to be evaluated.</param>
/// <param name="includeInherited">Indicates whether to include associations that are inherited from the base type.</param>
/// <returns>The <see cref="AssociationView"/> instances that reference other aggregate roots.</returns>
public static IEnumerable<AssociationView> GetAssociationsToReferenceableAggregateRoots(
this Entity entity,
bool includeInherited = false)
{
return entity
.NonNavigableParents
.Concat(
includeInherited
? entity.InheritedNonNavigableParents
: Enumerable.Empty<AssociationView>())
.Where(a => a.OtherEntity.IsReferenceable());
}
/// <summary>
/// Determines if a entityProperty is defined in the AggregateRootWithCompositeKey base class
/// </summary>
/// <param name="entityProperty"></param>
/// <returns></returns>
public static bool IsAlreadyDefinedInCSharpEntityBaseClasses(this EntityProperty entityProperty)
=> entityProperty.PropertyName.EqualsIgnoreCase("Id")
|| entityProperty.PropertyName.EqualsIgnoreCase("CreateDate")
|| entityProperty.PropertyName.EqualsIgnoreCase("LastModifiedDate");
/// <summary>
/// Returns if these properties are predefined in the base class.
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
public static bool IsPredefinedProperty(this EntityProperty property)
=> IsPredefinedProperty(property.PropertyName);
public static bool IsPredefinedProperty(string propertyName)
=> PredefinedProperties.Contains(propertyName);
/// <summary>
/// Generates the column name for a property
/// </summary>
/// <param name="property"></param>
/// <param name="databaseEngine"></param>
/// <param name="legacyColumnName"></param>
/// <returns></returns>
public static string ColumnName(this EntityProperty property, string databaseEngine, string legacyColumnName)
{
return property.ColumnNameByDatabaseEngine == null || property.ColumnNameByDatabaseEngine.Count == 0
? legacyColumnName
: property.ColumnNameByDatabaseEngine.TryGetValue(databaseEngine, out string columnName)
? columnName
: legacyColumnName;
}
/// <summary>
/// Gets the database-specific table name for the entity.
/// </summary>
/// <param name="entity">The entity for which to obtain the physical table name.</param>
/// <param name="databaseEngine">The key representing the database engine.</param>
/// <param name="explicitTableName">Explicit name to use instead of the <see cref="Entity.Name" /> property if no
/// entry is found for the specified database engine.</param>
/// <returns></returns>
public static string TableName(this Entity entity, string databaseEngine, string explicitTableName = null)
{
return entity.TableNameByDatabaseEngine == null || entity.TableNameByDatabaseEngine.Count == 0
? explicitTableName ?? entity.Name
: entity.TableNameByDatabaseEngine.TryGetValue(databaseEngine, out string tableName)
? tableName
: explicitTableName ?? entity.Name;
}
}
}
| 48.413793 | 145 | 0.597024 | [
"Apache-2.0"
] | gmcelhanon/Ed-Fi-ODS-1 | Application/EdFi.Ods.Common/Models/Domain/EntityExtensions.cs | 12,638 | C# |
using System;
using System.Text.RegularExpressions;
using NUnit.Framework;
namespace Faker.Tests
{
[TestFixture]
public class InternetFixture
{
[Test]
public void Should_Create_Email_Address()
{
var email = Internet.Email();
Console.WriteLine($@"Email=[{email}]");
Assert.IsTrue(Regex.IsMatch(email, @".+@.+\.\w+"));
}
[Test]
public void Should_Create_Email_Address_From_Given_Name()
{
var email = Internet.Email("Bob Smith");
Console.WriteLine($@"Email=[{email}]");
Assert.IsTrue(Regex.IsMatch(email, @"bob[_\.]smith@.+\.\w+"));
}
[Test]
public void Should_Create_Free_Email()
{
var email = Internet.FreeEmail();
Console.WriteLine($@"Email=[{email}]");
Assert.IsTrue(Regex.IsMatch(email, @".+@(gmail|hotmail|yahoo)\.com"));
}
[Test]
public void Should_Create_User_Name()
{
var username = Internet.UserName();
Console.WriteLine($@"UserName=[{username}]");
Assert.IsTrue(Regex.IsMatch(username, @"[a-z]+((_|\.)[a-z]+)?"));
}
[Test]
public void Should_Create_User_Name_From_Given_Name()
{
var username = Internet.UserName("Bob Smith");
Console.WriteLine($@"UserName=[{username}]");
Assert.IsTrue(Regex.IsMatch(username, @"bob[_\.]smith"));
}
[Test]
public void Should_Get_Domain_Name()
{
var domain = Internet.DomainName();
Console.WriteLine($@"DomainName=[{domain}]");
Assert.IsTrue(Regex.IsMatch(domain, @"\w+\.\w+"));
}
[Test]
public void Should_Get_Url()
{
var url = Internet.Url();
Console.WriteLine($@"Url=[{url}]");
Assert.IsTrue(Regex.IsMatch(url,
@"(http:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})"));
}
[Test]
public void Should_Get_Secure_Url()
{
var url = Internet.SecureUrl();
Console.WriteLine($@"Url=[{url}]");
Assert.IsTrue(Regex.IsMatch(url,
@"(https:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})"));
}
[Test]
public void Should_Get_Domain_Word()
{
var word = Internet.DomainWord();
Console.WriteLine($@"DomainWord=[{word}]");
Assert.IsTrue(Regex.IsMatch(word, @"^\w+$"));
}
[Test]
public void Should_Get_Domain_Suffix()
{
var suffix = Internet.DomainSuffix();
Console.WriteLine($@"DomainSuffix=[{suffix}]");
Assert.IsTrue(Regex.IsMatch(suffix, @"^\w+(\.\w+)?"));
}
}
} | 30.862745 | 230 | 0.498094 | [
"MIT"
] | ahems/faker-cs | tests/Faker.Tests/InternetFixture.cs | 3,150 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using Dolittle.ReadModels;
namespace Dolittle.Queries
{
/// <summary>
/// Defines a query for a specified type of <see cref="IReadModel"/>.
/// </summary>
/// <typeparam name="T">The type to query.</typeparam>
/// <remarks>
/// Types inheriting from this interface will be picked up proxy generation, deserialized and dispatched to the
/// correct instance of <see cref="IQueryProviderFor{T}"/>.
/// </remarks>
public interface IQueryFor<T> : IQuery where T : IReadModel
{
}
}
| 40.857143 | 115 | 0.52331 | [
"MIT"
] | dolittle-einar/Runtime | Source/Queries/IQueryFor.cs | 860 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryString
{
[OutputConstructor]
private WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryString()
{
}
}
}
| 34.181818 | 162 | 0.789894 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryString.cs | 752 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace XF_InstagramMini.Models
{
public class Activity
{
public int UserId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl {
get
{
return "http://lorempixel.com/100/100/people/" + UserId;
}
}
}
}
| 20.590909 | 71 | 0.560706 | [
"MIT"
] | LuizMarcello/XF_InstagramMini | XF_InstagramMini/XF_InstagramMini/XF_InstagramMini/Models/Activity.cs | 455 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SailScores.Api.Dtos;
namespace SailScores.Web.Areas.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class RacesController : ControllerBase
{
private readonly Core.Services.IRaceService _service;
private readonly Services.IAuthorizationService _authService;
private readonly IMapper _mapper;
public RacesController(
Core.Services.IRaceService service,
Services.IAuthorizationService authService,
IMapper mapper)
{
_service = service;
_authService = authService;
_mapper = mapper;
}
[HttpGet]
public async Task<IEnumerable<RaceDto>> Get(Guid clubId)
{
var races = await _service.GetRacesAsync(clubId);
return _mapper.Map<List<RaceDto>>(races);
}
[HttpGet("{identifier}")]
public async Task<RaceDto> Get([FromRoute] String identifier)
{
var r = await _service.GetRaceAsync(Guid.Parse(identifier));
return _mapper.Map<RaceDto>(r);
}
[HttpPost]
public async Task<ActionResult<Guid>> Post([FromBody] RaceDto race)
{
if (!await _authService.CanUserEdit(User, race.ClubId))
{
return Unauthorized();
}
return Ok(await _service.SaveAsync(race));
}
}
}
| 29.793103 | 79 | 0.637731 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SailScores/SailScores | SailScores.Web/Areas/Api/Controllers/RacesController.cs | 1,730 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Bot.Expressions;
namespace Microsoft.Bot.Builder.LanguageGeneration
{
/// <summary>
/// The template engine that loads .lg file and eval template based on memory/scope.
/// </summary>
public class TemplateEngine
{
private readonly ExpressionEngine expressionEngine;
/// <summary>
/// Initializes a new instance of the <see cref="TemplateEngine"/> class.
/// Return an empty engine, you can then use AddFile\AddFiles to add files to it,
/// or you can just use this empty engine to evaluate inline template.
/// </summary>
/// <param name="expressionEngine">The expression engine this template engine based on.</param>
public TemplateEngine(ExpressionEngine expressionEngine = null)
{
this.expressionEngine = expressionEngine ?? new ExpressionEngine();
}
/// <summary>
/// Gets or sets parsed LG templates.
/// </summary>
/// <value>
/// Parsed LG templates.
/// </value>
public List<LGTemplate> Templates { get; set; } = new List<LGTemplate>();
/// <summary>
/// Load .lg files into template engine
/// You can add one file, or mutlple file as once
/// If you have multiple files referencing each other, make sure you add them all at once,
/// otherwise static checking won't allow you to add it one by one.
/// </summary>
/// <param name="filePaths">Paths to .lg files.</param>
/// <param name="importResolver">resolver to resolve LG import id to template text.</param>
/// <returns>Teamplate engine with parsed files.</returns>
public TemplateEngine AddFiles(IEnumerable<string> filePaths, ImportResolverDelegate importResolver = null)
{
var totalLGResources = new List<LGResource>();
foreach (var filePath in filePaths)
{
var fullPath = Path.GetFullPath(ImportResolver.NormalizePath(filePath));
var rootResource = LGParser.Parse(File.ReadAllText(fullPath), fullPath);
var lgresources = rootResource.DiscoverDependencies(importResolver);
totalLGResources.AddRange(lgresources);
}
// Remove duplicated lg files by id
var deduplicatedLGResources = totalLGResources.GroupBy(x => x.Id).Select(x => x.First()).ToList();
Templates.AddRange(deduplicatedLGResources.SelectMany(x => x.Templates));
RunStaticCheck(Templates);
return this;
}
/// <summary>
/// Load single .lg file into template engine.
/// </summary>
/// <param name="filePath">Path to .lg file.</param>
/// <param name="importResolver">resolver to resolve LG import id to template text.</param>
/// <returns>Teamplate engine with single parsed file.</returns>
public TemplateEngine AddFile(string filePath, ImportResolverDelegate importResolver = null) => AddFiles(new List<string> { filePath }, importResolver);
/// <summary>
/// Add text as lg file content to template engine. A fullpath id is needed when importResolver is empty, or simply pass in customized importResolver.
/// </summary>
/// <param name="content">Text content contains lg templates.</param>
/// <param name="id">id is the content identifier. If importResolver is null, id must be a full path string. </param>
/// <param name="importResolver">resolver to resolve LG import id to template text.</param>
/// <returns>Template engine with the parsed content.</returns>
public TemplateEngine AddText(string content, string id = "", ImportResolverDelegate importResolver = null)
{
CheckImportResolver(id, importResolver);
var rootResource = LGParser.Parse(content, id);
var lgresources = rootResource.DiscoverDependencies(importResolver);
Templates.AddRange(lgresources.SelectMany(x => x.Templates));
RunStaticCheck(Templates);
return this;
}
/// <summary>
/// Evaluate a template with given name and scope.
/// </summary>
/// <param name="templateName">Template name to be evaluated.</param>
/// <param name="scope">The state visible in the evaluation.</param>
/// <returns>Evaluate result.</returns>
public object EvaluateTemplate(string templateName, object scope = null)
{
var evaluator = new Evaluator(Templates, this.expressionEngine);
return evaluator.EvaluateTemplate(templateName, scope);
}
/// <summary>
/// Expand a template with given name and scope.
/// Return all possible responses instead of random one.
/// </summary>
/// <param name="templateName">Template name to be evaluated.</param>
/// <param name="scope">The state visible in the evaluation.</param>
/// <returns>Expand result.</returns>
public List<string> ExpandTemplate(string templateName, object scope = null)
{
var expander = new Expander(Templates, this.expressionEngine);
return expander.EvaluateTemplate(templateName, scope);
}
public AnalyzerResult AnalyzeTemplate(string templateName)
{
var analyzer = new Analyzer(Templates, this.expressionEngine);
return analyzer.AnalyzeTemplate(templateName);
}
/// <summary>
/// Use to evaluate an inline template str.
/// </summary>
/// <param name="inlineStr">inline string which will be evaluated.</param>
/// <param name="scope">scope object or JToken.</param>
/// <returns>Evaluate result.</returns>
public object Evaluate(string inlineStr, object scope = null)
{
// wrap inline string with "# name and -" to align the evaluation process
var fakeTemplateId = "__temp__";
inlineStr = !inlineStr.Trim().StartsWith("```") && inlineStr.IndexOf('\n') >= 0
? "```" + inlineStr + "```" : inlineStr;
var wrappedStr = $"# {fakeTemplateId} \r\n - {inlineStr}";
var lgsource = LGParser.Parse(wrappedStr, "inline");
var templates = Templates.Concat(lgsource.Templates).ToList();
RunStaticCheck(templates);
var evaluator = new Evaluator(templates, this.expressionEngine);
return evaluator.EvaluateTemplate(fakeTemplateId, scope);
}
/// <summary>
/// Check templates/text to match LG format.
/// </summary>
/// <param name="templates">the templates which should be checked.</param>
private void RunStaticCheck(List<LGTemplate> templates = null)
{
var teamplatesToCheck = templates ?? this.Templates;
var diagnostics = new StaticChecker(this.expressionEngine).CheckTemplates(teamplatesToCheck);
var errors = diagnostics.Where(u => u.Severity == DiagnosticSeverity.Error).ToList();
if (errors.Count != 0)
{
throw new Exception(string.Join("\n", errors));
}
}
private void CheckImportResolver(string id, ImportResolverDelegate importResolver)
{
// Currently if no resolver is passed into AddText(),
// the default fileResolver is used to resolve the imports.
// default fileResolver require resource id should be fullPath,
// so that it can resolve relative path based on this fullPath.
// But we didn't check the id provided with AddText is fullPath or not.
// So when id != fullPath, fileResolver won't work.
if (importResolver == null)
{
var importPath = ImportResolver.NormalizePath(id);
if (!Path.IsPathRooted(importPath))
{
throw new Exception("[Error] id must be full path when importResolver is null");
}
}
}
}
}
| 45.769231 | 160 | 0.619448 | [
"MIT"
] | rggammon/botbuilder-dotnet | libraries/Microsoft.Bot.Builder.LanguageGeneration/TemplateEngine.cs | 8,332 | C# |
namespace DOTNET.WEBAPI.BOILERPLATE.Areas.HelpPage.ModelDescriptions
{
public class CollectionModelDescription : ModelDescription
{
public ModelDescription ElementDescription { get; set; }
}
} | 30.285714 | 68 | 0.759434 | [
"MIT"
] | ReyielGab/Allow_It | DOTNET.WEBAPI.BOILERPLATE/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs | 212 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.