content stringlengths 23 1.05M |
|---|
using System;
namespace ExRandom.MultiVariate {
public class InsideCircularRandom : Random<double> {
readonly MT19937 mt;
public InsideCircularRandom(MT19937 mt) {
if (mt is null) {
throw new ArgumentNullException(nameof(mt));
}
this.mt = mt;
}
public override Vector<double> Next() {
double theta, r;
theta = 2 * Math.PI * mt.NextDouble_OpenInterval1();
r = Math.Sqrt(mt.NextDouble());
return new Vector<double>(r * Math.Cos(theta), r * Math.Sin(theta));
}
}
}
|
using System;
namespace ServiceStack.Authentication.Azure.ServiceModel.Entities
{
public class Me
{
#region Properties and Indexers
public System.Guid ID { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string FullName => $"{FirstName} {LastName}".Trim();
public string DisplayName { get; set; }
public string Language { get; set; }
public string LastName { get; set; }
public string MobileNumber { get; set; }
public string JobTitle { get; set; }
public string UserPrincipalName { get; set; }
public string OfficeLocation { get; set; }
public string[] BusinessPhones { get; set; }
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
namespace Unity.Entities
{
public class World : IDisposable
{
private static readonly List<World> allWorlds = new List<World>();
private bool m_AllowGetManager = true;
//@TODO: What about multiple managers of the same type...
private Dictionary<Type, ScriptBehaviourManager> m_BehaviourManagerLookup =
new Dictionary<Type, ScriptBehaviourManager>();
private List<ScriptBehaviourManager> m_BehaviourManagers = new List<ScriptBehaviourManager>();
private int m_DefaultCapacity = 10;
public World(string name)
{
// Debug.LogError("Create World "+ name + " - " + GetHashCode());
Name = name;
allWorlds.Add(this);
}
public IEnumerable<ScriptBehaviourManager> BehaviourManagers =>
new ReadOnlyCollection<ScriptBehaviourManager>(m_BehaviourManagers);
public string Name { get; }
public override string ToString()
{
return Name;
}
public int Version { get; private set; }
public static World Active { get; set; }
public static ReadOnlyCollection<World> AllWorlds => new ReadOnlyCollection<World>(allWorlds);
public bool IsCreated => m_BehaviourManagers != null;
public void Dispose()
{
if (!IsCreated)
throw new ArgumentException("World is already disposed");
// Debug.LogError("Dispose World "+ Name + " - " + GetHashCode());
if (allWorlds.Contains(this))
allWorlds.Remove(this);
// Destruction should happen in reverse order to construction
m_BehaviourManagers.Reverse();
//@TODO: Crazy hackery to make EntityManager be destroyed last.
foreach (var behaviourManager in m_BehaviourManagers)
if (behaviourManager is EntityManager)
{
m_BehaviourManagers.Remove(behaviourManager);
m_BehaviourManagers.Add(behaviourManager);
break;
}
m_AllowGetManager = false;
foreach (var behaviourManager in m_BehaviourManagers)
try
{
behaviourManager.DestroyInstance();
}
catch (Exception e)
{
Debug.LogException(e);
}
if (Active == this)
Active = null;
m_BehaviourManagers.Clear();
m_BehaviourManagerLookup.Clear();
m_BehaviourManagers = null;
m_BehaviourManagerLookup = null;
}
private int GetCapacityForType(Type type)
{
return m_DefaultCapacity;
}
public void SetDefaultCapacity(int value)
{
m_DefaultCapacity = value;
}
public static void DisposeAllWorlds()
{
while (allWorlds.Count != 0)
allWorlds[0].Dispose();
}
private ScriptBehaviourManager CreateManagerInternal(Type type, int capacity, object[] constructorArguments)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!m_AllowGetManager)
throw new ArgumentException(
"During destruction of a system you are not allowed to create more systems.");
if (constructorArguments != null && constructorArguments.Length != 0)
{
var constructors =
type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (constructors.Length == 1 && constructors[0].IsPrivate)
throw new MissingMethodException(
$"Constructing {type} failed because the constructor was private, it must be public.");
}
#endif
m_AllowGetManager = true;
ScriptBehaviourManager manager;
try
{
manager = Activator.CreateInstance(type, constructorArguments) as ScriptBehaviourManager;
}
catch
{
m_AllowGetManager = false;
throw;
}
m_BehaviourManagers.Add(manager);
AddTypeLookup(type, manager);
try
{
manager.CreateInstance(this, capacity);
}
catch
{
RemoveManagerInteral(manager);
throw;
}
++Version;
return manager;
}
private ScriptBehaviourManager GetExistingManagerInternal(Type type)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!IsCreated)
throw new ArgumentException("During destruction ");
if (!m_AllowGetManager)
throw new ArgumentException(
"During destruction of a system you are not allowed to get or create more systems.");
#endif
ScriptBehaviourManager manager;
if (m_BehaviourManagerLookup.TryGetValue(type, out manager))
return manager;
return null;
}
private ScriptBehaviourManager GetOrCreateManagerInternal(Type type)
{
var manager = GetExistingManagerInternal(type);
return manager ?? CreateManagerInternal(type, GetCapacityForType(type), null);
}
private void AddTypeLookup(Type type, ScriptBehaviourManager manager)
{
while (type != typeof(ScriptBehaviourManager))
{
if (!m_BehaviourManagerLookup.ContainsKey(type))
m_BehaviourManagerLookup.Add(type, manager);
type = type.BaseType;
}
}
private void RemoveManagerInteral(ScriptBehaviourManager manager)
{
if (!m_BehaviourManagers.Remove(manager))
throw new ArgumentException($"manager does not exist in the world");
++Version;
var type = manager.GetType();
while (type != typeof(ScriptBehaviourManager))
{
if (m_BehaviourManagerLookup[type] == manager)
{
m_BehaviourManagerLookup.Remove(type);
foreach (var otherManager in m_BehaviourManagers)
if (otherManager.GetType().IsSubclassOf(type))
AddTypeLookup(otherManager.GetType(), otherManager);
}
type = type.BaseType;
}
}
public ScriptBehaviourManager CreateManager(Type type, params object[] constructorArgumnents)
{
return CreateManagerInternal(type, GetCapacityForType(type), constructorArgumnents);
}
public T CreateManager<T>(params object[] constructorArgumnents) where T : ScriptBehaviourManager
{
return (T) CreateManagerInternal(typeof(T), GetCapacityForType(typeof(T)), constructorArgumnents);
}
public T GetOrCreateManager<T>() where T : ScriptBehaviourManager
{
return (T) GetOrCreateManagerInternal(typeof(T));
}
public ScriptBehaviourManager GetOrCreateManager(Type type)
{
return GetOrCreateManagerInternal(type);
}
public T GetExistingManager<T>() where T : ScriptBehaviourManager
{
return (T) GetExistingManagerInternal(typeof(T));
}
public ScriptBehaviourManager GetExistingManager(Type type)
{
return GetExistingManagerInternal(type);
}
public void DestroyManager(ScriptBehaviourManager manager)
{
RemoveManagerInteral(manager);
manager.DestroyInstance();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace System.Configuration
{
internal static class IniSerializer
{
private static readonly Predicate<Type> PropertyTypeVerifier = IniKey.IsSupportedValueType;
public static void Serialize<T>(T source, IniSection section) where T : class, new()
{
foreach (var propertyPair in GetPropertyPairs(typeof(T)))
{
var key = section.Keys.Add(propertyPair.Key);
if (key.ParentCollectionCore != null)
SetKeyValue(propertyPair.Value, source, key);
}
}
public static T Deserialize<T>(IniSection section) where T : class, new()
{
T destination = new T();
foreach (var propertyPair in GetPropertyPairs(typeof(T)))
{
var key = section.Keys[propertyPair.Key];
if (key != null)
SetPropertyValue(propertyPair.Value, destination, key);
}
return destination;
}
private static IEnumerable<KeyValuePair<string, PropertyInfo>> GetPropertyPairs(Type type)
{
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!IniSerializer.PropertyTypeVerifier(property.PropertyType))
continue;
string propertyName = null;
var attributes = property.GetCustomAttributes(typeof(IniSerializationAttribute), false);
if (attributes.Length > 0)
{
var attribute = (IniSerializationAttribute)attributes[0];
if (attribute.Ignore)
continue;
propertyName = attribute.Alias;
}
yield return new KeyValuePair<string, PropertyInfo>((propertyName) ?? property.Name, property);
}
}
private static void SetKeyValue(PropertyInfo property, object source, IniKey key)
{
object propertyValue = property.GetValue(source, null);
if (propertyValue == null)
return;
if (property.PropertyType.IsArray || property.PropertyType.GetInterface(typeof(IList).Name) != null)
{
var values = new List<string>();
/* MZ(2016-01-02): Fixed issue with null items in array and list. */
foreach (var item in (IEnumerable)propertyValue)
values.Add(item != null ? item.ToString() : null);
key.Values = values.ToArray();
}
else
key.Value = propertyValue.ToString();
}
private static void SetPropertyValue(PropertyInfo property, object destination, IniKey key)
{
var propertyType = property.PropertyType;
if (propertyType.IsArray)
{
/* MZ(2016-01-02): Fixed issue with null array and list. */
if (!key.IsValueArray)
return;
var values = key.Values;
var itemType = propertyType.GetElementType();
var array = Array.CreateInstance(itemType, values.Length);
for (int i = 0; i < values.Length; i++)
array.SetValue(
TypeDescriptor.GetConverter(itemType).ConvertFromInvariantString(values[i]),
i);
property.SetValue(destination, array, null);
}
else if (propertyType.GetInterface(typeof(IList).Name) != null)
{
/* MZ(2016-01-02): Fixed issue with null array and list. */
if (!key.IsValueArray)
return;
var itemType = propertyType.GetGenericArguments()[0];
var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(itemType));
var values = key.Values;
if (!(values.Length == 1 && string.IsNullOrEmpty(values[0])))
foreach (var value in values)
list.Add(
TypeDescriptor.GetConverter(itemType).ConvertFromInvariantString(value));
property.SetValue(destination, list, null);
}
else
property.SetValue(
destination,
TypeDescriptor.GetConverter(propertyType).ConvertFromInvariantString(key.Value),
null);
}
}
}
|
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace Wikiled.Common.Utilities.Resources
{
public class DataDownloader : IDataDownloader
{
private readonly ILogger<DataDownloader> log;
public DataDownloader(ILogger<DataDownloader> logger)
{
log = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task DownloadFile(Uri url, string output, bool always = false)
{
log.LogInformation("Downloading <{0}> to <{1}>", url, output);
if (Directory.Exists(output))
{
log.LogInformation("Resources folder <{0} found.", output);
if (!always)
{
return;
}
}
WebRequest request = WebRequest.Create(url);
using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
{
using (Stream stream = response.GetResponseStream())
{
UnzipFromStream(stream, output);
}
}
}
private void UnzipFromStream(Stream zipStream, string outFolder)
{
ZipInputStream zipInputStream = new ZipInputStream(zipStream);
ZipEntry zipEntry = zipInputStream.GetNextEntry();
while (zipEntry != null)
{
string entryFileName = zipEntry.Name;
log.LogInformation("Unpacking [{0}]", entryFileName);
// to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
// Optionally match entrynames against a selection list here to skip as desired.
// The unpacked length is available in the zipEntry.Size property.
byte[] buffer = new byte[4096]; // 4K is optimum
// Manipulate the output filename here as desired.
string fullZipToPath = Path.Combine(outFolder, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
{
Directory.CreateDirectory(directoryName);
}
// Skip directory entry
string fileName = Path.GetFileName(fullZipToPath);
if (fileName.Length == 0)
{
zipEntry = zipInputStream.GetNextEntry();
continue;
}
// Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
// of the file, but does not waste memory.
// The "using" will close the stream even if an exception occurs.
using (FileStream streamWriter = File.Create(fullZipToPath))
{
StreamUtils.Copy(zipInputStream, streamWriter, buffer);
}
zipEntry = zipInputStream.GetNextEntry();
}
}
}
}
|
using C43COOL.Domain.Base;
using C43COOL.Models.Modules.Management;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C43COOL.Service.Permission.Strategy
{
public interface IAuthStrategy
{
List<ModuleViewModel> Modules { get; }
List<Role> Role { get; }
}
}
|
using CameraDataUtilities;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPositionMarker : MonoBehaviour
{
[SerializeField] Pan pan;
[SerializeField] RectTransform uiXform;
[SerializeField] float pedding;
FollowTargetLocator locator;
Transform target;
bool stickToTarget;
Camera cam;
Vector3 pivotPosition;
private void OnEnable()
{
}
// Start is called before the first frame update
void Start()
{
if (target == null)
{
locator = GameObject.FindObjectOfType<FollowTargetLocator>();
target = locator.GetTarget;
}
cam = Camera.main;
}
// Update is called once per frame
public void GoToTarget()
{
pan.SetPosition(target.position);
}
public void ToggleStickToTarget()
{
stickToTarget = !stickToTarget;
}
private void Update()
{
if (uiXform.gameObject.activeSelf&&target!=null)
{
var screenPoint = cam.WorldToScreenPoint(target.position);
var rect = uiXform.rect;
if (screenPoint.z < 0)
{
screenPoint.x = (Screen.width - screenPoint.x);
screenPoint.y = 0;
}
Vector3 outBound = Vector3.zero;
var position = ScreenClampPoint(rect, screenPoint, out outBound, pedding);
uiXform.position = position;
}
if (stickToTarget)
{
GoToTarget();
}
}
Vector3 ScreenClampPoint(Rect rect, Vector3 inputPoint, out Vector3 outBoundAmount, float pedding = 0f)
{
var newpoint = inputPoint;
newpoint.x = Mathf.Clamp(newpoint.x, 0 - rect.xMin + pedding, Screen.width - rect.xMax - pedding);
newpoint.y = Mathf.Clamp(newpoint.y, 0 - rect.yMin + pedding, Screen.height - rect.yMax - pedding);
outBoundAmount = inputPoint - newpoint;
return newpoint;
}
}
|
using Entitas;
using System.Collections.Generic;
namespace FineGameDesign.Entitas
{
public sealed class HealthTriggerSystem : ReactiveSystem<GameEntity>
{
private readonly GameContext m_Context;
public HealthTriggerSystem(Contexts contexts) : base(contexts.game)
{
m_Context = contexts.game;
}
protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
{
return context.CreateCollector(
GameMatcher.TriggerEnter.Added()
);
}
protected override bool Filter(GameEntity entity)
{
GameEntity other = m_Context.GetEntityWithId(entity.triggerEnter.otherId);
if (other == null)
return false;
if (entity.hasHealth && other.hasHealthChanger)
return true;
if (other.hasHealth && entity.hasHealthChanger)
return true;
return false;
}
protected override void Execute(List<GameEntity> entities)
{
foreach (GameEntity self in entities)
{
GameEntity other = m_Context.GetEntityWithId(self.triggerEnter.otherId);
TryReplaceHealth(self, other);
TryReplaceHealth(other, self);
}
}
private static void TryReplaceHealth(GameEntity self, GameEntity other)
{
if (!self.hasHealth || !other.hasHealthChanger)
return;
self.ReplaceHealth(self.health.value + other.healthChanger.value);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace UnMango.Rest.Internal
{
internal static class EnumerableExtensions
{
public static Dictionary<T1, T2> ToDictionary<T1, T2>(this IEnumerable<KeyValuePair<T1, T2>> enumerable)
{
return enumerable.ToDictionary(x => x.Key, x => x.Value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Core.Text;
using HolisticWare.Xamarin.Tools.Bindings.XamarinAndroid.AndroidX.Migraineator.Generated;
using Mono.Cecil;
using Mono.Cecil.Rocks;
namespace HolisticWare.Xamarin.Tools.Bindings.XamarinAndroid.AndroidX.Migraineator
{
public partial class ApiInfo
{
public partial class MonoCecilData
{
public MonoCecilData(string path)
{
this.file_name = path;
Console.WriteLine("Mono.Cecil initialized for API scraping");
return;
}
string file_name = null;
FileStream fs = null;
XDocument xml_doc = null;
public static IAssemblyResolver CreateAssemblyResolver()
{
var VsInstallRoot = "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\";
var TargetFrameworkVerison = "v9.0";
var resolver = new DefaultAssemblyResolver();
if (!string.IsNullOrEmpty(VsInstallRoot) && Directory.Exists(VsInstallRoot))
{
resolver.AddSearchDirectory(Path.Combine(
VsInstallRoot,
@"Common7\IDE\ReferenceAssemblies\Microsoft\Framework\MonoAndroid\" + TargetFrameworkVerison
));
}
else
{
resolver.AddSearchDirectory(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
@"Reference Assemblies\Microsoft\Framework\MonoAndroid\" + TargetFrameworkVerison
));
}
return resolver;
}
public new List <
(
string ManagedClass,
string ManagedNamespace,
string JNIPackage,
string JNIType
)
> TypesAndroidRegistered
{
get;
protected set;
}
public new List<
(
string ManagedClass,
string ManagedNamespace,
string JNIPackage,
string JNIType
)
> TypesNotAndroidRegistered
{
get;
protected set;
}
}
}
}
|
using System.Collections.Generic;
using System.IO;
using RenderStack.Math;
using I1 = System.SByte;
using I2 = System.Int16;
using I4 = System.Int32;
using U1 = System.Byte;
using U2 = System.UInt16;
using U4 = System.UInt32;
using F4 = System.Single;
using S0 = System.String;
using VX = System.UInt32;
using COL4 = RenderStack.Math.Vector4;
using COL12 = RenderStack.Math.Vector3;
using VEC12 = RenderStack.Math.Vector3;
using FP4 = System.Single;
using ANG4 = System.Single;
using FNAM0 = System.String;
namespace RenderStack.LightWave
{
public partial class LWSceneParser
{
void NumChannels()
{
/*num_channels = */file.read_int();
}
void Channel()
{
int channel_id = file.read_int();
currentEnvelope = new LWSEnvelope();
currentMotion.insert((LWChannel)channel_id, currentEnvelope);
}
void Envelope()
{
/*num_channel_keys = */file.read_int();
}
void Key()
{
float value = (float)( file.read_double() );
float time = (float)( file.read_double() );
Shape spantype = (Shape)file.read_int();
float p1 = (float)( file.read_double() );
float p2 = (float)( file.read_double() );
float p3 = (float)( file.read_double() );
float p4 = (float)( file.read_double() );
float p5 = (float)( file.read_double() );
float p6 = (float)( file.read_double() );
var channel_key = new LWChannelKey(
value,
time,
spantype,
p1,
p2,
p3,
p4,
p5,
p6
);
currentEnvelope.insert(channel_key);
}
void Behaviors()
{
Behavior pre = (Behavior)file.read_int();
Behavior post = (Behavior)file.read_int();
currentEnvelope.setBehaviors(pre, post);
file.read_end_scope();
}
}
}
|
namespace Client
{
public static class ClientFactory
{
private const string Url = "http://{0}/Service.svc";
public static IClient Create(string host)
{
return new ServiceClient(string.Format(Url, host));
}
}
}
|
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Runtime.Remoting.Channels
{
using System.Security.Permissions;
public interface ISecurableChannel
{
bool IsSecured
{
[System.Security.SecurityCritical] // auto-generated_required
get;
[System.Security.SecurityCritical] // auto-generated_required
set;
}
}
}
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace WXZ.GCC.LAWExport.Common
{
public class ActivityLogRoot{
[JsonProperty("value")]
public List<ActivityLog> ActivityLogs;
}
public class ActivityLog
{
public DateTime TimeGenerated { get; set; }
public DateTime BlobTime { get; set; }
public string OperationName { get; set; }
public string OperationNameValue { get; set; }
public string Level { get; set; }
public string ActivityStatus { get; set; }
public string ResourceGroup { get; set; }
public string SubscriptionId { get; set; }
public string Category { get; set; }
public DateTime EventSubmissionTimestamp { get; set; }
public string ClientIpAddress { get; set; }
public string ResourceId { get; set; }
}
} |
namespace SOLIDplate.Domain.Entities.Interfaces
{
public interface ICompositeEntity<TIdentityEntity1, TIdentityEntity2>
where TIdentityEntity1 : class, new()
where TIdentityEntity2 : class, new()
{
}
public interface ICompositeEntity<TIdentityEntity1, TIdentityEntity2, TIdentityEntity3>
where TIdentityEntity1 : class, new()
where TIdentityEntity2 : class, new()
where TIdentityEntity3 : class, new()
{
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public GameObject boomPrefab;
private Vector2 _direction = new Vector2();
private float _speed = 2000f;
private void Start()
{
}
private void Update()
{
this.GetComponent<Rigidbody2D>().velocity = _direction * _speed;
}
public void SetDirection(Vector2 direction)
{
_direction = direction;
}
private void OnCollisionEnter2D(Collision2D collision)
{
boomPrefab.transform.position = this.transform.position + new Vector3(_direction.x * 30, _direction.y * 30, 3);
boomPrefab.transform.localScale = new Vector3(100f, 100f);
var boom = Instantiate(boomPrefab);
Destroy(boom, 1);
collision.collider.SendMessage("ApplyDamage", 1, SendMessageOptions.DontRequireReceiver);
Destroy(this.gameObject);
}
}
|
using System;
namespace FabricAdcHub.Frontend.Models
{
public class CustomRole
{
public CustomRole()
{
RoleId = "role-" + Guid.NewGuid();
}
public string RoleId { get; set; }
public string RoleName { get; set; }
public string NormalizedRoleName { get; set; }
}
}
|
using BeekeepingDiary.Data;
using BeekeepingDiary.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BeekeepingDiary.Services.Inspections
{
public class InspectionService : IInspectionService
{
private readonly BeekeepingDbContext data;
public InspectionService(BeekeepingDbContext data)
{
this.data = data;
}
public InspectionQueryServiceModel All(string userId, int beehiveId)
{
var inspections = GetInspectionsByBeehiveId(beehiveId);
inspections = inspections.OrderByDescending(b => b.Date);
return new InspectionQueryServiceModel
{
Inspections = inspections
};
}
public IEnumerable<InspectionBeehiveServiceModel> AllBeehives(string userId)
{
var beehives = this.data
.Beehives
.Where(b => b.BeeGarden.UserId == userId)
.Select(b => new InspectionBeehiveServiceModel
{
Id = b.Id,
Name = b.Name,
UserId = b.BeeGarden.UserId
})
.ToList();
return beehives;
}
public int Create(DateTime date, int beehiveId, string description)
{
var inspectionData = new Inspection
{
Date = date,
Description = description,
BeehiveId = beehiveId
};
this.data.Inspections.Add(inspectionData);
this.data.SaveChanges();
return inspectionData.Id;
}
public InspectionDetailsServiceModel Details(int id)
=> this.data
.Inspections
.Where(i => i.Id == id)
.Select(i => new InspectionDetailsServiceModel
{
Id = i.Id,
Date = i.Date,
Description = i.Description,
BeehiveId = i.BeehiveId,
Beehive = i.Beehive.Name,
UserId = i.Beehive.BeeGarden.UserId
})
.FirstOrDefault();
public bool Edit(int inspectionId, DateTime date, string description)
{
var inspectionData = this.data.Inspections.Find(inspectionId);
if (inspectionData == null)
{
return false;
}
inspectionData.Date = date;
inspectionData.Description = description;
this.data.SaveChanges();
return true;
}
public IEnumerable<InspectionServiceModel> GetInspectionsByBeehiveId(int beehiveId)
{
var query = this.data.Inspections
.Where(x => x.BeehiveId == beehiveId)
.Select(x => new InspectionServiceModel
{
Id = x.Id,
Date = x.Date,
Beehive = x.Beehive.Name,
Description = x.Description
})
.ToList();
return query;
}
public bool Delete(int inspectionId)
{
var inspection = this.data.Inspections.FirstOrDefault(x => x.Id == inspectionId);
this.data.Inspections.Remove(inspection);
this.data.SaveChanges();
return true;
}
}
}
|
namespace Pancake.Core
{
public class ResourcePair
{
public Resource Should { get; set; }
public Resource System { get; set; }
}
} |
namespace Owin.Scim.v2.Model
{
using Canonicalization;
using Configuration;
using Extensions;
using Validation;
public class ScimGroup2Definition : ScimResourceTypeDefinitionBuilder<ScimGroup2>
{
public ScimGroup2Definition(ScimServerConfiguration serverConfiguration)
: base(
serverConfiguration,
ScimConstants.ResourceTypes.Group,
ScimConstantsV2.Schemas.Group,
ScimConstantsV2.Endpoints.Groups,
typeof (ScimGroup2Validator),
(schemaIdentifiers, parameterType) => schemaIdentifiers.Contains(ScimConstantsV2.Schemas.Group))
{
SetName("Group");
SetDescription("Group resource.");
For(u => u.Schemas)
.SetReturned(Returned.Always);
For(u => u.Id)
.SetMutability(Mutability.ReadOnly)
.SetReturned(Returned.Always)
.SetUniqueness(Uniqueness.Server)
.SetCaseExact(true);
For(u => u.DisplayName)
.SetDescription("A human-readable name for the group.")
.SetRequired(true);
For(u => u.Members)
.SetDescription("A list of members of the group.")
.AddCanonicalizationRule(member => member.Canonicalize(e => e.Type, StringExtensions.UppercaseFirstCharacter));
For(u => u.Meta)
.SetMutability(Mutability.ReadOnly)
.SetReturned(Returned.Always);
}
}
} |
using UnityEngine;
using Mirror;
public class MenuToggler : MonoBehaviour
{
public bool visible = true;
NetworkManagerHUD hud = null;
GameObject mainMenu = null;
void Start()
{
hud = GameObject.Find("NetworkManager").GetComponent<NetworkManagerHUD>();
mainMenu = GameObject.Find("MainMenu");
ShowHide(visible);
}
void Update()
{
if (Input.GetKeyUp("escape")) {
Toggle();
}
}
public void Toggle()
{
ShowHide(!visible);
}
public void ShowHide(bool v)
{
visible = v;
hud.showGUI = visible;
mainMenu.SetActive(visible);
}
}
|
//
// Copyright (c) 2019-2022 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//
namespace AngouriMath
{
partial record Entity
{
/// <summary>Generates Python code that you can use with sympy</summary>
internal abstract string ToSymPy();
/// <summary>
/// Generates python code without any additional symbols that can be run in SymPy
/// </summary>
/// <param name="parenthesesRequired">
/// Whether to wrap it with parentheses
/// Usually depends on its parental nodes
/// </param>
protected string ToSymPy(bool parenthesesRequired) =>
parenthesesRequired ? @$"({ToSymPy()})" : ToSymPy();
}
}
|
using CoreEngine.APIHandlers;
using CoreEngine.Model.DBModel;
using GalaSoft.MvvmLight.Command;
using Mobile.Core.Engines.Services;
using Mobile.Core.Models.Core;
using System;
using System.Collections.Generic;
using System.Windows.Input;
namespace Mobile.Core.ViewModels
{
public class CourseDetailViewModel : BaseViewModel
{
private readonly ICourseHandler _courseHandler;
private readonly IPreferenceEngine _preferenceEngine;
public bool CanEdit { get; private set; }
public Semester CurrentSemester { get; private set; }
public Course CurrentCourse { get; private set; }
public CourseDetailViewModel(ICourseHandler courseHandler, IPreferenceEngine preferenceEngine)
{
_courseHandler = courseHandler;
_preferenceEngine = preferenceEngine;
}
public override async void OnAppear(params object[] args)
{
base.OnAppear(args);
if (args != null && args.Length > 0 && args[0] is Course course)
{
CurrentSemester = course.Semester;
//CurrentCourse = course;
CanEdit = AppService.HasCRRole;
IsBusy = true;
CurrentCourse = await _courseHandler.GetCourse(course.Id);
IsBusy = false;
// RefreshAction();
}
else
{
GoBack();
}
}
protected override async void RefreshAction()
{
base.RefreshAction();
CurrentCourse = await _courseHandler.GetCourse(CurrentCourse.Id);
IsRefreshisng = false;
}
public ICommand EditCourseCommand => new RelayCommand(CourseAction);
public ICommand FileCommand => new RelayCommand<DBFile>(FileAction);
private void FileAction(DBFile obj)
{
_nav.OpenFile(obj.Id);
}
private void CourseAction()
{
var actionList = new Dictionary<string, Action>
{
{ "Add Event", () => _nav.NavigateTo<AddUpdateNoticeViewModel>(CurrentCourse) },
{ "Modify Course", () => _nav.NavigateTo<AddUpdateCourseViewModel>(CurrentSemester, CurrentCourse) },
{ "Add Lesson", () => _nav.NavigateTo<AddUpdateLessonViewModel>(CurrentCourse, new Lesson()) },
{ "Add Course Material", AddMaterialAction },
{ "Upload Course Grade", CourseGradeAction }
};
_dialog.ShowAction(CurrentCourse.CourseName, "Cancel", actionList);
}
private async void CourseGradeAction()
{
var file = await _preferenceEngine.PickFile();
IsBusy = true;
var res = await _courseHandler.UploadCourseResult(CurrentCourse.Id, file, null);
_dialog.ShowToastMessage(res.Message);
IsBusy = false;
}
private async void AddMaterialAction()
{
var file = await _preferenceEngine.PickFile();
IsBusy = true;
var res = await _courseHandler.AddMaterial(CurrentCourse.Id, new List<DBFile> { file });
IsBusy = false;
if (res != null)
{
_dialog.ShowToastMessage(res.Message);
if (res.Actionstatus)
{
RefreshAction();
}
}
}
}
}
|
using BO;
using System;
using System.Collections.Generic;
namespace api.Properties.Handlers
{
public interface IClientesHandler
{
Guid Save(Cliente model);
IEnumerable<Cliente> GetAll(out int totalPages, int pageNumber, int pageSize);
Cliente GetOne(Guid id);
Cliente Update(Guid id, Cliente model);
IEnumerable<Cliente> SearchByTerm(String term);
}
}
|
using System.Windows.Forms;
namespace GPSoft.Tools.ReaderMe.Forms
{
public partial class FormHelp : Form
{
public FormHelp()
{
InitializeComponent();
}
}
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using Dolittle.Artifacts;
using Dolittle.Commands;
using Dolittle.PropertyBags;
using Dolittle.Runtime.Commands;
using Dolittle.Tenancy;
namespace Dolittle.AspNetCore.Debugging.Commands
{
/// <summary>
/// Represents a coordinator capable of handling commands
/// </summary>
public interface ICommandCoordinator
{
/// <summary>
/// Handle a command
/// </summary>
CommandResult Handle(TenantId tenant, ICommand command);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace InfoService {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main() {
InfoService inf = new InfoService();
if (Debugger.IsAttached) {
inf.Start();
Console.ReadKey();
} else {
ServiceBase.Run(inf);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blazor.ECharts.Options
{
public record BMap
{
public double[] Center { get; set; }
public int Zoom { get; set; }
public bool Roam { get; set; }
public Mapstyle MapStyle { get; set; }
}
public record Mapstyle
{
public List<Stylejson> StyleJson { get; set; }
}
public record Stylejson
{
public string FeatureType { get; set; }
public string ElementType { get; set; }
public Stylers Stylers { get; set; }
}
public record Stylers
{
public string Color { get; set; }
public string Visibility { get; set; }
public int? Lightness { get; set; }
}
}
|
using System;
namespace Weikio.ApiFramework.Abstractions
{
public class PluginForApiNotFoundException : Exception
{
private readonly string _name;
private readonly Version _version;
public PluginForApiNotFoundException(string name, Version version)
{
_name = name;
_version = version;
}
}
} |
using System;
using UnityEngine;
using System.Collections;
using UniRx;
using UnityEngine.UI;
namespace UniRxWorkBook.Operators
{
public class Lesson_9_CombineLatest : MonoBehaviour
{
[SerializeField] private InputField leftInput;
[SerializeField] private InputField rightInput;
[SerializeField] private Text resultLabel;
private void Start()
{
var leftStream = leftInput.OnValueChangeAsObservable().Select(x => Int32.Parse(x));
var rightStream = rightInput.OnValueChangeAsObservable().Select(x => Int32.Parse(x));
// 下記のオペレータチェーンは2つのInputFieldに入力された数値を合計して表示するストリームを生成している
// ただ、Zipでは挙動がおかしいので、Zipを適切なオペレータに変更しInputFiledの変更が即時反映されるようにしよう
leftStream
.Zip(rightStream, (left, right) => left + right)
.SubscribeToText(resultLabel);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using NRC_Code_Designer.src.UI.Class;
namespace NRC_Code_Designer.src.Core.Project
{
/// <summary>
/// Give capacity to display.
/// </summary>
interface IDisplayAble
{
/// <summary>
/// Class absolute position in the parent grid.
/// </summary>
Point Position { get; set; }
/// <summary>
/// Event that is trigered when the position changes.
/// </summary>
event EventHandler Moved;
/// <summary>
/// User control to implement display.
/// </summary>
UserControlClass UserControl { get; set; }
}
}
|
namespace PayXpertLibrary
{
public enum TransactionTypes
{
AUTHORIZE, CAPTURE, SALE, REFUND, REBILL, CANCEL,
CREDIT,
_3DSCHECK, _3DSPARSE,
TODITO_SALE,
BLACKLIST_TRANSACTION, BLACKLIST_VALUE,
CANCEL_SUBSCRIPTION, STATUS_SUBSCRIPTION, EXPORT_SUBSCRIPTION, EXPORT_SUBSCRIPTION_OFFER,
QUERY_TRANSACTION_STATUS,
EXPORT_TRANSACTION_LIST,
INSTANT_CONVERSION
}
public enum BlacklistValueType
{
CREDIT_CARD_NUMBER, TODITO_CARD_NUMBER, ACCOUNT_NUMBER, SHOPPER_EMAIL, CUSTOMER_IP
}
public enum SubscriptionType
{
NORMAL, INFINITE, ONETIME, LIFETIME
}
}
|
namespace Benchmark.Base
{
public enum SorterCategories
{
System,
Serial,
Parallel
}
}
|
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using UnityEngine;
using UnityEngine.Jobs;
public class Rotation2DSystem : JobComponentSystem
{
private EntityQuery rotations;
protected override void OnCreate()
{
rotations = GetEntityQuery(ComponentType.ReadOnly<Rotation2D>(), ComponentType.ReadOnly<Transform>());
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var job = new RotationJob { Rotations = rotations.ToComponentDataArray<Rotation2D>(Allocator.TempJob) };
return job.Schedule(rotations.GetTransformAccessArray(), inputDeps);
}
private struct RotationJob : IJobParallelForTransform
{
[ReadOnly, DeallocateOnJobCompletion] public NativeArray<Rotation2D> Rotations;
public void Execute(int index, TransformAccess transform)
{
transform.rotation = Quaternion.Euler(0, Rotations[index].Axis >= 0 ? 0 : 180, Rotations[index].Rotation);
}
}
} |
using FluentAssertions;
using Moq;
using Xunit;
namespace Floatingman.CommandLineParser.xUnit
{
public class CommandLineTests
{
[Fact]
public void Parse_accepts_commands()
{
var args = new string[] { "azalea" };
var parameters = CommandLine.Instance.Parse<CommandTestArgs>(args);
parameters.Command.Should().Be("azalea");
}
[Fact]
public void Parse_positional_argument_can_be_after_boolean_options()
{
var args = new string[] { "-e", "123", "shark attack" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Shark.Should().Be("shark attack");
}
[Fact]
public void Parse_positional_argument_can_be_after_value_options()
{
var args = new string[] { "-a", "shark attack" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Shark.Should().Be("shark attack");
}
[Fact]
public void Parse_sets_longForm_bool_to_true()
{
var args = new string[] { "--dog" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Dog.Should().BeTrue();
}
[Fact]
public void Parse_sets_shortForm_bool_to_true()
{
var args = new string[] { "-b" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Baboon.Should().BeTrue();
}
[Fact]
public void Parse_should_get_an_array_of_double()
{
var args = new string[] { "-i", "1.23,4.56" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Ibis.Should().Equal(1.23, 4.56);
}
[Fact]
public void Parse_should_get_an_array_of_int()
{
var args = new string[] { "-h", "123,456,789" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Hog.Should().Equal(123, 456, 789);
}
[Fact]
public void Parse_should_get_an_array_of_string()
{
var args = new string[] { "-j", "there,are,dogs,about" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Jaguar.Should().Equal("there", "are", "dogs", "about");
}
[Fact]
public void Parse_should_get_a_double()
{
var args = new string[] { "--frog", "123.456" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Frog.Should().Be(123.456);
}
[Fact]
public void Parse_should_get_an_int()
{
var args = new string[] { "-e", "123" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Elephant.Should().Be(123);
}
[Fact]
public void Parse_should_get_a_string()
{
var args = new string[] { "-g", "will eat anything" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Goat.Should().Be("will eat anything");
}
[Fact]
public void Parse_should_get_argument()
{
var args = new string[] { "shark attack" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Shark.Should().Be("shark attack");
}
[Fact]
public void Parse_should_get_two_arguments()
{
var args = new string[] { "shark attack", "123" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Shark.Should().Be("shark attack");
parameters.Tiger.Should().Be(123);
}
[Fact]
public void Parse_should_log_an_error_if_unknown_parameter_passed_in()
{
var args = new string[] { "--zoo" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Errors.Should().NotBeEmpty();
parameters.Errors[0].Should().Be("zoo is not recognized");
}
[Fact]
public void Parse_should_pick_up_single_items_as_IEnumerable()
{
var args = new string[] { "-j", "shark attack" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Jaguar.Should().Equal("shark attack");
}
[Fact]
public void Parse_should_return_Default_value_if_no_value_set()
{
var args = new string[0];
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Kangaroo.Should().Be(555);
}
[Fact]
public void Parse_should_return_error_list_if_IsRequired_and_Default_and_no_value()
{
var args = new string[0];
var parameters = CommandLine.Instance.Parse<TestRequiredArgs>(args);
parameters.Errors.Should().NotBeEmpty();
parameters.Errors[0].Should().Be("Airplane is required, but not set");
}
[Theory]
[InlineData("-c")]
[InlineData("--cat")]
public void Parse_will_accept_either_long_or_short_form(params string[] args)
{
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Cat.Should().BeTrue();
}
[Fact]
public void Parse_will_log_an_error_if_multiple_parameters_have_same_short_option()
{
var args = new string[] { "-b", "-b" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Errors.Should().NotBeEmpty();
parameters.Errors[0].Should().Be("b is duplicated");
}
[Fact]
public void Parse_will_not_honor_IsRequired_on_bool()
{
var args = new string[0];
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Aardvark.Should().BeFalse();
}
[Theory]
[InlineData("-e", "eating peanuts")]
[InlineData("-e", "3.14")]
[InlineData("--frog", "sitting on a lily pad")]
[InlineData("-h", "1,1.21")]
public void Parse_will_return_error_list_if_data_not_coercable(params string[] args)
{
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Errors.Should().NotBeEmpty();
parameters.Errors[0].Should().StartWith($"[{args[1]}] cannot be converted to");
}
[Fact]
public void Parse_will_throw_an_exception_if_multiple_parameters_have_same_long_option()
{
var args = new string[] { "--cat", "--cat" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Errors.Should().NotBeEmpty();
parameters.Errors[0].Should().Be("cat is duplicated");
}
[Fact]
public void Parse_will_throw_an_exception_if_multiple_parameters_have_same_string_option()
{
var args = new string[] { "-g", "rex", "-g", "fido" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Errors.Should().NotBeEmpty();
parameters.Errors[0].Should().Be("g is duplicated");
}
[Fact]
public void Parse_will_throw_an_exception_if_multiple_parameters_have_same_boolean_option()
{
var args = new string[] { "-c", "--cat" };
var parameters = CommandLine.Instance.Parse<TestArgs>(args);
parameters.Errors.Should().NotBeEmpty();
parameters.Errors[0].Should().Be("cat is duplicated");
}
[Fact]
public void Parse_will_allow_multiple_string_parameters_with_same_name()
{
var args = new string[] { "-c", "Fluffy", "--cat", "Mittens" };
var parameters = CommandLine.Instance.Parse<MultipleTestArgs>(args);
parameters.Errors.Should().BeEmpty();
parameters.Cat.Length.Should().Be(2);
parameters.Cat[0].Should().Be("Fluffy");
}
[Fact]
public void Parse_will_allow_multiple_double_parameters_with_same_name()
{
var args = new string[] { "-d", "3.2", "--dog", "6.505" };
var parameters = CommandLine.Instance.Parse<MultipleTestArgs>(args);
parameters.Errors.Should().BeEmpty();
parameters.Dog.Length.Should().Be(2);
parameters.Dog[0].Should().Be(3.2);
}
[Command("plants")]
private class CommandTestArgs : CommandArgs
{
}
private class TestArgs : CommandArgs
{
// options
[Option('a', IsRequired = true)] public bool Aardvark { get; set; }
[Option('b')] public bool Baboon { get; set; }
[Option('c', "cat")] public bool Cat { get; set; }
[Option("dog")] public bool Dog { get; set; }
[Option('e')] public int Elephant { get; set; }
[Option("frog")] public double Frog { get; set; }
[Option('g')] public string Goat { get; set; }
[Option('h')] public int[] Hog { get; set; }
[Option('i')] public double[] Ibis { get; set; }
[Option('j')] public string[] Jaguar { get; set; }
[Option('k', Default = 555)] public int Kangaroo { get; set; }
// arguments
[Argument(0)] public string Shark { get; set; }
[Argument(1)] public int Tiger { get; set; }
}
private class TestRequiredArgs : CommandArgs
{
[Option("airplane", Default = 777, IsRequired = true, Name = "Airplane")] public int Airplane { get; set; }
}
}
internal class MultipleTestArgs : CommandArgs
{
[Option('c', "cat", AllowMultiple = true)] public string[] Cat { get; set; }
[Option('d', "dog", AllowMultiple = true)] public double[] Dog { get; set; }
}
}
|
using System.Collections.Generic;
using System.Windows.Automation;
using FluentAssertions;
using NUnit.Framework;
namespace UIA.Extensions.AutomationProviders.Tables
{
abstract class ProviderTest<TProvider> where TProvider : AutomationProvider
{
private readonly ControlType _expectedControlType;
protected ProviderTest(ControlType controlType)
{
_expectedControlType = controlType;
}
[SetUp]
public void Before()
{
Subject = Create();
}
[Test]
public void ItHasTheCorrectControlType()
{
Value<int>(AutomationElementIdentifiers.ControlTypeProperty.Id)
.Should().Be(_expectedControlType.Id);
}
[Test]
public void ItLocalizesTheControlType()
{
Value<string>(AutomationElementIdentifiers.LocalizedControlTypeProperty.Id)
.Should().Be(_expectedControlType.LocalizedControlType);
}
protected TProvider Subject { get; private set; }
protected abstract TProvider Create();
protected TPattern Pattern<TPattern>(int id)
{
return (TPattern)Subject.GetPatternProvider(id);
}
protected List<AutomationProvider> Children
{
get { return Subject.Children; }
}
private TValue Value<TValue>(int id)
{
return (TValue)Subject.GetPropertyValue(id);
}
}
} |
// Copyright (c) zhenlei520 All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Autofac;
using EInfrastructure.Core.Config.Entities.Configuration;
using EInfrastructure.Core.Config.Entities.Ioc;
using Microsoft.Extensions.DependencyInjection;
namespace EInfrastructure.Core.AutoFac.MySql
{
/// <summary>
/// 自动注入扩展
/// </summary>
public static class AutofacAutoRegisterExt
{
#region 添加多个数据库
/// <summary>
/// 添加多个数据库
/// </summary>
/// <param name="containerBuilder"></param>
/// <typeparam name="T"></typeparam>
public static void AddMultDbContext<T>(this ContainerBuilder containerBuilder) where T : IDbContext
{
containerBuilder.RegisterType<T>().As<IUnitOfWork<T>>().PropertiesAutowired()
.InstancePerLifetimeScope();
}
#endregion
#region 添加多个数据库
/// <summary>
/// 添加多个数据库
/// </summary>
/// <param name="services"></param>
/// <typeparam name="T"></typeparam>
public static IServiceCollection AddMultDbContext<T>(this IServiceCollection services) where T : IDbContext
{
services.AddScoped(typeof(IUnitOfWork<T>), typeof(T));
return services;
}
#endregion
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// ConfigurationSaveTest.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.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.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Configuration;
using System.Collections.Generic;
using SysConfig = System.Configuration.Configuration;
using Xunit;
namespace MonoTests.System.Configuration
{
using Util;
public class ConfigurationSaveTest
{
#region Test Framework
public abstract class ConfigProvider
{
public void Create(string filename)
{
if (File.Exists(filename))
File.Delete(filename);
var settings = new XmlWriterSettings();
settings.Indent = true;
using (var writer = XmlTextWriter.Create(filename, settings))
{
writer.WriteStartElement("configuration");
WriteXml(writer);
writer.WriteEndElement();
}
}
public abstract UserLevel Level
{
get;
}
public enum UserLevel
{
MachineAndExe,
RoamingAndExe
}
public virtual SysConfig OpenConfig(string parentFile, string configFile)
{
ConfigurationUserLevel level;
var map = new ExeConfigurationFileMap();
switch (Level)
{
case UserLevel.MachineAndExe:
map.ExeConfigFilename = configFile;
map.MachineConfigFilename = parentFile;
level = ConfigurationUserLevel.None;
break;
case UserLevel.RoamingAndExe:
map.RoamingUserConfigFilename = configFile;
map.ExeConfigFilename = parentFile;
level = ConfigurationUserLevel.PerUserRoaming;
break;
default:
throw new InvalidOperationException();
}
return ConfigurationManager.OpenMappedExeConfiguration(map, level);
}
protected abstract void WriteXml(XmlWriter writer);
}
public abstract class MachineConfigProvider : ConfigProvider
{
protected override void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("configSections");
WriteSections(writer);
writer.WriteEndElement();
WriteValues(writer);
}
public override UserLevel Level
{
get { return UserLevel.MachineAndExe; }
}
protected abstract void WriteSections(XmlWriter writer);
protected abstract void WriteValues(XmlWriter writer);
}
class DefaultMachineConfig : MachineConfigProvider
{
protected override void WriteSections(XmlWriter writer)
{
writer.WriteStartElement("section");
writer.WriteAttributeString("name", "my");
writer.WriteAttributeString("type", typeof(MySection).AssemblyQualifiedName);
writer.WriteAttributeString("allowLocation", "true");
writer.WriteAttributeString("allowDefinition", "Everywhere");
writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser");
writer.WriteAttributeString("restartOnExternalChanges", "true");
writer.WriteAttributeString("requirePermission", "true");
writer.WriteEndElement();
}
internal static void WriteConfigSections(XmlWriter writer)
{
var provider = new DefaultMachineConfig();
writer.WriteStartElement("configSections");
provider.WriteSections(writer);
writer.WriteEndElement();
}
protected override void WriteValues(XmlWriter writer)
{
writer.WriteStartElement("my");
writer.WriteEndElement();
}
}
class DefaultMachineConfig2 : MachineConfigProvider
{
protected override void WriteSections(XmlWriter writer)
{
writer.WriteStartElement("section");
writer.WriteAttributeString("name", "my2");
writer.WriteAttributeString("type", typeof(MySection2).AssemblyQualifiedName);
writer.WriteAttributeString("allowLocation", "true");
writer.WriteAttributeString("allowDefinition", "Everywhere");
writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser");
writer.WriteAttributeString("restartOnExternalChanges", "true");
writer.WriteAttributeString("requirePermission", "true");
writer.WriteEndElement();
}
internal static void WriteConfigSections(XmlWriter writer)
{
var provider = new DefaultMachineConfig2();
writer.WriteStartElement("configSections");
provider.WriteSections(writer);
writer.WriteEndElement();
}
protected override void WriteValues(XmlWriter writer)
{
}
}
abstract class ParentProvider : ConfigProvider
{
protected override void WriteXml(XmlWriter writer)
{
DefaultMachineConfig.WriteConfigSections(writer);
writer.WriteStartElement("my");
writer.WriteStartElement("test");
writer.WriteAttributeString("Hello", "29");
writer.WriteEndElement();
writer.WriteEndElement();
}
}
class RoamingAndExe : ParentProvider
{
public override UserLevel Level
{
get { return UserLevel.RoamingAndExe; }
}
}
private delegate void TestFunction(SysConfig config, TestLabel label);
private delegate void XmlCheckFunction(XPathNavigator nav, TestLabel label);
private static void Run(string name, TestFunction func)
{
var label = new TestLabel(name);
TestUtil.RunWithTempFile(filename =>
{
var fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = filename;
var config = ConfigurationManager.OpenMappedExeConfiguration(
fileMap, ConfigurationUserLevel.None);
func(config, label);
});
}
private static void Run<TConfig>(string name, TestFunction func)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(new TestLabel(name), func, null);
}
private static void Run<TConfig>(TestLabel label, TestFunction func)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(label, func, null);
}
private static void Run<TConfig>(
string name, TestFunction func, XmlCheckFunction check)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(new TestLabel(name), func, check);
}
private static void Run<TConfig>(
TestLabel label, TestFunction func, XmlCheckFunction check)
where TConfig : ConfigProvider, new()
{
TestUtil.RunWithTempFiles((parent, filename) =>
{
var provider = new TConfig();
provider.Create(parent);
Assert.False(File.Exists(filename));
var config = provider.OpenConfig(parent, filename);
Assert.False(File.Exists(filename));
try
{
label.EnterScope("config");
func(config, label);
}
finally
{
label.LeaveScope();
}
if (check == null)
return;
var xml = new XmlDocument();
xml.Load(filename);
var nav = xml.CreateNavigator().SelectSingleNode("/configuration");
try
{
label.EnterScope("xml");
check(nav, label);
}
finally
{
label.LeaveScope();
}
});
}
#endregion
#region Assertion Helpers
static void AssertNotModified(MySection my, TestLabel label)
{
label.EnterScope("modified");
Assert.NotNull(my);
Assert.False(my.IsModified, label.Get());
Assert.NotNull(my.List);
Assert.Equal(0, my.List.Collection.Count);
Assert.False(my.List.IsModified, label.Get());
label.LeaveScope();
}
static void AssertListElement(XPathNavigator nav, TestLabel label)
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
label.EnterScope("children");
Assert.True(my.HasChildren, label.Get());
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var test = iter2.Current;
label.EnterScope("test");
Assert.Equal("test", test.Name);
Assert.False(test.HasChildren, label.Get());
Assert.True(test.HasAttributes, label.Get());
var attr = test.GetAttribute("Hello", string.Empty);
Assert.Equal("29", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
}
#endregion
#region Tests
[Fact]
public void DefaultValues()
{
Run<DefaultMachineConfig>("DefaultValues", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
});
}
[Fact]
public void AddDefaultListElement()
{
Run<DefaultMachineConfig>("AddDefaultListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
});
}
[Fact]
public void AddDefaultListElement2()
{
Run<DefaultMachineConfig>("AddDefaultListElement2", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.False(my.HasChildren, label.Get());
label.LeaveScope();
});
}
[Fact]
public void AddDefaultListElement3()
{
Run<DefaultMachineConfig>("AddDefaultListElement3", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Full);
Assert.True(File.Exists(config.FilePath), label.Get());
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
label.EnterScope("children");
Assert.True(my.HasChildren, label.Get());
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(2, iter2.Count);
label.EnterScope("list");
var iter3 = my.Select("list/*");
Assert.Equal(1, iter3.Count);
Assert.True(iter3.MoveNext(), label.Get());
var collection = iter3.Current;
Assert.Equal("collection", collection.Name);
Assert.False(collection.HasChildren, label.Get());
Assert.True(collection.HasAttributes, label.Get());
var hello = collection.GetAttribute("Hello", string.Empty);
Assert.Equal("8", hello);
var world = collection.GetAttribute("World", string.Empty);
Assert.Equal("0", world);
label.LeaveScope();
label.EnterScope("test");
var iter4 = my.Select("test");
Assert.Equal(1, iter4.Count);
Assert.True(iter4.MoveNext(), label.Get());
var test = iter4.Current;
Assert.Equal("test", test.Name);
Assert.False(test.HasChildren, label.Get());
Assert.True(test.HasAttributes, label.Get());
var hello2 = test.GetAttribute("Hello", string.Empty);
Assert.Equal("8", hello2);
var world2 = test.GetAttribute("World", string.Empty);
Assert.Equal("0", world2);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void AddListElement()
{
Run<DefaultMachineConfig>("AddListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
AssertListElement(nav, label);
});
}
[Fact]
public void NotModifiedAfterSave()
{
Run<DefaultMachineConfig>("NotModifiedAfterSave", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
label.EnterScope("1st-save");
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Modified);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
label.EnterScope("modify");
element.Hello = 12;
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.True(element.IsModified, label.Get());
label.LeaveScope();
label.EnterScope("2nd-save");
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
Assert.False(my.IsModified, label.Get());
Assert.False(my.List.IsModified, label.Get());
Assert.False(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope(); // 2nd-save
});
}
[Fact]
public void AddSection()
{
Run("AddSection", (config, label) =>
{
Assert.Null(config.Sections["my"]);
var my = new MySection();
config.Sections.Add("my2", my);
config.Save(ConfigurationSaveMode.Full);
Assert.True(File.Exists(config.FilePath), label.Get());
});
}
[Fact]
public void AddElement()
{
Run<DefaultMachineConfig>("AddElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
var element = my.List.DefaultCollection.AddElement();
element.Hello = 12;
config.Save(ConfigurationSaveMode.Modified);
label.EnterScope("file");
Assert.True(File.Exists(config.FilePath), "#c2");
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var list = iter2.Current;
label.EnterScope("list");
Assert.Equal("list", list.Name);
Assert.False(list.HasChildren, label.Get());
Assert.True(list.HasAttributes, label.Get());
var attr = list.GetAttribute("Hello", string.Empty);
Assert.Equal("12", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void ModifyListElement()
{
Run<RoamingAndExe>("ModifyListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
});
}
[Fact]
public void ModifyListElement2()
{
Run<RoamingAndExe>("ModifyListElement2", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
AssertListElement(nav, label);
});
}
[Fact]
public void TestElementWithCollection()
{
Run<DefaultMachineConfig2>("TestElementWithCollection", (config, label) =>
{
label.EnterScope("section");
var my2 = config.Sections["my2"] as MySection2;
Assert.NotNull(my2);
Assert.NotNull(my2.Test);
Assert.NotNull(my2.Test.DefaultCollection);
Assert.Equal(0, my2.Test.DefaultCollection.Count);
label.LeaveScope();
my2.Test.DefaultCollection.AddElement();
my2.Element.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my2");
Assert.Equal("my2", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var element = iter2.Current;
label.EnterScope("element");
Assert.Equal("element", element.Name);
Assert.False(element.HasChildren, label.Get());
Assert.True(element.HasAttributes, label.Get());
var attr = element.GetAttribute("Hello", string.Empty);
Assert.Equal("29", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void TestElementWithCollection2()
{
Run<DefaultMachineConfig2>("TestElementWithCollection2", (config, label) =>
{
label.EnterScope("section");
var my2 = config.Sections["my2"] as MySection2;
Assert.NotNull(my2);
Assert.NotNull(my2.Test);
Assert.NotNull(my2.Test.DefaultCollection);
Assert.Equal(0, my2.Test.DefaultCollection.Count);
label.LeaveScope();
var element = my2.Test.DefaultCollection.AddElement();
var element2 = element.Test.DefaultCollection.AddElement();
element2.Hello = 1;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my2");
Assert.Equal("my2", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var collection = iter2.Current;
label.EnterScope("collection");
Assert.Equal("collection", collection.Name);
Assert.True(collection.HasChildren, label.Get());
Assert.False(collection.HasAttributes, label.Get());
label.EnterScope("children");
var iter3 = collection.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter3.Count);
Assert.True(iter3.MoveNext(), label.Get());
var element = iter3.Current;
label.EnterScope("element");
Assert.Equal("test", element.Name);
Assert.False(element.HasChildren, label.Get());
Assert.True(element.HasAttributes, label.Get());
var attr = element.GetAttribute("Hello", string.Empty);
Assert.Equal("1", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
#endregion
#region Configuration Classes
public class MyElement : ConfigurationElement
{
[ConfigurationProperty("Hello", DefaultValue = 8)]
public int Hello
{
get { return (int)base["Hello"]; }
set { base["Hello"] = value; }
}
[ConfigurationProperty("World", IsRequired = false)]
public int World
{
get { return (int)base["World"]; }
set { base["World"] = value; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyCollection<T> : ConfigurationElementCollection
where T : ConfigurationElement, new()
{
#region implemented abstract members of ConfigurationElementCollection
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((T)element).GetHashCode();
}
#endregion
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
public T AddElement()
{
var element = new T();
BaseAdd(element);
return element;
}
public void RemoveElement(T element)
{
BaseRemove(GetElementKey(element));
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyCollectionElement<T> : ConfigurationElement
where T : ConfigurationElement, new()
{
[ConfigurationProperty("",
Options = ConfigurationPropertyOptions.IsDefaultCollection,
IsDefaultCollection = true)]
public MyCollection<T> DefaultCollection
{
get { return (MyCollection<T>)this[string.Empty]; }
set { this[string.Empty] = value; }
}
[ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)]
public MyCollection<T> Collection
{
get { return (MyCollection<T>)this["collection"]; }
set { this["collection"] = value; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MySection : ConfigurationSection
{
[ConfigurationProperty("list", Options = ConfigurationPropertyOptions.None)]
public MyCollectionElement<MyElement> List
{
get { return (MyCollectionElement<MyElement>)this["list"]; }
}
[ConfigurationProperty("test", Options = ConfigurationPropertyOptions.None)]
public MyElement Test
{
get { return (MyElement)this["test"]; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyElementWithCollection : ConfigurationElement
{
[ConfigurationProperty("test")]
public MyCollectionElement<MyElement> Test
{
get { return (MyCollectionElement<MyElement>)this["test"]; }
}
}
public class MySection2 : ConfigurationSection
{
[ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)]
public MyCollectionElement<MyElementWithCollection> Test
{
get { return (MyCollectionElement<MyElementWithCollection>)this["collection"]; }
}
[ConfigurationProperty("element", Options = ConfigurationPropertyOptions.None)]
public MyElement Element
{
get { return (MyElement)this["element"]; }
}
}
public class MySectionGroup : ConfigurationSectionGroup
{
public MySection2 My2
{
get { return (MySection2)Sections["my2"]; }
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Text.RegularExpressions;
public class LevelManager : MonoBehaviour {
private const float loadSceneDelay = 1f;
public bool hurryUp; // within last 100 secs?
public int marioSize; // 0..2
public int lives;
public int coins;
public int scores;
public float timeLeft;
private int timeLeftInt;
private bool isRespawning;
private bool isPoweringDown;
public bool isInvinciblePowerdown;
public bool isInvincibleStarman;
private float MarioInvinciblePowerdownDuration = 2;
private float MarioInvincibleStarmanDuration = 12;
private float transformDuration = 1;
private GameStateManager t_GameStateManager;
private Mario mario;
private Animator mario_Animator;
private Rigidbody2D mario_Rigidbody2D;
public Text scoreText;
public Text coinText;
public Text timeText;
public GameObject FloatingTextEffect;
private const float floatingTextOffsetY = 2f;
public AudioSource musicSource;
public AudioSource soundSource;
public AudioSource pauseSoundSource;
public AudioClip levelMusic;
public AudioClip levelMusicHurry;
public AudioClip starmanMusic;
public AudioClip starmanMusicHurry;
public AudioClip levelCompleteMusic;
public AudioClip castleCompleteMusic;
public AudioClip oneUpSound;
public AudioClip bowserFallSound;
public AudioClip bowserFireSound;
public AudioClip breakBlockSound;
public AudioClip bumpSound;
public AudioClip coinSound;
public AudioClip deadSound;
public AudioClip fireballSound;
public AudioClip flagpoleSound;
public AudioClip jumpSmallSound;
public AudioClip jumpSuperSound;
public AudioClip kickSound;
public AudioClip pipePowerdownSound;
public AudioClip powerupSound;
public AudioClip powerupAppearSound;
public AudioClip stompSound;
public AudioClip warningSound;
public int coinBonus = 200;
public int powerupBonus = 1000;
public int starmanBonus = 1000;
public int oneupBonus = 0;
public int breakBlockBonus = 50;
public Vector2 stompBounceVelocity = new Vector2 (0, 15);
public bool gamePaused;
public bool timerPaused;
public bool musicPaused;
void Awake() {
Time.timeScale = 1;
}
// Use this for initialization
void Start () {
t_GameStateManager = FindObjectOfType<GameStateManager>();
RetrieveGameState ();
mario = FindObjectOfType<Mario> ();
mario_Animator = mario.gameObject.GetComponent<Animator> ();
mario_Rigidbody2D = mario.gameObject.GetComponent<Rigidbody2D> ();
mario.UpdateSize ();
// Sound volume
musicSource.volume = PlayerPrefs.GetFloat("musicVolume");
soundSource.volume = PlayerPrefs.GetFloat("soundVolume");
pauseSoundSource.volume = PlayerPrefs.GetFloat("soundVolume");
// HUD
SetHudCoin ();
SetHudScore ();
SetHudTime ();
if (hurryUp) {
ChangeMusic (levelMusicHurry);
} else {
ChangeMusic (levelMusic);
}
Debug.Log (this.name + " Start: current scene is " + SceneManager.GetActiveScene ().name);
}
void RetrieveGameState() {
marioSize = t_GameStateManager.marioSize;
lives = t_GameStateManager.lives;
coins = t_GameStateManager.coins;
scores = t_GameStateManager.scores;
timeLeft = t_GameStateManager.timeLeft;
hurryUp = t_GameStateManager.hurryUp;
}
/****************** Timer */
void Update() {
if (!timerPaused) {
timeLeft -= Time.deltaTime / .4f; // 1 game sec ~ 0.4 real time sec
SetHudTime ();
}
if (timeLeftInt < 100 && !hurryUp) {
hurryUp = true;
PauseMusicPlaySound (warningSound, true);
if (isInvincibleStarman) {
ChangeMusic (starmanMusicHurry, warningSound.length);
} else {
ChangeMusic (levelMusicHurry, warningSound.length);
}
}
if (timeLeftInt <= 0) {
MarioRespawn (true);
}
if (Input.GetButtonDown ("Pause")) {
if (!gamePaused) {
StartCoroutine (PauseGameCo ());
} else {
StartCoroutine (UnpauseGameCo ());
}
}
}
/****************** Game pause */
List<Animator> unscaledAnimators = new List<Animator> ();
float pauseGamePrevTimeScale;
bool pausePrevMusicPaused;
IEnumerator PauseGameCo() {
gamePaused = true;
pauseGamePrevTimeScale = Time.timeScale;
Time.timeScale = 0;
pausePrevMusicPaused = musicPaused;
musicSource.Pause ();
musicPaused = true;
soundSource.Pause ();
// Set any active animators that use unscaled time mode to normal
unscaledAnimators.Clear();
foreach (Animator animator in FindObjectsOfType<Animator>()) {
if (animator.updateMode == AnimatorUpdateMode.UnscaledTime) {
unscaledAnimators.Add (animator);
animator.updateMode = AnimatorUpdateMode.Normal;
}
}
pauseSoundSource.Play();
yield return new WaitForSecondsRealtime (pauseSoundSource.clip.length);
Debug.Log (this.name + " PauseGameCo stops: records prevTimeScale=" + pauseGamePrevTimeScale.ToString());
}
IEnumerator UnpauseGameCo() {
pauseSoundSource.Play();
yield return new WaitForSecondsRealtime (pauseSoundSource.clip.length);
musicPaused = pausePrevMusicPaused;
if (!musicPaused) {
musicSource.UnPause ();
}
soundSource.UnPause ();
// Reset animators
foreach (Animator animator in unscaledAnimators) {
animator.updateMode = AnimatorUpdateMode.UnscaledTime;
}
unscaledAnimators.Clear ();
Time.timeScale = pauseGamePrevTimeScale;
gamePaused = false;
Debug.Log (this.name + " UnpauseGameCo stops: resume prevTimeScale=" + pauseGamePrevTimeScale.ToString());
}
/****************** Invincibility */
public bool isInvincible() {
return isInvinciblePowerdown || isInvincibleStarman;
}
public void MarioInvincibleStarman() {
StartCoroutine (MarioInvincibleStarmanCo ());
AddScore (starmanBonus, mario.transform.position);
}
IEnumerator MarioInvincibleStarmanCo() {
isInvincibleStarman = true;
mario_Animator.SetBool ("isInvincibleStarman", true);
mario.gameObject.layer = LayerMask.NameToLayer ("Mario After Starman");
if (hurryUp) {
ChangeMusic (starmanMusicHurry);
} else {
ChangeMusic (starmanMusic);
}
yield return new WaitForSeconds (MarioInvincibleStarmanDuration);
isInvincibleStarman = false;
mario_Animator.SetBool ("isInvincibleStarman", false);
mario.gameObject.layer = LayerMask.NameToLayer ("Mario");
if (hurryUp) {
ChangeMusic (levelMusicHurry);
} else {
ChangeMusic (levelMusic);
}
}
void MarioInvinciblePowerdown() {
StartCoroutine (MarioInvinciblePowerdownCo ());
}
IEnumerator MarioInvinciblePowerdownCo() {
isInvinciblePowerdown = true;
mario_Animator.SetBool ("isInvinciblePowerdown", true);
mario.gameObject.layer = LayerMask.NameToLayer ("Mario After Powerdown");
yield return new WaitForSeconds (MarioInvinciblePowerdownDuration);
isInvinciblePowerdown = false;
mario_Animator.SetBool ("isInvinciblePowerdown", false);
mario.gameObject.layer = LayerMask.NameToLayer ("Mario");
}
/****************** Powerup / Powerdown / Die */
public void MarioPowerUp() {
soundSource.PlayOneShot (powerupSound); // should play sound regardless of size
if (marioSize < 2) {
StartCoroutine (MarioPowerUpCo ());
}
AddScore (powerupBonus, mario.transform.position);
}
IEnumerator MarioPowerUpCo() {
mario_Animator.SetBool ("isPoweringUp", true);
Time.timeScale = 0f;
mario_Animator.updateMode = AnimatorUpdateMode.UnscaledTime;
yield return new WaitForSecondsRealtime (transformDuration);
yield return new WaitWhile(() => gamePaused);
Time.timeScale = 1;
mario_Animator.updateMode = AnimatorUpdateMode.Normal;
marioSize++;
mario.UpdateSize ();
mario_Animator.SetBool ("isPoweringUp", false);
}
public void MarioPowerDown() {
if (!isPoweringDown) {
Debug.Log (this.name + " MarioPowerDown: called and executed");
isPoweringDown = true;
if (marioSize > 0) {
StartCoroutine (MarioPowerDownCo ());
soundSource.PlayOneShot (pipePowerdownSound);
} else {
MarioRespawn ();
}
Debug.Log (this.name + " MarioPowerDown: done executing");
} else {
Debug.Log (this.name + " MarioPowerDown: called but not executed");
}
}
IEnumerator MarioPowerDownCo() {
mario_Animator.SetBool ("isPoweringDown", true);
Time.timeScale = 0f;
mario_Animator.updateMode = AnimatorUpdateMode.UnscaledTime;
yield return new WaitForSecondsRealtime (transformDuration);
yield return new WaitWhile(() => gamePaused);
Time.timeScale = 1;
mario_Animator.updateMode = AnimatorUpdateMode.Normal;
MarioInvinciblePowerdown ();
marioSize = 0;
mario.UpdateSize ();
mario_Animator.SetBool ("isPoweringDown", false);
isPoweringDown = false;
}
public void MarioRespawn(bool timeup = false) {
if (!isRespawning) {
isRespawning = true;
marioSize = 0;
lives--;
soundSource.Stop ();
musicSource.Stop ();
musicPaused = true;
soundSource.PlayOneShot (deadSound);
Time.timeScale = 0f;
mario.FreezeAndDie ();
if (timeup) {
Debug.Log(this.name + " MarioRespawn: called due to timeup");
}
Debug.Log (this.name + " MarioRespawn: lives left=" + lives.ToString ());
if (lives > 0) {
ReloadCurrentLevel (deadSound.length, timeup);
} else {
LoadGameOver (deadSound.length, timeup);
Debug.Log(this.name + " MarioRespawn: all dead");
}
}
}
/****************** Kill enemy */
public void MarioStompEnemy(Enemy enemy) {
mario_Rigidbody2D.velocity = new Vector2 (mario_Rigidbody2D.velocity.x + stompBounceVelocity.x, stompBounceVelocity.y);
enemy.StompedByMario ();
soundSource.PlayOneShot (stompSound);
AddScore (enemy.stompBonus, enemy.gameObject.transform.position);
Debug.Log (this.name + " MarioStompEnemy called on " + enemy.gameObject.name);
}
public void MarioStarmanTouchEnemy(Enemy enemy) {
enemy.TouchedByStarmanMario ();
soundSource.PlayOneShot (kickSound);
AddScore (enemy.starmanBonus, enemy.gameObject.transform.position);
Debug.Log (this.name + " MarioStarmanTouchEnemy called on " + enemy.gameObject.name);
}
public void RollingShellTouchEnemy(Enemy enemy) {
enemy.TouchedByRollingShell ();
soundSource.PlayOneShot (kickSound);
AddScore (enemy.rollingShellBonus, enemy.gameObject.transform.position);
Debug.Log (this.name + " RollingShellTouchEnemy called on " + enemy.gameObject.name);
}
public void BlockHitEnemy(Enemy enemy) {
enemy.HitBelowByBlock ();
AddScore (enemy.hitByBlockBonus, enemy.gameObject.transform.position);
Debug.Log (this.name + " BlockHitEnemy called on " + enemy.gameObject.name);
}
public void FireballTouchEnemy(Enemy enemy) {
enemy.HitByMarioFireball ();
soundSource.PlayOneShot (kickSound);
AddScore (enemy.fireballBonus, enemy.gameObject.transform.position);
Debug.Log (this.name + " FireballTouchEnemy called on " + enemy.gameObject.name);
}
/****************** Scene loading */
void LoadSceneDelay(string sceneName, float delay = loadSceneDelay) {
timerPaused = true;
StartCoroutine (LoadSceneDelayCo (sceneName, delay));
}
IEnumerator LoadSceneDelayCo(string sceneName, float delay) {
Debug.Log (this.name + " LoadSceneDelayCo: starts loading " + sceneName);
float waited = 0;
while (waited < delay) {
if (!gamePaused) { // should not count delay while game paused
waited += Time.unscaledDeltaTime;
}
yield return null;
}
yield return new WaitWhile (() => gamePaused);
Debug.Log (this.name + " LoadSceneDelayCo: done loading " + sceneName);
isRespawning = false;
isPoweringDown = false;
SceneManager.LoadScene (sceneName);
}
public void LoadNewLevel(string sceneName, float delay = loadSceneDelay) {
t_GameStateManager.SaveGameState ();
t_GameStateManager.ConfigNewLevel ();
t_GameStateManager.sceneToLoad = sceneName;
LoadSceneDelay ("Level Start Screen", delay);
}
public void LoadSceneCurrentLevel(string sceneName, float delay = loadSceneDelay) {
t_GameStateManager.SaveGameState ();
t_GameStateManager.ResetSpawnPosition (); // TODO
LoadSceneDelay (sceneName, delay);
}
public void LoadSceneCurrentLevelSetSpawnPipe(string sceneName, int spawnPipeIdx, float delay = loadSceneDelay) {
t_GameStateManager.SaveGameState ();
t_GameStateManager.SetSpawnPipe (spawnPipeIdx);
LoadSceneDelay (sceneName, delay);
Debug.Log (this.name + " LoadSceneCurrentLevelSetSpawnPipe: supposed to load " + sceneName
+ ", spawnPipeIdx=" + spawnPipeIdx.ToString () + "; actual GSM spawnFromPoint="
+ t_GameStateManager.spawnFromPoint.ToString () + ", spawnPipeIdx="
+ t_GameStateManager.spawnPipeIdx.ToString ());
}
public void ReloadCurrentLevel(float delay = loadSceneDelay, bool timeup = false) {
t_GameStateManager.SaveGameState ();
t_GameStateManager.ConfigReplayedLevel ();
t_GameStateManager.sceneToLoad = SceneManager.GetActiveScene ().name;
if (timeup) {
LoadSceneDelay ("Time Up Screen", delay);
} else {
LoadSceneDelay ("Level Start Screen", delay);
}
}
public void LoadGameOver(float delay = loadSceneDelay, bool timeup = false) {
int currentHighScore = PlayerPrefs.GetInt ("highScore", 0);
if (scores > currentHighScore) {
PlayerPrefs.SetInt ("highScore", scores);
}
t_GameStateManager.timeup = timeup;
LoadSceneDelay ("Game Over Screen", delay);
}
/****************** HUD and sound effects */
public void SetHudCoin() {
coinText.text = "x" + coins.ToString ("D2");
}
public void SetHudScore() {
scoreText.text = scores.ToString ("D6");
}
public void SetHudTime() {
timeLeftInt = Mathf.RoundToInt (timeLeft);
timeText.text = timeLeftInt.ToString ("D3");
}
public void CreateFloatingText(string text, Vector3 spawnPos) {
GameObject textEffect = Instantiate (FloatingTextEffect, spawnPos, Quaternion.identity);
textEffect.GetComponentInChildren<TextMesh> ().text = text.ToUpper ();
}
public void ChangeMusic(AudioClip clip, float delay = 0) {
StartCoroutine (ChangeMusicCo (clip, delay));
}
IEnumerator ChangeMusicCo(AudioClip clip, float delay) {
Debug.Log (this.name + " ChangeMusicCo: starts changing music to " + clip.name);
musicSource.clip = clip;
yield return new WaitWhile (() => gamePaused);
yield return new WaitForSecondsRealtime (delay);
yield return new WaitWhile (() => gamePaused || musicPaused);
if (!isRespawning) {
musicSource.Play ();
}
Debug.Log (this.name + " ChangeMusicCo: done changing music to " + clip.name);
}
public void PauseMusicPlaySound(AudioClip clip, bool resumeMusic) {
StartCoroutine (PauseMusicPlaySoundCo (clip, resumeMusic));
}
IEnumerator PauseMusicPlaySoundCo(AudioClip clip, bool resumeMusic) {
string musicClipName = "";
if (musicSource.clip) {
musicClipName = musicSource.clip.name;
}
Debug.Log (this.name + " PausemusicPlaySoundCo: starts pausing music " + musicClipName + " to play sound " + clip.name);
musicPaused = true;
musicSource.Pause ();
soundSource.PlayOneShot (clip);
yield return new WaitForSeconds (clip.length);
if (resumeMusic) {
musicSource.UnPause ();
musicClipName = "";
if (musicSource.clip) {
musicClipName = musicSource.clip.name;
}
Debug.Log (this.name + " PausemusicPlaySoundCo: resume playing music " + musicClipName);
}
musicPaused = false;
Debug.Log (this.name + " PausemusicPlaySoundCo: done pausing music to play sound " + clip.name);
}
/****************** Game state */
public void AddLife() {
lives++;
soundSource.PlayOneShot (oneUpSound);
}
public void AddLife(Vector3 spawnPos) {
lives++;
soundSource.PlayOneShot (oneUpSound);
CreateFloatingText ("1UP", spawnPos);
}
public void AddCoin() {
coins++;
soundSource.PlayOneShot (coinSound);
if (coins == 100) {
AddLife ();
coins = 0;
}
SetHudCoin ();
AddScore (coinBonus);
}
public void AddCoin(Vector3 spawnPos) {
coins++;
soundSource.PlayOneShot (coinSound);
if (coins == 100) {
AddLife ();
coins = 0;
}
SetHudCoin ();
AddScore (coinBonus, spawnPos);
}
public void AddScore(int bonus) {
scores += bonus;
SetHudScore ();
}
public void AddScore(int bonus, Vector3 spawnPos) {
scores += bonus;
SetHudScore ();
if (bonus > 0) {
CreateFloatingText (bonus.ToString (), spawnPos);
}
}
/****************** Misc */
public Vector3 FindSpawnPosition() {
Vector3 spawnPosition;
GameStateManager t_GameStateManager = FindObjectOfType<GameStateManager>();
Debug.Log (this.name + " FindSpawnPosition: GSM spawnFromPoint=" + t_GameStateManager.spawnFromPoint.ToString()
+ " spawnPipeIdx= " + t_GameStateManager.spawnPipeIdx.ToString()
+ " spawnPointIdx=" + t_GameStateManager.spawnPointIdx.ToString());
if (t_GameStateManager.spawnFromPoint) {
spawnPosition = GameObject.Find ("Spawn Points").transform.GetChild (t_GameStateManager.spawnPointIdx).transform.position;
} else {
spawnPosition = GameObject.Find ("Spawn Pipes").transform.GetChild (t_GameStateManager.spawnPipeIdx).transform.FindChild("Spawn Pos").transform.position;
}
return spawnPosition;
}
public string GetWorldName(string sceneName) {
string[] sceneNameParts = Regex.Split (sceneName, " - ");
return sceneNameParts[0];
}
public bool isSceneInCurrentWorld(string sceneName) {
return GetWorldName (sceneName) == GetWorldName (SceneManager.GetActiveScene ().name);
}
public void MarioCompleteCastle() {
timerPaused = true;
ChangeMusic (castleCompleteMusic);
musicSource.loop = false;
mario.AutomaticWalk(mario.castleWalkSpeedX);
}
public void MarioCompleteLevel() {
timerPaused = true;
ChangeMusic (levelCompleteMusic);
musicSource.loop = false;
}
public void MarioReachFlagPole() {
timerPaused = true;
PauseMusicPlaySound (flagpoleSound, false);
mario.ClimbFlagPole ();
}
}
|
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.Scripting
{
public class TextSentToScriptingConsole
{
public List<string> lines = new List<string>();
public TextSentToScriptingConsole()
{
}
public void AddText(string text)
{
GetLines(text);
}
public void AddLines(IList<string> linesToAdd)
{
lines.AddRange(linesToAdd);
}
void GetLines(string text)
{
string[] linesToAdd = ConvertTextToLines(text);
lines.AddRange(linesToAdd);
}
string[] ConvertTextToLines(string text)
{
text = text.Replace("\r\n", "\n");
return text.Split('\n');
}
public bool HasLine {
get { return lines.Count > 0; }
}
public bool HasAtLeastOneLine {
get { return lines.Count > 1; }
}
/// <summary>
/// Returns line with '\r\n' if not the last line of text.
/// </summary>
public string RemoveFirstLine()
{
string line = GetFirstLine();
if (line != null) {
lines.RemoveAt(0);
}
return line;
}
public string GetFirstLine()
{
if (HasLine) {
if (lines.Count > 1) {
string firstLine = lines[0] + "\r\n";
return firstLine;
}
return lines[0];
}
return null;
}
}
}
|
/*
Copyright ©2020-2021 WellEngineered.us, all rights reserved.
Distributed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
using System;
namespace WellEngineered.TextMetal.Model.Database
{
public static class SchemaInfoConstants
{
#region Fields/Constants
public const string COLUMN_IS_ANONYMOUS_RECORD_KEY = "ColumnIsAnonymous";
public const string COLUMN_NAME_RECORD_KEY = "ColumnName";
public const string COLUMN_ORDINAL_RECORD_KEY = "ColumnOrdinal";
public const string DEFAULT_DATABASE_NAME = "DefaultDatabaseName";
public const string INSTANCE_NAME = "InstanceName";
public const string MACHINE_NAME = "MachineName";
public const string PARAMETER_NAME_RETURN_VALUE = "ReturnValue";
public const string SERVER_EDITION = "ServerEdition";
public const string SERVER_LEVEL = "ServerLevel";
public const string SERVER_NAME = "ServerName";
public const string SERVER_VERSION = "ServerVersion";
#endregion
}
} |
using System.Threading.Tasks;
using AutoMapper;
using HobbyPortal.Infrastructure.Services;
using HobbyPortal.WebApp.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace HobbyPortal.WebApp.Controllers
{
[Produces("application/json")]
[Route("api/account")]
[Authorize]
public class AccountController : Controller
{
private readonly AccountService accountService;
public AccountController(AccountService accountService)
{
this.accountService = accountService;
}
[Route("me")]
[HttpGet]
public async Task<MyAccountViewModel> GetMyAccountInfo()
{
return Mapper.Map<MyAccountViewModel>(await accountService.GetUserByName(User.Identity.Name));
}
}
} |
/* INFINITY CODE 2013-2017 */
/* http://www.infinity-code.com */
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// The base class of queries to Google API.
/// </summary>
public abstract class OnlineMapsGoogleAPIQuery: OnlineMapsTextWebService
{
/// <summary>
/// Event that occurs when the current request instance is disposed.
/// </summary>
public new Action<OnlineMapsGoogleAPIQuery> OnDispose;
/// <summary>
/// Event that occurs after OnComplete, when the response from Google API processed.
/// </summary>
public new Action<OnlineMapsGoogleAPIQuery> OnFinish;
/// <summary>
/// Converts Polyline to point list.
/// </summary>
/// <param name="encodedPoints">
/// The encoded polyline.
/// </param>
/// <returns>
/// A List of Vector2 points;
/// </returns>
[Obsolete("OnlineMapsGoogleAPIQuery.DecodePolylinePoints is obsolete. Use OnlineMapsUtils.DecodePolylinePoints.")]
public static List<Vector2> DecodePolylinePoints(string encodedPoints)
{
return OnlineMapsUtils.DecodePolylinePoints(encodedPoints);
}
/// <summary>
/// Converts XMLNode coordinates from Google Maps into Vector2.
/// </summary>
/// <param name="node">XMLNode coordinates from Google Maps.</param>
/// <returns>Coordinates as Vector2.</returns>
[Obsolete("OnlineMapsGoogleAPIQuery.GetVector2FromNode is obsolete. Use OnlineMapsXML.GetVector2FromNode.")]
public static Vector2 GetVector2FromNode(OnlineMapsXML node)
{
return OnlineMapsXML.GetVector2FromNode(node);
}
} |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace MichaelBrandonMorris.DirectoryPermissionTool
{
/// <summary>
/// Class MainWindow.
/// </summary>
/// <seealso cref="Window" />
/// <seealso cref="System.Windows.Markup.IComponentConnector" />
/// TODO Edit XML Comment Template for MainWindow
public partial class MainWindow : Window
{
/// <summary>
/// Initializes a new instance of the
/// <see cref="MainWindow" /> class.
/// </summary>
/// TODO Edit XML Comment Template for #ctor
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// Handles the OnMouseLeftButtonDown event of the
/// UIElement control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">
/// The <see cref="MouseButtonEventArgs" />
/// instance containing the event data.
/// </param>
/// TODO Edit XML Comment Template for UIElement_OnMouseLeftButtonDown
private void UIElement_OnMouseLeftButtonDown(
object sender,
MouseButtonEventArgs e)
{
if (e.ClickCount < 2)
{
return;
}
var messageBox = sender as Border;
var message = messageBox?.Child as TextBlock;
if (message == null)
{
return;
}
messageBox.Visibility = Visibility.Hidden;
message.Text = string.Empty;
Panel.SetZIndex(messageBox, -1);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Vehicles
{
public class Car : Vehicle
{
private const double INCREASEBYSUMMER = 0.9;
public Car(double fuelQuantity, double fuelConsuption, double tankCapacity)
: base(fuelQuantity, fuelConsuption, tankCapacity)
{
}
public override double FuelConsuption => base.FuelConsuption + INCREASEBYSUMMER;
public override void Refuel(double amount)
{
base.Refuel(amount);
}
public override bool CanDrive(double distance)
{
return base.CanDrive(distance);
}
}
}
|
using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace FeatureNinjas.LogPack.NotificationServices
{
public class EmailNotificationService : INotificationService
{
private readonly string _to;
private readonly string _from;
private readonly string _server;
private readonly string _username;
private readonly string _password;
public EmailNotificationService(string to, string from, string server, string username, string password)
{
_from = from;
_to = to;
_server = server;
_username = username;
_password = password;
}
public Task Send(string logPackName, string meta)
{
var client = new SmtpClient(_server);
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(_username, _password);
var body = $"New LogPack uploaded. Check!: {logPackName}";
body += "\n\n";
body += meta;
var message = new MailMessage();
message.From = new MailAddress(_from);
message.To.Add(_to);
message.IsBodyHtml = false;
message.Body = body;
message.Subject = $"New LogPack uploaded. Check!: {logPackName}";
return client.SendMailAsync(message);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Toolbox.Tools;
namespace DashboardMgmt.Application
{
public class DatabaseOption
{
public string ConnectionString { get; set; } = null!;
}
public static class DatabaseOptionExtensions
{
public static void Verify(this DatabaseOption subject)
{
subject.VerifyNotNull(nameof(subject));
subject.ConnectionString.VerifyNotEmpty(nameof(subject.ConnectionString));
}
}
}
|
namespace Tangle.Net.Mam.Entity
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Tangle.Net.Entity;
using Tangle.Net.Mam.Services;
using Tangle.Net.Repository;
/// <summary>
/// The mam channel subscription.
/// </summary>
public class MamChannelSubscription
{
/// <summary>
/// Initializes a new instance of the <see cref="MamChannelSubscription"/> class.
/// </summary>
/// <param name="repository">
/// The iota repository.
/// </param>
/// <param name="parser">
/// The parser.
/// </param>
/// <param name="mask">
/// The mask.
/// </param>
public MamChannelSubscription(IIotaRepository repository, IMamParser parser, IMask mask)
{
this.Repository = repository;
this.Parser = parser;
this.Mask = mask;
}
/// <summary>
/// Getsthe channel key.
/// </summary>
public TryteString Key { get; private set; }
/// <summary>
/// Gets the message root.
/// </summary>
public Hash MessageRoot { get; private set; }
/// <summary>
/// Gets the next root.
/// </summary>
public Hash NextRoot { get; private set; }
/// <summary>
/// Gets the mode.
/// </summary>
public Mode Mode { get; private set; }
/// <summary>
/// Gets the parser.
/// </summary>
private IMamParser Parser { get; }
/// <summary>
/// Gets the mask.
/// </summary>
private IMask Mask { get; }
/// <summary>
/// Gets the iota repository.
/// </summary>
private IIotaRepository Repository { get; }
/// <summary>
/// The fetch.
/// </summary>
/// <returns>
/// The <see cref="List"/>.
/// </returns>
public async Task<List<UnmaskedAuthenticatedMessage>> FetchAsync()
{
this.NextRoot = this.MessageRoot;
return await this.InternalFetch();
}
/// <summary>
/// The fetch next.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public async Task<List<UnmaskedAuthenticatedMessage>> FetchNext()
{
return await this.InternalFetch();
}
/// <summary>
/// The fetch single.
/// </summary>
/// <param name="root">
/// The root.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public async Task<UnmaskedAuthenticatedMessage> FetchSingle(Hash root)
{
var address = this.Mode == Mode.Public ? new Address(root.Value) : new Address(this.Mask.Hash(root).Value);
var transactionHashList = await this.Repository.FindTransactionsByAddressesAsync(new List<Address> { address });
if (!transactionHashList.Hashes.Any())
{
return null;
}
var bundles = await this.Repository.GetBundlesAsync(transactionHashList.Hashes, false);
foreach (var bundle in bundles)
{
try
{
return this.Parser.Unmask(bundle, root, this.Key);
}
catch (Exception exception)
{
if (exception is InvalidBundleException)
{
// TODO: Add invalid bundle handler
}
}
}
return null;
}
/// <summary>
/// The init.
/// </summary>
/// <param name="messageRoot">
/// The message root.
/// </param>
/// <param name="mode">
/// The mode.
/// </param>
/// <param name="channelKey">
/// The channel key.
/// </param>
/// <param name="nextRoot">
/// The next Root.
/// </param>
public void Init(Hash messageRoot, Mode mode, TryteString channelKey = null, Hash nextRoot = null)
{
this.MessageRoot = messageRoot;
this.Mode = mode;
this.Key = channelKey;
this.NextRoot = nextRoot;
}
/// <summary>
/// The to json.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
/// <summary>
/// The internal fetch.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
private async Task<List<UnmaskedAuthenticatedMessage>> InternalFetch()
{
var result = new List<UnmaskedAuthenticatedMessage>();
while (true)
{
var unmasked = await this.FetchSingle(this.NextRoot);
if (unmasked != null)
{
this.NextRoot = unmasked.NextRoot;
result.Add(unmasked);
}
else
{
break;
}
}
return result;
}
}
} |
using FluentAssertions;
using HousingSearchListener.V1.Infrastructure.Exceptions;
using System;
using Xunit;
namespace HousingSearchListener.Tests.V1.Infrastructure.Exceptions
{
public class AssetNotIndexedExceptionTests
{
[Fact]
public void AssetNotIndexedExceptionTest()
{
var id = Guid.NewGuid().ToString();
var ex = new AssetNotIndexedException(id);
ex.Id.Should().Be(id);
ex.Message.Should().Be($"Asset with id {id} is not indexed in elastic search");
}
}
}
|
using Data.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
namespace Data
{
public class Repository : IRepository
{
SuperHeroContext _Context;
public Repository(SuperHeroContext context)
{
_Context = context;
}
public IEnumerable<SuperHero> GetSuperHeroes()
{
return _Context.SuperHeroes.Include("SuperPowers").ToList();
}
public SuperHero GetSuperHeroById(int id)
{
if (id > 0)
{
var x= _Context.SuperHeroes.Where(s => s.Id == id).Include("SuperPowers").FirstOrDefault();
return x;
}
else
return null;
}
public void Add(SuperHero superHero)
{
if (superHero != null)
{
_Context.Add(superHero);
_Context.SaveChanges();
}
}
}
}
|
namespace ValueObjects
{
public enum TipoProduto
{
}
}
|
namespace Laraue.EfCoreTriggers.Tests
{
public static class CollectionNames
{
public const string MySql = "MySqlCollection";
public const string PostgreSql = "PostgreSqlCollection";
public const string SqlServer = "SqlServerCollection";
public const string Sqlite = "SqliteCollection";
}
} |
// Copyright (c) Bynder. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using Bynder.Sdk.Query.Decoder;
namespace Bynder.Sdk.Query.Asset
{
/// <summary>
/// Query used to get media information including media items
/// </summary>
public class MediaInformationQuery
{
/// <summary>
/// Id of the media from which we want to retrieve information
/// </summary>
public string MediaId { get; set; }
/// <summary>
/// This property has to be set to 1 so API returns media items
/// </summary>
[ApiField("versions")]
public int Versions { get; set; } = 1;
}
}
|
using Business.Communication;
using Business.Domain.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
namespace API.Controllers
{
[Route("api/v1/image")]
[ApiController]
public class ImageController : ControllerBase
{
#region Property
private readonly IImageService _imageService;
#endregion
#region Constructor
public ImageController(IImageService imageService)
{
this._imageService = imageService;
}
#endregion
#region Action
[HttpPut("{personId:int}")]
[Authorize(Roles = "editor, admin")]
[ProducesResponseType(typeof(BaseResponse<>), 200)]
[ProducesResponseType(typeof(BaseResponse<>), 400)]
public async Task<IActionResult> SaveImageAsync(int personId, [FromForm] IFormFile image)
{
var filePath = Path.GetTempFileName();
var stream = new FileStream(filePath, FileMode.Create);
await image.CopyToAsync(stream);
var result = await _imageService.SaveImageAsync(personId, stream);
stream.Dispose();
// Clean temp-file
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);
if (result.Success)
return Ok(result);
return BadRequest(result);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Git.Data
{
public class DataConstants
{
public const int UsernameMinLength = 5;
public const int UsernameMaxLength = 20;
public const int PasswordMinLength = 6;
public const int PasswordMaxLength = 20;
public const int RepoMinLength = 3;
public const int RepoMaxLength = 10;
public const string Private = "Private";
public const string Public = "Public";
public const int CommitMinLength = 5;
}
}
|
using UnityEngine;
using Photon.Pun;
public class OtherClientsObjects : MonoBehaviour
{
// Start is called before the first frame update
void Update()
{
if (PhotonNetwork.IsMasterClient)
gameObject.SetActive(false);
}
}
|
using System;
using System.Windows;
using FluiTec.CDoujin_Downloader.UserInterface.WpfCore.ViewModels;
namespace FluiTec.CDoujin_Downloader.UserInterface.WpfCore.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainView : Window
{
public MainView(MainViewModel viewModel)
{
DataContext = viewModel;
InitializeComponent();
}
private void Open_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void Open_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Save_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void Save_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Minimize_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void Minimize_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Quit_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void Quit_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void PasteClipboard_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void PasteClipboard_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void AddFromList_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void AddFromList_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ShowBookmarks_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void ShowBookmarks_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void SearchManga_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void SearchManga_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ClipboardMonitor_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void ClipboardMonitor_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void StartDownloads_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void StartDownloads_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void QueueDownloads_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void QueueDownloads_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void PauseDownloads_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void PauseDownloads_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void StopDownloads_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void StopDownloads_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void FilterDownloads_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void FilterDownloads_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void HistoryDownloads_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void HistoryDownloads_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Help_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
throw new NotImplementedException();
}
private void Help_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
}
}
|
namespace Innofactor.Xrm.Common.SDK
{
using Microsoft.Xrm.Sdk;
using System;
public class Message
{
#region Public Properties
public MessageFilter Filter
{
get;
set;
}
public string FriendlyName
{
get;
set;
}
public Guid Id
{
get;
set;
}
#endregion Public Properties
#region Public Methods
public static Message CreateFromStep(Entity entity)
{
if (entity == null)
{
return new Message();
}
var filter = new MessageFilter();
if (entity.Attributes.ContainsKey("message.sdkmessagefilterid"))
{
filter.Id = (Guid)((AliasedValue)entity.Attributes["message.sdkmessagefilterid"]).Value;
}
if (entity.Attributes.ContainsKey("filter.objecttypecode"))
{
filter.EntityName = (string)((AliasedValue)entity.Attributes["filter.objecttypecode"]).Value;
}
var message = new Message
{
Filter = filter
};
if (entity.Attributes.ContainsKey("message.sdkmessageid"))
{
message.Id = (Guid)((AliasedValue)entity.Attributes["message.sdkmessageid"]).Value;
}
if (entity.Attributes.ContainsKey("message.name"))
{
message.FriendlyName = (string)((AliasedValue)entity.Attributes["message.name"]).Value;
}
return message;
}
#endregion Public Methods
}
} |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Refit;
using SGDb.Common.Infrastructure;
using SGDb.Common.Infrastructure.Extensions;
using SGDb.Creators.Gateway.Infrastructure;
using SGDb.Creators.Gateway.Services.Creators;
using SGDb.Creators.Gateway.Services.GameDetailsViewService.Contracts;
using SGDb.Creators.Gateway.Services.Games.Contracts;
using SGDb.Creators.Gateway.Services.UserRoles.Contracts;
namespace SGDb.Creators.Gateway
{
public class Startup
{
public Startup(IConfiguration configuration) => this.Configuration = configuration;
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services
.AddHealth(this.Configuration)
.AddJwtAuthentication(this.Configuration)
.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory =
context => new BadRequestObjectResult((Result) context.ModelState);
});
var serviceEndpoints = this.Configuration.GetSection(nameof(ServiceEndpoints))
.Get<ServiceEndpoints>(config => config.BindNonPublicProperties = true);
services
.AddRefitClient<IGamesService>()
.WithConfiguration(serviceEndpoints.Creators);
services
.AddRefitClient<ICreatorsService>()
.WithConfiguration(serviceEndpoints.Creators);
services
.AddRefitClient<IGameDetailsViewService>()
.WithConfiguration(serviceEndpoints.Statistics);
services
.AddRefitClient<IUserRolesService>()
.WithConfiguration(serviceEndpoints.Identity);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
=> app.UseWebService(env);
}
} |
using System.Collections.Generic;
using KeySndr.Base;
using KeySndr.Common.Providers;
using KeySndr.Console.Providers;
namespace KeySndr.Console
{
class Program
{
static void Main(string[] args)
{
var providers = new List<IProvider>();
providers.Add(new LoggingProvider());
var keysndr = new KeySndrApp(providers);
keysndr.Run();
System.Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using DesignPatterns.Domain;
namespace DesignPatterns.Infra.Repository.EF
{
public class DesignContext : DbContext
{
public DesignContext(DbContextOptions<DesignContext> options) : base(options)
{}
public DbSet<Veiculo> Veiculos {get;set;}
}
} |
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RedWillow.Extensions;
using FluentAssertions;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace TypeExtensions.Tests
{
[TestClass]
public class StringExtensionTests
{
[TestMethod]
public void TitleCaseTest()
{
var str = "This has a miXEd set of w0rd5 in it. A-bit here.";
str.TitleCase().Should().Be("This Has A miXEd Set Of w0rd5 In It. A-bit Here.");
str.TitleCase(true).Should().Be("This Has A MiXEd Set Of W0rd5 In It. A-bit Here.");
}
[TestMethod]
public void IsMatchTest()
{
var str = "A super string";
str.IsMatch("s[uU]per [sS]tring").Should().BeTrue();
str.IsMatch("^a").Should().BeFalse();
}
[TestMethod]
public void IsMatchExtendedTest()
{
var str = "A super string";
str.IsMatch("s[U]per [S]tring", RegexOptions.IgnoreCase).Should().BeTrue();
str.IsMatch("^a", RegexOptions.IgnoreCase).Should().BeTrue();
}
[TestMethod]
public void ReReplaceTest()
{
var str = "Cost of $37.95 per week.";
str.ReReplace("[0-9]+(\\.[0-9]+)?", "0.00").Should().Be("Cost of $0.00 per week.");
str.ReReplace("\\$([0-9]+(\\.[0-9]+)?)", "{$1 NZD}").Should().Be("Cost of {37.95 NZD} per week.");
}
[TestMethod]
public void ReReplaceReadmeTest()
{
var str = "$39.95 per week";
str.IsMatch("^\\$?[0-9]+\\.[0-9]{2}").Should().BeTrue();
str.ReReplace("([0-9]+\\.[0-9]{2})", "0.00 (usually $1)").Should().Be("$0.00 (usually 39.95) per week");
}
[TestMethod]
public void ReReplaceExtendedTest()
{
var str = "Cost of $37.95 per week.";
str.ReReplace("[0-9]+(\\.[0-9]+)?", "0.00")
.ReReplace("PER (\\w+)", "every $1", RegexOptions.IgnoreCase).Should().Be("Cost of $0.00 every week.");
}
[TestMethod]
public void JoinTest()
{
var strList = new List<string>(new string[] { "one", "two", "three" });
strList.Join(",").Should().Be("one,two,three");
}
}
}
|
using System;
namespace Czar.Gateway.Configuration
{
/// <summary>
/// 金焰的世界
/// 2018-11-15
/// 是否存在的实体,缓存使用
/// </summary>
public class ClientRoleModel
{
/// <summary>
/// 缓存时间
/// </summary>
public DateTime CacheTime { get; set; }
/// <summary>
/// 是否有访问权限
/// </summary>
public bool Role { get; set; }
}
}
|
// /****************************** DynamicReports ******************************\
// Project: DynamicReports.Tests
// Filename: FakePluginConstants.cs
// Created: 02.05.2017
//
// <summary>
//
// </summary>
// \***************************************************************************/
namespace DynamicReports.Plugin.FakePlugin
{
public static class FakePluginConstants
{
public static string PluginName => "FakePlugin";
public static string TemplateExtension => ".fake";
public static string OutputExtension => ".fakeout";
}
} |
using System;
using SFA.DAS.DownloadService.Api.Types.Roatp;
using Swashbuckle.AspNetCore.Examples;
namespace SFA.DAS.DownloadService.Api.Roatp.SwaggerHelpers.Examples
{
public class ProviderExample : IExamplesProvider
{
public object GetExamples()
{
return new Provider
{
Ukprn = 12345678,
Name = "AtoA Trainers Ltd",
ProviderType = ProviderType.MainProvider,
ParentCompanyGuarantee = true,
NewOrganisationWithoutFinancialTrackRecord = false,
StartDate = new DateTime(DateTime.Now.Year - 1, 05, 17),
ApplicationDeterminedDate = null
};
}
}
}
|
using System;
namespace Ghostly.Uwp.Controls
{
public sealed class QueryClearedEventArgs : EventArgs
{
}
}
|
// Copyright (C) 2017 Dmitry Yakimenko (detunized@gmail.com).
// Licensed under the terms of the MIT license. See LICENCE for details.
namespace TrueKey
{
public class Account
{
public readonly int Id;
public readonly string Name;
public readonly string Username;
public readonly string Password;
public readonly string Url;
public readonly string Note;
public Account(int id, string name, string username, string password, string url, string note)
{
Id = id;
Name = name;
Username = username;
Password = password;
Url = url;
Note = note;
}
}
}
|
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;
using MeleeLib.DAT.Script;
namespace Smash_Forge.GUI.Melee
{
public partial class MeleeCMDEditor : Form
{
private DatFighterScript Script;
public MeleeCMDEditor(DatFighterScript Script)
{
InitializeComponent();
this.Script = Script;
foreach(SubAction a in Script.SubActions)
{
richTextBox1.Text += MeleeCMD.DecompileSubAction(a) + "\n";
}
}
// from https://www.c-sharpcorner.com/blogs/creating-line-numbers-for-richtextbox-in-c-sharp
/*public void AddLineNumbers()
{
// create & set Point pt to (0,0)
Point pt = new Point(0, 0);
// get First Index & First Line from richTextBox1
int First_Index = richTextBox1.GetCharIndexFromPosition(pt);
int First_Line = richTextBox1.GetLineFromCharIndex(First_Index);
// set X & Y coordinates of Point pt to ClientRectangle Width & Height respectively
pt.X = ClientRectangle.Width;
pt.Y = ClientRectangle.Height;
// get Last Index & Last Line from richTextBox1
int Last_Index = richTextBox1.GetCharIndexFromPosition(pt);
int Last_Line = richTextBox1.GetLineFromCharIndex(Last_Index);
// set Center alignment to LineNumberTextBox
LineNumberTextBox.SelectionAlignment = HorizontalAlignment.Center;
// set LineNumberTextBox text to null & width to getWidth() function value
LineNumberTextBox.Text = "";
LineNumberTextBox.Width = getWidth();
// now add each line number to LineNumberTextBox upto last line
for (int i = First_Line; i <= Last_Line + 2; i++)
{
LineNumberTextBox.Text += i + 1 + "\n";
}
}*/
public void HighlightLine(RichTextBox richTextBox, int index, Color color)
{
ClearHighlights(richTextBox);
var lines = richTextBox.Lines;
if (index < 0 || index >= lines.Length)
return;
var start = richTextBox.GetFirstCharIndexFromLine(index); // Get the 1st char index of the appended text
var length = lines[index].Length;
richTextBox.Select(start, length); // Select from there to the end
richTextBox.SelectionBackColor = color;
}
public void ClearHighlights(RichTextBox richTextBox)
{
richTextBox.SelectAll();
richTextBox.SelectionBackColor = richTextBox.BackColor;
}
private void buttonCompile_Click(object sender, EventArgs e)
{
string[] actionsrc = richTextBox1.Text.Split('\n');
ClearHighlights(richTextBox1);
List<SubAction> actions = new List<SubAction>();
int line = 0;
foreach(string a in actionsrc)
{
if (a.Equals("")) continue;
CompileError err;
SubAction comp = null;
try
{
comp = MeleeCMD.CompileCommand(a, out err);
}
catch (Exception)
{
err = CompileError.Syntax;
};
switch (err)
{
case CompileError.None:
actions.Add(comp);
break;
case CompileError.Syntax:
HighlightLine(richTextBox1, line, Color.PaleVioletRed);
MessageBox.Show("Syntax error on line " + line);
return;
case CompileError.ParameterCount:
HighlightLine(richTextBox1, line, Color.PaleVioletRed);
MessageBox.Show("Too many or too few parameters on line " + line);
return;
case CompileError.UnknownCommand:
HighlightLine(richTextBox1, line, Color.PaleVioletRed);
MessageBox.Show("Unknown Command on line " + line);
return;
}
line++;
}
MessageBox.Show("Compiled Successfully");
Script.SubActions = actions;
}
}
}
|
using MongoDB.Driver;
using Services.API.Data;
using Services.API.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Services.API.Repositories
{
public class ServiceRepository : IServiceRepository
{
private readonly IServiceContext _context;
public ServiceRepository(IServiceContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task<IEnumerable<Service>> GetServices()
{
return await _context
.Services
.Find(s => true)
.ToListAsync();
}
public async Task<Service> GetServiceById(string id)
{
return await _context
.Services
.Find(s => s.id == id)
.FirstOrDefaultAsync();
}
public async Task<IEnumerable<Service>> GetServiceByStatusId(string statusId)
{
FilterDefinition<Service> filter = Builders<Service>.Filter.Eq(s => s.StatusService, statusId);
return await _context
.Services
.Find(filter)
.ToListAsync();
}
public async Task CreateService(Service service)
{
await _context.Services.InsertOneAsync(service);
}
public async Task<bool> UpdateService(Service service)
{
var updateResult = await _context
.Services
.ReplaceOneAsync(filter: s => s.id == service.id, replacement: service);
return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0;
}
public async Task<bool> DeleteService(Service service)
{
var deleteResult = await _context
.Services
.ReplaceOneAsync(filter: s => s.id == service.id, replacement: service);
return deleteResult.IsAcknowledged && deleteResult.ModifiedCount > 0;
}
}
}
|
namespace BankCloud.Models.ViewModels.Home
{
public class HomeCategoriesViewModel
{
public string Type { get; set; }
public decimal InterestRate { get; set; }
public int Period { get; set; }
public decimal Amount { get; set; }
public decimal Commission { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using DG.Tweening;
public class PlayerMesh : MonoBehaviour
{
private Quaternion _initialRotation;
public void ResetRotation()
{
transform.localRotation = _initialRotation;
}
// Use this for initialization
void Start ()
{
_initialRotation = transform.localRotation;
}
private Tweener _danceTweener;
public void DanceTween()
{
if (_danceTweener == null)
{
ResetRotation();
var endVal = _initialRotation.eulerAngles.SetZ(30f);
_danceTweener = transform.DOLocalRotate(endVal, .5f)
.ChangeStartValue(_initialRotation.eulerAngles.SetZ(-30f))
.SetLoops(-1, LoopType.Yoyo)
.SetEase(Ease.Linear)
.Play();
}
}
public void StopDancing()
{
if (_danceTweener != null)
{
_danceTweener.Kill();
ResetRotation();
_danceTweener = null;
}
}
}
|
/*
* Free FFT and convolution (C++)
*
* Copyright (c) 2014 Project Nayuki
* https://www.nayuki.io/page/free-small-fft-in-multiple-languages
*
* (MIT License)
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
/*
Minor changes made to port this to C# and work the way I needed it to. -CH
*/
using System;
using UnityEngine;
namespace DerelictComputer.DroneMachine
{
public class FFT
{
public static void Forward(double[] real, double[] imag)
{
if (real.Length != imag.Length)
{
Debug.LogError("FFT: Input lengths do not match.");
return;
}
int n = real.Length;
int levels;
{
int temp = n;
levels = 0;
while (temp > 1)
{
levels++;
temp >>= 1;
}
if (1 << levels != n)
{
Debug.LogError("FFT: Length is not a power of 2");
return;
}
}
// Trignometric tables
double[] cosTable = new double[n/2];
double[] sinTable = new double[n/2];
for (int i = 0; i < n / 2; i++)
{
cosTable[i] = Math.Cos(2 * Math.PI * i / n);
sinTable[i] = Math.Sin(2 * Math.PI * i / n);
}
// Bit-reversed addressing permutation
for (int i = 0; i < n; i++)
{
int j = ReverseBits(i, levels);
if (j > i)
{
double temp = real[i];
real[i] = real[j];
real[j] = temp;
temp = imag[i];
imag[i] = imag[j];
imag[j] = temp;
}
}
// Cooley-Tukey decimation-in-time radix-2 FFT
for (int size = 2; size <= n; size *= 2)
{
int halfsize = size / 2;
int tablestep = n / size;
for (int i = 0; i < n; i += size)
{
for (int j = i, k = 0; j < i + halfsize; j++, k += tablestep)
{
double tpre = real[j + halfsize] * cosTable[k] + imag[j + halfsize] * sinTable[k];
double tpim = -real[j + halfsize] * sinTable[k] + imag[j + halfsize] * cosTable[k];
real[j + halfsize] = real[j] - tpre;
imag[j + halfsize] = imag[j] - tpim;
real[j] += tpre;
imag[j] += tpim;
}
}
if (size == n) // Prevent overflow in 'size *= 2'
break;
}
}
public static void Inverse(double[] real, double[] imag)
{
Forward(imag, real);
}
static int ReverseBits(int x, int n)
{
int result = 0;
int i;
for (i = 0; i < n; i++, x >>= 1)
result = (result << 1) | (x & 1);
return result;
}
}
} |
using Android.App;
using Xamarin.Forms.Xaml;
#if DEBUG
[assembly: Application(Debuggable = true)]
#else
[assembly: Application(Debuggable=false)]
#endif
[assembly: XamlCompilation(XamlCompilationOptions.Compile)] |
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Modulr.Controllers.Auth;
namespace Modulr.Models;
public class RegisterUser
{
public string CaptchaToken { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public async Task<bool> IsLikelyValid(Captcha capcha)
{
if (CaptchaToken == null || Name == null || Email == null || Password == null)
return false;
if (!await capcha.VerifyCaptcha(CaptchaToken))
return false;
if (!new EmailAddressAttribute().IsValid(Email))
return false;
if (Name.Length < 3 || Password.Length < 5)
return false;
return true;
}
} |
// Papercut
//
// Copyright © 2008 - 2012 Ken Robertson
// Copyright © 2013 - 2020 Jaben Cargman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Papercut.Helpers
{
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
public static class NotifyPropertyChangeReactiveExtensions
{
// Returns the values of property (an Expression) as they
// change, starting with the current value
public static IObservable<TValue> GetPropertyValues<TSource, TValue>(
this TSource source,
Expression<Func<TSource, TValue>> property,
IScheduler scheduler = null)
where TSource : INotifyPropertyChanged
{
var memberExpression = property.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException(
"property must directly access a property of the source");
}
string propertyName = memberExpression.Member.Name;
Func<TSource, TValue> accessor = property.Compile();
return source.GetPropertyChangedEvents(scheduler)
.Where(x => x.EventArgs.PropertyName == propertyName)
.Select(x => accessor(source))
.StartWith(accessor(source));
}
// This is a wrapper around FromEvent(PropertyChanged)
public static IObservable<EventPattern<PropertyChangedEventArgs>> GetPropertyChangedEvents(
this INotifyPropertyChanged source,
IScheduler scheduler = null)
{
return
Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
h => new PropertyChangedEventHandler(h),
h => source.PropertyChanged += h,
h => source.PropertyChanged -= h,
scheduler ?? Scheduler.Default);
}
public static IDisposable
Subscribe<TSource, TValue>(
this TSource source,
Expression<Func<TSource, TValue>> property,
Action<TValue> observer,
IScheduler scheduler = null)
where TSource : INotifyPropertyChanged
{
return source
.GetPropertyValues(property, scheduler)
.ObserveOnDispatcher()
.Subscribe(observer);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Manatee.Trello.Internal;
using Manatee.Trello.Internal.Caching;
using Manatee.Trello.Internal.DataAccess;
using Manatee.Trello.Internal.Eventing;
using Manatee.Trello.Internal.Synchronization;
using Manatee.Trello.Json;
namespace Manatee.Trello
{
/// <summary>
/// A read-only collection of cards.
/// </summary>
public class ReadOnlyCardCollection : ReadOnlyCollection<ICard>,
IReadOnlyCardCollection,
IHandle<EntityUpdatedEvent<IJsonCard>>,
IHandle<EntityDeletedEvent<IJsonCard>>
{
private readonly EntityRequestType _updateRequestType;
private readonly Dictionary<string, object> _requestParameters;
/// <summary>
/// Retrieves a card which matches the supplied key.
/// </summary>
/// <param name="key">The key to match.</param>
/// <returns>The matching card, or null if none found.</returns>
/// <remarks>
/// Matches on card ID and name. Comparison is case-sensitive.
/// </remarks>
public ICard this[string key] => GetByKey(key);
internal ReadOnlyCardCollection(Type type, Func<string> getOwnerId, TrelloAuthorization auth)
: base(getOwnerId, auth)
{
_updateRequestType = type == typeof(List)
? EntityRequestType.List_Read_Cards
: EntityRequestType.Board_Read_Cards;
_requestParameters = new Dictionary<string, object>();
EventAggregator.Subscribe(this);
}
internal ReadOnlyCardCollection(EntityRequestType requestType, Func<string> getOwnerId, TrelloAuthorization auth, Dictionary<string, object> requestParameters = null)
: base(getOwnerId, auth)
{
_updateRequestType = requestType;
_requestParameters = requestParameters ?? new Dictionary<string, object>();
EventAggregator.Subscribe(this);
}
/// <summary>
/// Adds a filter to the collection.
/// </summary>
/// <param name="filter">The filter value.</param>
public void Filter(CardFilter filter)
{
// NOTE: See issue 109. /1/lists/{listId}/cards does not support filter=visible
if (_updateRequestType == EntityRequestType.List_Read_Cards && filter == CardFilter.Visible)
{
AdditionalParameters.Remove("filter");
return;
}
AdditionalParameters["filter"] = filter.GetDescription();
}
/// <summary>
/// Adds a filter to the collection based on start and end date.
/// </summary>
/// <param name="start">The start date.</param>
/// <param name="end">The end date.</param>
public void Filter(DateTime? start, DateTime? end)
{
if (start != null)
AdditionalParameters["since"] = start.Value.ToUniversalTime().ToString("O");
if (end != null)
AdditionalParameters["before"] = end.Value.ToUniversalTime().ToString("O");
}
internal sealed override async Task PerformRefresh(bool force, CancellationToken ct)
{
IncorporateLimit();
_requestParameters["_id"] = OwnerId;
var allParameters = AdditionalParameters.Concat(CardContext.CurrentParameters)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var endpoint = EndpointFactory.Build(_updateRequestType, _requestParameters);
var newData = await JsonRepository.Execute<List<IJsonCard>>(Auth, endpoint, ct, allParameters);
var previousItems = new List<ICard>(Items);
Items.Clear();
EventAggregator.Unsubscribe(this);
Items.AddRange(newData.Select(jc =>
{
var card = jc.GetFromCache<Card, IJsonCard>(Auth);
card.Json = jc;
return card;
}));
EventAggregator.Subscribe(this);
var removedItems = previousItems.Except(Items, CacheableComparer.Get<ICard>()).OfType<Card>().ToList();
foreach (var item in removedItems)
{
item.Json.List = null;
}
}
private ICard GetByKey(string key)
{
return this.FirstOrDefault(c => key.In(c.Id, c.Name));
}
void IHandle<EntityUpdatedEvent<IJsonCard>>.Handle(EntityUpdatedEvent<IJsonCard> message)
{
ICard card;
switch (_updateRequestType)
{
case EntityRequestType.Board_Read_Cards:
if (!message.Properties.Contains(nameof(Card.Board))) return;
card = Items.FirstOrDefault(c => c.Id == message.Data.Id);
if (message.Data.Board?.Id != OwnerId && card != null)
Items.Remove(card);
else if (message.Data.Board?.Id == OwnerId && card == null)
Items.Add(message.Data.GetFromCache<Card>(Auth));
break;
case EntityRequestType.List_Read_Cards:
if (!message.Properties.Contains(nameof(Card.List))) return;
card = Items.FirstOrDefault(c => c.Id == message.Data.Id);
if (message.Data.List?.Id != OwnerId && card != null)
Items.Remove(card);
else if (message.Data.List?.Id == OwnerId && card == null)
Items.Add(message.Data.GetFromCache<Card>(Auth));
break;
case EntityRequestType.Member_Read_Cards:
if (!message.Properties.Contains(nameof(Card.Members))) return;
card = Items.FirstOrDefault(c => c.Id == message.Data.Id);
var memberIds = message.Data.Members.Select(m => m.Id).ToList();
if (!memberIds.Contains(OwnerId) && card != null)
Items.Remove(card);
else if (memberIds.Contains(OwnerId) && card == null)
Items.Add(message.Data.GetFromCache<Card>(Auth));
break;
}
}
void IHandle<EntityDeletedEvent<IJsonCard>>.Handle(EntityDeletedEvent<IJsonCard> message)
{
var item = Items.FirstOrDefault(c => c.Id == message.Data.Id);
Items.Remove(item);
}
}
}
|
namespace Caliburn.PresentationFramework.Filters
{
using System;
/// <summary>
/// Used to track property paths for change notification.
/// </summary>
public interface IChangeMonitorNode : IDisposable {
/// <summary>
/// The parent node.
/// </summary>
IChangeMonitorNode Parent { get; }
/// <summary>
/// Indicates whether to stop monitoring changes.
/// </summary>
/// <returns></returns>
bool ShouldStopMonitoring();
/// <summary>
/// Raises change notification.
/// </summary>
void NotifyChange();
}
} |
// Copyright (c) True Goodwill. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace FFT.TimeStamps.Benchmarks
{
using System;
using System.Linq;
using BenchmarkDotNet.Attributes;
using static FFT.TimeStamps.Benchmarks.TimeZones;
/// <summary>
/// Measures the speed of converting 1,000,000 UTC DateTimes in chronological order to New York timezone DateTimes.
/// </summary>
public class ConversionIteratorSpeed
{
private static readonly DateTime[] _dateTimes = ExampleFeed.ChronologicalUtcDateTimes().ToArray();
/// <summary>
/// Performs test using built-in .net framework feature.
/// </summary>
[Benchmark]
public void With_DotNet()
{
foreach (var datetime in _dateTimes)
TimeZoneInfo.ConvertTime(datetime, NewYork);
}
/// <summary>
/// Performs test using FFT.TimeStamps conversion feature.
/// </summary>
[Benchmark]
public void With_ConversionIterators()
{
var iterator = ConversionIterators.Create(TimeZoneInfo.Utc, NewYork);
foreach (var datetime in _dateTimes)
iterator.GetDateTime(datetime.Ticks);
}
}
}
|
// Copyright (c) 2020 Yann Crumeyrolle. All rights reserved.
// Licensed under the MIT license. See LICENSE in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
namespace JsonWebToken
{
/// <summary>Represents a cache for <see cref="JwtHeaderDocument"/>.</summary>
public interface IJwtHeaderDocumentCache
{
/// <summary>Gets or sets whether the cache is enabled.</summary>
bool Enabled { get; }
/// <summary>Adds the <see cref="JwtHeader"/> to the cache.</summary>
/// <param name="rawHeader"></param>
/// <param name="header"></param>
void AddHeader(ReadOnlySpan<byte> rawHeader, JwtHeaderDocument header);
/// <summary>Try to get the <see cref="JwtHeader"/>.</summary>
/// <param name="buffer"></param>
/// <param name="header"></param>
/// <returns></returns>
bool TryGetHeader(ReadOnlySpan<byte> buffer, [NotNullWhen(true)] out JwtHeaderDocument? header);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotcakes.Commerce.Catalog;
namespace Hotcakes.Commerce.Tests.IRepository
{
public interface IXmlProductChoicesRepository : IDisposable
{
#region Product Choice Repository Service
/// <summary>
/// Gets the total product shared choice count.
/// </summary>
/// <returns></returns>
int GetTotalProductSharedChoiceCount();
/// <summary>
/// Gets the total product choice count.
/// </summary>
/// <returns></returns>
int GetTotalProductChoiceCount();
/// <summary>
/// Gets the name of the delete product choice.
/// </summary>
/// <returns></returns>
int GetDeleteProductChoiceName();
/// <summary>
/// Gets the name of the add product shared choice.
/// </summary>
/// <returns></returns>
string GetAddProductSharedChoiceName();
/// <summary>
/// Gets the type of the add product choice.
/// </summary>
/// <returns></returns>
int[] GetAddProductChoiceTypeCode();
/// <summary>
/// Gets the name of the edit product choice.
/// </summary>
/// <returns></returns>
int[] GetEditProductChoiceName();
/// <summary>
/// Gets the edit product choice.
/// </summary>
/// <returns></returns>
Option GetEditProductChoice();
/// <summary>
/// Sets the product choice HTML.
/// </summary>
/// <param name="choice">The option.</param>
void SetProductChoiceInfo(ref Option choice);
/// <summary>
/// Sets the product choice item.
/// </summary>
/// <param name="choice">The option.</param>
void AddProductChoiceItem(ref Option choice);
/// <summary>
/// Deletes the product choice item.
/// </summary>
/// <param name="choice">The choice.</param>
void DeleteProductChoiceItem(ref Option choice);
/// <summary>
/// Edits the product choice item.
/// </summary>
/// <param name="choice">The choice.</param>
void EditProductChoiceItem(ref Option choice);
#region ProductXOption
/// <summary>
/// Finds all count.
/// </summary>
/// <returns></returns>
int FindAll_PXO_Count();
/// <summary>
/// Finds all for all stores count.
/// </summary>
/// <returns></returns>
int FindAll_PXO_ForAllStoresCount();
/// <summary>
/// Finds all paged count.
/// </summary>
/// <returns></returns>
int FindAll_PXO_PagedCount();
/// <summary>
/// Finds for product count.
/// </summary>
/// <returns></returns>
int Find_PXO_ForProductCount();
/// <summary>
/// Finds for option count.
/// </summary>
/// <returns></returns>
int Find_PXO_ForOptionCount();
/// <summary>
/// Gets the name of the option.
/// </summary>
/// <returns></returns>
string GetOptionName();
#endregion
#region ProductOption
/// <summary>
/// Finds the all product option count.
/// </summary>
/// <returns></returns>
int FindAll_PO_Count();
/// <summary>
/// Find product option by product identifier count.
/// </summary>
/// <returns></returns>
int Find_PO_ByProductIdCount();
/// <summary>
/// Finds the many product option count.
/// </summary>
/// <returns></returns>
int FindMany_PO_Count();
/// <summary>
/// Gets the product option list.
/// </summary>
/// <returns></returns>
List<string> GetProductOptionList();
#endregion
#region ProductOptionItems
#endregion
#endregion
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using StoreAppModelsLayer.EFModels;
using StoreAppModelsLayer.Interfaces;
using StoreAppModelsLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StoreAppUI.Controllers
{
[ApiController]
[Route("[controller]")]
public class ProductController : Controller
{
private readonly IProductRepository _productRepo;
private readonly IManager<Product> _productManager;
private readonly ILogger<ProductController> _logger;
public ProductController(IProductRepository pr, ILogger<ProductController> logger, IManager<Product> pM)
{
_productRepo = pr;
_productManager = pM;
_logger = logger;
}
// GET: ProductController
[HttpGet]
public ActionResult Index()
{
return View();
}
// GET: ProductController/Details/5
[HttpGet("Productlist")]
public async Task<ActionResult<List<Product>>> Details(int id)
{
List<Product> products = await _productRepo.Select();
//_logger.LogInformation();
return products;
}
[HttpGet("productlistings/{id}")]
public async Task<ActionResult<List<ProductListing>>> StoreProducts(int id)
{
List<Product> products = await _productRepo.GetStoreProducts(id);
List<StoreInventory> inventories = await _productRepo.GetStoreInventory(id);
List<ProductListing> storeProducts = new List<ProductListing>();
for(int i = 0; i < products.Count; i++)
{
ProductListing listing = new ProductListing();
listing.ProductId = products[i].ProductId;
listing.ProductName = products[i].ProductName;
listing.ProductDescription = products[i].ProductDescription;
listing.ProductPrice = products[i].ProductPrice;
listing.QuantityAvailable = products[i].QuantityAvailable;
listing.inventory = inventories[i].Inventory;
storeProducts.Add(listing);
}
return storeProducts;
}
// GET: ProductController/Create
[HttpGet("newproduct")]
public ActionResult Create()
{
return View();
}
//// POST: ProductController/Create
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult Create(IFormCollection collection)
//{
// try
// {
// return RedirectToAction(nameof(Index));
// }
// catch
// {
// return View();
// }
//}
// GET: ProductController/Edit/5
[HttpGet("alterproduct")]
public ActionResult Edit(int id)
{
return View();
}
// POST: ProductController/Edit/5
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult Edit(int id, IFormCollection collection)
//{
// try
// {
// return RedirectToAction(nameof(Index));
// }
// catch
// {
// return View();
// }
//}
// GET: ProductController/Delete/5
[HttpGet("removeproduct")]
public ActionResult Delete(int id)
{
return View();
}
// POST: ProductController/Delete/5
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult Delete(int id, IFormCollection collection)
//{
// try
// {
// return RedirectToAction(nameof(Index));
// }
// catch
// {
// return View();
// }
//}
}
}
|
// Copyright (c) CodeSmith Tools, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace CodeSmith.SchemaHelper {
/// <summary>
/// The .NET Framework Version.
/// </summary>
public enum FrameworkVersion : byte {
/// <summary>
/// .NET 3.5
/// </summary>
v35 = 0,
/// <summary>
/// .NET 4.0
/// </summary>
v40 = 1,
/// <summary>
/// .NET 4.5
/// </summary>
v45 = 2
}
}
|
using SkiAnalyze.Core.Common;
namespace SkiAnalyze.Util;
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Gondola, GondolaDto>()
.ForMember(x => x.Used,
x => x.MapFrom(g => g.Runs.Any()));;
CreateMap<GondolaNode, GondolaNodeDto>();
CreateMap<Piste, PisteDto>();
CreateMap<PisteNode, PisteNodeDto>();
CreateMap<Track, TrackDto>();
CreateMap<Run, RunDto>();
CreateMap<AnalysisStatus, AnalysisStatusDto>();
CreateMap<TrackPoint, TrackPointDto>();
CreateMap<SkiArea, SkiAreaDto>();
CreateMap<SkiArea, SkiAreaDetailDto>();
CreateMap<SkiAreaNode, SkiAreaNodeDto>();
CreateMap(typeof(BaseStatValue<,>), typeof(BaseStatValueDto<,>));
}
}
|
using System;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Caching.SqlServer;
using Microsoft.Extensions.DependencyInjection;
namespace DNT.Deskly.Web.Caching
{
public static class CustomTicketStoreExtensions
{
public static IServiceCollection AddCustomDistributSqlServerCache(
this IServiceCollection services, Action<SqlServerCacheOptions> setupAction)
{
// To manage large identity cookies
services.AddDistributedSqlServerCache(setupAction);
services.AddScoped<ITicketStore, DistributedCacheTicketStore>();
return services;
}
public static IServiceCollection AddCustomDistributedMemoryCache(this IServiceCollection services)
{
services.AddMemoryCache();
services.AddScoped<ITicketStore, MemoryCacheTicketStore>();
return services;
}
}
} |
using System;
using System.Windows.Input;
using ActivityAnalysis.WPF.State.Navigators;
namespace ActivityAnalysis.WPF.Commands
{
public class RenavigateCommand : ICommand
{
private readonly IRenavigator _renavigator;
public event EventHandler CanExecuteChanged;
public RenavigateCommand(IRenavigator renavigator)
{
_renavigator = renavigator;
}
public bool CanExecute(object parameter) => true;
public void Execute(object parameter)
{
_renavigator.Renavigate();
}
}
} |
@using CarManager.Models
@using CarManager.Web.Areas.LoggedUser.Models.ViewModels
@using CarManager.Web.Areas.LoggedUser.Models.BindingModels
@using CarManager.Web.Areas.LoggedUser.Pages
@namespace CarManager.Web.Areas.Admin
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
using System.Collections.Specialized;
using System.IO;
using System.Windows.Forms;
using ExtractorSharp.Core;
using ExtractorSharp.Core.Command;
using ExtractorSharp.Core.Model;
using ExtractorSharp.Json;
namespace ExtractorSharp.Command.ImageCommand {
public class CutImage : ICommand {
private Album _album;
private Clipboarder _clipboarder;
private int[] _indexes;
private ClipMode _mode;
public bool CanUndo => true;
public bool IsChanged => true;
public string Name => "CutImage";
public void Do(params object[] args) {
_album = args[0] as Album;
_indexes = args[1] as int[];
_mode = (ClipMode) args[2];
_clipboarder = Clipboarder.Default;
Clipboarder.Default = Clipboarder.CreateClipboarder(_album, _indexes, _mode);
var arr = new string[_indexes.Length];
var dir = $"{Program.Config["RootPath"]}/temp/clipbord_image";
if (Directory.Exists(dir)) Directory.Delete(dir, true);
Directory.CreateDirectory(dir);
var builder = new LSBuilder();
for (var i = 0; i < _indexes.Length; i++) {
var entity = _album[_indexes[i]];
var path = $"{dir}/{entity.Index}";
builder.WriteObject(entity, path + ".json");
arr[i] = path + ".png";
entity.Picture.Save(arr[i]);
}
var collection = new StringCollection();
collection.AddRange(arr);
Clipboard.SetFileDropList(collection);
}
public void Redo() {
Do(_album, _indexes, _mode);
}
public void Undo() {
Clipboarder.Default = _clipboarder;
}
}
} |
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
using MimeKit.Text;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using static eShopSolution.Utilities.Constants.SystemConstants;
namespace EmailService
{
public class EmailService : IEmailService
{
public void Send(string from, string to, string subject, string text)
{
// create message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(from));
email.To.Add(MailboxAddress.Parse(to));
email.Subject = subject;
// Send text format
//email.Body = new TextPart(TextFormat.Plain) { Text = text };
// Send html format
email.Body = new TextPart(TextFormat.Html)
{
Text = string.Format(text)
};
// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("hytranluan@gmail.com", "");
try
{
smtp.Send(email);
smtp.Disconnect(true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
} |
using System.Threading.Tasks;
using Fulgoribus.Luxae.Entities;
using Fulgoribus.Luxae.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Fulgoribus.Luxae.Web.Pages.Books
{
public class IndexModel : PageModel
{
[BindProperty(SupportsGet = true)]
public int? BookId { get; set; }
public Book Book { get; set; } = new Book();
private readonly IBookRepository bookRepository;
public IndexModel(IBookRepository bookRepository)
{
this.bookRepository = bookRepository;
}
public async Task<IActionResult> OnGet()
{
if (BookId.HasValue)
{
Book = await bookRepository.GetBookAsync(BookId.Value, User) ?? new Book();
}
return Book.IsValid
? (IActionResult)Page()
: NotFound();
}
public async Task<IActionResult> OnPostAdd()
{
if (!User.Identity.IsAuthenticated)
{
return Forbid();
}
else if (!BookId.HasValue)
{
return BadRequest();
}
await bookRepository.AddToCollection(BookId.Value, User);
return RedirectToPage();
}
public async Task<IActionResult> OnPostRemove()
{
if (!User.Identity.IsAuthenticated)
{
return Forbid();
}
else if (!BookId.HasValue)
{
return BadRequest();
}
await bookRepository.RemoveFromCollection(BookId.Value, User);
return RedirectToPage();
}
}
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class CMSModules_AdminControls_Controls_Class_FieldEditor_FieldEditor {
/// <summary>
/// pnlFieldEditor control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlFieldEditor;
/// <summary>
/// pnlFieldEditorWrapper control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlFieldEditorWrapper;
/// <summary>
/// pnlHeaderActions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlHeaderActions;
/// <summary>
/// hdrActions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSAdminControls_UI_PageElements_HeaderActions hdrActions;
/// <summary>
/// pnlHeaderPlaceHolder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlHeaderPlaceHolder;
/// <summary>
/// pnlLeft control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlLeft;
/// <summary>
/// pnlButtons control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlButtons;
/// <summary>
/// plcMainButtons control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcMainButtons;
/// <summary>
/// btnAdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSMoreOptionsButton btnAdd;
/// <summary>
/// btnNewCategory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnNewCategory;
/// <summary>
/// btnNewAttribute control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnNewAttribute;
/// <summary>
/// btnDeleteItem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSAccessibleButton btnDeleteItem;
/// <summary>
/// btnUpAttribute control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSAccessibleButton btnUpAttribute;
/// <summary>
/// btnDownAttribute control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSAccessibleButton btnDownAttribute;
/// <summary>
/// lstAttributes control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSListBox lstAttributes;
/// <summary>
/// pnlDevelopmentMode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlDevelopmentMode;
/// <summary>
/// lnkFormDef control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLinkButton lnkFormDef;
/// <summary>
/// lnkHideAllFields control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLinkButton lnkHideAllFields;
/// <summary>
/// lnkShowAllFields control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLinkButton lnkShowAllFields;
/// <summary>
/// documentSource control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_DocumentSource documentSource;
/// <summary>
/// pnlUpdateQuickSelect control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateQuickSelect;
/// <summary>
/// pnlQuickSelect control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlQuickSelect;
/// <summary>
/// lblQuickLinks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblQuickLinks;
/// <summary>
/// lblGeneral control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblGeneral;
/// <summary>
/// plcQuickAppearance control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcQuickAppearance;
/// <summary>
/// lblField control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblField;
/// <summary>
/// plcQuickSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcQuickSettings;
/// <summary>
/// lblSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblSettings;
/// <summary>
/// plcQuickValidation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcQuickValidation;
/// <summary>
/// lblValidation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblValidation;
/// <summary>
/// plcQuickStyles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcQuickStyles;
/// <summary>
/// lblStyles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblStyles;
/// <summary>
/// plcQuickHtmlEnvelope control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcQuickHtmlEnvelope;
/// <summary>
/// lblHtmlEnvelope control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblHtmlEnvelope;
/// <summary>
/// plcQuickAdvancedSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcQuickAdvancedSettings;
/// <summary>
/// lblAdvanced control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblAdvanced;
/// <summary>
/// pnlContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlContent;
/// <summary>
/// pnlContentPadding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlContentPadding;
/// <summary>
/// pnlRightWrapper control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlRightWrapper;
/// <summary>
/// plcMess control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.MessagesPlaceHolder plcMess;
/// <summary>
/// pnlField control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlField;
/// <summary>
/// plcCategory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcCategory;
/// <summary>
/// categoryEdit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_CategoryEdit categoryEdit;
/// <summary>
/// plcField control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcField;
/// <summary>
/// plcFieldType control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcFieldType;
/// <summary>
/// pnlUpdateFieldType control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateFieldType;
/// <summary>
/// fieldTypeSelector control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_FieldTypeSelector fieldTypeSelector;
/// <summary>
/// plcDatabase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcDatabase;
/// <summary>
/// pnlUpdateDatabase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateDatabase;
/// <summary>
/// databaseConfiguration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_DatabaseConfiguration databaseConfiguration;
/// <summary>
/// pnlUpdateDisplay control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateDisplay;
/// <summary>
/// chkDisplayInForm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkDisplayInForm;
/// <summary>
/// pnlDisplayInDashBoard control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlDisplayInDashBoard;
/// <summary>
/// chkDisplayInDashBoard control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkDisplayInDashBoard;
/// <summary>
/// plcFieldAppearance control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcFieldAppearance;
/// <summary>
/// pnlUpdateAppearance control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateAppearance;
/// <summary>
/// fieldAppearance control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_FieldAppearance fieldAppearance;
/// <summary>
/// plcSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcSettings;
/// <summary>
/// pnlUpdateSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateSettings;
/// <summary>
/// controlSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_ControlSettings controlSettings;
/// <summary>
/// plcValidation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcValidation;
/// <summary>
/// pnlUpdateValidation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateValidation;
/// <summary>
/// validationSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_ValidationSettings validationSettings;
/// <summary>
/// plcCSS control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcCSS;
/// <summary>
/// pnlUpdateCSS control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlUpdateCSS;
/// <summary>
/// cssSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_CSSsettings cssSettings;
/// <summary>
/// plcHtmlEnvelope control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcHtmlEnvelope;
/// <summary>
/// pnlHtmlEnvelope control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlHtmlEnvelope;
/// <summary>
/// htmlEnvelope control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_HTMLEnvelope htmlEnvelope;
/// <summary>
/// plcFieldAdvancedSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcFieldAdvancedSettings;
/// <summary>
/// pnlFieldAdvancedSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSUpdatePanel pnlFieldAdvancedSettings;
/// <summary>
/// fieldAdvancedSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_AdminControls_Controls_Class_FieldEditor_FieldAdvancedSettings fieldAdvancedSettings;
/// <summary>
/// ltlConfirmText control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltlConfirmText;
/// <summary>
/// ltlScript control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltlScript;
}
|
using Microsoft.EntityFrameworkCore;
using Noppes.Fluffle.Database;
namespace Noppes.Fluffle.Api.AccessControl
{
/// <summary>
/// Generic database context which supports access control.
/// </summary>
public abstract class ApiKeyContext<TApiKey, TPermission, TApiKeyPermission> : BaseContext
where TApiKey : ApiKey<TApiKey, TPermission, TApiKeyPermission>
where TPermission : Permission<TApiKey, TPermission, TApiKeyPermission>
where TApiKeyPermission : ApiKeyPermission<TApiKey, TPermission, TApiKeyPermission>
{
public virtual DbSet<TApiKey> ApiKeys { get; set; }
public virtual DbSet<TPermission> Permissions { get; set; }
public virtual DbSet<TApiKeyPermission> ApiKeyPermissions { get; set; }
protected ApiKeyContext()
{
}
protected ApiKeyContext(DbContextOptions options) : base(options)
{
}
}
}
|
using System;
using System.Text.RegularExpressions;
namespace MoneyArchiveDb.QifImport {
public abstract class Field {
public static Field Create(string line) {
string data = line[1..];
if (string.IsNullOrWhiteSpace(line)) throw new Exception("Blank Line");
return line[0] switch {
'D' => new DateField(data),
'T' or 'U' => new AmountField(data),
'M' => new MemoField(data),
'C' => new ClearedStatusField(data),
'N' => new ChequeNumberField(data),
'P' => new PayeeField(data),
'L' => data.StartsWith('[') ? new TransferField(data) : new CategoryField(data),
'S' => data.StartsWith('[') ? new SplitTransfer(data) : new SplitCategory(data),
'E' => new SplitMemo(data),
'$' => new SplitAmount(data),
_ => throw new Exception($"Unknown Field Type {line[0]}"),
};
}
}
class DateField : Field {
public DateTime Value { get; private set; }
static readonly Regex _date = new(@"(?'day'^\d{1,2})/(?'month'\d{1,2})(?'cent'/|')(?'year'\d\d)$");
public DateField(string data) {
var m = _date.Match(data);
if (!m.Success) throw new Exception($"Date Parse Failure: '{data}'");
var day = int.Parse(m.Groups["day"].Value);
var month = int.Parse(m.Groups["month"].Value);
var year = int.Parse(m.Groups["year"].Value);
year += m.Groups["cent"].Value == "/" ? 1900 : 2000;
Value = new DateTime(year, month, day);
}
}
class AmountField : Field {
public decimal Value { get; private set; }
public AmountField(string data) {
Value = decimal.Parse(data);
}
}
abstract class StringField : Field {
public string Value { get; protected set; }
public StringField(string data) {
Value = data;
}
}
class MemoField : StringField {
public MemoField(string data) : base(data) { }
}
class ClearedStatusField : Field {
public char Value { get; private set; }
public ClearedStatusField(string data) {
Value = string.IsNullOrWhiteSpace(data) || data.Length == 0 || data[0] == 0 ? ' ' : data[0];
}
}
class ChequeNumberField : Field {
public int? Number { get; private set; }
public string Value { get; private set; }
public ChequeNumberField(string data) {
Number = int.TryParse(data, out int n) ? n : null;
if (Number == null) Value = data;
}
}
class PayeeField : StringField {
public PayeeField(string data) : base(data) { }
}
class CategoryField : StringField {
public CategoryField(string data) : base(data) { }
}
class TransferField : StringField {
public TransferField(string data) : base(null) {
if (!data.StartsWith('[') || !data.EndsWith(']')) throw new Exception($"Invalid transfer account name: '{data}'");
Value = data[1..^1];
}
}
class SplitCategory : CategoryField {
public SplitCategory(string data) : base(data) { }
}
class SplitTransfer : TransferField {
public SplitTransfer(string data) : base(data) { }
}
class SplitMemo : MemoField {
public SplitMemo(string data) : base(data) { }
}
class SplitAmount : AmountField {
public SplitAmount(string data) : base(data) { }
}
}
|
using System;
using Xunit;
//// using Models;
//namespace TestCases
//{
// public class UnitTest1
// {
// [Fact]
// public void OrderShouldHaveValidId()
// {
// Order _orderTest = new Order();
// string orderProduct = "fifa";
// _orderTest.Order = orderProduct;
// Assert.NotNull(_orderTest);
// }
// [Theory]
// [InlineData("1253Maine")]
// [InlineData("12hjkh3")]
// [InlineData("15kaeaa")]
// [InlineData("123jfdshiu321")]
// [InlineData("huih123hjkfdh")]
// [InlineData("hguifeshgo")]
// [InLineData("iop321iop312")]
// [InlineData("uoinbiuhuyg3")]
// [InlineData("67857645")]
// public void HopefullyThisWorks(string p_input)
// {
// Order _orderTest = new Order();
// Assert.Throws<Exception>(() => _orderTest.Name);
// }
// }
//}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System;
public class CameraSize : MonoBehaviour
{
void Awake()
{
if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("Game"))
{
Application.targetFrameRate = 60;
float aspect = (float)Screen.width / (float)Screen.height;
aspect = (float)Math.Round(aspect, 2);
Debug.Log("aspect : " + aspect);
if (Screen.width >= 1280 && Screen.width <= 1400)
{
//GetComponent<Camera>().orthographicSize = 6f;
Debug.Log("Screen.width > 1280 : " + aspect);
}
if (aspect == 1.6f)
GetComponent<Camera>().orthographicSize = 6f; //16:10
else if (aspect == 1.78f)
GetComponent<Camera>().orthographicSize = 6.2f; //16:9
else if (aspect == 1.5f)
GetComponent<Camera>().orthographicSize = 5.5f; //3:2
else if (aspect == 1.33f)
GetComponent<Camera>().orthographicSize = 5.2f; //4:3
else if (aspect == 1.67f)
GetComponent<Camera>().orthographicSize = 5f; //5:3
else if (aspect == 1.25f)
GetComponent<Camera>().orthographicSize = 5f; //5:4
else if (aspect == 2.06f)
GetComponent<Camera>().orthographicSize = 5f; //2960:1440
else if (aspect == 2.17f)
GetComponent<Camera>().orthographicSize = 5f; //iphone x
else if (aspect == 2f)
GetComponent<Camera>().orthographicSize = 5.5f; //OppoA73
}
}
}
|
namespace Plus.Guids
{
/// <summary>
/// Describes the type of a sequential GUID value.
/// </summary>
public enum SequentialGuidType
{
/// <summary>
/// The GUID should be sequential when formatted using the <see cref="Guid.ToString()" /> method.
/// Used by MySql and PostgreSql.
/// </summary>
SequentialAsString,
/// <summary>
/// The GUID should be sequential when formatted using the <see cref="Guid.ToByteArray" /> method.
/// Used by Oracle.
/// </summary>
SequentialAsBinary,
/// <summary>
/// The sequential portion of the GUID should be located at the end of the Data4 block.
/// Used by SqlServer.
/// </summary>
SequentialAtEnd
}
} |
using System;
using System.Collections.Generic;
namespace ESFA.DC.JobContext.Interface
{
public interface IJobContextMessage
{
long JobId { get; }
DateTime SubmissionDateTimeUtc { get; }
IReadOnlyList<ITopicItem> Topics { get; }
int TopicPointer { get; }
IDictionary<string, object> KeyValuePairs { get; }
}
}
|
namespace UnityEngine.Analytics
{
[EnumCase(EnumCase.Styles.Lower)]
public enum SocialNetwork
{
None,
Facebook,
Twitter,
Instagram,
GooglePlus,
Pinterest,
WeChat,
SinaWeibo,
TencentWeibo,
QQ,
Zhihu,
VK,
OK_ru,
}
}
|
//<snippet16>
using System;
using System.Runtime.InteropServices;
//<snippet17>
// Declares a class member for each structure element.
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public class FindData
{
public int fileAttributes = 0;
// creationTime was an embedded FILETIME structure.
public int creationTime_lowDateTime = 0 ;
public int creationTime_highDateTime = 0;
// lastAccessTime was an embedded FILETIME structure.
public int lastAccessTime_lowDateTime = 0;
public int lastAccessTime_highDateTime = 0;
// lastWriteTime was an embedded FILETIME structure.
public int lastWriteTime_lowDateTime = 0;
public int lastWriteTime_highDateTime = 0;
public int nFileSizeHigh = 0;
public int nFileSizeLow = 0;
public int dwReserved0 = 0;
public int dwReserved1 = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
public String fileName = null;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)]
public String alternateFileName = null;
}
public class LibWrap
{
// Declares a managed prototype for the unmanaged function.
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr FindFirstFile(string fileName, [In, Out]
FindData findFileData);
}
//</snippet17>
//<snippet18>
public class App
{
public static void Main()
{
FindData fd = new FindData();
IntPtr handle = LibWrap.FindFirstFile("C:\\*.*", fd);
Console.WriteLine("The first file: {0}", fd.fileName);
}
}
//</snippet18>
//</snippet16>
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace Microsoft.NET.HostModel
{
internal static class HostModelUtils
{
private const string CodesignPath = @"/usr/bin/codesign";
public static bool IsCodesignAvailable() => File.Exists(CodesignPath);
public static (int ExitCode, string StdErr) RunCodesign(string args, string appHostPath)
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.OSX));
Debug.Assert(IsCodesignAvailable());
var psi = new ProcessStartInfo()
{
Arguments = $"{args} \"{appHostPath}\"",
FileName = CodesignPath,
RedirectStandardError = true,
UseShellExecute = false,
};
using (var p = Process.Start(psi))
{
p.WaitForExit();
return (p.ExitCode, p.StandardError.ReadToEnd());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kesco.Web.Mvc;
using BLToolkit.Reflection;
using Kesco.Persons.BusinessLogic;
namespace Kesco.Persons.Web.Models.Synchronize
{
/// <summary>
/// Модель представления синхронизации сотрудника и лица
/// </summary>
public class ViewModel : ViewModel<DataModel>
{
/// <summary>
/// Есть права на редактирование или нет?.
/// </summary>
public int AccessLevel { get; internal set; }
/// <summary>
/// Представляет отличия в данных сотрудника и лица
/// </summary>
/// <value>
/// Отличия в данных.
/// </value>
public Differences Differences { get; internal set; }
/// <summary>
/// Initializes a new instance of the <see cref="ViewModel" /> class.
/// </summary>
public ViewModel() : base()
{
Differences = new Differences();
}
/// <summary>
/// Создаёт объект с настройками пользователя.
/// </summary>
protected override void CreateSettings()
{
settings = TypeAccessor<ClientParameters>.CreateInstanceEx();
}
/// <summary>
/// Инициализирует модель представления с помощью переданных
/// идентификаторов лица и сотрудника
/// </summary>
/// <param name="personID">Идентификатор лица.</param>
/// <param name="employeeID">Идентификаторов сотрудника.</param>
public void Init(int personID, int employeeID)
{
var person = Model.Person = Repository.Persons.GetInstance(personID);
if (person != null) {
AccessLevel = (int) Repository.Persons.GetPersonAccessLevel(personID);
Model.PersonCard = Repository.NaturalPersonCards.GetCurrentPersonCard(personID);
Model.PersonPositions = Repository.Persons.GetPersonCurrentPositions(personID);
Model.Employee = Kesco.Employees.BusinessLogic.Repository.Employees.GetInstance(employeeID);
Model.EmployeePositions = Repository.Persons.GetPersonEmployeePositions(employeeID);
}
}
public void Compare()
{
Differences.Compare(Model);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.