content
stringlengths
23
1.05M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FindeyVouchers.Domain; using FindeyVouchers.Domain.EfModels; using FindeyVouchers.Interfaces; using Serilog; namespace FindeyVouchers.Services { public class MerchantService : IMerchantService { private readonly ApplicationDbContext _context; private readonly IMailService _mailService; public MerchantService(ApplicationDbContext context, IMailService mailService) { _context = context; _mailService = mailService; } public ApplicationUser GetMerchantInfo(string merchantName) { if (merchantName != null) { var merchant = _context.Users.FirstOrDefault(x => x.NormalizedCompanyName.Equals(merchantName.ToLower())); return merchant; } return null; } public async Task CreateAndSendMerchantNotification(List<CustomerVoucher> vouchers) { try { var merchantVouchers = vouchers.Select(x => x.MerchantVoucher).Distinct(); var sb = new StringBuilder(); foreach (var merchantVoucher in merchantVouchers) { var count = vouchers.Count(x => x.MerchantVoucher == merchantVoucher); var emailVoucher = _mailService.GetVoucherNoticiationHtml(merchantVoucher, count); sb.Append(emailVoucher); } var totalAmount = vouchers.Sum(x => x.Price); var subject = "Nieuwe bestelling via Findey Vouchers"; var body = _mailService.GetVoucherNotificationHtmlBody( vouchers.First().MerchantVoucher.Merchant.CompanyName, sb.ToString(), totalAmount, vouchers.Count()); var response = await _mailService.SendMail(vouchers.First().MerchantVoucher.Merchant.Email, subject, body); } catch (Exception e) { Log.Error($"{e}"); } } } }
// Copyright (c) Aksio Insurtech. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Aksio.Cratis.DependencyInversion; using Aksio.Cratis.Events.Projections.Definitions; using Aksio.Cratis.Execution; using Microsoft.AspNetCore.Mvc; namespace Aksio.Cratis.Events.Projections.Api; /// <summary> /// Represents the API for projections. /// </summary> [Route("/api/events/store/projections")] public class Projections : Controller { readonly ProviderFor<IProjectionDefinitions> _projectionDefinitionsProvider; readonly IExecutionContextManager _executionContextManager; /// <summary> /// Initializes a new instance of the <see cref="Projections"/> class. /// </summary> /// <param name="projectionDefinitionsProvider">Provider for <see cref="IProjectionDefinitions"/>.</param> /// <param name="executionContextManager"><see cref="IExecutionContextManager"/>.</param> public Projections( ProviderFor<IProjectionDefinitions> projectionDefinitionsProvider, IExecutionContextManager executionContextManager) { _projectionDefinitionsProvider = projectionDefinitionsProvider; _executionContextManager = executionContextManager; } /// <summary> /// Gets all projections. /// </summary> /// <param name="microserviceId">The <see cref="MicroserviceId"/> to get projections for.</param> /// <returns><see cref="Projection"/> containing all projections.</returns> [HttpGet] public async Task<IEnumerable<Projection>> AllProjections([FromQuery] MicroserviceId microserviceId) { _executionContextManager.Establish(microserviceId); var projections = await _projectionDefinitionsProvider().GetAll(); return projections.Select(_ => new Projection( _.Identifier, _.Name, _.Model.Name)).ToArray(); } /// <summary> /// Get all collections for projection. /// </summary> /// <param name="microserviceId">The <see cref="MicroserviceId"/> to get projection collections for.</param> /// <param name="projectionId">Id of projection to get for.</param> /// <returns>Collection of all the projection collections.</returns> [HttpGet("{projectionId}/collections")] #pragma warning disable IDE0060 public IEnumerable<ProjectionCollection> Collections( [FromQuery] MicroserviceId microserviceId, [FromRoute] ProjectionId projectionId) { return new ProjectionCollection[] { new("Something", 42) }; } }
using System; namespace Ship_Game.AI.StrategyAI.WarGoals { public class Defense : Campaign { SolarSystem CurrentTarget; /// <summary> /// Initializes from save a new instance of the <see cref="Defense"/> class. /// </summary> public Defense(Campaign campaign, War war) : base(campaign, war) => CreateSteps(); public Defense(CampaignType campaignType, War war) : base(campaignType, war) { CreateSteps(); } void CreateSteps() { Steps = new Func<GoalStep>[] { SetTargets, SetupRallyPoint, AttackSystems }; } GoalStep SetTargets() { AddTargetSystems(OwnerWar.ContestedSystems); if (TargetSystems.IsEmpty) return GoalStep.GoalComplete; return GoalStep.GoToNextStep; } GoalStep AttackSystems() { if (HaveConqueredTargets()) return GoalStep.GoalComplete; var tasks = new WarTasks(Owner, Them); foreach(var system in TargetSystems) { if (HaveConqueredTarget(system)) continue; tasks.StandardAssault(system, 0, 2); } Owner.GetEmpireAI().AddPendingTasks(tasks.GetNewTasks()); return GoalStep.RestartGoal; } bool HaveConqueredTargets() { foreach(var system in TargetSystems) { if (!HaveConqueredTarget(system)) return false; } return true; } bool HaveConqueredTarget(SolarSystem system) => !system.OwnerList.Contains(Them); } }
using System; using System.Text; #if !NETSTANDARD1_3 using System.Runtime.Serialization; using System.Security.Permissions; #endif using AdvancedStringBuilder; using MsieJavaScriptEngine.Constants; using MsieJavaScriptEngine.Helpers; namespace MsieJavaScriptEngine { /// <summary> /// The exception that is thrown during the work of JS engine /// </summary> #if !NETSTANDARD1_3 [Serializable] #endif public class JsException : Exception { /// <summary> /// Name of JS engine mode /// </summary> private readonly string _engineMode = string.Empty; /// <summary> /// Error category /// </summary> private string _category = JsErrorCategory.Unknown; /// <summary> /// Description of error /// </summary> private string _description = string.Empty; /// <summary> /// Gets a name of JS engine mode /// </summary> public string EngineMode { get { return _engineMode; } } /// <summary> /// Gets or sets a error category /// </summary> public string Category { get { return _category; } set { _category = value; } } /// <summary> /// Gets or sets a description of error /// </summary> public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Initializes a new instance of the <see cref="JsException"/> class /// with a specified error message /// </summary> /// <param name="message">The message that describes the error</param> public JsException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="JsException"/> class /// with a specified error message and a reference to the inner exception /// that is the cause of this exception /// </summary> /// <param name="message">The error message that explains the reason for the exception</param> /// <param name="innerException">The exception that is the cause of the current exception</param> public JsException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="JsException"/> class /// </summary> /// <param name="message">The error message that explains the reason for the exception</param> /// <param name="engineMode">Name of JS engine mode</param> public JsException(string message, string engineMode) : this(message, engineMode, null) { } /// <summary> /// Initializes a new instance of the <see cref="JsException"/> class /// </summary> /// <param name="message">The error message that explains the reason for the exception</param> /// <param name="engineMode">Name of JS engine mode</param> /// <param name="innerException">The exception that is the cause of the current exception</param> public JsException(string message, string engineMode, Exception innerException) : base(message, innerException) { _engineMode = engineMode; } #if !NETSTANDARD1_3 /// <summary> /// Initializes a new instance of the <see cref="JsException"/> class with serialized data /// </summary> /// <param name="info">The object that holds the serialized data</param> /// <param name="context">The contextual information about the source or destination</param> protected JsException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info != null) { _engineMode = info.GetString("EngineMode"); _category = info.GetString("Category"); _description = info.GetString("Description"); } } #region Exception overrides /// <summary> /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data</param> /// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization</param> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } base.GetObjectData(info, context); info.AddValue("EngineMode", _engineMode); info.AddValue("Category", _category); info.AddValue("Description", _description); } #endregion #endif #region Object overrides /// <summary> /// Returns a string that represents the current exception /// </summary> /// <returns>A string that represents the current exception</returns> public override string ToString() { string errorDetails = JsErrorHelpers.GenerateErrorDetails(this, true); var stringBuilderPool = StringBuilderPool.Shared; StringBuilder resultBuilder = stringBuilderPool.Rent(); resultBuilder.Append(this.GetType().FullName); resultBuilder.Append(": "); resultBuilder.Append(this.Message); if (errorDetails.Length > 0) { resultBuilder.AppendLine(); resultBuilder.AppendLine(); resultBuilder.Append(errorDetails); } if (this.InnerException != null) { resultBuilder.Append(" ---> "); resultBuilder.Append(this.InnerException.ToString()); } if (this.StackTrace != null) { resultBuilder.AppendLine(); resultBuilder.AppendLine(this.StackTrace); } string result = resultBuilder.ToString(); stringBuilderPool.Return(resultBuilder); return result; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FingannTemplate.Services.Navigation.Interfaces { /// <summary> /// The Displayable interface. /// </summary> public interface IDisplayable { /// <summary> /// Gets or sets the title. /// </summary> string DisplayTitle { get; set; } /// <summary> /// Gets or sets the parameter used for communication between DisplayableViews. /// </summary> object Parameter { get; set; } } }
namespace DotNetCenter.Beyond.Web.Core.Middlewares { using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore; using DotNetCenter.Beyond.Web.Core.Common.DIContainerServices; public static class ExceptionMiddleware { public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder app, SupportWebHosting env) { if (env.Service.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseMigrationsEndPoint(); } else { app.UseStatusCodePagesWithReExecute("/Error", "?scode={0}"); app.UseExceptionHandler("/Error"); } return app; } } }
using PaymentGateway.Domain.Common; using System; namespace PaymentGateway.Domain.Payments { /// <summary> /// Placeholder entity with no validations. To be implemented when a real bank is integrated. /// </summary> public class PaymentResponse:Entity { public PaymentRequest PaymentRequest { get; set; } public Guid ResponseId { get; set; } public bool Successful { get; set; } public DateTime Timestamp { get; set; } public PaymentResponse() { } public PaymentResponse(PaymentRequest paymentRequest, Guid responseId, bool successful, DateTime timestamp) { PaymentRequest = paymentRequest; ResponseId = responseId; Successful = successful; Timestamp = timestamp; } public override ValidationResults Validate() { return new ValidationResults(); } } }
namespace TennisBookings.Web.External.Models { public class Wind { public float Speed { get; set; } public float Degrees { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TPC_UPC.Domain.Models; namespace TPC_UPC.Domain.Persistence.Repositories { public interface ICoordinatorRepository { Task<IEnumerable<Coordinator>> ListAsync(); Task AddAsync(Coordinator coordinator); Task<Coordinator> FindById(int id); Task<Coordinator> FindByIdAndFacultyId(int facultyId, int id); Task<IEnumerable<Coordinator>> ListByFacultyIdAsync(int facultyId); void Update(Coordinator coordinator); void Remove(Coordinator coordinator); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace XForm.Data { /// <summary> /// ColumnDetails provides column metadata for columns in an XArray. /// </summary> public class ColumnDetails { public string Name { get; private set; } public Type Type { get; private set; } public ColumnDetails(string name, Type type) { this.Name = name; this.Type = type; } public ColumnDetails Rename(string name) { return new ColumnDetails(name, this.Type); } public ColumnDetails ChangeType(Type type) { return new ColumnDetails(this.Name, type); } public override bool Equals(object obj) { ColumnDetails other = obj as ColumnDetails; if (other == null) return false; return this.Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) && this.Type.Equals(other.Type); } public override int GetHashCode() { return this.Name.GetHashCode() ^ this.Type.GetHashCode(); } } }
using UnityEngine; using System.Collections; [DefaultExecutionOrder(100)] public class DisplayMenuData : MonoBehaviour { public string valueName; public TMPro.TextMeshProUGUI textObject; // Use this for initialization public GameObject dataSource; private IUIAdapter dataAdapter; void Start() { dataAdapter = dataSource.GetComponent<IUIAdapter>(); if(dataAdapter != null) { dataAdapter.AddListener(valueName, UpdateValue); } } void UpdateValue(IData data) { textObject.text = data.DisplayValue; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace rcsir.net.common.Network { public class VertexCollection<T> : HashSet<Vertex<T>> { public VertexCollection() : base() { } public VertexCollection(IEnumerable<Vertex<T>> oVertices) : base(oVertices) { } public Vertex<T> this[T ID] { get { return this.FirstOrDefault(x => x.ID.Equals(ID)); } set { this.RemoveWhere(x => x.ID.Equals(ID)); this.Add(value); } } //public Vertex this[int index] //{ // get { return this.ElementAt(index); } // set { this.Remove(this.ElementAt(index)); this.Add(value); } //} } }
using System; using System.Collections.Generic; using Xabbo.Messages; namespace Xabbo.Core { public class PetInfo : IComposable { public int Id { get; set; } public string Name { get; set; } = string.Empty; public int Level { get; set; } public int MaxLevel { get; set; } public int Experience { get; set; } public int MaxExperience { get; set; } public int Energy { get; set; } public int MaxEnergy { get; set; } public int Happiness { get; set; } public int MaxHappiness { get; set; } public int Scratches { get; set; } public int OwnerId { get; set; } public int Age { get; set; } public string OwnerName { get; set; } = string.Empty; public int Breed { get; set; } public bool HasFreeSaddle { get; set; } public bool IsRiding { get; set; } public List<int> SkillThresholds { get; set; } = new(); // Something to do with skills (horse) public int AccessRights { get; set; } public bool CanBreed { get; set; } public bool CanHarvest { get; set; } public bool CanRevive { get; set; } public int RarityLevel { get; set; } public int MaxWellbeingSeconds { get; set; } public int RemainingWellbeingSeconds { get; set; } public int RemainingGrowingSeconds { get; set; } public bool HasBreedingPermission { get; set; } public PetInfo() { } protected PetInfo(IReadOnlyPacket packet) : this() { Id = packet.ReadInt(); Name = packet.ReadString(); Level = packet.ReadInt(); MaxLevel = packet.ReadInt(); Experience = packet.ReadInt(); MaxExperience = packet.ReadInt(); Energy = packet.ReadInt(); MaxEnergy = packet.ReadInt(); Happiness = packet.ReadInt(); MaxHappiness = packet.ReadInt(); Scratches = packet.ReadInt(); OwnerId = packet.ReadInt(); Age = packet.ReadInt(); OwnerName = packet.ReadString(); Breed = packet.ReadInt(); HasFreeSaddle = packet.ReadBool(); IsRiding = packet.ReadBool(); int n = packet.ReadInt(); for (int i = 0; i < n; i++) SkillThresholds.Add(packet.ReadInt()); AccessRights = packet.ReadInt(); CanBreed = packet.ReadBool(); CanHarvest = packet.ReadBool(); CanRevive = packet.ReadBool(); RarityLevel = packet.ReadInt(); MaxWellbeingSeconds = packet.ReadInt(); RemainingWellbeingSeconds = packet.ReadInt(); RemainingGrowingSeconds = packet.ReadInt(); HasBreedingPermission = packet.ReadBool(); } public void Compose(IPacket packet) { packet.WriteInt(Id); packet.WriteString(Name); packet.WriteInt(Level); packet.WriteInt(MaxLevel); packet.WriteInt(Experience); packet.WriteInt(MaxExperience); packet.WriteInt(Energy); packet.WriteInt(MaxEnergy); packet.WriteInt(Happiness); packet.WriteInt(MaxHappiness); packet.WriteInt(Scratches); packet.WriteInt(OwnerId); packet.WriteInt(Age); packet.WriteString(OwnerName); packet.WriteInt(Breed); packet.WriteBool(HasFreeSaddle); packet.WriteBool(IsRiding); packet.WriteInt(SkillThresholds.Count); foreach (int value in SkillThresholds) packet.WriteInt(value); packet.WriteInt(AccessRights); packet.WriteBool(CanBreed); packet.WriteBool(CanHarvest); packet.WriteBool(CanRevive); packet.WriteInt(RarityLevel); packet.WriteInt(MaxWellbeingSeconds); packet.WriteInt(RemainingWellbeingSeconds); packet.WriteInt(RemainingGrowingSeconds); packet.WriteBool(HasBreedingPermission); } public static PetInfo Parse(IReadOnlyPacket packet) => new(packet); } }
namespace ScottPlot.Cookbook.Categories.PlotTypes; public class Arrow : ICategory { public string Name => "Arrow"; public string Folder => "plottable-arrow"; public string Description => "Arrows point to a location in coordinate space."; }
using System; namespace DbConnection { public class DbCommand { private DbConnection _connection; public DbCommand(DbConnection connection) { if (connection == null) throw new NullReferenceException("DbConnection cannot be null"); _connection = connection; } public void Execute(string command) { _connection.Open(); Console.WriteLine(); Console.WriteLine($"command {command} sent to {_connection.GetType()}"); Console.WriteLine(); _connection.Close(); Console.WriteLine("---------------------------------------------------------"); Console.WriteLine(); } } }
//----------------------------------------------------------------------- // <copyright file="ConfigurationErrorsException.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Exception class indicating that there was a validation</summary> //----------------------------------------------------------------------- using System; namespace Csla.Configuration { /// <summary> /// Exception thrown due to configuration errors. /// </summary> [Serializable] public class ConfigurationErrorsException : Exception { /// <summary> /// Creates an instance of the object. /// </summary> public ConfigurationErrorsException() { } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message">Message describing the exception.</param> public ConfigurationErrorsException(string message) : base(message) { } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message">Message describing the exception.</param> /// <param name="innerException">Inner exception object.</param> public ConfigurationErrorsException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Creates an instance of the object for serialization. /// </summary> /// <param name="context">Serialization context.</param> /// <param name="info">Serialization info.</param> protected ConfigurationErrorsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
using System.Linq; using System.Net.Http.Headers; using Tangle.Net.Crypto; using Tangle.Net.Utils; namespace Tangle.Net.Entity.Ed25519 { public class Ed25519Seed { public Ed25519Seed(byte[] secretKey) { SecretKey = secretKey; } private KeyPair keyPair { get; set; } public byte[] SecretKey { get; } public KeyPair KeyPair { get { if (keyPair == null) { var ed25519 = new Rebex.Security.Cryptography.Ed25519(); ed25519.FromSeed(this.SecretKey.Take(32).ToArray()); this.keyPair = new KeyPair { PrivateKey = ed25519.GetPrivateKey(), PublicKey = ed25519.GetPublicKey() }; } return keyPair; } } public static Ed25519Seed FromMnemonic(string mnemonic) { return new Ed25519Seed(Bip39.MnemonicToSeed(mnemonic)); } public static Ed25519Seed Random() { return new Ed25519Seed(Bip39.MnemonicToSeed(Bip39.RandomMnemonic())); } public Ed25519Seed GenerateSeedFromPath(Bip32Path path) { var result = Bip32.DerivePath(path, this.SecretKey); return new Ed25519Seed(result.Key); } } }
namespace SummitRidge.PlayerMove { public interface IMoverInput { float Horizontal(); float Vertical(); bool IsJump(); bool IsCrouch(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using OpenCover.Framework.Model; namespace OpenCover.Test.Framework.Model { [TestFixture] public class InstrumentationPointTests { [Test] public void CanRetrieveSavedTrackedRefs() { var point = new InstrumentationPoint(); point.TrackedMethodRefs = new []{new TrackedMethodRef(){UniqueId = 12345}}; Assert.AreEqual(1, point.TrackedMethodRefs.Count()); Assert.AreEqual(12345, point.TrackedMethodRefs[0].UniqueId); } [Test] public void CanClearSavedTrackedRefs() { var point = new InstrumentationPoint(); point.TrackedMethodRefs = new[] { new TrackedMethodRef() { UniqueId = 12345 } }; Assert.IsNotNull(point.TrackedMethodRefs); point.TrackedMethodRefs = null; Assert.IsNull(point.TrackedMethodRefs); } } }
using System.Security.Claims; using System.Threading.Tasks; using FinHub.Models; using FinHub.Models.EntityModels; namespace FinHub.Services { public interface IGroupUsersService { Task<ServiceResult<int>> AddUser(string groupCode, User user); Task<ServiceResult<int>> RemoveUser(int groupId, User user); Task<ServiceResult<string>> GetGroupUsers(ClaimsPrincipal user, int groupId); Task<ServiceResult<string>> GetGroupUser(ClaimsPrincipal user, int groupId, string userId); ServiceResult<int> GetUserGroups(string userId); } }
using System; using System.Reactive.Concurrency; using ReactiveUI; namespace Akavache { public static class BlobCache { static string applicationName; static ISecureBlobCache perSession = new TestBlobCache(Scheduler.Immediate); static BlobCache() { if (RxApp.InUnitTestRunner()) { localMachine = new TestBlobCache(RxApp.TaskpoolScheduler); userAccount = new TestBlobCache(RxApp.TaskpoolScheduler); secure = new TestBlobCache(RxApp.TaskpoolScheduler); } } /// <summary> /// Your application's name. Set this at startup, this defines where /// your data will be stored (usually at %AppData%\[ApplicationName]) /// </summary> public static string ApplicationName { get { if (applicationName == null) { throw new Exception("Make sure to set BlobCache.ApplicationName on startup"); } return applicationName; } set { applicationName = value; } } static IBlobCache localMachine; static IBlobCache userAccount; /// <summary> /// The local machine cache. Store data here that is unrelated to the /// user account or shouldn't be uploaded to other machines (i.e. /// image cache data) /// </summary> public static IBlobCache LocalMachine { get { return localMachine ?? PersistentBlobCache.LocalMachine; } set { localMachine = value; } } /// <summary> /// The user account cache. Store data here that is associated with /// the user; in large organizations, this data will be synced to all /// machines via NT Roaming Profiles. /// </summary> public static IBlobCache UserAccount { get { return userAccount ?? PersistentBlobCache.UserAccount; } set { userAccount = value; } } static ISecureBlobCache secure; /// <summary> /// An IBlobCache that is encrypted - store sensitive data in this /// cache such as login information. /// </summary> public static ISecureBlobCache Secure { get { return secure ?? EncryptedBlobCache.Current; } set { secure = value; } } /// <summary> /// An IBlobCache that simply stores data in memory. Data stored in /// this cache will be lost when the application restarts. /// </summary> public static ISecureBlobCache InMemory { get { return perSession; } set { perSession = value; } } } }
/*====================================================*\ *|| Copyright(c) KineticIsEpic. || *|| See LICENSE.TXT for details. || *====================================================*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using FluidSys; namespace FluidUI { public delegate void ElementChangedEventArgs(RollElement sender); public delegate void ElementRemovedEventArgs(RollElement sender); public delegate void ElementSelectedChangedEventArgs(RollElement sender, bool isSelected); public delegate void ElementEditingStateEventArgs(bool state); /// <summary> /// Interaction logic for RollElement.xaml /// </summary> public partial class RollElement : UserControl { public event ElementChangedEventArgs ElementPropertiesChanged; public event ElementRemovedEventArgs ElementRemoved; public event ElementSelectedChangedEventArgs ElementSelected; public event ElementChangedEventArgs ElementMouseDown; public event ElementChangedEventArgs ElementMouseUp; public event ElementEditingStateEventArgs ElementEditingStateChanged; // element colors public Brush SelectedForegroundBrush { get; set; } public Brush ForegroundBrush { get; set; } public Brush SelectedBackgroundBrush { get; set; } public Brush BackgroundBrush { get; set; } public Brush TextBkgBrush { get; set; } public Brush InvalidTextBkgBrush { get; set; } /// <summary> /// Determines if the control is selected. /// </summary> public bool IsSelected { get { return baseIsSelected; } set { if (value) setSelector(true); else setSelector(false); if (baseIsSelected != value) { try { ElementSelected.Invoke(this, value); } catch (Exception) { } } baseIsSelected = value; } } /// <summary> /// Gets a value indicating whether the mouse is currently over the resize element /// of this FluidUI.RollElement. /// </summary> public bool IsMouseOverResize { get { return resizer.IsMouseOver; } } /// <summary> /// Sets whether the nameTxtBox.Background is TextBkgBrush or InvalidTextBkgBrush. /// </summary> public bool IsInvalidtext { get { if (nameTxtBox.Background == InvalidTextBkgBrush) return true; return false; } set { if (value) nameTxtBox.Background = InvalidTextBkgBrush; else nameTxtBox.Background = TextBkgBrush; } } /// <summary> /// Gets or sets the tempo value. /// </summary> public int BPM { get; set; } /// <summary> /// Gets or sets a value representing pitch. /// </summary> public string Pitch { get; set; } /// <summary> /// Gets or sets a value representing note name. /// </summary> public string NoteName { get { return nameTxtBox.Text; } set { nameTxtBox.Text = value; } } /// <summary> /// Gets or sets the factor for calculating note length from screen length. /// </summary> public int LengthFactor { get; set; } /// <summary> /// Gets or sets the zero-based index of the note. /// </summary> public int NoteIndex { get; set; } /// <summary> /// Gets or sets the zoom factor (needed to correct note size). /// </summary> public double ZoomFactor { get; set; } /// <summary> /// used for zooming /// </summary> private bool baseIsSelected = false; /// <summary> /// Gets a FluidSys.Note with the properties of this RollElement. /// </summary> public Note ElementNote { get { Note n = new Note(); n.Length = (int)GetLength(); n.NotePitch = Pitch; n.DispName = nameTxtBox.Text; n.UUnitLength = (int)(this.Width / ZoomFactor) * 4; return n; } } public RollElement() { InitializeComponent(); ZoomFactor = 1; LengthFactor = 4; Pitch = "C#4"; NoteIndex = 0; BPM = 120; SelectedForegroundBrush = new SolidColorBrush(Color.FromArgb(255, 45, 157, 215)); ForegroundBrush = new SolidColorBrush(Color.FromArgb(255, 83, 83, 85)); SelectedBackgroundBrush = new SolidColorBrush(Color.FromArgb(255, 135, 171, 189)); BackgroundBrush = new SolidColorBrush(Color.FromArgb(255, 145, 145, 145)); TextBkgBrush = new SolidColorBrush(Color.FromArgb(255, 214, 214, 214)); InvalidTextBkgBrush = new SolidColorBrush(Color.FromArgb(255, 190, 57, 43)); //gripper1.MouseDown += gripper_Selected; //gripper2.MouseDown += gripper_Selected; //gripper3.MouseDown += gripper_Selected; bkgGrid.MouseDown += gripper_Selected; gripper1.MouseUp += gripper_MouseUp; gripper2.MouseUp += gripper_MouseUp; gripper3.MouseUp += gripper_MouseUp; bkgGrid.MouseUp += gripper_MouseUp; nameTxtBox.MouseDown += note_MouseDown; } public double GetLength() { // Using quarter note as a reference for calculation int qNotePx = 120; int qNoteMillis = 0; // Get reference length for note based on current tempo try { qNoteMillis = 60000 / BPM; } catch (Exception) { return -1; } double NoteLengthFactor = this.Width / ZoomFactor / qNotePx; return qNoteMillis * NoteLengthFactor; } private void setSelector(bool isSel) { if (isSel) { gripper1.Fill = SelectedForegroundBrush; gripper2.Fill = SelectedForegroundBrush; gripper3.Fill = SelectedForegroundBrush; resizer.Fill = SelectedBackgroundBrush; bkgGrid.Background = SelectedBackgroundBrush; } else { gripper1.Fill = ForegroundBrush; gripper2.Fill = ForegroundBrush; gripper3.Fill = ForegroundBrush; resizer.Fill = BackgroundBrush; bkgGrid.Background = BackgroundBrush; } } private void note_MouseDown(object sender, MouseButtonEventArgs e) { } private void gripper_Selected(object sender, MouseButtonEventArgs e) { if (e.RightButton == MouseButtonState.Pressed) { //if (!IsSelected) IsSelected = true; //else IsSelected = false; } try { ElementMouseDown.Invoke(this); } catch (Exception) { } } private void gripper_MouseUp(object sender, MouseButtonEventArgs e) { } private void Button_Click(object sender, RoutedEventArgs e) { if (nameTxtBox.IsVisible) nameTxtBox.Visibility = Visibility.Hidden; else nameTxtBox.Visibility = Visibility.Visible; } private void nameTxtBox_TextChanged(object sender, TextChangedEventArgs e) { try { ElementPropertiesChanged.Invoke(this); } catch (Exception) { } } private void nameTxtBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.D && Keyboard.Modifiers == ModifierKeys.Control) { ElementRemoved.Invoke(this); } } private void bkgGrid_MouseUp(object sender, MouseButtonEventArgs e) { try { if (e.ChangedButton == MouseButton.Right) ElementMouseUp.Invoke(this); } catch (Exception) { } } private void nameTxtBox_GotFocus(object sender, RoutedEventArgs e) { try { ElementEditingStateChanged.Invoke(true); } catch (Exception) { } } private void nameTxtBox_LostFocus(object sender, RoutedEventArgs e) { try { ElementEditingStateChanged.Invoke(false); } catch (Exception) { } } } }
using System.ComponentModel; using System.Drawing; using System.Threading.Tasks; using MarkPad.Plugins; namespace MarkPad.DocumentSources { public abstract class MarkpadDocumentBase : IMarkpadDocument { readonly IDocumentFactory documentFactory; protected MarkpadDocumentBase( string title, string content, string saveLocation, IDocumentFactory documentFactory) { Title = title; MarkdownContent = content; SaveLocation = saveLocation; this.documentFactory = documentFactory; } public string MarkdownContent { get; set; } public string Title { get; protected set; } public string SaveLocation { get; protected set; } public virtual ISiteContext SiteContext { get; protected set; } protected IDocumentFactory DocumentFactory { get { return documentFactory; } } public abstract Task<IMarkpadDocument> Save(); public virtual Task<IMarkpadDocument> SaveAs() { return documentFactory.SaveDocumentAs(this); } public virtual Task<IMarkpadDocument> Publish() { return documentFactory.PublishDocument(null, this); } public abstract string SaveImage(Bitmap bitmap); public abstract string ConvertToAbsolutePaths(string htmlDocument); public abstract bool IsSameItem(ISiteItem siteItem); public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Events; namespace FantomLib { /// <summary> /// Manage Overlay Permission Controller (API 23 or higher) /// ///・Open Manage Overlay Permission settings. /// ///・フローティング表示するアプリ権限設定画面を開く。 /// </summary> public class ManageOverlayPermissionController : ActionURIOnThisPackageBase { protected override string action { get { return "android.settings.action.MANAGE_OVERLAY_PERMISSION"; } } //Inspector settings public bool thisApp = true; //false = all App public override void StartAction() { if (thisApp) base.StartAction(); else { #if UNITY_EDITOR Debug.Log(name + ".Show"); #elif UNITY_ANDROID AndroidPlugin.StartAction(action); #endif } } } }
using commercetools.Sdk.Domain.Common; using commercetools.Sdk.Domain.Orders; using commercetools.Sdk.Domain.Stores; namespace commercetools.Sdk.Domain.Messages.Orders { [TypeMarker("OrderStoreSet")] public class OrderStoreSetMessage : Message<Order> { public KeyReference<Store> Store { get; set; } } }
using System.Collections.Generic; using System.Linq; using DotLiquid; using tradelr.DBML; using tradelr.Models.products; namespace tradelr.Models.liquid.models.Product { public class Variant : Drop { public long id { get; set; } public string title { get; set; } public bool available { get; set; } public int inventory_quantity { get; set; } public string sku { get; set; } public bool requires_shipping { get; set; } // todo public bool taxable { get; set; } // todo public decimal? price { get; set; } public decimal? weight { get; set; } // proprietary public string option1 { get; set; } // color public string option2 { get; set; } // size public List<string> options { get; set; } public Variant() { options = new List<string>(); } } public static class VariantHelper { public static Variant ToLiquidModel(this product_variant row, decimal? price) { var v = new Variant() { id = row.id, title = row.ToVariantTitle(), inventory_quantity = row.inventoryLocationItems.Sum(y => y.available) ?? 0, sku = row.sku, price = price, option1 = row.color, option2 = row.size }; // handle options if (!string.IsNullOrEmpty(v.option1)) { v.options.Add(v.option1); } if (!string.IsNullOrEmpty(v.option2)) { v.options.Add(v.option2); } v.available = row.HasStock(); return v; } public static IEnumerable<Variant> ToLiquidVariantModel(this IEnumerable<product_variant> rows, decimal? price) { foreach (var row in rows) { yield return row.ToLiquidModel(price); } } public static string ToVariantTitle(this product_variant v) { var options = new List<string>(); if (!string.IsNullOrEmpty(v.color)) { options.Add(v.color); } if (!string.IsNullOrEmpty(v.size)) { options.Add(v.size); } return string.Join(" / ", options); } } }
using Silksprite.EmoteWizardSupport.Collections.Base; using Silksprite.EmoteWizardSupport.Extensions; using UnityEditor; using UnityEngine; using static Silksprite.EmoteWizardSupport.Tools.PropertyDrawerUITools; namespace Silksprite.EmoteWizard.Collections { public class ExpressionItemListHeaderDrawer : ListHeaderDrawerBase { protected override void DrawHeaderContent(Rect position) { using (new EditorGUI.IndentLevelScope(-EditorGUI.indentLevel)) { GUI.Label(position.UISlice(0.05f, 0.35f, 0), "Icon"); GUI.Label(position.UISlice(0.4f, 0.6f, 0), "Path"); GUI.Label(position.UISlice(0.0f, 0.4f, 1), "Parameter"); GUI.Label(position.UISlice(0.4f, 0.2f, 1), "Value"); GUI.Label(position.UISlice(0.6f, 0.4f, 1), "ControlType"); } } public override float GetHeaderHeight() { return BoxHeight(LineHeight(2f)); } } }
using Furion.FriendlyException; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PowerAdmin.Domain.User.Models { public class Password { private string password = default!; public static implicit operator Password(string str) { if (string.IsNullOrWhiteSpace(str) || str.Length < 8 || str.Length > 20) { throw Oops.Bah("不正确的密码格式, 请输入 8~20 个字符: {0}!", str); } if (!IncludeDigit(str) || !IncludeUpperChar(str) || !IncludeSpecialChar(str)) { throw Oops.Bah("不正确的密码格式, 需要大小写字母、数字和特殊字符三种或以上: {0}!", str); } return new Password { password = str }; } public static implicit operator string(Password password) => password.password; public override bool Equals(object? obj) => Equals(obj as Password); private bool Equals(Password? password) { if (password is null) { return false; } return password.password == this.password; } public static bool operator ==(Password? password, Password? password1) { if (password is null) { if (password1 is null) { return true; } return false; } return password.Equals(password1); } public static bool operator !=(Password? password, Password? password1) => !(password == password1); public override int GetHashCode() => password.GetHashCode(); /// <summary> /// 是否包含数字 /// </summary> /// <param name="str"></param> /// <returns></returns> private static bool IncludeDigit(string str) { return str.Any(c => char.IsDigit(c)); } /// <summary> /// 是否包含大写字符 /// </summary> /// <param name="str"></param> /// <returns></returns> private static bool IncludeUpperChar(string str) { return str.Any(c => char.IsUpper(c)); } /// <summary> /// 是否包含特殊字符 /// </summary> /// <param name="str"></param> /// <returns></returns> private static bool IncludeSpecialChar(string str) { return str.Any(c => !char.IsLetterOrDigit(c)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConventionRegistration { /// <summary> /// /// </summary> enum EVENTTYPE { ENTER, LEAVE } class Evnt : IComparable { public EVENTTYPE Type { get; set; } public DateTime Time { get; set; } public int Patron { get; set; } public double Duration { get { return Duration; } set { Duration = value; } } public TimeSpan windowTime; private static Random ran = new Random(); public Evnt(DateTime currentTime) { Type = EVENTTYPE.ENTER; Time = currentTime; Patron = -1; windowTime = new TimeSpan(0, 0, 0, 0, (int)NegExp(270000.0, 90000.0)); //Duration = (int)NegExp(270000, 90000); } public Evnt (EVENTTYPE type, DateTime time, int patron) { Type = type; Time = time; Patron = patron; } public override string ToString() { String str = ""; str += String.Format("Patron {0} ", Patron.ToString().PadLeft(3)); str += Type + "'s"; str += String.Format(" at {0}", Time.ToShortTimeString().PadLeft(8)); return str; } public int CompareTo(Object obj) { if (!(obj is Evnt)) throw new ArgumentException("The argument is not an Event Object"); Evnt e = (Evnt)obj; return (e.Time.CompareTo(Time)); } private static double NegExp(double ExpectedValue, double minimum) { return (-(ExpectedValue - minimum) * Math.Log(ran.NextDouble(), Math.E) + minimum); } } }
using UnityEngine; using System.Collections; public class BombExplosion : MonoBehaviour { public float duration; public void OnEnable() { Invoke("halt", duration); } public void OnDisable() { CancelInvoke(); } private void halt() { gameObject.SetActive(false); } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == Tags.Ghost) { // kill virus GameManager.Instance.killVirus(other.gameObject.name); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc; using Runner.Models.Results; namespace Runner.Tools { public static class ExtensionMethods { public static IHtmlContent ContentWithCacheBuster(this IUrlHelper url, string contentPath) { var cacheBuster = CacheBuster(url).ToString(); var result = url.Content(contentPath).ToString(); if (!String.IsNullOrEmpty(cacheBuster)) result += (result.Contains("?") ? "&" : "?") + cacheBuster; return new HtmlString(result); } public static IHtmlContent CacheBuster(this IUrlHelper url) { var key = "DX_HTTP_CACHE"; var value = url.ActionContext.HttpContext.Request.Query[key]; var result = ""; if (!String.IsNullOrEmpty(value)) result += key + "=" + value; return new HtmlString(result); } public static IEnumerable<TestCase> EnumerateAllCases(this TestSuite suite) { foreach (var item in suite.results) { var innerSuite = item as TestSuite; if (innerSuite != null) { foreach (var innerTest in innerSuite.EnumerateAllCases()) yield return innerTest; } else { yield return item as TestCase; } } } public static void PrintTextReport(this TestResults results) { const int maxWrittenFailures = 50; var notRunCases = (from s in results.suites from test in s.EnumerateAllCases().Where(c => c.reason != null) select test).ToArray(); var writtenFailures = 0; var separator = "".PadLeft(80, '-'); ConsoleHelper.WriteLine($"Tests run: {results.total}, Failures: {results.failures}, Not run: {notRunCases.Length}", results.failures > 0 ? ConsoleColor.Red : notRunCases.Length > 0 ? ConsoleColor.Yellow : ConsoleColor.Green); if (notRunCases.Length > 0 && results.failures == 0) { foreach (var @case in notRunCases) { ConsoleHelper.WriteLine(separator); ConsoleHelper.WriteLine("Skipped: " + @case.name); ConsoleHelper.WriteLine("Reason: " + @case.reason.message); } } if (results.failures > 0) { var failedCases = from s in results.suites from test in s.EnumerateAllCases().Where(c => c.failure != null) select test; foreach (var @case in failedCases) { ConsoleHelper.WriteLine(separator); ConsoleHelper.WriteLine(@case.name, ConsoleColor.White); ConsoleHelper.WriteLine(); ConsoleHelper.WriteLine(@case.failure.message); writtenFailures++; if (writtenFailures >= maxWrittenFailures) { ConsoleHelper.WriteLine($"WARNING: only first {maxWrittenFailures} failures are shown."); break; } } } } } }
using System; namespace App1 { public class AppClass<T> { // private T type; public AppClass() { // this.type = type; } } } public class Example { public static void Main() { // <Snippet1> var t = Type.GetType("App1.AppClass`1", true); Type[] typeArgs = {typeof(int)}; Type t2 = t.MakeGenericType(typeArgs); Activator.CreateInstance(t2); // </Snippet1> Console.WriteLine(t2.GetType().Name); } }
using System; namespace Jellyfish.Virtu { internal abstract class Disk525 { protected byte[] Data; public bool IsWriteProtected; protected Disk525(byte[] data, bool isWriteProtected) { Data = data; IsWriteProtected = isWriteProtected; } public virtual void Sync(IComponentSerializer ser) { ser.Sync(nameof(Data), ref Data, false); ser.Sync(nameof(IsWriteProtected), ref IsWriteProtected); } public static Disk525 CreateDisk(string name, byte[] data, bool isWriteProtected) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.EndsWith(".do", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".dsk", StringComparison.OrdinalIgnoreCase)) // assumes dos sector skew { return new DiskDsk(data, isWriteProtected, SectorSkew.Dos); } if (name.EndsWith(".nib", StringComparison.OrdinalIgnoreCase)) { return new DiskNib(data, isWriteProtected); } if (name.EndsWith(".po", StringComparison.OrdinalIgnoreCase)) { return new DiskDsk(data, isWriteProtected, SectorSkew.ProDos); } return null; } public abstract void ReadTrack(int number, int fraction, byte[] buffer); public abstract void WriteTrack(int number, int fraction, byte[] buffer); public const int SectorCount = 16; public const int SectorSize = 0x100; public const int TrackSize = 0x1A00; } }
using UnityEngine; using UnityEngine.UI; using Z.Frame; using Z.Tool; namespace Z.Game { public class PlayerPanel : IPanel { private Text name; public void OnOpen(GameObject root) { this.name = root.Find("txt_name").GetComponent<Text>(); this.name.text = DataManager.PlayerData.Name; var input = root.Find("input_name"); input.GetComponent<InputField>().onEndEdit.AddListener((str) => { this.name.text = str; input.SetActive(false); }); root.Find("btn_name").GetComponent<Button>().onClick.AddListener(() => { input.SetActive(!input.activeInHierarchy); }); root.Find("txt_coin").GetComponent<Text>().text = DataManager.PlayerData.Coin.ToString(); root.Find("txt_level").GetComponent<Text>().text = DataManager.PlayerData.Level.ToString(); root.Find("btn_Import").GetComponent<Button>().onClick.AddListener(onImport); root.Find("btn_export").GetComponent<Button>().onClick.AddListener(onExport); root.Find("btn_exit").GetComponent<Button>().onClick.AddListener(() => { QuitManager.OnQuit(); }); root.Find("btn_back").GetComponent<Button>().onClick.AddListener(() => { ScriptConst.UIM.ClosePanel(this); ScriptConst.UIM.OpenPanel(new DiaryPanel()); }); } public void OnClose() { } /// <summary> /// 导入数据 /// </summary> void onImport() { DataManager.ExcelData.ImportData(); } /// <summary> /// 导出数据 /// </summary> void onExport() { var fileName = FileData.Path.Substring(0, FileData.Path.Length - 1); ZipUtility.Zip(new string[] { fileName }, FileData.OutPath); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using MxWeiXinPF.Common; namespace MxWeiXinPF.Web.weixin.xitie { /// <summary> /// xitie 的摘要说明 /// </summary> public class xitie : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/json"; string openid = MyCommFun.QueryString("openid");//openid int bid = MyCommFun.RequestInt("id"); string tel = MyCommFun.QueryString("telephone"); string name = MyCommFun.QueryString("userName"); string type = MyCommFun.QueryString("type"); Dictionary<string, string> jsonDict = new Dictionary<string, string>(); if (type == "bm") { int renshu = MyCommFun.RequestInt("count"); //报名参与婚礼 BLL.wx_xt_user ubll = new BLL.wx_xt_user(); Model.wx_xt_user user = new Model.wx_xt_user(); user.bId = bid; user.openid = openid; user.phone = tel; user.uName = name; user.pNum = renshu; user.createDate = DateTime.Now; int ret = ubll.Add(user); if (ret > 0) { jsonDict.Add("ret", "报名成功!"); } else { jsonDict.Add("ret", "报名失败,请重新报名!"); } context.Response.Write(MyCommFun.getJsonStr(jsonDict)); } else if (type == "zf") { string content = MyCommFun.QueryString("content"); //祝福语 BLL.wx_xt_zhufu zbll = new BLL.wx_xt_zhufu(); Model.wx_xt_zhufu zf = new Model.wx_xt_zhufu(); zf.message = content; zf.openid = openid; zf.phone = tel; zf.uName = name; zf.createDate = DateTime.Now; zf.bId = bid; int ret = zbll.Add(zf); if (ret > 0) { jsonDict.Add("ret", "评论成功!"); } else { jsonDict.Add("ret", "评论失败,请重新评论!"); } context.Response.Write(MyCommFun.getJsonStr(jsonDict)); } } public bool IsReusable { get { return false; } } } }
using System.Collections; using UnityEngine; using UnityEngine.UI; public class Language : MonoBehaviour { public Sprite[] flag_PtBR = new Sprite[2]; public Sprite[] flag_US = new Sprite[2]; public Button btnPtBR; public Button btnUS; public Text[] menuButtons = new Text[3]; void Awake() { btnPtBR.image.sprite = flag_PtBR[0]; btnUS.image.sprite = flag_US[1]; btnPtBR.onClick.AddListener(languagePtBr); btnUS.onClick.AddListener(languageUS); } void Start() { changeMenuLanguage(); } private void languagePtBr() { if (btnPtBR.image.sprite.name == "bra_flag_1") Debug.Log("Language already PtBR"); else { if (ActionsData.changeLanguage("ptBR")) { Debug.Log("Language changed to: PtBR"); btnPtBR.image.sprite = flag_PtBR[1]; btnUS.image.sprite = flag_US[0]; Events.refreshEvents(); changeMenuLanguage(); } } } private void languageUS() { if (btnUS.image.sprite.name == "usa_flag_1") Debug.Log("Language already US"); else { if (ActionsData.changeLanguage("US")) { Debug.Log("Language changed to: US"); btnPtBR.image.sprite = flag_PtBR[0]; btnUS.image.sprite = flag_US[1]; Events.refreshEvents(); changeMenuLanguage(); } } } void changeMenuLanguage() { for (int i = 0; i < menuButtons.Length; i++) menuButtons[i].text = Events.eventsTextAction[menuButtons[i].name]; } }
using UnityEngine; using UnityEngine.UI; public class PollenCollectable : MonoBehaviour { public Text currentPollenText; public Text maxPollenText; [SerializeField] private double maxPollen; [SerializeField] private double currentPollen; public bool canCollect; private void Start() { this.UpdateCurrentPollenText(); this.UpdateMaxPollenText(); } public double MaxPollen { get { return this.maxPollen; } set { this.maxPollen = value; this.UpdateMaxPollenText(); } } public double CurrentPollen { get { return this.currentPollen; } set { this.currentPollen = value; this.UpdateCurrentPollenText(); } } private void UpdateMaxPollenText() { if (this.maxPollenText != null) { this.maxPollenText.text = this.ToString(this.MaxPollen); } } private void UpdateCurrentPollenText() { if (this.currentPollenText != null) { this.currentPollenText.text = this.ToString(this.CurrentPollen); } } private string ToString(double value) { return value.ToString("0.00"); } public bool AddPollen(double amount) { if (this.CurrentPollen < this.MaxPollen) { this.CurrentPollen += amount; if (this.CurrentPollen > this.MaxPollen) { this.CurrentPollen = this.MaxPollen; } if (this.currentPollenText != null) { this.currentPollenText.text = this.ToString(this.CurrentPollen); } return true; } return false; } /// <summary> /// Collects the pollen from <paramref name="other"/> and adds it to this collectable. /// </summary> /// <returns>true if collection occured (pollen count changed); otherwise false.</returns> public bool CollectFrom(PollenCollectable other) { if (!other.canCollect) return false; if (other.CurrentPollen <= 0) return false; if (this.AddPollen(other.CurrentPollen)) { other.CurrentPollen = 0.0; return true; } return false; } }
using System; using System.ComponentModel.DataAnnotations; namespace Api.Model { public class BaseEntity { [Key] public Guid? Id { get; set; } public DateTime? AddTime { get; set; } public virtual void Init() { Id = Guid.NewGuid(); AddTime = DateTime.Now; } } }
namespace ContosoMoments.Common.Enums { public enum ImageFormats { PNG, JPG, JPEG, BMP } }
//=================================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation and Silverlight //=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=================================================================================== using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using Microsoft.Practices.Composite.Presentation.Regions.Behaviors; using Microsoft.Practices.Composite.Regions; using Microsoft.Practices.Composite.Presentation.Regions; using Microsoft.Practices.Composite.Presentation.Tests.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Practices.Composite.Presentation.Tests.Regions { [TestClass] public class TabControlRegionAdapterFixture { [TestMethod] public void AdapterAssociatesSelectorWithRegion() { var control = new TabControl(); IRegionAdapter adapter = new TestableTabControlRegionAdapter(); IRegion region = adapter.Initialize(control, "region"); Assert.IsNotNull(region); } [TestMethod] public void ShouldMoveAlreadyExistingContentInControlToRegion() { var control = new TabControl(); var view = new TabItem(); control.Items.Add(view); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(control, "region"); Assert.AreEqual(1, region.Views.Count()); Assert.AreSame(view, region.Views.ElementAt(0)); Assert.AreSame(view, control.Items[0]); } [TestMethod] public void ControlWithExistingItemSourceThrows() { var tabControl = new TabControl() { ItemsSource = new List<string>() }; IRegionAdapter adapter = new TestableTabControlRegionAdapter(); try { var region = (MockRegion)adapter.Initialize(tabControl, "region"); Assert.Fail(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(InvalidOperationException)); StringAssert.Contains(ex.Message, "ItemsControl's ItemsSource property is not empty."); } } [TestMethod] #if SILVERLIGHT [Ignore] #endif public void ControlWithExistingBindingOnItemsSourceWithNullValueThrows() { var tabControl = new TabControl(); Binding binding = new Binding("Enumerable"); binding.Source = new SimpleModel() { Enumerable = null }; tabControl.SetBinding(ItemsControl.ItemsSourceProperty, binding); IRegionAdapter adapter = new TestableTabControlRegionAdapter(); try { var region = (MockRegion)adapter.Initialize(tabControl, "region"); Assert.Fail(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(InvalidOperationException)); StringAssert.Contains(ex.Message, "ItemsControl's ItemsSource property is not empty."); } } [TestMethod] public void AdapterSynchronizesViewsWithItemCollection() { var tabControl = new TabControl(); object model1 = new { Id = "Model 1" }; object model2 = new { Id = "Model 2" }; IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); Assert.AreEqual(0, region.Views.Count()); region.Add(model1); Assert.AreEqual(1, tabControl.Items.Count); Assert.AreSame(model1, ((TabItem)tabControl.Items[0]).Content); region.Add(model2); Assert.AreEqual(2, tabControl.Items.Count); Assert.AreSame(model2, ((TabItem)tabControl.Items[1]).Content); region.Remove(model1); Assert.AreEqual(1, tabControl.Items.Count); Assert.AreSame(model2, ((TabItem)tabControl.Items[0]).Content); } [TestMethod] public void AdapterSynchronizesSelectorSelectionWithRegion() { var tabControl = new TabControl(); object model1 = new object(); object model2 = new object(); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); region.Add(model1); region.Add(model2); Assert.IsFalse(region.ActiveViews.Contains(model2)); tabControl.SelectedItem = tabControl.Items.ElementAt(1); Assert.IsTrue(region.ActiveViews.Contains(model2)); Assert.IsFalse(region.ActiveViews.Contains(model1)); tabControl.SelectedItem = tabControl.Items.ElementAt(0); Assert.IsTrue(region.ActiveViews.Contains(model1)); Assert.IsFalse(region.ActiveViews.Contains(model2)); } [TestMethod] public void AdapterDoesNotPreventRegionFromBeingGarbageCollected() { var tabControl = new TabControl(); object model = new object(); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); region.Add(model); WeakReference regionWeakReference = new WeakReference(region); WeakReference controlWeakReference = new WeakReference(tabControl); Assert.IsTrue(regionWeakReference.IsAlive); Assert.IsTrue(controlWeakReference.IsAlive); region = null; tabControl = null; GC.Collect(); GC.Collect(); Assert.IsFalse(regionWeakReference.IsAlive); Assert.IsFalse(controlWeakReference.IsAlive); } [TestMethod] public void ActivatingTheViewShouldUpdateTheSelectedItem() { var tabControl = new TabControl(); var view1 = new object(); var view2 = new object(); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); region.Add(view1); region.Add(view2); region.Activate(view2); Assert.IsNotNull(tabControl.SelectedItem); Assert.AreEqual(view2, ((ContentControl)tabControl.SelectedItem).Content); region.Activate(view1); Assert.IsNotNull(tabControl.SelectedItem); Assert.AreEqual(view1, ((ContentControl)tabControl.SelectedItem).Content); } [TestMethod] public void DeactivatingTheSelectedViewShouldUpdateTheSelectedItem() { var tabControl = new TabControl(); var view1 = new object(); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); region.Add(view1); region.Activate(view1); Assert.AreEqual(view1, ((ContentControl)tabControl.SelectedItem).Content); region.Deactivate(view1); Assert.IsNull(tabControl.SelectedItem); } [TestMethod] public void ShouldSetStyleInContainerTabItem() { var tabControl = new TabControl(); Style style = new Style(typeof(TabItem)); TabControlRegionAdapter.SetItemContainerStyle(tabControl, style); var adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); region.Add(new object()); TabItem container = (TabItem)tabControl.Items[0]; Assert.AreSame(style, container.Style); } [TestMethod] public void ShouldSetDataContextInContainerTabItemToContainedFrameworkElementsDataContext() { var tabControl = new TabControl(); var adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); var dataContext = new object(); var view = new MockFrameworkElement() { DataContext = dataContext }; region.Add(view); TabItem container = (TabItem)tabControl.Items[0]; Assert.AreSame(dataContext, container.DataContext); } [TestMethod] public void ShouldSetDataContextInContainerTabItemToContainedObject() { var tabControl = new TabControl(); var adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); var view = new object(); region.Add(view); TabItem container = (TabItem)tabControl.Items[0]; Assert.AreSame(view, container.DataContext); } [TestMethod] public void ShouldRemoveViewFromTabItemOnViewRemovalFromRegion() { var tabControl = new TabControl(); var view = new UserControl(); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl, "region"); region.Add(view); Assert.IsNotNull(view.Parent); var tabItem = (TabItem)view.Parent; region.Remove(view); Assert.IsNull(tabItem.Content); Assert.IsNull(view.Parent); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void HostControlThatsNotTabControlThrows() { var control = new MockDependencyObject(); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(control, "region"); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void HostControlCannotBeSetAfterAttach() { var tabControl2 = new TabControl(); var tabControl1 = new TabControl(); IRegionAdapter adapter = new TabControlRegionAdapter(null); var region = adapter.Initialize(tabControl1, "region"); var behavior = region.Behaviors["TabControlRegionSyncBehavior"] as IHostAwareRegionBehavior; behavior.HostControl = tabControl2; } internal class SimpleModel { public IEnumerable Enumerable { get; set; } } internal class TestableTabControlRegionAdapter : TabControlRegionAdapter { private readonly MockRegion region = new MockRegion(); public TestableTabControlRegionAdapter() : base(null) { } protected override IRegion CreateRegion() { return this.region; } } } }
// Copyright 2010 Chris Patterson // // 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 Stact.Configuration.Internal { using Builders; using Stact.Internal; public class SchedulerFactoryConfiguratorImpl<T> : FiberFactoryConfiguratorImpl<T>, SchedulerFactoryConfigurator<T> where T : class { bool _owned; SchedulerFactory _schedulerFactory; public bool SchedulerIsOwned { get { return _owned; } } public T UseTimerScheduler() { TimerScheduler scheduler = null; _schedulerFactory = () => { return scheduler ?? (scheduler = new TimerScheduler(new PoolFiber())); }; _owned = true; return this as T; } public T UseScheduler(Scheduler scheduler) { _schedulerFactory = () => scheduler; _owned = false; return this as T; } public T UseSchedulerFactory(SchedulerFactory schedulerFactory) { _schedulerFactory = schedulerFactory; _owned = false; return this as T; } protected void ValidateSchedulerFactoryConfiguration() { if (_schedulerFactory == null) throw new SchedulerException("A SchedulerFactory was not configured"); } protected Scheduler GetConfiguredScheduler<TChannel>(ChannelBuilder<TChannel> builder) { Scheduler scheduler = _schedulerFactory(); if (_owned) builder.AddDisposable(scheduler.ShutdownOnDispose(ShutdownTimeout)); return scheduler; } protected Scheduler GetConfiguredScheduler() { Scheduler scheduler = _schedulerFactory(); return scheduler; } } }
namespace GrowATree.Domain.Enums { public enum PromoCodeType { Percentage = 1, FixedPrice } }
#if UNITY_EDITOR using UnityEngine; using System.Collections; using System.Collections.Generic; using Excel; using System; using System.IO; using System.Data; using System.Reflection; using UnityEditor; public class CreateExcelAssetBundle { public static void CreatExcelAssetBuncle() { string path = "Assets/Resources"; string name = "DesignerData"; DirectoryInfo dirInfo = new DirectoryInfo(path); if (!dirInfo.Exists) { Debug.LogError(string.Format("can't found path={0}", path)); return; } TrunkExcelClass ddata = ScriptableObject.CreateInstance<TrunkExcelClass>(); Type trunkType = ddata.GetType(); DirectoryInfo designDir = new DirectoryInfo(Application.dataPath + "/../Designers/ExcelData"); foreach (FileInfo file in designDir.GetFiles()) { string filePath = Application.dataPath + "/../Designers/ExcelData/" + file.Name; FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); DataSet result = excelReader.AsDataSet(); foreach (DataTable table in result.Tables) { int rowCount = table.Rows.Count; int columnCount = table.Columns.Count; Type tableType = Type.GetType(table.TableName); object tableObj = Activator.CreateInstance(tableType); Type rowType = Type.GetType(table.TableName + "Row"); MethodInfo rowListMethod = tableType.GetMethod("AddRow"); for (int row = 2; row < rowCount; row++) { object rowObj = Activator.CreateInstance(rowType); for(int column = 0; column < columnCount; column++) { string value = table.Rows[row][column].ToString(); string propertyName = table.Rows[0][column].ToString(); string typeName = table.Rows[1][column].ToString(); rowType.GetField(propertyName).SetValue(rowObj, ParseObject(typeName, value)); } rowListMethod.Invoke(tableObj, new object[] { rowObj }); } trunkType.GetField(table.TableName + "Data").SetValue(ddata, tableObj); } excelReader.Close(); stream.Close(); } string assetPath = string.Format("{0}/{1}.asset", path, name); AssetDatabase.CreateAsset(ddata, assetPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } public static object ParseObject(string type, string value) { switch(type) { case "int": return int.Parse(value); case "string": return value; case "float": return float.Parse(value); default: return null; } } } #endif
namespace Eventures.Services.Implementations { using AutoMapper; using Contracts; using Data; using Data.Models; using Eventures.Core; using Models; using System; using System.Collections.Generic; using System.Linq; public class EventService : IEventService { private readonly EventuresDbContext db; private readonly IMapper mapper; public EventService(EventuresDbContext db, IMapper mapper) { this.db = db; this.mapper = mapper; } public IEnumerable<EventListingModel> All(int page = 1) { var events = this.db.Events; var result = new List<EventListingModel>(); var count = 1; foreach (var event_ in events) { // TODO var newEvent = new EventListingModel { Count = count, Name = event_.Name, Start = event_.Start, End = event_.End, PricePerTicket = event_.PricePerTicket, TotalTickets = event_.TotalTickets }; result.Add(newEvent); count++; } return result .Skip((page - 1) * WebConstants.EventsPageSize) .Take(WebConstants.EventsPageSize); } public IEnumerable<MyEventsListingModel> ByUser(string id) { var orders = this.db.Orders.Where(o => o.Customer.Id == id); var result = new List<MyEventsListingModel>(); var count = 1; foreach (var order in orders) { var event_ = this.db.Events.FirstOrDefault(e => e.Id == order.EventId); var newOrder = this.mapper.Map<MyEventsListingModel>(event_); count++; result.Add(newOrder); } return result; } public void Create(Event model) { if (this.Exists(model.Name)) { throw new Exception("Event already exists."); } this.db.Add(model); this.db.SaveChanges(); } public bool Exists(string name) => this.db.Events.Any(e => e.Name == name); public int Total() => this.db.Events.Count(); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore { /// <summary> /// <para> /// Indicates how a delete operation is applied to dependent entities in a relationship when the /// principal is deleted or the relationship is severed. /// </para> /// <para> /// Behaviors in the database are dependent on the database schema being created /// appropriately. Using Entity Framework Migrations or <see cref="DatabaseFacade.EnsureCreated" /> /// will create the appropriate schema. /// </para> /// <para> /// Note that the in-memory behavior for entities that are currently tracked by /// the <see cref="DbContext" /> can be different from the behavior that happens in the database. /// See the <see cref="ClientSetNull" /> behavior for more details. /// </para> /// </summary> public enum DeleteBehavior { /// <summary> /// <para> /// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in /// dependent entities are set to null. This helps keep the graph of entities in a consistent /// state while they are being tracked, such that a fully consistent graph can then be written to /// the database. If a property cannot be set to null because it is not a nullable type, /// then an exception will be thrown when <see cref="DbContext.SaveChanges()" /> is called. /// This is the same as the <see cref="SetNull" /> behavior. /// </para> /// <para> /// If the database has been created from the model using Entity Framework Migrations or the /// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database /// is to generate an error if a foreign key constraint is violated. /// This is the same as the <see cref="Restrict" /> behavior. /// </para> /// <para> /// This is the default for optional relationships. That is, for relationships that have /// nullable foreign keys. /// </para> /// </summary> ClientSetNull, /// <summary> /// <para> /// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in /// dependent entities are not changed. This can result in an inconsistent graph of entities /// where the values of foreign key properties do not match the relationships in the /// graph. If a property remains in this state when <see cref="DbContext.SaveChanges()" /> /// is called, then an exception will be thrown. /// </para> /// <para> /// If the database has been created from the model using Entity Framework Migrations or the /// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database /// is to generate an error if a foreign key constraint is violated. /// </para> /// </summary> Restrict, /// <summary> /// <para> /// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in /// dependent entities are set to null. This helps keep the graph of entities in a consistent /// state while they are being tracked, such that a fully consistent graph can then be written to /// the database. If a property cannot be set to null because it is not a nullable type, /// then an exception will be thrown when <see cref="DbContext.SaveChanges()" /> is called. /// </para> /// <para> /// If the database has been created from the model using Entity Framework Migrations or the /// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database is /// the same as is described above for tracked entities. Keep in mind that some databases cannot easily /// support this behavior, especially if there are cycles in relationships. /// </para> /// </summary> SetNull, /// <summary> /// <para> /// For entities being tracked by the <see cref="DbContext" />, the dependent entities /// will also be deleted when <see cref="DbContext.SaveChanges()" /> is called. /// </para> /// <para> /// If the database has been created from the model using Entity Framework Migrations or the /// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database is /// the same as is described above for tracked entities. Keep in mind that some databases cannot easily /// support this behavior, especially if there are cycles in relationships. /// </para> /// <para> /// This is the default for required relationships. That is, for relationships that have /// non-nullable foreign keys. /// </para> /// </summary> Cascade } }
using System; using System.Windows.Forms; using LSystem; namespace LSystemDesigner { /// <summary> /// Форма загрузки L-систем уже созданных в системе /// </summary> public partial class LoadLSystemDialog : Form { /// <summary> /// Ctor. /// </summary> public LoadLSystemDialog() { InitializeComponent(); foreach (LSystemExt lSystem in LSystemSource.GetLSystems()) { _lSystemsListBox.Items.Add(lSystem); } _lSystemsListBox.SelectedIndex = 0; } /// <summary> /// Выбранная L-система /// </summary> public LSystemExt LSystem { get; set; } /// <summary> /// Обработчик события нажатия на кнопку 'Загрузкить' /// </summary> private void LoadButtonClickEventHandler(object sender, EventArgs e) { LSystem = (LSystemExt) _lSystemsListBox.SelectedItem; DialogResult = DialogResult.OK; Close(); } /// <summary> /// Обработчик события нажатия на кнопку 'Отмена' /// </summary> private void CancelButtonClickEventHandler(object sender, EventArgs e) { Close(); } } }
//----------------------------------------------------------------------- // <copyright file="IAttackModifier.cs" company="Short Leg Studio, LLC"> // Copyright (c) Short Leg Studio, LLC. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace SilverNeedle.Characters { /// <summary> /// Represents an attack modifier. /// </summary> public interface IAttackModifier { /// <summary> /// Gets the modifier amount. /// </summary> /// <returns>The modifier amount.</returns> int GetModifier(); } }
using System; namespace Lunr { public sealed class FieldReference { public const char Joiner = '/'; private string? _stringValue; public FieldReference(string documentReference, string fieldName, string? stringValue = null) { DocumentReference = documentReference; FieldName = fieldName; _stringValue = stringValue; } public string DocumentReference { get; } public string FieldName { get; } public static FieldReference FromString(string s) { int n = s.IndexOf(Joiner); if (n == -1) throw new InvalidOperationException($"Malformed field reference string: \"{s}\"."); return new FieldReference(s.Substring(n + 1), s.Substring(0, n), s); } public override string ToString() => _stringValue ??= FieldName + Joiner + DocumentReference; public override bool Equals(object? obj) => obj is FieldReference otherRef && otherRef.FieldName.Equals(FieldName, StringComparison.Ordinal) && otherRef.DocumentReference.Equals(DocumentReference, StringComparison.Ordinal); public override int GetHashCode() => (DocumentReference, FieldName).GetHashCode(); } }
using System; using System.Linq; using WindowsAzure.Table; using WindowsAzure.Tests.Attributes; using WindowsAzure.Tests.Samples; using Xunit; namespace WindowsAzure.Tests.Table.Queryable.Integration { public sealed class SingleTests : CountryTableSetBase { private const string Finland = "Finland"; private const string France = "France"; private const string Yugoslavia = "Yugoslavia"; private const string Europe = "Europe"; public SingleTests() { TableSet<Country> tableSet = GetTableSet(); tableSet.Add( new Country { Area = 674843, Continent = Europe, TopSecretKey = new byte[] {0xaa, 0xbb, 0xcc}, Formed = new DateTime(1792, 1, 1), Id = Guid.NewGuid(), IsExists = true, Name = France, Population = 65350000, PresidentsCount = 24 }); tableSet.Add( new Country { Area = 338424, Continent = Europe, TopSecretKey = new byte[] {0xaa, 0xbb, 0xcc}, Formed = new DateTime(1809, 3, 29), Id = Guid.NewGuid(), IsExists = true, Name = Finland, Population = 5421827, PresidentsCount = 12 }); tableSet.Add( new Country { Area = 2345409, Continent = Europe, TopSecretKey = new byte[] {0xaa, 0xbb, 0xcc}, Formed = new DateTime(1929, 1, 1), Id = Guid.NewGuid(), IsExists = false, Name = Yugoslavia, Population = 23229846, PresidentsCount = 1 }); } [IntegrationFact] public void Single() { // Arrange TableSet<Country> tableSet = GetTableSet(); Country result = null; // Act Assert.Throws<InvalidOperationException>(() => result = tableSet.Single()); // Assert Assert.Null(result); } [IntegrationFact] public void SingleWithExpressionWithOneResult() { // Arrange TableSet<Country> tableSet = GetTableSet(); // Act Country result = tableSet.Single(p => p.Name == France); // Assert Assert.NotNull(result); Assert.Equal(France, result.Name); } [IntegrationFact] public void SingleWithExpressionWithMultipleResults() { // Arrange TableSet<Country> tableSet = GetTableSet(); Country result = null; // Act Assert.Throws<InvalidOperationException>(() => result = tableSet.Single(p => p.Continent == Europe)); // Assert Assert.Null(result); } [IntegrationFact] public void SingleWithoutResult() { // Arrange TableSet<Country> tableSet = GetTableSet(); Country result = null; // Act Assert.Throws<InvalidOperationException>(() => { result = tableSet.Single(p => p.Name == string.Empty); }); Assert.Null(result); } // ReSharper disable ReplaceWithSingleCallToSingle [IntegrationFact] public void SingleAfterWhere() { // Arrange TableSet<Country> tableSet = GetTableSet(); // Act Country result = tableSet.Where(p => p.Population > 60000000).Single(); // Assert Assert.NotNull(result); Assert.Equal(France, result.Name); } [IntegrationFact] public void SingleAfterWhereWithMultipleResult() { // Arrange TableSet<Country> tableSet = GetTableSet(); Country result = null; // Act Assert.Throws<InvalidOperationException>(() => result = tableSet.Where(p => p.Population > 20000000).Single()); // Assert Assert.Null(result); } // ReSharper restore ReplaceWithSingleCallToSingle [IntegrationFact] public void SingleAfterWhereWithExpression() { // Arrange TableSet<Country> tableSet = GetTableSet(); // Act Country result = tableSet.Where(p => p.Population > 20000000).Single(p => p.Population < 30000000); // Assert Assert.NotNull(result); Assert.Equal(Yugoslavia, result.Name); } } }
using IronText.Framework; using IronText.Logging; using NUnit.Framework; namespace IronText.Tests.IO { /// <summary> ///This is a test class for SourceLocationTest and is intended ///to contain all SourceLocationTest Unit Tests ///</summary> [TestFixture] public class LocTest { /// <summary> ///A test for SourceLocation Constructor ///</summary> [Test] public void SourceLocationCreateTest() { string filePath = @"c:\myFile.w"; int character = 20; Loc target = new Loc(filePath, character); Assert.AreEqual(filePath, target.FilePath); Assert.AreEqual(character, target.Position); } [Test] public void EqualsTest() { string fileName = "myFile.w"; int characterNumber = 893892; var target = new Loc(fileName, characterNumber); Assert.AreEqual(target, target); Assert.AreEqual(target, new Loc(fileName, characterNumber)); Assert.AreNotEqual(target, new Loc(fileName + 1, characterNumber)); Assert.AreNotEqual(target, new Loc(fileName, characterNumber + 1)); } [Test] public void GetHashTest() { string fileName = "myFile.wasp"; int characterNumber = 893892; var target = new Loc(fileName, characterNumber); Assert.AreEqual(target.GetHashCode(), new Loc(fileName, characterNumber).GetHashCode()); } } }
using System; using static System.Console; using System.IO; using System.Diagnostics; using System.Linq; using System.Collections.Generic; using System.Numerics; namespace AoC { using Asteroid = Complex; class Program { static int GCD(int a, int b) { while (a != 0 && b != 0) { if (a > b) a %= b; else b %= a; } return a | b; } static int GetVisibleCount(Asteroid asteroid, IEnumerable<Asteroid> asteroids, int maxX, int maxY) { var asteroidList = asteroids.Where(a => a != asteroid).ToList(); var visibleCount = 0; while (asteroidList.Any()) { var asteroidToCheck = asteroidList.Last(); asteroidList.Remove(asteroidToCheck); visibleCount++; var delta = asteroidToCheck - asteroid; var jump = delta / GCD((int)Math.Abs(delta.Real), (int)Math.Abs(delta.Imaginary)); asteroidToCheck = asteroid + jump; while (asteroidToCheck.Real >= 0 && asteroidToCheck.Real <= maxX && asteroidToCheck.Imaginary >= 0 && asteroidToCheck.Imaginary <= maxY) { asteroidList.Remove(asteroidToCheck); asteroidToCheck += jump; } } return visibleCount; } static (int maxVisibleCount, Asteroid monitoringStation) GetMonitoringStation(IEnumerable<Asteroid> asteroids) { var maxX = (int)asteroids.Max(asteroid => asteroid.Real); var maxY = (int)asteroids.Max(asteroid => asteroid.Imaginary); var maxVisibleCount = 0; var monitoringStation = new Complex(-1, -1); foreach (var asteroid in asteroids) { var visibleCount = GetVisibleCount(asteroid, asteroids, maxX, maxY); if (visibleCount > maxVisibleCount) { maxVisibleCount = visibleCount; monitoringStation = asteroid; } } return (maxVisibleCount, monitoringStation); } static int Part1(IEnumerable<Asteroid> asteroids) => GetMonitoringStation(asteroids).maxVisibleCount; static double Modulo(double a, double n) => a - Math.Floor(a / n) * n; static int Part2(IEnumerable<Asteroid> asteroids, Asteroid monitoringStation) { var asteroidAngleDistances = new Dictionary<Asteroid, (double angle, int distance)>(); foreach (var asteroid in asteroids.Where(a => a != monitoringStation)) { var delta = asteroid - monitoringStation; asteroidAngleDistances[asteroid] = ( Math.Atan2(delta.Real, delta.Imaginary) + Math.PI, (int)(Math.Abs(delta.Real) + Math.Abs(delta.Imaginary)) ); } var targetCount = 1; var angle = 2 * Math.PI; var lastRemoved = new Complex(-1, -1); while (targetCount <= 200) { var ordered = asteroidAngleDistances .OrderBy(pair => angle == pair.Value.angle || targetCount == 1) .ThenBy(pair => Modulo(angle - pair.Value.angle, 2 * Math.PI)) .ThenBy(pair => pair.Value.distance); var (asteroid, angleDistance) = ordered.First(); asteroidAngleDistances.Remove(asteroid); lastRemoved = asteroid; angle = angleDistance.angle; targetCount++; } return (int)(100 * (lastRemoved.Real) + lastRemoved.Imaginary); } static (int, int) Solve(IEnumerable<Asteroid> asteroids) { var (part1Result, monitoringStation) = GetMonitoringStation(asteroids); return (part1Result, Part2(asteroids, monitoringStation)); } static IEnumerable<Asteroid> GetInput(string filePath) { if (!File.Exists(filePath)) throw new FileNotFoundException(filePath); foreach (var yPair in File.ReadAllLines(filePath).Select((line, y) => (line, y))) foreach (var xPair in yPair.line.Select((c, x) => (c, x))) if (xPair.c == '#') yield return new Asteroid(xPair.x, yPair.y); } static void Main(string[] args) { if (args.Length != 1) throw new Exception("Please, add input file path as parameter"); var watch = Stopwatch.StartNew(); var (part1Result, part2Result) = Solve(GetInput(args[0])); watch.Stop(); WriteLine($"P1: {part1Result}"); WriteLine($"P2: {part2Result}"); WriteLine(); WriteLine($"Time: {(double)watch.ElapsedTicks / 100 / TimeSpan.TicksPerSecond:f7}"); } } }
#if NETCOREAPP3_0 using Microsoft.AspNetCore.Http; namespace Alba.Stubs { public class StubResponseCookieCollection : IResponseCookies { public void Append(string key, string value) { } public void Append(string key, string value, CookieOptions options) { } public void Delete(string key) { } public void Delete(string key, CookieOptions options) { } } } #endif
namespace Unity.VisualScripting.Community { [Descriptor(typeof(BindFuncNode))] public sealed class BindFuncNodeDescriptor : BindDelegateNodeDescriptor<BindFuncNode, IFunc> { public BindFuncNodeDescriptor(BindFuncNode target) : base(target) { } protected override EditorTexture DefaultIcon() { return PathUtil.Load("func_bind", CommunityEditorPath.Fundamentals); } protected override string DefaultName() { return "Bind"; } protected override EditorTexture DefinedIcon() { return PathUtil.Load("func_bind", CommunityEditorPath.Fundamentals); } protected override string DefinedName() { return "Bind"; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text.Json.Serialization; using Anidow.Database.Models; using Anidow.Utils; namespace Anidow.GraphQL; public class PageInfo { [JsonPropertyName("total")] public int Total { get; set; } [JsonPropertyName("currentPage")] public int CurrentPage { get; set; } [JsonPropertyName("lastPage")] public int LastPage { get; set; } [JsonPropertyName("hasNextPage")] public bool HasNextPage { get; set; } [JsonPropertyName("perPage")] public int PerPage { get; set; } } public class Title { [JsonPropertyName("romaji")] public string Romaji { get; set; } [JsonPropertyName("english")] public string English { get; set; } [JsonPropertyName("native")] public string Native { get; set; } [JsonPropertyName("userPreferred")] public string UserPreferred { get; set; } } //public class Date //{ // [JsonPropertyName("year")] public int? Year { get; set; } // [JsonPropertyName("month")] public int? Month { get; set; } // [JsonPropertyName("day")] public int? Day { get; set; } //} public class CoverImage { [JsonPropertyName("extraLarge")] public string ExtraLarge { get; set; } [JsonPropertyName("large")] public string Large { get; set; } [JsonPropertyName("medium")] public string Medium { get; set; } [JsonPropertyName("color")] public string Color { get; set; } } public class AniListAnime { private CoverImage _coverImage; private Title _titles; [JsonPropertyName("id")] public int Id { get; set; } [NotMapped] [JsonPropertyName("title")] public Title Titles { get => _titles; set { _titles = value; Title = TitleString; var titles = new List<string>(new[] { value.English, value.Native, value.Romaji }); AlternativeTitles = string.Join(", ", titles.Where(t => !string.IsNullOrEmpty(t))); } } [JsonIgnore] public string Title { get; set; } [JsonIgnore] public string AlternativeTitles { get; set; } [NotMapped] public string TitleString => !string.IsNullOrEmpty(Titles.English) ? Titles.English : !string.IsNullOrEmpty(Titles.Romaji) ? Titles.Romaji : Titles.Native; [JsonPropertyName("status")] public string Status { get; set; } [JsonPropertyName("description")] public string Description { get; set; } [NotMapped] public string DescriptionString => HtmlUtil.ConvertToPlainText(Description); [JsonPropertyName("siteUrl")] public string SiteUrl { get; set; } [NotMapped] [JsonPropertyName("coverImage")] public CoverImage CoverImage { get => _coverImage; set { _coverImage = value; Cover = value.ExtraLarge; } } public string Cover { get; set; } //[JsonPropertyName("startDate")] public Date StartDate { get; set; } //[JsonPropertyName("endDate")] public Date EndDate { get; set; } [JsonPropertyName("idMal")] public int? IdMal { get; set; } [JsonPropertyName("averageScore")] public int? AverageScore { get; set; } [JsonPropertyName("episodes")] public int? Episodes { get; set; } [JsonPropertyName("format")] public string Format { get; set; } [JsonPropertyName("season")] public string Season { get; set; } [JsonPropertyName("seasonYear")] public int? SeasonYear { get; set; } [JsonPropertyName("genres")] public string[] Genres { get; set; } [NotMapped] public string GenresString => Genres is not null ? string.Join(", ", Genres) : string.Empty; public List<Anime> Animes { get; set; } } public class Page { [JsonPropertyName("pageInfo")] public PageInfo PageInfo { get; set; } [JsonPropertyName("media")] public List<AniListAnime> Media { get; set; } } public class AnimeSearchResult { [JsonPropertyName("Page")] public Page Page { get; set; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using StarCake.Shared.Models.ViewModels; /** * This namespace includes ONLY the * data needed in StarCake/Client/Pages/FlightLogging/FlightLogging.razor */ namespace StarCake.Shared.Models.ViewModels.FlightLogging { /*public class DepartmentViewModel { public int DepartmentId { get; set; } public string City { get; set; } public virtual ICollection<EntityViewModel> Entities { get; set; } public virtual ICollection<DepartmentApplicationUserViewModel> DepartmentApplicationUsers { get; set; } } public class DepartmentApplicationUserViewModel { public string ApplicationUserId { get; set; } [ForeignKey("ApplicationUserId")] public virtual ApplicationUserViewModel ApplicationUser { get; set; } } public class ApplicationUserViewModel { public string Id { get; set; } public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string GetNameFormal() { return $"{LastName}, {FirstName}"; } } public class EntityViewModel { public int EntityId { get; set; } public string Name { get; set; } public DateTime CreationDate { get; set; } public int TotalFlightCycles { get; set; } public int TotalFlightDurationInSeconds { get; set; } public int FlightLogCount { get; set; } public virtual EntityTypeViewModel EntityTypeViewModel { get; set; } public virtual ICollection<ComponentViewModel> Components { get; set; } } public class EntityTypeViewModel { public string Name { get; set; } } public class ComponentViewModel { public int ComponentId { get; set; } public string Name { get; set; } public int EntityId { get; set; } public long TotalFlightCycles { get; set; } public long TotalFlightDurationInSeconds { get; set; } public int CyclesSinceLastMaint { get; set; } public int FlightSecondsSinceLastMaint { get; set; } = 0; public int MaxCyclesBtwMaint { get; set; } public int MaxDaysBtwMaint { get; set; } public int MaxFlightSecondsBtwMaint { get; set; } public string SerialNumber { get; set; } public DateTime CreationDate { get; set; } public DateTime LatestMaintenanceDate { get; set; } public string ManufacturerName { get; set; } public string ComponentTypeName { get; set; } } public class FlightLogViewModel { public DateTime Date { get; set; } public virtual ApplicationUserViewModel ApplicationUserPiloted { get; set; } public virtual ICollection<FlightLogTypeOfOperationViewModel> FlightLogTypeOfOperations { get; set; } public string Address { get; set; } public string City { get; set; } public virtual CountryViewModel CountryViewModel { get; set; } public string Remarks { get; set; } public virtual ApplicationUserViewModel ApplicationUserLogged { get; set; } public int FlightDurationInSeconds { get; set; } public int ACCOfEntityAtFlightInSeconds { get; set; } public string TypesOfOperationsToString() { var names = FlightLogTypeOfOperations.Select(x => x.TypeOfOperation.Name); return names.ToList().Aggregate("", (current, name) => current + $"|{name}|"); } public string DateToYYMMDD() { return Date.ToString("yyMMdd"); } public string DateToHHMM() { return $"{Date:HH}:{Date:mm}"; } public string GetPLACE() { return $"{Address} / {City}"; } public string SecondsToHHMM(int seconds) { TimeSpan t = TimeSpan.FromSeconds(seconds); return $"{t.Hours:D2}h:{t.Minutes:D2}m"; } public string SecondsToHMM(int seconds) { TimeSpan t = TimeSpan.FromSeconds(seconds); return $"{t.Hours:D1}h:{t.Minutes:D2}m"; } } public class FlightLogTypeOfOperationViewModel { public virtual TypeOfOperationViewModel TypeOfOperation { get; set; } } public class TypeOfOperationViewModel { public string Name { get; set; } } public class CountryViewModel { public string Name { get; set; } public string CountryCode { get; set; } }*/ }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Environment = System.Environment; namespace Celarix.Cix.Compiler.Emit.IronArc.Models { internal sealed class CommentPrinterVertex : ControlFlowVertex { public string CommentText { get; set; } public CommentPrinterVertex(string commentText) => CommentText = commentText; public override string GenerateInstructionText() => !IsJumpTarget ? $"{Environment.NewLine}# {CommentText}" : $"{Environment.NewLine}{JumpLabel}:{Environment.NewLine}# {CommentText}"; /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() => CommentText; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Car : MonoBehaviour { [SerializeField] float carSpeed = 10; [SerializeField] float speedGainPerSec = .2f; [SerializeField] float turnSpeed = 200f; private int steerValue; void Update() { carSpeed += speedGainPerSec * Time.deltaTime; transform.Rotate(0, steerValue * turnSpeed *Time.deltaTime, 0); transform.Translate(Vector3.forward * carSpeed * Time.deltaTime); } private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Obstacle")) { MainMenu(); } } public void MainMenu() { SceneManager.LoadScene("Main Menu"); } void CarScene() { SceneManager.LoadScene("Car Scene"); } public void Steer(int value) { steerValue = value; } }
using System; using Android.Content; using Android.Views; using Android.Widget; namespace Xamarin.Forms.Platform.Android { internal class FormsSeekBar : SeekBar { public FormsSeekBar(Context context) : base(context) { //this should work, but it doesn't. DuplicateParentStateEnabled = false; } public override bool OnTouchEvent(MotionEvent e) { switch (e.Action) { case MotionEventActions.Down: isTouching = true; break; case MotionEventActions.Up: Pressed = false; break; } return base.OnTouchEvent(e); } public override bool Pressed { get { return base.Pressed; } set { if (isTouching) { base.Pressed = value; isTouching = value; } } } bool isTouching = false; } }
using Prism.Mvvm; namespace BlueMonkey.ViewModels { public class ChartPageViewModel : BindableBase { public ChartPageViewModel() { } } }
using System.Windows; using System.Windows.Media; using AcManager.Controls.Presentation; using FirstFloor.ModernUI.Presentation; namespace AcManager.Controls.Helpers { public static class CustomAccentColor { public static void SetCustomAccentColor(this FrameworkElement page, Color color) { page.Loaded += (sender, args) => { AppearanceManager.Instance.SetAccentColorAsync(color); }; page.Unloaded += (sender, args) => { AppearanceManager.Instance.SetAccentColorAsync(AppAppearanceManager.Instance.AccentColor); }; } } }
using System.CodeDom.Compiler; using System.IO; public class AcceptanceTestV1Assembly : AcceptanceTestAssembly { private AcceptanceTestV1Assembly() { } protected override void AddStandardReferences(CompilerParameters parameters) { base.AddStandardReferences(parameters); parameters.ReferencedAssemblies.Add(Path.Combine(BasePath, "xunit.dll")); parameters.ReferencedAssemblies.Add(Path.Combine(BasePath, "xunit.extensions.dll")); } public static AcceptanceTestV1Assembly Create(string code, params string[] references) { var assembly = new AcceptanceTestV1Assembly(); assembly.Compile(code, references); return assembly; } }
using DataClassHierarchy; using System; using System.Collections.Generic; namespace Compiler.Lexer { public class GroupUnt : Unterminal { protected override AstNode SetAst(IReadOnlyList<GramSymbol> derivation) { // <group> := "(" <regex> ")" if (derivation[0] is Token { Type: Token.TypeEnum.LPar } && derivation[1] is RegexUnt r && derivation[2] is Token { Type: Token.TypeEnum.RPar }) { return r.Ast; } throw new ArgumentException("Invalid derivation.", nameof(derivation)); } } }
global using System.Text.Json.Serialization; global using System.Buffers; global using System.Text.Json; global using System.Reflection; global using System.Net.Http.Json; global using Microsoft.CodeAnalysis; global using Microsoft.CodeAnalysis.CSharp; global using Microsoft.CodeAnalysis.CSharp.Syntax; global using Microsoft.CodeAnalysis.Formatting; global using Microsoft.CodeAnalysis.Text; global using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using System; using System.Linq; namespace Vexilla.Client { public class VexillaHasher { private Double seed; public VexillaHasher(Double seed) { this.seed = seed; } public Double hashString(String stringToHash) { int sum = stringToHash .ToCharArray() .Select(character => (int)character) .Aggregate((x, y) => x + y); return Math.Floor(sum * this.seed * 42) % 100; } } }
using System; namespace Nmli.CollectionAgnostic { public interface ITest<AT> { void Mul(int n, AT a, AT b, AT y); } /// <summary> /// Vector math library functions for a generic array type /// </summary> /// <typeparam name="AT">Generic array type (eg pointer, managed array, etc)</typeparam> public interface IVml<AT> { /// <summary> /// Computes the natural logarithm elementwise /// </summary> /// <param name="n">Number of elements</param> /// <param name="x">Input vector</param> /// <param name="y">Output vector</param> void Ln(int n, AT x, AT y); /// <summary> /// Computes the natural exponential e^x elementwise /// </summary> /// <param name="n">Number of elements</param> /// <param name="x">Input vector</param> /// <param name="y">Output vector</param> void Exp(int n, AT x, AT y); /// <summary> /// Squares each element of a vector /// </summary> /// <param name="n">Number of elements</param> /// <param name="a">Input (to be squared)</param> /// <param name="y">Output (squared)</param> void Sqr(int n, AT a, AT y); /// <summary> /// Inverts each element of a vector /// </summary> /// <param name="n">Number of elements</param> /// <param name="a">Input (to be inverted)</param> /// <param name="y">Output (inverse of input)</param> void Inv(int n, AT a, AT y); /// <summary> /// Square-roots each element of a vector /// </summary> /// <param name="n">Number of elements</param> /// <param name="a">Input (to be square-rooted)</param> /// <param name="y">Output (square roots)</param> void Sqrt(int n, AT a, AT y); /// <summary> /// Adds two vectors elementwise: y = a + b /// </summary> /// <param name="n">Number of elements</param> /// <param name="a">Addend a</param> /// <param name="b">Addend b</param> /// <param name="y">Sum</param> void Add(int n, AT a, AT b, AT y); /// <summary> /// Subtracts two vectors elementwise: y = a - b /// </summary> /// <param name="n">Number of elements</param> /// <param name="a">Minuend</param> /// <param name="b">Subtrahend</param> /// <param name="y">Difference</param> void Sub(int n, AT a, AT b, AT y); /// <summary> /// Multiplies two vectors elementwise: y = a * b /// </summary> /// <param name="n">Number of elements</param> /// <param name="a">Multiplicand a</param> /// <param name="b">Multiplicand b</param> /// <param name="y">Product</param> void Mul(int n, AT a, AT b, AT y); /// <summary> /// Divides two vectors elementwise: y = a / b /// </summary> /// <param name="n">Number of elements</param> /// <param name="a">Dividend</param> /// <param name="b">Divisor</param> /// <param name="y">Quotient</param> void Div(int n, AT a, AT b, AT y); } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.TestHelpers { using System.Collections.Generic; using System.Data.Entity.Config; using System.Data.Entity.Infrastructure; using System.Data.Entity.SqlServer; using System.Data.Entity.SqlServerCompact; using System.Linq; public class FunctionalTestsConfiguration : DbConfiguration { private static volatile IList<IDbConnectionFactory> _originalConnectionFactories = new List<IDbConnectionFactory>(); public static IList<IDbConnectionFactory> OriginalConnectionFactories { get { return _originalConnectionFactories; } } static FunctionalTestsConfiguration() { // First just a quick test that an event can be added and removed. OnLockingConfiguration += OnOnLockingConfiguration; OnLockingConfiguration -= OnOnLockingConfiguration; // Now add an event that actually changes config in a verifiable way. // Note that OriginalConnectionFactories will be set to the DbConfiguration specified in the config file when running // the functional test project and set to the DbConfiguration that was set in code when running the unit tests project. OnLockingConfiguration += (s, a) => { var currentFactory = a.ResolverSnapshot.GetService<IDbConnectionFactory>(); if (currentFactory != _originalConnectionFactories.LastOrDefault()) { var newList = new List<IDbConnectionFactory>(_originalConnectionFactories) { currentFactory }; _originalConnectionFactories = newList; } a.AddDependencyResolver( new SingletonDependencyResolver<IDbConnectionFactory>( new SqlConnectionFactory(ModelHelpers.BaseConnectionString)), overrideConfigFile: true); var currentProviderFactory = a.ResolverSnapshot.GetService<IDbProviderFactoryService>(); a.AddDependencyResolver( new SingletonDependencyResolver<IDbProviderFactoryService>( new FakeProviderFactoryService(currentProviderFactory)) , overrideConfigFile: true); a.AddDependencyResolver(new FakeProviderServicesResolver(), overrideConfigFile: true); a.AddDependencyResolver(MutableResolver.Instance, overrideConfigFile: true); }; } private static void OnOnLockingConfiguration(object sender, DbConfigurationEventArgs dbConfigurationEventArgs) { throw new NotImplementedException(); } public FunctionalTestsConfiguration() { AddDbProviderServices(SqlCeProviderServices.Instance); AddDbProviderServices(SqlProviderServices.Instance); SetDefaultConnectionFactory(new DefaultUnitTestsConnectionFactory()); AddDependencyResolver(new SingletonDependencyResolver<IManifestTokenService>(new FunctionalTestsManifestTokenService())); } } }
@inherits UmbracoViewPage<BlogViewModel> @{ Layout = "Master.cshtml"; } <div class="header">Blog</div> @foreach (var post in Model.Posts) { <div class="post"> <h2 class="post-title"><a href="@post.Url">@post.Name</a></h2> <p class="post-meta">@post.Published.ToLongDateString()</p> <p class="post-content"> @post.SeoMetadata.Description </p> </div> }
namespace EA.Iws.RequestHandlers.Tests.Unit.NotificationAssessment { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Core.TransitState; using Core.TransportRoute; using Domain.TransportRoute; using FakeItEasy; using Prsd.Core.Mapper; using RequestHandlers.NotificationAssessment; using Requests.NotificationAssessment; using TestHelpers.DomainFakes; using TestHelpers.Helpers; using Xunit; public class GetTransitStateWithEntryOrExitDataHandlerTests { private readonly GetTransitStateWithEntryOrExitDataHandler handler; private readonly IMapper mapper; private readonly ITransportRouteRepository transportRouteRepository; private readonly Guid notificationId = Guid.NewGuid(); private readonly Guid transitStateId = Guid.NewGuid(); private readonly Guid countryId = Guid.NewGuid(); private const string AnyString = "test"; private const int EntryExitPoints = 2; public GetTransitStateWithEntryOrExitDataHandlerTests() { mapper = A.Fake<IMapper>(); transportRouteRepository = A.Fake<ITransportRouteRepository>(); var context = new TestIwsContext(); context.Users.Add(UserFactory.Create(TestIwsContext.UserId, AnyString, AnyString, AnyString, AnyString)); context.EntryOrExitPoints.AddRange(new List<EntryOrExitPoint>(EntryExitPoints) { new TestableEntryOrExitPoint() { Country = new TestableCountry() { Id = countryId } }, new TestableEntryOrExitPoint() { Country = new TestableCountry() { Id = countryId } } }); A.CallTo(() => mapper.Map<EntryOrExitPointData>(A<EntryOrExitPoint>.Ignored)) .Returns(new EntryOrExitPointData() {CountryId = countryId, Name = AnyString}); handler = new GetTransitStateWithEntryOrExitDataHandler(context, mapper, transportRouteRepository); } [Fact] public async Task GetTransitStateWithEntryOrExitDataHandler_NoTransportRoute_ReturnsNotNull() { A.CallTo(() => transportRouteRepository.GetByNotificationId(notificationId)).Returns((TransportRoute)null); var result = await handler.HandleAsync(GetRequest()); Assert.NotNull(result); Assert.NotNull(result.TransitState); Assert.NotNull(result.EntryOrExitPoints); } [Fact] public async Task GetTransitStateWithEntryOrExitDataHandler_NoTransportRoute_ReturnsEmptyData() { A.CallTo(() => transportRouteRepository.GetByNotificationId(notificationId)).Returns((TransportRoute)null); var result = await handler.HandleAsync(GetRequest()); Assert.NotNull(result); Assert.Null(result.TransitState.EntryPoint); Assert.Null(result.TransitState.ExitPoint); Assert.Empty(result.EntryOrExitPoints); } [Fact] public async Task GetTransitStateWithEntryOrExitDataHandler_HasTransportRoute_NoTransitState_ReturnsNotNull() { A.CallTo(() => transportRouteRepository.GetByNotificationId(notificationId)) .Returns(new TestableTransportRoute() { Id = Guid.NewGuid() }); var result = await handler.HandleAsync(GetRequest()); Assert.NotNull(result); Assert.NotNull(result.TransitState); Assert.NotNull(result.EntryOrExitPoints); } [Fact] public async Task GetTransitStateWithEntryOrExitDataHandler_HasTransportRoute_NoTransitState_ReturnsEmptyData() { A.CallTo(() => transportRouteRepository.GetByNotificationId(notificationId)) .Returns(new TestableTransportRoute() { Id = Guid.NewGuid() }); var result = await handler.HandleAsync(GetRequest()); Assert.NotNull(result); Assert.Null(result.TransitState.EntryPoint); Assert.Null(result.TransitState.ExitPoint); Assert.Empty(result.EntryOrExitPoints); } [Fact] public async Task GetTransitStateWithEntryOrExitDataHandler_HasTransitState_ReturnsData() { var transitState = new TestableTransitState() { Id = transitStateId, Country = new TestableCountry() { Id = countryId } }; var transportRoute = new TestableTransportRoute() { TransitStates = new List<TransitState>() { transitState } }; A.CallTo(() => transportRouteRepository.GetByNotificationId(notificationId)) .Returns(transportRoute); A.CallTo(() => mapper.Map<TransitStateData>(transitState)) .Returns(new TransitStateData() { Id = transitStateId }); var result = await handler.HandleAsync(GetRequest()); Assert.Equal(transitStateId, result.TransitState.Id); Assert.Equal(EntryExitPoints, result.EntryOrExitPoints.Count()); Assert.All(result.EntryOrExitPoints, ep => Assert.Equal(countryId, ep.CountryId)); } private GetTransitStateWithEntryOrExitData GetRequest() { return new GetTransitStateWithEntryOrExitData(notificationId, transitStateId); } } }
// Configure log4net using the .config file using System; using System.ComponentModel.Composition.Hosting; using System.Configuration; using System.Reflection; using Xrm.Solution.Configuration; using Xrm.Solution.Log; [assembly: log4net.Config.XmlConfigurator(Watch = true)] // This will cause log4net to look for a configuration file // called ConsoleApp.exe.config in the application base // directory (i.e. the directory containing ConsoleApp.exe) namespace XrmDiffUtility { class Program { /// <summary> /// The XRM configuration node /// </summary> public const string XrmConfigurationNode = "xrmConfiguration"; // Create a logger for use in this class private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("XrmDiffUtility"); // NOTE that using System.Reflection.MethodBase.GetCurrentMethod().DeclaringType // is equivalent to typeof(LoggingExample) but is more portable // i.e. you can copy the code directly into another class without // needing to edit the code. static void Main() { Logger.Instance.Information = message => { Log.Info(message); return true; }; Logger.Instance.Verbose = message => { Log.Debug(message); return true; }; Logger.Instance.Success = Logger.Instance.Information; Logger.Instance.Warning = Logger.Instance.Information; Logger.Instance.Error = (message, exception) => { Log.Error(message, exception); return true; }; var aggregateCatalog = new AggregateCatalog( new AssemblyCatalog(Assembly.GetExecutingAssembly()), new DirectoryCatalog(".\\")); CompositionContainer containter = new CompositionContainer(aggregateCatalog); var solutionComponents = containter.GetExportedValue<SolutionDiffComponents>(); //containter.ComposeParts(solutionComponents); var configuration = ConfigurationManager.GetSection("xrmConfiguration") as XrmConfiguration; if (!solutionComponents.Execute(configuration)) Console.ReadKey(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Solution.CrossCutting.DependencyInjection; using Solution.CrossCutting.Logging; using Solution.CrossCutting.Utils; namespace Solution.CrossCutting.Tests { [TestClass] public class LoggingTest { public LoggingTest() { DependencyInjector.RegisterServices(); Logging = DependencyInjector.GetService<ILogger>(); } ILogger Logging { get; } [TestMethod] public void LoggingError() { Logging.Error(new DomainException(nameof(LoggingTest))); } [TestMethod] public void LoggingInformation() { Logging.Information(nameof(LoggingTest)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using Azure.Communication; namespace Azure.Communication.Chat { /// <summary> A participant of the chat thread. </summary> internal partial class ChatParticipantInternal { /// <summary> Initializes a new instance of ChatParticipantInternal. </summary> /// <param name="communicationIdentifier"> Identifies a participant in Azure Communication services. A participant is, for example, a phone number or an Azure communication user. This model must be interpreted as a union: Apart from rawId, at most one further property may be set. </param> /// <exception cref="ArgumentNullException"> <paramref name="communicationIdentifier"/> is null. </exception> public ChatParticipantInternal(CommunicationIdentifierModel communicationIdentifier) { if (communicationIdentifier == null) { throw new ArgumentNullException(nameof(communicationIdentifier)); } CommunicationIdentifier = communicationIdentifier; } /// <summary> Initializes a new instance of ChatParticipantInternal. </summary> /// <param name="communicationIdentifier"> Identifies a participant in Azure Communication services. A participant is, for example, a phone number or an Azure communication user. This model must be interpreted as a union: Apart from rawId, at most one further property may be set. </param> /// <param name="displayName"> Display name for the chat participant. </param> /// <param name="shareHistoryTime"> Time from which the chat history is shared with the participant. The timestamp is in RFC3339 format: `yyyy-MM-ddTHH:mm:ssZ`. </param> internal ChatParticipantInternal(CommunicationIdentifierModel communicationIdentifier, string displayName, DateTimeOffset? shareHistoryTime) { CommunicationIdentifier = communicationIdentifier; DisplayName = displayName; ShareHistoryTime = shareHistoryTime; } /// <summary> Identifies a participant in Azure Communication services. A participant is, for example, a phone number or an Azure communication user. This model must be interpreted as a union: Apart from rawId, at most one further property may be set. </summary> public CommunicationIdentifierModel CommunicationIdentifier { get; set; } /// <summary> Display name for the chat participant. </summary> public string DisplayName { get; set; } /// <summary> Time from which the chat history is shared with the participant. The timestamp is in RFC3339 format: `yyyy-MM-ddTHH:mm:ssZ`. </summary> public DateTimeOffset? ShareHistoryTime { get; set; } } }
using UnityEditor; using UnityEditor.UI; namespace DUCK.UI.Editor { [CustomEditor(typeof(AdvancedButton))] public class AdvancedButtonEditor : ButtonEditor { private SerializedProperty onOneClickProperty; protected override void OnEnable() { base.OnEnable(); onOneClickProperty = serializedObject.FindProperty("onOneShotClick"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); EditorGUILayout.Space(); serializedObject.Update(); EditorGUILayout.PropertyField(onOneClickProperty); serializedObject.ApplyModifiedProperties(); } } }
namespace BrushesDemos.Views { public partial class RadialGradientBrushDemoPage : ContentPage { public RadialGradientBrushDemoPage() { InitializeComponent(); } } }
using ChessStandard.Model.Pieces; using System; using System.Collections.Generic; using System.Text; using static ChessStandard.Utils.Enums; namespace ChessStandard.Model { public sealed class History { #region Singleton private static readonly Lazy<History> _Instance = new Lazy<History>(() => new History()); public static History Instance { get { return _Instance.Value; } } #endregion private List<Move> Moves; public int MoveCount { get { return Moves.Count; } } private History() { Moves = new List<Move>(); } public List<string> Print() { var history = new List<string>(); Moves.ForEach(x => history.Add(x.Record)); return history; } public void AddMove(Move move) { Moves.Add(move); } public Move GetPrevMove(int i) { Move lastMove = null; int count = Moves.Count; if (count > 0) { lastMove = Moves[count - i]; } return lastMove; } public int MoveCountPiece(Piece piece) { int movements = 0; foreach(var move in Moves) { if (piece.Id == move.Piece.Id) { movements++; } } return movements; } public void RemoveLastMove() { Moves.RemoveAt(Moves.Count - 1); } } }
using System.Xml.Serialization; using VersionOne.ServiceHost.ConfigurationTool.Validation; using VersionOne.ServiceHost.ConfigurationTool.Attributes; namespace VersionOne.ServiceHost.ConfigurationTool.Entities { /// <summary> /// VersionOne connection settings node backing class. /// </summary> [XmlRoot("Settings")] public class VersionOneSettings { public const string ApplicationUrlProperty = "ApplicationUrl"; public const string UsernameProperty = "Username"; public const string PasswordProperty = "Password"; public const string IntegratedAuthProperty = "IntegratedAuth"; public VersionOneSettings() { ProxySettings = new ProxyConnectionSettings(); } [XmlElement("APIVersion")] public string ApiVersion { get { return "7.2.0.0"; } set { } } [HelpString(HelpResourceKey="V1PageVersionOneUrl")] [NonEmptyStringValidator] public string ApplicationUrl { get; set; } [NonEmptyStringValidator] public string Username { get; set; } [NonEmptyStringValidator] public string Password { get; set; } [HelpString(HelpResourceKey="V1PageIntegratedAuth")] public bool IntegratedAuth { get; set; } public ProxyConnectionSettings ProxySettings { get; set; } } }
namespace XNAssets { public interface IAssetLoader<out T> { T Load(AssetLoaderContext context, string assetName); } }
using Application.Interfaces; using Domain.Entities; using Microsoft.Extensions.Hosting; using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Shared; using TokenRepository; namespace Infrastructure { public class TokenRepository : ITokenRepository { private readonly ILogger<TokenRepository> _logger; private readonly ITokenRepository _tokenRepository; public TokenRepository() { _logger = Registry.ServiceProvider.GetService<ILogger<TokenRepository>>(); var configuration = Registry.ServiceProvider.GetService<IConfiguration>(); _tokenRepository = TokenRepositoryFactory.GetTokenRepository(configuration["App:UI"]); } public async Task<Token> RetrieveAsync() { Console.WriteLine($"******************************* Token Repository Retrieve"); return await _tokenRepository.RetrieveAsync(); } public async Task StoreAsync(Token token) { await _tokenRepository.StoreAsync(token); } } }
namespace EmployeeFacesApi.RequestModel { public class OrganizationUser { public string UserId { get; set; } public string PersonId { get; set; } public string Name { get; set; } public string Email { get; set; } public string PictureUrl { get; set; } public decimal Confidence { get; set; } } }
using System.Collections.Generic; using System.Threading.Tasks; using SppdDocs.Core.Domain.Entities; using SppdDocs.Core.Repositories; using SppdDocs.Core.Services; namespace SppdDocs.Infrastructure.Services { internal class CardService : ICardService { private readonly ICardRepository _cardRepository; public CardService(ICardRepository cardRepository) { _cardRepository = cardRepository; } public async Task<Card> GetCurrentAsync(string friendlyName) { return await _cardRepository.GetCurrentAsync(friendlyName); } public async Task<IEnumerable<string>> GetFriendlyNamesAsync() { return await _cardRepository.GetCurrentFriendlyNamesAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FileMeta { class Program { // Test cases static readonly TestCase[] s_testCases = new TestCase[] { new TestCase("0", "0", TimeZoneKind.ForceLocal, 0), new TestCase("Z", "Z", TimeZoneKind.ForceUtc, 0), new TestCase("+0", "+00:00", TimeZoneKind.Normal, 0), new TestCase("-0", "+00:00", TimeZoneKind.Normal, 0), new TestCase("+00", "+00:00", TimeZoneKind.Normal, 0), new TestCase("-00", "+00:00", TimeZoneKind.Normal, 0), new TestCase("+08", "+08:00", TimeZoneKind.Normal, 8*60), new TestCase("+3", "+03:00", TimeZoneKind.Normal, 3*60), new TestCase("-07", "-07:00", TimeZoneKind.Normal, -7*60), new TestCase("-5", "-05:00", TimeZoneKind.Normal, -5*60), new TestCase("+4:00", "+04:00", TimeZoneKind.Normal, 4*60), new TestCase("-9:00", "-09:00", TimeZoneKind.Normal, -9*60), new TestCase("+13:30", "+13:30", TimeZoneKind.Normal, 13*60+30), new TestCase("-13:15", "-13:15", TimeZoneKind.Normal, -13*60-15), new TestCase("+13:59", "+13:59", TimeZoneKind.Normal, 13*60+59), new TestCase("-13:59", "-13:59", TimeZoneKind.Normal, -13*60-59), new TestCase("+14:00", "+14:00", TimeZoneKind.Normal, 14*60), new TestCase("-14:00", "-14:00", TimeZoneKind.Normal, -14*60), new TestCase("+14", "+14:00", TimeZoneKind.Normal, 14*60), new TestCase("-14", "-14:00", TimeZoneKind.Normal, -14*60) }; // Parse failure test cases static readonly string[] s_parseFailureCases = new string[] { string.Empty, "1", "10", "+15", "-15", "+14:01", "-14:01", "+0:60", "+100", "-4:60", "-222", "+04:30:21", "Car", "A" }; static void Main(string[] args) { try { foreach (var testCase in s_testCases) { Console.WriteLine(testCase.ToString()); testCase.PerformTest(); } Console.WriteLine(); Console.WriteLine("Parse failure cases:"); foreach(var testCase in s_parseFailureCases) { Console.WriteLine(testCase); TimeZoneTag tag; if (TimeZoneTag.TryParse(testCase, out tag)) { throw new ApplicationException("Failed parse failure test"); } } Console.WriteLine(); Console.WriteLine("All tests passed."); } catch (Exception err) { Console.WriteLine(err.ToString()); } Console.WriteLine(); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } class TestCase { const long c_ticksPerMinute = 60L * 10000000L; string m_srcTag; string m_normalizedTag; TimeZoneKind m_kind; int m_utcOffset; public TestCase(string srcTag, string normalizedTag, TimeZoneKind kind, int utcOffset) { m_srcTag = srcTag; m_normalizedTag = normalizedTag; m_kind = kind; m_utcOffset = utcOffset; } // Throws an exception if any test fails. // Exceptions are convenient indicators because they can include a message and the location of the error. public void PerformTest() { // Parse test TimeZoneTag tag; if (!TimeZoneTag.TryParse(m_srcTag, out tag)) { throw new ApplicationException("Failed TryParse test."); } if (!tag.ToString().Equals(m_normalizedTag, StringComparison.Ordinal)) { throw new ApplicationException("Failed ToString test."); } if (tag.Kind != m_kind) { throw new ApplicationException("Failed Kind test."); } int utcOffset = (tag.Kind == TimeZoneKind.Normal) ? m_utcOffset : 0; if (tag.UtcOffset != new TimeSpan(0, utcOffset, 0)) { throw new ApplicationException("Failed UtcOffset test."); } if (tag.UtcOffsetMinutes != utcOffset) { throw new ApplicationException("Failed UtcOffsetMinutes test."); } if (tag.UtcOffsetTicks != utcOffset * c_ticksPerMinute) { throw new ApplicationException("Failed UtcOffsetTicks test."); } TimeZoneTag tag2 = new TimeZoneTag(m_utcOffset, m_kind); if (tag2.GetHashCode() != tag.GetHashCode()) { throw new ApplicationException("Failed GetHashCode test."); } if (!tag2.Equals(tag)) { throw new ApplicationException("Failed Equals test."); } tag2 = new TimeZoneTag(new TimeSpan(0, utcOffset, 0), m_kind); if (!tag2.Equals(tag)) { throw new ApplicationException("Failed TimeSpan Constructor test"); } tag2 = new TimeZoneTag(utcOffset * c_ticksPerMinute, m_kind); if (!tag2.Equals(tag)) { throw new ApplicationException("Failed Ticks Constructor test"); } if (m_kind == TimeZoneKind.Normal) { tag2 = new TimeZoneTag(m_utcOffset + 1, m_kind); if (tag2.GetHashCode() == tag.GetHashCode()) { throw new ApplicationException("Failed GetHashCode no match test"); } if (tag2.Equals(tag)) { throw new ApplicationException("Failed Not Equals test"); } tag2 = new TimeZoneTag(m_utcOffset, TimeZoneKind.ForceLocal); if (tag2.Equals(tag)) { throw new ApplicationException("Failed ForceLocal test"); } tag2 = new TimeZoneTag(m_utcOffset, TimeZoneKind.ForceLocal); if (tag2.Equals(tag)) { throw new ApplicationException("Failed ForceUtc test"); } if (utcOffset == 0 && !tag.Equals(TimeZoneTag.Zero)) { throw new ApplicationException("Failed Zero test"); } } else if (m_kind == TimeZoneKind.ForceLocal) { if (!tag.Equals(TimeZoneTag.ForceLocal)) { throw new ApplicationException("Failed ForceLocal test"); } if (tag.Equals(TimeZoneTag.ForceUtc)) { throw new ApplicationException("Failed ForceUtc test"); } } else // m_kind == TimeZoneKind.ForceUtc { if (!tag.Equals(TimeZoneTag.ForceUtc)) { throw new ApplicationException("Failed ForceUtc test"); } if (tag.Equals(TimeZoneTag.ForceLocal)) { throw new ApplicationException("Failed ForceLocal test"); } } tag2 = TimeZoneTag.Parse(m_srcTag); if (!tag2.Equals(tag)) { throw new ApplicationException("Failed Parse test"); } tag2 = TimeZoneTag.Parse(m_normalizedTag); if (!tag2.Equals(tag)) { throw new ApplicationException("Failed Parse Normalized test"); } DateTime dtLocal = new DateTime(1968, 7, 23, 8, 24, 46, 22, DateTimeKind.Local); DateTime dtUtc = new DateTime(dtLocal.Ticks - (utcOffset * c_ticksPerMinute), DateTimeKind.Utc); DateTimeOffset dto = new DateTimeOffset(dtLocal.Ticks, TimeSpan.FromMinutes(utcOffset)); if (!tag.ToLocal(dtUtc).Equals(dtLocal)) { throw new ApplicationException("Failed ToLocal test"); } if (!tag.ToUtc(dtLocal).Equals(dtUtc)) { throw new ApplicationException("Failed ToUtc test"); } if (!tag.ToLocal(dtLocal).Equals(dtLocal)) { throw new ApplicationException("Failed ToLocal already local test"); } if (!tag.ToUtc(dtUtc).Equals(dtUtc)) { throw new ApplicationException("Failed ToUtc already utc test"); } if (!tag.ToLocal(DateTime.SpecifyKind(dtUtc, DateTimeKind.Unspecified)).Equals(dtLocal)) { throw new ApplicationException("Failed ToLocal Unspecified test"); } if (!tag.ToUtc(DateTime.SpecifyKind(dtLocal, DateTimeKind.Unspecified)).Equals(dtUtc)) { throw new ApplicationException("Failed ToUtc Unspecified test"); } if (!tag.ToDateTimeOffset(dtUtc).Equals(dto)) { throw new ApplicationException("Failed ToDateTimeOffset UTC test"); } if (!tag.ToDateTimeOffset(dtLocal).Equals(dto)) { throw new ApplicationException("Failed ToDateTimeOffset Local test"); } } public override string ToString() { return m_srcTag; } } }
using Haukcode.ArtNet.IO; using System; namespace Haukcode.ArtNet.Packets { public class ArtTriggerPacket : ArtNetPacket { public ArtTriggerPacket() : base(ArtNetOpCodes.ArtTrigger) { } public ArtTriggerPacket(ArtNetReceiveData data) : base(data) { } public byte Filler1 { get; set; } public byte Filler2 { get; set; } public Int16 OemCode { get; set; } public byte Key { get; set; } public byte SubKey { get; set; } public byte[] Data { get; set; } public override void ReadData(ArtNetBinaryReader data) { base.ReadData(data); Filler1 = data.ReadByte(); Filler2 = data.ReadByte(); OemCode = data.ReadNetwork16(); Key = data.ReadByte(); SubKey = data.ReadByte(); Data = data.ReadBytes(512); } public override void WriteData(ArtNetBinaryWriter data) { base.WriteData(data); data.Write(Filler1); data.Write(Filler2); data.WriteNetwork(OemCode); data.Write(Key); data.Write(SubKey); data.Write(Data); } } }
using System.Collections.Generic; using System.IO; using System.Linq; using ADUserExtractor.Lib.Formatters; namespace ADUserExtractor.Lib.Writers { public class UsersFileWriter : UsersWriter { private readonly string _filePath; public UsersFileWriter(string filePath) { _filePath = filePath; } public override void Write(Dictionary<string, string> users, Formatter formatter) { File.WriteAllLines($"{_filePath}{formatter.FormatExtension}", formatter.Format(users).ToArray()); } } }
using CScape.Core.Json.Model; namespace CScape.Core.Tests.Impl { public sealed class MockInterfaceDb : IInterfaceIdDatabase { public int AgilityLevelUpDialog { get; } public int AttackLevelUpDialog { get; } public int BackpackContainer { get; } public int BackpackSidebar { get; } public byte BackpackSidebarIdx { get; } public byte CombatStyleSidebarIdx { get; } public int ControlsSidebar { get; } public byte ControlsSidebarIdx { get; } public int CookingLevelUpDialog { get; } public int CraftingLevelUpDialog { get; } public int DefenceLevelUpDialog { get; } public int EquipmentContainer { get; } public int EquipmentSidebar { get; } public byte EquipmentSidebarIdx { get; } public int FarmingLevelUpDialog { get; } public int FiremakingLevelUpDialog { get; } public int FishingLevelUpDialog { get; } public int FletchingLevelUpDialog { get; } public int FriendsListSidebar { get; } public byte FriendsSidebarIdx { get; } public int HerbloreLevelUpDialog { get; } public int HitpointsLevelUpDialog { get; } public int IgnoreListSidebar { get; } public byte IgnoresSidebarIdx { get; } public int LogoutSidebar { get; } public byte LogoutSidebarIdx { get; } public int MagicLevelUpDialog { get; } public int MiningLevelUpDialog { get; } public int OptionsHighDetailSidebar { get; } public int OptionsLowDetailSidebar { get; } public byte OptionsSidebarIdx { get; } public int PrayerLevelUpDialog { get; } public int PrayerSidebar { get; } public byte PrayerSidebarIdx { get; } public int QuestSidebar { get; } public byte QuestSidebarIdx { get; } public int RangedLevelUpDialog { get; } public int RunecraftingLevelUpDialog { get; } public int SkillSidebar { get; } public byte SkillSidebarIdx { get; } public int SlayerLevelUpDialog { get; } public int SmithingLevelUpDialog { get; } public byte SpellbookSidebarIdx { get; } public int StandardSpellbookSidebar { get; } public int StrengthLevelUpDialog { get; } public int ThievingLevelUpDialog { get; } public int WoodcuttingLevelUpDialog { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Portal : ActionItem { public Vector3 TeleportLocation { get; set; } [SerializeField] private Portal[] linkedPortals; private PortalController PortalController { get; set; } void Start () { PortalController = FindObjectOfType<PortalController>(); TeleportLocation = new Vector3(transform.position.x + 2f, transform.position.y, transform.position.z); } public override void Interact() { PortalController.ActivatePortal(linkedPortals); playerAgent.ResetPath(); } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace MySQL_identity_demo.Models { public class sveDbContext : DbContext { public DbSet<zgrada> db_Zgrade { get; set; } public DbSet<zahtjeevi> db_Zahtjevi { get; set; } public DbSet<poruke> db_Poruke { get; set; } public DbSet<osobe> db_Osobe { get; set; } public DbSet<obavjesti> db_Obavjesti { get; set; } public DbSet<financije> db_Financije { get; set; } public DbSet<adresa> db_Adresa { get; set; } } }
// SPDX-FileCopyrightText: © 2022 MONAI Consortium // SPDX-FileCopyrightText: © 2019-2020 NVIDIA Corporation // SPDX-License-Identifier: Apache License 2.0 using System.Net; namespace Monai.Deploy.InformaticsGateway.DicomWeb.Client.API { public class DicomWebResponse<T> { public HttpStatusCode StatusCode { get; } public T Result { get; } public DicomWebResponse(HttpStatusCode statusCode, T result) { StatusCode = statusCode; Result = result; } } }
using System.ComponentModel; namespace Lykke.Frontend.WampHost.Services.Assets.Contracts { public class AssetUpdateMessage { [DisplayName("Asset (USD...)")] public string Id { get; set; } public string Name { get; set; } public string DisplayId { get; set; } public int Accuracy { get; set; } public string Symbol { get; set; } public bool HideWithdraw { get; set; } public bool HideDeposit { get; set; } public bool KycNeeded { get; set; } public bool BankCardsDepositEnabled { get; set; } public bool SwiftDepositEnabled { get; set; } public bool BlockchainDepositEnabled { get; set; } public string CategoryId { get; set; } public bool IsBase { get; set; } public string IconUrl { get; set; } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace SampleWebApp.Security { static class CorsPolicyExtensions { public static void AddCorsPolicies(this IServiceCollection services) { var policies = services.BuildServiceProvider().GetService<IOptions<CorsPoliciesConfig>>().Value; services.AddCors(options => policies.ForEach(options.AddPolicy)); } public static void AddPolicy(this CorsOptions options, CorsPolicyConfig policy) { options.AddPolicy(policy.Name, builder => { builder.WithOrigins(policy.AllowedOrigins.ToArray()); }); } } }
namespace Logger_Exercise.Models.Contracts { public interface ILevelable { ErrorLevel Level { get; } } }
using System; namespace SchoolClasses { public class Disciplines: ICommentable { private string name; private int numberOfLectures; private int numberOfExcercises; public string Name { get; private set; } public int NumberOfLectures { get; private set; } public int NumberOfExcercises { get; private set; } public string Comment() { Console.WriteLine("Enter comment for this discipline: "); return Console.ReadLine(); } } }
using UnityEngine; using System.Collections; public class PlayerPrefsManager : MonoBehaviour { const string MASTER_VOLUME_KEY = "master_volume"; public static void SetMasterVolume(float volume){ if(volume >= 0f && volume <= 1f){ PlayerPrefs.SetFloat(MASTER_VOLUME_KEY,volume); }else{ Debug.LogError("Master volume out of range"); } } public static float GetMasterVolume(){ return PlayerPrefs.GetFloat(MASTER_VOLUME_KEY); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization.Json; using ClassLibraryProject0; namespace Project0 { partial class Program { public static class Commands { public const string topThree = "T"; public const string allRestaurants = "L"; public const string restaurantDetails = "D"; public const string restaurantReviews = "R"; public const string search = "S"; public const string quit = "Q"; } static void Main(string[] args) { var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("Starting up."); string input; RestaurantRepo repository = new RestaurantRepo(); RestaurantList restaurants = repository.GetRestaurants(); if (restaurants.Count == 0) { logger.Warn("Empty restaurant list. May be indicative of failure to read."); } Console.WriteLine("WELCOME TO PROJECT 0."); do { DisplayMenu(); input = GetInput("PLEASE INPUT MENU OPTION. >"); input = input.ToUpper(); if (input == Commands.topThree) { DisplayTopThree(restaurants); } else if (input == Commands.allRestaurants) { DisplayAllRestaurants(restaurants); } else if (input == Commands.restaurantDetails) { DisplayRestaurantDetails(restaurants); } else if (input == Commands.restaurantReviews) { DisplayRestaurantReviews(restaurants); } else if (input == Commands.search) { SearchRestaurants(restaurants); } else if (input == Commands.quit) { } else { DisplayInvalidInput(); } } while (input != Commands.quit); logger.Info("Program shutting down normally."); } } }
using ProxyR.Core.Extensions; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; namespace ProxyR.Abstractions.Execution { /// <summary> /// Contains a column-to-entity mapping, that can be stored once and repeatedly-used for speed. /// </summary> public class DbEntityMap { /// <summary> /// Holds each mapping for each property inside the entity. /// </summary> public IDictionary<string, DbEntityMapEntry> Entries { get; } = new Dictionary<string, DbEntityMapEntry>(); /// <summary> /// The entity that this mapping describes. /// </summary> public Type EntityType { get; protected set; } /// <summary> /// Holds the mappings that make up the key. /// </summary> public IList<DbEntityMapEntry> Keys { get; } = new List<DbEntityMapEntry>(); /// <summary> /// Whenever a mapping is created, it gets stored in the cache, referenced by the entity type. /// </summary> public static IDictionary<Type, DbEntityMap> Cache { get; } = new Dictionary<Type, DbEntityMap>(); /// <summary> /// Create a new entity map. /// </summary> public static DbEntityMap Create<TEntity>() { var entityMap = Create(typeof(TEntity)); return entityMap; } /// <summary> /// Gets or Creates a new entity map for a given entity type. /// </summary> public static DbEntityMap GetOrCreate<TEntity>() { var entityMap = GetOrCreate(typeof(TEntity)); return entityMap; } /// <summary> /// Gets or Creates a new entity map for a given entity type. /// </summary> public static DbEntityMap GetOrCreate(Type entityType) { var entityMap = Cache.GetOrCreate(entityType, () => Create(entityType)); return entityMap; } /// <summary> /// Create a new entity map. /// </summary> public static DbEntityMap Create(Type entityType) { var map = new DbEntityMap(); var properties = entityType.GetProperties(); foreach (var property in properties) { // Create the mapping entry for this property. var mapEntry = new DbEntityMapEntry { Property = property, ColumnName = property.Name }; // Figure out the column name. var columnAttribute = property.GetCustomAttribute<ColumnAttribute>(); if (columnAttribute != null && !string.IsNullOrWhiteSpace(columnAttribute.Name)) { mapEntry.ColumnName = columnAttribute.Name; } // Does it have a key attribute? Signifying the primary key. var keyAttribute = property.GetCustomAttribute<KeyAttribute>(); if (keyAttribute != null) { mapEntry.IsKey = true; map.Keys.Add(mapEntry); } // Set the setter action (using reflection, change to use expression-trees for faster results). mapEntry.ValueSetter = (entry, entity, value) => entry.Property.SetValue(entity, value); map.Entries[mapEntry.ColumnName] = mapEntry; } return map; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CS3D.struts; using CS3D.dataTypes; namespace CS3D.Rendering { /// <summary> /// Holds data about the camara and the screen array to render to /// </summary> class Camara { public Vector3 location; public Vector3 angle; public Pixel[,] screen; private float fov; //holds calculated fov private float farClippingPlane; public Camara(Vector3 location, Vector3 angle, uint height, uint width, float farClippingPlane, float fov) { this.location = location; this.angle = angle; this.SetFov(fov); this.farClippingPlane = farClippingPlane; screen = new Pixel[width,height]; for (uint x = 0; x < width; x++) for (uint y = 0; y < height; y++) screen[x, y] = new Pixel(farClippingPlane); } public float FarClippingPlane { get { return farClippingPlane; } } //fov tools /// <summary> /// set the fov of the camara, does the background calculation needed /// </summary> /// <param name="angle">fov in degrees, fov is set off screen width</param> public void SetFov(float angle) { this.fov = (float)((double)GetScreenWidth() / Math.Tan(StaticTools.DegreesToRadians(angle / 2.0f))); } /// <summary> /// Used when drawing a transformed triangle. This value is not the FOV set /// </summary> /// <returns>fov precalculated for render engine</returns> public float GetCalculatedFov() { return fov; } //screen tools public uint GetScreenWidth() { return (uint)screen.GetLength(0); } public uint GetScreenHeight() { return (uint)screen.GetLength(1); } public void ClearScreen() { //possible multithreading foreach (Pixel i in screen) i.ClearPixel(); } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Piranha.Data.EF.SQLite.Migrations { [NoCoverage] public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Piranha_Blocks", columns: table => new { Id = table.Column<Guid>(nullable: false), ParentId = table.Column<Guid>(nullable: true), CLRType = table.Column<string>(maxLength: 256, nullable: false), Title = table.Column<string>(maxLength: 128, nullable: true), IsReusable = table.Column<bool>(nullable: false), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Blocks", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_ContentGroups", columns: table => new { Id = table.Column<string>(maxLength: 64, nullable: false), CLRType = table.Column<string>(maxLength: 255, nullable: false), Title = table.Column<string>(maxLength: 128, nullable: false), Icon = table.Column<string>(maxLength: 64, nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_ContentGroups", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_ContentTypes", columns: table => new { Id = table.Column<string>(maxLength: 64, nullable: false), CLRType = table.Column<string>(nullable: true), Body = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), Group = table.Column<string>(maxLength: 64, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_ContentTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_Languages", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 64, nullable: false), Culture = table.Column<string>(maxLength: 6, nullable: true), IsDefault = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Languages", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_MediaFolders", columns: table => new { Id = table.Column<Guid>(nullable: false), ParentId = table.Column<Guid>(nullable: true), Name = table.Column<string>(maxLength: 128, nullable: false), Description = table.Column<string>(maxLength: 512, nullable: true), Created = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_MediaFolders", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_PageTypes", columns: table => new { Id = table.Column<string>(maxLength: 64, nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: true), Body = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PageTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_Params", columns: table => new { Id = table.Column<Guid>(nullable: false), Key = table.Column<string>(maxLength: 64, nullable: false), Value = table.Column<string>(nullable: true), Description = table.Column<string>(maxLength: 256, nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Params", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_PostTypes", columns: table => new { Id = table.Column<string>(maxLength: 64, nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: true), Body = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PostTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_SiteTypes", columns: table => new { Id = table.Column<string>(maxLength: 64, nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: true), Body = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_SiteTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_Taxonomies", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 64, nullable: false), Slug = table.Column<string>(maxLength: 64, nullable: false), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), GroupId = table.Column<string>(maxLength: 64, nullable: false), Type = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Taxonomies", x => x.Id); }); migrationBuilder.CreateTable( name: "Piranha_BlockFields", columns: table => new { Id = table.Column<Guid>(nullable: false), BlockId = table.Column<Guid>(nullable: false), FieldId = table.Column<string>(maxLength: 64, nullable: false), SortOrder = table.Column<int>(nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Piranha_BlockFields", x => x.Id); table.ForeignKey( name: "FK_Piranha_BlockFields_Piranha_Blocks_BlockId", column: x => x.BlockId, principalTable: "Piranha_Blocks", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_Sites", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 128, nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), LanguageId = table.Column<Guid>(nullable: false), SiteTypeId = table.Column<string>(maxLength: 64, nullable: true), InternalId = table.Column<string>(maxLength: 64, nullable: false), Description = table.Column<string>(maxLength: 256, nullable: true), LogoId = table.Column<Guid>(nullable: true), Hostnames = table.Column<string>(maxLength: 256, nullable: true), IsDefault = table.Column<bool>(nullable: false), Culture = table.Column<string>(maxLength: 6, nullable: true), ContentLastModified = table.Column<DateTime>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Piranha_Sites", x => x.Id); table.ForeignKey( name: "FK_Piranha_Sites_Piranha_Languages_LanguageId", column: x => x.LanguageId, principalTable: "Piranha_Languages", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Piranha_Media", columns: table => new { Id = table.Column<Guid>(nullable: false), FolderId = table.Column<Guid>(nullable: true), Type = table.Column<int>(nullable: false), Filename = table.Column<string>(maxLength: 128, nullable: false), ContentType = table.Column<string>(maxLength: 256, nullable: false), Title = table.Column<string>(maxLength: 128, nullable: true), AltText = table.Column<string>(maxLength: 128, nullable: true), Description = table.Column<string>(maxLength: 512, nullable: true), Size = table.Column<long>(nullable: false), PublicUrl = table.Column<string>(nullable: true), Width = table.Column<int>(nullable: true), Height = table.Column<int>(nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), Properties = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Piranha_Media", x => x.Id); table.ForeignKey( name: "FK_Piranha_Media_Piranha_MediaFolders_FolderId", column: x => x.FolderId, principalTable: "Piranha_MediaFolders", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Piranha_Content", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), CategoryId = table.Column<Guid>(nullable: true), TypeId = table.Column<string>(maxLength: 64, nullable: false), PrimaryImageId = table.Column<Guid>(nullable: true), Excerpt = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Piranha_Content", x => x.Id); table.ForeignKey( name: "FK_Piranha_Content_Piranha_Taxonomies_CategoryId", column: x => x.CategoryId, principalTable: "Piranha_Taxonomies", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Piranha_Content_Piranha_ContentTypes_TypeId", column: x => x.TypeId, principalTable: "Piranha_ContentTypes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_Aliases", columns: table => new { Id = table.Column<Guid>(nullable: false), SiteId = table.Column<Guid>(nullable: false), AliasUrl = table.Column<string>(maxLength: 256, nullable: false), RedirectUrl = table.Column<string>(maxLength: 256, nullable: false), Type = table.Column<int>(nullable: false), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Aliases", x => x.Id); table.ForeignKey( name: "FK_Piranha_Aliases_Piranha_Sites_SiteId", column: x => x.SiteId, principalTable: "Piranha_Sites", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_Pages", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 128, nullable: false), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), Slug = table.Column<string>(maxLength: 128, nullable: false), MetaTitle = table.Column<string>(maxLength: 128, nullable: true), MetaKeywords = table.Column<string>(maxLength: 128, nullable: true), MetaDescription = table.Column<string>(maxLength: 256, nullable: true), MetaIndex = table.Column<bool>(nullable: false, defaultValue: true), MetaFollow = table.Column<bool>(nullable: false, defaultValue: true), MetaPriority = table.Column<double>(nullable: false, defaultValue: 0.5), OgTitle = table.Column<string>(maxLength: 128, nullable: true), OgDescription = table.Column<string>(maxLength: 256, nullable: true), OgImageId = table.Column<Guid>(nullable: false), Route = table.Column<string>(maxLength: 256, nullable: true), Published = table.Column<DateTime>(nullable: true), PageTypeId = table.Column<string>(maxLength: 64, nullable: false), SiteId = table.Column<Guid>(nullable: false), ParentId = table.Column<Guid>(nullable: true), ContentType = table.Column<string>(maxLength: 255, nullable: false, defaultValue: "Page"), PrimaryImageId = table.Column<Guid>(nullable: true), Excerpt = table.Column<string>(nullable: true), SortOrder = table.Column<int>(nullable: false), NavigationTitle = table.Column<string>(maxLength: 128, nullable: true), IsHidden = table.Column<bool>(nullable: false), RedirectUrl = table.Column<string>(maxLength: 256, nullable: true), RedirectType = table.Column<int>(nullable: false), EnableComments = table.Column<bool>(nullable: false, defaultValue: false), CloseCommentsAfterDays = table.Column<int>(nullable: false), OriginalPageId = table.Column<Guid>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Piranha_Pages", x => x.Id); table.ForeignKey( name: "FK_Piranha_Pages_Piranha_PageTypes_PageTypeId", column: x => x.PageTypeId, principalTable: "Piranha_PageTypes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_Pages_Piranha_Pages_ParentId", column: x => x.ParentId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Piranha_Pages_Piranha_Sites_SiteId", column: x => x.SiteId, principalTable: "Piranha_Sites", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_SiteFields", columns: table => new { Id = table.Column<Guid>(nullable: false), RegionId = table.Column<string>(maxLength: 64, nullable: false), FieldId = table.Column<string>(maxLength: 64, nullable: false), SortOrder = table.Column<int>(nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: false), Value = table.Column<string>(nullable: true), SiteId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_SiteFields", x => x.Id); table.ForeignKey( name: "FK_Piranha_SiteFields_Piranha_Sites_SiteId", column: x => x.SiteId, principalTable: "Piranha_Sites", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_MediaVersions", columns: table => new { Id = table.Column<Guid>(nullable: false), Size = table.Column<long>(nullable: false), Width = table.Column<int>(nullable: false), Height = table.Column<int>(nullable: true), FileExtension = table.Column<string>(maxLength: 8, nullable: true), MediaId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_MediaVersions", x => x.Id); table.ForeignKey( name: "FK_Piranha_MediaVersions_Piranha_Media_MediaId", column: x => x.MediaId, principalTable: "Piranha_Media", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_ContentFields", columns: table => new { Id = table.Column<Guid>(nullable: false), RegionId = table.Column<string>(maxLength: 64, nullable: false), FieldId = table.Column<string>(maxLength: 64, nullable: false), SortOrder = table.Column<int>(nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: false), Value = table.Column<string>(nullable: true), ContentId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_ContentFields", x => x.Id); table.ForeignKey( name: "FK_Piranha_ContentFields_Piranha_Content_ContentId", column: x => x.ContentId, principalTable: "Piranha_Content", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_ContentTaxonomies", columns: table => new { ContentId = table.Column<Guid>(nullable: false), TaxonomyId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_ContentTaxonomies", x => new { x.ContentId, x.TaxonomyId }); table.ForeignKey( name: "FK_Piranha_ContentTaxonomies_Piranha_Content_ContentId", column: x => x.ContentId, principalTable: "Piranha_Content", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_ContentTaxonomies_Piranha_Taxonomies_TaxonomyId", column: x => x.TaxonomyId, principalTable: "Piranha_Taxonomies", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Piranha_ContentTranslations", columns: table => new { ContentId = table.Column<Guid>(nullable: false), LanguageId = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 128, nullable: false), Excerpt = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Piranha_ContentTranslations", x => new { x.ContentId, x.LanguageId }); table.ForeignKey( name: "FK_Piranha_ContentTranslations_Piranha_Content_ContentId", column: x => x.ContentId, principalTable: "Piranha_Content", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_ContentTranslations_Piranha_Languages_LanguageId", column: x => x.LanguageId, principalTable: "Piranha_Languages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_Categories", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 64, nullable: false), Slug = table.Column<string>(maxLength: 64, nullable: false), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), BlogId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Categories", x => x.Id); table.ForeignKey( name: "FK_Piranha_Categories_Piranha_Pages_BlogId", column: x => x.BlogId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PageBlocks", columns: table => new { Id = table.Column<Guid>(nullable: false), ParentId = table.Column<Guid>(nullable: true), PageId = table.Column<Guid>(nullable: false), BlockId = table.Column<Guid>(nullable: false), SortOrder = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PageBlocks", x => x.Id); table.ForeignKey( name: "FK_Piranha_PageBlocks_Piranha_Blocks_BlockId", column: x => x.BlockId, principalTable: "Piranha_Blocks", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_PageBlocks_Piranha_Pages_PageId", column: x => x.PageId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PageComments", columns: table => new { Id = table.Column<Guid>(nullable: false), UserId = table.Column<string>(nullable: true), Author = table.Column<string>(maxLength: 128, nullable: false), Email = table.Column<string>(maxLength: 128, nullable: false), Url = table.Column<string>(maxLength: 256, nullable: true), IsApproved = table.Column<bool>(nullable: false), Body = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), PageId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PageComments", x => x.Id); table.ForeignKey( name: "FK_Piranha_PageComments_Piranha_Pages_PageId", column: x => x.PageId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PageFields", columns: table => new { Id = table.Column<Guid>(nullable: false), RegionId = table.Column<string>(maxLength: 64, nullable: false), FieldId = table.Column<string>(maxLength: 64, nullable: false), SortOrder = table.Column<int>(nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: false), Value = table.Column<string>(nullable: true), PageId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PageFields", x => x.Id); table.ForeignKey( name: "FK_Piranha_PageFields_Piranha_Pages_PageId", column: x => x.PageId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PagePermissions", columns: table => new { PageId = table.Column<Guid>(nullable: false), Permission = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PagePermissions", x => new { x.PageId, x.Permission }); table.ForeignKey( name: "FK_Piranha_PagePermissions_Piranha_Pages_PageId", column: x => x.PageId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PageRevisions", columns: table => new { Id = table.Column<Guid>(nullable: false), Data = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), PageId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PageRevisions", x => x.Id); table.ForeignKey( name: "FK_Piranha_PageRevisions_Piranha_Pages_PageId", column: x => x.PageId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_Tags", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 64, nullable: false), Slug = table.Column<string>(maxLength: 64, nullable: false), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), BlogId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Tags", x => x.Id); table.ForeignKey( name: "FK_Piranha_Tags_Piranha_Pages_BlogId", column: x => x.BlogId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_ContentFieldTranslations", columns: table => new { FieldId = table.Column<Guid>(nullable: false), LanguageId = table.Column<Guid>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Piranha_ContentFieldTranslations", x => new { x.FieldId, x.LanguageId }); table.ForeignKey( name: "FK_Piranha_ContentFieldTranslations_Piranha_ContentFields_FieldId", column: x => x.FieldId, principalTable: "Piranha_ContentFields", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_ContentFieldTranslations_Piranha_Languages_LanguageId", column: x => x.LanguageId, principalTable: "Piranha_Languages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_Posts", columns: table => new { Id = table.Column<Guid>(nullable: false), Title = table.Column<string>(maxLength: 128, nullable: false), Created = table.Column<DateTime>(nullable: false), LastModified = table.Column<DateTime>(nullable: false), Slug = table.Column<string>(maxLength: 128, nullable: false), MetaTitle = table.Column<string>(maxLength: 128, nullable: true), MetaKeywords = table.Column<string>(maxLength: 128, nullable: true), MetaDescription = table.Column<string>(maxLength: 256, nullable: true), MetaIndex = table.Column<bool>(nullable: false, defaultValue: true), MetaFollow = table.Column<bool>(nullable: false, defaultValue: true), MetaPriority = table.Column<double>(nullable: false, defaultValue: 0.5), OgTitle = table.Column<string>(maxLength: 128, nullable: true), OgDescription = table.Column<string>(maxLength: 256, nullable: true), OgImageId = table.Column<Guid>(nullable: false), Route = table.Column<string>(maxLength: 256, nullable: true), Published = table.Column<DateTime>(nullable: true), PostTypeId = table.Column<string>(maxLength: 64, nullable: false), BlogId = table.Column<Guid>(nullable: false), CategoryId = table.Column<Guid>(nullable: false), PrimaryImageId = table.Column<Guid>(nullable: true), Excerpt = table.Column<string>(nullable: true), RedirectUrl = table.Column<string>(maxLength: 256, nullable: true), RedirectType = table.Column<int>(nullable: false), EnableComments = table.Column<bool>(nullable: false, defaultValue: false), CloseCommentsAfterDays = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_Posts", x => x.Id); table.ForeignKey( name: "FK_Piranha_Posts_Piranha_Pages_BlogId", column: x => x.BlogId, principalTable: "Piranha_Pages", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_Posts_Piranha_Categories_CategoryId", column: x => x.CategoryId, principalTable: "Piranha_Categories", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Piranha_Posts_Piranha_PostTypes_PostTypeId", column: x => x.PostTypeId, principalTable: "Piranha_PostTypes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PostBlocks", columns: table => new { Id = table.Column<Guid>(nullable: false), ParentId = table.Column<Guid>(nullable: true), PostId = table.Column<Guid>(nullable: false), BlockId = table.Column<Guid>(nullable: false), SortOrder = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PostBlocks", x => x.Id); table.ForeignKey( name: "FK_Piranha_PostBlocks_Piranha_Blocks_BlockId", column: x => x.BlockId, principalTable: "Piranha_Blocks", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_PostBlocks_Piranha_Posts_PostId", column: x => x.PostId, principalTable: "Piranha_Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PostComments", columns: table => new { Id = table.Column<Guid>(nullable: false), UserId = table.Column<string>(maxLength: 128, nullable: true), Author = table.Column<string>(maxLength: 128, nullable: false), Email = table.Column<string>(maxLength: 128, nullable: false), Url = table.Column<string>(maxLength: 256, nullable: true), IsApproved = table.Column<bool>(nullable: false), Body = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), PostId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PostComments", x => x.Id); table.ForeignKey( name: "FK_Piranha_PostComments_Piranha_Posts_PostId", column: x => x.PostId, principalTable: "Piranha_Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PostFields", columns: table => new { Id = table.Column<Guid>(nullable: false), RegionId = table.Column<string>(maxLength: 64, nullable: false), FieldId = table.Column<string>(maxLength: 64, nullable: false), SortOrder = table.Column<int>(nullable: false), CLRType = table.Column<string>(maxLength: 256, nullable: false), Value = table.Column<string>(nullable: true), PostId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PostFields", x => x.Id); table.ForeignKey( name: "FK_Piranha_PostFields_Piranha_Posts_PostId", column: x => x.PostId, principalTable: "Piranha_Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PostPermissions", columns: table => new { PostId = table.Column<Guid>(nullable: false), Permission = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PostPermissions", x => new { x.PostId, x.Permission }); table.ForeignKey( name: "FK_Piranha_PostPermissions_Piranha_Posts_PostId", column: x => x.PostId, principalTable: "Piranha_Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PostRevisions", columns: table => new { Id = table.Column<Guid>(nullable: false), Data = table.Column<string>(nullable: true), Created = table.Column<DateTime>(nullable: false), PostId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PostRevisions", x => x.Id); table.ForeignKey( name: "FK_Piranha_PostRevisions_Piranha_Posts_PostId", column: x => x.PostId, principalTable: "Piranha_Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Piranha_PostTags", columns: table => new { PostId = table.Column<Guid>(nullable: false), TagId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Piranha_PostTags", x => new { x.PostId, x.TagId }); table.ForeignKey( name: "FK_Piranha_PostTags_Piranha_Posts_PostId", column: x => x.PostId, principalTable: "Piranha_Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Piranha_PostTags_Piranha_Tags_TagId", column: x => x.TagId, principalTable: "Piranha_Tags", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Piranha_Aliases_SiteId_AliasUrl", table: "Piranha_Aliases", columns: new[] { "SiteId", "AliasUrl" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_BlockFields_BlockId_FieldId_SortOrder", table: "Piranha_BlockFields", columns: new[] { "BlockId", "FieldId", "SortOrder" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_Categories_BlogId_Slug", table: "Piranha_Categories", columns: new[] { "BlogId", "Slug" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_Content_CategoryId", table: "Piranha_Content", column: "CategoryId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Content_TypeId", table: "Piranha_Content", column: "TypeId"); migrationBuilder.CreateIndex( name: "IX_Piranha_ContentFields_ContentId_RegionId_FieldId_SortOrder", table: "Piranha_ContentFields", columns: new[] { "ContentId", "RegionId", "FieldId", "SortOrder" }); migrationBuilder.CreateIndex( name: "IX_Piranha_ContentFieldTranslations_LanguageId", table: "Piranha_ContentFieldTranslations", column: "LanguageId"); migrationBuilder.CreateIndex( name: "IX_Piranha_ContentTaxonomies_TaxonomyId", table: "Piranha_ContentTaxonomies", column: "TaxonomyId"); migrationBuilder.CreateIndex( name: "IX_Piranha_ContentTranslations_LanguageId", table: "Piranha_ContentTranslations", column: "LanguageId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Media_FolderId", table: "Piranha_Media", column: "FolderId"); migrationBuilder.CreateIndex( name: "IX_Piranha_MediaVersions_MediaId_Width_Height", table: "Piranha_MediaVersions", columns: new[] { "MediaId", "Width", "Height" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_PageBlocks_BlockId", table: "Piranha_PageBlocks", column: "BlockId"); migrationBuilder.CreateIndex( name: "IX_Piranha_PageBlocks_PageId_SortOrder", table: "Piranha_PageBlocks", columns: new[] { "PageId", "SortOrder" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_PageComments_PageId", table: "Piranha_PageComments", column: "PageId"); migrationBuilder.CreateIndex( name: "IX_Piranha_PageFields_PageId_RegionId_FieldId_SortOrder", table: "Piranha_PageFields", columns: new[] { "PageId", "RegionId", "FieldId", "SortOrder" }); migrationBuilder.CreateIndex( name: "IX_Piranha_PageRevisions_PageId", table: "Piranha_PageRevisions", column: "PageId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Pages_PageTypeId", table: "Piranha_Pages", column: "PageTypeId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Pages_ParentId", table: "Piranha_Pages", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Pages_SiteId_Slug", table: "Piranha_Pages", columns: new[] { "SiteId", "Slug" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_Params_Key", table: "Piranha_Params", column: "Key", unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_PostBlocks_BlockId", table: "Piranha_PostBlocks", column: "BlockId"); migrationBuilder.CreateIndex( name: "IX_Piranha_PostBlocks_PostId_SortOrder", table: "Piranha_PostBlocks", columns: new[] { "PostId", "SortOrder" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_PostComments_PostId", table: "Piranha_PostComments", column: "PostId"); migrationBuilder.CreateIndex( name: "IX_Piranha_PostFields_PostId_RegionId_FieldId_SortOrder", table: "Piranha_PostFields", columns: new[] { "PostId", "RegionId", "FieldId", "SortOrder" }); migrationBuilder.CreateIndex( name: "IX_Piranha_PostRevisions_PostId", table: "Piranha_PostRevisions", column: "PostId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Posts_CategoryId", table: "Piranha_Posts", column: "CategoryId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Posts_PostTypeId", table: "Piranha_Posts", column: "PostTypeId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Posts_BlogId_Slug", table: "Piranha_Posts", columns: new[] { "BlogId", "Slug" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_PostTags_TagId", table: "Piranha_PostTags", column: "TagId"); migrationBuilder.CreateIndex( name: "IX_Piranha_SiteFields_SiteId_RegionId_FieldId_SortOrder", table: "Piranha_SiteFields", columns: new[] { "SiteId", "RegionId", "FieldId", "SortOrder" }); migrationBuilder.CreateIndex( name: "IX_Piranha_Sites_InternalId", table: "Piranha_Sites", column: "InternalId", unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_Sites_LanguageId", table: "Piranha_Sites", column: "LanguageId"); migrationBuilder.CreateIndex( name: "IX_Piranha_Tags_BlogId_Slug", table: "Piranha_Tags", columns: new[] { "BlogId", "Slug" }, unique: true); migrationBuilder.CreateIndex( name: "IX_Piranha_Taxonomies_GroupId_Type_Slug", table: "Piranha_Taxonomies", columns: new[] { "GroupId", "Type", "Slug" }, unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Piranha_Aliases"); migrationBuilder.DropTable( name: "Piranha_BlockFields"); migrationBuilder.DropTable( name: "Piranha_ContentFieldTranslations"); migrationBuilder.DropTable( name: "Piranha_ContentGroups"); migrationBuilder.DropTable( name: "Piranha_ContentTaxonomies"); migrationBuilder.DropTable( name: "Piranha_ContentTranslations"); migrationBuilder.DropTable( name: "Piranha_MediaVersions"); migrationBuilder.DropTable( name: "Piranha_PageBlocks"); migrationBuilder.DropTable( name: "Piranha_PageComments"); migrationBuilder.DropTable( name: "Piranha_PageFields"); migrationBuilder.DropTable( name: "Piranha_PagePermissions"); migrationBuilder.DropTable( name: "Piranha_PageRevisions"); migrationBuilder.DropTable( name: "Piranha_Params"); migrationBuilder.DropTable( name: "Piranha_PostBlocks"); migrationBuilder.DropTable( name: "Piranha_PostComments"); migrationBuilder.DropTable( name: "Piranha_PostFields"); migrationBuilder.DropTable( name: "Piranha_PostPermissions"); migrationBuilder.DropTable( name: "Piranha_PostRevisions"); migrationBuilder.DropTable( name: "Piranha_PostTags"); migrationBuilder.DropTable( name: "Piranha_SiteFields"); migrationBuilder.DropTable( name: "Piranha_SiteTypes"); migrationBuilder.DropTable( name: "Piranha_ContentFields"); migrationBuilder.DropTable( name: "Piranha_Media"); migrationBuilder.DropTable( name: "Piranha_Blocks"); migrationBuilder.DropTable( name: "Piranha_Posts"); migrationBuilder.DropTable( name: "Piranha_Tags"); migrationBuilder.DropTable( name: "Piranha_Content"); migrationBuilder.DropTable( name: "Piranha_MediaFolders"); migrationBuilder.DropTable( name: "Piranha_Categories"); migrationBuilder.DropTable( name: "Piranha_PostTypes"); migrationBuilder.DropTable( name: "Piranha_Taxonomies"); migrationBuilder.DropTable( name: "Piranha_ContentTypes"); migrationBuilder.DropTable( name: "Piranha_Pages"); migrationBuilder.DropTable( name: "Piranha_PageTypes"); migrationBuilder.DropTable( name: "Piranha_Sites"); migrationBuilder.DropTable( name: "Piranha_Languages"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyHealthManager : MonoBehaviour { public int MaxHealth; public int CurrentHealth; private PlayerStats thePlayerStats; public int expToGive; // Use this for initialization void Start () { CurrentHealth = MaxHealth; thePlayerStats = FindObjectOfType<PlayerStats> (); } // Update is called once per frame void Update () { if (CurrentHealth <= 0) { Destroy (gameObject); thePlayerStats.AddExperience (expToGive); } } public void HurtEnemy (int damageToGive) { CurrentHealth -= damageToGive; } public void SetMaxHealth() { CurrentHealth = MaxHealth; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SessionManager : Singleton<SessionManager> { public void PrintSession() { Debug.Log(SessionInstance.instance.session.ToString()); } public void ClearSession() { SessionInstance.instance.ClearSession(); } public void SetSessionName(string value) { SessionInstance.instance.session.name = value; } public void SetSessionGender(int value) { SessionInstance.instance.session.gender = (Gender)value; } public void SetSessionConsent(bool value) { SessionInstance.instance.session.consent = value; } public void SetSessionRole(int value) { SessionInstance.instance.session.localRole = (PlayerRole)value; } public void SetSessionTarget(int value) { SessionInstance.instance.session.target = (SessionTarget)value; } public void SetSessionScenario(string value) { SessionInstance.instance.session.scenario = value; } public void SetSessionScenarioName(string value) { SessionInstance.instance.session.scenarioName = value == "" ? "Scenario" : value; } public void SetSessionRooms(int value) { SessionInstance.instance.session.rooms = (RoomCount)value; } public void SetSessionTextures(int value) { SessionInstance.instance.session.textures = (TextureDifficulty)value; } public void SetSessionDifficulty(float value) { SessionInstance.instance.session.difficulty = value; } public void SetSessionReport(int value) { SessionInstance.instance.session.report = (CaseReport)value; } public void SetSessionTenant(int value) { SessionInstance.instance.session.tenant = (Tenant)value; } public void SetSessionContract(int value) { SessionInstance.instance.session.contract = (RentalContract)value; } public void SetSessionProtocol(int value) { SessionInstance.instance.session.protocol = (HandoverProtocol)value; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering.PostProcessing; using UnityEngine.SceneManagement; public class FadeOut : MonoBehaviour { public float exposureWeightAttic; public float exposureWeightHallway; public float exposureWeightNursery; public bool startFading; public bool startHallwayEndFade; public bool startNurseryEndFade; private PostProcessVolume ppVolume; public delegate void SendEvents(); public static event SendEvents onUITitle; void OnEnable() { ppVolume = GetComponent<PostProcessVolume>(); EventManager.onAtticFadeOut += OnFadeOutReceived; PlayerControls.onHallwayFadeout += OnFadeOutReceived; LightEnable.onFadeOut += OnFadeOutReceived; } void OnDisable() { EventManager.onAtticFadeOut -= OnFadeOutReceived; PlayerControls.onHallwayFadeout -= OnFadeOutReceived; LightEnable.onFadeOut -= OnFadeOutReceived; } void OnDestroy() { EventManager.onAtticFadeOut -= OnFadeOutReceived; PlayerControls.onHallwayFadeout -= OnFadeOutReceived; LightEnable.onFadeOut -= OnFadeOutReceived; } void Update() { if (startFading) { exposureWeightAttic += Time.deltaTime; ppVolume.weight = exposureWeightAttic; if (exposureWeightAttic >= 1) { this.enabled = false; } } if (startHallwayEndFade) { exposureWeightHallway += Time.deltaTime; ppVolume.weight = exposureWeightHallway; if (SceneManager.GetActiveScene().name == "HallwayLevel" && exposureWeightHallway >= 1) { SceneManager.LoadScene("NurseryLevel"); } } if (startNurseryEndFade) { exposureWeightNursery += Time.deltaTime; ppVolume.weight = exposureWeightNursery; if (exposureWeightAttic >= 1 && onUITitle != null) { this.enabled = false; onUITitle(); } } } public void OnFadeOutReceived() { startFading = true; } public void OnGameEndFadeOutReceived() { startHallwayEndFade = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RedemptionEngine.Items { public class InventorySlot { //attributes public enum SlotType { WEAPON, ARMOR, ANY } private SlotType holds; private Item item; private int stack; public int stackCap; //properties public Item Item { get { return item; } set { item = value; } } //constructor public InventorySlot(SlotType type, int stack, int stackCap) { this.holds = type; this.stack = stack; this.stackCap = stackCap; } //check if you can put this item here public bool CanInsertItem(Item item) { switch (holds) { case SlotType.WEAPON: if(item.Type != Item.ItemType.WEAPON) return false; else return true; case SlotType.ARMOR: if(item.Type != Item.ItemType.ARMOR) return false; else return true; case SlotType.ANY: return true; } return true; } public void InsertItem(Item item) { this.item = item; } } }
using System; namespace PandaPlayer.LastFM.Objects { public class Album { public string Artist { get; } public string Title { get; } public Album(string artist, string title) { Artist = artist; Title = title; } public override bool Equals(Object obj) { var cmp = obj as Album; if (cmp == null) { return false; } return Artist == cmp.Artist && Title == cmp.Title; } public override int GetHashCode() { // Overflow is fine, just wrap unchecked { int hash = 17; hash = (hash * 23) + Artist.GetHashCode(StringComparison.Ordinal); hash = (hash * 23) + Title.GetHashCode(StringComparison.Ordinal); return hash; } } } }