content stringlengths 23 1.05M |
|---|
using UnityEngine;
using UnityEngine.Events;
namespace SHMUP.Events
{
public class OnTriggerStay2DEvent : MonoBehaviour
{
public UnityEvent<Collider2D> onTriggerStay2D = new UnityEvent<Collider2D>();
void OnTriggerStay2D(Collider2D collision)
{
if (onTriggerStay2D == null)
return;
onTriggerStay2D.Invoke(collision);
}
}
} |
/*
Copyright 2011 Google 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.
*/
using System.CodeDom;
using Google.Apis.Discovery;
using Google.Apis.Testing;
namespace Google.Apis.Tools.CodeGen.Decorator.ResourceDecorator.RequestDecorator
{
/// <summary>
/// A decorator which implements abstract properties of the ServiceRequest class
///
/// Example:
/// <c>protected override string ResourceName { get { return ...; } } </c>
/// <c>protected override string MethodName { get { return ...; } } </c>
/// </summary>
public class ServiceRequestFieldDecorator : IRequestDecorator
{
#region IRequestDecorator Members
public void DecorateClass(IResource resource,
IMethod request,
CodeTypeDeclaration requestClass,
CodeTypeDeclaration resourceClass)
{
// protected override string ResourceName { get { ... } }
CodeMemberProperty property = GenerateStringConstantPropertyOverride(
"ResourcePath", resource.Path);
requestClass.Members.Add(property);
// protected override string MethodName { get { ... } }
property = GenerateStringConstantPropertyOverride("MethodName", request.Name);
requestClass.Members.Add(property);
}
#endregion
/// <summary>
/// Generates a property which will return a constant string.
/// Will not do a used-name check. Assumes the name can be chosen.
/// Example:
/// <c>protected override string PropertyName { get { ... } }</c>
/// </summary>
[VisibleForTestOnly]
internal static CodeMemberProperty GenerateStringConstantPropertyOverride(string propertyName,
string returnValue)
{
var property = new CodeMemberProperty();
property.Name = propertyName;
property.Type = new CodeTypeReference(typeof(string));
property.Attributes = MemberAttributes.Family | MemberAttributes.Override; // "protected".
property.HasGet = true;
// get { return "..."; }
var returnString = new CodePrimitiveExpression(returnValue);
property.GetStatements.Add(new CodeMethodReturnStatement(returnString));
return property;
}
}
} |
using Newtonsoft.Json;
namespace BoxOptions.CoefficientCalculator.Algo
{
[JsonObject(MemberSerialization.OptIn)]
internal class BoxOption
{
// Transient (ScriptIgnoreAttribute)
private long _startsInMS;
private long _lenInMS;
private double _relatUpStrike;
private double _relatBotStrike;
private double _hitCoeff;
private double _missCoeff;
public BoxOption(long startsInMS, long lenInMS, double relatUpStrike, double relatBotStrike)
{
_startsInMS = startsInMS;
_lenInMS = lenInMS;
_relatUpStrike = relatUpStrike;
_relatBotStrike = relatBotStrike;
}
[JsonProperty]
public double HitCoeff { get => _hitCoeff; }
[JsonProperty]
public double MissCoeff { get => _missCoeff; }
public long StartsInMS { get => _startsInMS; }
public long LenInMS { get => _lenInMS; }
public double RelatUpStrike { get => _relatUpStrike; }
public double RelatBotStrike { get => _relatBotStrike; }
public BoxOption CloneBoxOption()
{
BoxOption boxOption = new BoxOption(_startsInMS, _lenInMS, _relatUpStrike, _relatBotStrike)
{
_hitCoeff = this._hitCoeff,
_missCoeff = this._missCoeff,
_relatUpStrike = this._relatUpStrike,
_relatBotStrike = this._relatBotStrike
};
return boxOption;
}
public void SetCoefficients(double[] coefficients)
{
_hitCoeff = coefficients[0];
_missCoeff = coefficients[1];
}
}
}
|
using CodingArena.Annotations;
using CodingArena.Common;
using System;
using System.Configuration;
using System.Windows;
using CodingArena.AI;
namespace CodingArena.Main.Battlefields.FirstAidKits
{
public sealed class FirstAidKit : Collider, IFirstAidKit
{
[NotNull] private readonly Battlefield myBattlefield;
public FirstAidKit([NotNull] Battlefield battlefield, Point position)
{
Radius = 10;
myBattlefield = battlefield ?? throw new ArgumentNullException(nameof(battlefield));
Position = position;
RegenerationAmount = double.Parse(ConfigurationManager.AppSettings["FirstAidKitRegenerationAmount"]);
}
public double RegenerationAmount { get; }
}
} |
using UnityEngine;
using System.Collections;
using System.IO;
public class FileData {
public string fileName;
public long fileSize;
public FileData(string file) {
fileName = file;
fileSize = new System.IO.FileInfo(file).Length;
}
}
|
namespace Appleseed.Services.Base.Engine.Processors.Impl
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Logging;
using SolrNet;
using Appleseed.Services.Base.Engine.Processors.Impl.SolrModel;
using Microsoft.Practices.ServiceLocation;
using java.util;
using System.Threading.Tasks;
public class SolrIndexer : IIndexThings
{
private readonly Common.Logging.ILog logger;
private readonly string indexPath;
public SolrIndexer(ILog logger, string pathToIndex)
{
if (logger == null)
{
throw new ArgumentNullException("logger");
}
if (string.IsNullOrEmpty(pathToIndex))
{
throw new ArgumentNullException("pathToIndex");
}
this.indexPath = pathToIndex;
this.logger = logger;
}
public void Build(IEnumerable<Model.AppleseedModuleItemIndex> indexableData)
{
if (indexableData.Count().Equals(0))
{
throw new Exception("Nothing to index");
}
try {
//Initialize the solr server
Startup.Init<SolrItem>(indexPath);
}
catch (Exception exc){}
ISolrOperations<SolrItem> solr = ServiceLocator.Current.GetInstance<ISolrOperations<SolrItem>>();
// grouping the results
List<SolrItem> solrResults = null;
List<List<SolrItem>> listResults = new List<List<SolrItem>>();
int size = 0;
int count = 0;
int errorCount = 0;
foreach (var data in indexableData)
{
if (size == 0)
{
solrResults = new List<SolrItem>();
}
count++;
if (!string.IsNullOrEmpty(data.Key) || !string.IsNullOrEmpty(data.Name))
{
var solrItem = new SolrItem
{
Key = data.Key,
Path = data.Path,
Name = data.Name,
Content = data.Content,
Summary = data.Summary,
SmartKeywords = data.SmartKeywords,
Type = data.Type,
ViewRoles = data.ViewRoles,
PortalID = data.PortalID,
ModuleID = data.ModuleID,
PageID = data.PageID,
FileSize = data.FileSize,
CreatedDate = DateTime.Parse(data.CreatedDate),
Source = data.Source
};
solrResults.Add(solrItem);
size++;
if (size == 3 || count == indexableData.Count())
{
size = 0;
listResults.Add(new List<SolrItem>(solrResults));
}
}
else
errorCount++;
}
// Sequencial Indexing
/*
int index = 0;
foreach (var list in listResults)
{
index++;
logger.Info("List " + index + ". Index Start: ");
try
{
solr.AddRange(list);
solr.Optimize();
}
catch (Exception e)
{
logger.Info("List " + index + ". Index End EXCEPTION : " + string.Empty);
logger.Error(e.Message);
}
logger.Info("List " + index + ". Index End : " + string.Empty);
}
*/
AddParameters addParameters = new AddParameters { Overwrite = true };
// Parallel Indexing
Parallel.ForEach(listResults, group => solr.AddRange(group, addParameters));
solr.Optimize();
logger.Info("----------------INDEXER SUMMARY--------------------------------");
logger.Info("Success Count: " + (count - errorCount).ToString());
logger.Info("Error Count: " + errorCount.ToString());
logger.Info("----------------INDEXER SUMMARY--------------------------------");
}
}
}
|
// Copyright (c) 2021 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using ReactiveUI.Validation.Collections;
using ReactiveUI.Validation.Components;
using ReactiveUI.Validation.Extensions;
using ReactiveUI.Validation.Formatters.Abstractions;
using ReactiveUI.Validation.Helpers;
using ReactiveUI.Validation.Tests.Models;
using Xunit;
namespace ReactiveUI.Validation.Tests
{
/// <summary>
/// Tests for INotifyDataErrorInfo support.
/// </summary>
public class NotifyDataErrorInfoTests
{
private const string NameShouldNotBeEmptyMessage = "Name shouldn't be empty.";
/// <summary>
/// Verifies that the ErrorsChanged event fires on ViewModel initialization.
/// </summary>
[Fact]
public void ShouldMarkPropertiesAsInvalidOnInit()
{
var viewModel = new IndeiTestViewModel();
var view = new IndeiTestView(viewModel);
using var firstValidation = new BasePropertyValidation<IndeiTestViewModel, string>(
viewModel,
vm => vm.Name,
s => !string.IsNullOrEmpty(s),
NameShouldNotBeEmptyMessage);
viewModel.ValidationContext.Add(firstValidation);
view.Bind(view.ViewModel, vm => vm.Name, v => v.NameLabel);
view.BindValidation(view.ViewModel, vm => vm.Name, v => v.NameErrorLabel);
// Verify validation context behavior.
Assert.False(viewModel.ValidationContext.IsValid);
Assert.Single(viewModel.ValidationContext.Validations);
Assert.Equal(NameShouldNotBeEmptyMessage, view.NameErrorLabel);
// Verify INotifyDataErrorInfo behavior.
Assert.True(viewModel.HasErrors);
Assert.Equal(NameShouldNotBeEmptyMessage, viewModel.GetErrors("Name").Cast<string>().First());
}
/// <summary>
/// Verifies that the view model listens to the INotifyPropertyChanged event
/// and sends INotifyDataErrorInfo notifications.
/// </summary>
[Fact]
public void ShouldSynchronizeNotifyDataErrorInfoWithValidationContext()
{
var viewModel = new IndeiTestViewModel();
var view = new IndeiTestView(viewModel);
using var firstValidation = new BasePropertyValidation<IndeiTestViewModel, string>(
viewModel,
vm => vm.Name,
s => !string.IsNullOrEmpty(s),
NameShouldNotBeEmptyMessage);
viewModel.ValidationContext.Add(firstValidation);
view.Bind(view.ViewModel, vm => vm.Name, v => v.NameLabel);
view.BindValidation(view.ViewModel, vm => vm.Name, v => v.NameErrorLabel);
// Verify the initial state.
Assert.True(viewModel.HasErrors);
Assert.False(viewModel.ValidationContext.IsValid);
Assert.Single(viewModel.ValidationContext.Validations);
Assert.Equal(NameShouldNotBeEmptyMessage, viewModel.GetErrors("Name").Cast<string>().First());
Assert.Equal(NameShouldNotBeEmptyMessage, view.NameErrorLabel);
// Send INotifyPropertyChanged.
viewModel.Name = "JoJo";
// Verify the changed state.
Assert.False(viewModel.HasErrors);
Assert.True(viewModel.ValidationContext.IsValid);
Assert.Empty(viewModel.GetErrors("Name").Cast<string>());
Assert.Empty(view.NameErrorLabel);
// Send INotifyPropertyChanged.
viewModel.Name = string.Empty;
// Verify the changed state.
Assert.True(viewModel.HasErrors);
Assert.False(viewModel.ValidationContext.IsValid);
Assert.Single(viewModel.ValidationContext.Validations);
Assert.Equal(NameShouldNotBeEmptyMessage, viewModel.GetErrors("Name").Cast<string>().First());
Assert.Equal(NameShouldNotBeEmptyMessage, view.NameErrorLabel);
}
/// <summary>
/// The ErrorsChanged event should fire when properties change.
/// </summary>
[Fact]
public void ShouldFireErrorsChangedEventWhenValidationStateChanges()
{
var viewModel = new IndeiTestViewModel();
DataErrorsChangedEventArgs arguments = null;
viewModel.ErrorsChanged += (_, args) => arguments = args;
using var firstValidation = new BasePropertyValidation<IndeiTestViewModel, string>(
viewModel,
vm => vm.Name,
s => !string.IsNullOrEmpty(s),
NameShouldNotBeEmptyMessage);
viewModel.ValidationContext.Add(firstValidation);
Assert.True(viewModel.HasErrors);
Assert.False(viewModel.ValidationContext.IsValid);
Assert.Single(viewModel.ValidationContext.Validations);
Assert.Single(viewModel.GetErrors("Name").Cast<string>());
viewModel.Name = "JoJo";
Assert.False(viewModel.HasErrors);
Assert.Empty(viewModel.GetErrors("Name").Cast<string>());
Assert.NotNull(arguments);
Assert.Equal("Name", arguments.PropertyName);
}
/// <summary>
/// Using ModelObservableValidation with NotifyDataErrorInfo should return errors when associated property changes.
/// </summary>
[Fact]
public void ShouldDeliverErrorsWhenModelObservableValidationTriggers()
{
var viewModel = new IndeiTestViewModel();
const string namesShouldMatchMessage = "names should match.";
viewModel.ValidationRule(
vm => vm.OtherName,
viewModel.WhenAnyValue(
m => m.Name,
m => m.OtherName,
(name, other) => name == other),
namesShouldMatchMessage);
Assert.False(viewModel.HasErrors);
Assert.True(viewModel.ValidationContext.IsValid);
Assert.Single(viewModel.ValidationContext.Validations);
Assert.Empty(viewModel.GetErrors(nameof(viewModel.Name)).Cast<string>());
Assert.Empty(viewModel.GetErrors(nameof(viewModel.OtherName)).Cast<string>());
viewModel.Name = "JoJo";
viewModel.OtherName = "NoNo";
Assert.True(viewModel.HasErrors);
Assert.Empty(viewModel.GetErrors(nameof(viewModel.Name)).Cast<string>());
Assert.Single(viewModel.GetErrors(nameof(viewModel.OtherName)).Cast<string>());
Assert.Single(viewModel.ValidationContext.Text);
Assert.Equal(namesShouldMatchMessage, viewModel.ValidationContext.Text.Single());
}
/// <summary>
/// Verifies that validation rules of the same property do not duplicate.
/// Earlier they sometimes could, due to the .Connect() method misuse.
/// </summary>
[Fact]
public void ValidationRulesOfTheSamePropertyShouldNotDuplicate()
{
var viewModel = new IndeiTestViewModel();
viewModel.ValidationRule(
m => m.Name,
m => m is not null,
"Name shouldn't be null.");
viewModel.ValidationRule(
m => m.Name,
m => !string.IsNullOrWhiteSpace(m),
"Name shouldn't be white space.");
Assert.False(viewModel.ValidationContext.IsValid);
Assert.Equal(2, viewModel.ValidationContext.Validations.Count);
}
/// <summary>
/// Verifies that the <see cref="INotifyDataErrorInfo"/> events are published
/// according to the changes of the validated properties.
/// </summary>
[Fact]
public void ShouldSendPropertyChangeNotificationsForCorrectProperties()
{
var viewModel = new IndeiTestViewModel();
viewModel.ValidationRule(
m => m.Name,
m => m is not null,
"Name shouldn't be null.");
viewModel.ValidationRule(
m => m.OtherName,
m => m is not null,
"Other name shouldn't be null.");
Assert.Single(viewModel.GetErrors(nameof(viewModel.Name)));
Assert.Single(viewModel.GetErrors(nameof(viewModel.OtherName)));
var arguments = new List<DataErrorsChangedEventArgs>();
viewModel.ErrorsChanged += (_, args) => arguments.Add(args);
viewModel.Name = "Josuke";
viewModel.OtherName = "Jotaro";
Assert.Equal(2, arguments.Count);
Assert.Equal(nameof(viewModel.Name), arguments[0].PropertyName);
Assert.Equal(nameof(viewModel.OtherName), arguments[1].PropertyName);
Assert.False(viewModel.HasErrors);
viewModel.Name = null;
viewModel.OtherName = null;
Assert.Equal(4, arguments.Count);
Assert.Equal(nameof(viewModel.Name), arguments[2].PropertyName);
Assert.Equal(nameof(viewModel.OtherName), arguments[3].PropertyName);
Assert.True(viewModel.HasErrors);
}
/// <summary>
/// Verifies that we detach and dispose the disposable validations once the
/// <see cref="ValidationHelper"/> is disposed. Also, here we ensure that
/// the property change subscriptions are unsubscribed.
/// </summary>
[Fact]
public void ShouldDetachAndDisposeTheComponentWhenValidationHelperDisposes()
{
var view = new IndeiTestView(new IndeiTestViewModel { Name = string.Empty });
var arguments = new List<DataErrorsChangedEventArgs>();
view.ViewModel.ErrorsChanged += (_, args) => arguments.Add(args);
var helper = view
.ViewModel
.ValidationRule(
viewModel => viewModel.Name,
name => !string.IsNullOrWhiteSpace(name),
"Name shouldn't be empty.");
Assert.Equal(1, view.ViewModel.ValidationContext.Validations.Count);
Assert.False(view.ViewModel.ValidationContext.IsValid);
Assert.True(view.ViewModel.HasErrors);
Assert.Equal(1, arguments.Count);
Assert.Equal(nameof(view.ViewModel.Name), arguments[0].PropertyName);
helper.Dispose();
Assert.Equal(0, view.ViewModel.ValidationContext.Validations.Count);
Assert.True(view.ViewModel.ValidationContext.IsValid);
Assert.False(view.ViewModel.HasErrors);
Assert.Equal(2, arguments.Count);
Assert.Equal(nameof(view.ViewModel.Name), arguments[1].PropertyName);
}
/// <summary>
/// Verifies that we support custom formatters in our <see cref="INotifyDataErrorInfo"/> implementation.
/// </summary>
[Fact]
public void ShouldInvokeCustomFormatters()
{
var formatter = new PrefixFormatter("Validation error:");
var view = new IndeiTestView(new IndeiTestViewModel(formatter) { Name = string.Empty });
var arguments = new List<DataErrorsChangedEventArgs>();
view.ViewModel.ErrorsChanged += (_, args) => arguments.Add(args);
view.ViewModel.ValidationRule(
viewModel => viewModel.Name,
name => !string.IsNullOrWhiteSpace(name),
"Name shouldn't be empty.");
Assert.Equal(1, view.ViewModel.ValidationContext.Validations.Count);
Assert.False(view.ViewModel.ValidationContext.IsValid);
Assert.True(view.ViewModel.HasErrors);
var errors = view.ViewModel
.GetErrors("Name")
.Cast<string>()
.ToArray();
Assert.Single(errors);
Assert.Equal("Validation error: Name shouldn't be empty.", errors[0]);
}
private class PrefixFormatter : IValidationTextFormatter<string>
{
private readonly string _prefix;
public PrefixFormatter(string prefix) => _prefix = prefix;
public string Format(ValidationText validationText) => $"{_prefix} {validationText.ToSingleLine()}";
}
}
}
|
using System.Windows.Input;
namespace Xmf2.Common.Extensions
{
public static class CommandExtensions
{
public static void TryExecute(this ICommand command, object parameter = null)
{
if (command != null && command.CanExecute(parameter))
{
command.Execute(parameter);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using TCCarShare.IServices;
using TCCarShare.Entity.Request;
using TCCarShare.Entity.Response;
using TCCarShare.Models;
using TCCarShare.Services;
using TC.ZBY.FrameworkCore.Utility;
using TCCarShare.Data;
using TCCarShare.Models.Request;
namespace TCCarShare.Controllers
{
[Route("[controller]")]
public partial class CarController : Controller
{
private readonly CarServices _repository;
private readonly DataContext _context;
public CarController(CarServices repository, DataContext context)
{
_repository = repository;
_context = context;
}
[HttpGet("GetCarInfoByEmpId")]
public string GetCarInfoByEmpId(int empId)
{
GetCarInfoByEmpIdResponse res = new GetCarInfoByEmpIdResponse();
res.ResultMsg = "success";
res.StateCode = 200;
res.Car = _repository.GetByEmpId(empId) ?? new Car();
if(res.Car == null || res.Car.id<=0)
{
res.ResultMsg = "no data";
res.StateCode = 200;
}
return JsonConvert.SerializeObject(res);
}
[HttpPost("EditCarInfo")]
public string EditCarInfo([FromBody]EditCarInfoRequest request)
{
var result = new CommonBaseInfo();
if (request.id.PackInt() > 0)
{
var model = _repository.GetById(request.id.PackInt());
if (model == null)
{
result.ResultMsg = "未查询到车辆信息";
result.StateCode = 404;
return JsonConvert.SerializeObject(result);
}
Car newCar = new Car
{
id = Convert.ToInt32(request.id),
carBrand = request.carBrand,
carColor = request.carColor,
carLicenseImg = request.carLicenseImg,
carMasterId = request.carMasterId.PackInt(),
carNo = request.carNo,
carSeatNum = request.carSeatNum.PackInt(),
carType = request.carType.PackInt()
};
var update = _repository.Edit(newCar);
if(update)
{
result.ResultMsg = "编辑成功";
result.StateCode = 200;
}
}
else
{
Car newCar = new Car
{
carBrand = request.carBrand,
carColor = request.carColor,
carLicenseImg = request.carLicenseImg,
carMasterId = request.carMasterId.PackInt(),
carNo = request.carNo,
carSeatNum = request.carSeatNum.PackInt(),
carType = request.carType.PackInt()
};
var add = _repository.Add(newCar);
if (add == null)
{
result.ResultMsg = "新增失败";
result.StateCode = 201;
return JsonConvert.SerializeObject(result);
}
result.ResultMsg = "新增成功";
result.StateCode = 200;
}
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 关键词输入提示
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("GetSuggestionList")]
public string GetSuggestionList([FromBody]GetSuggestionListRequest request)
{
var result = new MapServices(_context).GetSuggestionList(request);
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 逆地址解析
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("GetAddressBylnglat")]
public string GetAddressBylnglat([FromBody]GeocoderRequest request)
{
var result = new MapServices(_context).GetAddressBylnglat(request);
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 获取路线金额
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("GetMoneyNumber")]
public string GetMoneyNumber([FromBody]GetMoneyNumberResquest request)
{
var result = new MapServices(_context).GetMoneyNumber(request);
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 司机选单列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("GetOrderListByDriver")]
public string GetOrderListByDriver([FromBody]GetOrderListByDriverRequest request)
{
var result = new MapServices(_context).GetOrderListByDriver(request);
return JsonConvert.SerializeObject(result);
}
}
} |
using ProtocolSharp.Types;
using ProtocolSharp.Utils;
namespace ProtocolSharp.Entities.Entities
{
public class ArmorStand : LivingEntity
{
public override EntityType Type => EntityType.ArmorStand;
public override float BoundingBoxX
{
get
{
if (IsSmall) return 0.25f;
return IsMarker ? 0.0f : 0.5f;
}
}
public override float BoundingBoxY
{
get
{
if (IsSmall) return 0.9875f;
return IsMarker ? 0.0f : 1.975f;
}
}
public override Identifier ID => new Identifier("armor_stand");
public override bool UseWithSpawnObject => true;
public override void RegisterMetadata()
{
base.RegisterMetadata();
MetaRegistry.Add(ArmorDetails);
MetaRegistry.Add(HeadRotation);
MetaRegistry.Add(BodyRotation);
MetaRegistry.Add(LeftArmRotation);
MetaRegistry.Add(RightArmRotation);
MetaRegistry.Add(LeftLegRotation);
MetaRegistry.Add(RightLegRotation);
}
private byte _armorDetails = 0;
private const byte _isSmall = 0x01;
private const byte _hasArms = 0x04;
private const byte _hasNoBasePlate = 0x08;
private const byte _isMarker = 0x10;
public EntityMetaByte ArmorDetails =>
new EntityMetaByte
{
Index = 14,
DefaultValue = 0,
Value = _armorDetails
};
public EntityMetadata<Rotation> HeadRotation =
new EntityMetadata<Rotation>
{
Index = 15,
DefaultValue = new Rotation(0.0f, 0.0f, 0.0f)
};
public EntityMetadata<Rotation> BodyRotation =
new EntityMetadata<Rotation>
{
Index = 16,
DefaultValue = new Rotation(0.0f, 0.0f, 0.0f)
};
public EntityMetadata<Rotation> LeftArmRotation =
new EntityMetadata<Rotation>
{
Index = 17,
DefaultValue = new Rotation(-10.0f, 0.0f, -10.0f)
};
public EntityMetadata<Rotation> RightArmRotation =
new EntityMetadata<Rotation>
{
Index = 18,
DefaultValue = new Rotation(-15.0f, 0.0f, 10.0f)
};
public EntityMetadata<Rotation> LeftLegRotation =
new EntityMetadata<Rotation>
{
Index = 19,
DefaultValue = new Rotation(-1.0f, 0.0f, -1.0f)
};
public EntityMetadata<Rotation> RightLegRotation =
new EntityMetadata<Rotation>
{
Index = 20,
DefaultValue = new Rotation(1.0f, 0.0f, 1.0f)
};
#region Armor Details
public bool IsSmall
{
get => FlagsHelper.IsSet(_armorDetails, _isSmall);
set
{
if (value) FlagsHelper.Set(ref _armorDetails, _isSmall);
else FlagsHelper.Unset(ref _armorDetails, _isSmall);
}
}
public bool HasArms
{
get => FlagsHelper.IsSet(_armorDetails, _hasArms);
set
{
if (value) FlagsHelper.Set(ref _armorDetails, _hasArms);
else FlagsHelper.Unset(ref _armorDetails, _hasArms);
}
}
public bool HasNoBasePlate
{
get => FlagsHelper.IsSet(_armorDetails, _hasNoBasePlate);
set
{
if (value) FlagsHelper.Set(ref _armorDetails, _hasNoBasePlate);
else FlagsHelper.Unset(ref _armorDetails, _hasNoBasePlate);
}
}
public bool IsMarker
{
get => FlagsHelper.IsSet(_armorDetails, _isMarker);
set
{
if (value) FlagsHelper.Set(ref _armorDetails, _isMarker);
else FlagsHelper.Unset(ref _armorDetails, _isMarker);
}
}
#endregion
}
} |
using System;
using System.Linq;
using System.Reflection;
using TeeSquare.TypeMetadata;
using TeeSquare.Writers;
using MethodInfo = System.Reflection.MethodInfo;
using PropertyInfo = System.Reflection.PropertyInfo;
namespace TeeSquare.Reflection
{
public class ReflectiveWriterOptions : IReflectiveWriterOptions, ITypeScriptWriterOptions
{
public TypeConverter TypeConverter { get; set; } = new TypeConverter();
public TypeConverter ImportTypeConverter { get; set; } = null;
public BindingFlags PropertyFlags { get; set; } = BindingFlags.GetProperty
| BindingFlags.Public
| BindingFlags.Instance;
public BindingFlags FieldFlags { get; set; } = BindingFlags.Public
| BindingFlags.Instance;
public BindingFlags MethodFlags { get; set; } = BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.DeclaredOnly;
public Func<Type, bool> ReflectMethods { get; set; } = type => false;
public Func<Type, MethodInfo, bool> ReflectMethod { get; set; } = (type, mi) => true;
public string IndentCharacters { get; set; } = " ";
public IEnumWriterFactory EnumWriterFactory { get; set; } = new EnumWriterFactory();
public IInterfaceWriterFactory InterfaceWriterFactory { get; set; } = new InterfaceWriterFactory();
public IClassWriterFactory ClassWriterFactory { get; set; } = new ClassWriterFactory();
public IFunctionWriterFactory FunctionWriterFactory { get; set; } = new FunctionWriterFactory();
public WriteComplexType ComplexTypeStrategy { get; set; } =
(writer, typeInfo) => writer.WriteInterface(typeInfo);
public WriteHeader WriteHeader { get; set; } = writer =>
{
writer.WriteComment("Auto-generated Code - Do Not Edit");
writer.WriteLine();
};
public TypeCollection Types { get; set; } = new TypeCollection();
}
public delegate void WriteComplexType(TypeScriptWriter writer, IComplexTypeInfo complexType);
public delegate void WriteHeader(TypeScriptWriter writer);
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using NUnit.Framework;
using Shouldly;
using Wyam.Common.Documents;
using Wyam.Common.IO;
using Wyam.Common.Meta;
using Wyam.Testing;
using Wyam.Testing.Documents;
using Wyam.Testing.Execution;
namespace Wyam.Html.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.Self | ParallelScope.Children)]
public class MirrorResourcesFixture : BaseFixture
{
public class ExecuteTests : MirrorResourcesFixture
{
[Test]
public void ReplacesScriptResource()
{
// Given
TestExecutionContext context = new TestExecutionContext();
IDocument document = new TestDocument(
@"<html>
<head>
<script src=""https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js""></script>
</head>
<body>
</body>
</html>");
MirrorResources module = new MirrorResources();
// When
List<IDocument> result = module.Execute(new[] { document }, context).ToList();
// Then
result.Single().Content.ShouldBe(
@"<html><head>
<script src=""/mirror/cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js""></script>
</head>
<body>
</body></html>", StringCompareShould.IgnoreLineEndings);
}
[Test]
public void ReplacesLinkResource()
{
// Given
TestExecutionContext context = new TestExecutionContext();
IDocument document = new TestDocument(
@"<html>
<head>
<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/@@progress/kendo-theme-bootstrap@3.2.0/dist/all.min.css"" />
</head>
<body>
</body>
</html>");
MirrorResources module = new MirrorResources();
// When
List<IDocument> result = module.Execute(new[] { document }, context).ToList();
// Then
result.Single().Content.ShouldBe(
@"<html><head>
<link rel=""stylesheet"" href=""/mirror/cdn.jsdelivr.net/npm/@@progress/kendo-theme-bootstrap@3.2.0/dist/all.min.css"">
</head>
<body>
</body></html>", StringCompareShould.IgnoreLineEndings);
}
[Test]
public void DoesNotReplaceDataNoMirrorAttribute()
{
// Given
TestExecutionContext context = new TestExecutionContext();
IDocument document = new TestDocument(
@"<html>
<head>
<script src=""https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js"" data-no-mirror></script>
<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/@@progress/kendo-theme-bootstrap@3.2.0/dist/all.min.css"" data-no-mirror />
</head>
<body>
</body>
</html>");
MirrorResources module = new MirrorResources();
// When
List<IDocument> result = module.Execute(new[] { document }, context).ToList();
// Then
result.Single().Content.ShouldBe(
@"<html>
<head>
<script src=""https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js"" data-no-mirror></script>
<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/@@progress/kendo-theme-bootstrap@3.2.0/dist/all.min.css"" data-no-mirror />
</head>
<body>
</body>
</html>", StringCompareShould.IgnoreLineEndings);
}
[Test]
public void UsesCustomMirrorPath()
{
// Given
TestExecutionContext context = new TestExecutionContext();
IDocument document = new TestDocument(
@"<html>
<head>
<script src=""https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js""></script>
</head>
<body>
</body>
</html>");
MirrorResources module = new MirrorResources(x => new FilePath("/foo/bar.js"));
// When
List<IDocument> result = module.Execute(new[] { document }, context).ToList();
// Then
result.Single().Content.ShouldBe(
@"<html><head>
<script src=""/foo/bar.js""></script>
</head>
<body>
</body></html>", StringCompareShould.IgnoreLineEndings);
}
}
}
}
|
namespace Goofy.Data
{
public class GoofyDataConfiguration
{
public string DataProviderName { get; set; } = "sqlite";
public ConnectionConfiguration DefaultConnection { get; set; } = new ConnectionConfiguration();
}
}
|
using System.Collections.Generic;
using System.Text;
using ALaCart.Data;
using ALaCart.Models;
using ALaCart.Data.Interfaces;
namespace ALaCart.Service
{
public interface IRestaurantService
{
Restaurant GetById(int Id);
ICollection<Restaurant> GetAll();
}
public class RestaurantService : IRestaurantService
{
private readonly IRestaurantRepository _restaurantRepository;
public ICollection<Restaurant> GetAll()
{
return _restaurantRepository.GetAll();
}
public Restaurant GetById(int Id)
{
return _restaurantRepository.GetById(Id);
}
}
}
|
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 Pharmacy_Management
{
public partial class Form1 : Form
{
List <medicine> MEDICINE = new List <medicine> ();
List <accessories> ACCESSORIES = new List <accessories> ();
List <string> INFO = new List<string> ();
int COST = 0;
public Form1()
{
InitializeComponent();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void STOCK_Click(object sender, EventArgs e)
{
medicine dummy = new medicine ();
dummy.Name = Med_name_box.Text;
dummy.Type = Med_type_box.Text;
dummy.Company_name = Med_company_box.Text;
dummy.Production_Date = Med_production_date_box.Text;
dummy.Expired_Date = Med_expired_date_box.Text;
dummy.quantity = Convert.ToInt32 (Med_quantity_box.Text);
dummy.cost = Convert.ToInt32(Med_cost_box.Text);
MEDICINE.Add (dummy);
MessageBox.Show("MEDICINE ADDED");
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void ACC_STOCK_Click(object sender, EventArgs e)
{
accessories dummy = new accessories();
dummy.Name = Acc_name_box.Text;
dummy.Type = Acc_type_box.Text;
dummy.quantity = Convert.ToInt32(Acc_quantity_box.Text);
dummy.cost = Convert.ToInt32(Acc_cost_box.Text);
dummy.Company_name = Acc_company_name_box.Text;
dummy.warrany_date = Acc_warranty_box.Text;
ACCESSORIES.Add (dummy);
MessageBox.Show("Accessories Added");
}
private void BUY_Click(object sender, EventArgs e)
{
if(Buy_type_box.Text == "Medicine")
{
for(int i = 0; i < MEDICINE.Count; i++)
{
if(MEDICINE[i].Name == Buy_name_box.Text)
{
MEDICINE[i].quantity --;
COST += (MEDICINE[i].cost * Convert.ToInt32(Buy_quantity_box.Text));
break;
}
}
}
else
{
for(int i = 0; i < ACCESSORIES.Count;i++)
{
if(ACCESSORIES[i].Name == Buy_name_box.Text)
{
ACCESSORIES[i].quantity--;
COST += (ACCESSORIES[i].cost * Convert.ToInt32(Buy_quantity_box.Text));
break;
}
}
}
MessageBox.Show("BOUGHT");
}
private void BALANCE_Click(object sender, EventArgs e)
{
Cost_List.Items.Clear();
Cost_List.Items.Add(COST);
}
}
}
|
using Newtonsoft.Json;
using RaiBlocks.Interfaces;
using RaiBlocks.Results;
using System;
using System.Collections.Generic;
namespace RaiBlocks.Actions
{
public class AccountsPending : IAction<AccountsPendingResult>
{
public AccountsPending(List<string> accounts, long count, bool source)
{
Accounts = accounts ?? throw new ArgumentNullException(nameof(accounts));
Count = count;
Source = source;
}
[JsonProperty("action")]
public string Action { get; } = "accounts_pending";
[JsonProperty("accounts")]
public List<string> Accounts { get; private set; }
[JsonProperty("count")]
public long Count { get; private set; }
[JsonProperty("source")]
public bool Source { get; private set; }
}
}
|
using Survey.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Survey.ViewModels
{
public class PerguntaViewModel
{
public int Id { get; set; }
public string Titulo { get; set; }
public string Descricao { get; set; }
public string Dica { get; set; }
public char Obrigatoria { get; set; }
public decimal Ordem { get; set; }
public short TipoId { get; set; }
public int QuestionarioId { get; set; }
public List<RespostaViewModel> Respostas { get; set; }
public Object GetPergunta()
{
List<Resposta> respostas = new List<Resposta>();
foreach(RespostaViewModel rvm in this.Respostas)
{
respostas.Add(rvm.GetResposta() as Resposta);
}
return new Pergunta()
{
Id = this.Id,
Titulo = this.Titulo,
Descricao = this.Descricao,
Dica = this.Dica,
Obrigatoria = this.Obrigatoria,
Ordem = this.Ordem,
TipoId = this.TipoId,
QuestionarioId = this.QuestionarioId,
Respostas = respostas
};
}
}
}
|
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ErrorProne.NET.Extensions
{
public static class ExpressionExtensions
{
public static string GetLiteral(this ExpressionSyntax expression, SemanticModel semanticModel)
{
Contract.Requires(expression != null);
Contract.Requires(semanticModel != null);
if (expression is LiteralExpressionSyntax)
{
return expression.ToString();
}
IdentifierNameSyntax identifier = expression as IdentifierNameSyntax;
if (identifier != null)
{
var referencedIdentifier = semanticModel.GetSymbolInfo(identifier);
if (referencedIdentifier.Symbol != null)
{
IFieldSymbol fieldReference = referencedIdentifier.Symbol as IFieldSymbol;
if (fieldReference == null)
{
ILocalSymbol localSymbol = referencedIdentifier.Symbol as ILocalSymbol;
return localSymbol?.ConstantValue?.ToString();
}
// Checking if the field is a constant
string value = fieldReference.ConstantValue?.ToString();
if (value != null)
{
return value;
}
// Checking if the field is static readonly with literal initializer
if (fieldReference.IsStatic && fieldReference.IsReadOnly)
{
var referencedSyntax = fieldReference.DeclaringSyntaxReferences.FirstOrDefault();
VariableDeclaratorSyntax declarator = referencedSyntax?.GetSyntax() as VariableDeclaratorSyntax;
LiteralExpressionSyntax literal = declarator?.Initializer.Value as LiteralExpressionSyntax;
if (literal != null)
{
return literal.ToString();
}
}
}
}
return null;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIMissionBriefingMap : MonoBehaviour
{
public Transform MapPointRoot { get { return m_MapPointRoot; } }
[SerializeField] private Transform m_MapPointRoot;
[SerializeField] private UIMissionBriefingConcentric m_Concentric;
[SerializeField] private UIMissionMapPoint m_SpawnPointPrefab;
[SerializeField] private UIMissionMapPoint m_TowerPointPrefab;
public UIMissionBriefingConcentric Concentric { get { return m_Concentric; } }
#region Variable
private Vector3 m_WorldOrigin;
private UIMissionMapPoint m_Target;
private float m_MapWidth = 544.0f;
private float m_MapHeight = 720.0f;
private List<UIMissionMapPoint> m_PointList = new List<UIMissionMapPoint>();
#endregion
// Use this for initialization
void Awake()
{
//m_WorldOrigin = MapInfo.Instance.MapOrigin.position;
m_WorldOrigin = new Vector3(49.9f, 54.6f, 255.4f);
}
private void Update()
{
foreach (UIMissionMapPoint mapPoint in m_PointList)
{
if(Vector3.Distance(mapPoint.transform.position, m_Concentric.transform.position) < 20f)
{
m_Target = mapPoint;
mapPoint.Highlight();
}
else
{
if (mapPoint == m_Target) m_Target = null;
mapPoint.Normal();
}
}
}
public void AddPointPrefab(GameObject target, eMapPointType type)
{
UIMissionMapPoint mapPoint = null;
switch (type)
{
case eMapPointType.MISSIONTOWER:
mapPoint = Instantiate(m_TowerPointPrefab, m_MapPointRoot);
mapPoint.Init(target, type);
break;
case eMapPointType.SPAWNPOINT:
mapPoint = Instantiate(m_SpawnPointPrefab, m_MapPointRoot);
mapPoint.Init(target, type);
m_PointList.Add(mapPoint);
break;
}
if (mapPoint != null) CalculatePosition(target.transform.position, ref mapPoint);
}
private void CalculatePosition(Vector3 target,ref UIMissionMapPoint mapPoint)
{
Vector3 m_Dir = target - m_WorldOrigin;
float mapWidth = m_MapPointRoot.GetComponent<RectTransform>().sizeDelta.x;
float mapHeight = m_MapPointRoot.GetComponent<RectTransform>().sizeDelta.y;
Vector3 m_Pos = mapPoint.transform.localPosition;
m_Pos.x = m_Dir.x * mapWidth / m_MapWidth - mapWidth * 0.5f;
m_Pos.y = m_Dir.z * mapHeight / m_MapHeight - mapHeight * 0.5f;
mapPoint.transform.localPosition = m_Pos;
}
public bool ComfirmSpawnPosition()
{
if (m_Target == null) return false;
if (m_Target.SpawnPoint == null) return false;
GameMain.Instance.GameStart(m_Target.SpawnPoint.transform);
return true;
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
namespace System.Reflection.Runtime.CustomAttributes
{
//
// If a CustomAttributeData implementation derives from this, it is a hint that it has a AttributeType implementation
// that's more efficient than building a ConstructorInfo and gettings its DeclaredType.
//
[System.Runtime.CompilerServices.ReflectionBlocked]
public abstract class RuntimeImplementedCustomAttributeData : CustomAttributeData
{
public new abstract Type AttributeType { get; }
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Matching;
using Microsoft.Extensions.Primitives;
using Yarp.ReverseProxy.Configuration;
namespace Yarp.ReverseProxy.Routing;
internal sealed class HeaderMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, IEndpointSelectorPolicy
{
/// <inheritdoc/>
// Run after HttpMethodMatcherPolicy (-1000) and HostMatcherPolicy (-100), but before default (0)
public override int Order => -50;
/// <inheritdoc/>
public IComparer<Endpoint> Comparer => new HeaderMetadataEndpointComparer();
/// <inheritdoc/>
bool IEndpointSelectorPolicy.AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
_ = endpoints ?? throw new ArgumentNullException(nameof(endpoints));
// When the node contains dynamic endpoints we can't make any assumptions.
if (ContainsDynamicEndpoints(endpoints))
{
return true;
}
return AppliesToEndpointsCore(endpoints);
}
private static bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
{
return endpoints.Any(e =>
{
var metadata = e.Metadata.GetMetadata<IHeaderMetadata>();
return metadata?.Matchers?.Length > 0;
});
}
/// <inheritdoc/>
public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
{
_ = httpContext ?? throw new ArgumentNullException(nameof(httpContext));
_ = candidates ?? throw new ArgumentNullException(nameof(candidates));
var headers = httpContext.Request.Headers;
for (var i = 0; i < candidates.Count; i++)
{
if (!candidates.IsValidCandidate(i))
{
continue;
}
var matchers = candidates[i].Endpoint.Metadata.GetMetadata<IHeaderMetadata>()?.Matchers;
if (matchers is null)
{
continue;
}
foreach (var matcher in matchers)
{
if (headers.TryGetValue(matcher.Name, out var requestHeaderValues) &&
!StringValues.IsNullOrEmpty(requestHeaderValues))
{
if (matcher.Mode is HeaderMatchMode.Exists)
{
continue;
}
if (matcher.Mode is HeaderMatchMode.ExactHeader or HeaderMatchMode.HeaderPrefix
? TryMatchExactOrPrefix(matcher, requestHeaderValues)
: TryMatchContainsOrNotContains(matcher, requestHeaderValues))
{
continue;
}
}
candidates.SetValidity(i, false);
break;
}
}
return Task.CompletedTask;
}
private static bool TryMatchExactOrPrefix(HeaderMatcher matcher, StringValues requestHeaderValues)
{
var requestHeaderCount = requestHeaderValues.Count;
for (var i = 0; i < requestHeaderCount; i++)
{
var requestValue = requestHeaderValues[i].AsSpan();
while (!requestValue.IsEmpty)
{
requestValue = requestValue.TrimStart(' ');
// Find the end of the next value.
// Separators inside a quote pair must be ignored as they are a part of the value.
var separatorOrQuoteIndex = requestValue.IndexOfAny('"', matcher.Separator);
while (separatorOrQuoteIndex != -1 && requestValue[separatorOrQuoteIndex] == '"')
{
var closingQuoteIndex = requestValue.Slice(separatorOrQuoteIndex + 1).IndexOf('"');
if (closingQuoteIndex == -1)
{
separatorOrQuoteIndex = -1;
}
else
{
var offset = separatorOrQuoteIndex + closingQuoteIndex + 2;
separatorOrQuoteIndex = requestValue.Slice(offset).IndexOfAny('"', matcher.Separator);
if (separatorOrQuoteIndex != -1)
{
separatorOrQuoteIndex += offset;
}
}
}
ReadOnlySpan<char> value;
if (separatorOrQuoteIndex == -1)
{
value = requestValue;
requestValue = default;
}
else
{
value = requestValue.Slice(0, separatorOrQuoteIndex);
requestValue = requestValue.Slice(separatorOrQuoteIndex + 1);
}
if (value.Length > 1 && value[0] == '"' && value[^1] == '"')
{
value = value.Slice(1, value.Length - 2);
}
foreach (var expectedValue in matcher.Values)
{
if (matcher.Mode == HeaderMatchMode.ExactHeader
? value.Equals(expectedValue, matcher.Comparison)
: value.StartsWith(expectedValue, matcher.Comparison))
{
return true;
}
}
}
}
return false;
}
private static bool TryMatchContainsOrNotContains(HeaderMatcher matcher, StringValues requestHeaderValues)
{
Debug.Assert(matcher.Mode is HeaderMatchMode.Contains or HeaderMatchMode.NotContains, $"{matcher.Mode}");
var requestHeaderCount = requestHeaderValues.Count;
for (var i = 0; i < requestHeaderCount; i++)
{
var requestValue = requestHeaderValues[i];
if (requestValue is null)
{
continue;
}
foreach (var expectedValue in matcher.Values)
{
if (requestValue.Contains(expectedValue, matcher.Comparison))
{
return matcher.Mode != HeaderMatchMode.NotContains;
}
}
}
return matcher.Mode == HeaderMatchMode.NotContains;
}
private class HeaderMetadataEndpointComparer : EndpointMetadataComparer<IHeaderMetadata>
{
protected override int CompareMetadata(IHeaderMetadata? x, IHeaderMetadata? y)
{
return (y?.Matchers?.Length ?? 0).CompareTo(x?.Matchers?.Length ?? 0);
}
}
}
|
using API.SharedObjects.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace API.DataLayer.ConcreteClass
{
public class Property
{
[Key]
public Guid propertyId { get; set; }
public string PropertyType { get; set; }
public string FreeHolder { get; set; }
[ForeignKey("OwnerId")]
public IEnumerable<Address> address { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ThreadSafe
{
public class StateModifier<T>
{
private readonly Repository<T> m_repos;
/// <summary>
/// Get/Set WIP state. Modify this state directly.
/// </summary>
public T WorkingState { get; set; }
/// <summary>
/// Get revision of WorkingState.
/// </summary>
public uint WorkingRevision { get; private set; }
private Repository<T>.Revision m_originalRevision;
internal StateModifier(Repository<T> repos, Repository<T>.Revision revision)
{
m_repos = repos;
m_originalRevision = revision;
WorkingState = m_originalRevision.CurrentStateClone;
WorkingRevision = m_originalRevision.RevisionNumber;
}
/// <summary>
/// Get "deep-copied" original state.
/// </summary>
public T OriginalStateClone
{
get
{
lock (m_repos.m_syncRoot)
{
if (m_originalRevision is null)
{
return default(T);
}
return m_originalRevision.CurrentStateClone;
}
}
}
/// <summary>
/// Commit WorkingState. CurrentState of the repository will be updated.
/// </summary>
public bool Commit()
{
lock (m_repos.m_syncRoot)
{
var committedRevision = m_repos.Commit(WorkingState, WorkingRevision);
if (committedRevision != null)
{
// success
m_originalRevision = committedRevision;
WorkingRevision = committedRevision.RevisionNumber;
return true;
}
else
{
// failure
return false;
}
}
}
/// <summary>
/// Revert original state.
/// </summary>
public void Revert()
{
lock (m_repos.m_syncRoot)
{
WorkingState = m_originalRevision.CurrentStateClone;
WorkingRevision = m_originalRevision.RevisionNumber;
}
}
}
}
|
//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
namespace nanoFramework.Tools.Debugger
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// !!! KEEP IN SYNC WITH System.Net.NetworkInformation.WirelessAPConfiguration (in nanoFramework.System.Net) !!! //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class WirelessAPConfigurationBase
{
/// <summary>
/// This is the marker placeholder for this configuration block
/// 4 bytes length.
/// </summary>
public byte[] Marker;
/// <summary>
/// Id for the configuration
/// </summary>
public uint Id;
/// <summary>
/// Type of authentication used on the wireless network
/// </summary>
public byte Authentication;
/// <summary>
/// Type of encryption used on the wireless network.
/// </summary>
public byte Encryption;
/// <summary>
/// Type of radio used by the wireless network adapter.
/// </summary>
public byte Radio;
/// <summary>
/// Network SSID
/// 32 bytes length.
/// </summary>
public byte[] Ssid;
/// <summary>
/// Network password
/// 64 bytes length.
/// </summary>
public byte[] Password;
/// <summary>
/// Options
/// 1 byte length.
/// </summary>
public byte Options;
/// <summary>
/// Channel
/// 1 byte length.
/// </summary>
public byte Channel;
/// <summary>
/// Max connections
/// 1 byte length.
/// </summary>
public byte MaxConnections;
public WirelessAPConfigurationBase()
{
// need to init these here to match the expected size on the struct to be sent to the device
Marker = new byte[4];
Ssid = new byte[32];
Password = new byte[64];
}
}
} |
/* Copyright © 2021 Yusuf Sulaeman <sufsulae@gmail.com>
*
* 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.Net;
using System.Net.Sockets;
using System.Threading;
namespace Soketin
{
public class SoketinServer {
public bool useDispatcher { get; set; }
public SoketinUser[] clients { get { return m_clients.ToArray(); } }
public SoketinEvent onEvent
{
get { return m_event; }
set
{
if (value == null)
m_event = new SoketinEventImpl();
else
m_event = value;
}
}
private Socket m_socket;
private uint m_port;
private bool m_signalStop;
private ManualResetEventSlim m_signalAccept;
private List<SoketinUser> m_clients;
private Thread m_listenerThread;
private byte[] m_buffer;
private uint m_userID;
private SoketinEvent m_event;
public SoketinServer(uint port) {
m_port = port;
}
~SoketinServer() {
StopServer();
}
public void StartServer() {
m_signalStop = false;
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
m_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
m_socket.DontFragment = true;
m_socket.Bind(new IPEndPoint(IPAddress.Any, (int)m_port));
m_socket.Listen(100);
m_clients = new List<SoketinUser>();
m_signalAccept = new ManualResetEventSlim(false);
m_buffer = new byte[8196];
m_listenerThread = new Thread(_listenerThread);
m_listenerThread.Start();
_execute((Action)onEvent.OnServiceStart);
}
public void StopServer() {
m_signalStop = true;
m_signalAccept.Reset();
if (m_socket.Connected)
m_socket.Shutdown(SocketShutdown.Both);
m_socket.Close();
m_signalAccept.Dispose();
m_buffer = null;
_execute((Action)onEvent.OnServiceStop);
}
public void Broadcast(byte[] data) {
var packedData = SoketinUtility.PackRawData(data);
foreach (var client in m_clients) {
Send(client, packedData);
}
}
public void Broadcast(SoketinData data) {
Broadcast(data.GetBytes());
}
public void Send(SoketinUser client, byte[] data) {
var user = m_clients.Find((c) => { return c._socket == client._socket; });
if (user != null) {
var packedData = SoketinUtility.PackRawData(data);
client._socket.BeginSend(packedData, 0, packedData.Length, 0, new AsyncCallback(_onBeginSend), client);
}
}
public void Send(SoketinUser client, SoketinData data) {
Send(client, data.GetBytes());
}
public void Send(int clientId, byte[] data) {
var client = m_clients.Find((c) => { return c.id == clientId; });
Send(client, data);
}
public void Send(int clientId, SoketinData data) {
Send(clientId, data.GetBytes());
}
private void _onBeginAccept(IAsyncResult ar) {
m_signalAccept.Set();
if (m_signalStop)
return;
var client = ((Socket)ar.AsyncState).EndAccept(ar);
var newClient = new SoketinUser() {
_id = m_userID,
_ipAddress = ((IPEndPoint)client.RemoteEndPoint).Address.ToString(),
_port = ((IPEndPoint)client.RemoteEndPoint).Port,
_socket = client,
};
m_clients.Add(newClient);
client.BeginReceive(m_buffer, 0, m_buffer.Length, 0, new AsyncCallback(_onBeginReceive), client);
_execute((Action<SoketinUser>)onEvent.OnClientConnected,newClient);
m_userID++;
}
private void _onBeginReceive(IAsyncResult ar) {
var client = (Socket)ar.AsyncState;
var user = m_clients.Find((e) => { return e._socket == client; });
try
{
int byteReaded = client.EndReceive(ar);
if (byteReaded > 0) {
var packs = SoketinUtility.SplitRawPacket(m_buffer, byteReaded);
foreach (var pack in packs)
_execute((Action<SoketinUser, byte[]>)onEvent.OnDataRecieved, client, pack);
}
if (!m_signalStop)
client.BeginReceive(m_buffer, 0, m_buffer.Length, 0, new AsyncCallback(_onBeginReceive), client);
}
catch(Exception e){
_execute((Action<Exception, object>)onEvent.OnError, e, user);
client.Close();
m_clients.Remove(user);
Console.WriteLine("Client Disconnected");
_execute((Action<SoketinUser>)onEvent.OnClientDisconnected, user);
}
}
private void _onBeginSend(IAsyncResult ar) {
var client = (Socket)ar.AsyncState;
var byteTransfered = client.EndSend(ar);
}
private void _listenerThread() {
while (!m_signalStop) {
m_signalAccept.Reset();
m_socket.BeginAccept(new AsyncCallback(_onBeginAccept), m_socket);
m_signalAccept.Wait();
}
}
private void _execute(Delegate del, params object[] args) {
if (useDispatcher)
SoketinDispatcher.AddExecution(del, args);
else
del?.DynamicInvoke(args);
}
}
}
|
// ReSharper disable once CheckNamespace
namespace Svg.ExCSS
{
public abstract class Term
{
public static readonly InheritTerm Inherit = new InheritTerm();
}
}
|
namespace DryRun
{
public interface IUnknownService
{
void AddRef();
string QueryInterface(string key);
void Release();
}
} |
// Copyright (C) 2020 Fievus
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using Charites.Windows.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace Charites.Windows.Samples.SimpleLoginDemo
{
public class SimpleLoginDemoControllerFactory : IWindowsFormsControllerFactory
{
private readonly IServiceProvider services;
public SimpleLoginDemoControllerFactory(IServiceProvider services) => this.services = services;
public object Create(Type controllerType) => services.GetRequiredService(controllerType);
}
}
|
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AchtungStarter.Core
{
public class Controller
{
private readonly StateStorage _stateStorage;
private readonly ServerManager _serverManager;
private readonly ILogger<Controller> _logger;
public Controller(StateStorage stateStorage, ServerManager serverManager, ILogger<Controller> logger)
{
_logger = logger;
_serverManager = serverManager;
_stateStorage = stateStorage;
}
public State? GetState()
{
return _stateStorage.LoadState();
}
public void StartServer()
{
Task.Run(async () =>
{
try
{
await _serverManager.StartServer();
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception during 'Task.Run'.");
}
});
}
public async Task<State?> ShutDownServer()
{
return await _serverManager.ShutDownServer();
}
public async Task<State?> AddMinutes(int minutes)
{
if (minutes < 1)
{
throw new ArgumentOutOfRangeException(nameof(minutes));
}
return await _serverManager.AddMinutes(minutes);
}
}
}
|
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Braco.Services
{
/// <summary>
/// Defines that the inheriting member will setup one or more services.
/// </summary>
public interface ISetupService : IHaveConfigurationSection
{
/// <summary>
/// Name of the section where configuration for <see cref="ISetupService"/>s
/// should be placed.
/// </summary>
public const string ServicesSetupSection = "Services";
/// <summary>
/// Used for setting up the desired service(s).
/// </summary>
/// <param name="services">Collection of services to add the service(s) to.</param>
/// <param name="configuration">Read-only configuration.</param>
/// <param name="section">Section in the configuration dedicated to this <see cref="ISetupService"/>.</param>
void Setup(IServiceCollection services, IConfiguration configuration, IConfigurationSection section);
}
}
|
using System;
using log4net;
using RatTracker.Models.Journal;
namespace RatTracker.Infrastructure.Events
{
public class JournalEvents
{
private readonly ILog log;
public JournalEvents(ILog log)
{
this.log = log;
}
public event EventHandler<Location> Location;
public event EventHandler<Friends> Friends;
public event EventHandler<WingInvite> WingInvite;
public event EventHandler<WingJoin> WingJoin;
public event EventHandler<WingAdd> WingAdd;
public event EventHandler<WingLeave> WingLeave;
public void PostJournalEvent(object sender, JournalEntryBase journalEntry)
{
sender = sender ?? this;
switch (journalEntry)
{
case FSDJump jump:
Location?.Invoke(sender, jump);
break;
case Location location:
Location?.Invoke(sender, location);
break;
case Friends friends:
Friends?.Invoke(sender, friends);
break;
case WingInvite wingInvite:
WingInvite?.Invoke(sender, wingInvite);
break;
case WingJoin wingJoin:
WingJoin?.Invoke(sender, wingJoin);
break;
case WingAdd wingAdd:
WingAdd?.Invoke(sender, wingAdd);
break;
case WingLeave wingLeave:
WingLeave?.Invoke(sender, wingLeave);
break;
case null:
break;
default:
log.Warn($"Unmapped journal event '{journalEntry.GetType().Name}'");
break;
}
}
}
} |
// Copyright 2016 Raymond Neilson
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// This is not quite as generic as I'd like, especially regarding available settings/properties
// If I end up reusing this for something, I'll need some way of specifying said
// settings/properties w/o Unity's interference and weirdness
public class MenuControl : MonoBehaviour {
public bool debugInfo;
private Scorer scorer;
// Title text
private TextMesh titleMesh;
private TextMesh versionMesh;
// Menu lines
private MenuLine[] menuLines;
private int selectedLine;
// Selected text parameters
public int lineCols;
public int capCols;
public string leftCapText = "[";
public string rightCapText = "]";
public FontStyle selectedStyle = FontStyle.Normal;
// Menu node list and navigation
public MenuNode[] menuNodes;
public string rootNode;
private Dictionary<string, MenuNode> nodes = new Dictionary<string, MenuNode>();
private MenuNodePath currNode = MenuNodePath.None;
// Settings
//private Dictionary<string, MenuSetting> settings = new Dictionary<string, MenuSetting>();
// Cursor state
private CursorLockMode desiredCursorMode;
private bool desiredCursorVisibility;
private InputMode currentInput;
// Input axes
private InputAxisTracker moveVert = new InputAxisTracker("MoveVertical");
private InputAxisTracker moveHori = new InputAxisTracker("MoveHorizontal");
private InputAxisTracker fireVert = new InputAxisTracker("FireVertical");
private InputAxisTracker fireHori = new InputAxisTracker("FireHorizontal");
private InputAxisTracker selVert = new InputAxisTracker("SelectVertical");
private InputAxisTracker selHori = new InputAxisTracker("SelectHorizontal");
private InputAxisTracker bombTrig = new InputAxisTracker("BombTrigger");
private InputAxisTracker bombTrigL = new InputAxisTracker("BombTriggerL");
private InputAxisTracker bombTrigR = new InputAxisTracker("BombTriggerR");
// Visibility layers
int showLayer;
int hideLayer;
public bool Hidden {
get {
if (gameObject.layer == hideLayer) {
return true;
}
else {
return false;
}
}
}
public int LineColumns {
get { return lineCols; }
}
public int CapColumns {
get { return capCols; }
}
public string LeftCapText {
get { return leftCapText; }
}
public string RightCapText {
get { return rightCapText; }
}
public FontStyle SelectedStyle {
get {return selectedStyle; }
}
public string RootNode {
get { return rootNode; }
}
public InputMode CurrentInput {
get { return currentInput; }
}
// Use this for initialization
void Start () {
// Get scorer
scorer = GameObject.Find("Scorekeeper").GetComponent<Scorer>();
// Title init (assumes children 0 and 1)
titleMesh = transform.GetChild(0).GetComponent<TextMesh>();
versionMesh = transform.GetChild(1).GetComponent<TextMesh>();
SetTitle(GameSettings.GameName, GameSettings.Version);
// Line array init
menuLines = GetComponentsInChildren<MenuLine>();
if (debugInfo) {
Debug.Log("Found the following children:");
foreach (MenuLine line in menuLines) {
Debug.Log(line.gameObject.name, line.gameObject);
}
}
// Get layers
showLayer = LayerMask.NameToLayer("TransparentFX");
hideLayer = LayerMask.NameToLayer("Hidden");
// Let each line know its index, and clear what it has to
for (int i = 0; i < menuLines.Length; i++) {
menuLines[i].LineIndex = i;
menuLines[i].Deselect();
}
/*
// Setup settings dict
settings["Volume"] = new VolumeSetting("Volume");
settings["MouseSpeed"] = new MouseSpeedSetting("MouseSpeed", "FireCursor");
*/
// Parse menu node list
foreach (MenuNode node in menuNodes) {
nodes[node.name] = node;
}
// Show menu and select first line
ShowMenu(rootNode);
}
// Update is called once per frame
void Update () {
// Cursor state stuff
if (Cursor.lockState != desiredCursorMode) {
Cursor.lockState = desiredCursorMode;
}
if (Cursor.visible != desiredCursorVisibility) {
Cursor.visible = desiredCursorVisibility;
}
// Check for input
if (currentInput == InputMode.Game) {
// Check for screenshot command
// Here instead of in Scorer because I'm consolidating the hide-menu-before-capping code with the
// take-a-screenshot code
if (Input.GetButtonDown("Screenshot")) {
StartCoroutine(ScreenCapture(false));
}
}
else if (currentInput == InputMode.Menu) {
// Check commands
MenuCommand cmd = ParseInput();
if (cmd.cmdType != MenuCommandType.None) {
if (debugInfo) {
Debug.Log("Caught input: " + cmd.cmdType.ToString(), gameObject);
}
ExecuteCommand(cmd);
}
}
}
// Internal methods
void LoadNode (string nodeName) {
// Grab node name
MenuNode node = nodes[nodeName];
if (debugInfo) {
Debug.Log("Loading node: " + node.name, gameObject);
}
int lineIndex = 0;
int sourceIndex = 0;
// Make the first line a back cmd
string backName;
// Check if there's a previous node
if ((currNode.Prev == null) || (currNode.Prev.Name == "")) {
// Check if game's started
if (scorer.IsStarted) {
backName = "Resume";
}
// Otherwise, don't even show this line
else {
backName = "";
}
}
// Otherwise, use the generic "back"
// Could use prev node name, but that'll have to wait
// until I change nodes to have display names
else {
backName = "Back";
}
if ((node.autoCreateBack) && (backName != "")) {
menuLines[0].ConfigureLine(MenuLineType.Back, backName, "");
if (debugInfo) {
menuLines[0].DebugLineInfo();
}
lineIndex++;
}
// Configure listed lines
while ((sourceIndex < node.lines.Length) && (lineIndex < menuLines.Length)) {
MenuNodeLine line = node.lines[sourceIndex];
menuLines[lineIndex].ConfigureLine(line.lineType, line.label, line.target);
if (debugInfo) {
menuLines[lineIndex].DebugLineInfo();
}
lineIndex++;
sourceIndex++;
}
// Configure remaining lines as blank
while (lineIndex < menuLines.Length) {
menuLines[lineIndex].ConfigureLine(MenuLineType.Text, "", "");
if (debugInfo) {
menuLines[lineIndex].DebugLineInfo();
}
lineIndex++;
}
}
void MakeVisible () {
// Show ourselves
gameObject.layer = showLayer;
// Show title
titleMesh.gameObject.layer = showLayer;
versionMesh.gameObject.layer = showLayer;
// Show lines
foreach (MenuLine line in menuLines) {
line.SetLayer(showLayer);
}
// Show cursor
desiredCursorVisibility = true;
desiredCursorMode = CursorLockMode.None;
}
void MakeInvisible () {
// Hide lines
foreach (MenuLine line in menuLines) {
line.SetLayer(hideLayer);
}
// Hide title
titleMesh.gameObject.layer = hideLayer;
versionMesh.gameObject.layer = hideLayer;
// Hide ourselves
gameObject.layer = hideLayer;
// Hide cursor
desiredCursorVisibility = false;
desiredCursorMode = CursorLockMode.Locked;
}
void ShowMenu (MenuNodePath node) {
// Exit menu if node is null/none (empty string)
if (node.Name == "") {
HideMenu();
}
// Otherwise, get and parse node
else if (nodes.ContainsKey(node.Name)) {
if (debugInfo) {
Debug.Log("Going forward to " + node.Name, gameObject);
}
// Save current line and set new current node
currNode.Line = selectedLine;
currNode = node;
// Load up node lines
LoadNode(node.Name);
// Show ourselves
MakeVisible();
// Select saved/first line
if (node.Line >= 0) {
SelectLine(node.Line);
}
else {
int selected = 0;
while (!menuLines[selected].Selectable) {
selected++;
}
SelectLine(selected);
}
// Grab and reset input
currentInput = InputMode.Menu;
ResetInput();
}
}
void BackMenu () {
if (debugInfo) {
Debug.Log("Going back to " + currNode.Prev.Name, gameObject);
}
ShowMenu(currNode.Prev);
}
void BackMenu (string backTo) {
MenuNodePath node = currNode;
// Walk back until we find our node or hit root node
while ((node.Name != backTo) && (node.Prev.Name != "")) {
node = node.Prev;
}
// Go there
ShowMenu(node);
}
void SelectUp (int index) {
int newLine = (index < 0) ? 0 : index;
do {
newLine--;
if (newLine < 0) {
newLine = menuLines.Length - 1;
}
} while (!menuLines[newLine].Selectable);
SelectLine(newLine);
}
void SelectDown (int index) {
int newLine = (index < -1) ? -1 : index;
do {
newLine++;
if (newLine >= menuLines.Length) {
newLine = 0;
}
} while (!menuLines[newLine].Selectable);
SelectLine(newLine);
}
// For retrieving a command from the appropriate line when mouse clicked
MenuCommand ParseMouseClick () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// Cast a ray hitting only UI elements
if (Physics.Raycast(ray, out hit, 15f, (1 << showLayer))) {
// Only the menu line segments have colliders, so I think we can
// get away with assuming we're hitting one of these
MenuSegment segment = hit.collider.GetComponent<MenuSegment>();
// Check anyways
if (segment) {
return segment.ClickedOn();
}
else {
return MenuCommand.None;
}
}
else {
return MenuCommand.None;
}
}
// A big heap of ifs -- apologies, but I don't think there's another way to do it
// (Somewhere, somehow, buried perhaps, all input is a big heap of ifs)
MenuCommand ParseInput () {
// Update input dT
InputAxisTracker.Update(Time.unscaledDeltaTime);
// Grab current axis readings
float threshold = InputAxisTracker.Threshold;
float moveVertVal = moveVert.Read();
float moveHoriVal = moveHori.Read();
float fireVertVal = fireVert.Read();
float fireHoriVal = fireHori.Read();
float selVertVal = selVert.Read();
float selHoriVal = selHori.Read();
float bombTrigVal = bombTrig.Read();
float bombTrigLVal = bombTrigL.Read();
float bombTrigRVal = bombTrigR.Read();
// Screenshot first, because with the hiding/showing, we don't want to do anything else this frame
if (Input.GetButtonDown("Screenshot")) {
return MenuCommand.ScreenCap;
}
// Back button
else if (Input.GetButtonDown("Back")) {
return MenuCommand.Back;
}
// Mouse button
else if (Input.GetMouseButtonDown(0)) {
return ParseMouseClick();
}
// Triggers/spacebar/return
else if ((Input.GetButtonDown("BombKey"))
|| (Input.GetButtonDown("BombButton"))
|| (Input.GetButtonDown("Select"))
|| ((bombTrigVal > threshold) || (bombTrigVal < -threshold))
|| ((bombTrigLVal > threshold) || (bombTrigLVal < -threshold))
|| ((bombTrigRVal > threshold) || (bombTrigRVal < -threshold))) {
// Just run selected
return MenuCommand.RunCmdLine;
}
// Up next
else if ((moveVertVal > threshold)
|| (fireVertVal > threshold)
|| (selVertVal > threshold)) {
//else if ((Input.GetKeyDown(KeyCode.UpArrow))
// || (Input.GetKeyDown(KeyCode.W))) {
return MenuCommand.SelectUp;
}
// Then down
else if ((moveVertVal < -threshold)
|| (fireVertVal < -threshold)
|| (selVertVal < -threshold)) {
//else if ((Input.GetKeyDown(KeyCode.DownArrow))
// || (Input.GetKeyDown(KeyCode.S))) {
return MenuCommand.SelectDown;
}
// Now right
else if ((moveHoriVal > threshold)
|| (fireHoriVal > threshold)
|| (selHoriVal > threshold)) {
//else if ((Input.GetKeyDown(KeyCode.RightArrow))
// || (Input.GetKeyDown(KeyCode.D))) {
return MenuCommand.RunCmdRight;
}
// Then left
else if ((moveHoriVal < -threshold)
|| (fireHoriVal < -threshold)
|| (selHoriVal < -threshold)) {
//else if ((Input.GetKeyDown(KeyCode.LeftArrow))
// || (Input.GetKeyDown(KeyCode.A))) {
return MenuCommand.RunCmdLeft;
}
else {
return MenuCommand.None;
}
}
void ExecuteCommand (MenuCommand cmd) {
if ((debugInfo) && (cmd.cmdType != MenuCommandType.None)) {
Debug.Log("Executing: " + cmd.cmdType.ToString(), gameObject);
}
// Awful big-ass switch ahoy!
// (Sorry)
// ((Enums are meant for big-ass switches, IMNSHO))
switch (cmd.cmdType) {
case MenuCommandType.QuitApp:
scorer.SaveScores();
GameSettings.Quit();
break;
case MenuCommandType.Restart:
scorer.SaveScores();
GameSettings.Restart();
break;
case MenuCommandType.ExitMenu:
HideMenu();
break;
case MenuCommandType.NodeBack:
BackMenu();
break;
case MenuCommandType.NodeBackTo:
BackMenu(cmd.cmdTarget);
break;
case MenuCommandType.NodeGoto:
ShowMenu(cmd.cmdTarget);
break;
case MenuCommandType.SettingToggle:
GameSettings.ToggleSetting(cmd.cmdTarget);
menuLines[selectedLine].UpdateText();
break;
case MenuCommandType.SettingHigher:
GameSettings.RaiseSetting(cmd.cmdTarget);
menuLines[selectedLine].UpdateText();
break;
case MenuCommandType.SettingLower:
GameSettings.LowerSetting(cmd.cmdTarget);
menuLines[selectedLine].UpdateText();
break;
case MenuCommandType.SelectUp:
SelectUp(selectedLine);
break;
case MenuCommandType.SelectDown:
SelectDown(selectedLine);
break;
case MenuCommandType.RunCmdLine:
if (selectedLine >= 0) {
ExecuteCommand(menuLines[selectedLine].CommandLine());
}
break;
case MenuCommandType.RunCmdLeft:
if (selectedLine >= 0) {
ExecuteCommand(menuLines[selectedLine].CommandLeft());
}
break;
case MenuCommandType.RunCmdRight:
if (selectedLine >= 0) {
ExecuteCommand(menuLines[selectedLine].CommandRight());
}
break;
case MenuCommandType.ScreenCap:
StartCoroutine(ScreenCapture(true));
break;
case MenuCommandType.ResetInput:
GameSettings.ResetInputSettings();
ShowMenu(cmd.cmdTarget);
break;
case MenuCommandType.None:
default:
break;
}
}
void ResetInput () {
// Reset Unity's input
Input.ResetInputAxes();
// Lock in zero values for our custom input for first fraction of a second
moveVert.Read();
moveHori.Read();
fireVert.Read();
fireHori.Read();
selVert.Read();
selHori.Read();
bombTrig.Read();
bombTrigL.Read();
bombTrigR.Read();
}
IEnumerator ScreenCapture (bool hideMenu) {
if (hideMenu) {
MakeInvisible();
}
else {
GameSettings.Pause();
}
yield return 0;
GameSettings.ScreenCap();
yield return 0;
if (hideMenu) {
MakeVisible();
}
else {
GameSettings.Resume();
}
}
// External methods
public void SelectLine (int index) {
if ((index < menuLines.Length) && (menuLines[index].Selectable)) {
if (selectedLine >= 0) {
menuLines[selectedLine].Deselect();
}
selectedLine = index;
menuLines[index].Select();
}
// else do nothing
}
public void DeselectLine (int index) {
// Only deselect if it's actually selected
if ((index >= 0) && (selectedLine == index)) {
menuLines[selectedLine].Deselect();
selectedLine = -1;
}
// else do nothing
}
public void SetTitle (string title, string version = "") {
titleMesh.text = title;
if (version != "") {
versionMesh.text = version;
}
}
public void ShowMenu (string nodeName) {
// Creates a new nodepath...
MenuNodePath newNode = new MenuNodePath(currNode, nodeName, -1);
if (debugInfo) {
Debug.Log("New path node, target: " + newNode.Name
+ ", previous: " + newNode.Prev.Name, gameObject);
}
// and tries to go there
ShowMenu(newNode);
}
public void HideMenu () {
// Set current node to None (all the way back)
currNode = MenuNodePath.None;
// Deselect current line
DeselectLine(selectedLine);
// Hide ourselves
MakeInvisible();
// Release input
currentInput = InputMode.Game;
Input.ResetInputAxes();
// Tell GameSettings to resume
GameSettings.Resume();
}
public string GetSetting (string settingName) {
return GameSettings.GetSetting(settingName);
}
}
// For directing input to us, or to the game
public enum InputMode : byte {
Game = 0,
Menu
}
// For checking an axis while timescale = 0
public class InputAxisTracker {
private const float resetTime = 0.35f;
private const float threshold = 0.1f;
private static float deltaTime;
private float resetCountdown = 0.0f;
private bool wasCaptured = false;
private bool wasRead = false;
private float axisValue;
private string axisName;
public static float Threshold {
get { return threshold; }
}
public InputAxisTracker (string axisName) {
this.axisName = axisName;
this.axisValue = 0.0f;
}
void Set (float axisReading) {
axisValue = axisReading;
resetCountdown = resetTime;
wasCaptured = true;
wasRead = false;
}
void Reset () {
axisValue = 0.0f;
resetCountdown = 0.0f;
wasCaptured = false;
wasRead = false;
}
public static void Update (float dT) {
deltaTime = dT;
}
void Capture () {
// Get temp reading to check
float tempCap = Input.GetAxisRaw(axisName);
// If previously captured, test for axis return to 0 or reset time met
if (wasCaptured) {
resetCountdown -= deltaTime;
if (((tempCap < threshold) && (tempCap > -threshold)) || (resetCountdown <= 0.0f)) {
Reset();
}
}
// This is not an else statement -- we want the fall-through
if (!wasCaptured) {
if ((tempCap > threshold) || (tempCap < -threshold)) {
Set(tempCap);
}
}
}
public float Read () {
// Capture input if possible
Capture();
if (wasRead) {
return 0.0f;
}
else {
wasRead = true;
return axisValue;
}
}
}
// For passing commands up and down the tree
public enum MenuCommandType : byte {
None = 0,
QuitApp,
Restart,
ExitMenu,
NodeGoto,
NodeBack,
SettingToggle,
SettingHigher,
SettingLower,
SelectUp,
SelectDown,
RunCmdLine,
RunCmdLeft,
RunCmdRight,
ScreenCap,
ResetInput,
NodeBackTo
}
// To be returned from input queries
public struct MenuCommand {
public MenuCommandType cmdType;
public string cmdTarget;
public MenuCommand (MenuCommandType cmdType, string cmdTarget) {
this.cmdType = cmdType;
this.cmdTarget = cmdTarget;
}
public static MenuCommand None = new MenuCommand(MenuCommandType.None, "");
public static MenuCommand Back = new MenuCommand(MenuCommandType.NodeBack, "");
public static MenuCommand RunCmdLine = new MenuCommand(MenuCommandType.RunCmdLine, "");
public static MenuCommand SelectUp = new MenuCommand(MenuCommandType.SelectUp, "");
public static MenuCommand SelectDown = new MenuCommand(MenuCommandType.SelectDown, "");
public static MenuCommand RunCmdRight = new MenuCommand(MenuCommandType.RunCmdRight, "");
public static MenuCommand RunCmdLeft = new MenuCommand(MenuCommandType.RunCmdLeft, "");
public static MenuCommand ScreenCap = new MenuCommand(MenuCommandType.ScreenCap, "");
}
// For menu setup
[System.Serializable]
public class MenuNodeLine {
public MenuLineType lineType;
public string label;
public string target;
}
[System.Serializable]
public class MenuNode {
public string name;
public bool autoCreateBack = true;
public MenuNodeLine[] lines;
}
public class MenuNodePath {
// Pretty bare-bones linked list, with, like, hardly any methods
// (Don't need them at the moment)
private MenuNodePath prev;
private string name;
private int line;
public MenuNodePath Prev { get { return prev; } }
public string Name { get { return name; } }
public int Line {
get { return line; }
set {
if (name != "") {
line = value;
}
}
}
public MenuNodePath (MenuNodePath prev, string name, int line) {
this.prev = prev;
this.name = name;
this.line = line;
}
public MenuNodePath () : this(null, "", 0) {}
// Trick to make it refer to itself as previous
private MenuNodePath MakeRecursive () {
this.prev = this;
return this;
}
// Base empty node
public static MenuNodePath None = (new MenuNodePath()).MakeRecursive();
}
|
using System.Collections.Generic;
/**
* Utilitary functions for dictionary
* @author zeh
*/
public class JSONDictUtils {
public static Dictionary<string, object> getDict(Dictionary<string, object> input, string key, Dictionary<string, object> defaultValue = null) {
if (input.ContainsKey(key)) return (Dictionary<string, object>)input[key];
return defaultValue;
}
public static string getString(Dictionary<string, object> input, string key, string defaultValue = "") {
if (input.ContainsKey(key)) return (string)input[key];
return defaultValue;
}
public static bool getBoolean(Dictionary<string, object> input, string key, bool defaultValue = false) {
if (input.ContainsKey(key)) return (bool)input[key];
return defaultValue;
}
public static List<object> getList(Dictionary<string, object> input, string key, List<object> defaultValue = null) {
if (input.ContainsKey(key)) return (List<object>)input[key];
return defaultValue;
}
} |
using Dapper;
using Shared.Domains;
using Shared.Domains.Enumerations;
using System.Data;
namespace Shared.Contracts.DapperExtensions
{
public interface IQueryParameters<T>
{
IQueryParameters<T> AddQueryParameter(string name, object value,
QueryType queryType = QueryType.Equal,
QueryCondition queryCondition = QueryCondition.And,
DbType? dbType = null, int groupByOrder = 0);
string GetSqlQuery(out DynamicParameters dynamicParameters);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UCPeer.Builder
{
public class NodeBuilder
{
private readonly List<MiddlewareWrapper> _middlewares = new List<MiddlewareWrapper>();
private INetwork _network;
private Func<PipelineContext, Task> _endpointAction;
public Node Build()
{
if (_network == null)
throw new NodePipelineException("A network interface must be specified");
if (_middlewares.Count == 0)
throw new NodePipelineException("At least one middleware must be specified");
var reversedMiddlewares = ((IEnumerable<MiddlewareWrapper>)_middlewares).Reverse();
return new Node(_network, _endpointAction, _middlewares, reversedMiddlewares);
}
public NodeBuilder Use(Type middlewareType, MiddlewareScope scope, object options)
{
var wrapper = new MiddlewareWrapper(middlewareType, scope, options);
_middlewares.Add(wrapper);
return this;
}
public NodeBuilder Use(Type middlewareType, MiddlewareScope scope, Type optionsType, Delegate optionsBuilder)
{
var wrapper = new MiddlewareWrapper(middlewareType, scope, optionsType, optionsBuilder);
_middlewares.Add(wrapper);
return this;
}
public NodeBuilder Use<TMiddleware>(TMiddleware singleton)
{
var wrapper = new MiddlewareWrapper(typeof(TMiddleware), singleton);
_middlewares.Add(wrapper);
return this;
}
public NodeBuilder UseNetwork(INetwork network)
{
_network = network;
return this;
}
public NodeBuilder UseEndpoint(Func<PipelineContext, Task> endpointAction)
{
_endpointAction = endpointAction;
return this;
}
}
}
|
using System;
namespace Gsemac.IO {
[Flags]
public enum FindFileOptions {
None = 0,
Default = None,
IgnoreExtension = 1,
IgnoreCase = 2
}
} |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2022 Ingo Herbote
* https://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
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types.Extensions
{
#region Using
using System;
using System.Collections.Generic;
using System.Linq;
using YAF.Types.Attributes;
#endregion
/// <summary>
/// The Enumerator Extensions
/// </summary>
public static class EnumExtensions
{
#region Public Methods
/// <summary>
/// Gets all items for an Enumerator type.
/// </summary>
/// <typeparam name="T">
/// the Typed Parameter
/// </typeparam>
/// <returns>
/// Returns all Enumerator Items
/// </returns>
public static IEnumerable<T> GetAllItems<T>() where T : struct
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
/// <summary>
/// Will get the string value for a given Enumerator value, this will
/// only work if you assign the StringValue attribute to
/// the items in your Enumerator.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string GetStringValue(this Enum value)
{
// Get the type
var type = value.GetType();
// Get field info for this type
var fieldInfo = type.GetField(value.ToString());
if (fieldInfo == null)
{
return Enum.GetName(type, value);
}
// Return the first if there was a match.
if (fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) is StringValueAttribute[] attribs)
{
return attribs.Length > 0 ? attribs[0].StringValue : Enum.GetName(type, value);
}
return Enum.GetName(type, value);
}
/// <summary>
/// Converts A Integer to an Enumerator.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <typeparam name="T">
/// The Typed Enumerator.
/// </typeparam>
/// <returns>
/// Returns the Typed Enumerator.
/// </returns>
public static T ToEnum<T>(this int value)
{
var enumType = typeof(T);
if (enumType.BaseType != typeof(Enum))
{
throw new ArgumentNullException(nameof(value), "ToEnum does not support non-enum types");
}
return (T)Enum.Parse(enumType, value.ToString());
}
/// <summary>
/// Converts A String to an Enumerator.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <typeparam name="T">
/// The Typed Enumerator.
/// </typeparam>
/// <returns>
/// Returns the Typed Enumerator.
/// </returns>
public static T ToEnum<T>(this string value)
{
var enumType = typeof(T);
if (enumType.BaseType != typeof(Enum))
{
throw new ArgumentNullException(nameof(value), "ToEnum does not support non-enum types");
}
return (T)Enum.Parse(enumType, value);
}
/// <summary>
/// Converts A String to an Enumerator.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <param name="ignoreCase">
/// The ignore Case.
/// </param>
/// <typeparam name="T">
/// The Typed Enumerator.
/// </typeparam>
/// <returns>
/// Returns the Typed Enumerator.
/// </returns>
public static T ToEnum<T>(this string value, bool ignoreCase)
{
var enumType = typeof(T);
if (enumType.BaseType != typeof(Enum))
{
throw new ArgumentNullException(nameof(value), "ToEnum does not support non-enum types");
}
return (T)Enum.Parse(enumType, value, ignoreCase);
}
/// <summary>
/// Will get the Enumerator value as an integer saving a cast
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The Integer value.
/// </returns>
public static int ToInt(this Enum value)
{
return value.ToType<int>();
}
#endregion
}
} |
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
namespace Windows.Devices.Adc
{
internal interface IAdcController
{
bool IsChannelModeSupported(AdcChannelMode channelMode);
AdcChannel OpenChannel(int channelNumber);
int ChannelCount { get; }
AdcChannelMode ChannelMode { get; set; }
int MaxValue { get; }
int MinValue { get; }
int ResolutionInBits { get; }
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Whitespace.Entities
{
/// <summary>
/// Indicates if a channel is blocked.
/// </summary>
public enum BlockedType
{
/// <summary>
/// Channel is not blocked for either mobile or fixed.
/// </summary>
None,
/// <summary>
/// Fixed devices are blocked.
/// </summary>
Fixed,
/// <summary>
/// Both Fixed and Mobile devices are blocked.
/// </summary>
Both,
/// <summary>
/// Mobile devices are blocked.
/// </summary>
Mobile
}
}
|
using System.Windows;
namespace iBank.Operator.Desktop
{
/// <summary>
/// Interaction logic for TextPopup.xaml
/// </summary>
public partial class TextPopupWindow : Window
{
public TextPopupWindow()
{
InitializeComponent();
}
public TextPopupWindow(string question, string title, string defaultValue = "")
{
InitializeComponent();
Loaded += PromptDialog_Loaded;
txtQuestion.Text = question;
Title = title;
txtResponse.Text = defaultValue;
}
private void PromptDialog_Loaded(object sender, RoutedEventArgs e) => txtResponse.Focus();
public static string? Prompt(string question, string title, string defaultValue = "")
{
var inst = new TextPopupWindow(question, title, defaultValue);
inst.ShowDialog();
return inst.DialogResult == true ? inst.ResponseText : null;
}
public string ResponseText => txtResponse.Text;
private void BtnOk_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
private void BtnCancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
|
namespace NetCoreTeamCity.Clients
{
internal interface ITeamCityApiClient
{
T Get<T>(string url);
T Post<T>(string url, T obj);
T2 Post<T1, T2>(string url, T1 obj);
T Put<T>(string url, T obj);
T2 Put<T1, T2>(string url, T1 obj);
void Delete<T>(string url, T obj);
}
} |
using System;
using System.Data;
using System.Xml.Serialization;
namespace IBatisNet.Common
{
/// <summary>
/// Factory interface to create provider specific ado.net objects.
/// </summary>
public interface IDbProvider
{
/// <summary>
/// The name of the assembly which conatins the definition of the provider.
/// </summary>
/// <example>Examples : "System.Data", "Microsoft.Data.Odbc"</example>
[XmlAttribute("assemblyName")]
string AssemblyName { get; set; }
/// <summary>
/// Tell us if it is the default data source.
/// Default false.
/// </summary>
[XmlAttribute("default")]
bool IsDefault { get; set; }
/// <summary>
/// Tell us if this provider is enabled.
/// Default true.
/// </summary>
[XmlAttribute("enabled")]
bool IsEnabled { get; set; }
/// <summary>
/// Tell us if this provider allows having multiple open <see cref="IDataReader"/> with
/// the same <see cref="IDbConnection"/>.
/// </summary>
[XmlAttribute("allowMultipleActiveDataReaders")]
bool AllowMARS { get; set; }
/// <summary>
/// An optional property to specify the DBCommand Timeout for
/// the specified provider.
/// </summary>
[XmlAttribute("commandTimeout")]
int DbCommandTimeout { get; set; }
/// <summary>
/// The connection class name to use.
/// </summary>
/// <example>
/// "System.Data.OleDb.OleDbConnection",
/// "System.Data.SqlClient.SqlConnection",
/// "Microsoft.Data.Odbc.OdbcConnection"
/// </example>
[XmlAttribute("connectionClass")]
string DbConnectionClass { get; set; }
/// <summary>
/// Does this ConnectionProvider require the use of a Named Prefix in the SQL
/// statement.
/// </summary>
/// <remarks>
/// The OLE DB/ODBC .NET Provider does not support named parameters for
/// passing parameters to an SQL Statement or a stored procedure called
/// by an IDbCommand when CommandType is set to Text.
///
/// For example, SqlClient requires select * from simple where simple_id = @simple_id
/// If this is false, like with the OleDb or Obdc provider, then it is assumed that
/// the ? can be a placeholder for the parameter in the SQL statement when CommandType
/// is set to Text.
/// </remarks>
[XmlAttribute("useParameterPrefixInSql")]
bool UseParameterPrefixInSql { get; set; }
/// <summary>
/// Does this ConnectionProvider require the use of the Named Prefix when trying
/// to reference the Parameter in the Command's Parameter collection.
/// </summary>
/// <remarks>
/// This is really only useful when the UseParameterPrefixInSql = true.
/// When this is true the code will look like IDbParameter param = cmd.Parameters["@paramName"],
/// if this is false the code will be IDbParameter param = cmd.Parameters["paramName"] - ie - Oracle.
/// </remarks>
[XmlAttribute("useParameterPrefixInParameter")]
bool UseParameterPrefixInParameter { get; set; }
/// <summary>
/// The OLE DB/OBDC .NET Provider uses positional parameters that are marked with a
/// question mark (?) instead of named parameters.
/// </summary>
[XmlAttribute("usePositionalParameters")]
bool UsePositionalParameters { get; set; }
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter size.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter size.
/// </remarks>
[XmlAttribute("setDbParameterSize")]
bool SetDbParameterSize { get; set; }
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter precision.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter precision.
/// </remarks>
[XmlAttribute("setDbParameterPrecision")]
bool SetDbParameterPrecision { get; set; }
/// <summary>
/// Used to indicate whether or not the provider
/// supports a parameter scale.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter scale.
/// </remarks>
[XmlAttribute("setDbParameterScale")]
bool SetDbParameterScale { get; set; }
/// <summary>
/// Used to indicate whether or not the provider
/// supports DeriveParameters method for procedure.
/// </summary>
[XmlAttribute("useDeriveParameters")]
bool UseDeriveParameters { get; set; }
/// <summary>
/// The command class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlClient.SqlCommand"
/// </example>
[XmlAttribute("commandClass")]
string DbCommandClass { get; set; }
/// <summary>
/// The ParameterDbType class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("parameterDbTypeClass")]
string ParameterDbTypeClass { get; set; }
/// <summary>
/// The ParameterDbTypeProperty class name to use.
/// </summary>
/// <example >
/// SqlDbType in SqlParamater.SqlDbType,
/// OracleType in OracleParameter.OracleType.
/// </example>
[XmlAttribute("parameterDbTypeProperty")]
string ParameterDbTypeProperty { get; set; }
/// <summary>
/// The dataAdapter class name to use.
/// </summary>
/// <example >
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("dataAdapterClass")]
string DataAdapterClass { get; set; }
/// <summary>
/// The commandBuilder class name to use.
/// </summary>
/// <example >
/// "System.Data.OleDb.OleDbCommandBuilder",
/// "System.Data.SqlClient.SqlCommandBuilder",
/// "Microsoft.Data.Odbc.OdbcCommandBuilder"
/// </example>
[XmlAttribute("commandBuilderClass")]
string CommandBuilderClass { get; set; }
/// <summary>
/// Name used to identify the provider amongst the others.
/// </summary>
[XmlAttribute("name")]
string Name { get; set; }
/// <summary>
/// Description.
/// </summary>
[XmlAttribute("description")]
string Description { get; set; }
/// <summary>
/// Parameter prefix use in store procedure.
/// </summary>
/// <example> @ for Sql Server.</example>
[XmlAttribute("parameterPrefix")]
string ParameterPrefix { get; set; }
/// <summary>
/// Check if this provider is Odbc ?
/// </summary>
[XmlIgnore]
bool IsObdc { get; }
/// <summary>
/// Create a connection object for this provider.
/// </summary>
/// <returns>An 'IDbConnection' object.</returns>
IDbConnection CreateConnection();
/// <summary>
/// Create a command object for this provider.
/// </summary>
/// <returns>An 'IDbCommand' object.</returns>
IDbCommand CreateCommand();
/// <summary>
/// Create a dataAdapter object for this provider.
/// </summary>
/// <returns>An 'IDbDataAdapter' object.</returns>
IDbDataAdapter CreateDataAdapter();
/// <summary>
/// Create a IDataParameter object for this provider.
/// </summary>
/// <returns>An 'IDbDataParameter' object.</returns>
IDbDataParameter CreateDataParameter();
/// <summary>
/// Create the CommandBuilder Type for this provider.
/// </summary>
/// <returns>An object.</returns>
Type CommandBuilderType { get; }
/// <summary>
/// Get the ParameterDb Type for this provider.
/// </summary>
/// <returns>An object.</returns>
Type ParameterDbType { get; }
/// <summary>
/// Change the parameterName into the correct format IDbCommand.CommandText
/// for the ConnectionProvider
/// </summary>
/// <param name="parameterName">The unformatted name of the parameter</param>
/// <returns>A parameter formatted for an IDbCommand.CommandText</returns>
string FormatNameForSql(string parameterName);
/// <summary>
/// Changes the parameterName into the correct format for an IDbParameter
/// for the Driver.
/// </summary>
/// <remarks>
/// For SqlServerConnectionProvider it will change <c>id</c> to <c>@id</c>
/// </remarks>
/// <param name="parameterName">The unformatted name of the parameter</param>
/// <returns>A parameter formatted for an IDbParameter.</returns>
string FormatNameForParameter(string parameterName);
/// <summary>
/// Init the provider.
/// </summary>
void Initialize();
}
} |
using System;
using System.Reflection;
namespace Core.Reflection.Contracts
{
public interface IReflectionClient : IDisposable
{
string BaseAssemblyPath { get; }
Assembly CurrentAssembly { get; }
}
}
|
using DFC.App.CareerPath.FunctionalTests.Model.API;
using RestSharp;
using System.Threading.Tasks;
namespace DFC.App.CareerPath.FunctionalTests.Support.API
{
public interface ICareerPathAPI
{
Task<IRestResponse<CareerPathAPIResponse>> GetById(string id);
}
}
|
namespace Shouldly.MessageGenerators
{
internal class ShouldContainWithinRangeMessageGenerator : ShouldlyMessageGenerator
{
public override bool CanProcess(IShouldlyAssertionContext context)
{
return context.ShouldMethod.StartsWith("Should")
&& context.ShouldMethod.Contains("Contain")
&& context.Tolerance != null;
}
public override string GenerateErrorMessage(IShouldlyAssertionContext context)
{
var codePart = context.CodePart;
var tolerance = context.Tolerance.ToStringAwesomely();
var expectedValue = context.Expected.ToStringAwesomely();
var actualValue = context.Actual.ToStringAwesomely();
var negated = context.ShouldMethod.Contains("Not") ? "not " : string.Empty;
var actualValueString = codePart == actualValue ? " not" : $@"
{actualValue}";
return
$@"{codePart}
should {negated}contain
{expectedValue}
within
{tolerance}
but was{actualValueString}";
}
}
} |
namespace ThreeDPrinting.Tests.Controllers.Admin.HomeController
{
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThreeDPrinting.Models;
using ThreeDPrinting.Tests.Mocks;
using ThreeDPrinting.Web.Areas.Admin.Controllers;
using ThreeDPrinting.Web.Data;
[TestClass]
public class IndexTests
{
private ThreeDPrintingDbContext dbContext;
private IMapper mapper;
private UserManager<User> userManager;
[TestMethod]
public void Index_ReturnsTheProperView()
{
// Arrange
var controller = new HomeController();
// Act
var result = controller.Index();
// Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
}
[TestInitialize]
public void InitializeTests()
{
this.dbContext = MockDbContext.GetContext();
this.mapper = MockAutoMapper.GetMapper();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace DissectingAsyncMethods
{
public struct _GetStockPriceForAsync_d__1 : IAsyncStateMachine
{
public StockPrices __this;
public string companyId;
public AsyncTaskMethodBuilder<decimal> __builder;
public int __state;
private TaskAwaiter __task1Awaiter;
[AsyncStateMachine(typeof(_GetStockPriceForAsync_d__1))]
public Task<decimal> GetStockPriceFor(string companyId)
{
_GetStockPriceForAsync_d__1 _GetStockPriceFor_d__ = default;
_GetStockPriceFor_d__.__this = new StockPrices(); // here has to be __this = this;
_GetStockPriceFor_d__.companyId = companyId;
_GetStockPriceFor_d__.__builder = AsyncTaskMethodBuilder<decimal>.Create();
_GetStockPriceFor_d__.__state = -1;
var __t__builder = _GetStockPriceFor_d__.__builder;
__t__builder.Start<_GetStockPriceForAsync_d__1>(ref _GetStockPriceFor_d__);
return _GetStockPriceFor_d__.__builder.Task;
}
public void MoveNext()
{
decimal result;
try
{
TaskAwaiter awaiter;
if (__state != 0)
{
// State 1 of the generated state machine:
if (string.IsNullOrEmpty(companyId))
throw new ArgumentNullException();
awaiter = __this.InitializeMapIfNeededAsync().GetAwaiter();
// Hot path optimization: if the task is completed,
// the state machine automatically moves to the next step
if (!awaiter.IsCompleted)
{
__state = 0;
__task1Awaiter = awaiter;
// The following call will eventually cause boxing of the state machine.
__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
return;
}
}
else
{
awaiter = __task1Awaiter;
__task1Awaiter = default(TaskAwaiter);
__state = -1;
}
// GetResult returns void, but it'll throw if the awaited task failed.
// This exception is catched later and changes the resulting task.
awaiter.GetResult();
__this._stockPrices.TryGetValue(companyId, out result);
}
catch (Exception exception)
{
// Final state: failure
__state = -2;
__builder.SetException(exception);
return;
}
// Final state: success
__state = -2;
__builder.SetResult(result);
}
void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
{
__builder.SetStateMachine(stateMachine);
}
}
}
|
using System.Collections.Generic;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
namespace NetTopologySuite.Operation.Distance
{
/// <summary>
/// Extracts a single point
/// from each connected element in a Geometry
/// (e.g. a polygon, linestring or point)
/// and returns them in a list
/// </summary>
public class ConnectedElementPointFilter : IGeometryFilter
{
/// <summary>
/// Returns a list containing a Coordinate from each Polygon, LineString, and Point
/// found inside the specified point. Thus, if the specified point is
/// not a GeometryCollection, an empty list will be returned.
/// </summary>
public static IList<Coordinate> GetCoordinates(Geometry geom)
{
var pts = new List<Coordinate>();
geom.Apply(new ConnectedElementPointFilter(pts));
return pts;
}
private readonly IList<Coordinate> _pts;
/// <summary>
///
/// </summary>
/// <param name="pts"></param>
ConnectedElementPointFilter(IList<Coordinate> pts)
{
_pts = pts;
}
/// <summary>
///
/// </summary>
/// <param name="geom"></param>
public void Filter(IGeometry geom)
{
if (geom is IPoint || geom is ILineString || geom is IPolygon)
_pts.Add(geom.Coordinate);
}
}
}
|
// ================================================================================================
// <summary>
// ゲーム開始ユースケースソース</summary>
//
// <copyright file="StartGameUseCase.cs">
// Copyright (C) 2018 Koichi Tanaka. All rights reserved.</copyright>
// <author>
// Koichi Tanaka</author>
// ================================================================================================
namespace Honememo.RougeLikeMmo.UseCases
{
using System.Threading.Tasks;
using Zenject;
using Honememo.RougeLikeMmo.Entities;
using Honememo.RougeLikeMmo.Gateways;
/// <summary>
/// ゲーム開始ユースケースクラス。
/// </summary>
public class StartGameUseCase
{
#region 内部変数
/// <summary>
/// グローバルデータ。
/// </summary>
[Inject]
private Global global = null;
/// <summary>
/// ゲームリポジトリ。
/// </summary>
[Inject]
private GameRepository gameRepository = null;
#endregion
#region 公開メソッド
/// <summary>
/// ゲームを開始する。
/// </summary>
/// <param name="pcId">使用するPCのID。</param>
/// <param name="dungeonId">プレイするダンジョンのID。</param>
/// <returns>処理状態。</returns>
public async Task Start(int pcId, int dungeonId)
{
var pc = this.global.PlayerCharacterEntities[pcId];
var dungeon = this.global.DungeonEntities[dungeonId];
var url = await this.gameRepository.Start(pcId, dungeonId);
// 開始されたゲームと接続先URLを保存
this.global.GameEntity = new GameEntity() {
PlayerCharacter = pc,
Dungeon = dungeon,
Url = url,
};
}
#endregion
}
} |
using tvn.cosine.api;
using tvn.cosine.ai.util;
namespace tvn.cosine.ai.agent.agentprogram.simplerule
{
/// <summary>
/// Base abstract class for describing conditions.
/// </summary>
public abstract class Condition : IEquatable, IHashable, IStringable
{
public abstract bool evaluate(ObjectWithDynamicAttributes p);
public override bool Equals(object o)
{
return o != null
&& GetType() == o.GetType()
&& ToString().Equals(o.ToString());
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
return base.ToString();
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Cli.FunctionalTests.Templates
{
public class AngularTemplate : SpaBaseTemplate
{
public AngularTemplate() { }
public override string Name => "angular";
protected override IEnumerable<string> NormalizeFilesAfterPublish(IEnumerable<string> filesAfterPublish)
{
// Remove generated hashes since they may vary by platform
return base.NormalizeFilesAfterPublish(filesAfterPublish)
.Select(f => Regex.Replace(f, @"\.[0-9a-f]{20}\.", ".[HASH]."));
}
public override IEnumerable<string> ExpectedFilesAfterPublish =>
base.ExpectedFilesAfterPublish
.Concat(new[]
{
Path.Combine("wwwroot", "favicon.ico"),
Path.Combine("ClientApp", "dist", "3rdpartylicenses.txt"),
Path.Combine("ClientApp", "dist", "index.html"),
Path.Combine("ClientApp", "dist", $"runtime.[HASH].js"),
Path.Combine("ClientApp", "dist", $"main.[HASH].js"),
Path.Combine("ClientApp", "dist", $"polyfills.[HASH].js"),
Path.Combine("ClientApp", "dist", $"styles.[HASH].css"),
});
}
}
|
using Mapsui.Geometries;
using System;
namespace Mapsui.Widgets
{
public abstract class Widget : IWidget
{
public HorizontalAlignment HorizontalAlignment { get; set; } = HorizontalAlignment.Right;
public VerticalAlignment VerticalAlignment { get; set; } = VerticalAlignment.Bottom;
public float MarginX { get; set; } = 2;
public float MarginY { get; set; } = 2;
public BoundingBox Envelope { get; set; }
public float CalculatePositionX(float left, float right, float width)
{
switch (HorizontalAlignment)
{
case HorizontalAlignment.Left:
return MarginX;
case HorizontalAlignment.Center:
return (right - left - width) / 2;
case HorizontalAlignment.Right:
return right - left - width - MarginX;
}
throw new ArgumentException("Unknown horizontal alignment: " + HorizontalAlignment);
}
public float CalculatePositionY(float top, float bottom, float height)
{
switch (VerticalAlignment)
{
case VerticalAlignment.Top:
return MarginY;
case VerticalAlignment.Bottom:
return bottom - top - height - MarginY;
case VerticalAlignment.Center:
return (bottom - top - height) / 2;
}
throw new ArgumentException("Unknown vertical alignment: " + VerticalAlignment);
}
public abstract void HandleWidgetTouched(INavigator navigator, Point position);
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
using Xamarin.Forms.Core.UITests;
#endif
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Github, 13577,
"[Bug][DatePicker][XF5] DatePicker empty format now invalid",
PlatformAffected.iOS)]
public partial class Issue13577 : TestContentPage
{
public Issue13577()
{
#if APP
InitializeComponent();
#endif
}
protected override void Init()
{
BindingContext = new Issue13577ViewModel();
}
}
public class Issue13577ViewModel
{
public Issue13577ViewModel()
{
NullableDate = null;
}
public DateTime? NullableDate { get; set; }
}
public class NullableDatePicker : Xamarin.Forms.DatePicker
{
public static readonly BindableProperty NullableDateProperty = BindableProperty.Create("NullableDate", typeof(DateTime?), typeof(NullableDatePicker), null, BindingMode.TwoWay);
public DateTime? NullableDate
{
get
{
return (DateTime?)GetValue(NullableDateProperty);
}
set
{
if (value != NullableDate)
{
SetValue(NullableDateProperty, value);
UpdateDate();
}
}
}
public void CleanDate()
{
NullableDate = null;
UpdateDate();
}
public void AssignValue()
{
NullableDate = Date;
UpdateDate();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
UpdateDate();
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == IsFocusedProperty.PropertyName)
{
if (!IsFocused)
{
OnPropertyChanged(DateProperty.PropertyName);
}
}
if (propertyName == DateProperty.PropertyName)
{
NullableDate = Date;
}
if (propertyName == NullableDateProperty.PropertyName)
{
if (NullableDate.HasValue)
{
Date = NullableDate.Value;
Format = "dd-MM-yyyy";
}
else
{
Format = " ";
}
}
}
private void UpdateDate()
{
if (NullableDate.HasValue)
{
Date = NullableDate.Value;
Format = "dd-MM-yyyy";
}
else
{
Format = " ";
}
}
}
} |
using EventCentric.Publishing;
using EventCentric.Publishing.Dto;
using EventCentric.Transport;
namespace EventCentric.Messaging
{
public interface IInMemoryEventPublisherRegistry
{
void Register(IPollableEventSource publisher);
}
public interface IInMemoryEventPublisher : IInMemoryEventPublisherRegistry
{
PollResponse PollEvents(string streamType, long fromVersion, string consumerName);
bool TryUpdateConsumer(string serverName, PollResponse response, out ServerStatus status);
}
}
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Debugger.Interop;
using AndroidPlusPlus.Common;
using AndroidPlusPlus.VsDebugCommon;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace AndroidPlusPlus.VsDebugEngine
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[ComVisible (true)]
[Guid (DebugEngineGuids.guidDebugProgramProviderStringCLSID)]
[ClassInterface (ClassInterfaceType.None)]
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class DebugProgramProvider : IDebugProgramProvider2
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#region IDebugProgramProvider2 Members
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int GetProviderProcessData (enum_PROVIDER_FLAGS Flags, IDebugDefaultPort2 port, AD_PROCESS_ID ProcessId, CONST_GUID_ARRAY EngineFilter, PROVIDER_PROCESS_DATA [] processArray)
{
//
// Retrieves a list of running programs from a specified process.
//
LoggingUtils.PrintFunction ();
try
{
processArray [0] = new PROVIDER_PROCESS_DATA ();
if ((Flags & enum_PROVIDER_FLAGS.PFLAG_GET_PROGRAM_NODES) != 0)
{
// The debugger is asking the engine to return the program nodes it can debug. The
// sample engine claims that it can debug all processes, and returns exactly one
// program node for each process. A full-featured debugger may wish to examine the
// target process and determine if it understands how to debug it.
IDebugProgramNode2 node = (IDebugProgramNode2)(new DebuggeeProgram (null));
IntPtr [] programNodes = { Marshal.GetComInterfaceForObject (node, typeof (IDebugProgramNode2)) };
IntPtr destinationArray = Marshal.AllocCoTaskMem (IntPtr.Size * programNodes.Length);
Marshal.Copy (programNodes, 0, destinationArray, programNodes.Length);
processArray [0].Fields = enum_PROVIDER_FIELDS.PFIELD_PROGRAM_NODES;
processArray [0].ProgramNodes.Members = destinationArray;
processArray [0].ProgramNodes.dwCount = (uint)programNodes.Length;
return Constants.S_OK;
}
return Constants.S_FALSE;
}
catch (Exception e)
{
LoggingUtils.HandleException (e);
return Constants.E_FAIL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int GetProviderProgramNode (enum_PROVIDER_FLAGS Flags, IDebugDefaultPort2 pPort, AD_PROCESS_ID ProcessId, ref Guid guidEngine, ulong programId, out IDebugProgramNode2 ppProgramNode)
{
//
// Retrieves the program node for a specific program. Not implemented.
//
LoggingUtils.PrintFunction ();
ppProgramNode = null;
// This method is used for Just-In-Time debugging support, which this program provider does not support
return Constants.E_NOTIMPL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int SetLocale (ushort wLangID)
{
//
// Establishes a locale to be used for any locale-specific resources.
//
LoggingUtils.PrintFunction ();
return Constants.S_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int WatchForProviderEvents (enum_PROVIDER_FLAGS Flags, IDebugDefaultPort2 pPort, AD_PROCESS_ID ProcessId, CONST_GUID_ARRAY EngineFilter, ref Guid guidLaunchingEngine, IDebugPortNotify2 pEventCallback)
{
//
// Allows the process to be notified of port events.
//
// The sample debug engine is a native debugger, and can therefore always provide a program node
// in GetProviderProcessData. Non-native debuggers may wish to implement this method as a way
// of monitoring the process before code for their runtime starts. For example, if implementing a
// 'foo script' debug engine, one could attach to a process which might eventually run 'foo script'
// before this 'foo script' started.
//
// To implement this method, an engine would monitor the target process and call AddProgramNode
// when the target process started running code which was debuggable by the engine. The
// enum_PROVIDER_FLAGS.PFLAG_ATTACHED_TO_DEBUGGEE flag indicates if the request is to start
// or stop watching the process.
LoggingUtils.PrintFunction ();
return Constants.S_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
/*
*
* XMLTree.cs
*
* Copyright 2017 Yuichi Yoshii
* 吉井雄一 @ 吉井産業 you.65535.kir@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using SAXWrapper;
using System.Windows.Controls;
namespace Tree {
public class XMLTree {
#region -- Private Fields --
private TreeView tree;
private XMLNode root;
#endregion -- Private Fields --
#region -- Getter --
public TreeView GetTree() {
return tree;
}
#endregion -- Getter --
#region -- Constructor --
public XMLTree() {
}
#endregion -- Constructor --
#region -- Public Methods --
public virtual void Prepare(TreeView arg) {
tree = arg;
PrepareMouseGesture(arg);
PrepareContextMenu(arg);
}
public virtual void Tree(NodeEntity arg) {
if (tree.Items != null) {
tree.Items.Clear();
}
root = new XMLNode();
root.SetNode(arg);
root.SetTree(this);
root.Tree();
tree.Items.Add(root);
}
public void Refresh(NodeEntity arg) {
TreeViewItem oldRoot = root;
Tree(arg);
XMLNode oldNode = oldRoot as XMLNode;
XMLNode newNode = root as XMLNode;
Refresh(oldNode, newNode);
}
#endregion -- Public Methods --
#region -- Private Methods --
private void Refresh(XMLNode oldNode, XMLNode newNode) {
if (oldNode.IsExpanded) {
newNode.IsExpanded = true;
int count = oldNode.Items.Count;
if (newNode.Items.Count == 0) {
return;
}
for (int i = 0; i < count; i++) {
XMLNode oldChild = oldNode.Items[i] as XMLNode;
if (newNode.Items.Count < i) {
return;
}
XMLNode newChild = newNode.Items[i] as XMLNode;
if (oldChild != null && newChild != null) {
Refresh(oldChild, newChild);
}
}
}
}
#endregion -- Private Methods --
#region -- Mouse Gesture --
private void PrepareMouseGesture(TreeView arg) {
arg.AllowDrop = true;
arg.PreviewMouseLeftButtonDown += OnPreviewLeftDown;
arg.MouseMove += OnMove;
}
private System.Windows.Point p;
private void OnPreviewLeftDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
try {
p = e.GetPosition(tree);
} catch (System.Exception ex) {
System.Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
}
}
private void OnMove(object sender, System.Windows.Input.MouseEventArgs e) {
try {
if (e.LeftButton == System.Windows.Input.MouseButtonState.Released) {
return;
}
System.Windows.Point senderPos = e.GetPosition(tree);
double moveX = p.X - senderPos.X;
double moveY = p.Y - senderPos.Y;
if (moveX < 0) {
moveX = moveX * -1;
}
if (moveY < 0) {
moveY = moveY * -1;
}
if (moveY / System.Math.Sin(System.Math.Atan(moveY / moveX)) > 10) {
System.Windows.DragDrop.DoDragDrop(tree, tree.SelectedItem, System.Windows.DragDropEffects.Move);
}
} catch (System.Exception ex) {
System.Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
}
}
#endregion -- Mouse Gesture --
#region -- Context Menu --
private void PrepareContextMenu(TreeView arg) {
ContextMenu m = new ContextMenu();
MenuItem add1 = new MenuItem();
add1.Name = @"Context_Upward";
add1.Header = @"Upward";
add1.Click += Upward_Click;
m.Items.Add(add1);
MenuItem add2 = new MenuItem();
add2.Name = @"Context_Downward";
add2.Header = @"Downward";
add2.Click += Downward_Click;
m.Items.Add(add2);
arg.ContextMenu = m;
}
private void Upward_Click(object sender, System.Windows.RoutedEventArgs e) {
try {
XMLNode n = tree.SelectedItem as XMLNode;
if (n == null) {
return;
}
NodeEntity newRoot = root.GetNode().Clone();
newRoot.MoveUpByID(n.GetNode().GetNodeID());
Refresh(newRoot);
} catch (System.Exception ex) {
System.Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
}
}
private void Downward_Click(object sender, System.Windows.RoutedEventArgs e) {
try {
XMLNode n = tree.SelectedItem as XMLNode;
if (n == null) {
return;
}
NodeEntity newRoot = root.GetNode().Clone();
newRoot.MoveDownByID(n.GetNode().GetNodeID());
Refresh(newRoot);
} catch (System.Exception ex) {
System.Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
}
}
#endregion -- Context Menu --
}
} |
using System;
using System.Collections.Generic;
using System.Reflection;
using Android.Content;
using Cirrious.MvvmCross.Droid.Platform;
using Cirrious.MvvmCross.Application;
using Cirrious.MvvmCross.Binding.Droid;
using Cirrious.MvvmCross.Interfaces.ServiceProvider;
using Cirrious.MvvmCross.Interfaces.ViewModels;
using CustomerManagement.Core;
using CustomerManagement.Core.ViewModels;
using CustomerManagement.Droid.Views;
namespace CustomerManagement.Droid
{
public class Setup
: MvxBaseAndroidBindingSetup
{
public Setup(Context applicationContext)
: base(applicationContext)
{
}
protected override MvxApplication CreateApp()
{
var app = new App();
return app;
}
}
} |
namespace exclucv.Repository.RepositoryContracts
{
using exclucv.DAL.Entities;
using System;
using System.Threading.Tasks;
public interface IApplicationUserRepository : IRepository<Template>
{
Task<User> Register(User user);
bool IsExistingUser(string email);
User GetUserByEmail(string email);
User GetUserInfo(Guid userId);
}
}
|
using PiRhoSoft.Utilities.Editor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace PiRhoSoft.Utilities.Samples
{
public class FrameCodeSample : CodeSample
{
public override void Create(VisualElement root)
{
var frame = new Frame();
frame.IsCollapsable = true;
frame.IsCollapsed = false;
frame.Label = "Sample Frame";
frame.Tooltip = "This is an example of a standalone frame";
frame.AddHeaderButton(Icon.Info.Texture, "Header Button", null, () => Debug.Log("Header button clicked"));
root.Add(frame);
frame.Add(new IntegerField("Child Int"));
frame.Add(new Slider("Child Slider"));
frame.Add(new Toggle("Child Toggle"));
var isCollapsableToggle = new Toggle(nameof(Frame.IsCollapsable));
isCollapsableToggle.value = frame.IsCollapsable;
isCollapsableToggle.RegisterValueChangedCallback(e => frame.IsCollapsable = e.newValue);
root.Add(isCollapsableToggle);
var isCollapsedToggle = new Toggle(nameof(Frame.IsCollapsed));
isCollapsedToggle.value = frame.IsCollapsed;
isCollapsedToggle.RegisterValueChangedCallback(e => frame.IsCollapsed = e.newValue);
root.Add(isCollapsedToggle);
var labelText = new TextField(nameof(Frame.Label));
labelText.value = frame.Label;
labelText.RegisterValueChangedCallback(e => frame.Label = e.newValue);
root.Add(labelText);
var tooltipText = new TextField(nameof(Frame.Tooltip));
tooltipText.value = frame.Tooltip;
tooltipText.RegisterValueChangedCallback(e => frame.Tooltip = e.newValue);
root.Add(tooltipText);
}
}
}
|
@model CurrencyConverter
@{
decimal priceRUB = 1000;
}
<div>
Цена товара в российских рублях: @priceRUB руб.
<div>
@($"Курс доллара: {Model.USD}. Цена в долларах: {Decimal.Round(Model.ConvertToUSD(priceRUB), 2)}")
</div>
<div>
@($"Курс евро: {Model.EUR}. Цена в евро: {Decimal.Round(Model.ConvertToEUR(priceRUB), 2)}")
</div>
<div>
@($"Курс гривны: {Model.UAN / 10}. Цена в гривнах: {Decimal.Round(Model.ConvertToUAN(priceRUB), 2)}")
</div>
</div> |
using RoboBogus.Conventions;
using RoboBogus;
interface IAutoConventionGenerator
{
bool CanGenerate(AutoConventionConfig config, AutoGenerateContext context);
object Generate(AutoConventionContext context);
} |
using System;
class EmployeeData
{
static void Main()
{
Random randomGenerator = new Random();
string firstName = "Mariyan";
string lastName = "Vasilev";
byte age = 23;
bool isMale = true;
long personalID = (long)((randomGenerator.NextDouble() * 2.0 - 1.0) * 9999999999);
string uniqueEmployee = randomGenerator.Next(27560000, 27569999).ToString();
Console.WriteLine("First name: {0}\n" + "Last name: {1}\n" + "Age: {2}\n" +
"Male: {3}\n" + "Personal ID: {4}\n" + "Unique employee number: {5}",
firstName, lastName, age, isMale, personalID, uniqueEmployee);
}
}
|
using System;
using System.Data.Entity;
using System.Threading.Tasks;
using Farming.WpfClient.Models;
using MaterialDesignThemes.Wpf;
namespace Farming.WpfClient.ViewModels.Database
{
public class UsersTypesViewModel : DatabaseTableViewModel<UserTypeViewModel>
{
public UsersTypesViewModel(ISnackbarMessageQueue snackbarMessageQueue, User user)
: base("Типы пользователей", user, snackbarMessageQueue)
{
}
protected async override Task UpdateAsync(FarmingEntities db)
{
var usersTypes = await db.UsersTypes.ToArrayAsync();
foreach (var userType in usersTypes)
{
Models.Add(new UserTypeViewModel()
{
Id = userType.Id,
Name = userType.Name
});
}
}
protected override Task AddAsync(FarmingEntities db, UserTypeViewModel model)
{
throw new NotImplementedException();
}
protected override Task UpdateAsync(FarmingEntities db, UserTypeViewModel model)
{
throw new NotImplementedException();
}
protected override Task DeleteAsync(FarmingEntities db, UserTypeViewModel model)
{
throw new NotImplementedException();
}
}
}
|
using System;
using UnityEngine;
public class OdeJointHinge : OdeJoint
{
public Vector3 anchor
{
get
{
Vector3 v;
UnityOde.odeJointGetHingeAnchor(JointId, out v.x, out v.y, out v.z);
return v;
}
set
{
UnityOde.odeJointSetHingeAnchor(JointId, value.x, value.y, value.z);
}
}
public float loStop
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.LoStop);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.LoStop, value);
}
}
public float hiStop
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.HiStop);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.HiStop, value);
}
}
public float fmax
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.FMax);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.FMax, value);
}
}
public float fudgeFactor
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.FudgeFactor);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.FudgeFactor, value);
}
}
public float stopERP
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.StopERP);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.StopERP, value);
}
}
public float stopCFM
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.StopCFM);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.StopCFM, value);
}
}
public float cfm
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.CFM);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.CFM, value);
}
}
public float erp
{
get
{
return UnityOde.odeJointGetHingeParam(JointId, (int)OdeWrapper.OdeParam.ERP);
}
set
{
UnityOde.odeJointSetHingeParam(JointId, (int)OdeWrapper.OdeParam.ERP, value);
}
}
public override Vector3? getAnchor()
{
Vector3 v = new Vector3();
UnityOde.odeJointGetHingeAnchor(JointId, out v.x, out v.y, out v.z);
return v;
}
public override void setAnchor(Vector3 anchor)
{
this.anchor = anchor;
}
public Vector3 axis
{
get
{
Vector3 v = new Vector3();
UnityOde.odeJointGetHingeAxis(JointId, out v.x, out v.y, out v.z);
return v;
}
set
{
UnityOde.odeJointSetHingeAxis(JointId, value.x, value.y, value.z);
localAxes[0] = Quaternion.Inverse(axesRel[0].rotation) * value;
}
}
protected override void Awake()
{
JointId = UnityOde.odeJointCreateHinge();
//Debug.Log("Created hinge joint: " + name);
base.Awake();
}
protected override void Start()
{
// transform.position = anchor;
base.Start();
}
protected override void FixedUpdate()
{
if (!disableUpdate)
{
transform.position = anchor;
}
base.FixedUpdate();
}
new void OnDrawGizmosSelected()
{
if (!drawGizmos)
{
return;
}
UnityOde.setCurrentOdeContext(myContext);
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(anchor, 0.05f);
Gizmos.DrawLine(anchor, anchor + axis);
base.OnDrawGizmosSelected();
}
}
|
// Copyright 2018 Ionx Solutions (https://www.ionxsolutions.com)
// Ionx Solutions licenses this file to you under the Apache License,
// Version 2.0. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Serilog.Events;
using Serilog.Sinks.PeriodicBatching;
namespace Serilog.Sinks.Syslog
{
/// <summary>
/// Sink that writes events to a remote syslog service using UDP
/// </summary>
public class SyslogUdpSink : PeriodicBatchingSink
{
private readonly ISyslogFormatter formatter;
private UdpClient client;
private readonly IPEndPoint endpoint;
private bool disposed;
public SyslogUdpSink(IPEndPoint endpoint, ISyslogFormatter formatter, BatchConfig batchConfig)
: base(batchConfig.BatchSizeLimit, batchConfig.Period, batchConfig.QueueSizeLimit)
{
this.formatter = formatter;
this.endpoint = endpoint;
this.client = new UdpClient();
}
/// <summary>
/// Emit a batch of log events, running asynchronously.
/// </summary>
/// <param name="events">The events to send to the syslog service</param>
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
foreach (var logEvent in events)
{
var message = this.formatter.FormatMessage(logEvent);
var data = Encoding.UTF8.GetBytes(message);
try
{
await this.client.SendAsync(data, data.Length, this.endpoint).ConfigureAwait(false);
}
catch (SocketException ex)
{
Console.WriteLine(ex);
}
}
}
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
// If disposing == true, we're being called from an inheriting class calling base.Dispose()
if (disposing)
{
this.client.Close();
this.client.Dispose();
this.client = null;
}
this.disposed = true;
}
base.Dispose(disposing);
}
}
}
|
using Unity.Cloud.Collaborate.Presenters;
using Unity.Cloud.Collaborate.Views;
namespace Unity.Cloud.Collaborate.Tests.Presenters
{
internal class TestStartView : IStartView
{
public bool buttonVisible;
public IStartPresenter Presenter { get; set; }
public string Text { get; set; }
public string ButtonText { get; set; }
public void SetButtonVisible(bool isVisible)
{
buttonVisible = isVisible;
}
}
}
|
/* SerializableInt.cs, CWebb.
*/
using UnityEngine;
[CreateAssetMenu(menuName = "Serializable/Int", fileName = "New Serializable Int")]
public class SerializableInt : Serializable<int> { } |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractWithPhysics : MonoBehaviour
{
void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
if (body != null && !body.isKinematic)
body.velocity += hit.controller.velocity;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DogsIRL.Services
{
public interface INotificationRegistrationService
{
Task DeregisterDeviceAsync();
Task RegisterDeviceAsync(params string[] tags);
Task RefreshRegistrationAsync();
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using Drachenhorn.Core.IO;
using Drachenhorn.Core.Lang;
using Drachenhorn.Core.UI;
using Drachenhorn.Desktop.Views;
using Drachenhorn.Xml.Sheet.Common;
using GalaSoft.MvvmLight.Ioc;
namespace Drachenhorn.Desktop.UserControls
{
/// <summary>
/// Interaktionslogik für CoatOfArmsControl.xaml
/// </summary>
public partial class CoatOfArmsControl : UserControl
{
#region c'tor
public CoatOfArmsControl()
{
InitializeComponent();
}
#endregion
private void EditButton_Click(object sender, RoutedEventArgs e)
{
if (!(DataContext is CoatOfArms))
return;
if (!string.IsNullOrEmpty(((CoatOfArms) DataContext).Base64String))
{
var result = MessageFactory.NewMessage()
.MessageTranslated("Dialog.Replace")
.TitleTranslated("Dialog.Replace_Caption")
.ButtonTranslated("Dialog.Yes", 0)
.ButtonTranslated("Dialog.No")
.ShowMessage().Result;
if (result != 0)
return;
}
var view = new CoatOfArmsPainterView();
view.Closing += (s, args) =>
{
if (view.DialogResult == true)
((CoatOfArms) DataContext).Base64String = view.GetBase64();
};
view.ShowDialog();
}
private void ClearButton_OnClick(object sender, RoutedEventArgs e)
{
((CoatOfArms) DataContext).Base64String = null;
}
private void ImportButton_OnClick(object sender, RoutedEventArgs e)
{
var data = SimpleIoc.Default.GetInstance<IIoService>().OpenDataDialog(
".png",
LanguageManager.Translate("PNG.FileType.Name"),
LanguageManager.Translate("UI.Import"));
if (data != null)
((CoatOfArms) DataContext).Base64String = Convert.ToBase64String(data);
}
private void ExportButton_OnClick(object sender, RoutedEventArgs e)
{
var image = ((CoatOfArms) DataContext).Base64String;
if (image == null) return;
var data = Convert.FromBase64String(image);
SimpleIoc.Default.GetInstance<IIoService>().SaveDataDialog(
LanguageManager.Translate("CharacterSheet.CoatOfArms").Replace("/", "_"),
".png",
LanguageManager.Translate("PNG.FileType.Name"),
LanguageManager.Translate("UI.Export"),
data);
}
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RevendaDeCarro.model
{
class Carro : IComparable
{
public int codigo { get; private set; }
public string modelo { get; private set; }
public int ano { get; private set; }
public double precoBasico { get; private set; }
public Marca marca { get; private set; }
public List<Acessorio> acessorios { get; private set; }
public Carro(int codigo, string modelo, int ano, double precoBasico, Marca marca)
{
this.codigo = codigo;
this.modelo = modelo;
this.ano = ano;
this.precoBasico = precoBasico;
this.marca = marca;
acessorios = new List<Acessorio>();
}
public double precoTotal()
{
double custoAcessorio = 0.00;
foreach (Acessorio acessorio in acessorios)
custoAcessorio += acessorio.preco;
return precoBasico + custoAcessorio;
}
public void adicionarAcessorio(Acessorio acessorio)
{
acessorios.Add(acessorio);
}
public override string ToString()
{
string carro = "";
carro = codigo + ", " + modelo + ", Ano: " + ano
+ ", Preço básico: " + precoBasico.ToString("F2", CultureInfo.InvariantCulture)
+ ", Preço total: " + precoTotal().ToString("F2", CultureInfo.InvariantCulture)
+ "\n";
if (acessorios.Count > 0)
{
carro += "Acessórios: \n";
foreach (Acessorio acessorio in acessorios)
carro += acessorio + "\n";
}
return carro;
}
public int CompareTo(object obj)
{
Carro outroCarro = (Carro)obj;
int resultado = modelo.CompareTo(outroCarro.modelo);
if (resultado != 0)
return resultado;
return -precoBasico.CompareTo(outroCarro.precoTotal());
}
}
}
|
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
namespace Microsoft.Azure.Management.ANF.Samples.Model
{
using System.Collections.Generic;
/// <summary>
/// Instantiates a ModelVolume object
/// </summary>
public class ModelVolume
{
/// <summary>
/// Gets or sets exportPolicy
/// </summary>
public List<ModelExportPolicyRule> ExportPolicies { get; set; }
/// <summary>
/// Gets or sets usageThreshold
/// </summary>
/// <remarks>
/// Maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only.
/// Minimum size is 100 GiB. Upper limit is 100TiB. Number must be represented in bytes = 107370000000.
/// </remarks>
public long UsageThreshold { get; set; }
/// <summary>
/// Gets or sets creation Token or File Path
/// </summary>
/// <remarks>A unique file path for the volume. Used when creating mount targets</remarks>
public string CreationToken { get; set; }
/// <summary>
/// Gets or sets volume type
/// </summary>
/// <remarks>Ällowed values are "NFSv3" or "SMB"</remarks>
public string Type { get; set; }
/// <summary>
/// Gets or sets volume name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the Azure Resource URI for a delegated subnet. Must have the delegation
/// Microsoft.NetApp/volumes
/// </summary>
public string SubnetId { get; set; }
}
}
|
using System;
namespace stringFeatures
{
class Program
{
static void Main(string[] args)
{
// some string features
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
if (String.IsNullOrEmpty(name))
{
Console.WriteLine("\nERROR: No text found! Program exiting.");
}
else
{
Console.WriteLine($"\nHi {name}! Thanks for entering your name.");
Console.WriteLine($"Your name character length is {name.Length}.");
string query = name.StartsWith("A") ? "Does" : "Does Not";
Console.WriteLine($"Your name {query} start with an 'A'.");
query = name.EndsWith("e") ? "Does" : "Does Not";
Console.WriteLine($"Your name {query} end with an 'e'.");
query = name.Contains("pizza") ? "Does" : "Does Not";
Console.WriteLine($"The entered text {query} contain the word 'pizza'.");
}
Console.WriteLine("\n\n\n");
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Ipfs.Registry
{
[TestClass]
public class MultiBaseAlgorithmTest
{
[TestMethod]
public void Bad_Name()
{
Assert.ThrowsException<ArgumentNullException>(() => MultiBaseAlgorithm.Register(null, '?'));
Assert.ThrowsException<ArgumentNullException>(() => MultiBaseAlgorithm.Register("", '?'));
Assert.ThrowsException<ArgumentNullException>(() => MultiBaseAlgorithm.Register(" ", '?'));
}
[TestMethod]
public void Name_Already_Exists()
{
Assert.ThrowsException<ArgumentException>(() => MultiBaseAlgorithm.Register("base58btc", 'z'));
}
[TestMethod]
public void Code_Already_Exists()
{
Assert.ThrowsException<ArgumentException>(() => MultiBaseAlgorithm.Register("base58btc-x", 'z'));
}
[TestMethod]
public void Algorithms_Are_Enumerable()
{
Assert.AreNotEqual(0, MultiBaseAlgorithm.All.Count());
}
[TestMethod]
public void Roundtrip_All_Algorithms()
{
var bytes = new byte[] { 1, 2, 3, 4, 5 };
foreach (var alg in MultiBaseAlgorithm.All)
{
var s = alg.Encode(bytes);
CollectionAssert.AreEqual(bytes, alg.Decode(s), alg.Name);
}
}
[TestMethod]
public void Name_Is_Also_ToString()
{
foreach (var alg in MultiBaseAlgorithm.All)
{
Assert.AreEqual(alg.Name, alg.ToString());
}
}
[TestMethod]
public void Known_But_NYI()
{
var alg = MultiBaseAlgorithm.Register("nyi", 'n');
try
{
Assert.ThrowsException<NotImplementedException>(() => alg.Encode(null));
Assert.ThrowsException<NotImplementedException>(() => alg.Decode(null));
}
finally
{
MultiBaseAlgorithm.Deregister(alg);
}
}
}
}
|
using UnityEngine;
namespace SuperPivot
{
namespace Samples
{
/// <summary>
/// Demo script to highlight runtime pivot position edition
/// </summary>
[RequireComponent(typeof(Collider))]
public class SetPivotUnderMouseClick : MonoBehaviour
{
public Transform target;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) // get the 3d position under the mouse click
{
if (target && hit.transform == transform)
{
Debug.Log("Change pivot position to " + hit.point);
SuperPivot.API.SetPivot(target.transform, hit.point);
}
}
}
}
}
}
}
|
using Composite.Sample;
using System;
namespace Composite
{
class Program
{
static void Main(string[] args)
{
Sample.Composite root = new Sample.Composite("系统配置");
Sample.Composite sysConfig = new Sample.Composite("系统设置");
Sample.Composite menu = new Sample.Composite("菜单设置");
sysConfig.Add(menu);
sysConfig.Add(new Leaf("角色设置"));
sysConfig.Add(new Leaf("用户管理"));
sysConfig.Add(new Leaf("基础配置"));
Sample.Composite businessData = new Sample.Composite("上线初始");
businessData.Add(new Leaf("主数据导入"));
businessData.Add(new Leaf("库存数据导入"));
businessData.Add(new Leaf("未清订单导入"));
Sample.Composite useData = new Sample.Composite("占用数据");
useData.Add(new Leaf("库区占用"));
useData.Add(new Leaf("库位占用"));
menu.Add(businessData);
menu.Add(useData);
root.Add(sysConfig);
Sample.Composite orgConfig = new Sample.Composite("机构配置");
orgConfig.Add(new Leaf("组织机构"));
orgConfig.Add(new Leaf("公司信息"));
orgConfig.Add(new Leaf("人员信息"));
root.Add(orgConfig);
root.Add(new Leaf("接口管理"));
root.Display(1);
Console.Read();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace PaletteConversion
{
public class HexConversion : IPaletteFormatReader, IPaletteFormatWriter
{
private IList<string> _fileExtensions = new List<string>
{
".hex"
};
public IList<string> FileExtensions
{
get
{
return _fileExtensions;
}
}
public Palette FromContents(string content, string title = "palette")
{
Regex hexRegex = new Regex("[a-fA-F0-9]+", RegexOptions.Compiled);
var colors = new List<Color>();
var description = string.Empty;
Regex _regexHex = new Regex("[^a-fA-F0-9]", RegexOptions.Compiled);
var hexMatches = hexRegex.Matches(content);
foreach (Match item in hexMatches)
{
colors.Add(ColorUtility.ParseHexColor(item.Value));
}
return new Palette
{
Colors = colors,
Description = description,
Title = title,
};
}
public string PaletteToFormat(Palette palette)
{
StringBuilder builder = new StringBuilder();
foreach (var color in palette.Colors)
{
builder.AppendLine(ColorUtility.ColorToHexString(color));
}
return builder.ToString();
}
}
}
|
namespace FakeItEasy.Tests.ArgumentConstraintManagerExtensions
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using FakeItEasy.Core;
using FakeItEasy.Tests.TestHelpers;
using Xunit;
public class EqualToWithComparerConstraintTests
: ArgumentConstraintTestBase<string>
{
protected override string ExpectedDescription => @"equal to ""IgnoreCase""";
public static IEnumerable<object?[]> InvalidValues()
{
return TestCases.FromObject(
(object?)null,
string.Empty,
" ",
"differentValue");
}
public static IEnumerable<object?[]> ValidValues()
{
return TestCases.FromObject("IgnoreCase", "ignoreCase");
}
[Theory]
[MemberData(nameof(InvalidValues))]
public override void IsValid_should_return_false_for_invalid_values(object invalidValue)
{
base.IsValid_should_return_false_for_invalid_values(invalidValue);
}
[Theory]
[MemberData(nameof(ValidValues))]
public override void IsValid_should_return_true_for_valid_values(object validValue)
{
base.IsValid_should_return_true_for_valid_values(validValue);
}
[Fact]
public void IsEqualTo_should_be_null_guarded_when_comparer_is_null()
{
// Arrange
var constraintManager = new DefaultArgumentConstraintManager<string>(x => { });
Expression<Action> call = () => constraintManager.IsEqualTo(null!, StringComparer.OrdinalIgnoreCase);
// Act
// Assert
call.Should().BeNullGuarded();
}
protected override void CreateConstraint(INegatableArgumentConstraintManager<string> scope)
{
scope.IsEqualTo("IgnoreCase", StringComparer.OrdinalIgnoreCase);
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="Serialization.cs" company="Asynkron HB">
// Copyright (C) 2015-2016 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System.Collections.Generic;
using Google.Protobuf;
using Google.Protobuf.Reflection;
namespace GAM.Remoting
{
public static class Serialization
{
private static readonly Dictionary<string, MessageParser> TypeLookup = new Dictionary<string, MessageParser>();
static Serialization()
{
RegisterFileDescriptor(GAM.ProtosReflection.Descriptor);
RegisterFileDescriptor(ProtosReflection.Descriptor);
}
public static void RegisterFileDescriptor(FileDescriptor fd)
{
foreach (var msg in fd.MessageTypes)
{
var name = fd.Package + "." + msg.Name;
TypeLookup.Add(name, msg.Parser);
}
}
public static ByteString Serialize(IMessage message)
{
return message.ToByteString();
}
public static object Deserialize(string typeName, ByteString bytes)
{
var parser = TypeLookup[typeName];
var o = parser.ParseFrom(bytes);
return o;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.StatusEffects
{
public interface IEffective
{
// Effects which the owner gets
public List<BaseEffect> OwnerEffects { get; set; }
// Effects which will be passed on to the enemy
public List<BaseEffect> EmitEffects { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KiteNeedDeleteAnimationCache
{
private Dictionary<GameObject, HashSet<Type>> _deleteAnimationCache = new Dictionary<GameObject, HashSet<Type>>();
public void Add(GameObject obj, System.Type animationType)
{
HashSet<Type> typeList = null;
if (!_deleteAnimationCache.TryGetValue(obj, out typeList))
{
typeList = new HashSet<Type>();
_deleteAnimationCache.Add(obj, typeList);
}
typeList.Add(animationType);
}
public void Remove(GameObject obj, System.Type animationType)
{
HashSet<Type> typeList = null;
if (_deleteAnimationCache.TryGetValue(obj, out typeList))
{
if(typeList.Contains(animationType))
{
typeList.Remove(animationType);
}
}
}
public void ForEachItem(Action<GameObject, Type> callBack)
{
foreach(var pair in _deleteAnimationCache)
{
var obj = pair.Key;
foreach(var type in pair.Value)
{
callBack(obj, type);
}
}
}
}
|
using Takenet.Textc;
namespace Axaprj.Textc.Vect
{
/// <summary>
/// Textc.Vect Text Cursor
/// </summary>
public interface IVTextCursor : ITextCursor
{
/// <summary>Textc.Vect Request Context</summary>
IVRequestContext VContext { get; }
}
/// <summary>
/// Cursor with tokens replacement capability
/// </summary>
public interface IVReplaceTextCursor : IVTextCursor
{
/// <summary>
/// Move current token to processed and setup start to next token
/// </summary>
/// <returns>false on the end of stream</returns>
bool GoToNextToken();
/// <summary>
/// Set replacement to processed and setup start to the following token
/// </summary>
void GoForwardWithReplacement(string replacement_text, string remaining_text);
/// <summary>
/// Setup processed to input tokens
/// </summary>
void SetupProcessedToInput();
}
}
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
namespace Microsoft.VisualStudio.Text.Differencing
{
using System;
public interface IDifferenceViewer3 : IDifferenceViewer2
{
/// <summary>
/// Should the differences be displayed?
/// </summary>
/// <remarks>
/// <para>This will be true if and only if there is a baseline and if the <see cref="DifferenceViewerOptions.ShowDifferencesId"/> option is true.</para>
/// <para><see cref="IDifferenceViewer.ViewModeChanged"/> will be raised whenever this value changes.</para>
/// </remarks>
bool DisplayDifferences { get; }
}
}
|
namespace Musoq.Schema.Os.Zip
{
public class ZipBasedTable : ISchemaTable
{
public ZipBasedTable()
{
Columns = SchemaZipHelper.SchemaColumns;
}
public ISchemaColumn[] Columns { get; }
}
} |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using ArcanumTextureSlicer.Core;
using ArcanumTextureSlicer.Gui.Commands;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
using Point = System.Windows.Point;
namespace ArcanumTextureSlicer.Gui
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Bitmap _bitmap;
private string _lastExportPath;
private Point _mousePosition;
private Point _scrollOffset;
private double _zoom = 1.0;
public MainWindow()
{
InitializeComponent();
RenderOptions.SetBitmapScalingMode(BitmapViewer, BitmapScalingMode.NearestNeighbor);
RenderOptions.SetBitmapScalingMode(GridViewer, BitmapScalingMode.NearestNeighbor);
}
private bool IsFileOpen => _bitmap != null;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
OpenFile(args[1]);
}
}
private void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Open_Executed(object sender, ExecutedRoutedEventArgs e)
{
var dialog = new OpenFileDialog
{
Multiselect = false,
ShowReadOnly = true,
Filter = "Bitmap Images (*.bmp)|*.bmp|All Files (*.*)|*.*"
};
if (dialog.ShowDialog() == true)
{
OpenFile(dialog.FileName);
}
}
private void Close_Executed(object sender, ExecutedRoutedEventArgs e)
{
GridViewer.Source = null;
BitmapViewer.Source = null;
DestroyBitmap();
_bitmap = null;
}
private void FileOpen_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsFileOpen;
}
private void Export_Executed(object sender, ExecutedRoutedEventArgs e)
{
var dialog = new FolderBrowserDialog
{
SelectedPath = _lastExportPath
};
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
_lastExportPath = dialog.SelectedPath;
Directory.GetFiles(_lastExportPath, "tile_???.bmp").ToList().ForEach(File.Delete);
var i = 1;
foreach (var tile in GridViewer.SelectedTiles)
{
using (var output = _bitmap.CreateTile(tile.X, tile.Y))
{
try
{
var tilePath = $"{_lastExportPath.TrimEnd('/', '\\')}\\tile_{i.ToString("D3")}.bmp";
output.Save(tilePath, ImageFormat.Bmp);
}
catch (Exception exception)
{
ShowError(exception);
}
i++;
}
}
}
}
private void OpenFile(string file)
{
_lastExportPath = new FileInfo(file).DirectoryName;
var bitmap = CreateBitmap(file);
if (bitmap != null)
{
DestroyBitmap();
_bitmap = bitmap;
DisplayBitmap();
}
}
private Bitmap CreateBitmap(string file)
{
Bitmap bitmap = null;
try
{
bitmap = new Bitmap(file);
if (!bitmap.RawFormat.Equals(ImageFormat.Bmp)
|| !bitmap.PixelFormat.Equals(PixelFormat.Format8bppIndexed))
{
throw new Exception("Incorrect image format. 8bit bmp is expected.");
}
return bitmap;
}
catch (Exception e)
{
bitmap?.Dispose();
ShowError(e);
}
return null;
}
private void DestroyBitmap()
{
if (IsFileOpen)
{
BitmapViewer.Source = null;
_bitmap.Dispose();
}
}
private void DisplayBitmap()
{
try
{
_zoom = 1.0;
UpdateZoom();
BitmapViewer.DisplayBitmap(_bitmap);
GridViewer.CreateGrid(_bitmap);
}
catch (Exception e)
{
ShowError(e);
}
}
private void ShowError(Exception e)
{
MessageBox.Show(this, e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
private void MoveGrid_Executed(object sender, ExecutedRoutedEventArgs e)
{
var moveGridCommand = e.Command as MoveGridCommand;
if (moveGridCommand != null)
{
GridViewer.OffsetX += moveGridCommand.X;
GridViewer.OffsetY += moveGridCommand.Y;
}
var resetGridCommand = e.Command as ResetGridCommand;
if (resetGridCommand != null)
{
GridViewer.OffsetX = 0;
GridViewer.OffsetY = 0;
GridViewer.ClearSelection();
}
GridViewer.UpdateGrid();
}
private void GridViewer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsFileOpen && (Keyboard.Modifiers & ModifierKeys.Control) > 0)
{
var p = Mouse.GetPosition(GridViewer);
var scale = _bitmap.Width/GridViewer.ActualWidth;
p.X *= scale;
p.Y *= scale;
GridViewer.SelectTileAt((int) p.X, (int) p.Y);
GridViewer.UpdateGrid();
}
}
private void Zoom_Executed(object sender, ExecutedRoutedEventArgs e)
{
var zoomCommnand = (ZoomCommand) e.Command;
_zoom = zoomCommnand.Zoom;
UpdateZoom();
}
private void ScrollContent_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (IsFileOpen && (Keyboard.Modifiers & ModifierKeys.Control) > 0)
{
_zoom += 0.001*e.Delta;
UpdateZoom();
e.Handled = true;
}
}
private void UpdateZoom()
{
_zoom = Math.Max(1, _zoom);
_zoom = Math.Min(4, _zoom);
if (ScrollViewer.ScrollableHeight > 0 && ScrollViewer.ScrollableWidth > 0)
{
var verticalScrollPosition = ScrollViewer.VerticalOffset/ScrollViewer.ScrollableHeight;
var horizontalScrollPosition = ScrollViewer.HorizontalOffset/ScrollViewer.ScrollableWidth;
ScrollContent.LayoutTransform = new ScaleTransform(_zoom, _zoom);
ScrollViewer.UpdateLayout();
ScrollViewer.ScrollToVerticalOffset(verticalScrollPosition*ScrollViewer.ScrollableHeight);
ScrollViewer.ScrollToHorizontalOffset(horizontalScrollPosition*ScrollViewer.ScrollableWidth);
}
else
{
ScrollContent.LayoutTransform = new ScaleTransform(_zoom, _zoom);
}
}
private void ScrollViewer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (IsFileOpen && (Keyboard.Modifiers & ModifierKeys.Control) == 0)
{
_mousePosition = e.GetPosition(ScrollViewer);
_scrollOffset = new Point(ScrollViewer.HorizontalOffset, ScrollViewer.VerticalOffset);
ScrollViewer.CaptureMouse();
}
}
private void ScrollViewer_OnMouseMove(object sender, MouseEventArgs e)
{
if (ScrollViewer.IsMouseCaptured)
{
var p = e.GetPosition(ScrollViewer);
ScrollViewer.ScrollToVerticalOffset(_scrollOffset.Y + _mousePosition.Y - p.Y);
ScrollViewer.ScrollToHorizontalOffset(_scrollOffset.X + _mousePosition.X - p.X);
}
}
private void ScrollViewer_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (ScrollViewer.IsMouseCaptured)
{
ScrollViewer.ReleaseMouseCapture();
}
}
}
} |
using System.Runtime.Serialization;
namespace Rain.Client
{
[DataContract]
public class ExceptionEntry : Entry
{
[DataMember]
public string Source { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public string Description { get; set; }
public override bool Equals(object obj)
{
if (obj is ExceptionEntry exceptionEntry)
{
return exceptionEntry.Description == Description;
}
else
{
return false;
}
}
public static bool operator ==(ExceptionEntry a, ExceptionEntry b)
{
return (object)a == (object)b || ((object)a != null && a.Equals(b));
}
public static bool operator !=(ExceptionEntry a, ExceptionEntry b)
{
return (object)a != (object)b && ((object)a == null || !a.Equals(b));
}
public override int GetHashCode()
{
return Description.GetHashCode();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CalibrationUI : UIElement
{
/// <summary>
/// The text objects contained in the CalibrationUI
/// </summary>
private enum Texts
{
Title,
Message
}
/// <summary>
/// Static reference to the one CalibrationUI object in the scene to enable static methods
/// </summary>
public static CalibrationUI instance;
////////////////////////////////////////////////////////////////
// Methods
////////////////////////////////////////////////////////////////
/// <summary>
/// Updates the message shown to the user
/// </summary>
/// <param name="text">New message show</param>
public static void UpdateMessage(string text)
{
instance.texts[Texts.Message.GetHashCode()].text = text;
}
protected override void Awake()
{
base.Awake();
this.defaultActive = true;
instance = GameObject.FindGameObjectsWithTag("HUD")[0].GetComponent<CalibrationUI>();
}
}
|
using TaskCore.Domain;
namespace TaskCore.Data.Interfaces
{
public interface IAttachmentRepository : IBaseRepository<Attachment>
{
}
} |
// <summary>
// Command line parser.
// </summary>
namespace Odgs.Common
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
/// <summary>
/// Parses the command line.
/// </summary>
/// <remarks>
/// The parser recognizes the following command line option forms:
/// <list type="bullet">
/// <item>
/// <term>--option</term>
/// <description>
/// Simple option.
/// </description>
/// </item>
/// <item>
/// <term>--option=</term>
/// <description>
/// Option with an empty value.
/// </description>
/// </item>
/// <item>
/// <term>--option=value</term>
/// <description>
/// Option with an specified value.
/// </description>
/// </item>
/// </list>
/// <para>
/// Options are case sensitive.
/// The forward slash <i>'/'</i> character can be used instead of <i>--</i>.
/// </para>
/// <para>
/// The option can be specified multiple times. All values for each instance are preserved.
/// </para>
/// </remarks>
public class CommandLine
{
private readonly CommandLineOptionsDictionary _flags = new CommandLineOptionsDictionary();
private readonly StringCollection _parameters = new StringCollection();
/// <summary>
/// Gets the list of arguments in order they appear in the command line.
/// </summary>
public StringCollection Arguments
{
get { return _parameters; }
}
/// <summary>
/// Gets the collection of command line options along with their values.
/// </summary>
/// <remarks>
/// <para>
/// Each entry of the collection represents a single specified option.
/// If multiple option instances are specified, they are collapsed into a single entry.
/// </para>
/// <para>
/// If option specified without value (e.g --option), then value list is empty.
/// If option specified with equal sign (e.g. --option=), but no value provided, then the list contains
/// an empty string.
/// If multiple option instances with values specified, then list contains values in order option
/// instances appear in the command line.
/// </para>
/// <example>This example shows how options are stored:
/// <code>
/// --option1 --option1 --option2= --option3= -option3=value1 -option3=value2
///
/// "option1" : {}
/// "option2" : { "" }
/// "option3" : { "", "value1", "value2" }
///
/// </code>
/// </example>
/// </remarks>
public CommandLineOptionsDictionary Options
{
get { return _flags; }
}
/// <summary>
/// Parses the command line.
/// </summary>
/// <param name="args">
/// Command line.
/// </param>
/// <returns>
/// Object that contains parsed command line.
/// </returns>
public static CommandLine Parse(string[] args)
{
return Parse(args, 0);
}
/// <summary>
/// Parses the command line starting from index.
/// </summary>
/// <param name="args">
/// Command line.
/// </param>
/// <param name="start">
/// Index in <c>args</c> to start parsing from.
/// </param>
/// <returns>
/// Object that contains parsed command line.
/// </returns>
public static CommandLine Parse(string[] args, int start)
{
CommandLine commandLine = new CommandLine();
for( int i = start; i < args.Length; i++ )
{
string arg = args[i];
Match match = Regex.Match(
arg,
"^(--|/)(?<name>[^=]+)(=(?<value>.*)?)?",
RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
if( match.Success )
{
string name = match.Groups["name"].Value;
if(!commandLine._flags.ContainsKey(name))
{
commandLine._flags[name] = new List<string>();
}
Group valueGroup = match.Groups["value"];
if(valueGroup.Success)
{
commandLine._flags[name].Add(valueGroup.Value);
}
}
else
{
commandLine._parameters.Add(arg);
}
}
return commandLine;
}
/// <summary>
/// Splits each option value and stores each part as a separate value.
/// </summary>
/// <param name="optionName">
/// Option name.
/// </param>
/// <remarks>
/// Semicolumn ';' and comma ',' used as separators.
/// </remarks>
public void ConsolidateOptionValues(string optionName)
{
ConsolidateOptionValues(optionName, new[] { ';', ',' });
}
/// <summary>
/// Splits each option value and stores each part as a separate value.
/// </summary>
/// <param name="optionName">
/// Option name.
/// </param>
/// <param name="separators">
/// List of separator characters.
/// </param>
public void ConsolidateOptionValues(string optionName, char[] separators)
{
List<string> separateOptions;
if(Options.TryGetValue(optionName, out separateOptions))
{
var consolidation = new List<string>();
foreach( string option in separateOptions )
{
string[] items = option.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach( string item in items )
{
consolidation.Add(item);
}
}
_flags[optionName] = consolidation;
}
}
}
}
|
using System.Collections;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace TheGamedevGuru
{
public class PlayFabDemo : MonoBehaviour
{
[SerializeField] private AssetReference spriteReference = null;
[SerializeField] private Image image = null;
public IEnumerator Start()
{
yield return LoginToPlayFab();
yield return InitializeAddressables();
TestRemoteAddressableAsset();
}
private IEnumerator InitializeAddressables()
{
Addressables.ResourceManager.ResourceProviders.Add(new AssetBundleProvider());
Addressables.ResourceManager.ResourceProviders.Add(new PlayFabStorageHashProvider());
Addressables.ResourceManager.ResourceProviders.Add(new PlayFabStorageAssetBundleProvider());
Addressables.ResourceManager.ResourceProviders.Add(new PlayFabStorageJsonAssetProvider());
return Addressables.InitializeAsync();
}
private IEnumerator LoginToPlayFab()
{
var loginSuccessful = false;
var request = new LoginWithCustomIDRequest {CustomId = "MyPlayerId", CreateAccount = true};
PlayFabClientAPI.LoginWithCustomID(request, result => loginSuccessful = true,
error => error.GenerateErrorReport());
return new WaitUntil(() => loginSuccessful);
}
private void TestRemoteAddressableAsset()
{
var asyncOperation = spriteReference.LoadAssetAsync<Sprite>();
asyncOperation.Completed += result => image.sprite = asyncOperation.Result;
}
}
} |
using HRM.Domain.Models;
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace HRM.Application.ViewModels
{
public class EmployeeViewModel
{
[Key]
public Guid Id { get; set; }
[Required(ErrorMessage = "The First Name is Required")]
[MinLength(2)]
[MaxLength(100)]
[DisplayName("FirstName")]
public string FirstName { get; set; }
[Required(ErrorMessage = "The Last Name is Required")]
[MinLength(2)]
[MaxLength(100)]
[DisplayName("LastName")]
public string LastName { get; set; }
[Required(ErrorMessage = "The E-mail is Required")]
[EmailAddress]
[DisplayName("E-mail")]
public string Email { get; set; }
[Required(ErrorMessage = "The BirthDate is Required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[DataType(DataType.Date, ErrorMessage = "Date format is invalid")]
[DisplayName("Birth Date")]
public DateTime Dob { get; set; }
[Required(ErrorMessage = "The Gender is Required")]
public Gender Gender { get; set; }
public string Detail { get; set; }
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using Moq;
using WinForms.Common.Tests;
using Xunit;
namespace System.Drawing.Design.Tests
{
public class MetafileEditorTests
{
[Fact]
public void MetafileEditor_Ctor_Default()
{
var editor = new MetafileEditor();
Assert.False(editor.IsDropDownResizable);
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetITypeDescriptorContextTestData))]
public void MetafileEditor_GetEditStyle_Invoke_ReturnsModal(ITypeDescriptorContext context)
{
var editor = new MetafileEditor();
Assert.Equal(UITypeEditorEditStyle.Modal, editor.GetEditStyle(context));
}
[Fact]
public void MetafileEditor_GetExtensions_InvokeDefault_ReturnsExpected()
{
var editor = new SubMetafileEditor();
string[] extensions = editor.GetExtensions();
Assert.Equal(new string[] { "emf", "wmf" }, extensions);
Assert.NotSame(extensions, editor.GetExtensions());
}
[Fact]
public void MetafileEditor_GetFileDialogDescription_Invoke_ReturnsExpected()
{
var editor = new SubMetafileEditor();
Assert.Equal("Metafiles", editor.GetFileDialogDescription());
}
[Theory]
[CommonMemberData(nameof(CommonTestHelper.GetITypeDescriptorContextTestData))]
public void MetafileEditor_GetPaintValueSupported_Invoke_ReturnsTrue(ITypeDescriptorContext context)
{
var editor = new MetafileEditor();
Assert.True(editor.GetPaintValueSupported(context));
}
[Fact]
public void MetafileEditor_LoadFromStream_BitmapStream_ThrowsExternalException()
{
var editor = new SubMetafileEditor();
using (MemoryStream stream = new MemoryStream())
using (var image = new Bitmap(10, 10))
{
image.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
Assert.Throws<ExternalException>(() => editor.LoadFromStream(stream));
}
}
[Fact]
public void MetafileEditor_LoadFromStream_MetafileStream_ReturnsExpected()
{
var editor = new SubMetafileEditor();
using (Stream stream = File.OpenRead("Resources/telescope_01.wmf"))
{
Metafile result = Assert.IsType<Metafile>(editor.LoadFromStream(stream));
Assert.Equal(new Size(3096, 4127), result.Size);
}
}
[Fact]
public void MetafileEditor_LoadFromStream_NullStream_ThrowsArgumentNullException()
{
var editor = new SubMetafileEditor();
Assert.Throws<ArgumentNullException>("stream", () => editor.LoadFromStream(null));
}
private class SubMetafileEditor : MetafileEditor
{
public new string[] GetExtensions() => base.GetExtensions();
public new string GetFileDialogDescription() => base.GetFileDialogDescription();
public new Image LoadFromStream(Stream stream) => base.LoadFromStream(stream);
}
private class CustomGetImageExtendersEditor : MetafileEditor
{
public new string[] GetExtensions() => base.GetExtensions();
protected override Type[] GetImageExtenders() => new Type[] { typeof(CustomGetExtensionsEditor) };
}
private class CustomGetExtensionsEditor : ImageEditor
{
protected override string[] GetExtensions() => new string[] { "CustomGetExtensionsEditor" };
}
}
} |
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using System;
namespace Microsoft.AppInspector
{
public class WriterFactory
{
public static Writer GetWriter(string writerName, string defaultWritter, string format = null)
{
if (string.IsNullOrEmpty(writerName))
writerName = defaultWritter;
if (string.IsNullOrEmpty(writerName))
writerName = "text";
switch (writerName.ToLowerInvariant())
{
case "_dummy":
return new DummyWriter();
case "json":
return new JsonWriter();
case "text":
return new SimpleTextWriter(format);
case "html":
return new LiquidWriter();
default:
throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-f")));
}
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using Knowledgebase.UnitOfWork;
using Knowledgebase.Models.AppUser;
namespace Knowledgebase.Application.Services
{
public class AppUserService : _ServiceBase
{
private readonly IRepository<Entities.AppUser> _usersRepository;
public AppUserService(IServiceProvider serviceProvider, IUnitOfWork uow)
: base(serviceProvider)
{
_usersRepository = uow.GetRepository<Entities.AppUser>();
}
public ICollection<AppUserBrief> GetAll()
{
return _usersRepository.GetAll()
.Select(x => new AppUserBrief
{
Id = x.Id,
Name = x.Name,
Picture = x.Picture,
}).ToList();
}
public AppUserDetails GetDetails(Guid id)
{
return _usersRepository.GetAll()
.Where(x => x.Id == id)
.Select(x => new AppUserDetails
{
Id = x.Id,
Name = x.Name,
Email = x.Email,
CreatedAt = x.CreatedAt,
IsOwner = x.IsOwner,
Picture = x.Picture,
}).FirstOrDefault();
}
public Guid Create(AppUserCreate input)
{
var model = new Entities.AppUser
{
Id = Guid.NewGuid(),
CreatedAt = DateTime.UtcNow,
ExternalId = input.ExternalId,
Picture = input.Picture,
Name = input.Name,
Email = input.Email,
IsOwner = true,
};
_usersRepository.Insert(model);
return model.Id;
}
}
}
|
using CoCSharp.Csv;
using System;
using System.Diagnostics;
namespace CoCSharp.Logic
{
/// <summary>
/// Represents a Clash of Clans <see cref="VillageObject"/> that can be constructed.
/// </summary>
[DebuggerDisplay("{DebuggerDisplayString}")]
public abstract class Buildable<TCsvData> : VillageObject<TCsvData> where TCsvData : CsvData, new()
{
#region Constants
/// <summary>
/// Level at which a <see cref="Buildable{TCsvData}"/> is not constructed.
/// </summary>
public const int NotConstructedLevel = -1;
/// <summary>
/// <see cref="TimeSpan"/> representing an instant construction time.
/// </summary>
protected static readonly TimeSpan InstantConstructionTime = new TimeSpan(0);
#endregion
#region Constructors
// Constructor used to load the VillageObject from a JsonTextReader.
internal Buildable() : base()
{
_timer = new TickTimer();
}
/// <summary>
/// Initializes a new instance of the <see cref="Buildable{TCsvData}"/> class with the specified
/// <see cref="Village"/> instance and <typeparamref name="TCsvData"/>.
/// </summary>
///
/// <param name="village">
/// <see cref="Village"/> instance which owns this <see cref="Buildable{TCsvData}"/>.
/// </param>
///
/// <param name="data"><typeparamref name="TCsvData"/> representing the data of the <see cref="Buildable{TCsvData}"/>.</param>
///
/// <exception cref="ArgumentNullException"><paramref name="village"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
protected Buildable(Village village, TCsvData data) : base(village, data)
{
_upgradeLevel = -1;
_timer = new TickTimer();
}
#endregion
#region Fields & Properties
// CsvData of the next upgrade.
private TCsvData _nextUprade;
// Value to determine if the Buildable is upgradeable.
private bool _isUpgradeable;
// Value indicating the level of the Buildable.
private int _upgradeLevel;
// Timer to time constructions.
private TickTimer _timer;
private CsvDataRow<TCsvData> _rowCache;
/// <summary>
/// Gets the <see cref="TickTimer"/> associated with this <see cref="Buildable{TCsvData}"/> instance.
/// </summary>
protected TickTimer Timer => _timer;
/// <summary>
/// Gets the cache to the <see cref="CsvDataRow{TCsvData}"/> in which <see cref="Data"/> is found.
/// </summary>
protected CsvDataRow<TCsvData> RowCache => _rowCache;
/// <summary>
/// Gets a value indicating whether the <see cref="Buildable{TCsvData}"/> object is in construction.
/// </summary>
public bool IsConstructing => _timer.IsActive;
/// <summary>
/// Gets a value indicating whether the <see cref="Buildable{TCsvData}"/> object can be upgraded.
/// </summary>
public bool IsUpgradeable => _isUpgradeable;
/// <summary>
/// Gets the level of the <see cref="Buildable{TCsvData}"/> object.
/// </summary>
public int UpgradeLevel
{
get
{
return _upgradeLevel;
}
set
{
if (value < NotConstructedLevel)
throw new ArgumentOutOfRangeException(nameof(value), "value cannot be less than NotConstructedLevel.");
_upgradeLevel = value;
// If level is -1 (NotConstructedLevel), VillageObject.Data will be null.
// and NextUpgrade will point to a CsvData of level 0 from CollectionCache.
UpdateData(RowCache.Id, value);
UpdateIsUpgradable();
}
}
/// <summary>
/// Gets the next upgrade's <typeparamref name="TCsvData"/>.
/// </summary>
///
/// <remarks>
/// All construction data will be taken from this.
/// </remarks>
public TCsvData NextUpgrade => _nextUprade;
/// <summary>
/// Gets the duration of the construction of the <see cref="Buildable{TCsvData}"/> object.
/// </summary>
///
/// <exception cref="InvalidOperationException">The <see cref="Buildable{TCsvData}"/> object is not in construction.</exception>
public TimeSpan ConstructionDuration
{
get
{
if (!IsConstructing)
throw new InvalidOperationException("Buildable object is not in construction.");
return TimeSpan.FromSeconds(_timer.Duration);
}
}
/// <summary>
/// Gets the UTC time at which the construction of the <see cref="Buildable{TCsvData}"/> object will end.
/// </summary>
///
/// <exception cref="InvalidOperationException">The <see cref="Buildable{TCsvData}"/> object is not in construction.</exception>
public DateTime ConstructionEndTime
{
get
{
if (!IsConstructing)
throw new InvalidOperationException("Buildable object is not in construction.");
return TimeUtils.FromUnixTimestamp(_timer.EndTime);
}
}
/// <summary>
/// Gets the duration of construction in seconds.
/// </summary>
///
/// <remarks>
/// Represents the "const_t" field of the village JSONs.
/// </remarks>
protected int ConstructionTSeconds => (int)_timer.Duration;
/// <summary>
/// Gets or sets the date of when the construction is going to end in UNIX timestamps.
/// Everything is relative to this, changing this will also change the other values.
/// </summary>
///
/// <remarks>
/// Represents the "const_t_end" field of village JSONs.
/// </remarks>
protected int ConstructionTEndUnixTimestamp => IsConstructing ? _timer.EndTime : 0;
#endregion
#region Methods
/// <summary>
/// Begins the construction of the <see cref="Buildable{TCsvData}"/> and increases its level by 1
/// when done.
/// </summary>
public void BeginConstruction(int ctick)
{
if (IsConstructing)
throw new InvalidOperationException("Buildable object is already in construction.");
if (NextUpgrade == null)
Debug.WriteLine("BeginConstruction: NextUpgrade was null, calling UpdateIsUpgradable to set NextUpgrade.");
UpdateIsUpgradable();
if (!IsUpgradeable)
throw new InvalidOperationException("Buildable object is maxed or Town Hall level too low to perform construction.");
var buildTime = GetBuildTime(NextUpgrade);
// No need to start up a TickTimer if the construction is instant.
if (buildTime == InstantConstructionTime)
{
FinishConstruction(ctick);
}
else
{
Village.WorkerManager.AllocateWorker(this);
_timer.Start(Village.LastTickTime, ctick, (int)buildTime.TotalSeconds);
}
}
/// <summary>
/// Cancels the construction of the <see cref="Buildable{TCsvData}"/>.
/// </summary>
public void CancelConstruction(int ctick)
{
if (!IsConstructing)
throw new InvalidOperationException("Buildable object is not in construction.");
_timer.Stop();
Village.WorkerManager.DeallotateWorker(this);
var level = Village.Level;
var data = NextUpgrade;
var buildCost = GetBuildCost(data);
var buildResource = GetBuildResource(data);
// 50% of build cost.
var refund = (int)Math.Round(0.5 * buildCost);
level.Avatar.UseResource(buildResource, -refund);
}
/// <summary>
/// Speeds up the construction of the <see cref="Buildable{TCsvData}"/> and finishes the construction instantly
/// and increases its level by 1.
/// </summary>
public void SpeedUpConstruction(int ctick)
{
if (!IsConstructing)
throw new InvalidOperationException("Buildable object not in construction.");
FinishConstruction(ctick);
}
// Called when construction has finished.
private void FinishConstruction(int ctick)
{
_timer.Stop();
Debug.WriteLine($"FinishConstruction: Construction for {Id} finished on tick {ctick} expected {_timer.EndTick}...");
Village.WorkerManager.DeallotateWorker(this);
var duration = GetBuildTime(NextUpgrade);
var player = Level;
//TODO: Clean up level and experience calculation.
var expPointsGained = LogicUtils.CalculateExpPoints(duration);
var expPoints = player.Avatar.ExpPoints + expPointsGained;
var expCurLevel = player.Avatar.ExpLevels;
var expLevel = LogicUtils.CalculateExpLevel(Assets, ref expCurLevel, ref expPoints);
player.Avatar.ExpPoints = expPoints;
player.Avatar.ExpLevels = expLevel;
_upgradeLevel++;
_data = NextUpgrade;
// Calling UpdateCanUpgrade will set the IsUpgradable & NextUpgrade property as well.
UpdateIsUpgradable();
}
/// <summary>
/// Returns the BuildTime of the specified data.
/// </summary>
/// <param name="data"><typeparamref name="TCsvData"/> from which to obtain the BuildTime.</param>
/// <returns>BuildTime of the specified data.</returns>
protected abstract TimeSpan GetBuildTime(TCsvData data);
/// <summary>
/// Return the BuildCost of the specified data.
/// </summary>
/// <param name="data"><typeparamref name="TCsvData"/> from which to obtain the BuildCost.</param>
/// <returns>BuildCost of the specified data.</returns>
protected abstract int GetBuildCost(TCsvData data);
/// <summary>
/// Return the BuildResource of the specified data.
/// </summary>
/// <param name="data"><typeparamref name="TCsvData"/> from which to obtain the BuildResource.</param>
/// <returns>BuildResource of the specified data.</returns>
protected abstract string GetBuildResource(TCsvData data);
/// <summary>
/// Returns the Town Hall level at which the Buildable can upgrade from the specified data.
/// </summary>
/// <param name="data"><typeparamref name="TCsvData"/> from which to obtain the TownHallLevel.</param>
/// <returns>TownHallLevel of the specified data.</returns>
protected abstract int GetTownHallLevel(TCsvData data);
protected virtual void SetUpgradeLevel(int level)
{
// Space
}
/// <summary>
/// Updates the <see cref="VillageObject{TCsvData}.Data"/> associated with this <see cref="Buildable{TCsvData}"/> using
/// <see cref="VillageObject.Assets"/>, the specified data ID and level.
/// </summary>
/// <param name="dataId"></param>
/// <param name="level"></param>
protected virtual void UpdateData(int dataId, int level)
{
Debug.Assert(level >= NotConstructedLevel, "Level was less than NotConstructedLevel.");
// If we haven't cached the CsvDataRow in which Data
// is found, we do it.
if (RowCache == null)
{
var tableCollections = Assets.DataTables;
var dataRef = new CsvDataRowRef<TCsvData>(dataId);
var row = dataRef.Get(tableCollections);
if (row == null)
throw new InvalidOperationException("Could not find CsvDataRow with ID '" + dataId + "'.");
_rowCache = row;
}
if (RowCache.Name == "Town Hall")
Village._townhall = this as Building;
else if (RowCache.Name == "Worker Building")
Village.WorkerManager._totalWorkers++;
// Data is null when lvl is -1
// However NextUpgrade should not.
if (level == NotConstructedLevel)
{
_data = null;
}
else
{
_data = RowCache[level];
if (_data == null)
throw new InvalidOperationException("Could not find CsvData with ID '" + dataId + "' and with level '" + level + "'.");
}
_upgradeLevel = level;
}
/// <summary>
/// Update the <see cref="IsUpgradeable"/> field by taking into consideration the town hall
/// level required to do so.
/// </summary>
protected virtual void UpdateIsUpgradable()
{
if (RowCache == null)
{
Debug.WriteLine("UpdateIsUpgradable: RowCache was null, calling UpdateData to set RowCache.");
UpdateData(Data.Id, _upgradeLevel);
}
_nextUprade = RowCache[_upgradeLevel + 1];
if (NextUpgrade == null)
{
// There are no upgrades left.
_isUpgradeable = false;
}
else
{
// Check if the level of the TownHall in the Village suits the Buildable
// TownHallLevel required.
Debug.Assert(NextUpgrade != null, "NextUpgrade was null.");
var thLevel = GetTownHallLevel(NextUpgrade);
if (thLevel == 0)
{
_isUpgradeable = true;
}
else
{
if (Village.TownHall == null)
throw new InvalidOperationException("Village does not contain a Town Hall.");
_isUpgradeable = Village.TownHall.UpgradeLevel >= thLevel - 1;
}
}
}
/// <summary/>
protected internal override void ResetVillageObject()
{
base.ResetVillageObject();
//_timer.Stop();
_timer.Reset();
Village?.WorkerManager.DeallotateWorker(this);
_nextUprade = default(TCsvData);
_isUpgradeable = default(bool);
_rowCache = default(CsvDataRow<TCsvData>);
}
/// <summary/>
protected internal override void Tick(int ctick)
{
// Check if the construction Timer has completed.
_timer.Tick(ctick);
if (_timer.IsComplete)
FinishConstruction(ctick);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
namespace Carupano
{
using Persistence;
using Carupano.Messaging;
using Configuration;
using InMemory;
public static class Extensions
{
public static BoundedContextModelBuilder UseInMemoryEventStore(this BoundedContextModelBuilder builder)
{
builder.Services(cfg =>
{
cfg.AddSingleton<IEventStore>(new InMemoryEventStore());
});
return builder;
}
public static BoundedContextModelBuilder UseInMemoryBuses(this BoundedContextModelBuilder builder)
{
builder.Services(cfg =>
{
var bus = new InMemoryBus();
cfg.AddSingleton<ICommandBus>(bus);
cfg.AddSingleton<IEventBus>(bus);
cfg.AddSingleton<IInboundMessageBus>(bus);
});
return builder;
}
}
}
|
using BenchmarkDotNet.Attributes;
using System;
using System.Collections;
namespace LinqAF.Benchmark.Benchmarks
{
public class ToList
{
static string[] Source1 = new[] { "foo", "bar", "fizz" };
static System.Collections.Generic.IEnumerable<string> Source2 = new UnsizedEnumerable();
class UnsizedEnumerable : System.Collections.Generic.IEnumerable<string>
{
class Enumerator : System.Collections.Generic.IEnumerator<string>
{
public string Current { get; set; }
object IEnumerator.Current => Current;
public int Index = 0;
public bool MoveNext()
{
if (Index >= Source1.Length) return false;
Current = Source1[Index];
Index++;
return true;
}
public void Reset()
{
Index = 0;
}
public void Dispose() { }
}
public System.Collections.Generic.IEnumerator<string> GetEnumerator()
{
return new Enumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class UnderlyingSized
{
[Benchmark]
public void LinqAF()
{
foreach (var str in Source1.ToList())
{
System.GC.KeepAlive(str);
}
}
[Benchmark(Baseline = true)]
public void LINQ2Objects()
{
foreach (var str in System.Linq.Enumerable.ToList(Source1))
{
System.GC.KeepAlive(str);
}
}
}
public class UnderlyingUnsized
{
[Benchmark]
public void LinqAF()
{
foreach (var str in Source2.ToList())
{
System.GC.KeepAlive(str);
}
}
[Benchmark(Baseline = true)]
public void LINQ2Objects()
{
foreach (var str in System.Linq.Enumerable.ToList(Source2))
{
System.GC.KeepAlive(str);
}
}
}
}
}
|
using System.Runtime.Serialization;
namespace Nop.Plugin.Shipping.EasyPost.Domain.Batch
{
/// <summary>
/// Represents batch status enumeration
/// </summary>
public enum BatchStatus
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Creating
/// </summary>
[EnumMember(Value = "creating")]
Creating,
/// <summary>
/// Creation failed
/// </summary>
[EnumMember(Value = "creation_failed")]
CreationFailed,
/// <summary>
/// Created
/// </summary>
[EnumMember(Value = "created")]
Created,
/// <summary>
/// Purchasing
/// </summary>
[EnumMember(Value = "purchasing")]
Purchasing,
/// <summary>
/// Purchase failed
/// </summary>
[EnumMember(Value = "purchase_failed")]
PurchaseFailed,
/// <summary>
/// Purchased
/// </summary>
[EnumMember(Value = "purchased")]
Purchased,
/// <summary>
/// Label generating
/// </summary>
[EnumMember(Value = "label_generating")]
LabelGenerating,
/// <summary>
/// Label generated
/// </summary>
[EnumMember(Value = "label_generated")]
LabelGenerated
}
/// <summary>
/// Represents batch shipment status enumeration
/// </summary>
public enum BatchShipmentStatus
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Postage purchased
/// </summary>
[EnumMember(Value = "postage_purchased")]
PostagePurchased,
/// <summary>
/// Postage purchase failed
/// </summary>
[EnumMember(Value = "postage_purchase_failed")]
PostagePurchaseFailed,
/// <summary>
/// Queued for purchase
/// </summary>
[EnumMember(Value = "queued_for_purchase")]
QueuedForPurchase,
/// <summary>
/// Creation failed
/// </summary>
[EnumMember(Value = "creation_failed")]
CreationFailed
}
} |
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Luna.Repository;
namespace Luna.Dapper.Repository
{
public abstract class DapperRepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>, new()
{
private readonly IDbConnection _connection;
protected DapperRepositoryBase(IDbConnection dbConnection)
{
_connection = dbConnection;
}
public IDbConnection GetConnection()
{
var connection = _connection;
connection.Open();
return connection;
}
public List<TEntity> GetAllList()
{
using var dbConnection = GetConnection();
return dbConnection.GetList<TEntity>().ToList();
}
public async Task<List<TEntity>> GetAllListAsync()
{
using var dbConnection = GetConnection();
var listAsync = await dbConnection.GetListAsync<TEntity>();
return listAsync.ToList();
}
public TEntity Get(TPrimaryKey id)
{
using var dbConnection = GetConnection();
return dbConnection.Get<TEntity>(id);
}
public async Task<TEntity> GetAsync(TPrimaryKey id)
{
using var dbConnection = GetConnection();
return await dbConnection.GetAsync<TEntity>(id);
}
public TPrimaryKey Insert(TEntity entity)
{
using var dbConnection = GetConnection();
dbConnection.Insert(entity);
return entity.Id;
}
public async Task<TPrimaryKey> InsertAsync(TEntity entity)
{
using var dbConnection = GetConnection();
await dbConnection.InsertAsync(entity);
return entity.Id;
}
public void Update(TEntity entity)
{
using var dbConnection = GetConnection();
dbConnection.Update(entity);
}
public async Task UpdateAsync(TEntity entity)
{
using var dbConnection = GetConnection();
await dbConnection.UpdateAsync(entity);
}
public void Delete(TEntity entity)
{
using var dbConnection = GetConnection();
dbConnection.Delete(entity);
}
public void Delete(TPrimaryKey id)
{
using var dbConnection = GetConnection();
dbConnection.Delete(new TEntity {Id = id});
}
public async Task DeleteAsync(TEntity entity)
{
using var dbConnection = GetConnection();
await dbConnection.DeleteAsync(entity);
}
public async Task DeleteAsync(TPrimaryKey id)
{
using var dbConnection = GetConnection();
await dbConnection.DeleteAsync(new TEntity {Id = id});
}
public int Count()
{
using var dbConnection = GetConnection();
return dbConnection.RecordCount<TEntity>();
}
public async Task<int> CountAsync()
{
using var dbConnection = GetConnection();
return await dbConnection.RecordCountAsync<TEntity>();
}
}
} |
using System.Collections.Generic;
namespace SFA.DAS.Experiment.Application.Cms.Models
{
public class DomainArticle
{
public string LandingPageSlug { get; set; }
public string LandingPageTitle { get; set; }
public List<DomainArticleSection> Sections { get; set; }
public string Summary { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.