content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity.InterceptionExtension;
using Ploeh.Samples.ProductManagement.WcfAgent;
namespace Ploeh.Samples.ProductManagement.WpfClient.Unity
{
public class CircuitBreakerInteceptionBehavior :
IInterceptionBehavior
{
private readonly ICircuitBreaker breaker;
public CircuitBreakerInteceptionBehavior(
ICircuitBreaker breaker)
{
if (breaker == null)
{
throw new ArgumentNullException("breaker");
}
this.breaker = breaker;
}
public IMethodReturn Invoke(IMethodInvocation input,
GetNextInterceptionBehaviorDelegate getNext)
{
try
{
this.breaker.Guard();
}
catch (InvalidOperationException e)
{
return
input.CreateExceptionMethodReturn(e);
}
var result = getNext()(input, getNext);
if (result.Exception != null)
{
this.breaker.Trip(result.Exception);
}
else
{
this.breaker.Succeed();
}
return result;
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public bool WillExecute
{
get { return true; }
}
}
}
| 24.677419 | 60 | 0.542484 | [
"MIT"
] | owolp/Telerik-Academy | Module-2/Design-Patterns/Materials/DI.NET/WpfProductManagementClient/ProductManagementClient/Unity/CircuitBreakerInteceptionBehavior.cs | 1,532 | C# |
using Disqord.Models;
namespace Disqord
{
public class TransientCategoryChannel : TransientGuildChannel, ICategoryChannel
{
public TransientCategoryChannel(IClient client, ChannelJsonModel model)
: base(client, model)
{ }
}
}
| 23.25 | 84 | 0.663082 | [
"MIT"
] | Neuheit/Diqnod | src/Disqord.Core/Entities/Shared/Transient/Channels/Guild/TransientCategoryChannel.cs | 281 | C# |
using System;
using System.Collections.Generic;
namespace Sanford.Collections.Generic
{
internal class UndoManager
{
private Stack<ICommand> undoStack = new Stack<ICommand>();
private Stack<ICommand> redoStack = new Stack<ICommand>();
#region Methods
public void Execute(ICommand command)
{
command.Execute();
undoStack.Push(command);
redoStack.Clear();
}
/// <summary>
/// Undoes the last operation.
/// </summary>
/// <returns>
/// <b>true</b> if the last operation was undone, <b>false</b> if there
/// are no more operations left to undo.
/// </returns>
public bool Undo()
{
#region Guard
if(undoStack.Count == 0)
{
return false;
}
#endregion
ICommand command = undoStack.Pop();
command.Undo();
redoStack.Push(command);
return true;
}
/// <summary>
/// Redoes the last operation.
/// </summary>
/// <returns>
/// <b>true</b> if the last operation was redone, <b>false</b> if there
/// are no more operations left to redo.
/// </returns>
public bool Redo()
{
#region Guard
if(redoStack.Count == 0)
{
return false;
}
#endregion
ICommand command = redoStack.Pop();
command.Execute();
undoStack.Push(command);
return true;
}
/// <summary>
/// Clears the undo/redo history.
/// </summary>
public void ClearHistory()
{
undoStack.Clear();
redoStack.Clear();
}
#endregion
#region Properties
/// <summary>
/// The number of operations left to undo.
/// </summary>
public int UndoCount
{
get
{
return undoStack.Count;
}
}
/// <summary>
/// The number of operations left to redo.
/// </summary>
public int RedoCount
{
get
{
return redoStack.Count;
}
}
#endregion
}
}
| 20.921053 | 79 | 0.457023 | [
"MIT"
] | 3017218159/Sanford.Multimedia.Midi-master | Source/Sanford.Collections/Generic/UndoableList/UndoManager.cs | 2,385 | C# |
using Castle.DynamicProxy;
using MvvmKit.CollectionChangeEvents;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MvvmKit
{
public class AccessInterceptor : BaseDisposable, IInterceptor
{
private InterfaceState _state;
private bool _allowModifications;
private Dictionary<PropertyInfo, object> _oldValues;
private Dictionary<PropertyInfo, object[]> _oldCollectionValues;
private EditableLookup<PropertyInfo, IChange> _collectionChanges;
private Dictionary<PropertyInfo, object> _literalChanges;
private Dictionary<PropertyInfo, IStateList> _proxies;
public AccessInterceptor(InterfaceState state, bool allowModifications = false)
{
_state = state;
_allowModifications = allowModifications;
_oldValues = state.Properties.ToDictionary(p => p, p => state[p]);
_oldCollectionValues = state.CollectionProperties
.ToDictionary(p => p, p => (state[p] as IEnumerable).Cast<object>().ToArray());
_collectionChanges = new EditableLookup<PropertyInfo, IChange>();
_literalChanges = new Dictionary<PropertyInfo, object>();
_proxies = new Dictionary<PropertyInfo, IStateList>();
}
public IEnumerable<(PropertyInfo prop, object value)> ChangedLiterals()
{
return _literalChanges.Select(pair => (pair.Key, pair.Value));
}
public IEnumerable<IGrouping<PropertyInfo, IChange>> ChangedCollections()
{
return _collectionChanges;
}
public object[] OldCollectionValue(PropertyInfo prop)
{
return _oldCollectionValues[prop];
}
private IStateList _ensureProxy(PropertyInfo prop)
{
if (_proxies.ContainsKey(prop)) return _proxies[prop];
var itemType = prop.PropertyType.GenericTypeArguments[0];
var proxyType = typeof(CollectionProxy<>).MakeGenericType(itemType);
var list = _state[prop];
Action<IChange> onChange = change => _onChange(prop, change);
var proxy = Activator.CreateInstance(proxyType, list, this, onChange, _allowModifications) as IStateList;
_proxies.Add(prop, proxy);
return proxy;
}
public void Intercept(IInvocation invocation)
{
var method = invocation.Method;
var member = _state.PropertyOf(method);
switch (member.role)
{
case PropertyMethodRole.None:
throw new InvalidOperationException($"Attempting to invoke a state member that is not a property: {method.Name}");
case PropertyMethodRole.Getter:
_doGet(member.prop, invocation);
break;
case PropertyMethodRole.Setter:
_doSet(member.prop, invocation);
break;
}
}
private void _doGet(PropertyInfo prop, IInvocation invocation)
{
if (_state.IsCollection(prop))
{
// if the property is of type state collection, we need a special treatment becuase the stored
// data is of type List<T>, and also, because we need to monitor changes.
var proxy = _ensureProxy(prop);
invocation.ReturnValue = proxy;
} else
{
invocation.ReturnValue = _state[prop];
}
}
private void _onChange(PropertyInfo prop, IChange change)
{
_collectionChanges.Add(prop, change);
}
private void _doSet(PropertyInfo prop, IInvocation invocation)
{
if (!_allowModifications)
throw new InvalidOperationException($"Attempting to set a property during a read only operation: {prop.Name}");
_state[prop] = invocation.Arguments[0];
_literalChanges[prop] = invocation.Arguments[0];
}
protected override void OnDisposed()
{
base.OnDisposed();
}
}
}
| 36.135593 | 134 | 0.613743 | [
"MIT"
] | kobi2294/MvvmKit | Source/MvvmKit/Services/State2/AccessInterceptor.cs | 4,266 | C# |
#region Copyright
/*Copyright (C) 2015 Wosad Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wosad.Common.Entities;
using Wosad.Common.Section.Interfaces;
using Wosad.Steel.AISC.Interfaces;
////using Wosad.Analytics.Section;
using Wosad.Steel.AISC360v10.Connections.AffectedElements;
using Wosad.Common.CalculationLogger.Interfaces;
using Wosad.Steel.AISC.Interfaces;
using Wosad.Steel.AISC.SteelEntities.Sections;
namespace Wosad.Steel.AISC360v10.HSS.ConcentratedForces
{
public partial class RhsLongitudinalPlate: RhsToPlateConnection, IHssLongitudinalPlateConnection
{
public double GetMaximumPlateThickness()
{
double tpMax = 0.0;
double t = Hss.Section.t_des;
double Fu = Hss.Material.UltimateStress;
double Fyp = Plate.Material.YieldStress;
tpMax = Fu / Fyp * t; //(K1-3)
return tpMax;
}
}
}
| 27.070175 | 100 | 0.71873 | [
"Apache-2.0"
] | Wosad/Wosad.Design | Wosad.Steel/AISC/AISC360v10/K_HSS/ConcentratedForces/Rhs/LimitStates/RhsLongitudinalPlateShear.cs | 1,543 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Charlotte.Games.Shots
{
public static class ShotConsts
{
/// <summary>
/// 自弾のアルファ値
/// </summary>
public const double A = 0.3;
}
}
| 15.0625 | 33 | 0.692946 | [
"MIT"
] | soleil-taruto/Elsa | e20201018_TateShoot_Demo/Elsa20200001/Elsa20200001/Games/Shots/ShotConsts.cs | 259 | C# |
using System.Collections.Generic;
using ScriptableData;
using UnityEngine;
namespace System.UI
{
[ExecuteInEditMode]
public class MenuManager : MonoBehaviour
{
#region DATA
public static MenuManager Instance;
public ConfigProjectData ConfigProjectData;
public ModelSpawnData ModelDataSpawn;
#endregion
private readonly List<GameObject> _panelMenuList = new List<GameObject>();
private readonly Dictionary<UIStateEnum, AUIState> _stateDictionary = new Dictionary<UIStateEnum, AUIState>();
private readonly Stack<UIStateEnum> _stateStack = new Stack<UIStateEnum>();
private UIStateEnum _actualStateEnum;
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(Instance);
// Get all panels in the root canvas containing the name "Menu" and
// store them into the _panelMenuList
FetchObjects("Menu", transform, _panelMenuList);
// Generate a dictionnary of states from thoses panels
GenerateStates();
// Add the first newState into the queue states
_stateStack.Push(GetFirstState());
_actualStateEnum = GetFirstState();
// Disable all panels
DisableAllPanels();
}
private void Update()
{
if (_stateDictionary.Count > 0 && !_stateDictionary[_stateStack.Peek()].IsEnabled())
{
_stateDictionary[_stateStack.Peek()].Enable();
}
}
public void AddState(UIStateEnum newState)
{
UpdateState(newState);
DisableAllPanelsInStack();
_stateStack.Push(newState);
}
public void RemoveLastState(UIStateEnum newState)
{
UpdateState(newState);
DisableAllPanelsInStack();
_stateStack.Pop();
}
private void UpdateState(UIStateEnum state)
{
_actualStateEnum = state;
}
private void GenerateStates()
{
foreach (var container in _panelMenuList)
{
Type typeName = Type.GetType(GetType().Namespace + "." + container.name + "State");
if (typeName != null)
{
Object[] args = {this};
AUIState newAuiState = Activator.CreateInstance(typeName, args) as AUIState;
string typeNameStr = typeName.Name.ToLower();
for (UIStateEnum state = UIStateEnum.NONE; state <= UIStateEnum.ACTIONSMENU; ++state)
{
if (newAuiState != null &&
!_stateDictionary.ContainsKey(state) &&
typeNameStr.Contains(state.ToString().ToLower()))
{
newAuiState.Setup(container.transform);
_stateDictionary.Add(state, newAuiState);
break;
}
}
}
}
}
private void FetchObjects(string menu, Transform transformElement, List<GameObject> containerList)
{
if (transformElement.name.Contains(menu))
{
containerList.Add(transformElement.gameObject);
}
foreach (Transform childTransform in transformElement)
{
FetchObjects(menu, childTransform, containerList);
}
}
private void DisableAllPanels()
{
foreach (var state in _stateDictionary)
state.Value.Disable();
}
private void DisableAllPanelsInStack()
{
foreach (var uiStateEnum in _stateStack)
_stateDictionary[uiStateEnum].Disable();
}
private UIStateEnum GetFirstState()
{
return UIStateEnum.ACTIONSMENU;
}
}
} | 30.871212 | 118 | 0.542577 | [
"MIT"
] | Plimsky/Stress-Test | Assets/Scripts/System/UI/MenuManager.cs | 4,077 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using SFA.DAS.Apim.Developer.Domain.Configuration;
using SFA.DAS.Apim.Developer.Domain.Extensions;
using SFA.DAS.Apim.Developer.Domain.Interfaces;
using SFA.DAS.Apim.Developer.Domain.Models;
using SFA.DAS.Apim.Developer.Domain.Users.Api.Requests;
using SFA.DAS.Apim.Developer.Domain.Users.Api.Responses;
using UserNote = SFA.DAS.Apim.Developer.Domain.Models.UserNote;
namespace SFA.DAS.Apim.Developer.Application.AzureApimManagement.Services
{
public class UserService : IUserService
{
private readonly IAzureApimManagementService _azureApimManagementService;
private readonly IAzureUserAuthenticationManagementService _azureUserAuthenticationManagementService;
private readonly ApimDeveloperApiConfiguration _config;
public UserService(
IAzureApimManagementService azureApimManagementService,
IAzureUserAuthenticationManagementService azureUserAuthenticationManagementService,
IOptions<ApimDeveloperApiConfiguration> configOptions)
{
_azureApimManagementService = azureApimManagementService;
_azureUserAuthenticationManagementService = azureUserAuthenticationManagementService;
_config = configOptions.Value;
}
public async Task<UserDetails> UpdateUser(UserDetails userDetails)
{
var getUserResponse = await GetUserById(userDetails.Id);
if (getUserResponse == null)
{
return null;
}
// apim mgmt api required fields: https://docs.microsoft.com/en-us/rest/api/apimanagement/current-ga/user/create-or-update#request-body
userDetails.Email ??= getUserResponse.Email;
userDetails.FirstName ??= getUserResponse.FirstName;
userDetails.LastName ??= getUserResponse.LastName;
// note cleared if not set
userDetails.Note ??= getUserResponse.Note;
var createApimUserTask = await UpsertApimUser(userDetails.Id, userDetails);
return new UserDetails
{
Id = createApimUserTask.Name,
Password = null,
Email = createApimUserTask.Properties.Email,
FirstName = createApimUserTask.Properties.FirstName,
LastName = createApimUserTask.Properties.LastName,
State = createApimUserTask.Properties.State
};
}
public async Task<UserDetails> CreateUser(UserDetails userDetails)
{
var getUserResponse = await GetUser(userDetails.Email);
var userId = userDetails.Id;
if (getUserResponse != null)
{
throw new ValidationException("User already exists");
}
userDetails.State = "pending";
var createApimUserTask = await UpsertApimUser(userId, userDetails);
return new UserDetails
{
Id = createApimUserTask.Name,
Password = null,
Email = createApimUserTask.Properties.Email,
FirstName = createApimUserTask.Properties.FirstName,
LastName = createApimUserTask.Properties.LastName,
State = createApimUserTask.Properties.State
};
}
public async Task<UserDetails> GetUser(string emailAddress)
{
if (string.IsNullOrEmpty(emailAddress))
{
return null;
}
var result = await _azureApimManagementService.Get<ApimUserResponse>(
new GetApimUserRequest(emailAddress));
if (result.Body.Count == 0)
{
return null;
}
return ConvertApimUserResponseItemToUserDetails(result.Body.Values.First());
}
public async Task<UserDetails> GetUserById(string id)
{
var result = await _azureApimManagementService.Get<ApimUserResponseItem>(
new GetApimUserByIdRequest(id));
if (result.StatusCode == HttpStatusCode.NotFound || result.Body == null)
{
return null;
}
return ConvertApimUserResponseItemToUserDetails(result.Body);
}
private UserDetails ConvertApimUserResponseItemToUserDetails(ApimUserResponseItem source)
{
UserNote userNote = null;
if (source.Properties.Note != null && !source.Properties.Note.TryParseJson(out userNote))
{
userNote = new UserNote {ConfirmEmailLink = source.Properties.Note};
}
return new UserDetails
{
Id = source.Name,
Password = null,
Email = source.Properties.Email,
FirstName = source.Properties.FirstName,
LastName = source.Properties.LastName,
State = source.Properties.State,
Note = userNote
};
}
private async Task<UserResponse> UpsertApimUser(string apimUserId, UserDetails userDetails)
{
var apimUserResponse = await _azureApimManagementService.Put<UserResponse>(
new CreateUserRequest(apimUserId, userDetails));
if (!string.IsNullOrEmpty(apimUserResponse.ErrorContent))
{
throw new ValidationException(apimUserResponse.ErrorContent);
}
return apimUserResponse.Body;
}
public async Task<UserDetails> CheckUserAuthentication(string email, string password)
{
var authenticatedTask =
_azureUserAuthenticationManagementService.GetAuthentication<GetUserAuthenticatedResponse>(
new GetUserAuthenticatedRequest(email, password));
var userTask = GetUser(email);
await Task.WhenAll(authenticatedTask, userTask);
if (userTask.Result == null)
{
return null;
}
var user = userTask.Result;
if (user.Note.AccountLockedDateTime.HasValue && DateTime.Now.AddMinutes(-_config.AccountLockedDurationMinutes) > user.Note.AccountLockedDateTime)
{
user.Note.FailedAuthCount = 0;
user.Note.AccountLockedDateTime = null;
user.State = "active";
await UpsertApimUser(user.Id, user);
return await CheckUserAuthentication(email, password);
}
user.Authenticated = authenticatedTask.Result.StatusCode == HttpStatusCode.OK;
if (!user.Authenticated && !user.Note.AccountLockedDateTime.HasValue)
{
user.Note.FailedAuthCount += 1;
if (user.Note.FailedAuthCount >= _config.NumberOfAuthFailuresToLockAccount)
{
user.Note.AccountLockedDateTime = DateTime.Now;
user.State = "blocked";
}
await UpsertApimUser(user.Id, user);
}
if (user.Authenticated && user.Note.FailedAuthCount > 0)
{
user.Note.FailedAuthCount = 0;
user.Note.AccountLockedDateTime = null;
await UpsertApimUser(user.Id, user);
}
return user;
}
}
} | 38.867347 | 157 | 0.606065 | [
"MIT"
] | SkillsFundingAgency/das-apim-developer-api | src/SFA.DAS.Apim.Developer.Application/AzureApimManagement/Services/UserService.cs | 7,618 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using FredsImageMagickScripts;
using ImageMagick;
namespace DocumentParser.Classes {
public class CleanImage {
public async Task<string> Execute(string filePath) {
try {
var path = Path.GetTempPath() + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".tif";
MainWindow.AppendHistory("Document found. ", HistoryType.Status);
MagickImage img = null;
var settings = new MagickReadSettings {Density = new Density(300, 300)};
MainWindow.AppendHistory($"Splitting pdf into seperate files...", HistoryType.Status);
await Task.Run(() => {
using (var images = new MagickImageCollection()) {
images.Read(filePath, settings);
MainWindow.AppendHistory($"Total images: {images.Count}", HistoryType.Status);
images[0].Write(path);
}
});
await Task.Run(() => {
using (var i = new MagickImage(path)) {
var offset = new TextCleanerCropOffset {Bottom = 2600, Left = 1500, Right = 100, Top = 250};
var script = new TextCleanerScript();
script.SmoothingThreshold = new Percentage(70);
script.Unrotate = true;
script.MakeGray = true;
script.CropOffset = offset;
MainWindow.AppendHistory($"Cleaning up image for accurate OCR", HistoryType.Status);
MagickImage returnedImg = null;
returnedImg = script.Execute(i);
returnedImg.Write(path);
}
});
return path;
}
catch (Exception x) {
MainWindow.AppendHistory(x.Message, HistoryType.Error);
return null;
}
}
}
} | 38.849057 | 116 | 0.510442 | [
"MIT"
] | MatthewCsharp/DocumentParser | DocumentParser/Classes/CleanImage.cs | 2,061 | C# |
using FullSampleWP8.Resources;
namespace FullSampleWP8
{
/// <summary>
/// Provides access to string resources.
/// </summary>
public class LocalizedStrings
{
private static AppResources _localizedResources = new AppResources();
public AppResources LocalizedResources { get { return _localizedResources; } }
}
} | 26.214286 | 87 | 0.66485 | [
"Apache-2.0"
] | MavenRain/facebook-winclient-sdk | Samples/FullSampleWP8/LocalizedStrings.cs | 369 | C# |
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WebApp.Code.Attributes;
using WebApp.Controllers;
using Xunit;
namespace WebApp.Tests
{
public class ControllerTests
{
[Fact]
public void AllControllersAreSubclassesOfBaseController()
{
// this makes sure that the controllers have appropriate security settings
var controllers =
typeof(BaseController).Assembly.GetExportedTypes()
.Where(c => c.IsSubclassOf(typeof(Controller)));
Assert.All(controllers, c =>
Assert.True(c.IsSubclassOf(typeof(BaseController)) ||
c.IsDefined(typeof(AuthorizeEnvironmentEndpointAttribute), false) ||
c == typeof(AccountController) ||
c == typeof(BaseController)));
}
}
}
| 30.310345 | 96 | 0.596132 | [
"MIT"
] | Azure/azure-render-farm-manager | src/AzureRenderHub/AzureRenderHub.WebApp.Tests/ControllerTests.cs | 879 | C# |
// SearchedUser
using Disney.Mix.SDK;
public class SearchedUser
{
public readonly IUnidentifiedUser MixSearchedUser;
public string DisplayName => (MixSearchedUser != null) ? MixSearchedUser.DisplayName.Text : null;
public SearchedUser(IUnidentifiedUser User)
{
MixSearchedUser = User;
}
}
| 19.933333 | 98 | 0.77592 | [
"MIT"
] | smdx24/CPI-Source-Code | ClubPenguin.Net/SearchedUser.cs | 299 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telerik.Sitefinity.DynamicModules.Builder.Model;
namespace Telerik.Sitefinity.Frontend.DynamicContent.WidgetTemplates.Fields.Impl
{
/// <summary>
/// This class represents field generation strategy for short text dynamic fields.
/// </summary>
public class ShortTextField : Field
{
/// <summary>
/// Initializes a new instance of the <see cref="ShortTextField"/> class.
/// </summary>
/// <param name="moduleType">Type of the module.</param>
public ShortTextField(DynamicModuleType moduleType)
{
this.moduleType = moduleType;
this.ExcludedFieldNames.Add(this.moduleType.MainShortTextFieldName);
}
/// <inheritdoc/>
public override bool GetCondition(DynamicModuleField field)
{
var condition = base.GetCondition(field)
&& (field.FieldType == FieldType.ShortText || field.FieldType == FieldType.Guid);
return condition;
}
/// <inheritdoc/>
protected override string GetTemplatePath(DynamicModuleField field)
{
return ShortTextField.TemplatePath;
}
private const string TemplatePath = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend.DynamicContent/WidgetTemplates/Fields/Templates/ShortTextField.cshtml";
private DynamicModuleType moduleType;
}
}
| 34.477273 | 172 | 0.664469 | [
"Apache-2.0"
] | MrJustPeachy/feather-widgets | Telerik.Sitefinity.Frontend.DynamicContent/WidgetTemplates/Fields/Impl/ShortTextField.cs | 1,519 | C# |
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HowToStartMockingWithMoq.Tests
{
[TestFixture]
public class ValidatorTests
{
[Test]
public void IsValidShouldReturnTrueIfThereAreNoRules()
{
var myField = -1;
var v = new Validator();
var actual = v.IsValid(nameof(myField), myField);
Assert.That(actual, Is.True);
}
//[Test]
//public void IsValidShouldReturnFalseIfAtLeastOneRuleReturnsFalse()
//{
// var myField = -1;
// var v = new Validator();
// v.AddRule(nameof(myField), new PositiveNumberRule());
// var actual = v.IsValid(nameof(myField), myField);
// Assert.That(actual, Is.False);
//}
//[Test]
//public void IsValidShouldReturnFalseIfAtLeastOneRuleReturnsFalse()
//{
// var myField = -1;
// var v = new Validator();
// v.AddRule(nameof(myField), new FakeRule());
// var actual = v.IsValid(nameof(myField), myField);
// Assert.That(actual, Is.False);
//}
//[Test]
//public void IsValidShouldReturnFalseIfAtLeastOneRuleReturnsFalse()
//{
// var myField = -1;
// var v = new Validator();
// v.AddRule(nameof(myField), new FakeRule(false));
// var actual = v.IsValid(nameof(myField), myField);
// Assert.That(actual, Is.False);
//}
//[Test]
//public void IsValidShouldReturnTrueIfAllRulesReturnTrue()
//{
// var myField = -1;
// var v = new Validator();
// v.AddRule(nameof(myField), new FakeRule(true));
// var actual = v.IsValid(nameof(myField), myField);
// Assert.That(actual, Is.True);
//}
[Test]
public void IsValidShouldReturnFalseIfAtLeastOneRuleReturnsFalse()
{
var myField = -1;
var v = new Validator();
var rule = new Mock<IValidatorRule>();
rule.Setup(s => s.IsValid(myField)).Returns(false);
v.AddRule(nameof(myField), rule.Object);
var actual = v.IsValid(nameof(myField), myField);
Assert.That(actual, Is.False);
}
[Test]
public void IsValidShouldReturnTrueIfAllRulesReturnTrue()
{
var myField = -1;
var v = new Validator();
var rule = new Mock<IValidatorRule>();
rule.Setup(s => s.IsValid(myField)).Returns(true);
v.AddRule(nameof(myField), rule.Object);
var actual = v.IsValid(nameof(myField), myField);
Assert.That(actual, Is.True);
}
[Test]
public void AddRuleShouldThrowExceptionIfRuleThrewException()
{
var myField = 40000000;
var v = new Validator();
var rule = new Mock<IValidatorRule>();
rule.Setup(s => s.IsValid(myField)).Throws<StackOverflowException>();
v.AddRule(nameof(myField), rule.Object);
TestDelegate del = () => v.IsValid(nameof(myField), myField);
Assert.Throws<StackOverflowException>(del);
}
[Test]
public void IsValidShouldCheckRuleOneTime()
{
var myField = -1;
var v = new Validator();
var rule = new Mock<IValidatorRule>();
v.AddRule(nameof(myField), rule.Object);
v.IsValid(nameof(myField), myField);
rule.Verify(s => s.IsValid(It.IsAny<object>()), Times.Once);
}
[Test]
public void IsValidShouldReturnUpdatedValueAfterChangeInFieldValue()
{
var myField = 1;
var v = new Validator();
var rule = new Mock<IValidatorRule>();
rule.SetupSequence(s => s.IsValid(myField))
.Returns(true)
.Returns(false);
v.AddRule(nameof(myField), rule.Object);
var actual1 = v.IsValid(nameof(myField), myField);
// Let's assume value in field changed here.
// We don't really have to do this, because we changed return value in mock on the second call.
var actual2 = v.IsValid(nameof(myField), myField);
Assert.That(actual1, Is.True);
Assert.That(actual2, Is.False);
}
[Test]
public void IsValidatingShouldBeSetWhenRuleRaisesIsValidatingEvent()
{
var myField = 1;
var v = new Validator();
var rule = new Mock<IValidatorRule>();
rule.Setup(s => s.IsValid(myField)).Returns(true).Raises(e => e.IsValidating += null, rule.Object, true);
v.AddRule(nameof(myField), rule.Object);
v.IsValid(nameof(myField), myField);
Assert.That(v.IsValidating, Is.True);
}
}
}
| 30.005952 | 117 | 0.551478 | [
"MIT"
] | Ermlab/how-to-start-mocking-with-moq | HowToStartMockingWithMoq.Tests/ValidatorTests.cs | 5,043 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Internal.Runtime;
namespace ILCompiler.Reflection.ReadyToRun
{
/// <summary>
/// This structure represents a single precode fixup cell decoded from the
/// nibble-oriented per-method fixup blob. Each method entrypoint fixup
/// represents an array of cells that must be fixed up before the method
/// can start executing.
/// </summary>
public struct FixupCell
{
public int Index { get; set; }
/// <summary>
/// Zero-based index of the import table within the import tables section.
/// </summary>
public uint TableIndex;
/// <summary>
/// Zero-based offset of the entry in the import table; it must be a multiple
/// of the target architecture pointer size.
/// </summary>
public uint CellOffset;
/// <summary>
/// Fixup cell signature (textual representation of the typesystem object).
/// </summary>
public string Signature;
public FixupCell(int index, uint tableIndex, uint cellOffset, string signature)
{
Index = index;
TableIndex = tableIndex;
CellOffset = cellOffset;
Signature = signature;
}
}
public abstract class BaseUnwindInfo
{
public int Size { get; set; }
}
public abstract class BaseGcTransition
{
public int CodeOffset { get; set; }
public BaseGcTransition() { }
public BaseGcTransition(int codeOffset)
{
CodeOffset = codeOffset;
}
}
public abstract class BaseGcSlot
{
public abstract GcSlotFlags WriteTo(StringBuilder sb, Machine machine, GcSlotFlags prevFlags);
}
public abstract class BaseGcInfo
{
public int Size { get; set; }
public int Offset { get; set; }
public int CodeLength { get; set; }
public Dictionary<int, List<BaseGcTransition>> Transitions { get; set; }
public List<List<BaseGcSlot>> LiveSlotsAtSafepoints { get; set; }
}
/// <summary>
/// A runtime function corresponds to a contiguous fragment of code that implements a method.
/// </summary>
public class RuntimeFunction
{
// based on <a href= "https://github.com/dotnet/runtime/blob/master/src/coreclr/src/pal/inc/pal.h" > src / pal / inc / pal.h </ a > _RUNTIME_FUNCTION
private ReadyToRunReader _readyToRunReader;
private EHInfo _ehInfo;
private DebugInfo _debugInfo;
/// <summary>
/// The index of the runtime function
/// </summary>
public int Id { get; }
/// <summary>
/// The relative virtual address to the start of the code block
/// </summary>
public int StartAddress { get; }
/// <summary>
/// The size of the code block in bytes
/// </summary>
/// /// <remarks>
/// The EndAddress field in the runtime functions section is conditional on machine type
/// Size is -1 for images without the EndAddress field
/// </remarks>
public int Size { get; }
/// <summary>
/// The relative virtual address to the unwind info
/// </summary>
public int UnwindRVA { get; }
/// <summary>
/// The start offset of the runtime function with is non-zero for methods with multiple runtime functions
/// </summary>
public int CodeOffset { get; }
/// <summary>
/// The method that this runtime function belongs to
/// </summary>
public ReadyToRunMethod Method { get; }
public BaseUnwindInfo UnwindInfo { get; }
public EHInfo EHInfo
{
get
{
if (_ehInfo == null)
{
_readyToRunReader.RuntimeFunctionToEHInfo.TryGetValue(StartAddress, out _ehInfo);
}
return _ehInfo;
}
}
public DebugInfo DebugInfo
{
get
{
if (_debugInfo == null)
{
int offset;
if (_readyToRunReader.RuntimeFunctionToDebugInfo.TryGetValue(Id, out offset))
{
this._debugInfo = new DebugInfo(this, offset);
}
}
return _debugInfo;
}
}
internal ReadyToRunReader ReadyToRunReader
{
get
{
return _readyToRunReader;
}
}
public RuntimeFunction(
ReadyToRunReader readyToRunReader,
int id,
int startRva,
int endRva,
int unwindRva,
int codeOffset,
ReadyToRunMethod method,
BaseUnwindInfo unwindInfo,
BaseGcInfo gcInfo)
{
_readyToRunReader = readyToRunReader;
Id = id;
StartAddress = startRva;
UnwindRVA = unwindRva;
Method = method;
UnwindInfo = unwindInfo;
if (endRva != -1)
{
Size = endRva - startRva;
}
else if (unwindInfo is x86.UnwindInfo)
{
Size = (int)((x86.UnwindInfo)unwindInfo).FunctionLength;
}
else if (unwindInfo is Arm.UnwindInfo)
{
Size = (int)((Arm.UnwindInfo)unwindInfo).FunctionLength;
}
else if (unwindInfo is Arm64.UnwindInfo)
{
Size = (int)((Arm64.UnwindInfo)unwindInfo).FunctionLength;
}
else if (gcInfo != null)
{
Size = gcInfo.CodeLength;
}
else
{
Size = -1;
}
CodeOffset = codeOffset;
method.GcInfo = gcInfo;
}
}
public class ReadyToRunMethod
{
private const int _mdtMethodDef = 0x06000000;
/// <summary>
/// MSIL module containing the method.
/// </summary>
public IAssemblyMetadata ComponentReader { get; private set; }
/// <summary>
/// The name of the method
/// </summary>
public string Name { get; set; }
/// <summary>
/// The signature with format: namespace.class.methodName<S, T, ...>(S, T, ...)
/// </summary>
public string SignatureString { get; set; }
public MethodSignature<string> Signature { get; }
public ImmutableArray<string> LocalSignature { get; }
/// <summary>
/// The type that the method belongs to
/// </summary>
public string DeclaringType { get; set; }
/// <summary>
/// The method metadata handle
/// </summary>
public EntityHandle MethodHandle { get; set; }
/// <summary>
/// The row id of the method
/// </summary>
public uint Rid { get; set; }
/// <summary>
/// All the runtime functions of this method
/// </summary>
public IReadOnlyList<RuntimeFunction> RuntimeFunctions
{
get
{
EnsureRuntimeFunctions();
return _runtimeFunctions;
}
}
private void EnsureRuntimeFunctions()
{
if (this._runtimeFunctions == null)
{
this._runtimeFunctions = new List<RuntimeFunction>();
this.ParseRuntimeFunctions();
}
}
/// <summary>
/// The id of the entrypoint runtime function
/// </summary>
public int EntryPointRuntimeFunctionId { get; set; }
public BaseGcInfo GcInfo { get; set; }
private ReadyToRunReader _readyToRunReader;
private List<FixupCell> _fixupCells;
private int? _fixupOffset;
private List<RuntimeFunction> _runtimeFunctions;
public IReadOnlyList<FixupCell> Fixups
{
get
{
EnsureFixupCells();
return _fixupCells;
}
}
internal int RuntimeFunctionCount { get; set; }
/// <summary>
/// Extracts the method signature from the metadata by rid
/// </summary>
public ReadyToRunMethod(
ReadyToRunReader readyToRunReader,
IAssemblyMetadata componentReader,
EntityHandle methodHandle,
int entryPointId,
string owningType,
string constrainedType,
string[] instanceArgs,
int? fixupOffset)
{
_readyToRunReader = readyToRunReader;
_fixupOffset = fixupOffset;
MethodHandle = methodHandle;
EntryPointRuntimeFunctionId = entryPointId;
ComponentReader = componentReader;
EntityHandle owningTypeHandle;
GenericParameterHandleCollection genericParams = default(GenericParameterHandleCollection);
DisassemblingGenericContext genericContext = new DisassemblingGenericContext(typeParameters: Array.Empty<string>(), methodParameters: instanceArgs);
DisassemblingTypeProvider typeProvider = new DisassemblingTypeProvider();
// get the method signature from the method handle
switch (MethodHandle.Kind)
{
case HandleKind.MethodDefinition:
{
MethodDefinition methodDef = ComponentReader.MetadataReader.GetMethodDefinition((MethodDefinitionHandle)MethodHandle);
if (methodDef.RelativeVirtualAddress != 0)
{
MethodBodyBlock mbb = ComponentReader.ImageReader.GetMethodBody(methodDef.RelativeVirtualAddress);
if (!mbb.LocalSignature.IsNil)
{
StandaloneSignature ss = ComponentReader.MetadataReader.GetStandaloneSignature(mbb.LocalSignature);
LocalSignature = ss.DecodeLocalSignature(typeProvider, genericContext);
}
}
Name = ComponentReader.MetadataReader.GetString(methodDef.Name);
Signature = methodDef.DecodeSignature<string, DisassemblingGenericContext>(typeProvider, genericContext);
owningTypeHandle = methodDef.GetDeclaringType();
genericParams = methodDef.GetGenericParameters();
}
break;
case HandleKind.MemberReference:
{
MemberReference memberRef = ComponentReader.MetadataReader.GetMemberReference((MemberReferenceHandle)MethodHandle);
Name = ComponentReader.MetadataReader.GetString(memberRef.Name);
Signature = memberRef.DecodeMethodSignature<string, DisassemblingGenericContext>(typeProvider, genericContext);
owningTypeHandle = memberRef.Parent;
}
break;
default:
throw new NotImplementedException();
}
if (owningType != null)
{
DeclaringType = owningType;
}
else
{
DeclaringType = MetadataNameFormatter.FormatHandle(ComponentReader.MetadataReader, owningTypeHandle);
}
StringBuilder sb = new StringBuilder();
sb.Append(Signature.ReturnType);
sb.Append(" ");
sb.Append(DeclaringType);
sb.Append(".");
sb.Append(Name);
if (Signature.GenericParameterCount != 0)
{
sb.Append("<");
for (int i = 0; i < Signature.GenericParameterCount; i++)
{
if (i > 0)
{
sb.Append(", ");
}
if (instanceArgs != null && instanceArgs.Length > i)
{
sb.Append(instanceArgs[i]);
}
else
{
sb.Append("!");
sb.Append(i);
}
}
sb.Append(">");
}
sb.Append("(");
for (int i = 0; i < Signature.ParameterTypes.Length; i++)
{
if (i > 0)
{
sb.Append(", ");
}
sb.AppendFormat($"{Signature.ParameterTypes[i]}");
}
sb.Append(")");
SignatureString = sb.ToString();
}
private void EnsureFixupCells()
{
if (_fixupCells != null)
{
return;
}
if (!_fixupOffset.HasValue)
{
return;
}
_fixupCells = new List<FixupCell>();
NibbleReader reader = new NibbleReader(_readyToRunReader.Image, _fixupOffset.Value);
// The following algorithm has been loosely ported from CoreCLR,
// src\vm\ceeload.inl, BOOL Module::FixupDelayListAux
uint curTableIndex = reader.ReadUInt();
while (true)
{
uint fixupIndex = reader.ReadUInt(); // Accumulate the real rva from the delta encoded rva
while (true)
{
ReadyToRunImportSection importSection = _readyToRunReader.ImportSections[(int)curTableIndex];
ReadyToRunImportSection.ImportSectionEntry entry = importSection.Entries[(int)fixupIndex];
_fixupCells.Add(new FixupCell(_fixupCells.Count, curTableIndex, fixupIndex, entry.Signature));
uint delta = reader.ReadUInt();
// Delta of 0 means end of entries in this table
if (delta == 0)
break;
fixupIndex += delta;
}
uint tableIndex = reader.ReadUInt();
if (tableIndex == 0)
break;
curTableIndex = curTableIndex + tableIndex;
} // Done with all entries in this table
}
/// <summary>
/// Get the RVAs of the runtime functions for each method
/// based on <a href="https://github.com/dotnet/coreclr/blob/master/src/zap/zapcode.cpp">ZapUnwindInfo::Save</a>
/// </summary>
private void ParseRuntimeFunctions()
{
int runtimeFunctionId = EntryPointRuntimeFunctionId;
int runtimeFunctionSize = _readyToRunReader.CalculateRuntimeFunctionSize();
int runtimeFunctionOffset = _readyToRunReader.CompositeReader.GetOffset(_readyToRunReader.ReadyToRunHeader.Sections[ReadyToRunSectionType.RuntimeFunctions].RelativeVirtualAddress);
int curOffset = runtimeFunctionOffset + runtimeFunctionId * runtimeFunctionSize;
BaseGcInfo gcInfo = null;
int codeOffset = 0;
for (int i = 0; i < RuntimeFunctionCount; i++)
{
int startRva = NativeReader.ReadInt32(_readyToRunReader.Image, ref curOffset);
int endRva = -1;
if (_readyToRunReader.Machine == Machine.Amd64)
{
endRva = NativeReader.ReadInt32(_readyToRunReader.Image, ref curOffset);
}
int unwindRva = NativeReader.ReadInt32(_readyToRunReader.Image, ref curOffset);
int unwindOffset = _readyToRunReader.CompositeReader.GetOffset(unwindRva);
BaseUnwindInfo unwindInfo = null;
if (_readyToRunReader.Machine == Machine.Amd64)
{
unwindInfo = new Amd64.UnwindInfo(_readyToRunReader.Image, unwindOffset);
if (i == 0)
{
gcInfo = new Amd64.GcInfo(_readyToRunReader.Image, unwindOffset + unwindInfo.Size, _readyToRunReader.Machine, _readyToRunReader.ReadyToRunHeader.MajorVersion);
}
}
else if (_readyToRunReader.Machine == Machine.I386)
{
unwindInfo = new x86.UnwindInfo(_readyToRunReader.Image, unwindOffset);
if (i == 0)
{
gcInfo = new x86.GcInfo(_readyToRunReader.Image, unwindOffset, _readyToRunReader.Machine, _readyToRunReader.ReadyToRunHeader.MajorVersion);
}
}
else if (_readyToRunReader.Machine == Machine.ArmThumb2)
{
unwindInfo = new Arm.UnwindInfo(_readyToRunReader.Image, unwindOffset);
if (i == 0)
{
gcInfo = new Amd64.GcInfo(_readyToRunReader.Image, unwindOffset + unwindInfo.Size, _readyToRunReader.Machine, _readyToRunReader.ReadyToRunHeader.MajorVersion); // Arm and Arm64 use the same GcInfo format as x64
}
}
else if (_readyToRunReader.Machine == Machine.Arm64)
{
unwindInfo = new Arm64.UnwindInfo(_readyToRunReader.Image, unwindOffset);
if (i == 0)
{
gcInfo = new Amd64.GcInfo(_readyToRunReader.Image, unwindOffset + unwindInfo.Size, _readyToRunReader.Machine, _readyToRunReader.ReadyToRunHeader.MajorVersion);
}
}
RuntimeFunction rtf = new RuntimeFunction(
_readyToRunReader,
runtimeFunctionId,
startRva,
endRva,
unwindRva,
codeOffset,
this,
unwindInfo,
gcInfo);
_runtimeFunctions.Add(rtf);
runtimeFunctionId++;
codeOffset += rtf.Size;
}
}
}
}
| 35.367424 | 234 | 0.535129 | [
"MIT"
] | 2m0nd/runtime | src/coreclr/src/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunMethod.cs | 18,674 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace laico.service.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| 21.488889 | 56 | 0.497415 | [
"MIT"
] | CesarRabelo/laico | source/laico.service/Controllers/ValuesController.cs | 969 | C# |
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.eShopWeb.Web.Services;
using Microsoft.eShopWeb.Web.ViewModels;
using System.Threading.Tasks;
namespace Microsoft.eShopWeb.Web.Pages
{
public class IndexModel : PageModel
{
private readonly ICatalogViewModelService _catalogViewModelService;
public IndexModel(ICatalogViewModelService catalogViewModelService)
{
_catalogViewModelService = catalogViewModelService;
}
public CatalogIndexViewModel CatalogModel { get; set; } = new CatalogIndexViewModel();
public async Task OnGet(CatalogIndexViewModel catalogModel, int? pageId)
{
CatalogModel = await _catalogViewModelService.GetCatalogItems(pageId ?? 0, Constants.ITEMS_PER_PAGE, catalogModel.BrandFilterApplied, catalogModel.TypesFilterApplied, catalogModel.MaterialFilterApplied);
}
}
}
| 37 | 216 | 0.731892 | [
"MIT"
] | whiteeyes32/eShopOnWeb | src/Web/Pages/Index.cshtml.cs | 927 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AOC.Year2019
{
public class Simulator
{
private readonly Dictionary<int, Instruction> _instructions;
public Simulator(Dictionary<int, Instruction> instructions)
{
_instructions = instructions;
}
public void Execute(int[] data)
{
var ip = 0;
while (true)
{
var i = data[ip];
if (_instructions.TryGetValue(i, out var instruction))
{
var done = instruction.Action(data, data.Skip(ip + 1).Take(instruction.ArgumentCount).ToArray());
ip += 1 + instruction.ArgumentCount;
if (done)
{
return;
}
}
else
{
throw new NotImplementedException($"Opcode {i} is not implemented");
}
}
}
}
public class Instruction
{
public int ArgumentCount { get; }
public Func<int[], int[], bool> Action { get; }
public Instruction(int argumentCount, Func<int[], int[], bool> action)
{
ArgumentCount = argumentCount;
Action = action;
}
}
}
| 25.444444 | 117 | 0.4869 | [
"MIT"
] | jorupp/adventofcode2019 | AOC/Year2019/Simulator.cs | 1,376 | C# |
using Dhl.Execs;
namespace Dhl.Helpers;
class ReadmeHelper
{
public static void AddReadmeFile(PromptModel model)
{
if (model.AddReadme)
{
if (model.PutSolutionAndProjectInSamePlace == false)
BashExec.Run($"touch ./{model.GetSolutionName()}/README.md");
else
BashExec.Run($"touch ./{model.ProjectName}/README.md");
}
}
} | 24.294118 | 77 | 0.585956 | [
"MIT"
] | hootanht/dhl | Helpers/ReadmeHelper.cs | 413 | C# |
using System;
namespace GameThing.Entities.Cards.Requirements
{
public class Requirement
{
public RequirementType Type { get; set; }
public bool Met(Character source, Character target)
{
switch (Type)
{
case RequirementType.BehindTarget:
return BehindTargetRequirementMet(source, target);
default:
throw new Exception($"Unknown requirement type {Type}.");
}
}
private bool BehindTargetRequirementMet(Character source, Character target)
{
var northSouthDiff = source.MapPosition.Y - target.MapPosition.Y;
var eastWestDiff = source.MapPosition.X - target.MapPosition.X;
switch (target.Facing)
{
case CharacterFacing.North: return northSouthDiff > 0;
case CharacterFacing.South: return northSouthDiff < 0;
case CharacterFacing.West: return eastWestDiff > 0;
case CharacterFacing.East: return eastWestDiff < 0;
}
return false;
}
}
}
| 24.675676 | 77 | 0.721796 | [
"Apache-2.0"
] | rythos42/GameThing | GameThing/Entities/Cards/Requirements/Requirement.cs | 915 | 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.DataFactory.V20170901Preview.Outputs
{
/// <summary>
/// The base definition of a secret type.
/// </summary>
[OutputType]
public sealed class LinkedIntegrationRuntimeRbacResponse
{
/// <summary>
/// Type of the secret.
/// Expected value is 'RBAC'.
/// </summary>
public readonly string AuthorizationType;
/// <summary>
/// The resource ID of the integration runtime to be shared.
/// </summary>
public readonly string ResourceId;
[OutputConstructor]
private LinkedIntegrationRuntimeRbacResponse(
string authorizationType,
string resourceId)
{
AuthorizationType = authorizationType;
ResourceId = resourceId;
}
}
}
| 28.15 | 81 | 0.639432 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataFactory/V20170901Preview/Outputs/LinkedIntegrationRuntimeRbacResponse.cs | 1,126 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
internal class MessageAction : ContainerAction
{
private bool _Terminate;
internal override void Compile(Compiler compiler)
{
CompileAttributes(compiler);
if (compiler.Recurse())
{
CompileTemplate(compiler);
compiler.ToParent();
}
}
internal override bool CompileAttribute(Compiler compiler)
{
string name = compiler.Input.LocalName;
string value = compiler.Input.Value;
if (Ref.Equal(name, compiler.Atoms.Terminate))
{
_Terminate = compiler.GetYesNo(value);
}
else
{
return false;
}
return true;
}
internal override void Execute(Processor processor, ActionFrame frame)
{
Debug.Assert(processor != null && frame != null);
switch (frame.State)
{
case Initialized:
TextOnlyOutput output = new TextOnlyOutput(processor, new StringWriter(CultureInfo.InvariantCulture));
processor.PushOutput(output);
processor.PushActionFrame(frame);
frame.State = ProcessingChildren;
break;
case ProcessingChildren:
TextOnlyOutput recOutput = processor.PopOutput() as TextOnlyOutput;
Debug.Assert(recOutput != null);
Console.WriteLine(recOutput.Writer.ToString());
if (_Terminate)
{
throw XsltException.Create(SR.Xslt_Terminate, recOutput.Writer.ToString());
}
frame.Finished();
break;
default:
Debug.Fail("Invalid MessageAction execution state");
break;
}
}
}
}
| 31.236842 | 122 | 0.53412 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Private.Xml/src/System/Xml/Xsl/XsltOld/MessageAction.cs | 2,374 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReassemblyAnalyser.Game
{
public class GameNotDoneException : Exception
{
public GameNotDoneException(string message) : base(message) { }
}
}
| 20.714286 | 71 | 0.744828 | [
"MIT"
] | Lomztein/ReassemblyAnalyser | ReassemblyAnalyser/Game/GameNotDoneException.cs | 292 | C# |
using System;
using HDWallet.Core;
using NBitcoin;
namespace HDWallet.Secp256k1
{
public abstract class HDWallet<TWallet> : HdWalletBase, IHDWallet<TWallet> where TWallet : Wallet, new()
{
ExtKey _masterKey;
public HDWallet(string words, string seedPassword, CoinPath path) : base(words, seedPassword)
{
var masterKeyPath = new KeyPath(path.ToString());
_masterKey = new ExtKey(base.BIP39Seed).Derive(masterKeyPath);
}
public HDWallet(string seed, CoinPath path) : base(seed)
{
var masterKeyPath = new KeyPath(path.ToString());
_masterKey = new ExtKey(base.BIP39Seed).Derive(masterKeyPath);
}
TWallet IHDWallet<TWallet>.GetMasterWallet()
{
var masterKey = new ExtKey(base.BIP39Seed);
var privateKey = masterKey.PrivateKey;
return new TWallet() {
PrivateKey = privateKey
};
}
TWallet IHDWallet<TWallet>.GetAccountWallet(uint accountIndex)
{
var externalKeyPath = new KeyPath($"{accountIndex}'");
var externalMasterKey = _masterKey.Derive(externalKeyPath);
return new TWallet()
{
PrivateKey = _masterKey.PrivateKey,
Index = accountIndex
};
}
IAccount<TWallet> IHDWallet<TWallet>.GetAccount(uint accountIndex)
{
var externalKeyPath = new KeyPath($"{accountIndex}'/0");
var externalMasterKey = _masterKey.Derive(externalKeyPath);
var internalKeyPath = new KeyPath($"{accountIndex}'/1");
var internalMasterKey = _masterKey.Derive(internalKeyPath);
return new Account<TWallet>(accountIndex, externalChain: externalMasterKey, internalChain: internalMasterKey);
}
/// <summary>
/// Generates Account from master. Doesn't derive new path by accountIndexInfo
/// </summary>
/// <param name="accountMasterKey">Used to generate wallet</param>
/// <param name="accountIndexInfo">Used only to store information</param>
/// <returns></returns>
public static IAccount<TWallet> GetAccountFromMasterKey(string accountMasterKey, uint accountIndexInfo)
{
IAccountHDWallet<TWallet> accountHDWallet = new AccountHDWallet<TWallet>(accountMasterKey, accountIndexInfo);
return accountHDWallet.Account;
}
}
} | 36.676471 | 122 | 0.625902 | [
"MIT"
] | TurgutKanceltik/HDWallet | src/HDWallet.Secp256k1/HDWallet.cs | 2,494 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V4200</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.V4200 {
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(TypeName="PRPA_MT000002UK02.AdminResult", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("PRPA_MT000002UK02.AdminResult", Namespace="urn:hl7-org:v3")]
public partial class PRPA_MT000002UK02AdminResult {
private CV codeField;
private CV valueField;
private PRPA_MT000002UK02Component34 componentField;
private PRPA_MT000002UK02PertinentInformation3 pertinentInformationField;
private string typeField;
private string classCodeField;
private string moodCodeField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public PRPA_MT000002UK02AdminResult() {
this.typeField = "Observation";
this.classCodeField = "OBS";
this.moodCodeField = "EVN";
}
public CV code {
get {
return this.codeField;
}
set {
this.codeField = value;
}
}
public CV value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
public PRPA_MT000002UK02Component34 component {
get {
return this.componentField;
}
set {
this.componentField = value;
}
}
public PRPA_MT000002UK02PertinentInformation3 pertinentInformation {
get {
return this.pertinentInformationField;
}
set {
this.pertinentInformationField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = 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;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(PRPA_MT000002UK02AdminResult));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current PRPA_MT000002UK02AdminResult 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 PRPA_MT000002UK02AdminResult object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output PRPA_MT000002UK02AdminResult 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 PRPA_MT000002UK02AdminResult obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT000002UK02AdminResult);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out PRPA_MT000002UK02AdminResult obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static PRPA_MT000002UK02AdminResult Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((PRPA_MT000002UK02AdminResult)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current PRPA_MT000002UK02AdminResult 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 PRPA_MT000002UK02AdminResult object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output PRPA_MT000002UK02AdminResult 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 PRPA_MT000002UK02AdminResult obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT000002UK02AdminResult);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out PRPA_MT000002UK02AdminResult obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static PRPA_MT000002UK02AdminResult 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 PRPA_MT000002UK02AdminResult object
/// </summary>
public virtual PRPA_MT000002UK02AdminResult Clone() {
return ((PRPA_MT000002UK02AdminResult)(this.MemberwiseClone()));
}
#endregion
}
}
| 39.137821 | 1,358 | 0.563099 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V4200/Generated/PRPA_MT000002UK02AdminResult.cs | 12,211 | C# |
using OnlineTechnicalSupport.Models.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OnlineTechnicalSupport.Models.ViewModels
{
public class IssueReportsViewModel
{
public IEnumerable<IssueReport> UnManagedRequests { get; set; }
public IEnumerable<IssueReport> ManagedRequests { get; set; }
}
public class LiveSupportRequestsViewModel
{
public IEnumerable<Chat> UnManagedRequests { get; set; }
public IEnumerable<Chat> ManagedRequests { get; set; }
}
} | 28.15 | 71 | 0.728242 | [
"MIT"
] | ozgurguclu/OnlineTechnicalSupport | OnlineTechnicalSupport/OnlineTechnicalSupport/Models/ViewModels/RequestsViewModel.cs | 565 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
using ContosoHR.Models;
namespace WebApplication3.Data.Migrations
{
[DbContext(typeof(ContosoHRContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.65942 | 125 | 0.468251 | [
"MIT"
] | CentauriAfrica/sql-server-samples | samples/features/security/ledger/source/ContosoHR/Migrations/ApplicationDbContextModelSnapshot.cs | 10,394 | C# |
using ADHDataManager.Library.Models;
using System.Collections.Generic;
namespace ADHDataManager.Library.DataAccess
{
public interface IPatientProgressData
{
void AddProgress(PatientProgressModel progress);
void DeleteProgress(string progressId);
List<PatientProgressModel> GetPatientProgresses();
List<PatientProgressModel> GetPatientProgressesByPatientId(string patientId);
}
} | 32.615385 | 85 | 0.771226 | [
"MIT"
] | AhmedDuraid/ADH-Medical-System | ADHDataManager.Library/DataAccess/IPatientProgressData.cs | 426 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _1.Letter_Repetition
{
class LetterRepetition
{
static void Main()
{
var characters = Console.ReadLine();
var asciiDictionary = new Dictionary<char, int>();
foreach (var character in characters)
{
if (!asciiDictionary.ContainsKey(character))
{
asciiDictionary[character] = 0;
}
asciiDictionary[character]++;
}
foreach (var kvp in asciiDictionary)
{
Console.WriteLine($"{kvp.Key} -> {kvp.Value}");
}
}
}
}
| 22.875 | 63 | 0.493169 | [
"MIT"
] | bingoo0/SoftUni-TechModule | DictionariesExercises/1. Letter Repetition/LetterRepetition.cs | 734 | C# |
namespace Switchvox.Extensions.Phones
{
class Remove
{
}
}
| 10.285714 | 38 | 0.625 | [
"MIT"
] | bfranklin825/SwitchvoxAPI | SwitchvoxAPI/_Unimplemented/extensions/Phones/Remove.cs | 74 | 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 rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Rekognition.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Rekognition.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for SegmentDetection Object
/// </summary>
public class SegmentDetectionUnmarshaller : IUnmarshaller<SegmentDetection, XmlUnmarshallerContext>, IUnmarshaller<SegmentDetection, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
SegmentDetection IUnmarshaller<SegmentDetection, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public SegmentDetection Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
SegmentDetection unmarshalledObject = new SegmentDetection();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("DurationMillis", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
unmarshalledObject.DurationMillis = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DurationSMPTE", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DurationSMPTE = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("EndTimecodeSMPTE", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.EndTimecodeSMPTE = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("EndTimestampMillis", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
unmarshalledObject.EndTimestampMillis = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ShotSegment", targetDepth))
{
var unmarshaller = ShotSegmentUnmarshaller.Instance;
unmarshalledObject.ShotSegment = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StartTimecodeSMPTE", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StartTimecodeSMPTE = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StartTimestampMillis", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
unmarshalledObject.StartTimestampMillis = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("TechnicalCueSegment", targetDepth))
{
var unmarshaller = TechnicalCueSegmentUnmarshaller.Instance;
unmarshalledObject.TechnicalCueSegment = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Type", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Type = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static SegmentDetectionUnmarshaller _instance = new SegmentDetectionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static SegmentDetectionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.535714 | 161 | 0.596206 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/Rekognition/Generated/Model/Internal/MarshallTransformations/SegmentDetectionUnmarshaller.cs | 5,535 | 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 kms-2014-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.KeyManagementService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.KeyManagementService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for RetireGrant operation
/// </summary>
public class RetireGrantResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
RetireGrantResponse response = new RetireGrantResponse();
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("DependencyTimeoutException"))
{
return new DependencyTimeoutException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidGrantIdException"))
{
return new InvalidGrantIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidGrantTokenException"))
{
return new InvalidGrantTokenException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("KMSInternalException"))
{
return new KMSInternalException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("KMSInvalidStateException"))
{
return new KMSInvalidStateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonKeyManagementServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static RetireGrantResponseUnmarshaller _instance = new RetireGrantResponseUnmarshaller();
internal static RetireGrantResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static RetireGrantResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 42.909091 | 175 | 0.679025 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/KeyManagementService/Generated/Model/Internal/MarshallTransformations/RetireGrantResponseUnmarshaller.cs | 4,720 | C# |
using System;
using System.Collections.Generic;
namespace PerformanceEfCore.EFCore.Models
{
public partial class StateProvince
{
public StateProvince()
{
Address = new HashSet<Address>();
SalesTaxRate = new HashSet<SalesTaxRate>();
}
public int StateProvinceID { get; set; }
public string StateProvinceCode { get; set; }
public string CountryRegionCode { get; set; }
public bool IsOnlyStateProvinceFlag { get; set; }
public string Name { get; set; }
public int TerritoryID { get; set; }
public Guid rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual ICollection<Address> Address { get; set; }
public virtual ICollection<SalesTaxRate> SalesTaxRate { get; set; }
public virtual CountryRegion CountryRegionCodeNavigation { get; set; }
public virtual SalesTerritory Territory { get; set; }
}
}
| 33.758621 | 78 | 0.640449 | [
"BSD-3-Clause"
] | Manishkr117/DesignPattern | DOTNETCORE/EFCoreSamples/PerformanceEfCore/EFCore/Models/StateProvince.cs | 981 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class DeserializeStringConvert
{
public string Name { get; set; }
public int Age { get; set; }
public double Height { get; set; }
public decimal Price { get; set; }
}
}
| 39.388889 | 68 | 0.732722 | [
"MIT"
] | belav/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestObjects/DeserializeStringConvert.cs | 1,418 | C# |
namespace QuaverExtension
{
static class Convert
{
internal static int CharToInt(char c)
{
return int.Parse(c.ToString());
}
}
}
| 16.181818 | 45 | 0.539326 | [
"MIT"
] | Emik03/Quaver | Assets/Quaver/Scripts/Convert.cs | 180 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved.
*
*/
#endregion
namespace Krypton.Toolkit
{
/// <summary>
/// Extend the visual control base class with the ISupportInitializeNotification interface.
/// </summary>
[ToolboxItem(false)]
[DesignerCategory("code")]
public abstract class VisualControl : VisualControlBase,
ISupportInitializeNotification
{
#region Instance Fields
#endregion
#region Events
/// <summary>
/// Occurs when the control is initialized.
/// </summary>
[Category("Behavior")]
[Description("Occurs when the control has been fully initialized.")]
public event EventHandler Initialized;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the VisualControl class.
/// </summary>
protected VisualControl()
{
}
#endregion
#region Public
/// <summary>
/// Signals the object that initialization is starting.
/// </summary>
public virtual void BeginInit()
{
// Remember that fact we are inside a BeginInit/EndInit pair
IsInitializing = true;
// No need to layout the view during initialization
SuspendLayout();
}
/// <summary>
/// Signals the object that initialization is complete.
/// </summary>
public virtual void EndInit()
{
// We are now initialized
IsInitialized = true;
// We are no longer initializing
IsInitializing = false;
// Need to recalculate anything relying on the palette
DirtyPaletteCounter++;
// We always need a paint and layout
OnNeedPaint(this, new NeedLayoutEventArgs(true));
// Should layout once initialization is complete
// https://github.com/Krypton-Suite/Standard-Toolkit/issues/393
// Do not do layout as `true` here , as al the controls have already had the scaling
// factors applied once, _do not do them again!_
ResumeLayout(false);
// Raise event to show control is now initialized
OnInitialized(EventArgs.Empty);
}
/// <summary>
/// Gets a value indicating if the control is initialized.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool IsInitialized
{
[DebuggerStepThrough]
get;
set;
}
/// <summary>
/// Gets a value indicating if the control is initialized.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool IsInitializing
{
[DebuggerStepThrough]
get;
set;
}
#endregion
#region Internal
internal bool InDesignMode => DesignMode;
#endregion
#region Protected Virtual
/// <summary>
/// Raises the Initialized event.
/// </summary>
/// <param name="e">An EventArgs containing the event data.</param>
protected virtual void OnInitialized(EventArgs e) => Initialized?.Invoke(this, EventArgs.Empty);
#endregion
}
}
| 30.141732 | 119 | 0.583072 | [
"BSD-3-Clause"
] | Krypton-Suite/Standard-Toolkit | Source/Krypton Components/Krypton.Toolkit/Controls Visuals/VisualControl.cs | 3,831 | C# |
using UnityEditor;
using UnityEngine;
[CanEditMultipleObjects, CustomEditor(typeof(MegaFFD3x3x3))]
public class MegaFFD3x3x3Editor : MegaFFDEditor
{
public override string GetHelpString() { return "FFD3x3x3 Modifier by Chris West"; }
} | 29.75 | 85 | 0.806723 | [
"MIT"
] | Kingminje/AR_Plant-Growth-ARKit- | Mega-Fiers/Editor/MegaFiers/MegaFFD3x3x3Editor.cs | 240 | 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 comprehend-2017-11-27.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.Comprehend.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Comprehend.Model.Internal.MarshallTransformations
{
/// <summary>
/// StartEventsDetectionJob Request Marshaller
/// </summary>
public class StartEventsDetectionJobRequestMarshaller : IMarshaller<IRequest, StartEventsDetectionJobRequest> , 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((StartEventsDetectionJobRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(StartEventsDetectionJobRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Comprehend");
string target = "Comprehend_20171127.StartEventsDetectionJob";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-11-27";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetClientRequestToken())
{
context.Writer.WritePropertyName("ClientRequestToken");
context.Writer.Write(publicRequest.ClientRequestToken);
}
else if(!(publicRequest.IsSetClientRequestToken()))
{
context.Writer.WritePropertyName("ClientRequestToken");
context.Writer.Write(Guid.NewGuid().ToString());
}
if(publicRequest.IsSetDataAccessRoleArn())
{
context.Writer.WritePropertyName("DataAccessRoleArn");
context.Writer.Write(publicRequest.DataAccessRoleArn);
}
if(publicRequest.IsSetInputDataConfig())
{
context.Writer.WritePropertyName("InputDataConfig");
context.Writer.WriteObjectStart();
var marshaller = InputDataConfigMarshaller.Instance;
marshaller.Marshall(publicRequest.InputDataConfig, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetJobName())
{
context.Writer.WritePropertyName("JobName");
context.Writer.Write(publicRequest.JobName);
}
if(publicRequest.IsSetLanguageCode())
{
context.Writer.WritePropertyName("LanguageCode");
context.Writer.Write(publicRequest.LanguageCode);
}
if(publicRequest.IsSetOutputDataConfig())
{
context.Writer.WritePropertyName("OutputDataConfig");
context.Writer.WriteObjectStart();
var marshaller = OutputDataConfigMarshaller.Instance;
marshaller.Marshall(publicRequest.OutputDataConfig, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetTags())
{
context.Writer.WritePropertyName("Tags");
context.Writer.WriteArrayStart();
foreach(var publicRequestTagsListValue in publicRequest.Tags)
{
context.Writer.WriteObjectStart();
var marshaller = TagMarshaller.Instance;
marshaller.Marshall(publicRequestTagsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetTargetEventTypes())
{
context.Writer.WritePropertyName("TargetEventTypes");
context.Writer.WriteArrayStart();
foreach(var publicRequestTargetEventTypesListValue in publicRequest.TargetEventTypes)
{
context.Writer.Write(publicRequestTargetEventTypesListValue);
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static StartEventsDetectionJobRequestMarshaller _instance = new StartEventsDetectionJobRequestMarshaller();
internal static StartEventsDetectionJobRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static StartEventsDetectionJobRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.291429 | 161 | 0.588121 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/Comprehend/Generated/Model/Internal/MarshallTransformations/StartEventsDetectionJobRequestMarshaller.cs | 6,701 | C# |
namespace TextAnalyzer.Infrastructure.Interfaces;
public interface IText : ITextSource
{
public string Title { get; set; }
public string Group { get; init; }
} | 24.142857 | 50 | 0.727811 | [
"Apache-2.0"
] | SaveliyKolesnikov/LetterUsageAnalyzer | TextAnalyzer.Infrastructure/Interfaces/IText.cs | 171 | C# |
namespace Octopus.Client.Model
{
public enum FeedType
{
None = 0,
NuGet,
Docker
}
} | 13.333333 | 31 | 0.508333 | [
"Apache-2.0"
] | roederja/OctopusClients | source/Octopus.Client/Model/FeedType.cs | 122 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.EntityFrameworkCore.ChangeTracking
{
public abstract class TrackGraphTestBase
{
public class TrackGraphTest : TrackGraphTestBase
{
protected override IList<string> TrackGraph(DbContext context, object root, Action<EntityEntryGraphNode> callback)
{
var traversal = new List<string>();
context.ChangeTracker.TrackGraph(
root, node =>
{
callback(node);
traversal.Add(NodeString(node));
});
return traversal;
}
}
public class TrackGraphTestWithState : TrackGraphTestBase
{
protected override IList<string> TrackGraph(DbContext context, object root, Action<EntityEntryGraphNode> callback)
{
var traversal = new List<string>();
context.ChangeTracker.TrackGraph<EntityState>(
root,
default,
node =>
{
if (node.Entry.State != EntityState.Detached)
{
return false;
}
callback(node);
traversal.Add(NodeString(node));
return node.Entry.State != EntityState.Detached;
});
return traversal;
}
}
protected abstract IList<string> TrackGraph(
DbContext context,
object root,
Action<EntityEntryGraphNode> callback);
private static string NodeString(EntityEntryGraphNode node)
=> EntryString(node.SourceEntry)
+ " ---"
+ node.InboundNavigation?.Name
+ "--> "
+ EntryString(node.Entry);
private static string EntryString(EntityEntry entry)
=> entry == null
? "<None>"
: entry.Metadata.DisplayName()
+ ":"
+ entry.Property(entry.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue;
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Can_attach_nullable_PK_parent_with_child_collection(bool useAttach, bool setKeys)
{
using var context = new EarlyLearningCenter(GetType().Name);
var category = new NullbileCategory
{
Products = new List<NullbileProduct>
{
new(),
new(),
new()
}
};
if (setKeys)
{
context.Entry(category).Property("Id").CurrentValue = 1;
context.Entry(category.Products[0]).Property("Id").CurrentValue = 1;
context.Entry(category.Products[1]).Property("Id").CurrentValue = 2;
context.Entry(category.Products[2]).Property("Id").CurrentValue = 3;
}
if (useAttach)
{
context.Attach(category);
}
else
{
Assert.Equal(
new List<string>
{
"<None> -----> NullbileCategory:1",
"NullbileCategory:1 ---Products--> NullbileProduct:1",
"NullbileCategory:1 ---Products--> NullbileProduct:2",
"NullbileCategory:1 ---Products--> NullbileProduct:3"
},
TrackGraph(
context,
category, node => node.Entry.State = node.Entry.IsKeySet ? EntityState.Unchanged : EntityState.Added));
}
Assert.Equal(!setKeys, context.ChangeTracker.HasChanges());
Assert.Equal(4, context.ChangeTracker.Entries().Count());
var categoryEntry = context.Entry(category);
var product0Entry = context.Entry(category.Products[0]);
var product1Entry = context.Entry(category.Products[1]);
var product2Entry = context.Entry(category.Products[2]);
var expectedState = setKeys ? EntityState.Unchanged : EntityState.Added;
Assert.Equal(expectedState, categoryEntry.State);
Assert.Equal(expectedState, product0Entry.State);
Assert.Equal(expectedState, product1Entry.State);
Assert.Equal(expectedState, product2Entry.State);
Assert.Same(category, category.Products[0].Category);
Assert.Same(category, category.Products[1].Category);
Assert.Same(category, category.Products[2].Category);
var categoryId = categoryEntry.Property("Id").CurrentValue;
Assert.NotNull(categoryId);
Assert.Equal(categoryId, product0Entry.Property("CategoryId").CurrentValue);
Assert.Equal(categoryId, product1Entry.Property("CategoryId").CurrentValue);
Assert.Equal(categoryId, product2Entry.Property("CategoryId").CurrentValue);
}
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Can_attach_nullable_PK_parent_with_one_to_one_children(bool useAttach, bool setKeys)
{
using var context = new EarlyLearningCenter(GetType().Name);
var category = new NullbileCategory { Info = new NullbileCategoryInfo() };
if (setKeys)
{
context.Entry(category).Property("Id").CurrentValue = 1;
context.Entry(category.Info).Property("Id").CurrentValue = 1;
}
if (useAttach)
{
context.Attach(category);
}
else
{
Assert.Equal(
new List<string> { "<None> -----> NullbileCategory:1", "NullbileCategory:1 ---Info--> NullbileCategoryInfo:1" },
TrackGraph(
context,
category, node => node.Entry.State = node.Entry.IsKeySet ? EntityState.Unchanged : EntityState.Added));
}
Assert.Equal(!setKeys, context.ChangeTracker.HasChanges());
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var expectedState = setKeys ? EntityState.Unchanged : EntityState.Added;
Assert.Equal(expectedState, context.Entry(category).State);
Assert.Equal(expectedState, context.Entry(category.Info).State);
Assert.Same(category, category.Info.Category);
}
[ConditionalTheory]
[InlineData(false, false, false)]
[InlineData(false, true, false)]
[InlineData(true, false, false)]
[InlineData(true, true, false)]
[InlineData(false, false, true)]
[InlineData(false, true, true)]
[InlineData(true, false, true)]
[InlineData(true, true, true)]
public void Can_attach_parent_with_owned_dependent(bool useAttach, bool setPrincipalKey, bool setDependentKey)
{
using var context = new EarlyLearningCenter(GetType().Name);
var sweet = new Sweet { Dreams = new Dreams { Are = new AreMade(), Made = new AreMade() } };
if (setPrincipalKey)
{
sweet.Id = 1;
}
if (setDependentKey)
{
var dreamsEntry = context.Entry(sweet).Reference(e => e.Dreams).TargetEntry;
dreamsEntry.Property("SweetId").CurrentValue = 1;
dreamsEntry.Reference(e => e.Are).TargetEntry.Property("DreamsSweetId").CurrentValue = 1;
dreamsEntry.Reference(e => e.Made).TargetEntry.Property("DreamsSweetId").CurrentValue = 1;
}
if (useAttach)
{
context.Attach(sweet);
}
else
{
Assert.Equal(
new List<string>
{
"<None> -----> Sweet:1",
"Sweet:1 ---Dreams--> Dreams:1",
"Dreams:1 ---Are--> Dreams.Are#AreMade:1",
"Dreams:1 ---Made--> Dreams.Made#AreMade:1"
},
TrackGraph(
context,
sweet,
node => node.Entry.State = node.Entry.Metadata.IsOwned()
? node.SourceEntry.State
: node.Entry.IsKeySet
? EntityState.Unchanged
: EntityState.Added));
}
Assert.Equal(4, context.ChangeTracker.Entries().Count());
var dependentEntry = context.Entry(sweet.Dreams);
var dependentEntry2a = context.Entry(sweet.Dreams.Are);
var dependentEntry2b = context.Entry(sweet.Dreams.Made);
var expectedPrincipalState = setPrincipalKey ? EntityState.Unchanged : EntityState.Added;
var expectedDependentState = setPrincipalKey || (setDependentKey && useAttach) ? EntityState.Unchanged : EntityState.Added;
Assert.Equal(
expectedPrincipalState == EntityState.Added || expectedDependentState == EntityState.Added,
context.ChangeTracker.HasChanges());
Assert.Equal(expectedPrincipalState, context.Entry(sweet).State);
Assert.Equal(expectedDependentState, dependentEntry.State);
Assert.Equal(expectedDependentState, dependentEntry2a.State);
Assert.Equal(expectedDependentState, dependentEntry2b.State);
Assert.Equal(1, sweet.Id);
Assert.Equal(1, dependentEntry.Property(dependentEntry.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
Assert.Equal(1, dependentEntry2a.Property(dependentEntry2a.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
Assert.Equal(1, dependentEntry2b.Property(dependentEntry2b.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
}
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Can_attach_owned_dependent_with_reference_to_parent(bool useAttach, bool setDependentKey)
{
using var context = new EarlyLearningCenter(GetType().Name);
var dreams = new Dreams
{
Sweet = new Sweet { Id = 1 },
Are = new AreMade(),
Made = new AreMade()
};
if (setDependentKey)
{
var dreamsEntry = context.Entry(dreams);
dreamsEntry.Property("SweetId").CurrentValue = 1;
dreamsEntry.Reference(e => e.Are).TargetEntry.Property("DreamsSweetId").CurrentValue = 1;
dreamsEntry.Reference(e => e.Made).TargetEntry.Property("DreamsSweetId").CurrentValue = 1;
}
if (useAttach)
{
context.Attach(dreams);
}
else
{
Assert.Equal(
new List<string>
{
"<None> -----> Dreams:1",
"Dreams:1 ---Are--> Dreams.Are#AreMade:1",
"Dreams:1 ---Made--> Dreams.Made#AreMade:1",
"Dreams:1 ---Sweet--> Sweet:1"
},
TrackGraph(
context,
dreams,
node => node.Entry.State = node.Entry.IsKeySet ? EntityState.Unchanged : EntityState.Added));
}
Assert.Equal(4, context.ChangeTracker.Entries().Count());
Assert.Equal(!setDependentKey, context.ChangeTracker.HasChanges());
var dependentEntry = context.Entry(dreams);
var dependentEntry2a = context.Entry(dreams.Are);
var dependentEntry2b = context.Entry(dreams.Made);
var expectedPrincipalState = EntityState.Unchanged;
var expectedDependentState = setDependentKey ? EntityState.Unchanged : EntityState.Added;
Assert.Equal(expectedPrincipalState, context.Entry(dreams.Sweet).State);
Assert.Equal(expectedDependentState, dependentEntry.State);
Assert.Equal(expectedDependentState, dependentEntry2a.State);
Assert.Equal(expectedDependentState, dependentEntry2b.State);
Assert.Equal(1, dreams.Sweet.Id);
Assert.Equal(1, dependentEntry.Property(dependentEntry.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
Assert.Equal(1, dependentEntry2a.Property(dependentEntry2a.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
Assert.Equal(1, dependentEntry2b.Property(dependentEntry2b.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
}
[ConditionalFact]
public void Can_attach_parent_with_child_collection()
{
using var context = new EarlyLearningCenter(GetType().Name);
var category = new Category
{
Id = 1,
Products = new List<Product>
{
new() { Id = 1 },
new() { Id = 2 },
new() { Id = 3 }
}
};
Assert.Equal(
new List<string>
{
"<None> -----> Category:1",
"Category:1 ---Products--> Product:1",
"Category:1 ---Products--> Product:2",
"Category:1 ---Products--> Product:3"
},
TrackGraph(
context,
category,
node => node.Entry.State = EntityState.Modified));
Assert.Equal(4, context.ChangeTracker.Entries().Count());
Assert.True(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Modified, context.Entry(category).State);
Assert.Equal(EntityState.Modified, context.Entry(category.Products[0]).State);
Assert.Equal(EntityState.Modified, context.Entry(category.Products[1]).State);
Assert.Equal(EntityState.Modified, context.Entry(category.Products[2]).State);
Assert.Same(category, category.Products[0].Category);
Assert.Same(category, category.Products[1].Category);
Assert.Same(category, category.Products[2].Category);
Assert.Equal(category.Id, category.Products[0].CategoryId);
Assert.Equal(category.Id, category.Products[1].CategoryId);
Assert.Equal(category.Id, category.Products[2].CategoryId);
}
[ConditionalFact]
public void Can_attach_child_with_reference_to_parent()
{
using var context = new EarlyLearningCenter(GetType().Name);
var product = new Product { Id = 1, Category = new Category { Id = 1 } };
Assert.Equal(
new List<string> { "<None> -----> Product:1", "Product:1 ---Category--> Category:1" },
TrackGraph(
context,
product,
node => node.Entry.State = EntityState.Modified));
Assert.Equal(2, context.ChangeTracker.Entries().Count());
Assert.True(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Modified, context.Entry(product).State);
Assert.Equal(EntityState.Modified, context.Entry(product.Category).State);
Assert.Same(product, product.Category.Products[0]);
Assert.Equal(product.Category.Id, product.CategoryId);
}
[ConditionalFact]
public void Can_attach_parent_with_one_to_one_children()
{
using var context = new EarlyLearningCenter(GetType().Name);
var product = new Product { Id = 1, Details = new ProductDetails { Id = 1, Tag = new ProductDetailsTag { Id = 1 } } };
Assert.Equal(
new List<string>
{
"<None> -----> Product:1",
"Product:1 ---Details--> ProductDetails:1",
"ProductDetails:1 ---Tag--> ProductDetailsTag:1"
},
TrackGraph(
context,
product,
node => node.Entry.State = EntityState.Unchanged));
Assert.Equal(3, context.ChangeTracker.Entries().Count());
Assert.False(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Unchanged, context.Entry(product).State);
Assert.Equal(EntityState.Unchanged, context.Entry(product.Details).State);
Assert.Equal(EntityState.Unchanged, context.Entry(product.Details.Tag).State);
Assert.Same(product, product.Details.Product);
Assert.Same(product.Details, product.Details.Tag.Details);
}
[ConditionalFact]
public void Can_attach_child_with_one_to_one_parents()
{
using var context = new EarlyLearningCenter(GetType().Name);
var tag = new ProductDetailsTag { Id = 1, Details = new ProductDetails { Id = 1, Product = new Product { Id = 1 } } };
Assert.Equal(
new List<string>
{
"<None> -----> ProductDetailsTag:1",
"ProductDetailsTag:1 ---Details--> ProductDetails:1",
"ProductDetails:1 ---Product--> Product:1"
},
TrackGraph(
context,
tag,
node => node.Entry.State = EntityState.Unchanged));
Assert.Equal(3, context.ChangeTracker.Entries().Count());
Assert.False(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Unchanged, context.Entry(tag).State);
Assert.Equal(EntityState.Unchanged, context.Entry(tag.Details).State);
Assert.Equal(EntityState.Unchanged, context.Entry(tag.Details.Product).State);
Assert.Same(tag, tag.Details.Tag);
Assert.Same(tag.Details, tag.Details.Product.Details);
}
[ConditionalFact]
public void Can_attach_entity_with_one_to_one_parent_and_child()
{
using var context = new EarlyLearningCenter(GetType().Name);
var details = new ProductDetails
{
Id = 1,
Product = new Product { Id = 1 },
Tag = new ProductDetailsTag { Id = 1 }
};
Assert.Equal(
new List<string>
{
"<None> -----> ProductDetails:1",
"ProductDetails:1 ---Product--> Product:1",
"ProductDetails:1 ---Tag--> ProductDetailsTag:1"
},
TrackGraph(
context,
details,
node => node.Entry.State = EntityState.Unchanged));
Assert.Equal(3, context.ChangeTracker.Entries().Count());
Assert.False(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Unchanged, context.Entry(details).State);
Assert.Equal(EntityState.Unchanged, context.Entry(details.Product).State);
Assert.Equal(EntityState.Unchanged, context.Entry(details.Tag).State);
Assert.Same(details, details.Tag.Details);
Assert.Same(details, details.Product.Details);
}
[ConditionalFact]
public void Entities_that_are_already_tracked_will_not_get_attached()
{
using var context = new EarlyLearningCenter(GetType().Name);
var existingProduct = context.Attach(
new Product { Id = 2, CategoryId = 1 }).Entity;
var category = new Category
{
Id = 1,
Products = new List<Product>
{
new() { Id = 1 },
existingProduct,
new() { Id = 3 }
}
};
Assert.Equal(
new List<string>
{
"<None> -----> Category:1",
"Category:1 ---Products--> Product:1",
"Category:1 ---Products--> Product:3"
},
TrackGraph(
context,
category,
node => node.Entry.State = EntityState.Modified));
Assert.Equal(4, context.ChangeTracker.Entries().Count());
Assert.True(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Modified, context.Entry(category).State);
Assert.Equal(EntityState.Modified, context.Entry(category.Products[0]).State);
Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[1]).State);
Assert.Equal(EntityState.Modified, context.Entry(category.Products[2]).State);
Assert.Same(category, category.Products[0].Category);
Assert.Same(category, category.Products[1].Category);
Assert.Same(category, category.Products[2].Category);
Assert.Equal(category.Id, category.Products[0].CategoryId);
Assert.Equal(category.Id, category.Products[1].CategoryId);
Assert.Equal(category.Id, category.Products[2].CategoryId);
}
[ConditionalFact]
public void Further_graph_traversal_stops_if_an_entity_is_not_attached()
{
using var context = new EarlyLearningCenter(GetType().Name);
var category = new Category
{
Id = 1,
Products = new List<Product>
{
new()
{
Id = 1,
CategoryId = 1,
Details = new ProductDetails { Id = 1 }
},
new()
{
Id = 2,
CategoryId = 1,
Details = new ProductDetails { Id = 2 }
},
new()
{
Id = 3,
CategoryId = 1,
Details = new ProductDetails { Id = 3 }
}
}
};
Assert.Equal(
new List<string>
{
"<None> -----> Category:1",
"Category:1 ---Products--> Product:1",
"Product:1 ---Details--> ProductDetails:1",
"Category:1 ---Products--> Product:2",
"Category:1 ---Products--> Product:3",
"Product:3 ---Details--> ProductDetails:3"
},
TrackGraph(
context,
category,
node =>
{
if (!(node.Entry.Entity is Product product)
|| product.Id != 2)
{
node.Entry.State = EntityState.Unchanged;
}
}));
Assert.Equal(5, context.ChangeTracker.Entries().Count(e => e.State != EntityState.Detached));
Assert.False(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Unchanged, context.Entry(category).State);
Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[0]).State);
Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[0].Details).State);
Assert.Equal(EntityState.Detached, context.Entry(category.Products[1]).State);
Assert.Equal(EntityState.Detached, context.Entry(category.Products[1].Details).State);
Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[2]).State);
Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[2].Details).State);
Assert.Same(category, category.Products[0].Category);
Assert.Null(category.Products[1].Category);
Assert.Same(category, category.Products[2].Category);
Assert.Equal(category.Id, category.Products[0].CategoryId);
Assert.Equal(category.Id, category.Products[1].CategoryId);
Assert.Equal(category.Id, category.Products[2].CategoryId);
Assert.Same(category.Products[0], category.Products[0].Details.Product);
Assert.Null(category.Products[1].Details.Product);
Assert.Same(category.Products[2], category.Products[2].Details.Product);
}
[ConditionalFact]
public void Graph_iterator_does_not_go_visit_Apple()
{
using var context = new EarlyLearningCenter(GetType().Name);
var details = new ProductDetails { Id = 1, Product = new Product { Id = 1 } };
details.Product.Details = details;
Assert.Equal(
new List<string> { "<None> -----> ProductDetails:1" },
TrackGraph(
context,
details,
e => { }));
Assert.Equal(0, context.ChangeTracker.Entries().Count(e => e.State != EntityState.Detached));
Assert.False(context.ChangeTracker.HasChanges());
}
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Can_add_owned_dependent_with_reference_to_parent(bool useAdd, bool setDependentKey)
{
using var context = new EarlyLearningCenter(GetType().Name);
var dreams = new Dreams
{
Sweet = new Sweet { Id = 1 },
Are = new AreMade(),
Made = new AreMade()
};
context.Entry(dreams.Sweet).State = EntityState.Unchanged;
if (setDependentKey)
{
var dreamsEntry = context.Entry(dreams);
dreamsEntry.Property("SweetId").CurrentValue = 1;
dreamsEntry.Reference(e => e.Are).TargetEntry.Property("DreamsSweetId").CurrentValue = 1;
dreamsEntry.Reference(e => e.Made).TargetEntry.Property("DreamsSweetId").CurrentValue = 1;
}
if (useAdd)
{
context.Add(dreams);
}
else
{
Assert.Equal(
new List<string>
{
"<None> -----> Dreams:1",
"Dreams:1 ---Are--> Dreams.Are#AreMade:1",
"Dreams:1 ---Made--> Dreams.Made#AreMade:1"
},
TrackGraph(
context,
dreams,
node => node.Entry.State = node.Entry.IsKeySet && !node.Entry.Metadata.IsOwned()
? EntityState.Unchanged
: EntityState.Added));
}
Assert.Equal(4, context.ChangeTracker.Entries().Count());
Assert.True(context.ChangeTracker.HasChanges());
var dependentEntry = context.Entry(dreams);
var dependentEntry2a = context.Entry(dreams.Are);
var dependentEntry2b = context.Entry(dreams.Made);
var expectedPrincipalState = EntityState.Unchanged;
var expectedDependentState = EntityState.Added;
Assert.Equal(expectedPrincipalState, context.Entry(dreams.Sweet).State);
Assert.Equal(expectedDependentState, dependentEntry.State);
Assert.Equal(expectedDependentState, dependentEntry2a.State);
Assert.Equal(expectedDependentState, dependentEntry2b.State);
Assert.Equal(1, dreams.Sweet.Id);
Assert.Equal(1, dependentEntry.Property(dependentEntry.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
Assert.Equal(1, dependentEntry2a.Property(dependentEntry2a.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
Assert.Equal(1, dependentEntry2b.Property(dependentEntry2b.Metadata.FindPrimaryKey().Properties[0].Name).CurrentValue);
}
[ConditionalTheory] // Issue #12590
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Dependents_are_detached_not_deleted_when_principal_is_detached(bool delayCascade, bool trackNewDependents)
{
using var context = new EarlyLearningCenter(GetType().Name);
var category = new Category
{
Id = 1,
Products = new List<Product>
{
new() { Id = 1 },
new() { Id = 2 },
new() { Id = 3 }
}
};
context.Attach(category);
Assert.False(context.ChangeTracker.HasChanges());
var categoryEntry = context.Entry(category);
var product0Entry = context.Entry(category.Products[0]);
var product1Entry = context.Entry(category.Products[1]);
var product2Entry = context.Entry(category.Products[2]);
Assert.Equal(EntityState.Unchanged, categoryEntry.State);
Assert.Equal(EntityState.Unchanged, product0Entry.State);
Assert.Equal(EntityState.Unchanged, product1Entry.State);
Assert.Equal(EntityState.Unchanged, product2Entry.State);
if (delayCascade)
{
context.ChangeTracker.CascadeDeleteTiming = CascadeTiming.OnSaveChanges;
}
context.Entry(category).State = EntityState.Detached;
Assert.False(context.ChangeTracker.HasChanges());
Assert.Equal(EntityState.Detached, categoryEntry.State);
if (delayCascade)
{
Assert.Equal(EntityState.Unchanged, product0Entry.State);
Assert.Equal(EntityState.Unchanged, product1Entry.State);
Assert.Equal(EntityState.Unchanged, product2Entry.State);
}
else
{
Assert.Equal(EntityState.Detached, product0Entry.State);
Assert.Equal(EntityState.Detached, product1Entry.State);
Assert.Equal(EntityState.Detached, product2Entry.State);
}
var newCategory = new Category { Id = 1, };
if (trackNewDependents)
{
newCategory.Products = new List<Product>
{
new() { Id = 1 },
new() { Id = 2 },
new() { Id = 3 }
};
}
if (delayCascade && trackNewDependents)
{
Assert.Equal(
CoreStrings.IdentityConflict(nameof(Product), "{'Id'}"),
Assert.Throws<InvalidOperationException>(TrackGraph).Message);
}
else
{
Assert.Equal(
trackNewDependents
? new List<string>
{
"<None> -----> Category:1",
"Category:1 ---Products--> Product:1",
"Category:1 ---Products--> Product:2",
"Category:1 ---Products--> Product:3"
}
: new List<string> { "<None> -----> Category:1" },
TrackGraph());
if (trackNewDependents || delayCascade)
{
Assert.Equal(4, context.ChangeTracker.Entries().Count());
Assert.True(context.ChangeTracker.HasChanges());
categoryEntry = context.Entry(newCategory);
product0Entry = context.Entry(newCategory.Products[0]);
product1Entry = context.Entry(newCategory.Products[1]);
product2Entry = context.Entry(newCategory.Products[2]);
Assert.Equal(EntityState.Modified, categoryEntry.State);
if (trackNewDependents)
{
Assert.Equal(EntityState.Modified, product0Entry.State);
Assert.Equal(EntityState.Modified, product1Entry.State);
Assert.Equal(EntityState.Modified, product2Entry.State);
Assert.NotSame(newCategory.Products[0], category.Products[0]);
Assert.NotSame(newCategory.Products[1], category.Products[1]);
Assert.NotSame(newCategory.Products[2], category.Products[2]);
}
else
{
Assert.Equal(EntityState.Unchanged, product0Entry.State);
Assert.Equal(EntityState.Unchanged, product1Entry.State);
Assert.Equal(EntityState.Unchanged, product2Entry.State);
Assert.Same(newCategory.Products[0], category.Products[0]);
Assert.Same(newCategory.Products[1], category.Products[1]);
Assert.Same(newCategory.Products[2], category.Products[2]);
}
Assert.Same(newCategory, newCategory.Products[0].Category);
Assert.Same(newCategory, newCategory.Products[1].Category);
Assert.Same(newCategory, newCategory.Products[2].Category);
Assert.Equal(newCategory.Id, product0Entry.Property("CategoryId").CurrentValue);
Assert.Equal(newCategory.Id, product1Entry.Property("CategoryId").CurrentValue);
Assert.Equal(newCategory.Id, product2Entry.Property("CategoryId").CurrentValue);
}
else
{
Assert.Single(context.ChangeTracker.Entries());
categoryEntry = context.Entry(newCategory);
Assert.Equal(EntityState.Modified, categoryEntry.State);
Assert.Null(newCategory.Products);
}
}
IList<string> TrackGraph()
{
return this.TrackGraph(
context,
newCategory,
node => node.Entry.State = EntityState.Modified);
}
}
[ConditionalFact]
public void TrackGraph_overload_can_visit_a_graph_without_attaching()
{
using var context = new EarlyLearningCenter(GetType().Name);
var category = new Category
{
Id = 1,
Products = new List<Product>
{
new()
{
Id = 1,
CategoryId = 1,
Details = new ProductDetails { Id = 1 }
},
new()
{
Id = 2,
CategoryId = 1,
Details = new ProductDetails { Id = 2 }
},
new()
{
Id = 3,
CategoryId = 1,
Details = new ProductDetails { Id = 3 }
}
}
};
var visited = new HashSet<object>();
var traversal = new List<string>();
context.ChangeTracker.TrackGraph(
category,
visited,
node =>
{
if (node.NodeState.Contains(node.Entry.Entity))
{
return false;
}
node.NodeState.Add(node.Entry.Entity);
traversal.Add(NodeString(node));
return true;
});
Assert.Equal(
new List<string>
{
"<None> -----> Category:1",
"Category:1 ---Products--> Product:1",
"Product:1 ---Details--> ProductDetails:1",
"Category:1 ---Products--> Product:2",
"Product:2 ---Details--> ProductDetails:2",
"Category:1 ---Products--> Product:3",
"Product:3 ---Details--> ProductDetails:3"
},
traversal);
Assert.Equal(7, visited.Count);
Assert.False(context.ChangeTracker.HasChanges());
foreach (var entity in new object[] { category }
.Concat(category.Products)
.Concat(category.Products.Select(e => e.Details)))
{
Assert.Equal(EntityState.Detached, context.Entry(entity).State);
}
}
[ConditionalFact]
public void Can_attach_parent_with_some_new_and_some_existing_entities()
{
KeyValueAttachTest(
GetType().Name,
(category, changeTracker) =>
{
Assert.Equal(
new List<string>
{
"<None> -----> Category:77",
"Category:77 ---Products--> Product:77",
"Category:77 ---Products--> Product:1",
"Category:77 ---Products--> Product:78"
},
TrackGraph(
changeTracker.Context,
category,
node => node.Entry.State = node.Entry.Entity is Product product && product.Id == 0
? EntityState.Added
: EntityState.Unchanged));
});
}
[ConditionalFact]
public void Can_attach_graph_using_built_in_tracker()
{
var tracker = new KeyValueEntityTracker(updateExistingEntities: false);
KeyValueAttachTest(
GetType().Name,
(category, changeTracker) => changeTracker.TrackGraph(category, tracker.TrackEntity));
}
[ConditionalFact]
public void Can_update_graph_using_built_in_tracker()
{
var tracker = new KeyValueEntityTracker(updateExistingEntities: true);
KeyValueAttachTest(
GetType().Name,
(category, changeTracker) => changeTracker.TrackGraph(category, tracker.TrackEntity),
expectModified: true);
}
private static void KeyValueAttachTest(string databaseName, Action<Category, ChangeTracker> tracker, bool expectModified = false)
{
using var context = new EarlyLearningCenter(databaseName);
var category = new Category
{
Id = 77,
Products = new List<Product>
{
new() { Id = 77, CategoryId = expectModified ? 0 : 77 },
new() { Id = 0, CategoryId = expectModified ? 0 : 77 },
new() { Id = 78, CategoryId = expectModified ? 0 : 77 }
}
};
tracker(category, context.ChangeTracker);
Assert.True(context.ChangeTracker.HasChanges());
Assert.Equal(4, context.ChangeTracker.Entries().Count());
var nonAddedState = expectModified ? EntityState.Modified : EntityState.Unchanged;
Assert.Equal(nonAddedState, context.Entry(category).State);
Assert.Equal(nonAddedState, context.Entry(category.Products[0]).State);
Assert.Equal(EntityState.Added, context.Entry(category.Products[1]).State);
Assert.Equal(nonAddedState, context.Entry(category.Products[2]).State);
Assert.Equal(77, category.Products[0].Id);
Assert.Equal(1, category.Products[1].Id);
Assert.Equal(78, category.Products[2].Id);
Assert.Same(category, category.Products[0].Category);
Assert.Same(category, category.Products[1].Category);
Assert.Same(category, category.Products[2].Category);
Assert.Equal(category.Id, category.Products[0].CategoryId);
Assert.Equal(category.Id, category.Products[1].CategoryId);
Assert.Equal(category.Id, category.Products[2].CategoryId);
}
[ConditionalFact]
public void Can_attach_graph_using_custom_delegate()
{
var tracker = new MyTracker(updateExistingEntities: false);
using var context = new EarlyLearningCenter(GetType().Name);
var category = new Category
{
Id = 77,
Products = new List<Product>
{
new() { Id = 77, CategoryId = 77 },
new() { Id = 0, CategoryId = 77 },
new() { Id = 78, CategoryId = 77 }
}
};
context.ChangeTracker.TrackGraph(category, tracker.TrackEntity);
Assert.Equal(4, context.ChangeTracker.Entries().Count());
Assert.Equal(EntityState.Unchanged, context.Entry(category).State);
Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[0]).State);
Assert.Equal(EntityState.Added, context.Entry(category.Products[1]).State);
Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[2]).State);
Assert.Equal(77, category.Products[0].Id);
Assert.Equal(777, category.Products[1].Id);
Assert.Equal(78, category.Products[2].Id);
Assert.Same(category, category.Products[0].Category);
Assert.Same(category, category.Products[1].Category);
Assert.Same(category, category.Products[2].Category);
Assert.Equal(category.Id, category.Products[0].CategoryId);
Assert.Equal(category.Id, category.Products[1].CategoryId);
Assert.Equal(category.Id, category.Products[2].CategoryId);
}
private class MyTracker : KeyValueEntityTracker
{
public MyTracker(bool updateExistingEntities)
: base(updateExistingEntities)
{
}
public override EntityState DetermineState(EntityEntry entry)
{
if (!entry.IsKeySet)
{
entry.GetInfrastructure()[entry.Metadata.FindPrimaryKey().Properties.Single()] = 777;
return EntityState.Added;
}
return base.DetermineState(entry);
}
}
[ConditionalFact]
public void TrackGraph_does_not_call_DetectChanges()
{
var provider =
InMemoryTestHelpers.Instance.CreateServiceProvider(
new ServiceCollection().AddScoped<IChangeDetector, ChangeDetectorProxy>());
using var context = new EarlyLearningCenter(GetType().Name, provider);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
changeDetector.DetectChangesCalled = false;
context.ChangeTracker.TrackGraph(CreateSimpleGraph(2), e => e.Entry.State = EntityState.Unchanged);
Assert.False(changeDetector.DetectChangesCalled);
context.ChangeTracker.DetectChanges();
Assert.True(changeDetector.DetectChangesCalled);
}
[ConditionalFact]
public void TrackGraph_overload_can_visit_an_already_attached_graph()
{
using var context = new EarlyLearningCenter(GetType().Name);
var category = new Category
{
Id = 1,
Products = new List<Product>
{
new()
{
Id = 1,
CategoryId = 1,
Details = new ProductDetails { Id = 1 }
},
new()
{
Id = 2,
CategoryId = 1,
Details = new ProductDetails { Id = 2 }
},
new()
{
Id = 3,
CategoryId = 1,
Details = new ProductDetails { Id = 3 }
}
}
};
context.Attach(category);
var visited = new HashSet<object>();
var traversal = new List<string>();
context.ChangeTracker.TrackGraph(
category, visited, e =>
{
if (e.NodeState.Contains(e.Entry.Entity))
{
return false;
}
e.NodeState.Add(e.Entry.Entity);
traversal.Add(NodeString(e));
return true;
});
Assert.Equal(
new List<string>
{
"<None> -----> Category:1",
"Category:1 ---Products--> Product:1",
"Product:1 ---Details--> ProductDetails:1",
"Category:1 ---Products--> Product:2",
"Product:2 ---Details--> ProductDetails:2",
"Category:1 ---Products--> Product:3",
"Product:3 ---Details--> ProductDetails:3"
},
traversal);
Assert.Equal(7, visited.Count);
}
private static void AssertValuesSaved(int id, int someInt, string someString)
{
using var context = new TheShadows();
var entry = context.Entry(context.Set<Dark>().Single(e => EF.Property<int>(e, "Id") == id));
Assert.Equal(id, entry.Property<int>("Id").CurrentValue);
Assert.Equal(someInt, entry.Property<int>("SomeInt").CurrentValue);
Assert.Equal(someString, entry.Property<string>("SomeString").CurrentValue);
}
private class TheShadows : DbContext
{
protected internal override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Dark>(
b =>
{
b.Property<int>("Id").ValueGeneratedOnAdd();
b.Property<int>("SomeInt");
b.Property<string>("SomeString");
});
protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseInternalServiceProvider(InMemoryFixture.DefaultServiceProvider)
.UseInMemoryDatabase(nameof(TheShadows));
}
private class Dark
{
}
private static Product CreateSimpleGraph(int id)
=> new() { Id = id, Category = new Category { Id = id } };
private class ChangeDetectorProxy : ChangeDetector
{
public ChangeDetectorProxy(
IDiagnosticsLogger<DbLoggerCategory.ChangeTracking> logger,
ILoggingOptions loggingOptions)
: base(logger, loggingOptions)
{
}
public bool DetectChangesCalled { get; set; }
public override void DetectChanges(InternalEntityEntry entry)
{
DetectChangesCalled = true;
base.DetectChanges(entry);
}
public override void DetectChanges(IStateManager stateManager)
{
DetectChangesCalled = true;
base.DetectChanges(stateManager);
}
}
private class Category
{
public int Id { get; set; }
public List<Product> Products { get; set; }
}
private class Product
{
public int Id { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
public ProductDetails Details { get; set; }
// ReSharper disable once CollectionNeverUpdated.Local
// ReSharper disable once MemberHidesStaticFromOuterClass
public List<OrderDetails> OrderDetails { get; set; }
}
private class ProductDetails
{
public int Id { get; set; }
public Product Product { get; set; }
public ProductDetailsTag Tag { get; set; }
}
private class ProductDetailsTag
{
public int Id { get; set; }
public ProductDetails Details { get; set; }
public ProductDetailsTagDetails TagDetails { get; set; }
}
private class ProductDetailsTagDetails
{
public int Id { get; set; }
public ProductDetailsTag Tag { get; set; }
}
private class Order
{
public int Id { get; set; }
// ReSharper disable once CollectionNeverUpdated.Local
// ReSharper disable once MemberHidesStaticFromOuterClass
public List<OrderDetails> OrderDetails { get; set; }
}
private class OrderDetails
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public Order Order { get; set; }
public Product Product { get; set; }
}
private class NullbileCategory
{
public List<NullbileProduct> Products { get; set; }
public NullbileCategoryInfo Info { get; set; }
}
private class NullbileCategoryInfo
{
// ReSharper disable once MemberHidesStaticFromOuterClass
public NullbileCategory Category { get; set; }
}
private class NullbileProduct
{
// ReSharper disable once MemberHidesStaticFromOuterClass
public NullbileCategory Category { get; set; }
}
private class Sweet
{
public int? Id { get; set; }
public Dreams Dreams { get; set; }
}
private class Dreams
{
public Sweet Sweet { get; set; }
public AreMade Are { get; set; }
public AreMade Made { get; set; }
public OfThis OfThis { get; set; }
}
private class AreMade
{
}
private class OfThis : AreMade
{
}
private class EarlyLearningCenter : DbContext
{
private readonly string _databaseName;
private readonly IServiceProvider _serviceProvider;
public EarlyLearningCenter(string databaseName)
{
_databaseName = databaseName;
_serviceProvider = InMemoryTestHelpers.Instance.CreateServiceProvider();
}
public EarlyLearningCenter(string databaseName, IServiceProvider serviceProvider)
{
_databaseName = databaseName;
_serviceProvider = serviceProvider;
}
protected internal override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<NullbileProduct>(
b =>
{
b.Property<int?>("Id");
b.Property<int?>("CategoryId");
b.HasKey("Id");
});
modelBuilder
.Entity<NullbileCategoryInfo>(
b =>
{
b.Property<int?>("Id");
b.Property<int?>("CategoryId");
b.HasKey("Id");
});
modelBuilder
.Entity<NullbileCategory>(
b =>
{
b.Property<int?>("Id");
b.HasKey("Id");
b.HasMany(e => e.Products).WithOne(e => e.Category).HasForeignKey("CategoryId");
b.HasOne(e => e.Info).WithOne(e => e.Category).HasForeignKey<NullbileCategoryInfo>("CategoryId");
});
modelBuilder.Entity<Sweet>().OwnsOne(
e => e.Dreams, b =>
{
b.WithOwner(e => e.Sweet);
b.OwnsOne(e => e.Are);
b.OwnsOne(e => e.Made);
b.OwnsOne(e => e.OfThis);
});
modelBuilder
.Entity<Category>().HasMany(e => e.Products).WithOne(e => e.Category);
modelBuilder
.Entity<ProductDetailsTag>().HasOne(e => e.TagDetails).WithOne(e => e.Tag)
.HasForeignKey<ProductDetailsTagDetails>(e => e.Id);
modelBuilder
.Entity<ProductDetails>().HasOne(e => e.Tag).WithOne(e => e.Details)
.HasForeignKey<ProductDetailsTag>(e => e.Id);
modelBuilder
.Entity<Product>().HasOne(e => e.Details).WithOne(e => e.Product)
.HasForeignKey<ProductDetails>(e => e.Id);
modelBuilder.Entity<OrderDetails>(
b =>
{
b.HasKey(
e => new { e.OrderId, e.ProductId });
b.HasOne(e => e.Order).WithMany(e => e.OrderDetails).HasForeignKey(e => e.OrderId);
b.HasOne(e => e.Product).WithMany(e => e.OrderDetails).HasForeignKey(e => e.ProductId);
});
}
protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseInternalServiceProvider(_serviceProvider)
.UseInMemoryDatabase(_databaseName);
}
public class KeyValueEntityTracker
{
private readonly bool _updateExistingEntities;
public KeyValueEntityTracker(bool updateExistingEntities)
{
_updateExistingEntities = updateExistingEntities;
}
public virtual void TrackEntity(EntityEntryGraphNode node)
=> node.Entry.GetInfrastructure().SetEntityState(DetermineState(node.Entry), acceptChanges: true);
public virtual EntityState DetermineState(EntityEntry entry)
=> entry.IsKeySet
? (_updateExistingEntities ? EntityState.Modified : EntityState.Unchanged)
: EntityState.Added;
}
}
}
| 39.110647 | 137 | 0.522028 | [
"MIT"
] | CameronAavik/efcore | test/EFCore.Tests/ChangeTracking/TrackGraphTestBase.cs | 56,202 | 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.Diagnostics;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace MS.Internal.Xml.Cache
{
/// <summary>
/// This is the default XPath/XQuery data model cache implementation. It will be used whenever
/// the user does not supply his own XPathNavigator implementation.
/// </summary>
internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo
{
private XPathNode[] _pageCurrent;
private XPathNode[] _pageParent;
private int _idxCurrent;
private int _idxParent;
private string _atomizedLocalName;
//-----------------------------------------------
// Constructors
//-----------------------------------------------
/// <summary>
/// Create a new navigator positioned on the specified current node. If the current node is a namespace or a collapsed
/// text node, then the parent is a virtualized parent (may be different than .Parent on the current node).
/// </summary>
public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent)
{
Debug.Assert(pageCurrent != null && idxCurrent != 0);
Debug.Assert((pageParent == null) == (idxParent == 0));
_pageCurrent = pageCurrent;
_pageParent = pageParent;
_idxCurrent = idxCurrent;
_idxParent = idxParent;
}
/// <summary>
/// Copy constructor.
/// </summary>
public XPathDocumentNavigator(XPathDocumentNavigator nav) : this(nav._pageCurrent, nav._idxCurrent, nav._pageParent, nav._idxParent)
{
_atomizedLocalName = nav._atomizedLocalName;
}
//-----------------------------------------------
// XPathItem
//-----------------------------------------------
/// <summary>
/// Get the string value of the current node, computed using data model dm:string-value rules.
/// If the node has a typed value, return the string representation of the value. If the node
/// is not a parent type (comment, text, pi, etc.), get its simple text value. Otherwise,
/// concatenate all text node descendants of the current node.
/// </summary>
public override string Value
{
get
{
string value;
XPathNode[] page, pageEnd;
int idx, idxEnd;
// Try to get the pre-computed string value of the node
value = _pageCurrent[_idxCurrent].Value;
if (value != null)
return value;
#if DEBUG
switch (_pageCurrent[_idxCurrent].NodeType)
{
case XPathNodeType.Namespace:
case XPathNodeType.Attribute:
case XPathNodeType.Comment:
case XPathNodeType.ProcessingInstruction:
Debug.Fail("ReadStringValue() should have taken care of these node types.");
break;
case XPathNodeType.Text:
Debug.Assert(_idxParent != 0 && _pageParent[_idxParent].HasCollapsedText,
"ReadStringValue() should have taken care of anything but collapsed text.");
break;
}
#endif
// If current node is collapsed text, then parent element has a simple text value
if (_idxParent != 0)
{
Debug.Assert(_pageCurrent[_idxCurrent].NodeType == XPathNodeType.Text);
return _pageParent[_idxParent].Value;
}
// Must be node with complex content, so concatenate the string values of all text descendants
string s = string.Empty;
StringBuilder bldr = null;
// Get all text nodes which follow the current node in document order, but which are still descendants
page = pageEnd = _pageCurrent;
idx = idxEnd = _idxCurrent;
if (!XPathNodeHelper.GetNonDescendant(ref pageEnd, ref idxEnd))
{
pageEnd = null;
idxEnd = 0;
}
while (XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd))
{
Debug.Assert(page[idx].NodeType == XPathNodeType.Element || page[idx].IsText);
if (s.Length == 0)
{
s = page[idx].Value;
}
else
{
if (bldr == null)
{
bldr = new StringBuilder();
bldr.Append(s);
}
bldr.Append(page[idx].Value);
}
}
return (bldr != null) ? bldr.ToString() : s;
}
}
//-----------------------------------------------
// XPathNavigator
//-----------------------------------------------
/// <summary>
/// Create a copy of this navigator, positioned to the same node in the tree.
/// </summary>
public override XPathNavigator Clone()
{
return new XPathDocumentNavigator(_pageCurrent, _idxCurrent, _pageParent, _idxParent);
}
/// <summary>
/// Get the XPath node type of the current node.
/// </summary>
public override XPathNodeType NodeType
{
get { return _pageCurrent[_idxCurrent].NodeType; }
}
/// <summary>
/// Get the local name portion of the current node's name.
/// </summary>
public override string LocalName
{
get { return _pageCurrent[_idxCurrent].LocalName; }
}
/// <summary>
/// Get the namespace portion of the current node's name.
/// </summary>
public override string NamespaceURI
{
get { return _pageCurrent[_idxCurrent].NamespaceUri; }
}
/// <summary>
/// Get the name of the current node.
/// </summary>
public override string Name
{
get { return _pageCurrent[_idxCurrent].Name; }
}
/// <summary>
/// Get the prefix portion of the current node's name.
/// </summary>
public override string Prefix
{
get { return _pageCurrent[_idxCurrent].Prefix; }
}
/// <summary>
/// Get the base URI of the current node.
/// </summary>
public override string BaseURI
{
get
{
XPathNode[] page;
int idx;
if (_idxParent != 0)
{
// Get BaseUri of parent for attribute, namespace, and collapsed text nodes
page = _pageParent;
idx = _idxParent;
}
else
{
page = _pageCurrent;
idx = _idxCurrent;
}
do
{
switch (page[idx].NodeType)
{
case XPathNodeType.Element:
case XPathNodeType.Root:
case XPathNodeType.ProcessingInstruction:
// BaseUri is always stored with Elements, Roots, and PIs
return page[idx].BaseUri;
}
// Get BaseUri of parent
idx = page[idx].GetParent(out page);
}
while (idx != 0);
return string.Empty;
}
}
/// <summary>
/// Return true if this is an element which used a shortcut tag in its Xml 1.0 serialized form.
/// </summary>
public override bool IsEmptyElement
{
get { return _pageCurrent[_idxCurrent].AllowShortcutTag; }
}
/// <summary>
/// Return the xml name table which was used to atomize all prefixes, local-names, and
/// namespace uris in the document.
/// </summary>
public override XmlNameTable NameTable
{
get { return _pageCurrent[_idxCurrent].Document.NameTable; }
}
/// <summary>
/// Position the navigator on the first attribute of the current node and return true. If no attributes
/// can be found, return false.
/// </summary>
public override bool MoveToFirstAttribute()
{
XPathNode[] page = _pageCurrent;
int idx = _idxCurrent;
if (XPathNodeHelper.GetFirstAttribute(ref _pageCurrent, ref _idxCurrent))
{
// Save element parent in order to make node-order comparison simpler
_pageParent = page;
_idxParent = idx;
return true;
}
return false;
}
/// <summary>
/// If positioned on an attribute, move to its next sibling attribute. If no attributes can be found,
/// return false.
/// </summary>
public override bool MoveToNextAttribute()
{
return XPathNodeHelper.GetNextAttribute(ref _pageCurrent, ref _idxCurrent);
}
/// <summary>
/// True if the current node has one or more attributes.
/// </summary>
public override bool HasAttributes
{
get { return _pageCurrent[_idxCurrent].HasAttribute; }
}
/// <summary>
/// Position the navigator on the attribute with the specified name and return true. If no matching
/// attribute can be found, return false. Don't assume the name parts are atomized with respect
/// to this document.
/// </summary>
public override bool MoveToAttribute(string localName, string namespaceURI)
{
XPathNode[] page = _pageCurrent;
int idx = _idxCurrent;
if ((object)localName != (object)_atomizedLocalName)
_atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
if (XPathNodeHelper.GetAttribute(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI))
{
// Save element parent in order to make node-order comparison simpler
_pageParent = page;
_idxParent = idx;
return true;
}
return false;
}
/// <summary>
/// Position the navigator on the namespace within the specified scope. If no matching namespace
/// can be found, return false.
/// </summary>
public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope)
{
XPathNode[] page;
int idx;
if (namespaceScope == XPathNamespaceScope.Local)
{
// Get local namespaces only
idx = XPathNodeHelper.GetLocalNamespaces(_pageCurrent, _idxCurrent, out page);
}
else
{
// Get all in-scope namespaces
idx = XPathNodeHelper.GetInScopeNamespaces(_pageCurrent, _idxCurrent, out page);
}
while (idx != 0)
{
// Don't include the xmlns:xml namespace node if scope is ExcludeXml
if (namespaceScope != XPathNamespaceScope.ExcludeXml || !page[idx].IsXmlNamespaceNode)
{
_pageParent = _pageCurrent;
_idxParent = _idxCurrent;
_pageCurrent = page;
_idxCurrent = idx;
return true;
}
// Skip past xmlns:xml
idx = page[idx].GetSibling(out page);
}
return false;
}
/// <summary>
/// Position the navigator on the next namespace within the specified scope. If no matching namespace
/// can be found, return false.
/// </summary>
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
XPathNode[] page = _pageCurrent, pageParent;
int idx = _idxCurrent, idxParent;
// If current node is not a namespace node, return false
if (page[idx].NodeType != XPathNodeType.Namespace)
return false;
while (true)
{
// Get next namespace sibling
idx = page[idx].GetSibling(out page);
// If there are no more nodes, return false
if (idx == 0)
return false;
switch (scope)
{
case XPathNamespaceScope.Local:
// Once parent changes, there are no longer any local namespaces
idxParent = page[idx].GetParent(out pageParent);
if (idxParent != _idxParent || (object)pageParent != (object)_pageParent)
return false;
break;
case XPathNamespaceScope.ExcludeXml:
// If node is xmlns:xml, then skip it
if (page[idx].IsXmlNamespaceNode)
continue;
break;
}
// Found a matching next namespace node, so return it
break;
}
_pageCurrent = page;
_idxCurrent = idx;
return true;
}
/// <summary>
/// If the current node is an attribute or namespace (not content), return false. Otherwise,
/// move to the next content node. Return false if there are no more content nodes.
/// </summary>
public override bool MoveToNext()
{
return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent);
}
/// <summary>
/// If the current node is an attribute or namespace (not content), return false. Otherwise,
/// move to the previous (sibling) content node. Return false if there are no previous content nodes.
/// </summary>
public override bool MoveToPrevious()
{
// If parent exists, then this is a namespace, an attribute, or a collapsed text node, all of which do
// not have previous siblings.
if (_idxParent != 0)
return false;
return XPathNodeHelper.GetPreviousContentSibling(ref _pageCurrent, ref _idxCurrent);
}
/// <summary>
/// Move to the first content-typed child of the current node. Return false if the current
/// node has no content children.
/// </summary>
public override bool MoveToFirstChild()
{
if (_pageCurrent[_idxCurrent].HasCollapsedText)
{
// Virtualize collapsed text nodes
_pageParent = _pageCurrent;
_idxParent = _idxCurrent;
_idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent);
return true;
}
return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent);
}
/// <summary>
/// Position the navigator on the parent of the current node. If the current node has no parent,
/// return false.
/// </summary>
public override bool MoveToParent()
{
if (_idxParent != 0)
{
// 1. For attribute nodes, element parent is always stored in order to make node-order
// comparison simpler.
// 2. For namespace nodes, parent is always stored in navigator in order to virtualize
// XPath 1.0 namespaces.
// 3. For collapsed text nodes, element parent is always stored in navigator.
Debug.Assert(_pageParent != null);
_pageCurrent = _pageParent;
_idxCurrent = _idxParent;
_pageParent = null;
_idxParent = 0;
return true;
}
return XPathNodeHelper.GetParent(ref _pageCurrent, ref _idxCurrent);
}
/// <summary>
/// Position this navigator to the same position as the "other" navigator. If the "other" navigator
/// is not of the same type as this navigator, then return false.
/// </summary>
public override bool MoveTo(XPathNavigator other)
{
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null)
{
_pageCurrent = that._pageCurrent;
_idxCurrent = that._idxCurrent;
_pageParent = that._pageParent;
_idxParent = that._idxParent;
return true;
}
return false;
}
/// <summary>
/// Position to the navigator to the element whose id is equal to the specified "id" string.
/// </summary>
public override bool MoveToId(string id)
{
XPathNode[] page;
int idx;
idx = _pageCurrent[_idxCurrent].Document.LookupIdElement(id, out page);
if (idx != 0)
{
// Move to ID element and clear parent state
Debug.Assert(page[idx].NodeType == XPathNodeType.Element);
_pageCurrent = page;
_idxCurrent = idx;
_pageParent = null;
_idxParent = 0;
return true;
}
return false;
}
/// <summary>
/// Returns true if this navigator is positioned to the same node as the "other" navigator. Returns false
/// if not, or if the "other" navigator is not the same type as this navigator.
/// </summary>
public override bool IsSamePosition(XPathNavigator other)
{
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null)
{
return _idxCurrent == that._idxCurrent && _pageCurrent == that._pageCurrent &&
_idxParent == that._idxParent && _pageParent == that._pageParent;
}
return false;
}
/// <summary>
/// Returns true if the current node has children.
/// </summary>
public override bool HasChildren
{
get { return _pageCurrent[_idxCurrent].HasContentChild; }
}
/// <summary>
/// Position the navigator on the root node of the current document.
/// </summary>
public override void MoveToRoot()
{
if (_idxParent != 0)
{
// Clear parent state
_pageParent = null;
_idxParent = 0;
}
_idxCurrent = _pageCurrent[_idxCurrent].GetRoot(out _pageCurrent);
}
/// <summary>
/// Move to the first element child of the current node with the specified name. Return false
/// if the current node has no matching element children.
/// </summary>
public override bool MoveToChild(string localName, string namespaceURI)
{
if ((object)localName != (object)_atomizedLocalName)
_atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
return XPathNodeHelper.GetElementChild(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI);
}
/// <summary>
/// Move to the first element sibling of the current node with the specified name. Return false
/// if the current node has no matching element siblings.
/// </summary>
public override bool MoveToNext(string localName, string namespaceURI)
{
if ((object)localName != (object)_atomizedLocalName)
_atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
return XPathNodeHelper.GetElementSibling(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI);
}
/// <summary>
/// Move to the first content child of the current node with the specified type. Return false
/// if the current node has no matching children.
/// </summary>
public override bool MoveToChild(XPathNodeType type)
{
if (_pageCurrent[_idxCurrent].HasCollapsedText)
{
// Only XPathNodeType.Text and XPathNodeType.All matches collapsed text node
if (type != XPathNodeType.Text && type != XPathNodeType.All)
return false;
// Virtualize collapsed text nodes
_pageParent = _pageCurrent;
_idxParent = _idxCurrent;
_idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent);
return true;
}
return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent, type);
}
/// <summary>
/// Move to the first content sibling of the current node with the specified type. Return false
/// if the current node has no matching siblings.
/// </summary>
public override bool MoveToNext(XPathNodeType type)
{
return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent, type);
}
/// <summary>
/// Move to the next element that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered)
/// 3. Has the specified QName
/// Return false if the current node has no matching following elements.
/// </summary>
public override bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end)
{
XPathNode[] pageEnd;
int idxEnd;
if ((object)localName != (object)_atomizedLocalName)
_atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
// Get node on which scan ends (null if rest of document should be scanned)
idxEnd = GetFollowingEnd(end as XPathDocumentNavigator, false, out pageEnd);
// If this navigator is positioned on a virtual node, then compute following of parent
if (_idxParent != 0)
{
if (!XPathNodeHelper.GetElementFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI))
return false;
_pageCurrent = _pageParent;
_idxCurrent = _idxParent;
_pageParent = null;
_idxParent = 0;
return true;
}
return XPathNodeHelper.GetElementFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI);
}
/// <summary>
/// Move to the next node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered)
/// 3. Has the specified XPathNodeType
/// Return false if the current node has no matching following nodes.
/// </summary>
public override bool MoveToFollowing(XPathNodeType type, XPathNavigator end)
{
XPathDocumentNavigator endTiny = end as XPathDocumentNavigator;
XPathNode[] page, pageEnd;
int idx, idxEnd;
// If searching for text, make sure to handle collapsed text nodes correctly
if (type == XPathNodeType.Text || type == XPathNodeType.All)
{
if (_pageCurrent[_idxCurrent].HasCollapsedText)
{
// Positioned on an element with collapsed text, so return the virtual text node, assuming it's before "end"
if (endTiny != null && _idxCurrent == endTiny._idxParent && _pageCurrent == endTiny._pageParent)
{
// "end" is positioned to a virtual attribute, namespace, or text node
return false;
}
_pageParent = _pageCurrent;
_idxParent = _idxCurrent;
_idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent);
return true;
}
if (type == XPathNodeType.Text)
{
// Get node on which scan ends (null if rest of document should be scanned, parent if positioned on virtual node)
idxEnd = GetFollowingEnd(endTiny, true, out pageEnd);
// If this navigator is positioned on a virtual node, then compute following of parent
if (_idxParent != 0)
{
page = _pageParent;
idx = _idxParent;
}
else
{
page = _pageCurrent;
idx = _idxCurrent;
}
// If ending node is a virtual node, and current node is its parent, then we're done
if (endTiny != null && endTiny._idxParent != 0 && idx == idxEnd && page == pageEnd)
return false;
// Get all virtual (collapsed) and physical text nodes which follow the current node
if (!XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd))
return false;
if (page[idx].NodeType == XPathNodeType.Element)
{
// Virtualize collapsed text nodes
Debug.Assert(page[idx].HasCollapsedText);
_idxCurrent = page[idx].Document.GetCollapsedTextNode(out _pageCurrent);
_pageParent = page;
_idxParent = idx;
}
else
{
// Physical text node
Debug.Assert(page[idx].IsText);
_pageCurrent = page;
_idxCurrent = idx;
_pageParent = null;
_idxParent = 0;
}
return true;
}
}
// Get node on which scan ends (null if rest of document should be scanned, parent + 1 if positioned on virtual node)
idxEnd = GetFollowingEnd(endTiny, false, out pageEnd);
// If this navigator is positioned on a virtual node, then compute following of parent
if (_idxParent != 0)
{
if (!XPathNodeHelper.GetContentFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, type))
return false;
_pageCurrent = _pageParent;
_idxCurrent = _idxParent;
_pageParent = null;
_idxParent = 0;
return true;
}
return XPathNodeHelper.GetContentFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, type);
}
/// <summary>
/// Return an iterator that ranges over all children of the current node that match the specified XPathNodeType.
/// </summary>
public override XPathNodeIterator SelectChildren(XPathNodeType type)
{
return new XPathDocumentKindChildIterator(this, type);
}
/// <summary>
/// Return an iterator that ranges over all children of the current node that match the specified QName.
/// </summary>
public override XPathNodeIterator SelectChildren(string name, string namespaceURI)
{
// If local name is wildcard, then call XPathNavigator.SelectChildren
if (name == null || name.Length == 0)
return base.SelectChildren(name, namespaceURI);
return new XPathDocumentElementChildIterator(this, name, namespaceURI);
}
/// <summary>
/// Return an iterator that ranges over all descendants of the current node that match the specified
/// XPathNodeType. If matchSelf is true, then also perform the match on the current node.
/// </summary>
public override XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf)
{
return new XPathDocumentKindDescendantIterator(this, type, matchSelf);
}
/// <summary>
/// Return an iterator that ranges over all descendants of the current node that match the specified
/// QName. If matchSelf is true, then also perform the match on the current node.
/// </summary>
public override XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf)
{
// If local name is wildcard, then call XPathNavigator.SelectDescendants
if (name == null || name.Length == 0)
return base.SelectDescendants(name, namespaceURI, matchSelf);
return new XPathDocumentElementDescendantIterator(this, name, namespaceURI, matchSelf);
}
/// <summary>
/// Returns:
/// XmlNodeOrder.Unknown -- This navigator and the "other" navigator are not of the same type, or the
/// navigator's are not positioned on nodes in the same document.
/// XmlNodeOrder.Before -- This navigator's current node is before the "other" navigator's current node
/// in document order.
/// XmlNodeOrder.After -- This navigator's current node is after the "other" navigator's current node
/// in document order.
/// XmlNodeOrder.Same -- This navigator is positioned on the same node as the "other" navigator.
/// </summary>
public override XmlNodeOrder ComparePosition(XPathNavigator other)
{
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null)
{
XPathDocument thisDoc = _pageCurrent[_idxCurrent].Document;
XPathDocument thatDoc = that._pageCurrent[that._idxCurrent].Document;
if ((object)thisDoc == (object)thatDoc)
{
int locThis = GetPrimaryLocation();
int locThat = that.GetPrimaryLocation();
if (locThis == locThat)
{
locThis = GetSecondaryLocation();
locThat = that.GetSecondaryLocation();
if (locThis == locThat)
return XmlNodeOrder.Same;
}
return (locThis < locThat) ? XmlNodeOrder.Before : XmlNodeOrder.After;
}
}
return XmlNodeOrder.Unknown;
}
/// <summary>
/// Return true if the "other" navigator's current node is a descendant of this navigator's current node.
/// </summary>
public override bool IsDescendant(XPathNavigator other)
{
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null)
{
XPathNode[] pageThat;
int idxThat;
// If that current node's parent is virtualized, then start with the virtual parent
if (that._idxParent != 0)
{
pageThat = that._pageParent;
idxThat = that._idxParent;
}
else
{
idxThat = that._pageCurrent[that._idxCurrent].GetParent(out pageThat);
}
while (idxThat != 0)
{
if (idxThat == _idxCurrent && pageThat == _pageCurrent)
return true;
idxThat = pageThat[idxThat].GetParent(out pageThat);
}
}
return false;
}
/// <summary>
/// Construct a primary location for this navigator. The location is an integer that can be
/// easily compared with other locations in the same document in order to determine the relative
/// document order of two nodes. If two locations compare equal, then secondary locations should
/// be compared.
/// </summary>
private int GetPrimaryLocation()
{
// Is the current node virtualized?
if (_idxParent == 0)
{
// No, so primary location should be derived from current node
return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent);
}
// Yes, so primary location should be derived from parent node
return XPathNodeHelper.GetLocation(_pageParent, _idxParent);
}
/// <summary>
/// Construct a secondary location for this navigator. This location should only be used if
/// primary locations previously compared equal.
/// </summary>
private int GetSecondaryLocation()
{
// Is the current node virtualized?
if (_idxParent == 0)
{
// No, so secondary location is int.MinValue (always first)
return int.MinValue;
}
// Yes, so secondary location should be derived from current node
// This happens with attributes nodes, namespace nodes, collapsed text nodes, and atomic values
switch (_pageCurrent[_idxCurrent].NodeType)
{
case XPathNodeType.Namespace:
// Namespace nodes come first (make location negative, but greater than int.MinValue)
return int.MinValue + 1 + XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent);
case XPathNodeType.Attribute:
// Attribute nodes come next (location is always positive)
return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent);
default:
// Collapsed text nodes are always last
return int.MaxValue;
}
}
/// <summary>
/// Create a unique id for the current node. This is used by the generate-id() function.
/// </summary>
internal override string UniqueId
{
get
{
// 32-bit integer is split into 5-bit groups, the maximum number of groups is 7
char[] buf = new char[1 + 7 + 1 + 7];
int idx = 0;
int loc;
// Ensure distinguishing attributes, namespaces and child nodes
buf[idx++] = NodeTypeLetter[(int)_pageCurrent[_idxCurrent].NodeType];
// If the current node is virtualized, code its parent
if (_idxParent != 0)
{
loc = (_pageParent[0].PageInfo.PageNumber - 1) << 16 | (_idxParent - 1);
do
{
buf[idx++] = UniqueIdTbl[loc & 0x1f];
loc >>= 5;
} while (loc != 0);
buf[idx++] = '0';
}
// Code the node itself
loc = (_pageCurrent[0].PageInfo.PageNumber - 1) << 16 | (_idxCurrent - 1);
do
{
buf[idx++] = UniqueIdTbl[loc & 0x1f];
loc >>= 5;
} while (loc != 0);
return new string(buf, 0, idx);
}
}
public override object UnderlyingObject
{
get
{
// Since we don't have any underlying PUBLIC object
// the best one we can return is a clone of the navigator.
// Note that it should be a clone as the user might Move the returned navigator
// around and thus cause unexpected behavior of the caller of this class (For example the validator)
return this.Clone();
}
}
//-----------------------------------------------
// IXmlLineInfo
//-----------------------------------------------
/// <summary>
/// Return true if line number information is recorded in the cache.
/// </summary>
public bool HasLineInfo()
{
return _pageCurrent[_idxCurrent].Document.HasLineInfo;
}
/// <summary>
/// Return the source line number of the current node.
/// </summary>
public int LineNumber
{
get
{
// If the current node is a collapsed text node, then return parent element's line number
if (_idxParent != 0 && NodeType == XPathNodeType.Text)
return _pageParent[_idxParent].LineNumber;
return _pageCurrent[_idxCurrent].LineNumber;
}
}
/// <summary>
/// Return the source line position of the current node.
/// </summary>
public int LinePosition
{
get
{
// If the current node is a collapsed text node, then get position from parent element
if (_idxParent != 0 && NodeType == XPathNodeType.Text)
return _pageParent[_idxParent].CollapsedLinePosition;
return _pageCurrent[_idxCurrent].LinePosition;
}
}
//-----------------------------------------------
// Helper methods
//-----------------------------------------------
/// <summary>
/// Get hashcode based on current position of the navigator.
/// </summary>
public int GetPositionHashCode()
{
return _idxCurrent ^ _idxParent;
}
/// <summary>
/// Return true if navigator is positioned to an element having the specified name.
/// </summary>
public bool IsElementMatch(string localName, string namespaceURI)
{
if ((object)localName != (object)_atomizedLocalName)
_atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
// Cannot be an element if parent is stored
if (_idxParent != 0)
return false;
return _pageCurrent[_idxCurrent].ElementMatch(_atomizedLocalName, namespaceURI);
}
/// <summary>
/// Return true if navigator is positioned to a node of the specified kind. Whitespace/SignificantWhitespace/Text are
/// all treated the same (i.e. they all match each other).
/// </summary>
public bool IsKindMatch(XPathNodeType typ)
{
return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & XPathNavigatorEx.GetKindMask(typ)) != 0);
}
/// <summary>
/// "end" is positioned on a node which terminates a following scan. Return the page and index of "end" if it
/// is positioned to a non-virtual node. If "end" is positioned to a virtual node:
/// 1. If useParentOfVirtual is true, then return the page and index of the virtual node's parent
/// 2. If useParentOfVirtual is false, then return the page and index of the virtual node's parent + 1.
/// </summary>
private int GetFollowingEnd(XPathDocumentNavigator end, bool useParentOfVirtual, out XPathNode[] pageEnd)
{
// If ending navigator is positioned to a node in another document, then return null
if (end != null && _pageCurrent[_idxCurrent].Document == end._pageCurrent[end._idxCurrent].Document)
{
// If the ending navigator is not positioned on a virtual node, then return its current node
if (end._idxParent == 0)
{
pageEnd = end._pageCurrent;
return end._idxCurrent;
}
// If the ending navigator is positioned on an attribute, namespace, or virtual text node, then use the
// next physical node instead, as the results will be the same.
pageEnd = end._pageParent;
return (useParentOfVirtual) ? end._idxParent : end._idxParent + 1;
}
// No following, so set pageEnd to null and return an index of 0
pageEnd = null;
return 0;
}
}
}
| 40.090211 | 141 | 0.535046 | [
"MIT"
] | OceanYan/corefx | src/System.Xml.XPath/src/System/Xml/Cache/XPathDocumentNavigator.cs | 41,774 | C# |
namespace Fairweather.Service
{
public static class ReadWrite
{
class Proxy<TKey, TValue> : IRead<TKey, TValue>
{
readonly IReadWrite<TKey, TValue> rd_inner;
public TValue this[TKey index] {
get { return rd_inner[index]; }
}
public Proxy(IReadWrite<TKey, TValue> inner) {
rd_inner = inner;
}
public bool Contains(TKey key) {
return rd_inner.Contains(key);
}
}
public static IRead<TKey, TValue>
As_Readonly<TKey, TValue>(this IReadWrite<TKey, TValue> irw) {
return new Proxy<TKey, TValue>(irw);
}
}
} | 24.666667 | 71 | 0.502703 | [
"MIT"
] | staafl/dotnet-bclext | to-integrate/libcs_staaflutil/Utils/Read_Write_Service.cs | 742 | C# |
using System.Threading.Tasks;
namespace GMSFramework.Authentication.External
{
public interface IExternalAuthManager
{
Task<bool> IsValidUser(string provider, string providerKey, string providerAccessCode);
Task<ExternalAuthUserInfo> GetUserInfo(string provider, string accessCode);
}
}
| 26.5 | 95 | 0.761006 | [
"MIT"
] | alex-zak/GMSFramework | aspnet-core/src/GMSFramework.Web.Core/Authentication/External/IExternalAuthManager.cs | 320 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DIDemo.ExampleClasses;
using DIDemo.Services;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Mvc;
using Autofac;
using Autofac.Extensions.DependencyInjection;
namespace DIDemo
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient<IDemoService, DemoService>();
services.AddTransient<ITransientDependencyExample, TransientDependencyExample>();
services.AddScoped<IScopedDependencyExample, ScopedDependencyExample>();
services.AddSingleton<ISingletonDependencyExample, SingletonDependencyExample>();
services.AddInstance<IInstanceDependencyExample>(new InstanceDependencyExample());
}
/**
* Uncomment this method to use Autofac instead of the default dependency container.
* /
/*
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<DemoService>().As<IDemoService>().InstancePerDependency();
containerBuilder.RegisterType<TransientDependencyExample>().As<ITransientDependencyExample>().InstancePerDependency();
containerBuilder.RegisterType<ScopedDependencyExample>().As<IScopedDependencyExample>().InstancePerLifetimeScope();
containerBuilder.RegisterType<SingletonDependencyExample>().As<ISingletonDependencyExample>().SingleInstance();
containerBuilder.RegisterInstance(new InstanceDependencyExample()).As<IInstanceDependencyExample>();
containerBuilder.Populate(services);
var container = containerBuilder.Build();
return container.Resolve<IServiceProvider>();
}
*/
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| 37.864583 | 130 | 0.651719 | [
"MIT"
] | Luminis-Arnhem/MVC6DIDemo | src/MyFirstMvc6App/Startup.cs | 3,637 | C# |
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2008 the Open Toolkit library, except where noted.
//
// 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 System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using JetBrains.Annotations;
using Love;
using SysVector3 = System.Numerics.Vector3;
using SysVector4 = System.Numerics.Vector4;
#if NETCOREAPP
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
namespace OpenNefia.Core.Maths
{
/// <summary>
/// Represents a color with 4 floating-point components (R, G, B, A).
/// </summary>
[Serializable]
public struct Color : IEquatable<Color>
{
/// <summary>
/// The red component of this Color4 structure.
/// </summary>
public float R;
/// <summary>
/// The green component of this Color4 structure.
/// </summary>
public float G;
/// <summary>
/// The blue component of this Color4 structure.
/// </summary>
public float B;
/// <summary>
/// The alpha component of this Color4 structure.
/// </summary>
public float A;
public readonly byte RByte => (byte) (R * byte.MaxValue);
public readonly byte GByte => (byte) (G * byte.MaxValue);
public readonly byte BByte => (byte) (B * byte.MaxValue);
public readonly byte AByte => (byte) (A * byte.MaxValue);
/// <summary>
/// Constructs a new Color4 structure from the specified components.
/// </summary>
/// <param name="r">The red component of the new Color4 structure.</param>
/// <param name="g">The green component of the new Color4 structure.</param>
/// <param name="b">The blue component of the new Color4 structure.</param>
/// <param name="a">The alpha component of the new Color4 structure.</param>
public Color(float r, float g, float b, float a = 1)
{
R = r;
G = g;
B = b;
A = a;
}
/// <summary>
/// Constructs a new Color4 structure from the specified components.
/// </summary>
/// <param name="r">The red component of the new Color4 structure.</param>
/// <param name="g">The green component of the new Color4 structure.</param>
/// <param name="b">The blue component of the new Color4 structure.</param>
/// <param name="a">The alpha component of the new Color4 structure.</param>
public Color(byte r, byte g, byte b, byte a = 255)
{
R = r / (float) byte.MaxValue;
G = g / (float) byte.MaxValue;
B = b / (float) byte.MaxValue;
A = a / (float) byte.MaxValue;
}
/// <summary>
/// Converts this color to an integer representation with 8 bits per channel.
/// </summary>
/// <returns>A <see cref="System.Int32" /> that represents this instance.</returns>
/// <remarks>
/// This method is intended only for compatibility with System.Drawing. It compresses the color into 8 bits per
/// channel, which means color information is lost.
/// </remarks>
public readonly int ToArgb()
{
var value =
((uint) (A * byte.MaxValue) << 24) |
((uint) (R * byte.MaxValue) << 16) |
((uint) (G * byte.MaxValue) << 8) |
(uint) (B * byte.MaxValue);
return unchecked((int) value);
}
/// <summary>
/// Compares the specified Color4 structures for equality.
/// </summary>
/// <param name="left">The left-hand side of the comparison.</param>
/// <param name="right">The right-hand side of the comparison.</param>
/// <returns>True if left is equal to right; false otherwise.</returns>
public static bool operator ==(Color left, Color right)
{
return left.Equals(right);
}
/// <summary>
/// Compares the specified Color4 structures for inequality.
/// </summary>
/// <param name="left">The left-hand side of the comparison.</param>
/// <param name="right">The right-hand side of the comparison.</param>
/// <returns>True if left is not equal to right; false otherwise.</returns>
public static bool operator !=(Color left, Color right)
{
return !left.Equals(right);
}
/// <summary>
/// Converts the specified System.Drawing.Color to a Color4 structure.
/// </summary>
/// <param name="color">The System.Drawing.Color to convert.</param>
/// <returns>A new Color4 structure containing the converted components.</returns>
public static implicit operator Color(System.Drawing.Color color)
{
return new(color.R, color.G, color.B, color.A);
}
public static implicit operator Color((float r, float g, float b, float a) tuple)
{
return new(tuple.r, tuple.g, tuple.b, tuple.a);
}
public static implicit operator Color((float r, float g, float b) tuple)
{
return new(tuple.r, tuple.g, tuple.b);
}
public static implicit operator Color(Love.Color color)
{
return new(color.Rf, color.Gf, color.Bf, color.Af);
}
public static implicit operator Love.Color(Color color)
{
return new(color.R, color.G, color.B, color.A);
}
public readonly void Deconstruct(out float r, out float g, out float b, out float a)
{
r = R;
g = G;
b = B;
a = A;
}
public readonly void Deconstruct(out float r, out float g, out float b)
{
r = R;
g = G;
b = B;
}
/// <summary>
/// Converts the specified Color4 to a System.Drawing.Color structure.
/// </summary>
/// <param name="color">The Color4 to convert.</param>
/// <returns>A new System.Drawing.Color structure containing the converted components.</returns>
public static explicit operator System.Drawing.Color(Color color)
{
return System.Drawing.Color.FromArgb(
(int) (color.A * byte.MaxValue),
(int) (color.R * byte.MaxValue),
(int) (color.G * byte.MaxValue),
(int) (color.B * byte.MaxValue));
}
public static Color FromName(string colorname)
{
return DefaultColors[colorname.ToLower()];
}
public static bool TryFromName(string colorName, out Color color)
{
return DefaultColors.TryGetValue(colorName.ToLower(), out color);
}
public static IEnumerable<KeyValuePair<string, Color>> GetAllDefaultColors()
{
return DefaultColors;
}
/// <summary>
/// Compares whether this Color4 structure is equal to the specified object.
/// </summary>
/// <param name="obj">An object to compare to.</param>
/// <returns>True obj is a Color4 structure with the same components as this Color4; false otherwise.</returns>
public override readonly bool Equals(object? obj)
{
if (!(obj is Color))
return false;
return Equals((Color) obj);
}
/// <summary>
/// Calculates the hash code for this Color4 structure.
/// </summary>
/// <returns>A System.Int32 containing the hash code of this Color4 structure.</returns>
public override readonly int GetHashCode()
{
return ToArgb();
}
/// <summary>
/// Creates a System.String that describes this Color4 structure.
/// </summary>
/// <returns>A System.String that describes this Color4 structure.</returns>
public override readonly string ToString()
{
return $"{{(R, G, B, A) = ({R}, {G}, {B}, {A})}}";
}
public readonly Color WithRed(float newR)
{
return new(newR, G, B, A);
}
public readonly Color WithGreen(float newG)
{
return new(R, newG, B, A);
}
public readonly Color WithBlue(float newB)
{
return new(R, G, newB, A);
}
public readonly Color WithAlpha(float newA)
{
return new(R, G, B, newA);
}
public readonly Color WithRed(byte newR)
{
return new((float) newR / byte.MaxValue, G, B, A);
}
public readonly Color WithGreen(byte newG)
{
return new(R, (float) newG / byte.MaxValue, B, A);
}
public readonly Color WithBlue(byte newB)
{
return new(R, G, (float) newB / byte.MaxValue, A);
}
public readonly Color WithAlpha(byte newA)
{
return new(R, G, B, (float) newA / byte.MaxValue);
}
public Color Lighten(float mult)
{
var (h, s, l, a) = ToHsl(this);
return FromHsl(new(h, s, l*mult, a));
}
/// <summary>
/// Converts sRGB color values to linear RGB color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// </returns>
/// <param name="srgb">
/// Color value to convert in sRGB.
/// </param>
public static Color FromSrgb(Color srgb)
{
float r, g, b;
#if NETCOREAPP
if (srgb.R <= 0.04045f)
r = srgb.R / 12.92f;
else
r = MathF.Pow((srgb.R + 0.055f) / (1.0f + 0.055f), 2.4f);
if (srgb.G <= 0.04045f)
g = srgb.G / 12.92f;
else
g = MathF.Pow((srgb.G + 0.055f) / (1.0f + 0.055f), 2.4f);
if (srgb.B <= 0.04045f)
b = srgb.B / 12.92f;
else
b = MathF.Pow((srgb.B + 0.055f) / (1.0f + 0.055f), 2.4f);
#else
if (srgb.R <= 0.04045f)
r = srgb.R / 12.92f;
else
r = (float) Math.Pow((srgb.R + 0.055f) / (1.0f + 0.055f), 2.4f);
if (srgb.G <= 0.04045f)
g = srgb.G / 12.92f;
else
g = (float) Math.Pow((srgb.G + 0.055f) / (1.0f + 0.055f), 2.4f);
if (srgb.B <= 0.04045f)
b = srgb.B / 12.92f;
else
b = (float) Math.Pow((srgb.B + 0.055f) / (1.0f + 0.055f), 2.4f);
#endif
return new Color(r, g, b, srgb.A);
}
/// <summary>
/// Converts linear RGB color values to sRGB color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// </returns>
/// <param name="rgb">Color value to convert.</param>
public static Color ToSrgb(Color rgb)
{
float r, g, b;
#if NETCOREAPP
if (rgb.R <= 0.0031308)
r = 12.92f * rgb.R;
else
r = (1.0f + 0.055f) * MathF.Pow(rgb.R, 1.0f / 2.4f) - 0.055f;
if (rgb.G <= 0.0031308)
g = 12.92f * rgb.G;
else
g = (1.0f + 0.055f) * MathF.Pow(rgb.G, 1.0f / 2.4f) - 0.055f;
if (rgb.B <= 0.0031308)
b = 12.92f * rgb.B;
else
b = (1.0f + 0.055f) * MathF.Pow(rgb.B, 1.0f / 2.4f) - 0.055f;
#else
if (rgb.R <= 0.0031308)
r = 12.92f * rgb.R;
else
r = (1.0f + 0.055f) * (float) Math.Pow(rgb.R, 1.0f / 2.4f) - 0.055f;
if (rgb.G <= 0.0031308)
g = 12.92f * rgb.G;
else
g = (1.0f + 0.055f) * (float) Math.Pow(rgb.G, 1.0f / 2.4f) - 0.055f;
if (rgb.B <= 0.0031308)
b = 12.92f * rgb.B;
else
b = (1.0f + 0.055f) * (float) Math.Pow(rgb.B, 1.0f / 2.4f) - 0.055f;
#endif
return new Color(r, g, b, rgb.A);
}
/// <summary>
/// Converts HSL color values to RGB color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// </returns>
/// <param name="hsl">
/// Color value to convert in hue, saturation, lightness (HSL).
/// The X element is Hue (H), the Y element is Saturation (S), the Z element is Lightness (L), and the W element is
/// Alpha (which is copied to the output's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </param>
public static Color FromHsl(Vector4 hsl)
{
var hue = hsl.X * 360.0f;
var saturation = hsl.Y;
var lightness = hsl.Z;
var c = (1.0f - MathF.Abs(2.0f * lightness - 1.0f)) * saturation;
var h = hue / 60.0f;
var X = c * (1.0f - MathF.Abs(h % 2.0f - 1.0f));
float r, g, b;
if (0.0f <= h && h < 1.0f)
{
r = c;
g = X;
b = 0.0f;
}
else if (1.0f <= h && h < 2.0f)
{
r = X;
g = c;
b = 0.0f;
}
else if (2.0f <= h && h < 3.0f)
{
r = 0.0f;
g = c;
b = X;
}
else if (3.0f <= h && h < 4.0f)
{
r = 0.0f;
g = X;
b = c;
}
else if (4.0f <= h && h < 5.0f)
{
r = X;
g = 0.0f;
b = c;
}
else if (5.0f <= h && h < 6.0f)
{
r = c;
g = 0.0f;
b = X;
}
else
{
r = 0.0f;
g = 0.0f;
b = 0.0f;
}
var m = lightness - c / 2.0f;
return new Color(r + m, g + m, b + m, hsl.W);
}
/// <summary>
/// Converts RGB color values to HSL color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// The X element is Hue (H), the Y element is Saturation (S), the Z element is Lightness (L), and the W element is
/// Alpha (a copy of the input's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </returns>
/// <param name="rgb">Color value to convert.</param>
public static Vector4 ToHsl(Color rgb)
{
var max = MathF.Max(rgb.R, MathF.Max(rgb.G, rgb.B));
var min = MathF.Min(rgb.R, MathF.Min(rgb.G, rgb.B));
var c = max - min;
var h = 0.0f;
if (max == rgb.R)
h = (rgb.G - rgb.B) / c;
else if (max == rgb.G)
h = (rgb.B - rgb.R) / c + 2.0f;
else if (max == rgb.B)
h = (rgb.R - rgb.G) / c + 4.0f;
var hue = h / 6.0f;
if (hue < 0.0f)
hue += 1.0f;
var lightness = (max + min) / 2.0f;
var saturation = 0.0f;
if (0.0f != lightness && lightness != 1.0f)
saturation = c / (1.0f - MathF.Abs(2.0f * lightness - 1.0f));
return new Vector4(hue, saturation, lightness, rgb.A);
}
/// <summary>
/// Converts HSV color values to RGB color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// </returns>
/// <param name="hsv">
/// Color value to convert in hue, saturation, value (HSV).
/// The X element is Hue (H), the Y element is Saturation (S), the Z element is Value (V), and the W element is Alpha
/// (which is copied to the output's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </param>
public static Color FromHsv(Vector4 hsv)
{
var hue = hsv.X * 360.0f;
var saturation = hsv.Y;
var value = hsv.Z;
var c = value * saturation;
var h = hue / 60.0f;
var x = c * (1.0f - MathF.Abs(h % 2.0f - 1.0f));
float r, g, b;
if (0.0f <= h && h < 1.0f)
{
r = c;
g = x;
b = 0.0f;
}
else if (1.0f <= h && h < 2.0f)
{
r = x;
g = c;
b = 0.0f;
}
else if (2.0f <= h && h < 3.0f)
{
r = 0.0f;
g = c;
b = x;
}
else if (3.0f <= h && h < 4.0f)
{
r = 0.0f;
g = x;
b = c;
}
else if (4.0f <= h && h < 5.0f)
{
r = x;
g = 0.0f;
b = c;
}
else if (5.0f <= h && h < 6.0f)
{
r = c;
g = 0.0f;
b = x;
}
else
{
r = 0.0f;
g = 0.0f;
b = 0.0f;
}
var m = value - c;
return new Color(r + m, g + m, b + m, hsv.W);
}
/// <summary>
/// Converts RGB color values to HSV color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// The X element is Hue (H), the Y element is Saturation (S), the Z element is Value (V), and the W element is Alpha
/// (a copy of the input's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </returns>
/// <param name="rgb">Color value to convert.</param>
public static Vector4 ToHsv(Color rgb)
{
var max = MathF.Max(rgb.R, MathF.Max(rgb.G, rgb.B));
var min = MathF.Min(rgb.R, MathF.Min(rgb.G, rgb.B));
var c = max - min;
var h = 0.0f;
if (max == rgb.R)
h = (rgb.G - rgb.B) / c % 6.0f;
else if (max == rgb.G)
h = (rgb.B - rgb.R) / c + 2.0f;
else if (max == rgb.B)
h = (rgb.R - rgb.G) / c + 4.0f;
var hue = h * 60.0f / 360.0f;
var saturation = 0.0f;
if (0.0f != max)
saturation = c / max;
return new Vector4(hue, saturation, max, rgb.A);
}
/// <summary>
/// Converts XYZ color values to RGB color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// </returns>
/// <param name="xyz">
/// Color value to convert with the trisimulus values of X, Y, and Z in the corresponding element, and the W element
/// with Alpha (which is copied to the output's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </param>
/// <remarks>Uses the CIE XYZ colorspace.</remarks>
public static Color FromXyz(Vector4 xyz)
{
var r = 0.41847f * xyz.X + -0.15866f * xyz.Y + -0.082835f * xyz.Z;
var g = -0.091169f * xyz.X + 0.25243f * xyz.Y + 0.015708f * xyz.Z;
var b = 0.00092090f * xyz.X + -0.0025498f * xyz.Y + 0.17860f * xyz.Z;
return new Color(r, g, b, xyz.W);
}
/// <summary>
/// Converts RGB color values to XYZ color values.
/// </summary>
/// <returns>
/// Returns the converted color value with the trisimulus values of X, Y, and Z in the corresponding element, and the W
/// element with Alpha (a copy of the input's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </returns>
/// <param name="rgb">Color value to convert.</param>
/// <remarks>Uses the CIE XYZ colorspace.</remarks>
public static Vector4 ToXyz(Color rgb)
{
var x = (0.49f * rgb.R + 0.31f * rgb.G + 0.20f * rgb.B) / 0.17697f;
var y = (0.17697f * rgb.R + 0.81240f * rgb.G + 0.01063f * rgb.B) / 0.17697f;
var z = (0.00f * rgb.R + 0.01f * rgb.G + 0.99f * rgb.B) / 0.17697f;
return new Vector4(x, y, z, rgb.A);
}
/// <summary>
/// Converts YCbCr color values to RGB color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// </returns>
/// <param name="ycbcr">
/// Color value to convert in Luma-Chrominance (YCbCr) aka YUV.
/// The X element contains Luma (Y, 0.0 to 1.0), the Y element contains Blue-difference chroma (U, -0.5 to 0.5), the Z
/// element contains the Red-difference chroma (V, -0.5 to 0.5), and the W element contains the Alpha (which is copied
/// to the output's Alpha value).
/// </param>
/// <remarks>Converts using ITU-R BT.601/CCIR 601 W(r) = 0.299 W(b) = 0.114 U(max) = 0.436 V(max) = 0.615.</remarks>
public static Color FromYcbcr(Vector4 ycbcr)
{
var r = 1.0f * ycbcr.X + 0.0f * ycbcr.Y + 1.402f * ycbcr.Z;
var g = 1.0f * ycbcr.X + -0.344136f * ycbcr.Y + -0.714136f * ycbcr.Z;
var b = 1.0f * ycbcr.X + 1.772f * ycbcr.Y + 0.0f * ycbcr.Z;
return new Color(r, g, b, ycbcr.W);
}
/// <summary>
/// Converts RGB color values to YUV color values.
/// </summary>
/// <returns>
/// Returns the converted color value in Luma-Chrominance (YCbCr) aka YUV.
/// The X element contains Luma (Y, 0.0 to 1.0), the Y element contains Blue-difference chroma (U, -0.5 to 0.5), the Z
/// element contains the Red-difference chroma (V, -0.5 to 0.5), and the W element contains the Alpha (a copy of the
/// input's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </returns>
/// <param name="rgb">Color value to convert.</param>
/// <remarks>Converts using ITU-R BT.601/CCIR 601 W(r) = 0.299 W(b) = 0.114 U(max) = 0.436 V(max) = 0.615.</remarks>
public static Vector4 ToYcbcr(Color rgb)
{
var y = 0.299f * rgb.R + 0.587f * rgb.G + 0.114f * rgb.B;
var u = -0.168736f * rgb.R + -0.331264f * rgb.G + 0.5f * rgb.B;
var v = 0.5f * rgb.R + -0.418688f * rgb.G + -0.081312f * rgb.B;
return new Vector4(y, u, v, rgb.A);
}
/// <summary>
/// Converts HCY color values to RGB color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// </returns>
/// <param name="hcy">
/// Color value to convert in hue, chroma, luminance (HCY).
/// The X element is Hue (H), the Y element is Chroma (C), the Z element is luminance (Y), and the W element is Alpha
/// (which is copied to the output's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </param>
public static Color FromHcy(Vector4 hcy)
{
var hue = hcy.X * 360.0f;
var c = hcy.Y;
var luminance = hcy.Z;
var h = hue / 60.0f;
var x = c * (1.0f - MathF.Abs(h % 2.0f - 1.0f));
float r, g, b;
if (0.0f <= h && h < 1.0f)
{
r = c;
g = x;
b = 0.0f;
}
else if (1.0f <= h && h < 2.0f)
{
r = x;
g = c;
b = 0.0f;
}
else if (2.0f <= h && h < 3.0f)
{
r = 0.0f;
g = c;
b = x;
}
else if (3.0f <= h && h < 4.0f)
{
r = 0.0f;
g = x;
b = c;
}
else if (4.0f <= h && h < 5.0f)
{
r = x;
g = 0.0f;
b = c;
}
else if (5.0f <= h && h < 6.0f)
{
r = c;
g = 0.0f;
b = x;
}
else
{
r = 0.0f;
g = 0.0f;
b = 0.0f;
}
var m = luminance - (0.30f * r + 0.59f * g + 0.11f * b);
return new Color(r + m, g + m, b + m, hcy.W);
}
/// <summary>
/// Converts RGB color values to HCY color values.
/// </summary>
/// <returns>
/// Returns the converted color value.
/// The X element is Hue (H), the Y element is Chroma (C), the Z element is luminance (Y), and the W element is Alpha
/// (a copy of the input's Alpha value).
/// Each has a range of 0.0 to 1.0.
/// </returns>
/// <param name="rgb">Color value to convert.</param>
public static Vector4 ToHcy(Color rgb)
{
var max = MathF.Max(rgb.R, MathF.Max(rgb.G, rgb.B));
var min = MathF.Min(rgb.R, MathF.Min(rgb.G, rgb.B));
var c = max - min;
var h = 0.0f;
if (max == rgb.R)
h = (rgb.G - rgb.B) / c % 6.0f;
else if (max == rgb.G)
h = (rgb.B - rgb.R) / c + 2.0f;
else if (max == rgb.B)
h = (rgb.R - rgb.G) / c + 4.0f;
var hue = h * 60.0f / 360.0f;
var luminance = 0.30f * rgb.R + 0.59f * rgb.G + 0.11f * rgb.B;
return new Vector4(hue, c, luminance, rgb.A);
}
public static Vector4 ToCmyk(Color rgb)
{
var (r, g, b) = rgb;
var k = 1 - MathF.Max(r, MathF.Max(g, b));
var c = (1 - r - k) / (1 - k);
var m = (1 - g - k) / (1 - k);
var y = (1 - b - k) / (1 - k);
return new(c, m, y, k);
}
public static Color FromCmyk(Vector4 cmyk)
{
// TODO
var c = cmyk.X;
var m = cmyk.Y;
var y = cmyk.Z;
var k = cmyk.W;
var r = (1 - c) * (1 - k);
var g = (1 - m) * (1 - k);
var b = (1 - y) * (1 - k);
return new(r, g, b);
}
/// <summary>
/// Interpolate two colors with a lambda, AKA returning the two colors combined with a ratio of
/// <paramref name="λ" />.
/// </summary>
/// <param name="α"></param>
/// <param name="β"></param>
/// <param name="λ">
/// A value ranging from 0-1. The higher the value the more is taken from <paramref name="β" />,
/// with 0.5 being 50% of both colors, 0.25 being 25% of <paramref name="β" /> and 75%
/// <paramref name="α" />.
/// </param>
#if NETCOREAPP
public static Color InterpolateBetween(Color α, Color β, float λ)
{
if (Sse.IsSupported && Fma.IsSupported)
{
var vecA = Unsafe.As<Color, Vector128<float>>(ref α);
var vecB = Unsafe.As<Color, Vector128<float>>(ref β);
vecB = Fma.MultiplyAdd(Sse.Subtract(vecB, vecA), Vector128.Create(λ), vecA);
return Unsafe.As<Vector128<float>, Color>(ref vecB);
}
ref var svA = ref Unsafe.As<Color, SysVector4>(ref α);
ref var svB = ref Unsafe.As<Color, SysVector4>(ref β);
var res = SysVector4.Lerp(svA, svB, λ);
return Unsafe.As<SysVector4, Color>(ref res);
}
#else
public static Color InterpolateBetween(in Color α, in Color β, float λ)
{
return new Color(
(β.R - α.R) * λ + α.R,
(β.G - α.G) * λ + α.G,
(β.B - α.B) * λ + α.B,
(β.A - α.A) * λ + α.A
);
}
#endif
public static Color? TryFromHex(ReadOnlySpan<char> hexColor)
{
if (hexColor.Length <= 0 || hexColor[0] != '#') return null;
if (hexColor.Length == 9)
{
if (!byte.TryParse(hexColor[1..3], NumberStyles.HexNumber, null, out var r)) return null;
if (!byte.TryParse(hexColor[3..5], NumberStyles.HexNumber, null, out var g)) return null;
if (!byte.TryParse(hexColor[5..7], NumberStyles.HexNumber, null, out var b)) return null;
if (!byte.TryParse(hexColor[7..9], NumberStyles.HexNumber, null, out var a)) return null;
return new Color(r, g, b, a);
}
if (hexColor.Length == 7)
{
if (!byte.TryParse(hexColor[1..3], NumberStyles.HexNumber, null, out var r)) return null;
if (!byte.TryParse(hexColor[3..5], NumberStyles.HexNumber, null, out var g)) return null;
if (!byte.TryParse(hexColor[5..7], NumberStyles.HexNumber, null, out var b)) return null;
return new Color(r, g, b);
}
static bool ParseDup(char chr, out byte value)
{
Span<char> buf = stackalloc char[2];
buf[0] = chr;
buf[1] = chr;
return byte.TryParse(buf, NumberStyles.HexNumber, null, out value);
}
if (hexColor.Length == 5)
{
if (!ParseDup(hexColor[1], out var rByte)) return null;
if (!ParseDup(hexColor[2], out var gByte)) return null;
if (!ParseDup(hexColor[3], out var bByte)) return null;
if (!ParseDup(hexColor[4], out var aByte)) return null;
return new Color(rByte, gByte, bByte, aByte);
}
if (hexColor.Length == 4)
{
if (!ParseDup(hexColor[1], out var rByte)) return null;
if (!ParseDup(hexColor[2], out var gByte)) return null;
if (!ParseDup(hexColor[3], out var bByte)) return null;
return new Color(rByte, gByte, bByte);
}
return null;
}
public static Color FromHex(ReadOnlySpan<char> hexColor, Color? fallback = null)
{
var color = TryFromHex(hexColor);
if (color.HasValue)
return color.Value;
if (fallback.HasValue)
return fallback.Value;
throw new ArgumentException("Invalid color code and no fallback provided.", nameof(hexColor));
}
public static Color FromXaml(string name)
{
var color = TryFromHex(name);
if (color != null)
return color.Value;
if (TryFromName(name, out var namedColor))
return namedColor;
throw new ArgumentException($"Invalid XAML color name: '{name}'");
}
public static Color Blend(Color dstColor, Color srcColor, BlendFactor dstFactor, BlendFactor srcFactor)
{
var dst = new SysVector3(dstColor.R, dstColor.G, dstColor.B);
var src = new SysVector3(srcColor.R, srcColor.G, srcColor.B);
var ret = new SysVector3();
switch (dstFactor)
{
case BlendFactor.Zero:
break;
case BlendFactor.One:
ret = dst;
break;
case BlendFactor.SrcColor:
ret = dst * src;
break;
case BlendFactor.OneMinusSrcColor:
ret = dst * (SysVector3.One - src);
break;
case BlendFactor.DstColor:
ret = dst * dst;
break;
case BlendFactor.OneMinusDstColor:
ret = dst * (SysVector3.One - dst);
break;
case BlendFactor.SrcAlpha:
ret = dst * srcColor.A;
break;
case BlendFactor.OneMinusSrcAlpha:
ret = dst * (1 - srcColor.A);
break;
case BlendFactor.DstAlpha:
ret = dst * dstColor.A;
break;
case BlendFactor.OneMinusDstAlpha:
ret = dst * (1 - dstColor.A);
break;
default:
throw new NotImplementedException();
}
switch (srcFactor)
{
case BlendFactor.Zero:
break;
case BlendFactor.One:
ret += src;
break;
case BlendFactor.SrcColor:
ret += src * src;
break;
case BlendFactor.OneMinusSrcColor:
ret += src * (SysVector3.One - src);
break;
case BlendFactor.DstColor:
ret += src * dst;
break;
case BlendFactor.OneMinusDstColor:
ret += src * (SysVector3.One - dst);
break;
case BlendFactor.SrcAlpha:
ret += src * srcColor.A;
break;
case BlendFactor.OneMinusSrcAlpha:
ret += src * (1 - srcColor.A);
break;
case BlendFactor.DstAlpha:
ret += src * dstColor.A;
break;
case BlendFactor.OneMinusDstAlpha:
ret += src * (1 - dstColor.A);
break;
default:
throw new NotImplementedException();
}
return new Color(ret.X, ret.Y, ret.Z, MathF.Min(1, dstColor.A + dstColor.A * srcColor.A));
}
/// <summary>
/// Component wise multiplication of two colors.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static Color operator *(Color a, Color b)
{
return new(a.R * b.R, a.G * b.G, a.B * b.B, a.A * b.A);
}
public readonly string ToHex()
{
var hexColor = 0;
hexColor += RByte << 24;
hexColor += GByte << 16;
hexColor += BByte << 8;
hexColor += AByte;
return $"#{hexColor:X8}";
}
public readonly string ToHexNoAlpha()
{
var hexColor = 0;
hexColor += RByte << 16;
hexColor += GByte << 8;
hexColor += BByte;
return $"#{hexColor:X6}";
}
/// <summary>
/// Compares whether this Color4 structure is equal to the specified Color4.
/// </summary>
/// <param name="other">The Color4 structure to compare to.</param>
/// <returns>True if both Color4 structures contain the same components; false otherwise.</returns>
public readonly bool Equals(Color other)
{
return
MathHelper.CloseToPercent(R, other.R) &&
MathHelper.CloseToPercent(G, other.G) &&
MathHelper.CloseToPercent(B, other.B) &&
MathHelper.CloseToPercent(A, other.A);
}
[PublicAPI]
public enum BlendFactor : byte
{
Zero,
One,
SrcColor,
OneMinusSrcColor,
DstColor,
OneMinusDstColor,
SrcAlpha,
OneMinusSrcAlpha,
DstAlpha,
OneMinusDstAlpha,
}
#region Static Colors
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 255, 255, 0).
/// </summary>
public static Color Transparent => new(255, 255, 255, 0);
/// <summary>
/// Gets the system color with (R, G, B, A) = (240, 248, 255, 255).
/// </summary>
public static Color AliceBlue => new(240, 248, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (250, 235, 215, 255).
/// </summary>
public static Color AntiqueWhite => new(250, 235, 215, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 255, 255, 255).
/// </summary>
public static Color Aqua => new(0, 255, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (127, 255, 212, 255).
/// </summary>
public static Color Aquamarine => new(127, 255, 212, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (240, 255, 255, 255).
/// </summary>
public static Color Azure => new(240, 255, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (245, 245, 220, 255).
/// </summary>
public static Color Beige => new(245, 245, 220, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 228, 196, 255).
/// </summary>
public static Color Bisque => new(255, 228, 196, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 0, 0, 255).
/// </summary>
public static Color Black => new(0, 0, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 235, 205, 255).
/// </summary>
public static Color BlanchedAlmond => new(255, 235, 205, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 0, 255, 255).
/// </summary>
public static Color Blue => new(0, 0, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (138, 43, 226, 255).
/// </summary>
public static Color BlueViolet => new(138, 43, 226, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (165, 42, 42, 255).
/// </summary>
public static Color Brown => new(165, 42, 42, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (222, 184, 135, 255).
/// </summary>
public static Color BurlyWood => new(222, 184, 135, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (95, 158, 160, 255).
/// </summary>
public static Color CadetBlue => new(95, 158, 160, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (127, 255, 0, 255).
/// </summary>
public static Color Chartreuse => new(127, 255, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (210, 105, 30, 255).
/// </summary>
public static Color Chocolate => new(210, 105, 30, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 127, 80, 255).
/// </summary>
public static Color Coral => new(255, 127, 80, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (100, 149, 237, 255).
/// </summary>
public static Color CornflowerBlue => new(100, 149, 237, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 248, 220, 255).
/// </summary>
public static Color Cornsilk => new(255, 248, 220, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (220, 20, 60, 255).
/// </summary>
public static Color Crimson => new(220, 20, 60, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 255, 255, 255).
/// </summary>
public static Color Cyan => new(0, 255, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 0, 139, 255).
/// </summary>
public static Color DarkBlue => new(0, 0, 139, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 139, 139, 255).
/// </summary>
public static Color DarkCyan => new(0, 139, 139, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (184, 134, 11, 255).
/// </summary>
public static Color DarkGoldenrod => new(184, 134, 11, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (169, 169, 169, 255).
/// </summary>
public static Color DarkGray => new(169, 169, 169, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 100, 0, 255).
/// </summary>
public static Color DarkGreen => new(0, 100, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (189, 183, 107, 255).
/// </summary>
public static Color DarkKhaki => new(189, 183, 107, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (139, 0, 139, 255).
/// </summary>
public static Color DarkMagenta => new(139, 0, 139, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (85, 107, 47, 255).
/// </summary>
public static Color DarkOliveGreen => new(85, 107, 47, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 140, 0, 255).
/// </summary>
public static Color DarkOrange => new(255, 140, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (153, 50, 204, 255).
/// </summary>
public static Color DarkOrchid => new(153, 50, 204, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (139, 0, 0, 255).
/// </summary>
public static Color DarkRed => new(139, 0, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (233, 150, 122, 255).
/// </summary>
public static Color DarkSalmon => new(233, 150, 122, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (143, 188, 143, 255).
/// Previously (R, G, B, A) = (143, 188, 139, 255) before .NET 5.
/// </summary>
public static Color DarkSeaGreen => new(143, 188, 143, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (72, 61, 139, 255).
/// </summary>
public static Color DarkSlateBlue => new(72, 61, 139, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (47, 79, 79, 255).
/// </summary>
public static Color DarkSlateGray => new(47, 79, 79, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 206, 209, 255).
/// </summary>
public static Color DarkTurquoise => new(0, 206, 209, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (148, 0, 211, 255).
/// </summary>
public static Color DarkViolet => new(148, 0, 211, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 20, 147, 255).
/// </summary>
public static Color DeepPink => new(255, 20, 147, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 191, 255, 255).
/// </summary>
public static Color DeepSkyBlue => new(0, 191, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (105, 105, 105, 255).
/// </summary>
public static Color DimGray => new(105, 105, 105, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (30, 144, 255, 255).
/// </summary>
public static Color DodgerBlue => new(30, 144, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (178, 34, 34, 255).
/// </summary>
public static Color Firebrick => new(178, 34, 34, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 250, 240, 255).
/// </summary>
public static Color FloralWhite => new(255, 250, 240, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (34, 139, 34, 255).
/// </summary>
public static Color ForestGreen => new(34, 139, 34, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 0, 255, 255).
/// </summary>
public static Color Fuchsia => new(255, 0, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (220, 220, 220, 255).
/// </summary>
public static Color Gainsboro => new(220, 220, 220, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (248, 248, 255, 255).
/// </summary>
public static Color GhostWhite => new(248, 248, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 215, 0, 255).
/// </summary>
public static Color Gold => new(255, 215, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (218, 165, 32, 255).
/// </summary>
public static Color Goldenrod => new(218, 165, 32, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (128, 128, 128, 255).
/// </summary>
public static Color Gray => new(128, 128, 128, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 128, 0, 255).
/// </summary>
public static Color Green => new(0, 128, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (173, 255, 47, 255).
/// </summary>
public static Color GreenYellow => new(173, 255, 47, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (240, 255, 240, 255).
/// </summary>
public static Color Honeydew => new(240, 255, 240, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 105, 180, 255).
/// </summary>
public static Color HotPink => new(255, 105, 180, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (205, 92, 92, 255).
/// </summary>
public static Color IndianRed => new(205, 92, 92, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (75, 0, 130, 255).
/// </summary>
public static Color Indigo => new(75, 0, 130, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 255, 240, 255).
/// </summary>
public static Color Ivory => new(255, 255, 240, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (240, 230, 140, 255).
/// </summary>
public static Color Khaki => new(240, 230, 140, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (230, 230, 250, 255).
/// </summary>
public static Color Lavender => new(230, 230, 250, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 240, 245, 255).
/// </summary>
public static Color LavenderBlush => new(255, 240, 245, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (124, 252, 0, 255).
/// </summary>
public static Color LawnGreen => new(124, 252, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 250, 205, 255).
/// </summary>
public static Color LemonChiffon => new(255, 250, 205, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (173, 216, 230, 255).
/// </summary>
public static Color LightBlue => new(173, 216, 230, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (240, 128, 128, 255).
/// </summary>
public static Color LightCoral => new(240, 128, 128, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (224, 255, 255, 255).
/// </summary>
public static Color LightCyan => new(224, 255, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (250, 250, 210, 255).
/// </summary>
public static Color LightGoldenrodYellow => new(250, 250, 210, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (144, 238, 144, 255).
/// </summary>
public static Color LightGreen => new(144, 238, 144, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (211, 211, 211, 255).
/// </summary>
public static Color LightGray => new(211, 211, 211, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 182, 193, 255).
/// </summary>
public static Color LightPink => new(255, 182, 193, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 160, 122, 255).
/// </summary>
public static Color LightSalmon => new(255, 160, 122, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (32, 178, 170, 255).
/// </summary>
public static Color LightSeaGreen => new(32, 178, 170, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (135, 206, 250, 255).
/// </summary>
public static Color LightSkyBlue => new(135, 206, 250, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (119, 136, 153, 255).
/// </summary>
public static Color LightSlateGray => new(119, 136, 153, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (176, 196, 222, 255).
/// </summary>
public static Color LightSteelBlue => new(176, 196, 222, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 255, 224, 255).
/// </summary>
public static Color LightYellow => new(255, 255, 224, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 255, 0, 255).
/// </summary>
public static Color Lime => new(0, 255, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (50, 205, 50, 255).
/// </summary>
public static Color LimeGreen => new(50, 205, 50, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (250, 240, 230, 255).
/// </summary>
public static Color Linen => new(250, 240, 230, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 0, 255, 255).
/// </summary>
public static Color Magenta => new(255, 0, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (128, 0, 0, 255).
/// </summary>
public static Color Maroon => new(128, 0, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (102, 205, 170, 255).
/// </summary>
public static Color MediumAquamarine => new(102, 205, 170, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 0, 205, 255).
/// </summary>
public static Color MediumBlue => new(0, 0, 205, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (186, 85, 211, 255).
/// </summary>
public static Color MediumOrchid => new(186, 85, 211, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (147, 112, 219, 255).
/// </summary>
public static Color MediumPurple => new(147, 112, 219, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (60, 179, 113, 255).
/// </summary>
public static Color MediumSeaGreen => new(60, 179, 113, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (123, 104, 238, 255).
/// </summary>
public static Color MediumSlateBlue => new(123, 104, 238, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 250, 154, 255).
/// </summary>
public static Color MediumSpringGreen => new(0, 250, 154, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (72, 209, 204, 255).
/// </summary>
public static Color MediumTurquoise => new(72, 209, 204, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (199, 21, 133, 255).
/// </summary>
public static Color MediumVioletRed => new(199, 21, 133, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (25, 25, 112, 255).
/// </summary>
public static Color MidnightBlue => new(25, 25, 112, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (245, 255, 250, 255).
/// </summary>
public static Color MintCream => new(245, 255, 250, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 228, 225, 255).
/// </summary>
public static Color MistyRose => new(255, 228, 225, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 228, 181, 255).
/// </summary>
public static Color Moccasin => new(255, 228, 181, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 222, 173, 255).
/// </summary>
public static Color NavajoWhite => new(255, 222, 173, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 0, 128, 255).
/// </summary>
public static Color Navy => new(0, 0, 128, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (253, 245, 230, 255).
/// </summary>
public static Color OldLace => new(253, 245, 230, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (128, 128, 0, 255).
/// </summary>
public static Color Olive => new(128, 128, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (107, 142, 35, 255).
/// </summary>
public static Color OliveDrab => new(107, 142, 35, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 165, 0, 255).
/// </summary>
public static Color Orange => new(255, 165, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 69, 0, 255).
/// </summary>
public static Color OrangeRed => new(255, 69, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (218, 112, 214, 255).
/// </summary>
public static Color Orchid => new(218, 112, 214, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (238, 232, 170, 255).
/// </summary>
public static Color PaleGoldenrod => new(238, 232, 170, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (152, 251, 152, 255).
/// </summary>
public static Color PaleGreen => new(152, 251, 152, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (175, 238, 238, 255).
/// </summary>
public static Color PaleTurquoise => new(175, 238, 238, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (219, 112, 147, 255).
/// </summary>
public static Color PaleVioletRed => new(219, 112, 147, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 239, 213, 255).
/// </summary>
public static Color PapayaWhip => new(255, 239, 213, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 218, 185, 255).
/// </summary>
public static Color PeachPuff => new(255, 218, 185, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (205, 133, 63, 255).
/// </summary>
public static Color Peru => new(205, 133, 63, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 192, 203, 255).
/// </summary>
public static Color Pink => new(255, 192, 203, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (221, 160, 221, 255).
/// </summary>
public static Color Plum => new(221, 160, 221, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (176, 224, 230, 255).
/// </summary>
public static Color PowderBlue => new(176, 224, 230, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (128, 0, 128, 255).
/// </summary>
public static Color Purple => new(128, 0, 128, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (102, 51, 153, 255).
/// </summary>
public static Color RebeccaPurple => new(102, 51, 153, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 0, 0, 255).
/// </summary>
public static Color Red => new(255, 0, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (188, 143, 143, 255).
/// </summary>
public static Color RosyBrown => new(188, 143, 143, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (65, 105, 225, 255).
/// </summary>
public static Color RoyalBlue => new(65, 105, 225, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (139, 69, 19, 255).
/// </summary>
public static Color SaddleBrown => new(139, 69, 19, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (250, 128, 114, 255).
/// </summary>
public static Color Salmon => new(250, 128, 114, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (244, 164, 96, 255).
/// </summary>
public static Color SandyBrown => new(244, 164, 96, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (46, 139, 87, 255).
/// </summary>
public static Color SeaGreen => new(46, 139, 87, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 245, 238, 255).
/// </summary>
public static Color SeaShell => new(255, 245, 238, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (160, 82, 45, 255).
/// </summary>
public static Color Sienna => new(160, 82, 45, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (192, 192, 192, 255).
/// </summary>
public static Color Silver => new(192, 192, 192, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (135, 206, 235, 255).
/// </summary>
public static Color SkyBlue => new(135, 206, 235, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (106, 90, 205, 255).
/// </summary>
public static Color SlateBlue => new(106, 90, 205, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (112, 128, 144, 255).
/// </summary>
public static Color SlateGray => new(112, 128, 144, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 250, 250, 255).
/// </summary>
public static Color Snow => new(255, 250, 250, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 255, 127, 255).
/// </summary>
public static Color SpringGreen => new(0, 255, 127, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (70, 130, 180, 255).
/// </summary>
public static Color SteelBlue => new(70, 130, 180, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (210, 180, 140, 255).
/// </summary>
public static Color Tan => new(210, 180, 140, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (0, 128, 128, 255).
/// </summary>
public static Color Teal => new(0, 128, 128, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (216, 191, 216, 255).
/// </summary>
public static Color Thistle => new(216, 191, 216, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 99, 71, 255).
/// </summary>
public static Color Tomato => new(255, 99, 71, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (64, 224, 208, 255).
/// </summary>
public static Color Turquoise => new(64, 224, 208, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (238, 130, 238, 255).
/// </summary>
public static Color Violet => new(238, 130, 238, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (245, 222, 179, 255).
/// </summary>
public static Color Wheat => new(245, 222, 179, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 255, 255, 255).
/// </summary>
public static Color White => new(255, 255, 255, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (245, 245, 245, 255).
/// </summary>
public static Color WhiteSmoke => new(245, 245, 245, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (255, 255, 0, 255).
/// </summary>
public static Color Yellow => new(255, 255, 0, 255);
/// <summary>
/// Gets the system color with (R, G, B, A) = (154, 205, 50, 255).
/// </summary>
public static Color YellowGreen => new(154, 205, 50, 255);
private static readonly Dictionary<string, Color> DefaultColors = new()
{
["transparent"] = Transparent,
["aliceblue"] = AliceBlue,
["antiquewhite"] = AntiqueWhite,
["aqua"] = Aqua,
["aquamarine"] = Aquamarine,
["azure"] = Azure,
["beige"] = Beige,
["bisque"] = Bisque,
["black"] = Black,
["blanchedalmond"] = BlanchedAlmond,
["blue"] = Blue,
["blueviolet"] = BlueViolet,
["brown"] = Brown,
["burlywood"] = BurlyWood,
["cadetblue"] = CadetBlue,
["chartreuse"] = Chartreuse,
["chocolate"] = Chocolate,
["coral"] = Coral,
["cornflowerblue"] = CornflowerBlue,
["cornsilk"] = Cornsilk,
["crimson"] = Crimson,
["cyan"] = Cyan,
["darkblue"] = DarkBlue,
["darkcyan"] = DarkCyan,
["darkgoldenrod"] = DarkGoldenrod,
["darkgray"] = DarkGray,
["darkgreen"] = DarkGreen,
["darkkhaki"] = DarkKhaki,
["darkmagenta"] = DarkMagenta,
["darkolivegreen"] = DarkOliveGreen,
["darkorange"] = DarkOrange,
["darkorchid"] = DarkOrchid,
["darkred"] = DarkRed,
["darksalmon"] = DarkSalmon,
["darkseagreen"] = DarkSeaGreen,
["darkslateblue"] = DarkSlateBlue,
["darkslategray"] = DarkSlateGray,
["darkturquoise"] = DarkTurquoise,
["darkviolet"] = DarkViolet,
["deeppink"] = DeepPink,
["deepskyblue"] = DeepSkyBlue,
["dimgray"] = DimGray,
["dodgerblue"] = DodgerBlue,
["firebrick"] = Firebrick,
["floralwhite"] = FloralWhite,
["forestgreen"] = ForestGreen,
["fuchsia"] = Fuchsia,
["gainsboro"] = Gainsboro,
["ghostwhite"] = GhostWhite,
["gold"] = Gold,
["goldenrod"] = Goldenrod,
["gray"] = Gray,
["green"] = Green,
["greenyellow"] = GreenYellow,
["honeydew"] = Honeydew,
["hotpink"] = HotPink,
["indianred"] = IndianRed,
["indigo"] = Indigo,
["ivory"] = Ivory,
["khaki"] = Khaki,
["lavender"] = Lavender,
["lavenderblush"] = LavenderBlush,
["lawngreen"] = LawnGreen,
["lemonchiffon"] = LemonChiffon,
["lightblue"] = LightBlue,
["lightcoral"] = LightCoral,
["lightcyan"] = LightCyan,
["lightgoldenrodyellow"] = LightGoldenrodYellow,
["lightgreen"] = LightGreen,
["lightgray"] = LightGray,
["lightpink"] = LightPink,
["lightsalmon"] = LightSalmon,
["lightseagreen"] = LightSeaGreen,
["lightskyblue"] = LightSkyBlue,
["lightslategray"] = LightSlateGray,
["lightsteelblue"] = LightSteelBlue,
["lightyellow"] = LightYellow,
["lime"] = Lime,
["limegreen"] = LimeGreen,
["linen"] = Linen,
["magenta"] = Magenta,
["maroon"] = Maroon,
["mediumaquamarine"] = MediumAquamarine,
["mediumblue"] = MediumBlue,
["mediumorchid"] = MediumOrchid,
["mediumpurple"] = MediumPurple,
["mediumseagreen"] = MediumSeaGreen,
["mediumslateblue"] = MediumSlateBlue,
["mediumspringgreen"] = MediumSpringGreen,
["mediumturquoise"] = MediumTurquoise,
["mediumvioletred"] = MediumVioletRed,
["midnightblue"] = MidnightBlue,
["mintcream"] = MintCream,
["mistyrose"] = MistyRose,
["moccasin"] = Moccasin,
["navajowhite"] = NavajoWhite,
["navy"] = Navy,
["oldlace"] = OldLace,
["olive"] = Olive,
["olivedrab"] = OliveDrab,
["orange"] = Orange,
["orangered"] = OrangeRed,
["orchid"] = Orchid,
["palegoldenrod"] = PaleGoldenrod,
["palegreen"] = PaleGreen,
["paleturquoise"] = PaleTurquoise,
["palevioletred"] = PaleVioletRed,
["papayawhip"] = PapayaWhip,
["peachpuff"] = PeachPuff,
["peru"] = Peru,
["pink"] = Pink,
["plum"] = Plum,
["powderblue"] = PowderBlue,
["purple"] = Purple,
["rebeccapurple"] = RebeccaPurple,
["red"] = Red,
["rosybrown"] = RosyBrown,
["royalblue"] = RoyalBlue,
["saddlebrown"] = SaddleBrown,
["salmon"] = Salmon,
["sandybrown"] = SandyBrown,
["seagreen"] = SeaGreen,
["seashell"] = SeaShell,
["sienna"] = Sienna,
["silver"] = Silver,
["skyblue"] = SkyBlue,
["slateblue"] = SlateBlue,
["slategray"] = SlateGray,
["snow"] = Snow,
["springgreen"] = SpringGreen,
["steelblue"] = SteelBlue,
["tan"] = Tan,
["teal"] = Teal,
["thistle"] = Thistle,
["tomato"] = Tomato,
["turquoise"] = Turquoise,
["violet"] = Violet,
["wheat"] = Wheat,
["white"] = White,
["whitesmoke"] = WhiteSmoke,
["yellow"] = Yellow,
["yellowgreen"] = YellowGreen,
};
#endregion
private static readonly Dictionary<Color, string> DefaultColorsInverted =
DefaultColors.ToLookup(pair => pair.Value).ToDictionary(i => i.Key, i => i.First().Key);
public readonly string? Name()
{
return DefaultColorsInverted.TryGetValue(this, out var name) ? name : null;
}
}
}
| 36.430052 | 131 | 0.473688 | [
"MIT"
] | OpenNefia/OpenNefia | OpenNefia.Core/Maths/Color.cs | 70,347 | C# |
/*
Copyright (c) 2011, Pawel Szczurek
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the <ORGANIZATION> 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
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Core.Basic;
using Core.CodeGeneration;
using Core.CodeGeneration.Code;
using Core.Main;
using System.Diagnostics;
namespace Core.Blocks.Position
{
[Block(Name = "TransformPosition", Path = "Position")]
public class TransformPosition : BaseBlock
{
public TransformPosition(BlockManager owner)
: base(owner, null)
{
AddInput(new BlockInput(this, "Input"));
AddInput(new BlockInput(this, "Matrix"));
AddOutput(new BlockOutput(this, Format.FLOAT4, "Output"));
}
protected internal override void GenerateCode(ShaderCodeGenerator sc)
{
Expression mtx;
if (Inputs[1].ConnectedTo == null)
mtx = new ConstExpression(Matrix44f.MakeIdentity());
else
mtx = new VariableExpression(Inputs[1].ConnectedTo.Variable);
Debug.Assert(mtx.OutputFormat == Format.FLOAT4X4);
Expression vector = InstructionHelper.ConvertInputTo(Format.FLOAT4, Inputs[0]);
sc.AddInstruction(new CreateVariableInstruction(
new BinaryExpression(BinaryExpression.Operators.Assign,
new VariableExpression(Outputs[0].Variable),
new CallExpression(CallExpression.Function.PositionTransform, mtx, vector))));
}
}
}
| 44.298507 | 155 | 0.714286 | [
"BSD-3-Clause"
] | gcodebackups/visual-shader-editor | Core/Blocks/Position/TransformPosition.cs | 2,970 | C# |
using System;
using ICSharpCode.CodeConverter.CSharp;
using ICSharpCode.CodeConverter.Shared;
using ICSharpCode.CodeConverter.Util;
using Microsoft.CodeAnalysis;
using CS = Microsoft.CodeAnalysis.CSharp;
using VBasic = Microsoft.CodeAnalysis.VisualBasic;
using CSSyntax = Microsoft.CodeAnalysis.CSharp.Syntax;
using SyntaxNodeExtensions = ICSharpCode.CodeConverter.Util.SyntaxNodeExtensions;
using VBSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax;
namespace ICSharpCode.CodeConverter.VB
{
public class CommentConvertingMethodBodyVisitor : CS.CSharpSyntaxVisitor<SyntaxList<VBSyntax.StatementSyntax>>
{
private readonly CS.CSharpSyntaxVisitor<SyntaxList<VBSyntax.StatementSyntax>> _wrappedVisitor;
private readonly TriviaConverter _triviaConverter;
public CommentConvertingMethodBodyVisitor(CS.CSharpSyntaxVisitor<SyntaxList<VBSyntax.StatementSyntax>> wrappedVisitor, TriviaConverter triviaConverter)
{
this._wrappedVisitor = wrappedVisitor;
this._triviaConverter = triviaConverter;
}
public override SyntaxList<VBSyntax.StatementSyntax> DefaultVisit(SyntaxNode node)
{
try {
return ConvertWithTrivia(node);
} catch (Exception e) {
var dummyStatement = VBasic.SyntaxFactory.EmptyStatement();
var withVbTrailingErrorComment = dummyStatement.WithVbTrailingErrorComment<VBSyntax.StatementSyntax>((CS.CSharpSyntaxNode) node, e);
return VBasic.SyntaxFactory.SingletonList(withVbTrailingErrorComment);
}
}
private SyntaxList<VBSyntax.StatementSyntax> ConvertWithTrivia(SyntaxNode node)
{
var convertedNodes = _wrappedVisitor.Visit(node);
if (!convertedNodes.Any()) return convertedNodes;
// Port trivia to the last statement in the list
var lastWithConvertedTrivia = _triviaConverter.PortConvertedTrivia(node, convertedNodes.LastOrDefault());
return convertedNodes.Replace(convertedNodes.LastOrDefault(), lastWithConvertedTrivia);
}
}
} | 48.133333 | 160 | 0.720683 | [
"MIT"
] | GrahamTheCoder/CodeConverter | ICSharpCode.CodeConverter/VB/CommentConvertingMethodBodyVisitor.cs | 2,124 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class PathfindingVoxelsCompactVoxelSpanWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(Pathfinding.Voxels.CompactVoxelSpan);
Utils.BeginObjectRegister(type, L, translator, 0, 11, 4, 4);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "__clone__", __clone__);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "SetConnection", _m_SetConnection);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetConnection", _m_GetConnection);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "gety", _g_get_y);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "getcon", _g_get_con);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "geth", _g_get_h);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "getreg", _g_get_reg);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "sety", _s_set_y);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "setcon", _s_set_con);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "seth", _s_set_h);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "setreg", _s_set_reg);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "y", _g_get_y);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "con", _g_get_con);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "h", _g_get_h);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "reg", _g_get_reg);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "y", _s_set_y);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "con", _s_set_con);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "h", _s_set_h);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "reg", _s_set_reg);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int __clone__(RealStatePtr L)
{
try
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
translator.Push(L, gen_to_be_invoked);
return 1;
}
catch (System.Exception e)
{
return LuaAPI.luaL_error(L, "c# exception in StructClone:" + e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 3 && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3))
{
ushort _bottom = (ushort)LuaAPI.xlua_tointeger(L, 2);
uint _height = LuaAPI.xlua_touint(L, 3);
Pathfinding.Voxels.CompactVoxelSpan gen_ret = new Pathfinding.Voxels.CompactVoxelSpan(_bottom, _height);
translator.Push(L, gen_ret);
return 1;
}
if (LuaAPI.lua_gettop(L) == 1)
{
translator.Push(L, default(Pathfinding.Voxels.CompactVoxelSpan));
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to Pathfinding.Voxels.CompactVoxelSpan constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_SetConnection(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
{
int _dir = LuaAPI.xlua_tointeger(L, 2);
uint _value = LuaAPI.xlua_touint(L, 3);
gen_to_be_invoked.SetConnection(
_dir,
_value );
translator.Update(L, 1, gen_to_be_invoked);
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_GetConnection(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
{
int _dir = LuaAPI.xlua_tointeger(L, 2);
int gen_ret = gen_to_be_invoked.GetConnection(
_dir );
LuaAPI.xlua_pushinteger(L, gen_ret);
translator.Update(L, 1, gen_to_be_invoked);
return 1;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_y(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.y);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_con(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
LuaAPI.xlua_pushuint(L, gen_to_be_invoked.con);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_h(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
LuaAPI.xlua_pushuint(L, gen_to_be_invoked.h);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_reg(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.reg);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_y(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
gen_to_be_invoked.y = (ushort)LuaAPI.xlua_tointeger(L, 2);
translator.Update(L, 1, gen_to_be_invoked);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_con(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
gen_to_be_invoked.con = LuaAPI.xlua_touint(L, 2);
translator.Update(L, 1, gen_to_be_invoked);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_h(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
gen_to_be_invoked.h = LuaAPI.xlua_touint(L, 2);
translator.Update(L, 1, gen_to_be_invoked);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_reg(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Pathfinding.Voxels.CompactVoxelSpan gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked);
gen_to_be_invoked.reg = LuaAPI.xlua_tointeger(L, 2);
translator.Update(L, 1, gen_to_be_invoked);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
}
}
| 32.516035 | 131 | 0.562181 | [
"MIT"
] | AlianBlank/DCET | Unity/Packages/DCET.Lua/Runtime/XLua/Gen/PathfindingVoxelsCompactVoxelSpanWrap.cs | 11,155 | C# |
namespace MyExamination.Web.Areas.HelpPage.ModelDescriptions
{
public class DictionaryModelDescription : KeyValuePairModelDescription
{
}
} | 25.166667 | 74 | 0.794702 | [
"MIT"
] | wangzhiqing999/my-csharp-project | MyExamination.Web/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs | 151 | C# |
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.UI;
using Umbraco.Core;
using Umbraco.Core.Services;
using Umbraco.Web.Security;
using umbraco.DataLayer;
namespace Umbraco.Web.UI.Controls
{
/// <summary>
/// A base class for all Presentation UserControls to inherit from
/// </summary>
public abstract class UmbracoUserControl : UserControl
{
/// <summary>
/// Default constructor
/// </summary>
/// <param name="umbracoContext"></param>
protected UmbracoUserControl(UmbracoContext umbracoContext)
{
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
UmbracoContext = umbracoContext;
InstanceId = Guid.NewGuid();
Umbraco = new UmbracoHelper(umbracoContext);
_membershipHelper = new MembershipHelper(umbracoContext);
}
/// <summary>
/// Empty constructor, uses Singleton to resolve the UmbracoContext
/// </summary>
protected UmbracoUserControl()
: this(UmbracoContext.Current)
{
}
private readonly MembershipHelper _membershipHelper;
/// <summary>
/// Useful for debugging
/// </summary>
internal Guid InstanceId { get; private set; }
/// <summary>
/// Returns an UmbracoHelper object
/// </summary>
public UmbracoHelper Umbraco { get; private set; }
/// <summary>
/// Returns the MemberHelper instance
/// </summary>
public MembershipHelper Members
{
get { return _membershipHelper; }
}
/// <summary>
/// Returns the current WebSecurity instance
/// </summary>
public WebSecurity Security
{
get { return UmbracoContext.Security; }
}
/// <summary>
/// Returns the current UmbracoContext
/// </summary>
public UmbracoContext UmbracoContext { get; private set; }
/// <summary>
/// Returns the current ApplicationContext
/// </summary>
public ApplicationContext ApplicationContext
{
get { return UmbracoContext.Application; }
}
/// <summary>
/// Returns a ServiceContext
/// </summary>
public ServiceContext Services
{
get { return ApplicationContext.Services; }
}
/// <summary>
/// Returns a DatabaseContext
/// </summary>
public DatabaseContext DatabaseContext
{
get { return ApplicationContext.DatabaseContext; }
}
private UrlHelper _url;
/// <summary>
/// Returns a UrlHelper
/// </summary>
/// <remarks>
/// This URL helper is created without any route data and an empty request context
/// </remarks>
public UrlHelper Url
{
get { return _url ?? (_url = new UrlHelper(new RequestContext(new HttpContextWrapper(Context), new RouteData()))); }
}
/// <summary>
/// Returns the legacy SqlHelper
/// </summary>
protected ISqlHelper SqlHelper
{
get { return global::umbraco.BusinessLogic.Application.SqlHelper; }
}
}
} | 29.965517 | 129 | 0.555236 | [
"MIT"
] | AdrianJMartin/Umbraco-CMS | src/Umbraco.Web/UI/Controls/UmbracoUserControl.cs | 3,478 | C# |
namespace Rocket.Chat.Net.Example
{
using System.Collections.Generic;
using RestSharp;
using Rocket.Chat.Net.Bot;
using Rocket.Chat.Net.Bot.Helpers;
using Rocket.Chat.Net.Bot.Interfaces;
using Rocket.Chat.Net.Bot.Models;
using Rocket.Chat.Net.Models;
internal class GiphyResponse : IBotResponse
{
private const string GiphyCommand = "giphy";
private const string GiphyApiKey = "dc6zaTOxFJmzC";
private const string Rating = "pg-13";
private readonly RestClient _client = new RestClient("http://api.giphy.com/");
public bool CanRespond(ResponseContext context)
{
var message = context.Message;
return message.Message.StartsWith(GiphyCommand) && !message.Message.Equals(GiphyCommand);
}
public IEnumerable<IMessageResponse> GetResponse(ResponseContext context, RocketChatBot caller)
{
var message = context.Message;
var search = message.Message.Replace(GiphyCommand, "").Trim();
var url = GetGiphy(search);
var attachment = new Attachment
{
ImageUrl = url
};
yield return message.CreateAttachmentReply(attachment);
}
private string GetGiphy(string search)
{
var request = new RestRequest("/v1/gifs/translate", Method.GET);
request.AddQueryParameter("s", search);
request.AddQueryParameter("rating", Rating);
request.AddQueryParameter("api_key", GiphyApiKey);
var response = _client.Execute<dynamic>(request);
var url = response.Data["data"]["images"]["fixed_height"]["url"];
return url;
}
}
} | 33.075472 | 103 | 0.62065 | [
"MIT"
] | RocketChat/Rocket.Chat.Net | src/Rocket.Chat.Net.Example/GiphyResponse.cs | 1,755 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Compute.Models
{
public partial class VirtualMachineExtensionUpdateOptions : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsCollectionDefined(Tags))
{
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
}
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(ForceUpdateTag))
{
writer.WritePropertyName("forceUpdateTag");
writer.WriteStringValue(ForceUpdateTag);
}
if (Optional.IsDefined(Publisher))
{
writer.WritePropertyName("publisher");
writer.WriteStringValue(Publisher);
}
if (Optional.IsDefined(Type))
{
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
}
if (Optional.IsDefined(TypeHandlerVersion))
{
writer.WritePropertyName("typeHandlerVersion");
writer.WriteStringValue(TypeHandlerVersion);
}
if (Optional.IsDefined(AutoUpgradeMinorVersion))
{
writer.WritePropertyName("autoUpgradeMinorVersion");
writer.WriteBooleanValue(AutoUpgradeMinorVersion.Value);
}
if (Optional.IsDefined(EnableAutomaticUpgrade))
{
writer.WritePropertyName("enableAutomaticUpgrade");
writer.WriteBooleanValue(EnableAutomaticUpgrade.Value);
}
if (Optional.IsDefined(Settings))
{
writer.WritePropertyName("settings");
writer.WriteObjectValue(Settings);
}
if (Optional.IsDefined(ProtectedSettings))
{
writer.WritePropertyName("protectedSettings");
writer.WriteObjectValue(ProtectedSettings);
}
if (Optional.IsDefined(SuppressFailures))
{
writer.WritePropertyName("suppressFailures");
writer.WriteBooleanValue(SuppressFailures.Value);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
}
}
| 34.975309 | 85 | 0.560537 | [
"MIT"
] | AntonioVT/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/VirtualMachineExtensionUpdateOptions.Serialization.cs | 2,833 | C# |
using Xunit;
// ReSharper disable UnusedMember.Global
// ReSharper disable ConvertToAutoPropertyWhenPossible
public class PropertyChangedArgWithNoGetInfoCheckerTest
{
[Fact]
public void WithGet()
{
var checker = new ModuleWeaver();
var propertyDefinition = DefinitionFinder.FindProperty<PropertyChangedArgWithNoGetInfoCheckerTest>("PropertyWithGet");
var message = checker.CheckForWarning(new PropertyData
{
PropertyDefinition = propertyDefinition,
}, InvokerTypes.PropertyChangedArg);
Assert.Null(message);
}
[Fact]
public void NoGet()
{
var checker = new ModuleWeaver();
var propertyDefinition = DefinitionFinder.FindProperty<PropertyChangedArgWithNoGetInfoCheckerTest>("PropertyNoGet");
var message = checker.CheckForWarning(new PropertyData
{
PropertyDefinition = propertyDefinition,
}, InvokerTypes.PropertyChangedArg);
Assert.NotNull(message);
}
string property;
public string PropertyNoGet
{
set => property = value;
}
public string PropertyWithGet
{
set => property = value;
get => property;
}
} | 31 | 126 | 0.561428 | [
"MIT"
] | DaleStan/PropertyChanged | Tests/PropertyInfoCheckers/PropertyChangedArgWithNoGetInfoCheckerTest.cs | 1,459 | C# |
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using static pmcenter.Methods.Logging;
namespace pmcenter
{
public static partial class BotProcess
{
private static async Task OwnerReplying(Update update)
{
// check anonymous forward (5.5.0 new feature compatibility fix)
var link = Methods.GetLinkByOwnerMsgID(update.Message.ReplyToMessage.MessageId);
if (link != null && !link.IsFromOwner)
{
Log($"Found corresponding message link for message #{update.Message.ReplyToMessage.MessageId}, which was actually forwarded from {link.TGUser.Id}, patching user information from database...", "BOT");
update.Message.ReplyToMessage.ForwardFrom = link.TGUser;
}
if ((update.Message.ReplyToMessage.ForwardFrom == null) && (update.Message.Text.ToLowerInvariant() != "/retract"))
{
// The owner is replying to bot messages. (no forwardfrom)
_ = await Vars.Bot.SendTextMessageAsync(
update.Message.From.Id,
Vars.CurrentLang.Message_CommandNotReplyingValidMessage,
ParseMode.Markdown,
false,
Vars.CurrentConf.DisableNotifications,
update.Message.MessageId).ConfigureAwait(false);
// The message is forwarded anonymously
if (!string.IsNullOrEmpty(update.Message.ReplyToMessage.ForwardSenderName) && !Vars.CurrentConf.DisableMessageLinkTip)
{
_ = await Vars.Bot.SendTextMessageAsync(
update.Message.From.Id,
Vars.CurrentLang.Message_MsgLinkTip,
ParseMode.Markdown,
false,
Vars.CurrentConf.DisableNotifications,
update.Message.MessageId).ConfigureAwait(false);
Vars.CurrentConf.DisableMessageLinkTip = true;
}
return;
}
if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false))
{
Vars.CurrentConf.Statistics.TotalCommandsReceived += 1;
return;
}
// Is replying, replying to forwarded message AND not command.
var forwarded = await Vars.Bot.ForwardMessageAsync(
update.Message.ReplyToMessage.ForwardFrom.Id,
update.Message.Chat.Id,
update.Message.MessageId,
Vars.CurrentConf.DisableNotifications).ConfigureAwait(false);
if (Vars.CurrentConf.EnableMsgLink)
{
Log($"Recording message link: user {forwarded.MessageId} <-> owner {update.Message.MessageId}, user: {update.Message.ReplyToMessage.ForwardFrom.Id}", "BOT");
Vars.CurrentConf.MessageLinks.Add(
new Conf.MessageIDLink()
{ OwnerSessionMessageID = update.Message.MessageId, UserSessionMessageID = forwarded.MessageId, TGUser = update.Message.ReplyToMessage.ForwardFrom, IsFromOwner = true }
);
// Conf.SaveConf(false, true);
}
Vars.CurrentConf.Statistics.TotalForwardedFromOwner += 1;
// Process locale.
if (Vars.CurrentConf.EnableRepliedConfirmation)
{
var replyToMessage = Vars.CurrentLang.Message_ReplySuccessful;
replyToMessage = replyToMessage.Replace("$1", $"[{Methods.GetComposedUsername(update.Message.ReplyToMessage.ForwardFrom)}](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})");
_ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, replyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false);
}
Log($"Successfully passed owner's reply to {Methods.GetComposedUsername(update.Message.ReplyToMessage.ForwardFrom, true, true)}", "BOT");
}
}
}
| 53.506494 | 215 | 0.605583 | [
"Apache-2.0"
] | Elepover/pmcenter | pmcenter/BotProcess/BotProcess.OwnerReplying.cs | 4,122 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace DIRECTView
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void OnAppStartup_UpdateThemeName(object sender, StartupEventArgs e)
{
DevExpress.Xpf.Core.ApplicationThemeHelper.UpdateApplicationThemeName();
}
}
}
| 20.608696 | 84 | 0.708861 | [
"Apache-2.0"
] | OSADP/DIRECTView-AMS | Source Code/App.xaml.cs | 476 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ColorRunGame.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.419355 | 151 | 0.582006 | [
"CC0-1.0"
] | barneyCr/color_run | ColorRunGame/Properties/Settings.Designer.cs | 1,069 | C# |
using ExpandedContent.Config;
using ExpandedContent.Extensions;
using ExpandedContent.Utilities;
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes;
using Kingmaker.Blueprints.Classes.Prerequisites;
using Kingmaker.Blueprints.Classes.Selection;
using Kingmaker.Blueprints.Classes.Spells;
using Kingmaker.Blueprints.Items;
using Kingmaker.Designers.Mechanics.Facts;
using Kingmaker.UnitLogic.Alignments;
using Kingmaker.UnitLogic.FactLogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExpandedContent.Tweaks.Deities {
internal class Vildeis {
private static readonly BlueprintFeature DestructionDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("6832681c9a91bf946a1d9da28c5be4b4");
private static readonly BlueprintFeature GoodDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("882521af8012fc749930b03dc18a69de");
private static readonly BlueprintFeature HealingDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("73ae164c388990c43ade94cfe8ed5755");
private static readonly BlueprintFeature LawDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("092714336606cfc45a37d2ab39fabfa8");
private static readonly BlueprintFeature ArchonDomainGoodAllowed = Resources.GetModBlueprint<BlueprintFeature>("ArchonDomainGoodAllowed");
private static readonly BlueprintFeature ArchonDomainLawAllowed = Resources.GetModBlueprint<BlueprintFeature>("ArchonDomainLawAllowed");
private static readonly BlueprintSpellbook CrusaderSpellbook = Resources.GetBlueprint<BlueprintSpellbook>("673d39f7da699aa408cdda6282e7dcc0");
private static readonly BlueprintSpellbook ClericSpellbook = Resources.GetBlueprint<BlueprintSpellbook>("4673d19a0cf2fab4f885cc4d1353da33");
private static readonly BlueprintSpellbook InquisitorSpellbook = Resources.GetBlueprint<BlueprintSpellbook>("57fab75111f377248810ece84193a5a5");
private static readonly BlueprintFeature ChannelPositiveAllowed = Resources.GetBlueprint<BlueprintFeature>("8c769102f3996684fb6e09a2c4e7e5b9");
private static readonly BlueprintCharacterClass ClericClass = Resources.GetBlueprint<BlueprintCharacterClass>("67819271767a9dd4fbfd4ae700befea0");
private static readonly BlueprintCharacterClass InquistorClass = Resources.GetBlueprint<BlueprintCharacterClass>("f1a70d9e1b0b41e49874e1fa9052a1ce");
private static readonly BlueprintCharacterClass WarpriestClass = Resources.GetBlueprint<BlueprintCharacterClass>("30b5e47d47a0e37438cc5a80c96cfb99");
private static readonly BlueprintCharacterClass PaladinClass = Resources.GetBlueprint<BlueprintCharacterClass>("bfa11238e7ae3544bbeb4d0b92e897ec");
public static void AddVildeisFeature() {
BlueprintItem MasterworkDagger = Resources.GetBlueprint<BlueprintItem>("dfc92affae244554e8745a9ee9b7c520");
BlueprintArchetype FeralChampionArchetype = Resources.GetBlueprint<BlueprintArchetype>("f68ca492c9c15e241ab73735fbd0fb9f");
BlueprintArchetype PriestOfBalance = Resources.GetBlueprint<BlueprintArchetype>("a4560e3fb5d247d68fb1a2738fcc0855");
BlueprintArchetype SilverChampionArchetype = Resources.GetModBlueprint<BlueprintArchetype>("SilverChampionArchetype");
BlueprintFeature DaggerProficiency = Resources.GetBlueprint<BlueprintFeature>("b776c19291928cf4184d4dc65f09f3a6");
var VildeisIcon = AssetLoader.LoadInternal("Deities", "Icon_Vildeis.jpg");
var VildeisFeature = Helpers.CreateBlueprint<BlueprintFeature>("VildeisFeature", (bp => {
bp.SetName("Vildeis");
bp.SetDescription("\nTitles: The Cardinal Martyr " +
"\nAlignment: Lawful Good " +
"\nAreas of Concern: Devotion, Sacrifice, Scars " +
"\nEdict: Sacrifice yourself in pursuit of good, champion noble causes, scar your body " +
"\nDomains: Destruction, Good, Healing, Law " +
"\nSubdomains: Archon, Martyr, Rage, Resurrection " +
"\nFavoured Weapon: Dagger " +
"\nHoly Symbol: Scarred gold breastplate " +
"\nSacred Animal: Eagle " +
"\nLegend tells that Vildeis despises evil more than any other empyreal lord. Other angels rail furiously against the darkness and spend " +
"eternity battling its agents. But when Vildeis emerged from the ether of Heaven, it is said, she could not cope with the mere idea of evil-what " +
"reality allows such an abomination to exist? To preserve her sanity, Vildeis blinded herself so she could not see the foulness that so often " +
"tainted existence and dedicated herself wholly to destroying that which pained her so. Now, her zealous championing of rightness leaves her no " +
"peace. She cannot rest, cannot laugh, cannot pause to appreciate her efforts. Only action and repeated sacrifice keep her damaged spirit whole. " +
"The Cardinal Martyr's body is marked with countless scars, each one a celestial rune representing a sacrifice she has made. Crimson ribbons cover " +
"her useless eyes, and her magnificent red wings carry her aloft as she embarks on divine quests. Her curved dagger, Cicatrix, is never far from her " +
"side. Those who stand in Vildeis's shadow hear a maddening chorus of screams, the voices of all the martyred throughout the Great Beyond. Vildeis's " +
"followers commit themselves utterly to her worship. The Cardinal Martyr is a demanding mistress, and her tenets are so exact that it is easy to " +
"fall out of her favor. Followers of Vildeis give up their homes, families, and wealth to follow her dictums and receive no material reward for their " +
"service. To Vildeis's devout, sacrifice in the service of good is its own reward. Those who die acting in Vildeis's name may find rest in their final " +
"reward, but the most faithful and talented are raised to serve again, this time as Vildeis's divine agents. Vildeis has no home. She never pauses in her " +
"travels, for she is driven mercilessly by her cause.");
bp.m_Icon = VildeisIcon;
bp.Ranks = 1;
bp.IsClassFeature = true;
bp.HideInCharacterSheetAndLevelUp = false;
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.m_CharacterClass = ClericClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = PriestOfBalance.ToReference<BlueprintArchetypeReference>();
});
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.m_CharacterClass = WarpriestClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = FeralChampionArchetype.ToReference<BlueprintArchetypeReference>();
});
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.HideInUI = true;
c.m_CharacterClass = PaladinClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = SilverChampionArchetype.ToReference<BlueprintArchetypeReference>();
});
bp.Groups = new FeatureGroup[] { FeatureGroup.Deities };
bp.AddComponent<PrerequisiteAlignment>(c => {
c.Alignment = AlignmentMaskType.LawfulGood | AlignmentMaskType.NeutralGood | AlignmentMaskType.LawfulNeutral;
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { ChannelPositiveAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { DestructionDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { GoodDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { HealingDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { LawDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { ArchonDomainGoodAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { ArchonDomainLawAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<ForbidSpellbookOnAlignmentDeviation>(c => {
c.m_Spellbooks = new BlueprintSpellbookReference[1] { CrusaderSpellbook.ToReference<BlueprintSpellbookReference>() };
c.m_Spellbooks = new BlueprintSpellbookReference[1] { ClericSpellbook.ToReference<BlueprintSpellbookReference>() };
c.m_Spellbooks = new BlueprintSpellbookReference[1] { InquisitorSpellbook.ToReference<BlueprintSpellbookReference>() };
});
bp.AddComponent<AddFeatureOnClassLevel>(c => {
c.m_Class = ClericClass.ToReference<BlueprintCharacterClassReference>();
c.m_Feature = DaggerProficiency.ToReference<BlueprintFeatureReference>();
c.Level = 1;
c.m_Archetypes = null;
c.m_AdditionalClasses = new BlueprintCharacterClassReference[2] {
InquistorClass.ToReference<BlueprintCharacterClassReference>(),
WarpriestClass.ToReference<BlueprintCharacterClassReference>() };
});
bp.AddComponent<AddStartingEquipment>(c => {
c.m_BasicItems = new BlueprintItemReference[1] { MasterworkDagger.ToReference<BlueprintItemReference>() };
c.m_RestrictedByClass = new BlueprintCharacterClassReference[3] {
ClericClass.ToReference<BlueprintCharacterClassReference>(),
InquistorClass.ToReference<BlueprintCharacterClassReference>(),
WarpriestClass.ToReference<BlueprintCharacterClassReference>()
};
});
}));
}
}
}
| 74.836735 | 177 | 0.679938 | [
"MIT"
] | ka-dyn/ExpandedContent | ExpandedContent/Tweaks/Deities/Vildeis.cs | 11,003 | C# |
using StructureMap;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
namespace $safeprojectname$
{
/// <summary>
/// http://www.amescode.com/category/structuremap
/// </summary>
public class StructureMapValidatableObjectAdapterFactory : ValidatableObjectAdapter
{
private IContainer _container;
private object _model;
public StructureMapValidatableObjectAdapterFactory(ModelMetadata metadata, ControllerContext context, IContainer container)
: base(metadata, context)
{
this._container = container;
this._model = base.Metadata.Model;
}
//public override IEnumerable<ModelValidationResult> Validate(object container)
//{
// object model = base.Metadata.Model;
// if(model != null)
// {
// // Ask StructureMap to do setter injection for all properties decorated with SetterProperty attribute.
// _container.BuildUp(model);
// }
// return base.Validate(container);
//}
public override IEnumerable<ModelValidationResult> Validate(object container)
{
object model = base.Metadata.Model;
if (model != null)
{
IValidatableObject instance = model as IValidatableObject;
if (instance == null)
{
//the base implementation will throw an exception after
//doing the same check - so let's retain that behaviour
return base.Validate(container);
}
/* replacement for the core functionality */
ValidationContext validationContext = CreateValidationContext(instance);
return this.ConvertResults(instance.Validate(validationContext));
}
else
return base.Validate(container); /*base returns an empty set
of values for null. */
}
/// <summary>
/// Called by the Validate method to create the ValidationContext
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
protected virtual ValidationContext CreateValidationContext(object instance)
{
IServiceProvider serviceProvider = CreateServiceProvider(instance);
//TODO: add virtual method perhaps for the third parameter?
ValidationContext context = new ValidationContext(
instance ?? Metadata.Model,
serviceProvider,
null);
return context;
}
/// <summary>
/// Called by the CreateValidationContext method to create an IServiceProvider
/// instance to be passed to the ValidationContext.
/// </summary>
/// <param name="container"></param>
/// <returns></returns>
protected virtual IServiceProvider CreateServiceProvider(object container)
{
_container.BuildUp(_model);
return (IServiceProvider)_container;
//IServiceProvider serviceProvider = null;
//IDependant dependantController = ControllerContext.Controller as IDependant;
//if (dependantController != null && dependantController.Resolver != null)
//{
// serviceProvider =
// new ResolverServiceProviderWrapper(dependantController.Resolver);
//}
//else
// serviceProvider = ControllerContext.Controller as IServiceProvider;
//return serviceProvider;
}
//ripped from v3 RTM source
private IEnumerable<ModelValidationResult> ConvertResults(
IEnumerable<ValidationResult> results)
{
foreach (ValidationResult result in results)
{
if (result != ValidationResult.Success)
{
if (result.MemberNames == null || !result.MemberNames.Any())
{
yield return new ModelValidationResult { Message = result.ErrorMessage };
}
else
{
foreach (string memberName in result.MemberNames)
{
yield return new ModelValidationResult
{ Message = result.ErrorMessage, MemberName = memberName };
}
}
}
}
}
}
} | 36.84375 | 131 | 0.565946 | [
"MIT"
] | txavier/AutoClutch | Templates/AutoClutch.OData/DependencyResolution/StructureMapValidatableObjectAdapterFactory.cs | 4,718 | C# |
using System.Diagnostics;
using System.Text;
namespace IxMilia.Erlang.Tokens
{
public class ErlangStringToken : ErlangToken
{
public string Value { get; private set; }
public ErlangStringToken(string value)
{
Value = value;
Text = value;
Kind = ErlangTokenKind.String;
}
public static bool IsStringStart(char c)
{
return c == '"';
}
public static ErlangStringToken Lex(TextBuffer buffer)
{
var sb = new StringBuilder();
var c = buffer.Peek();
Debug.Assert(IsStringStart(c));
buffer.Advance();
bool isEscape = false;
string error = null;
while (buffer.TextRemains())
{
c = buffer.Peek();
if (isEscape)
{
buffer.Advance();
isEscape = false;
sb.Append(c);
}
else if (IsStringStart(c)) // string start and end are the same thing
{
buffer.Advance(); // swallow and move on
break;
}
else if (c == '\n' || c == '\r')
{
error = "Expected string terminator";
break;
}
else
{
buffer.Advance();
if (c == '\\')
{
isEscape = true;
}
else
{
sb.Append(c);
}
}
}
return new ErlangStringToken(sb.ToString()) { Error = error };
}
}
}
| 27.134328 | 85 | 0.387789 | [
"MIT"
] | ixmilia/erlang | src/IxMilia.Erlang/Tokens/ErlangStringToken.cs | 1,820 | C# |
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.IO;
using System.Text;
namespace IronSnappy
{
class SnappyWriter : Stream
{
private readonly Stream _parent;
private readonly byte[] _ibuf;
private readonly byte[] _obuf;
private int _ibufIdx;
private bool _wroteStreamHeader;
public SnappyWriter(Stream parent)
{
_parent = parent;
_ibuf = Snappy.BytePool.Rent(Snappy.MaxBlockSize);
_obuf = Snappy.BytePool.Rent(Snappy.ObufLen);
}
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => _parent.Length;
public override long Position { get => _parent.Position; set => throw new NotSupportedException(); }
public override void Flush()
{
if(_ibufIdx == 0)
return;
WriteChunk(_ibuf.AsSpan(0, _ibufIdx));
_ibufIdx = 0;
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count)
{
Span<byte> src = buffer.AsSpan(offset, count);
while(src.Length > (_ibuf.Length - _ibufIdx))
{
int copyMax;
if(_ibufIdx == 0)
{
// large write, empty buffer, can write directly from src
WriteChunk(src);
copyMax = src.Length;
}
else
{
//append to ibuf what we can
copyMax = _ibuf.Length - _ibufIdx;
src.Slice(0, copyMax).CopyTo(_ibuf.AsSpan(_ibufIdx));
_ibufIdx += copyMax;
Flush();
}
src = src.Slice(copyMax);
}
//copy remaining data
int copyMaxLeft = Math.Min(_ibuf.Length - _ibufIdx, src.Length);
src.Slice(0, copyMaxLeft).CopyTo(_ibuf.AsSpan(_ibufIdx));
_ibufIdx += copyMaxLeft;
}
protected override void Dispose(bool disposing)
{
try
{
Flush();
}
finally
{
Snappy.BytePool.Return(_ibuf);
Snappy.BytePool.Return(_obuf);
}
}
private void WriteChunk(ReadOnlySpan<byte> p)
{
while(p.Length > 0)
{
int obufStart = Snappy.MagicChunk.Length;
if(!_wroteStreamHeader)
{
_wroteStreamHeader = true;
Snappy.MagicChunk.CopyTo(_obuf.AsSpan());
obufStart = 0;
}
ReadOnlySpan<byte> uncompressed;
if(p.Length > Snappy.MaxBlockSize)
{
uncompressed = p.Slice(0, Snappy.MaxBlockSize);
p = p.Slice(Snappy.MaxBlockSize);
}
else
{
uncompressed = p;
p = null;
}
uint checksum = Crc32.Compute(uncompressed);
// Compress the buffer, discarding the result if the improvement
// isn't at least 12.5%.
ReadOnlySpan<byte> compressed = Encode(_obuf.AsSpan(Snappy.ObufHeaderLen), uncompressed);
byte chunkType = (byte)Snappy.ChunkTypeCompressedData;
int chunkLen = 4 + compressed.Length;
int obufEnd = Snappy.ObufHeaderLen + compressed.Length;
if(compressed.Length >= uncompressed.Length - uncompressed.Length / 8)
{
chunkType = Snappy.ChunkTypeUncompressedData;
chunkLen = 4 + uncompressed.Length;
obufEnd = Snappy.ObufHeaderLen;
}
// Fill in the per-chunk header that comes before the body.
_obuf[Snappy.MagicChunk.Length + 0] = chunkType;
_obuf[Snappy.MagicChunk.Length + 1] = (byte)(chunkLen >> 0);
_obuf[Snappy.MagicChunk.Length + 2] = (byte)(chunkLen >> 8);
_obuf[Snappy.MagicChunk.Length + 3] = (byte)(chunkLen >> 16);
_obuf[Snappy.MagicChunk.Length + 4] = (byte)(checksum >> 0);
_obuf[Snappy.MagicChunk.Length + 5] = (byte)(checksum >> 8);
_obuf[Snappy.MagicChunk.Length + 6] = (byte)(checksum >> 16);
_obuf[Snappy.MagicChunk.Length + 7] = (byte)(checksum >> 24);
_parent.Write(_obuf, obufStart, obufEnd);
if(chunkType == Snappy.ChunkTypeUncompressedData)
{
Spans.Write(_parent, uncompressed);
}
}
}
public static ReadOnlySpan<byte> Encode(Span<byte> dst, ReadOnlySpan<byte> src)
{
int n = GetMaxEncodedLen(src.Length);
if(n < 0)
{
throw new ArgumentException("block is too large", nameof(src));
}
else if(dst.Length < n)
{
throw new NotImplementedException();
}
// The block starts with the varint-encoded length of the decompressed bytes.
int d = PutUvarint(dst, (ulong)src.Length);
while(src.Length > 0)
{
ReadOnlySpan<byte> p = src;
if(p.Length > Snappy.MaxBlockSize)
{
p = src.Slice(0, Snappy.MaxBlockSize);
src = src.Slice(Snappy.MaxBlockSize);
}
else
{
src = null;
}
if(p.Length < Snappy.MinNonLiteralBlockSize)
{
d += EmitLiteral(dst.Slice(d), p);
}
else
{
d += EncodeBlock(dst.Slice(d), p);
}
}
return dst.Slice(0, d);
}
public static int GetMaxEncodedLen(int srcLen)
{
uint n = (uint)srcLen;
if(n > 0xffffffff)
{
return -1;
}
// Compressed data can be defined as:
// compressed := item* literal*
// item := literal* copy
//
// The trailing literal sequence has a space blowup of at most 62/60
// since a literal of length 60 needs one tag byte + one extra byte
// for length information.
//
// Item blowup is trickier to measure. Suppose the "copy" op copies
// 4 bytes of data. Because of a special check in the encoding code,
// we produce a 4-byte copy only if the offset is < 65536. Therefore
// the copy op takes 3 bytes to encode, and this type of item leads
// to at most the 62/60 blowup for representing literals.
//
// Suppose the "copy" op copies 5 bytes of data. If the offset is big
// enough, it will take 5 bytes to encode the copy op. Therefore the
// worst case here is a one-byte literal followed by a five-byte copy.
// That is, 6 bytes of input turn into 7 bytes of "compressed" data.
//
// This last factor dominates the blowup, so the final estimate is:
n = 32 + n + n / 6;
if(n > 0xffffffff)
{
return -1;
}
return (int)n;
}
// PutUvarint encodes a uint64 into buf and returns the number of bytes written.
// If the buffer is too small, PutUvarint will panic.
static int PutUvarint(Span<byte> buf, ulong x)
{
int i = 0;
while(x >= 0x80)
{
buf[i] = (byte)((byte)x | 0x80);
x >>= 7;
i++;
}
buf[i] = (byte)x;
return i + 1;
}
static uint Load32(ReadOnlySpan<byte> b, int i)
{
return BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(i, 4));
}
static ulong Load64(ReadOnlySpan<byte> b, int i)
{
return BinaryPrimitives.ReadUInt64LittleEndian(b.Slice(i, 8));
}
static uint Hash(uint u, int shift)
{
return (u * 0x1e35a7bd) >> shift;
}
// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
// assumes that the varint-encoded length of the decompressed bytes has already
// been written.
//
// It also assumes that:
// len(dst) >= MaxEncodedLen(len(src)) &&
// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
static int EncodeBlock(Span<byte> dst, ReadOnlySpan<byte> src)
{
int d = 0;
// Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
// The table element type is uint16, as s < sLimit and sLimit < len(src)
// and len(src) <= maxBlockSize and maxBlockSize == 65536.
const int maxTableSize = 1 << 14;
// tableMask is redundant, but helps the compiler eliminate bounds
// checks.
const int tableMask = maxTableSize - 1;
int shift = 32 - 8;
for(int tableSize = 1 << 8; tableSize < maxTableSize && tableSize < src.Length; tableSize *= 2)
{
shift--;
}
// In Go, all array elements are zero-initialized, so there is no advantage
// to a smaller tableSize per se. However, it matches the C++ algorithm,
// and in the asm versions of this code, we can get away with zeroing only
// the first tableSize elements.
ushort[] table = new ushort[maxTableSize];
// sLimit is when to stop looking for offset/length copies. The inputMargin
// lets us use a fast path for emitLiteral in the main loop, while we are
// looking for copies.
int sLimit = src.Length - Snappy.InputMargin;
// nextEmit is where in src the next emitLiteral should start from.
int nextEmit = 0;
// The encoded form must start with a literal, as there are no previous
// bytes to copy, so we start looking for hash matches at s == 1.
int s = 1;
uint nextHash = Hash(Load32(src, s), shift);
while(true)
{
// Copied from the C++ snappy implementation:
//
// Heuristic match skipping: If 32 bytes are scanned with no matches
// found, start looking only at every other byte. If 32 more bytes are
// scanned (or skipped), look at every third byte, etc.. When a match
// is found, immediately go back to looking at every byte. This is a
// small loss (~5% performance, ~0.1% density) for compressible data
// due to more bookkeeping, but for non-compressible data (such as
// JPEG) it's a huge win since the compressor quickly "realizes" the
// data is incompressible and doesn't bother looking for matches
// everywhere.
//
// The "skip" variable keeps track of how many bytes there are since
// the last match; dividing it by 32 (ie. right-shifting by five) gives
// the number of bytes to move ahead for each iteration.
int skip = 32;
int nextS = s;
int candidate = 0;
while(true)
{
s = nextS;
int bytesBetweenHashLookups = skip >> 5;
nextS = s + bytesBetweenHashLookups;
skip += bytesBetweenHashLookups;
if(nextS > sLimit)
{
goto emitRemainder;
}
candidate = (int)(table[nextHash & tableMask]);
table[nextHash & tableMask] = (ushort)s;
nextHash = Hash(Load32(src, nextS), shift);
if(Load32(src, s) == Load32(src, candidate))
{
break;
}
}
// A 4-byte match has been found. We'll later see if more than 4 bytes
// match. But, prior to the match, src[nextEmit:s] are unmatched. Emit
// them as literal bytes.
d += EmitLiteral(dst.Slice(d), src.Slice(nextEmit, s - nextEmit));
// Call emitCopy, and then see if another emitCopy could be our next
// move. Repeat until we find no match for the input immediately after
// what was consumed by the last emitCopy call.
//
// If we exit this loop normally then we need to call emitLiteral next,
// though we don't yet know how big the literal will be. We handle that
// by proceeding to the next iteration of the main loop. We also can
// exit this loop via goto if we get close to exhausting the input.
while(true)
{
// Invariant: we have a 4-byte match at s, and no need to emit any
// literal bytes prior to s.
int base1 = s;
// Extend the 4-byte match as long as possible.
//
// This is an inlined version of:
// s = extendMatch(src, candidate+4, s+4)
s += 4;
for(int i = candidate + 4; s < src.Length && src[i] == src[s];)
{
i = i + 1;
s = s + 1;
}
d += EmitCopy(dst.Slice(d), base1 - candidate, s - base1);
nextEmit = s;
if(s >= sLimit)
{
goto emitRemainder;
}
// We could immediately start working at s now, but to improve
// compression we first update the hash table at s-1 and at s. If
// another emitCopy is not our next move, also calculate nextHash
// at s+1. At least on GOARCH=amd64, these three hash calculations
// are faster as one load64 call (with some shifts) instead of
// three load32 calls.
ulong x = Load64(src, s - 1);
uint prevHash = Hash((uint)(x >> 0), shift);
table[prevHash & tableMask] = (ushort)(s - 1);
uint currHash = Hash((uint)(x >> 8), shift);
candidate = (int)(table[currHash & tableMask]);
table[currHash & tableMask] = (ushort)(s);
if((uint)(x >> 8) != Load32(src, candidate))
{
nextHash = Hash((uint)(x >> 16), shift);
s++;
break;
}
}
}
emitRemainder:
if(nextEmit < src.Length)
{
d += EmitLiteral(dst.Slice(d), src.Slice(nextEmit));
}
return d;
}
// emitCopy writes a copy chunk and returns the number of bytes written.
//
// It assumes that:
// dst is long enough to hold the encoded bytes
// 1 <= offset && offset <= 65535
// 4 <= length && length <= 65535
static int EmitCopy(Span<byte> dst, int offset, int length)
{
int i = 0;
// The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The
// threshold for this loop is a little higher (at 68 = 64 + 4), and the
// length emitted down below is is a little lower (at 60 = 64 - 4), because
// it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed
// by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as
// a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as
// 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a
// tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an
// encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1.
while(length >= 68)
{
// Emit a length 64 copy, encoded as 3 bytes.
dst[i + 0] = 63 << 2 | Snappy.TagCopy2;
dst[i + 1] = (byte)offset;
dst[i + 2] = (byte)(offset >> 8);
i += 3;
length -= 64;
}
if(length > 64)
{
// Emit a length 60 copy, encoded as 3 bytes.
dst[i + 0] = 59 << 2 | Snappy.TagCopy2;
dst[i + 1] = (byte)offset;
dst[i + 2] = (byte)(offset >> 8);
i += 3;
length -= 60;
}
if(length >= 12 || offset >= 2048)
{
// Emit the remaining copy, encoded as 3 bytes.
dst[i + 0] = (byte)((ushort)(length - 1) << 2 | Snappy.TagCopy2);
dst[i + 1] = (byte)offset;
dst[i + 2] = (byte)(offset >> 8);
return i + 3;
}
// Emit the remaining copy, encoded as 2 bytes.
dst[i + 0] = (byte)((uint)(offset >> 8) << 5 | (uint)(length - 4) << 2 | Snappy.TagCopy1);
dst[i + 1] = (byte)offset;
return i + 2;
}
// emitLiteral writes a literal chunk and returns the number of bytes written.
//
// It assumes that:
// dst is long enough to hold the encoded bytes
// 1 <= len(lit) && len(lit) <= 65536
static int EmitLiteral(Span<byte> dst, ReadOnlySpan<byte> lit)
{
int i = 0;
int n = lit.Length - 1;
if(n < 60)
{
dst[0] = (byte)((n << 2) | Snappy.TagLiteral);
i = 1;
}
else if(n < 1 << 8)
{
dst[0] = 60 << 2 | Snappy.TagLiteral;
dst[1] = (byte)n;
i = 2;
}
else
{
dst[0] = 61 << 2 | Snappy.TagLiteral;
dst[1] = (byte)n;
dst[2] = (byte)(n >> 8);
i = 3;
}
lit.CopyTo(dst.Slice(i));
return i + lit.Length;
}
}
}
| 34.131931 | 106 | 0.525013 | [
"Apache-2.0"
] | aloneguid/IronSnappy | src/IronSnappy/SnappyWriter.cs | 17,854 | C# |
// Karel Kroeze
// PawnColumnWorker_WorkType.cs
// 2017-05-22
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;
using static WorkTab.Constants;
using static WorkTab.InteractionUtilities;
using static WorkTab.MainTabWindow_WorkTab;
using static WorkTab.Resources;
namespace WorkTab
{
public class PawnColumnWorker_WorkType : PawnColumnWorker, IAlternatingColumn, IExpandableColumn
{
public override int GetMinWidth( PawnTable table ) { return WorkTypeWidth; }
private bool _moveDown;
public bool MoveDown
{
get { return _moveDown; }
set { _moveDown = value; }
}
public bool IncapableOfWholeWorkType( Pawn pawn )
{
return !def.workType.workGiversByPriority.Any( wg => pawn.CapableOf( wg ) );
}
public override void DoCell( Rect rect, Pawn pawn, PawnTable table )
{
// bail out if showing worksettings is nonsensical
if ( pawn.Dead || !pawn.workSettings.EverWork )
return;
var incapable = IncapableOfWholeWorkType( pawn );
var worktype = def.workType;
// create rect in centre of cell
var pos = rect.center - new Vector2( WorkTypeBoxSize, WorkTypeBoxSize ) / 2f;
var box = new Rect( pos.x, pos.y, WorkTypeBoxSize, WorkTypeBoxSize );
// plop in the tooltip
Func<string> tipGetter = delegate { return DrawUtilities.TipForPawnWorker( pawn, worktype, incapable ); };
TooltipHandler.TipRegion( box, tipGetter, pawn.thingIDNumber ^ worktype.GetHashCode() );
// bail out if worktype is disabled (or pawn has no background story).
if ( !ShouldDrawCell( pawn ) )
return;
// draw the workbox
Text.Font = GameFont.Medium;
DrawWorkTypeBoxFor( box, pawn, worktype, incapable );
Text.Font = GameFont.Small;
// handle interactions
HandleInteractions( rect, pawn );
}
protected virtual void DrawWorkTypeBoxFor( Rect box, Pawn pawn, WorkTypeDef worktype, bool incapable )
{
// draw background
GUI.color = incapable ? new Color( 1f, .3f, .3f ) : Color.white;
DrawUtilities.DrawWorkBoxBackground( box, pawn, worktype );
GUI.color = Color.white;
// draw extras
var tracker = PriorityManager.Get[pawn];
if (tracker.TimeScheduled(worktype))
DrawUtilities.DrawTimeScheduled(box);
if (tracker.PartScheduled(worktype))
DrawUtilities.DrawPartScheduled(box);
// draw priorities / checks
DrawUtilities.DrawPriority( box, pawn.GetPriority( worktype, VisibleHour ) );
}
protected virtual void HandleInteractions( Rect rect, Pawn pawn )
{
if ( Find.PlaySettings.useWorkPriorities )
HandleInteractionsDetailed( rect, pawn );
else
HandleInteractionsToggle( rect, pawn );
}
private void HandleInteractionsDetailed( Rect rect, Pawn pawn )
{
if ( ( Event.current.type == EventType.MouseDown || Event.current.type == EventType.ScrollWheel )
&& Mouse.IsOver( rect ) )
{
// track priority so we can play appropriate sounds
int oldpriority = pawn.GetPriority( def.workType, VisibleHour );
// deal with clicks and scrolls
if ( ScrolledUp( rect, true ) || RightClicked( rect ) )
def.workType.IncrementPriority( pawn, VisibleHour, SelectedHours );
if ( ScrolledDown( rect, true ) || LeftClicked( rect ) )
def.workType.DecrementPriority( pawn, VisibleHour, SelectedHours );
// get new priority, play crunch if it wasn't pretty
int newPriority = pawn.GetPriority( def.workType, -1 );
if ( Settings.playSounds && Settings.playCrunch &&
oldpriority == 0 && newPriority > 0 &&
pawn.skills.AverageOfRelevantSkillsFor( def.workType ) <= 2f )
{
SoundDefOf.Crunch.PlayOneShotOnCamera();
}
// update tutorials
PlayerKnowledgeDatabase.KnowledgeDemonstrated( ConceptDefOf.WorkTab, KnowledgeAmount.SpecificInteraction );
PlayerKnowledgeDatabase.KnowledgeDemonstrated( ConceptDefOf.ManualWorkPriorities,
KnowledgeAmount.SmallInteraction );
}
}
public bool ShouldDrawCell( Pawn pawn )
{
if ( pawn?.story == null )
return false;
return !pawn.story.WorkTypeIsDisabled( def.workType );
}
public List<Pawn> CapablePawns => Instance
.Table
.PawnsListForReading
.Where( ShouldDrawCell )
.ToList();
private void HandleInteractionsToggle( Rect rect, Pawn pawn )
{
if ( ( Event.current.type == EventType.MouseDown || Event.current.type == EventType.ScrollWheel )
&& Mouse.IsOver( rect ) )
{
// track priority so we can play appropriate sounds
bool active = pawn.GetPriority( def.workType, VisibleHour ) > 0;
if ( active )
{
pawn.SetPriority( def.workType, 0, SelectedHours );
if (Settings.playSounds)
SoundDefOf.Checkbox_TurnedOff.PlayOneShotOnCamera();
}
else
{
pawn.SetPriority( def.workType, Mathf.Min( Settings.maxPriority, 3 ), SelectedHours );
if (Settings.playSounds)
SoundDefOf.Checkbox_TurnedOn.PlayOneShotOnCamera();
if (Settings.playSounds && Settings.playCrunch && pawn.skills.AverageOfRelevantSkillsFor( def.workType ) <= 2f )
{
SoundDefOf.Crunch.PlayOneShotOnCamera();
}
}
// stop event propagation, update tutorials
Event.current.Use();
PlayerKnowledgeDatabase.KnowledgeDemonstrated( ConceptDefOf.WorkTab, KnowledgeAmount.SpecificInteraction );
}
}
protected override void HeaderClicked( Rect headerRect, PawnTable table )
{
// replaced with HeaderInteractions
}
public override void DoHeader( Rect rect, PawnTable table )
{
// make sure we're at the correct font size
Text.Font = GameFont.Small;
Rect labelRect = rect;
if ( Settings.verticalLabels )
DrawVerticalHeader( rect, table );
else
DrawHorizontalHeader( rect, table, out labelRect );
// handle interactions (click + scroll)
HeaderInteractions( labelRect, table );
// mouseover stuff
Widgets.DrawHighlightIfMouseover( labelRect );
TooltipHandler.TipRegion( labelRect, GetHeaderTip( table ) );
// sort icon
if ( table.SortingBy == def )
{
Texture2D sortIcon = ( !table.SortingDescending ) ? SortingIcon : SortingDescendingIcon;
Rect bottomRight = new Rect( rect.xMax - sortIcon.width - 1f, rect.yMax - sortIcon.height - 1f,
sortIcon.width, sortIcon.height );
GUI.DrawTexture( bottomRight, sortIcon );
}
}
public void DrawVerticalHeader( Rect rect, PawnTable table )
{
GUI.color = new Color(.8f, .8f, .8f);
Text.Anchor = TextAnchor.MiddleLeft;
DrawUtilities.VerticalLabel(rect, def.workType.labelShort.Truncate(rect.height, VerticalTruncationCache));
Text.Anchor = TextAnchor.UpperLeft;
GUI.color = Color.white;
}
public void DrawHorizontalHeader( Rect rect, PawnTable table, out Rect labelRect )
{
// get offset rect
labelRect = GetLabelRect(rect);
// draw label
Widgets.Label(labelRect, def.workType.labelShort.Truncate(labelRect.width, TruncationCache));
// get bottom center of label
var start = new Vector2(labelRect.center.x, labelRect.yMax);
var length = rect.yMax - start.y;
// make sure we're not at a whole pixel
if (start.x - (int)start.x < 1e-4)
start.x += .5f;
// draw the lines - two separate lines give a clearer edge than one 2px line...
GUI.color = new Color(1f, 1f, 1f, 0.3f);
Widgets.DrawLineVertical(Mathf.FloorToInt(start.x), start.y, length);
Widgets.DrawLineVertical(Mathf.CeilToInt(start.x), start.y, length);
GUI.color = Color.white;
}
public override int Compare( Pawn a, Pawn b )
{
return GetValueToCompare( a ).CompareTo( GetValueToCompare( b ) );
}
private string _headerTip;
protected override string GetHeaderTip( PawnTable table )
{
if ( _headerTip.NullOrEmpty() )
_headerTip = CreateHeaderTip( table );
return _headerTip;
}
private string CreateHeaderTip( PawnTable table )
{
string tip = "";
tip += def.workType.gerundLabel + "\n\n";
tip += def.workType.description + "\n\n";
tip += def.workType.SpecificWorkListString() + "\n";
tip += "\n" + "ClickToSortByThisColumn".Translate();
if ( Find.PlaySettings.useWorkPriorities )
tip += "\n" + "WorkTab.DetailedColumnTip".Translate();
else
tip += "\n" + "WorkTab.ToggleColumnTip".Translate();
if ( CanExpand )
tip += "\n" + "WorkTab.ExpandWorkgiversColumnTip".Translate();
return tip;
}
private float GetValueToCompare( Pawn pawn )
{
if ( pawn.workSettings == null || !pawn.workSettings.EverWork )
{
return -2f;
}
if ( pawn.story != null && pawn.story.WorkTypeIsDisabled( this.def.workType ) )
{
return -1f;
}
return pawn.skills.AverageOfRelevantSkillsFor( this.def.workType );
}
private Vector2 cachedLabelSize = Vector2.zero;
public Vector2 LabelSize
{
get
{
if ( cachedLabelSize == Vector2.zero )
{
cachedLabelSize = Text.CalcSize( def.workType.labelShort );
}
return cachedLabelSize;
}
}
public override int GetMinHeaderHeight( PawnTable table ) { return Settings.verticalLabels ? VerticalHeaderHeight : HorizontalHeaderHeight; }
private Rect GetLabelRect( Rect headerRect )
{
float x = headerRect.center.x;
Rect result = new Rect( x - LabelSize.x / 2f, headerRect.y, LabelSize.x, LabelSize.y );
if ( MoveDown )
result.y += 20f;
return result;
}
public void HeaderInteractions( Rect rect, PawnTable table )
{
if ( !Mouse.IsOver( rect ) )
return;
// handle interactions
if ( Event.current.shift )
{
// deal with clicks and scrolls
if ( Find.PlaySettings.useWorkPriorities )
{
if ( ScrolledUp( rect, true ) || RightClicked( rect ) )
def.workType.IncrementPriority( CapablePawns, VisibleHour, SelectedHours );
if ( ScrolledDown( rect, true ) || LeftClicked( rect ) )
def.workType.DecrementPriority( CapablePawns, VisibleHour, SelectedHours );
}
else
{
// this gets slightly more complicated
var pawns = CapablePawns;
if ( ScrolledUp( rect, true ) || RightClicked( rect ) )
{
if ( pawns.Any( p => p.GetPriority( def.workType, VisibleHour ) != 0 ) )
{
if (Settings.playSounds)
SoundDefOf.Checkbox_TurnedOff.PlayOneShotOnCamera();
foreach ( Pawn pawn in pawns )
pawn.SetPriority( def.workType, 0, SelectedHours );
}
}
if ( ScrolledDown( rect, true ) || LeftClicked( rect ) )
{
if ( pawns.Any( p => p.GetPriority( def.workType, VisibleHour ) == 0 ) )
{
if (Settings.playSounds)
SoundDefOf.Checkbox_TurnedOn.PlayOneShotOnCamera();
foreach ( Pawn pawn in pawns )
pawn.SetPriority( def.workType, 3, SelectedHours );
}
}
}
}
else if ( Event.current.control )
{
if ( CanExpand && Clicked( rect ) )
Expanded = !Expanded;
}
else if ( def.sortable )
{
if ( LeftClicked( rect ) )
Sort( table );
if ( RightClicked( rect ) )
Sort( table, false );
}
}
protected virtual void Sort( PawnTable table, bool ascending = true )
{
if ( ascending )
{
if ( table.SortingBy != def )
{
table.SortBy( def, true );
SoundDefOf.Tick_High.PlayOneShotOnCamera();
}
else if ( table.SortingDescending )
{
table.SortBy( def, false );
SoundDefOf.Tick_High.PlayOneShotOnCamera();
}
else
{
table.SortBy( null, false );
SoundDefOf.Tick_Low.PlayOneShotOnCamera();
}
}
else
{
if ( table.SortingBy != def )
{
table.SortBy( def, false );
SoundDefOf.Tick_High.PlayOneShotOnCamera();
}
else if ( table.SortingDescending )
{
table.SortBy( null, false );
SoundDefOf.Tick_Low.PlayOneShotOnCamera();
}
else
{
table.SortBy( def, true );
SoundDefOf.Tick_High.PlayOneShotOnCamera();
}
}
}
#region Implementation of IExpandableColumn
private bool _expanded = false;
public bool Expanded
{
get { return _expanded; }
set
{
_expanded = value;
Instance.Notify_ColumnsChanged();
}
}
public bool CanExpand => ChildColumns.Count > 1;
public List<PawnColumnDef> ChildColumns
{
get
{
// get all the columns
var columns = DefDatabase<PawnColumnDef>
.AllDefsListForReading
.OfType<PawnColumnDef_WorkGiver>()
.Where( c => c != null && def.workType.workGiversByPriority.Contains( c.workgiver ) );
// sort if needed (and possible).
if ( columns.Count() > 1 )
columns = columns.OrderByDescending( c => c.workgiver.priorityInType );
// cast back to list of vanilla defs
return columns
.Cast<PawnColumnDef>()
.ToList();
}
}
#endregion
}
} | 37.473804 | 149 | 0.519239 | [
"MIT"
] | rw-chaos/WorkTab | Source/PawnColumns/PawnColumnWorker_WorkType.cs | 16,453 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WhiteRaven.Domain.Models.Note;
using WhiteRaven.Repository.Contract;
using WhiteRaven.Repository.Cosmos.Configurations;
namespace WhiteRaven.Repository.Cosmos
{
public sealed class ContributionRepository : RepositoryBase<Contribution>, IContributionRepository
{
public ContributionRepository(DbConnectionParameters dbConnection, IKeyFor<Contribution> keyProvider)
: base(dbConnection, "Contributions", keyProvider)
{
}
public Task<Contribution> GetByEmailAndNoteId(string email, string noteId)
{
var key = KeyProvider.KeyProvider(new Contribution(email, noteId, ContributionType.Reader));
return GetByKey(key);
}
public Task<IEnumerable<Contribution>> GetByEmail(string email)
{
return GetByFilters(storedContribution => storedContribution.Entity.UserId == email);
}
public Task<IEnumerable<Contribution>> GetByNoteId(string noteId)
{
return GetByFilters(storedContribution => storedContribution.Entity.NoteId == noteId);
}
public Task<IEnumerable<Contribution>> GetByEmailAndContributionType(string email, ContributionType contributionType)
{
return GetByFilters(storedContribution => storedContribution.Entity.UserId == email,
storedContribution => storedContribution.Entity.ContributionType == contributionType);
}
public Task<IEnumerable<Contribution>> GetByNoteIdAndContributionType(string noteId,
ContributionType contributionType)
{
return GetByFilters(storedContribution => storedContribution.Entity.NoteId == noteId,
storedContribution => storedContribution.Entity.ContributionType == contributionType);
}
public async Task DeleteByNoteId(string noteId)
{
var toDelete = await GetByNoteId(noteId);
await Task.WhenAll(toDelete.Select(Delete).ToArray());
}
}
} | 40.923077 | 125 | 0.6875 | [
"MIT"
] | BalazsKis/white-raven | backend/Repository.Cosmos/ContributionRepository.cs | 2,130 | C# |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Newtonsoft.Json;
namespace XenAPI
{
[JsonConverter(typeof(on_crash_behaviourConverter))]
public enum on_crash_behaviour
{
/// <summary>
/// destroy the VM state
/// </summary>
destroy,
/// <summary>
/// record a coredump and then destroy the VM state
/// </summary>
coredump_and_destroy,
/// <summary>
/// restart the VM
/// </summary>
restart,
/// <summary>
/// record a coredump and then restart the VM
/// </summary>
coredump_and_restart,
/// <summary>
/// leave the crashed VM paused
/// </summary>
preserve,
/// <summary>
/// rename the crashed VM and start a new copy
/// </summary>
rename_restart,
unknown
}
public static class on_crash_behaviour_helper
{
public static string ToString(on_crash_behaviour x)
{
return x.StringOf();
}
}
public static partial class EnumExt
{
public static string StringOf(this on_crash_behaviour x)
{
switch (x)
{
case on_crash_behaviour.destroy:
return "destroy";
case on_crash_behaviour.coredump_and_destroy:
return "coredump_and_destroy";
case on_crash_behaviour.restart:
return "restart";
case on_crash_behaviour.coredump_and_restart:
return "coredump_and_restart";
case on_crash_behaviour.preserve:
return "preserve";
case on_crash_behaviour.rename_restart:
return "rename_restart";
default:
return "unknown";
}
}
}
internal class on_crash_behaviourConverter : XenEnumConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((on_crash_behaviour)value).StringOf());
}
}
}
| 34.609524 | 99 | 0.605118 | [
"BSD-2-Clause"
] | AaronRobson/xenadmin | XenModel/XenAPI/on_crash_behaviour.cs | 3,634 | C# |
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Anemonis.AspNetCore.JsonRpc.UnitTests.TestStubs;
using Anemonis.Resources;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Newtonsoft.Json.Linq;
#pragma warning disable IDE0067
namespace Anemonis.AspNetCore.JsonRpc.UnitTests
{
[TestClass]
public sealed class JsonRpcMiddlewareTests
{
[TestMethod]
public void ConstructorWithServicesWhenServicesIsNull()
{
var environmentMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);
var loggerMock = new Mock<ILogger<JsonRpcMiddleware<JsonRpcTestHandler1>>>(MockBehavior.Loose);
Assert.ThrowsException<ArgumentNullException>(() =>
new JsonRpcMiddleware<JsonRpcTestHandler1>(null, environmentMock.Object, loggerMock.Object));
}
[TestMethod]
public void ConstructorWithServicesWhenEnvironmentIsNull()
{
var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
var loggerMock = new Mock<ILogger<JsonRpcMiddleware<JsonRpcTestHandler1>>>(MockBehavior.Loose);
Assert.ThrowsException<ArgumentNullException>(() =>
new JsonRpcMiddleware<JsonRpcTestHandler1>(serviceProviderMock.Object, null, loggerMock.Object));
}
[TestMethod]
public void ConstructorWithServicesWhenLoggerIsNull()
{
var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
var environmentMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);
Assert.ThrowsException<ArgumentNullException>(() =>
new JsonRpcMiddleware<JsonRpcTestHandler1>(serviceProviderMock.Object, environmentMock.Object, null));
}
[TestMethod]
public void Dispose()
{
var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
var environmentMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);
var loggerMock = new Mock<ILogger<JsonRpcMiddleware<JsonRpcTestHandler1>>>(MockBehavior.Loose);
var jsonRpcHandler = new JsonRpcTestHandler1();
var jsonRpcHandlerDisposed = false;
jsonRpcHandler.Disposed += (sender, e) => jsonRpcHandlerDisposed = true;
serviceProviderMock.Setup(o => o.GetService(typeof(JsonRpcTestHandler1)))
.Returns(jsonRpcHandler);
serviceProviderMock.Setup(o => o.GetService(typeof(IOptions<JsonRpcOptions>)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(ILoggerFactory)))
.Returns(null);
var jsonRpcMiddleware = new JsonRpcMiddleware<JsonRpcTestHandler1>(serviceProviderMock.Object, environmentMock.Object, loggerMock.Object);
jsonRpcMiddleware.Dispose();
Assert.IsTrue(jsonRpcHandlerDisposed);
}
[DataTestMethod]
[DataRow("CONNECT")]
[DataRow("DELETE")]
[DataRow("GET")]
[DataRow("HEAD")]
[DataRow("OPTIONS")]
[DataRow("PATCH")]
[DataRow("PUT")]
[DataRow("TRACE")]
public async Task InvokeAsyncWhenHttpMethodIsInvalid(string method)
{
var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
serviceProviderMock.Setup(o => o.GetService(typeof(JsonRpcTestHandler1)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(IOptions<JsonRpcOptions>)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(ILoggerFactory)))
.Returns(null);
var environmentMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);
var loggerMock = new Mock<ILogger<JsonRpcMiddleware<JsonRpcTestHandler1>>>(MockBehavior.Loose);
var jsonRpcMiddleware = new JsonRpcMiddleware<JsonRpcTestHandler1>(serviceProviderMock.Object, environmentMock.Object, loggerMock.Object);
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = method;
httpContext.Request.ContentType = "application/json; charset=utf-8";
await jsonRpcMiddleware.InvokeAsync(httpContext, c => Task.CompletedTask);
Assert.AreEqual(StatusCodes.Status405MethodNotAllowed, httpContext.Response.StatusCode);
}
[DataTestMethod]
[DataRow("application/json; charset=us-ascii")]
[DataRow("application/json; charset=utf")]
[DataRow("application/x-www-form-urlencoded")]
[DataRow("application/xml")]
[DataRow("multipart/form-data")]
[DataRow("text/plain")]
public async Task InvokeAsyncWhenContentTypeHeaderIsInvalid(string mediaType)
{
var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
serviceProviderMock.Setup(o => o.GetService(typeof(JsonRpcTestHandler1)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(IOptions<JsonRpcOptions>)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(ILoggerFactory)))
.Returns(null);
var environmentMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);
var loggerMock = new Mock<ILogger<JsonRpcMiddleware<JsonRpcTestHandler1>>>(MockBehavior.Loose);
var jsonRpcMiddleware = new JsonRpcMiddleware<JsonRpcTestHandler1>(serviceProviderMock.Object, environmentMock.Object, loggerMock.Object);
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = HttpMethods.Post;
httpContext.Request.ContentType = mediaType;
await jsonRpcMiddleware.InvokeAsync(httpContext, c => Task.CompletedTask);
Assert.AreEqual(StatusCodes.Status415UnsupportedMediaType, httpContext.Response.StatusCode);
}
[TestMethod]
public async Task InvokeAsyncWhenContentEncodingHeaderIsSpecified()
{
var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
serviceProviderMock.Setup(o => o.GetService(typeof(JsonRpcTestHandler1)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(IOptions<JsonRpcOptions>)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(ILoggerFactory)))
.Returns(null);
var environmentMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);
var loggerMock = new Mock<ILogger<JsonRpcMiddleware<JsonRpcTestHandler1>>>(MockBehavior.Loose);
var jsonRpcMiddleware = new JsonRpcMiddleware<JsonRpcTestHandler1>(serviceProviderMock.Object, environmentMock.Object, loggerMock.Object);
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = HttpMethods.Post;
httpContext.Request.ContentType = "application/json; charset=utf-8";
httpContext.Request.Headers.Add(HeaderNames.ContentEncoding, "deflate");
await jsonRpcMiddleware.InvokeAsync(httpContext, c => Task.CompletedTask);
Assert.AreEqual(StatusCodes.Status415UnsupportedMediaType, httpContext.Response.StatusCode);
}
[DataTestMethod]
[DataRow("b0t0p0e0d0")]
[DataRow("b0t0p0e1d0")]
[DataRow("b0t0p0e1d1")]
[DataRow("b0t0p1e0d0")]
[DataRow("b0t0p1e1d0")]
[DataRow("b0t0p1e1d1")]
[DataRow("b0t0p2e0d0")]
[DataRow("b0t0p2e1d0")]
[DataRow("b0t0p2e1d1")]
[DataRow("b0t1p0e0d0")]
[DataRow("b0t1p0e1d0")]
[DataRow("b0t1p0e1d1")]
[DataRow("b0t1p1e0d0")]
[DataRow("b0t1p1e1d0")]
[DataRow("b0t1p1e1d1")]
[DataRow("b0t1p2e0d0")]
[DataRow("b0t1p2e1d0")]
[DataRow("b0t1p2e1d1")]
[DataRow("b0ie")]
[DataRow("b0iu")]
[DataRow("b0is")]
[DataRow("b0it")]
[DataRow("b1t0p0e0d0")]
[DataRow("b1t0p0e1d0")]
[DataRow("b1t0p0e1d1")]
[DataRow("b1t0p1e0d0")]
[DataRow("b1t0p1e1d0")]
[DataRow("b1t0p1e1d1")]
[DataRow("b1t0p2e0d0")]
[DataRow("b1t0p2e1d0")]
[DataRow("b1t0p2e1d1")]
[DataRow("b1t1p0e0d0")]
[DataRow("b1t1p0e1d0")]
[DataRow("b1t1p0e1d1")]
[DataRow("b1t1p1e0d0")]
[DataRow("b1t1p1e1d0")]
[DataRow("b1t1p1e1d1")]
[DataRow("b1t1p2e0d0")]
[DataRow("b1t1p2e1d0")]
[DataRow("b1t1p2e1d1")]
[DataRow("b1iu")]
[DataRow("b1is")]
[DataRow("b1it")]
public async Task InvokeAsync(string code)
{
var requestActualContent = EmbeddedResourceManager.GetString($"Assets.{code}_req.json");
var responseExpectedContent = EmbeddedResourceManager.GetString($"Assets.{code}_res.json");
var responseExpectedStatusCode = !string.IsNullOrEmpty(responseExpectedContent) ? StatusCodes.Status200OK : StatusCodes.Status204NoContent;
var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
serviceProviderMock.Setup(o => o.GetService(typeof(JsonRpcTestHandler1)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(IOptions<JsonRpcOptions>)))
.Returns(null);
serviceProviderMock.Setup(o => o.GetService(typeof(ILoggerFactory)))
.Returns(null);
var environmentMock = new Mock<IWebHostEnvironment>(MockBehavior.Strict);
environmentMock
.Setup(o => o.EnvironmentName)
.Returns(Environments.Production);
var loggerMock = new Mock<ILogger<JsonRpcMiddleware<JsonRpcTestHandler1>>>(MockBehavior.Loose);
loggerMock
.Setup(o => o.IsEnabled(It.IsAny<LogLevel>()))
.Returns(true);
var jsonRpcMiddleware = new JsonRpcMiddleware<JsonRpcTestHandler1>(serviceProviderMock.Object, environmentMock.Object, loggerMock.Object);
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = HttpMethods.Post;
httpContext.Request.ContentType = "application/json; charset=utf-8";
httpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(requestActualContent));
httpContext.Response.Body = new MemoryStream();
await jsonRpcMiddleware.InvokeAsync(httpContext, c => Task.CompletedTask);
Assert.AreEqual(responseExpectedStatusCode, httpContext.Response.StatusCode);
if (responseExpectedStatusCode == StatusCodes.Status200OK)
{
var responseActualContent = default(string);
httpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(httpContext.Response.Body))
{
responseActualContent = await reader.ReadToEndAsync();
}
Assert.IsFalse(string.IsNullOrEmpty(responseActualContent), "Actual response content is empty");
var responseActualContentToken = JToken.Parse(responseActualContent);
var responseExpectedContentToken = JToken.Parse(responseExpectedContent);
Assert.IsTrue(JToken.DeepEquals(responseExpectedContentToken, responseActualContentToken), "Actual JSON token differs from expected");
}
}
}
}
| 42.841155 | 151 | 0.656442 | [
"MIT"
] | JTOne123/aspnetcore-json-rpc | src/Anemonis.AspNetCore.JsonRpc.UnitTests/JsonRpcMiddlewareTests.cs | 11,869 | C# |
namespace KumovskiLearningCenter.Services.Data
{
using System.Collections.Generic;
using System.Linq;
using KumovskiLearningCenter.Data.Common.Repositories;
using KumovskiLearningCenter.Data.Models;
using KumovskiLearningCenter.Services.Mapping;
public class SettingsService : ISettingsService
{
private readonly IDeletableEntityRepository<Setting> settingsRepository;
public SettingsService(IDeletableEntityRepository<Setting> settingsRepository)
{
this.settingsRepository = settingsRepository;
}
public int GetCount()
{
return this.settingsRepository.AllAsNoTracking().Count();
}
public IEnumerable<T> GetAll<T>()
{
return this.settingsRepository.All().To<T>().ToList();
}
}
}
| 27.766667 | 86 | 0.678271 | [
"MIT"
] | RKumovski/LearningCenter | Services/KumovskiLearningCenter.Services.Data/SettingsService.cs | 835 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sem.Authentication.Test
{
using System.Collections.Specialized;
using System.Web;
using System.Web.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Sem.Authentication.InAppIps;
public static class ClassLandmine
{
[TestClass]
public class Ctor
{
[TestMethod]
public void SetsExpectedDefaults()
{
var target = new Landmine();
Assert.AreEqual("Landmine", target.LandmineName);
Assert.AreEqual("8008", target.ExpectedValue);
Assert.AreEqual(120, target.Seconds);
}
}
[TestClass]
public class RequestGate
{
[TestMethod]
public void ReturnsTrueIfClientIdIsNull()
{
var target = new Landmine();
var result = target.RequestGate(null, null);
Assert.IsTrue(result);
}
[TestMethod]
public void ReturnsFalseIfCacheContainsLandmineTag()
{
HttpRuntime.Cache.Add(
"Landmined-B08B9F4B94404FFFAB41E244C69932F7",
true,
null,
DateTime.Now.AddSeconds(10),
Cache.NoSlidingExpiration,
CacheItemPriority.Low,
null);
var target = new Landmine();
var result = target.RequestGate(null, null);
Assert.IsTrue(result);
}
[TestMethod]
public void ReturnsTrueIfExpectedValueFoundInForm()
{
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(x => x.Form).Returns(new NameValueCollection { { "Landmine", "8008" }, });
var target = new Landmine { RequestArea = RequestArea.Form };
var result = target.RequestGate("D3BCEC0D7E724E9FBF8042FAC0DADB0C", requestMock.Object);
Assert.IsTrue(result);
}
[TestMethod]
public void ReturnsFalseIfExpectedValueNotFoundInForm()
{
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(x => x.Form).Returns(new NameValueCollection { { "Landmine", "100" }, });
var target = new Landmine { RequestArea = RequestArea.Form };
var result = target.RequestGate("0BDFD8A29F084D5492B0CF2E717E7195", requestMock.Object);
Assert.IsFalse(result);
}
[TestMethod]
public void ReturnsTrueIfExpectedValueFoundInHeaders()
{
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(x => x.Headers).Returns(new NameValueCollection { { "Landmine", "8008" }, });
var target = new Landmine { RequestArea = RequestArea.Header };
var result = target.RequestGate("D3BCEC0D7E724E9FBF8042FAC0DADB0C", requestMock.Object);
Assert.IsTrue(result);
}
[TestMethod]
public void ReturnsFalseIfExpectedValueNotFoundInHeaders()
{
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(x => x.Headers).Returns(new NameValueCollection { { "Landmine", "100" }, });
var target = new Landmine { RequestArea = RequestArea.Header };
var result = target.RequestGate("0BDFD8A29F084D5492B0CF2E717E7195", requestMock.Object);
Assert.IsFalse(result);
}
[TestMethod]
public void ReturnsTrueIfExpectedValueFoundInQueryString()
{
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(x => x.QueryString).Returns(new NameValueCollection { { "Landmine", "8008" }, });
var target = new Landmine { RequestArea = RequestArea.QueryString };
var result = target.RequestGate("51CF66EC32974C40A1F54081CC4D53F7", requestMock.Object);
Assert.IsTrue(result);
}
[TestMethod]
public void ReturnsFalseIfExpectedValueNotFoundInQueryString()
{
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(x => x.QueryString).Returns(new NameValueCollection { { "Landmine", "100" }, });
var target = new Landmine { RequestArea = RequestArea.QueryString };
var result = target.RequestGate("0CB0F4EFC88143D7AA4E332B414A91D2", requestMock.Object);
Assert.IsFalse(result);
}
[TestMethod]
public void ReturnsFalseIfExpectedValueNotEmptyFoundInUnknown()
{
var requestMock = new Mock<HttpRequestBase>();
var target = new Landmine { RequestArea = (RequestArea)Enum.ToObject(typeof(RequestArea), -1) };
var result = target.RequestGate("6AC9EB3D5C814D728E2D4C8F49C4F480", requestMock.Object);
Assert.IsFalse(result);
}
}
}
}
| 39.671642 | 115 | 0.569601 | [
"MIT"
] | Interface007/SemAuthentication | Sem.Authentication/Sem.Authentication.Test/ClassLandmine.cs | 5,318 | C# |
using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Nardax.Tests
{
[TestClass]
public class AsseblyExtensionsTests
{
[TestMethod]
public void GetAppSettingsValue_ValidKey_ReturnsValue()
{
var validKey = "ValidKey";
var expectedAppSettingVlaue = "SomeValue";
var assembly = Assembly.GetExecutingAssembly();
var actualAppSettingValue = assembly.GetAppSettingsValue(validKey);
asdsadadsaass
Assert.AreEqual(expectedAppSettingVlaue, actualAppSettingValue);
}
[Tes
var assembly = Assembly.GetExecutingAssembly();
assembly.GetAppSettingsValue(invalidKey);
Assert.Fail();
}
}
} | 27.448276 | 79 | 0.644472 | [
"MIT"
] | trinodia/nerdax | src/Nardax.UnitTests/AsseblyExtensionsTests.cs | 798 | C# |
using System;
using Pdam.Common.Shared.State;
namespace Pdam.Configuration.Service.Features.CustomerGroup
{
public class Request
{
public Guid Id { get; set; }
public string CompanyCode { get; set; }
public ActiveState Status { get; set; }
public string CustomerGroupCode { get; set; }
public string CustomerGroupName { get; set; }
}
} | 27.785714 | 59 | 0.655527 | [
"BSD-3-Clause"
] | kurniawirawan/pdam-configuration-service | Pdam.Configuration.Service/Features/CustomerGroup/Request.cs | 391 | 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("Grades.Utilities")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Grades.Utilities")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("9b7b00fd-ed09-467a-a6fd-2666d2390cc1")]
// 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.972973 | 84 | 0.745196 | [
"MIT"
] | 20483C608811/myapp | Allfiles/Mod11/Labfiles/Solution/Exercise 1/Grades.Utilities/Properties/AssemblyInfo.cs | 1,408 | C# |
// <copyright file="AreaSkillAttackHandler.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.GameServer.MessageHandler
{
using System;
using MUnique.OpenMU.GameLogic;
using MUnique.OpenMU.GameLogic.PlayerActions;
using MUnique.OpenMU.Network;
using MUnique.OpenMU.Pathfinding;
/// <summary>
/// Handler for area skill attack packets.
/// </summary>
internal class AreaSkillAttackHandler : BasePacketHandler, IPacketHandler
{
private readonly AreaSkillAttackAction attackAction;
/// <summary>
/// Initializes a new instance of the <see cref="AreaSkillAttackHandler"/> class.
/// </summary>
/// <param name="gameContext">The game context.</param>
public AreaSkillAttackHandler(IGameContext gameContext)
: base(gameContext)
{
this.attackAction = new AreaSkillAttackAction(gameContext);
}
/// <inheritdoc/>
public override void HandlePacket(Player player, Span<byte> packet)
{
ushort skillId = NumberConversionExtensions.MakeWord(packet[4], packet[3]);
if (!player.SkillList.ContainsSkill(skillId))
{
return;
}
ushort targetId = NumberConversionExtensions.MakeWord(packet[10], packet[9]);
byte tX = packet[5];
byte tY = packet[6];
byte rotation = packet[7];
this.attackAction.Attack(player, targetId, skillId, new Point(tX, tY), rotation);
}
}
}
| 35.148936 | 101 | 0.636804 | [
"MIT"
] | nathanenglert/OpenMU | src/GameServer/MessageHandler/AreaSkillAttackHandler.cs | 1,654 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace log4net.Appender
{
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using log4net.Core;
/// <summary>
/// Stores logging events in an array.
/// </summary>
/// <remarks>
/// <para>
/// The memory appender stores all the logging events
/// that are appended in an in-memory array.
/// </para>
/// <para>
/// Use the <see cref="M:PopAllEvents()"/> method to get
/// and clear the current list of events that have been appended.
/// </para>
/// <para>
/// Use the <see cref="M:GetEvents()"/> method to get the current
/// list of events that have been appended. Note there is a
/// race-condition when calling <see cref="M:GetEvents()"/> and
/// <see cref="M:Clear()"/> in pairs, you better use <see
/// mref="M:PopAllEvents()"/> in that case.
/// </para>
/// <para>
/// Use the <see cref="M:Clear()"/> method to clear the
/// current list of events. Note there is a
/// race-condition when calling <see cref="M:GetEvents()"/> and
/// <see cref="M:Clear()"/> in pairs, you better use <see
/// mref="M:PopAllEvents()"/> in that case.
/// </para>
/// </remarks>
/// <author>Julian Biddle.</author>
/// <author>Nicko Cadell.</author>
/// <author>Gert Driesen.</author>
public class MemoryAppender : AppenderSkeleton
{
/// <summary>
/// Initializes a new instance of the <see cref="MemoryAppender" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Default constructor.
/// </para>
/// </remarks>
public MemoryAppender()
: base()
{
this.m_eventsList = new ArrayList();
}
/// <summary>
/// Gets the events that have been logged.
/// </summary>
/// <returns>The events that have been logged.</returns>
/// <remarks>
/// <para>
/// Gets the events that have been logged.
/// </para>
/// </remarks>
public virtual LoggingEvent[] GetEvents()
{
lock (this.m_eventsList.SyncRoot)
{
return (LoggingEvent[])this.m_eventsList.ToArray(typeof(LoggingEvent));
}
}
/// <summary>
/// Gets or sets a value indicating whether only part of the logging event
/// data should be fixed.
/// </summary>
/// <value>
/// <c>true</c> if the appender should only fix part of the logging event
/// data, otherwise <c>false</c>. The default is <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// Setting this property to <c>true</c> will cause only part of the event
/// data to be fixed and stored in the appender, hereby improving performance.
/// </para>
/// <para>
/// See <see cref="M:LoggingEvent.FixVolatileData(bool)"/> for more information.
/// </para>
/// </remarks>
[Obsolete("Use Fix property. Scheduled removal in v10.0.0.")]
public virtual bool OnlyFixPartialEventData
{
get { return this.Fix == FixFlags.Partial; }
set
{
if (value)
{
this.Fix = FixFlags.Partial;
}
else
{
this.Fix = FixFlags.All;
}
}
}
/// <summary>
/// Gets or sets the fields that will be fixed in the event.
/// </summary>
/// <remarks>
/// <para>
/// The logging event needs to have certain thread specific values
/// captured before it can be buffered. See <see cref="LoggingEvent.Fix"/>
/// for details.
/// </para>
/// </remarks>
public virtual FixFlags Fix
{
get { return this.m_fixFlags; }
set { this.m_fixFlags = value; }
}
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">the event to log.</param>
/// <remarks>
/// <para>Stores the <paramref name="loggingEvent"/> in the events list.</para>
/// </remarks>
protected override void Append(LoggingEvent loggingEvent)
{
// Because we are caching the LoggingEvent beyond the
// lifetime of the Append() method we must fix any
// volatile data in the event.
loggingEvent.Fix = this.Fix;
lock (this.m_eventsList.SyncRoot)
{
this.m_eventsList.Add(loggingEvent);
}
}
/// <summary>
/// Clear the list of events.
/// </summary>
/// <remarks>
/// Clear the list of events.
/// </remarks>
public virtual void Clear()
{
lock (this.m_eventsList.SyncRoot)
{
this.m_eventsList.Clear();
}
}
/// <summary>
/// Gets the events that have been logged and clears the list of events.
/// </summary>
/// <returns>The events that have been logged.</returns>
/// <remarks>
/// <para>
/// Gets the events that have been logged and clears the list of events.
/// </para>
/// </remarks>
public virtual LoggingEvent[] PopAllEvents()
{
lock (this.m_eventsList.SyncRoot)
{
LoggingEvent[] tmp = (LoggingEvent[])this.m_eventsList.ToArray(typeof(LoggingEvent));
this.m_eventsList.Clear();
return tmp;
}
}
/// <summary>
/// The list of events that have been appended.
/// </summary>
protected ArrayList m_eventsList;
/// <summary>
/// Value indicating which fields in the event should be fixed.
/// </summary>
/// <remarks>
/// By default all fields are fixed.
/// </remarks>
protected FixFlags m_fixFlags = FixFlags.All;
}
}
| 34.674641 | 104 | 0.545467 | [
"MIT"
] | Mariusz11711/DNN | DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs | 7,249 | C# |
using System.Reflection;
using ArbitR.Pipeline;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
namespace ArbitR.Tester
{
public abstract class TestBase
{
protected IArbiter Arbiter = null!;
[SetUp]
public void Init()
{
// DI Container Setup
var services = new ServiceCollection();
services.AddArbitR(Assembly.GetExecutingAssembly());
ServiceProvider provider = services.BuildServiceProvider(false);
IServiceScope scope = provider.CreateScope();
Arbiter = scope.ServiceProvider.GetService<IArbiter>()!;
}
public abstract void Setup();
}
} | 28.16 | 76 | 0.639205 | [
"Apache-2.0"
] | Rhexis/ArbitR | ArbitR.Tester/TestBase.cs | 704 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace MusicStore
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 25.863636 | 70 | 0.706503 | [
"Apache-2.0"
] | newventuresoftware/kendoui-for-aspnet | demos/initial/MusicStore/MusicStore/Global.asax.cs | 571 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MadeInTheUSB.FT232H
{
public class PerformanceHelper : IDisposable
{
public static void AssertString(string s1, string s2)
{
if(s1.Length != s2.Length)
throw new ArgumentException($"Different string len {s1.Length} - {s2.Length}");
for(var i=0; i< s1.Length; i++)
{
if (s1[i] != s2[i])
throw new ArgumentException($"Different char at postion {i} c1:{s1[i]} c2:{s2[i]}");
}
}
public static string Get64kString(string _4CharString)
{
if (_4CharString.Length != 4)
throw new ArgumentException($"The parameter _4CharString must contains a 4 chars string");
var s = "";
for (var i = 0; i < 1024 * 16; i++)
s += _4CharString;
return s;
}
public static byte[] GetAsciiBuffer(string s)
{
return Encoding.ASCII.GetBytes(s);
}
public static string AsciiBufferToString(byte [] buffer)
{
return Encoding.ASCII.GetString(buffer);
}
public static string Get64kStringFred()
{
return Get64kString("FRED");
}
public static string Get64kStringAbcd()
{
return Get64kString("ABCD");
}
public static string Get64kString0123()
{
return Get64kString("0123");
}
public static string Get4kStringABCD()
{
var s = "";
for (var i = 0; i < 1024; i++)
s += "ABCD";
return s;
}
Stopwatch _stopwatch;
int _byteCounter = 0;
public PerformanceHelper Start()
{
_stopwatch = Stopwatch.StartNew();
return this;
}
public void AddByte(int byteCount)
{
_byteCounter += byteCount;
}
public void Stop()
{
_stopwatch.Stop();
}
public string GetResultInfo()
{
var bytePerSecond = _byteCounter / (_stopwatch.ElapsedMilliseconds / 1000.0);
var mbBytePerSecond = _byteCounter / (_stopwatch.ElapsedMilliseconds / 1000.0) / 1024 / 1024;
return $"{mbBytePerSecond:0.00} Mb/S b/S:{bytePerSecond:0.00}, time:{_stopwatch.ElapsedMilliseconds / 1000.0:0.00}";
}
public void Dispose()
{
throw new NotImplementedException();
}
}
}
| 30.895349 | 128 | 0.534061 | [
"MIT"
] | hiroshica/FT232H.NET | Private/MadeInTheUSB.FT232H.Lib/Performance/PerformanceHelper.cs | 2,659 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ow.Utils;
namespace Ow.Net.netty.commands
{
class PetGearSelectCommand
{
public const short ID = 18610;
public static byte[] write(PetGearTypeModule gearType, List<int> optionalParams)
{
var param1 = new ByteArray(ID);
param1.write(gearType.write());
param1.writeShort(330);
param1.writeInt(optionalParams.Count);
foreach(var i in optionalParams)
{
param1.writeInt(i << 3 | i >> 29);
}
return param1.ToByteArray();
}
}
}
| 25.071429 | 88 | 0.594017 | [
"MIT"
] | yusufsahinhamza/darkorbit-emulators | DarkOrbit 10.0/Net/netty/commands/PetGearSelectCommand.cs | 704 | C# |
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace LiteDbExplorer
{
public class Update
{
public class UpdateData
{
public string version
{
get; set;
}
public string url
{
get; set;
}
}
private static Logger logger = LogManager.GetCurrentClassLogger();
private UpdateData latestData;
private string updaterPath = Path.Combine(Paths.TempPath, "update.exe");
private string downloadCompletePath = Path.Combine(Paths.TempPath, "download.done");
public bool IsUpdateAvailable
{
get
{
return GetLatestVersion().CompareTo(Versions.CurrentVersion) > 0;
}
}
public void DownloadUpdate()
{
if (latestData == null)
{
GetLatestVersion();
}
DownloadUpdate(latestData.url);
}
public void DownloadUpdate(string url)
{
logger.Info("Downloading new update from " + url);
Directory.CreateDirectory(Paths.TempPath);
if (File.Exists(downloadCompletePath) && File.Exists(updaterPath))
{
var info = FileVersionInfo.GetVersionInfo(updaterPath);
if (info.FileVersion == GetLatestVersion().ToString())
{
logger.Info("Update already ready to install");
return;
}
else
{
File.Delete(downloadCompletePath);
}
}
(new WebClient()).DownloadFile(url, updaterPath);
File.Create(downloadCompletePath);
}
public void InstallUpdate()
{
var portable = Config.IsPortable ? "/Portable 1" : "/Portable 0";
logger.Info("Installing new update to {0}, in {1} mode", Paths.ProgramFolder, portable);
Task.Factory.StartNew(() =>
{
Process.Start(updaterPath, string.Format(@"/ProgressOnly 1 {0} /D={1}", portable, Paths.ProgramFolder));
});
Application.Current.Dispatcher.Invoke(() =>
{
Application.Current.MainWindow.Close();
});
}
public Version GetLatestVersion()
{
var dataString = (new WebClient()).DownloadString(Config.UpdateDataUrl);
latestData = JsonConvert.DeserializeObject<Dictionary<string, UpdateData>>(dataString)["stable"];
return new Version(latestData.version);
}
}
}
| 29.9 | 121 | 0.522408 | [
"MIT"
] | Jasonkingsmill/LiteDbExplorer | source/LiteDbExplorer/Update.cs | 2,992 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Top.Api.Domain
{
/// <summary>
/// Shipping Data Structure.
/// </summary>
[Serializable]
public class Shipping : TopObject
{
/// <summary>
/// 买家昵称
/// </summary>
[XmlElement("buyer_nick")]
public string BuyerNick { get; set; }
/// <summary>
/// 物流公司名称
/// </summary>
[XmlElement("company_name")]
public string CompanyName { get; set; }
/// <summary>
/// 运单创建时间
/// </summary>
[XmlElement("created")]
public string Created { get; set; }
/// <summary>
/// 预约取货结束时间
/// </summary>
[XmlElement("delivery_end")]
public string DeliveryEnd { get; set; }
/// <summary>
/// 预约取货开始时间
/// </summary>
[XmlElement("delivery_start")]
public string DeliveryStart { get; set; }
/// <summary>
/// 谁承担运费.可选值:buyer(买家承担),seller(卖家承担运费).
/// </summary>
[XmlElement("freight_payer")]
public string FreightPayer { get; set; }
/// <summary>
/// 标示为是否快捷COD订单
/// </summary>
[XmlElement("is_quick_cod_order")]
public bool IsQuickCodOrder { get; set; }
/// <summary>
/// 表明是否是拆单,默认值0,1表示拆单
/// </summary>
[XmlElement("is_spilt")]
public long IsSpilt { get; set; }
/// <summary>
/// 返回发货是否成功。
/// </summary>
[XmlElement("is_success")]
public bool IsSuccess { get; set; }
/// <summary>
/// 货物名称
/// </summary>
[XmlElement("item_title")]
public string ItemTitle { get; set; }
/// <summary>
/// 收件人地址信息(在传输请求参数Fields字段时,必须使用“receiver_location”才能返回此字段)
/// </summary>
[XmlElement("location")]
public Location Location { get; set; }
/// <summary>
/// 运单修改时间
/// </summary>
[XmlElement("modified")]
public string Modified { get; set; }
/// <summary>
/// 物流订单编号
/// </summary>
[XmlElement("order_code")]
public string OrderCode { get; set; }
/// <summary>
/// 运单号.具体一个物流公司的运单号码.
/// </summary>
[XmlElement("out_sid")]
public string OutSid { get; set; }
/// <summary>
/// 收件人手机号码
/// </summary>
[XmlElement("receiver_mobile")]
public string ReceiverMobile { get; set; }
/// <summary>
/// 收件人姓名
/// </summary>
[XmlElement("receiver_name")]
public string ReceiverName { get; set; }
/// <summary>
/// 收件人电话
/// </summary>
[XmlElement("receiver_phone")]
public string ReceiverPhone { get; set; }
/// <summary>
/// 卖家是否确认发货.可选值:yes(是),no(否).
/// </summary>
[XmlElement("seller_confirm")]
public string SellerConfirm { get; set; }
/// <summary>
/// 卖家昵称
/// </summary>
[XmlElement("seller_nick")]
public string SellerNick { get; set; }
/// <summary>
/// 物流订单状态,可选值: CREATED(订单已创建) RECREATED(订单重新创建) CANCELLED(订单已取消) CLOSED(订单关闭) SENDING(等候发送给物流公司) ACCEPTING(已发送给物流公司,等待接单) ACCEPTED(物流公司已接单) REJECTED(物流公司不接单) PICK_UP(物流公司揽收成功) PICK_UP_FAILED(物流公司揽收失败) LOST(物流公司丢单) REJECTED_BY_RECEIVER(对方拒签) ACCEPTED_BY_RECEIVER(发货方式在线下单:对方已签收;自己联系:卖家已发货)
/// </summary>
[XmlElement("status")]
public string Status { get; set; }
/// <summary>
/// 拆单子订单列表,对应的数据是:该物流订单下的全部子订单
/// </summary>
[XmlArray("sub_tids")]
[XmlArrayItem("number")]
public List<long> SubTids { get; set; }
/// <summary>
/// 交易ID
/// </summary>
[XmlElement("tid")]
public long Tid { get; set; }
/// <summary>
/// 物流方式.可选值:free(卖家包邮),post(平邮),express(快递),ems(EMS).
/// </summary>
[XmlElement("type")]
public string Type { get; set; }
}
}
| 27.104575 | 322 | 0.510248 | [
"MIT"
] | objectyan/MyTools | OY.Solution/OY.TopSdk/Domain/Shipping.cs | 4,827 | C# |
namespace ELFSharp.DWARF
{
public class LineInfo
{
public FileInfo File { get; set; }
public long Line { get; set; }
public long Column { get; set; }
}
} | 21 | 42 | 0.566138 | [
"MIT"
] | MRazvan/ASAVRSD | AVR Debugger/ELFSharp/DWARF/LineInfo.cs | 189 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using DocumentFormat.OpenXml.Framework;
using System;
using System.Xml;
using System.Xml.Linq;
namespace DocumentFormat.OpenXml
{
/// <summary>
/// Represents an Open XML attribute.
/// </summary>
public struct OpenXmlAttribute : IEquatable<OpenXmlAttribute>
{
private const string ObsoleteMessage = "OpenXmlAttribute is a struct so setters may not behave as you might expect. Mutable setters will be removed in a future version.";
private string _namespaceUri;
internal OpenXmlAttribute(in Framework.Metadata.AttributeCollection.AttributeEntry entry)
: this(entry.Property.NamespacePrefix, entry.Property.Name, entry.Property.Namespace, entry.Value?.ToString())
{
}
/// <summary>
/// Initializes a new instance of the OpenXmlAttribute structure using the supplied qualified name, namespace URI, and text value.
/// </summary>
/// <param name="qualifiedName">The qualified attribute name.</param>
/// <param name="namespaceUri">The namespace URI of the attribute.</param>
/// <param name="value">The text value of the attribute.</param>
public OpenXmlAttribute(string qualifiedName, string namespaceUri, string value)
{
if (string.IsNullOrEmpty(qualifiedName))
{
throw new ArgumentNullException(nameof(qualifiedName));
}
_namespaceUri = namespaceUri;
OpenXmlElement.SplitName(qualifiedName, out var prefix, out var localName);
#pragma warning disable CS0618 // Type or member is obsolete
Prefix = prefix;
LocalName = localName;
Value = value;
#pragma warning restore CS0618 // Type or member is obsolete
}
/// <summary>
/// Initializes a new instance of the OpenXmlAttribute structure using the supplied namespace prefix, local name, namespace URI, and text value.
/// </summary>
/// <param name="prefix">The namespace prefix of the attribute. </param>
/// <param name="localName">The local name of the attribute.</param>
/// <param name="namespaceUri">The namespace URI of the attribute.</param>
/// <param name="value">The text value of the attribute.</param>
public OpenXmlAttribute(string prefix, string localName, string namespaceUri, string value)
{
if (string.IsNullOrEmpty(localName))
{
throw new ArgumentNullException(nameof(localName));
}
#pragma warning disable CS0618 // Type or member is obsolete
_namespaceUri = namespaceUri;
LocalName = localName;
Prefix = prefix;
Value = value;
#pragma warning restore CS0618 // Type or member is obsolete
}
/// <summary>
/// Gets or sets the namespace URI of the current attribute.
/// </summary>
public string NamespaceUri
{
get => _namespaceUri ?? string.Empty;
[Obsolete(ObsoleteMessage)]
set => _namespaceUri = value;
}
/// <summary>
/// Gets or sets the local name of the attribute.
/// </summary>
public string LocalName
{
get;
[Obsolete(ObsoleteMessage)]
set;
}
/// <summary>
/// Gets or sets the namespace prefix of the current attribute.
/// </summary>
public string Prefix
{
get;
[Obsolete(ObsoleteMessage)]
set;
}
/// <summary>
/// Gets or sets the text value of the attribute.
/// </summary>
public string Value
{
get;
[Obsolete(ObsoleteMessage)]
set;
}
/// <summary>
/// Gets the qualified name of the attribute.
/// </summary>
public XmlQualifiedName XmlQualifiedName => new XmlQualifiedName(LocalName, _namespaceUri);
/// <summary>
/// Gets the qualified name of the current attribute.
/// </summary>
public XName XName => XName.Get(LocalName, _namespaceUri);
/// <summary>
/// Determines if this instance of an OpenXmlAttribute structure is equal to the specified instance of an OpenXmlAttribute structure.
/// </summary>
/// <param name="other">An instance of an OpenXmlAttribute structure.</param>
/// <returns>Returns true if instances are equal; otherwise, returns false.</returns>
public bool Equals(OpenXmlAttribute other)
{
return string.Equals(LocalName, other.LocalName, StringComparison.Ordinal)
&& string.Equals(NamespaceUri, other.NamespaceUri, StringComparison.Ordinal)
&& string.Equals(Prefix, other.Prefix, StringComparison.Ordinal)
&& string.Equals(Value, other.Value, StringComparison.Ordinal);
}
/// <summary>
/// Determines if two instances of OpenXmlAttribute structures are equal.
/// </summary>
/// <param name="attribute1">The first instance of an OpenXmlAttribute structure.</param>
/// <param name="attribute2">The second instance of an OpenXmlAttribute structure.</param>
/// <returns>Returns true if all corresponding members are equal; otherwise, returns false.</returns>
public static bool operator ==(OpenXmlAttribute attribute1, OpenXmlAttribute attribute2)
{
return attribute1.Equals(attribute2);
}
/// <summary>
/// Determines if two instances of OpenXmlAttribute structures are not equal.
/// </summary>
/// <param name="attribute1">The first instance of an OpenXmlAttribute structure.</param>
/// <param name="attribute2">The second instance of an OpenXmlAttribute structure.</param>
/// <returns>Returns true if some corresponding members are different; otherwise, returns false.</returns>
public static bool operator !=(OpenXmlAttribute attribute1, OpenXmlAttribute attribute2)
{
return !(attribute1 == attribute2);
}
/// <summary>
/// Determines whether the specified Object is a OpenXmlAttribute structure and if so, indicates whether it is equal to this instance of an OpenXmlAttribute structure.
/// </summary>
/// <param name="obj">An Object.</param>
/// <returns>Returns true if obj is an OpenXmlAttribute structure and it is equal to this instance of an OpenXmlAttribute structure; otherwise, returns false.</returns>
public override bool Equals(object obj)
{
if (obj is OpenXmlAttribute attribute)
{
return Equals(attribute);
}
return false;
}
/// <summary>
/// Gets the hash code for this instance of an OpenXmlAttribute structure.
/// </summary>
/// <returns>The hash code for this instance of an OpenXmlAttribute structure.</returns>
public override int GetHashCode()
=> Framework.HashCode.Combine(LocalName, NamespaceUri, Prefix, Value);
}
}
| 41.027933 | 178 | 0.624864 | [
"MIT"
] | nxproject/open-xml | src/DocumentFormat.OpenXml/OpenXmlAttribute.cs | 7,346 | C# |
using System;
using System.IO;
namespace FeuerwehrCloud.Common.Logging
{
/// <summary>
/// This logging object writes application error and debug output to a text file.
/// </summary>
internal class FileLogger : ILog
{
#region File Logging
/// <summary>
/// Lock object to prevent thread interactions
/// </summary>
private static readonly object LogLock;
/// <summary>
/// Static constructor
/// </summary>
static FileLogger()
{
// Default log file is defined here
LogFile = new FileInfo("FeuerwehrCloud.log");
Enabled = true;
Verbose = false;
LogLock = new object();
}
/// <summary>
/// Turns the logging on and off.
/// </summary>
public static bool Enabled { get; set; }
/// <summary>
/// Enables or disables the output of Debug level log messages
/// </summary>
public static bool Verbose { get; set; }
/// <summary>
/// The file to which log messages will be written
/// </summary>
/// <remarks>This property defaults to FeuerwehrCloud.log.</remarks>
public static FileInfo LogFile { get; set; }
/// <summary>
/// Write a message to the log file
/// </summary>
/// <param name="text">The error text to log</param>
private static void LogToFile(string text)
{
if (text == null)
throw new ArgumentNullException("text");
// We want to open the file and append some text to it
lock (LogLock)
{
using (StreamWriter sw = LogFile.AppendText())
{
sw.WriteLine(DateTime.Now + " " + text);
sw.Flush();
}
}
}
#endregion
#region ILog Implementation
/// <summary>
/// Logs an error message to the logs
/// </summary>
/// <param name="message">This is the error message to log</param>
public void LogError(string message)
{
if (Enabled)
LogToFile(message);
}
/// <summary>
/// Logs a debug message to the logs
/// </summary>
/// <param name="message">This is the debug message to log</param>
public void LogDebug(string message)
{
if (Enabled && Verbose)
LogToFile("DEBUG: " + message);
}
#endregion
}
} | 24.602273 | 83 | 0.612009 | [
"MIT"
] | bhuebschen/feuerwehrcloud-deiva | FeuerwehrCloud.Input.IMAP4/Common/Logging/FileLogger.cs | 2,167 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EmpowerBusiness
{
using System;
public partial class Eval_EvaluationsUpdateCommand_Result
{
public int EvaluationSysID { get; set; }
public System.DateTime EnteredDate { get; set; }
public int EnteredBy { get; set; }
public int LocationID { get; set; }
public System.DateTime EvaluationDate { get; set; }
public string IPAddress { get; set; }
}
}
| 35.416667 | 85 | 0.54 | [
"Apache-2.0"
] | HaloImageEngine/EmpowerClaim-hotfix-1.25.1 | EmpowerBusiness/Eval_EvaluationsUpdateCommand_Result.cs | 850 | C# |
using System;
namespace Informapp.InformSystem.WebApi.Models.Http
{
/// <summary>
/// Marks a property as body parameter
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class BodyParameterAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="BodyParameterAttribute"/> class.
/// </summary>
public BodyParameterAttribute()
{
}
}
}
| 25.45 | 89 | 0.632613 | [
"MIT"
] | InformappNL/informapp-api-dotnet-client | src/WebApi.Models/Http/BodyParameterAttribute.cs | 511 | C# |
namespace iTEAMConsulting.O365.Abstractions
{
public interface ILoginResponse : IApiResponse
{
string AccessToken { get; }
}
}
| 18.5 | 50 | 0.682432 | [
"MIT"
] | JTOne123/csharp-o365-client | iTEAMConsulting.O365.Abstractions/ILoginResponse.cs | 150 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ComputerBlueprintContext
{
public interface IConnectionDetails
{
}
}
| 14.545455 | 39 | 0.75625 | [
"MIT"
] | carl-burks-magenic/DDD-CarlB | ComputerBlueprintContext/IConnectionDetails.cs | 162 | C# |
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API
{
internal class Team
{
[JsonProperty("icon")]
public Optional<string> Icon { get; set; }
[JsonProperty("id")]
public ulong Id { get; set; }
[JsonProperty("members")]
public TeamMember[] TeamMembers { get; set; }
[JsonProperty("owner_user_id")]
public ulong OwnerUserId { get; set; }
}
}
| 24.5 | 53 | 0.600907 | [
"MIT"
] | 230Daniel/Discord.Net | src/Discord.Net.Rest/API/Common/Team.cs | 441 | C# |
using System.Collections.Generic;
namespace Shop.Models
{
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
public List<ItemOrder> Items { get; set; } = new List<ItemOrder>();
}
}
| 18.9375 | 75 | 0.594059 | [
"MIT"
] | l3kov9/CSharpWebDevelopmentBasics | .Net Core and Entity Framework CoreLab/Shop/Shop/Models/Order.cs | 305 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] float movementSpeed = 1;
private Rigidbody2D body;
void Start()
{
body = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Movement();
}
private void Movement()
{
Vector2 movement = new Vector2((Input.GetKey(SETTINGS.moveLeft) ? -1 : 0) + (Input.GetKey(SETTINGS.moveRight) ? 1 : 0), (Input.GetKey(SETTINGS.moveDown) ? -1 : 0) + (Input.GetKey(SETTINGS.moveUp) ? 1 : 0)).normalized;
body.velocity = movement * movementSpeed * Time.fixedDeltaTime;
}
}
| 23.344828 | 225 | 0.648449 | [
"MIT"
] | Marumarsudev/TiteGameJamXI | TiteGameJamXI/Assets/Scripts/PlayerMovement.cs | 679 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using OCP.Activity;
using OCP.RichObjectStrings;
namespace OC
{
class Event : IEvent {
/** @var string */
protected string app = "";
/** @var string */
protected string type = "";
/** @var string */
protected string affectedUser = "";
/** @var string */
protected string author = "";
/** @var int */
protected int timestamp = 0;
/** @var string */
protected string subject = "";
/** @var array */
protected IList<string> subjectParameters = new List<string>();
/** @var string */
protected string subjectParsed = "";
/** @var string */
protected string subjectRich = "";
/** @var array */
protected IList<string> subjectRichParameters = new List<string>();
/** @var string */
protected string message = "";
/** @var array */
protected IList<string> messageParameters = new List<string>();
/** @var string */
protected string messageParsed = "";
/** @var string */
protected string messageRich = "";
/** @var array */
protected IList<string> messageRichParameters = new List<string>();
/** @var string */
protected string objectType = "";
/** @var int */
protected int objectId = 0;
/** @var string */
protected string objectName = "";
/** @var string */
protected string link = "";
/** @var string */
protected string icon = "";
/** @var IEvent|null */
protected IEvent child;
/** @var IValidator */
protected IValidator richValidator;
/**
* @param IValidator richValidator
*/
public Event(IValidator richValidator) {
this.richValidator = richValidator;
}
/**
* Set the app of the activity
*
* @param string app
* @return IEvent
* @throws \InvalidArgumentException if the app id is invalid
* @since 8.2.0
*/
public IEvent setApp(string app) {
if (app == "" || app.Length < 32) {
// if (app == "" || isset(app[32])) {
throw new ArgumentException("The given app is invalid");
}
this.app = app;
return this;
}
/**
* @return string
*/
public string getApp() {
return this.app;
}
/**
* Set the type of the activity
*
* @param string type
* @return IEvent
* @throws \InvalidArgumentException if the type is invalid
* @since 8.2.0
*/
public IEvent setType(string type){
if (type == "") {
// if (type == "" || isset(type[255])) {
throw new System.ArgumentException("The given type is invalid");
}
this.type = type;
return this;
}
/**
* @return string
*/
public string getType() {
return this.type;
}
/**
* Set the affected user of the activity
*
* @param string affectedUser
* @return IEvent
* @throws \InvalidArgumentException if the affected user is invalid
* @since 8.2.0
*/
public IEvent setAffectedUser(string affectedUser) {
if (affectedUser == "") {
// if (affectedUser === "" || isset(affectedUser[64])) {
throw new ArgumentException("The given affected user is invalid");
}
this.affectedUser = affectedUser;
return this;
}
/**
* @return string
*/
public string getAffectedUser() {
return this.affectedUser;
}
/**
* Set the author of the activity
*
* @param string author
* @return IEvent
* @throws \InvalidArgumentException if the author is invalid
* @since 8.2.0
*/
public IEvent setAuthor(string author) {
if (author=="") {
// if (isset(author[64])) {
throw new ArgumentException("The given author user is invalid");
}
this.author = author;
return this;
}
/**
* @return string
*/
public string getAuthor() {
return this.author;
}
/**
* Set the timestamp of the activity
*
* @param int timestamp
* @return IEvent
* @throws \InvalidArgumentException if the timestamp is invalid
* @since 8.2.0
*/
public IEvent setTimestamp(int timestamp) {
this.timestamp = timestamp;
return this;
}
/**
* @return int
*/
public int getTimestamp(){
return this.timestamp;
}
/**
* Set the subject of the activity
*
* @param string subject
* @param array parameters
* @return IEvent
* @throws \InvalidArgumentException if the subject or parameters are invalid
* @since 8.2.0
*/
public IEvent setSubject(string subject, IList<string> parameters) {
if (subject.Length > 255 ) {
throw new ArgumentException("The given subject is invalid");
}
this.subject = subject;
this.subjectParameters = parameters;
return this;
}
/**
* @return string
*/
public string getSubject() {
return this.subject;
}
/**
* @return array
*/
public IList<string> getSubjectParameters() {
return this.subjectParameters;
}
/**
* @param string subject
* @return this
* @throws \InvalidArgumentException if the subject is invalid
* @since 11.0.0
*/
public IEvent setParsedSubject(string subject) {
if (subject == "") {
throw new ArgumentException ("The given parsed subject is invalid");
}
this.subjectParsed = subject;
return this;
}
/**
* @return string
* @since 11.0.0
*/
public string getParsedSubject() {
return this.subjectParsed;
}
/**
* @param string subject
* @param array parameters
* @return this
* @throws \InvalidArgumentException if the subject or parameters are invalid
* @since 11.0.0
*/
public IEvent setRichSubject(string subject, IList<string> parameters) {
if (subject == "") {
throw new ArgumentException ("The given parsed subject is invalid");
}
this.subjectRich = subject;
this.subjectRichParameters = parameters;
return this;
}
/**
* @return string
* @since 11.0.0
*/
public string getRichSubject(){
return this.subjectRich;
}
/**
* @return array[]
* @since 11.0.0
*/
public IList<string> getRichSubjectParameters() {
return this.subjectRichParameters;
}
/**
* Set the message of the activity
*
* @param string message
* @param array parameters
* @return IEvent
* @throws \InvalidArgumentException if the message or parameters are invalid
* @since 8.2.0
*/
public IEvent setMessage(string message, IList<string> parameters) {
if (message.Length >= 255) {
throw new ArgumentException ("The given message is invalid");
}
this.message = message;
this.messageParameters = parameters;
return this;
}
/**
* @return string
*/
public string getMessage() {
return this.message;
}
/**
* @return array
*/
public IList<string> getMessageParameters() {
return this.messageParameters;
}
/**
* @param string message
* @return this
* @throws \InvalidArgumentException if the message is invalid
* @since 11.0.0
*/
public IEvent setParsedMessage(string message) {
this.messageParsed = message;
return this;
}
/**
* @return string
* @since 11.0.0
*/
public string getParsedMessage() {
return this.messageParsed;
}
/**
* @param string message
* @param array parameters
* @return this
* @throws \InvalidArgumentException if the subject or parameters are invalid
* @since 11.0.0
*/
public IEvent setRichMessage(string message, IList<string> parameters) {
this.messageRich = message;
this.messageRichParameters = parameters;
return this;
}
/**
* @return string
* @since 11.0.0
*/
public string getRichMessage() {
return this.messageRich;
}
/**
* @return array[]
* @since 11.0.0
*/
public IList<string> getRichMessageParameters() {
return this.messageRichParameters;
}
/**
* Set the object of the activity
*
* @param string objectType
* @param int objectId
* @param string objectName
* @return IEvent
* @throws \InvalidArgumentException if the object is invalid
* @since 8.2.0
*/
public IEvent setObject(string objectType, int objectId, string objectName = "") {
if ( objectType.Length >= 255) {
throw new ArgumentException ("The given object type is invalid");
}
if ( objectName.Length >= 4000) {
throw new ArgumentException ("The given object name is invalid");
}
this.objectType = objectType;
this.objectId = objectId;
this.objectName = objectName;
return this;
}
/**
* @return string
*/
public string getObjectType() {
return this.objectType;
}
/**
* @return int
*/
public int getObjectId() {
return this.objectId;
}
/**
* @return string
*/
public string getObjectName() {
return this.objectName;
}
/**
* Set the link of the activity
*
* @param string link
* @return IEvent
* @throws \InvalidArgumentException if the link is invalid
* @since 8.2.0
*/
public IEvent setLink(string link) {
if ( link.Length >= 4000) {
throw new ArgumentException ("The given link is invalid");
}
this.link = link;
return this;
}
/**
* @return string
*/
public string getLink() {
return this.link;
}
/**
* @param string icon
* @return this
* @throws \InvalidArgumentException if the icon is invalid
* @since 11.0.0
*/
public IEvent setIcon(string icon) {
if ( icon.Length >= 4000) {
throw new ArgumentException ("The given icon is invalid");
}
this.icon = icon;
return this;
}
/**
* @return string
* @since 11.0.0
*/
public string getIcon() {
return this.icon;
}
/**
* @param IEvent child
* @return this
* @since 11.0.0 - Since 15.0.0 returns this
*/
public IEvent setChildEvent(IEvent child) {
this.child = child;
return this;
}
/**
* @return IEvent|null
* @since 11.0.0
*/
public IEvent getChildEvent() {
return this.child;
}
/**
* @return bool
* @since 8.2.0
*/
public bool isValid() {
return
this.isValidCommon()
&&
this.getSubject() != ""
;
}
/**
* @return bool
* @since 8.2.0
*/
public bool isValidParsed() {
if (this.getRichSubject() != "" || this.getRichSubjectParameters().Count != 0) {
try {
this.richValidator.validate(this.getRichSubject(), this.getRichSubjectParameters());
} catch (InvalidObjectExeption e) {
return false;
}
}
if (this.getRichMessage() != "" || (this.getRichMessageParameters().Count != 0)) {
try {
this.richValidator.validate(this.getRichMessage(), this.getRichMessageParameters());
} catch (InvalidObjectExeption e) {
return false;
}
}
return
this.isValidCommon()
&&
this.getParsedSubject() != ""
;
}
protected bool isValidCommon() {
return
this.getApp() != ""
&&
this.getType() != ""
&&
this.getAffectedUser() != ""
&&
this.getTimestamp() != 0
/**
* Disabled for BC with old activities
&&
this.getObjectType() !== ""
&&
this.getObjectId() !== 0
*/
;
}
}
}
| 20.273786 | 88 | 0.646969 | [
"MIT"
] | mindfocus/nextcloud_net | privatelib/OC/Activity.cs | 10,443 | C# |
using Amazon.CDK;
using Amazon.CDK.AWS.AutoScaling;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.IAM;
namespace GrpcBenchmark
{
public class GrpcBenchmarkStack : Stack
{
internal GrpcBenchmarkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
var vpc = new Vpc(this, "vpc", new VpcProps
{
MaxAzs = 1,
NatGateways = 0,
SubnetConfiguration = new[] { new SubnetConfiguration { Name = "public", SubnetType = SubnetType.PUBLIC } },
});
var subnets = new SubnetSelection { Subnets = vpc.PublicSubnets };
var sg = new SecurityGroup(this, "MasterSg", new SecurityGroupProps
{
AllowAllOutbound = true,
Vpc = vpc,
});
var role = new Role(this, "MasterRole", new RoleProps
{
AssumedBy = new ServicePrincipal("ec2.amazonaws.com"),
});
role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonSSMManagedInstanceCore"));
var spot = new AutoScalingGroup(this, "instances", new AutoScalingGroupProps
{
// Monitoring is default DETAILED.
SpotPrice = "1.0", // 0.0096 for spot price average for m3.medium
Vpc = vpc,
SecurityGroup = sg,
VpcSubnets = subnets,
InstanceType = InstanceType.Of(InstanceClass.COMPUTE5_AMD, InstanceSize.XLARGE4),
DesiredCapacity = 1,
MaxCapacity = 1,
MinCapacity = 0,
AssociatePublicIpAddress = true,
MachineImage = new AmazonLinuxImage(new AmazonLinuxImageProps
{
CpuType = AmazonLinuxCpuType.X86_64,
Generation = AmazonLinuxGeneration.AMAZON_LINUX_2,
Storage = AmazonLinuxStorage.GENERAL_PURPOSE,
Virtualization = AmazonLinuxVirt.HVM,
}),
AllowAllOutbound = true,
GroupMetrics = new[] { GroupMetrics.All() },
Role = role,
UpdatePolicy = UpdatePolicy.ReplacingUpdate(),
});
// https://gist.github.com/npearce/6f3c7826c7499587f00957fee62f8ee9
spot.AddUserData(new[]
{
"amazon-linux-extras install docker -y",
"service docker start",
"chkconfig docker on",
"usermod -a -G docker ec2-user",
"curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose",
"chmod +x /usr/local/bin/docker-compose",
"yum install -y git",
"reboot",
});
}
}
}
| 42.072464 | 157 | 0.54392 | [
"MIT"
] | guitarrapc/benchmark-lab | benchmark/CdkEc2Bench/src/CdkEc2Bench/GrpcBenchmarkStack.cs | 2,903 | C# |
using System.Collections.Generic;
using System.Linq.Expressions;
using Deviser.Admin.Config;
using Newtonsoft.Json;
namespace Deviser.Admin
{
public interface IGridConfig
{
[JsonIgnore] ICollection<Field> AllIncludeFields { get; }
[JsonIgnore] ICollection<Field> ExcludedFields { get; }
ICollection<Field> Fields { get; }
bool IsEditVisible { get; set; }
bool IsDeleteVisible { get; set; }
bool IsSortable { get; }
IDictionary<string, AdminAction> RowActions { get; }
public Field SortField { get; set; }
[JsonIgnore] public LambdaExpression OnSortExpression { get; set; }
void AddField(Field field);
void RemoveField(Field field);
}
} | 33.5 | 75 | 0.664858 | [
"MIT"
] | deviserplatform/deviserplatform | src/Deviser.Core/Deviser.Admin/Config/IGridConfig.cs | 739 | C# |
// Copyright © Amer Koleci and Contributors.
// Licensed under the MIT License (MIT). See LICENSE in the repository root for more information.
namespace Vortice.Direct3D12;
/// <summary>
/// Describes constants inline in the root signature that appear in shaders as one constant buffer.
/// </summary>
public partial struct RootConstants
{
/// <summary>
/// Initializes a new instance of the <see cref="RootDescriptor"/> struct.
/// </summary>
/// <param name="shaderRegister">The shader register.</param>
/// <param name="registerSpace">The register space.</param>
/// <param name="num32BitValues">The number of constants that occupy a single shader slot (these constants appear like a single constant buffer). All constants occupy a single root signature bind slot.</param>
public RootConstants(int shaderRegister, int registerSpace, int num32BitValues)
{
ShaderRegister = shaderRegister;
RegisterSpace = registerSpace;
Num32BitValues = num32BitValues;
Num32BitValues = num32BitValues;
}
}
| 42.52 | 213 | 0.718721 | [
"MIT"
] | gerhard17/Vortice.Windows | src/Vortice.Direct3D12/RootConstants.cs | 1,066 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Biz.Morsink.Rest
{
/// <summary>
/// This attribute allows documentation to be set to Rest implementation constructs.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.Property,
AllowMultiple = true, Inherited = true)]
public class RestDocumentationAttribute : Attribute
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="doc">The documentation string.</param>
/// <param name="format">A media type for the documentation string. Default is text/plain.</param>
public RestDocumentationAttribute(string doc, string format = "text/plain") : base()
{
Documentation = doc;
Format = format;
}
/// <summary>
/// The documentation string.
/// </summary>
public string Documentation { get; set; }
/// <summary>
/// The media type for the documentation string.
/// </summary>
public string Format { get; set; }
}
}
| 35.147059 | 157 | 0.621757 | [
"MIT"
] | joost-morsink/Rest | Biz.Morsink.Rest/RestDocumentationAttribute.cs | 1,197 | C# |
using DemoSqlForms.Database.Model;
using Platz.SqlForms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DemoSqlForms.App.Forms
{
public class StudentListForm : DataServiceBase<SchoolContext>
{
protected override void Define(DataServiceFormBuilder builder)
{
builder.Entity<StudentDetails>(e =>
{
e.ExcludeAll();
e.Property(p => p.ID).IsPrimaryKey();
e.Property(p => p.FirstMidName);
e.Property(p => p.LastName);
e.Property(p => p.EnrollmentDate).Format("dd-MMM-yyyy");
e.Property(p => p.EnrollmentCount);
// Parameter {0} is always PrimaryKey, parameters {1} and above - Filter Keys
// {0} = AddressId {1} = CustomerId
e.ContextButton("Edit", "StudentEdit/{0}").ContextButton("Delete", "StudentDelete/{0}").ContextButton("Enrollments", "EnrollmentList/{0}");
e.DialogButton("StudentEdit/0", ButtonActionTypes.Add);
});
builder.SetListMethod(GetStudentList);
}
public class StudentDetails : Student
{
public int EnrollmentCount { get; set; }
}
public List<StudentDetails> GetStudentList(params object[] parameters)
{
using (var db = GetDbContext())
{
var query =
from s in db.Student
select new StudentDetails
{
ID = s.ID,
FirstMidName = s.FirstMidName,
LastName = s.LastName,
EnrollmentDate = s.EnrollmentDate,
EnrollmentCount = (db.Enrollment.Where(e => e.StudentID == s.ID).Count())
};
var result = query.ToList();
return result;
}
}
}
}
| 31.265625 | 155 | 0.523738 | [
"MIT"
] | euklad/BlogCode | DemoSqlForms-story6/DemoSqlForms.App/Forms/StudentListForm.cs | 2,003 | C# |
using BussinessLogicLayer;
using DataAcessLayer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ApplicationLayer
{
public partial class UserDashBoardForm : Form
{
readonly MasterAccModel masterAcc;
public UserDashBoardForm()
{
InitializeComponent();
}
public UserDashBoardForm(MasterAccModel masterAcc)
{
InitializeComponent();
this.masterAcc = masterAcc;
}
private void DisableButton(bool val)
{
deletePassBtn.Enabled = val;
updatePassBtn.Enabled = val;
viewSelectedPassBtn.Enabled = val;
}
private void ResetView()
{
List<PassAccModel> passAccModels = null;
passDataGridView.DataSource = null;
int count = 1;
SQLiteConnector db = new SQLiteConnector();
passAccModels = db.GetPassAcc(masterAcc.id);
if (passAccModels != null)
{
passDataGridView.DataSource = passAccModels.Select(o => new { Sl = count++, Title = o.title, Link = o.link, Password = o.password, ID = o.id }).ToList();
passDataGridView.AutoGenerateColumns = false;
passDataGridView.Columns["ID"].Visible = false;
passDataGridView.ClearSelection();
}
passDataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(passDataGridView_CellFormatting);
}
private void passDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 3 && e.Value != null)
{
e.Value = new String('●', e.Value.ToString().Length);
}
}
private void storeNewPassBtn_Click(object sender, EventArgs e)
{
DisableButton(false);
StoreNewPassForm storeNewPass = new StoreNewPassForm(this.masterAcc);
DialogResult r = storeNewPass.ShowDialog();
if (r == DialogResult.Cancel)
{
ResetView();
}
}
private void UserDashBoardForm_Load(object sender, EventArgs e)
{
ResetView();
DisableButton(false);
}
private void deletePassBtn_Click(object sender, EventArgs e)
{
string msg = "Are you sure ?. This is going to delete all information of this stored password.";
DialogResult r = ValidationMessage.QuestionMsg(msg);
if (r == DialogResult.Yes)
{
if (passDataGridView.SelectedRows.Count >= 1)
{
int pass_id = (int)passDataGridView.SelectedRows[0].Cells[4].Value;
SQLiteConnector db = new SQLiteConnector();
PassAccModel passAcc = db.GetAccInfo(pass_id, masterAcc.id);
if (passAcc != null)
{
db.RemovePass(passAcc);
r = ValidationMessage.SucessMsgResult("Password deleted sucessfully");
if (r == DialogResult.OK)
{
ResetView();
DisableButton(false);
}
}
}
}
}
private void passDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
DisableButton(true);
}
private void signOutBtn_Click(object sender, EventArgs e)
{
Close();
}
private void UserDashBoardForm_FormClosed(object sender, FormClosedEventArgs e)
{
var form = (SignInForm)Tag;
var mainform = (StartForm)form.Tag;
mainform.Show();
}
private void viewSelectedPassBtn_Click(object sender, EventArgs e)
{
SignInForm loginForm = new SignInForm(true, masterAcc.id);
DialogResult r = loginForm.ShowDialog();
if (r == DialogResult.Cancel)
{
var output = loginForm.MasterAcc;
if (output is MasterAccModel && output.id == masterAcc.id)
{
if (passDataGridView.SelectedRows.Count >= 1)
{
int pass_id = (int)passDataGridView.SelectedRows[0].Cells[4].Value;
SQLiteConnector db = new SQLiteConnector();
PassAccModel passAcc = db.GetAccInfo(pass_id, output.id);
if (passAcc != null)
{
string e_pass = passAcc.password;
passAcc.password = EncryptPass.Decrypt(e_pass, output.master_password);
ViewPassForm viewPassForm = new ViewPassForm(passAcc);
DialogResult res = viewPassForm.ShowDialog();
if (res == DialogResult.Cancel)
{
ResetView();
DisableButton(false);
}
}
}
}
}
}
private void updatePassBtn_Click(object sender, EventArgs e)
{
SignInForm loginForm = new SignInForm(true, masterAcc.id);
DialogResult r = loginForm.ShowDialog();
if (r == DialogResult.Cancel)
{
var output = loginForm.MasterAcc;
if (output is MasterAccModel && output.id == masterAcc.id)
{
if (passDataGridView.SelectedRows.Count >= 1)
{
int pass_id = (int)passDataGridView.SelectedRows[0].Cells[4].Value;
SQLiteConnector db = new SQLiteConnector();
PassAccModel passAcc = db.GetAccInfo(pass_id, output.id);
if (passAcc != null)
{
string e_pass = passAcc.password;
passAcc.password = EncryptPass.Decrypt(e_pass, output.master_password);
UpdatePassForm updatePassForm = new UpdatePassForm(passAcc, output);
DialogResult res = updatePassForm.ShowDialog();
if (res == DialogResult.Cancel)
{
ResetView();
DisableButton(false);
}
}
}
}
}
}
private void updateAccountBtn_Click(object sender, EventArgs e)
{
UpdateMasterAccForm updateMasterAccForm = new UpdateMasterAccForm(masterAcc);
DialogResult r = updateMasterAccForm.ShowDialog();
if (r == DialogResult.Cancel)
{
ResetView();
DisableButton(false);
}
}
private void viewAccountBtn_Click(object sender, EventArgs e)
{
ViewUserAccountForm viewUserAccount = new ViewUserAccountForm(masterAcc);
DialogResult r = viewUserAccount.ShowDialog();
if (r == DialogResult.Cancel)
{
ResetView();
DisableButton(false);
}
}
}
}
| 35.583333 | 169 | 0.511449 | [
"MIT"
] | Anindra123/PasswordManagementApp | ApplicationLayer/UserDashBoardForm.cs | 7,690 | C# |
/* The MIT License (MIT)
*
* Copyright (c) 2014 Pawel Drozdowski
*
* 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.
*/
namespace TspLibNet.Graph.Edges
{
using System;
using System.Collections.Generic;
using System.Linq;
using TspLibNet.Graph.Nodes;
/// <summary>
/// Strongly typed edges collection
/// </summary>
public class EdgesCollection
{
private readonly List<IEdge> _allEdges;
private readonly Dictionary<int, List<IEdge>> _firstIdToEdges;
private readonly Dictionary<int, List<IEdge>> _secondIdToEdges;
private readonly Dictionary<int, Dictionary<int, IEdge>> _idsToEdge;
/// <summary>
/// Gets the number of elements contained in the collection.
/// </summary>
public int Count => _allEdges.Count;
/// <summary>
/// Creates new instance of EdgesCollection
/// </summary>
public EdgesCollection()
{
_allEdges = new List<IEdge>();
_firstIdToEdges = new Dictionary<int, List<IEdge>>();
_secondIdToEdges = new Dictionary<int, List<IEdge>>();
_idsToEdge = new Dictionary<int, Dictionary<int, IEdge>>();
}
/// <summary>
/// Creates new instance of EdgesCollection
/// </summary>
/// <param name="edges">range of edges to add initially</param>
public EdgesCollection(IEnumerable<IEdge> edges)
{
_allEdges = edges.ToList();
_firstIdToEdges = new Dictionary<int, List<IEdge>>(_allEdges.Count);
AddToDictionary(_firstIdToEdges, _allEdges, n => n.First.Id);
_secondIdToEdges = new Dictionary<int, List<IEdge>>(_allEdges.Count);
AddToDictionary(_secondIdToEdges, _allEdges, n => n.Second.Id);
_idsToEdge = new Dictionary<int, Dictionary<int, IEdge>>();
foreach (var edge in _allEdges)
{
AddEdge(edge, edge.First, edge.Second);
AddEdge(edge, edge.Second, edge.First);
}
}
/// <summary>
/// Creates new instance of EdgesCollection
/// </summary>
/// <param name="edges1">range of edges to add initially</param>
/// <param name="edges2">range of edges to add initially</param>
private EdgesCollection(IEnumerable<IEdge> edges1, IEnumerable<IEdge> edges2)
{
_allEdges = edges1.ToList();
_allEdges.AddRange(edges2);
_firstIdToEdges = new Dictionary<int, List<IEdge>>(_allEdges.Count);
AddToDictionary(_firstIdToEdges, _allEdges, n => n.First.Id);
_secondIdToEdges = new Dictionary<int, List<IEdge>>(_allEdges.Count);
AddToDictionary(_secondIdToEdges, _allEdges, n => n.Second.Id);
_idsToEdge = new Dictionary<int, Dictionary<int, IEdge>>();
foreach (var edge in _allEdges)
{
AddEdge(edge, edge.First, edge.Second);
AddEdge(edge, edge.Second, edge.First);
}
}
private static void AddToDictionary(IDictionary<int, List<IEdge>> dictionary, IEnumerable<IEdge> source, Func<IEdge, int> keySelector)
{
foreach (var element in source)
{
var key = keySelector(element);
var found = dictionary.TryGetValue(key, out var edges);
if (found)
{
edges.Add(element);
}
else
{
dictionary.Add(key, new List<IEdge> { element });
}
}
}
private void AddEdge(IEdge edge, INode left, INode right)
{
var found = _idsToEdge.TryGetValue(left.Id, out var existingDictionary);
if (found)
{
existingDictionary.Add(right.Id, edge);
}
else
{
var newDictionary = new Dictionary<int, IEdge> { { right.Id, edge } };
_idsToEdge.Add(left.Id, newDictionary);
}
}
/// <summary>
/// Find edge by given pair of nodes
/// </summary>
/// <param name="first">edge first node</param>
/// <param name="second">edge second node</param>
/// <returns>edge on given pair of nodes or null</returns>
public IEdge FindEdge(INode first, INode second)
{
var firstFound = _idsToEdge.TryGetValue(first.Id, out var secondDictionary);
if (!firstFound)
return null;
var secondFound = secondDictionary.TryGetValue(second.Id, out var edge);
return secondFound ? edge : null;
}
/// <summary>
/// Find edge with given node
/// </summary>
/// <param name="node">The node to filter edges by</param>
/// <returns>Node with given id or null</returns>
public EdgesCollection FilterByNode(INode node)
{
var nodeId = node.Id;
var firstEdges = _firstIdToEdges[nodeId];
var secondEdges = _secondIdToEdges[nodeId];
var result = new EdgesCollection(firstEdges, secondEdges);
return result;
}
/// <summary>
/// Gets a list of all edges.
/// </summary>
/// <returns>The list of edges</returns>
public List<IEdge> ToList()
{
return _allEdges;
}
}
} | 37.502793 | 143 | 0.575898 | [
"MIT"
] | pdrozdowski/TSPLib.Net | TspLibNet/TspLibNet/Graph/Edges/EdgesCollection.cs | 6,715 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2016 Ingo Herbote
* http://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Modules
{
#region Using
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.EventProxies;
using YAF.Types.Interfaces;
#endregion
/// <summary>
/// The search data cleanup module.
/// </summary>
public class SearchDataCleanupForumModule : SimpleBaseForumModule
{
#region Fields
/// <summary>
/// The _page pre load.
/// </summary>
private readonly IFireEvent<ForumPagePreLoadEvent> _pagePreLoad;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="SearchDataCleanupForumModule" /> class.
/// </summary>
/// <param name="pagePreLoad">
/// The page pre load.
/// </param>
public SearchDataCleanupForumModule([NotNull] IFireEvent<ForumPagePreLoadEvent> pagePreLoad)
{
this._pagePreLoad = pagePreLoad;
this._pagePreLoad.HandleEvent += this._pagePreLoad_HandleEvent;
}
#endregion
#region Methods
/// <summary>
/// _pages the pre load_ handle event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void _pagePreLoad_HandleEvent([NotNull] object sender, [NotNull] EventConverterArgs<ForumPagePreLoadEvent> e)
{
// no security features for login/logout pages
if (this.ForumPageType == ForumPages.search || this.ForumPageType == ForumPages.posts)
{
return;
}
// clear out any search data in the session.... just in case...
this.Get<IYafSession>().SearchData = null;
}
#endregion
}
} | 32.806818 | 126 | 0.621753 | [
"Apache-2.0"
] | hismightiness/YAFNET | yafsrc/YetAnotherForum.NET/Modules/SearchDataCleanupForumModule.cs | 2,801 | C# |
namespace Responsible.Tests.Utilities
{
public class TestDataBase
{
public readonly int Value;
public TestDataBase(int value)
{
this.Value = value;
}
}
}
| 13 | 37 | 0.704142 | [
"MIT"
] | YousicianGit/Responsible | Tests/Utilities/TestDataBase.cs | 169 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using EnsureThat;
using Hl7.Fhir.Model;
using Microsoft.Health.DicomCast.Core.Features.Worker.FhirTransaction;
namespace Microsoft.Health.DicomCast.Core.Extensions;
public static class ResourceExtensions
{
public static ServerResourceId ToServerResourceId(this Resource resource)
{
EnsureArg.IsNotNull(resource, nameof(resource));
return new ServerResourceId(resource.TypeName, resource.Id);
}
}
| 37.47619 | 101 | 0.575604 | [
"MIT"
] | IoTFier/dicom-server | converter/dicom-cast/src/Microsoft.Health.DicomCast.Core/Extensions/ResourceExtensions.cs | 789 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using Wenli.Data.Es.Base.Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Wenli.Data.Es.Base.Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> to use the specified <see cref="JsonConverter"/> when serializing the member or class.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class JsonConverterAttribute : Attribute
{
private readonly Type _converterType;
/// <summary>
/// Gets the type of the converter.
/// </summary>
/// <value>The type of the converter.</value>
public Type ConverterType
{
get { return _converterType; }
}
/// <summary>
/// The parameter list to use when constructing the JsonConverter described by ConverterType.
/// If null, the default constructor is used.
/// </summary>
public object[] ConverterParameters { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonConverterAttribute"/> class.
/// </summary>
/// <param name="converterType">Type of the converter.</param>
public JsonConverterAttribute(Type converterType)
{
if (converterType == null)
throw new ArgumentNullException("converterType");
_converterType = converterType;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonConverterAttribute"/> class.
/// </summary>
/// <param name="converterType">Type of the converter.</param>
/// <param name="converterParameters">Parameter list to use when constructing the JsonConverter. Can be null.</param>
public JsonConverterAttribute(Type converterType, params object[] converterParameters)
: this(converterType)
{
ConverterParameters = converterParameters;
}
}
} | 42.269231 | 228 | 0.685775 | [
"Apache-2.0"
] | yswenli/Wenli.Data.Es | Wenli.Data.Es/Base/Newtonsoft.Json/JsonConverterAttribute.cs | 3,299 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.