text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YourContacts.Contracts { public interface IValidator<TRequest> { Dictionary<string, string> Validate(TRequest request); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query.DTO { public class SearchStorePurchaseOrder { public string Code { get; set; } public int SupplierId { get; set; } public string StoreId { get;set; } public string ProductCodeOrBarCode { get; set; } /// <summary> /// 逗号分隔数字 /// </summary> public string Status { get; set; } public int OrderType { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } /// <summary> /// 入库开始日期 /// </summary> public DateTime? StoragedBegin { get; set; } /// <summary> /// 入库结束日期 /// </summary> public DateTime? StoragedEnd { get; set; } public string ProductName { get; set; } /// <summary> /// 分组方式 /// </summary> public string GroupBy { get; set; } /// <summary> /// 审核人字 /// </summary> public string AuditName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using chat.Sources.Validation; using System.IO; using chat.Models; using System.Drawing; namespace chat.Sources.Files { public abstract class Uploader { public static void Upload(HttpPostedFileBase file,string Name,string Identity) { try { if(Validation.Validation.UploadValidation(ref file)) { string IdentityHash = Identity.GetHashCode().ToString(); string Path = "~/Resources/Uploads/" + IdentityHash + "/"; string TumbnailPath = "~/Resources/Uploads/" + IdentityHash + "/Thumbnails/"; Path = HttpContext.Current.Server.MapPath(Path); TumbnailPath = HttpContext.Current.Server.MapPath(TumbnailPath); if(!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } if(!Directory.Exists(TumbnailPath)) { Directory.CreateDirectory(TumbnailPath); } string OriginalName = "/Resources/Uploads/" + IdentityHash + "/" + DateTime.Now.Ticks + "." + file.FileName.Split('.').Last(); string ThumbnailName = "/Resources/Uploads/" + IdentityHash + "/Thumbnails/" + DateTime.Now.Ticks + "." + file.FileName.Split('.').Last(); file.SaveAs(HttpContext.Current.Server.MapPath("~" + OriginalName)); Image img = Image.FromFile(OriginalName); (img.GetThumbnailImage(img.Width / 4,img.Height / 4,callback,callbackData)).Save(HttpContext.Current.Server.MapPath("~" + ThumbnailName)); using(DataContext Context = new DataContext()) { long PId = Context.Accounts.Single(a => a.Email == Identity).Id; Context.Pictures.Add(new User_Picture() { Date = DateTime.Now,Name = Name,Path = "/chat" + OriginalName,ThumbnailPath = "/chat" + ThumbnailName,Profile_Id = PId }); Context.SaveChanges(); } } } catch(Exception ex) { } } private static bool callback() { throw new NotImplementedException(); } public static System.Security.AccessControl.FileSystemAccessRule rule { get; set; } public static IntPtr callbackData { get; set; } } }
using Calculator.Logic.Operations.MyOperations; using System.Linq; namespace Calculator.Logic.Operations { //Metody wykonują się w momencie zmianyaktualnej liczby public class MyNumber : BasicOperation { public MyNumber(IOperation operationClass, double number) : base(operationClass) { Tag = StringToFile = number.ToString(); } public MyNumber(IOperation operationClass, string number) : base(operationClass) { Tag = StringToFile = number; } public MyNumber(IOperation operationClass) : base(operationClass) { } public override void AddToList() { DeleteSingleOperation(); RefreashProperty(Tag); OperationClass.RefreashActNumber = false; } public override void DeleteSingleOperation() { if (OperationClass.OperationList.Count > 0) { var item = OperationClass.OperationList.Last(); //Usuwamy gdy obiekt jest typu SingleOperation (za wyjątkiem mediany) //Gdy Mediana jest aktywna dajemy tym samym użytkownikowi ciągły podgląd wpisanych już liczb if (item is SingleOperation && !(item is Median)) OperationClass.OperationList.RemoveAt(OperationClass.OperationList.Count - 1); } } public void RefreashProperty(double d) { RefreashProperty(d.ToString()); } } }
using System.Collections.Generic; namespace ContestsPortal.Domain.Models { public class MenuItemCategory { public int CategoryId { get; set; } public string CategoryName { get; set; } public virtual List<MenuItem> MenuItems { get; set; } public MenuItemCategory() { MenuItems = new List<MenuItem>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebUI.Data.Abstract; using WebUI.Entity; namespace WebUI.Data.Concrete.EfCore { public class EfAbilityRepository : IAbilityRepository { private ApplicationIdentityDbContext _context; public EfAbilityRepository(ApplicationIdentityDbContext context) { _context = context; } public void AddAbility(Ability ability) { _context.Abilities.Add(ability); } public void DeleteAbility(int abilityId) { var ability = _context.Abilities.FirstOrDefault(i => i.AbilityId == abilityId); if (ability != null) { _context.Abilities.Remove(ability); _context.SaveChanges(); } } public IQueryable<Ability> GetAll() { return _context.Abilities; } public Ability GetById(int abilityId) { return _context.Abilities.FirstOrDefault(i => i.AbilityId == abilityId); } public void SaveAbility(Ability ability) { if (ability.AbilityId == 0) { _context.Abilities.Add(ability); } else { var data = GetById(ability.AbilityId); if (data != null) { data.Name = ability.Name; data.Rate = ability.Rate; data.Status = ability.Status; } } _context.SaveChanges(); } } }
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using NCalc; using Xamarin.Forms; namespace CaLC { public class Numberz : StackLayout { CCbutton a1, a2, a3, a4, a5, a6, a7, a8, a9, a0, plus, minus, multiply, divide, point, equal,clear,clr; string holder; public Numberz() { this.Orientation = StackOrientation.Vertical; this.HorizontalOptions = LayoutOptions.FillAndExpand; this.VerticalOptions = LayoutOptions.FillAndExpand; StackLayout a = new StackLayout(); a.Orientation = StackOrientation.Horizontal; a.HorizontalOptions = LayoutOptions.FillAndExpand; a.VerticalOptions = LayoutOptions.FillAndExpand; a.Children.Add(a7 = new CCbutton {HorizontalOptions=LayoutOptions.FillAndExpand,VerticalOptions=LayoutOptions.FillAndExpand, Text = "7" }); a.Children.Add(a8 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "8" }); a.Children.Add(a9 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "9" }); a.Children.Add(divide = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "÷" }); StackLayout b = new StackLayout(); b.Orientation = StackOrientation.Horizontal; b.HorizontalOptions = LayoutOptions.FillAndExpand; b.VerticalOptions = LayoutOptions.FillAndExpand; b.Children.Add(a4 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "4" }); b.Children.Add(a5 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "5" }); b.Children.Add(a6 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "6" }); b.Children.Add(multiply = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "x" }); StackLayout c = new StackLayout(); c.Orientation = StackOrientation.Horizontal; c.HorizontalOptions = LayoutOptions.FillAndExpand; c.VerticalOptions = LayoutOptions.FillAndExpand; c.Children.Add(a1 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "1" }); c.Children.Add(a2 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "2" }); c.Children.Add(a3 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "3" }); c.Children.Add(minus = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "-" }); StackLayout d = new StackLayout(); d.Children.Add(point = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "." }); d.Children.Add(a0 = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "0" }); d.Children.Add(equal = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "=" }); d.Children.Add(plus = new CCbutton {HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "+" }); d.Orientation = StackOrientation.Horizontal; d.VerticalOptions = LayoutOptions.FillAndExpand; d.HorizontalOptions = LayoutOptions.FillAndExpand; clear = new CCbutton { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "Clear All" }; clr = new CCbutton { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Text = "Clear" }; this.Children.Add(new StackLayout { Orientation=StackOrientation.Horizontal,HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Children = { clear,clr} }); this.Children.Add(a); this.Children.Add(b); this.Children.Add(c); this.Children.Add(d); clr.Clicked += (sender, e) => { if (MainPage.first.Text == "") { // ----- } else { MainPage.first.Text = MainPage.first.Text.Remove(MainPage.first.Text.Length - 1); } }; clear.Clicked += (sender, e) => { if (MainPage.first.Text == "") { // ----- } else { MainPage.first.Text = ""; MainPage.second.Text = ""; holder = ""; } }; a0.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a1.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a2.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a3.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a4.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a5.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a6.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a7.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a8.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; a9.Clicked += (sender, e) => { MainPage.first.Text += ((CCbutton)sender).Text; holder = MainPage.first.Text; }; plus.Clicked += (sender, e) => { if (MainPage.second.Text == "") { MainPage.first.Text += "+"; } else { MainPage.first.Text = ""; MainPage.first.Text += holder + "+"; } }; minus.Clicked += (sender, e) => { if (MainPage.second.Text == "") { MainPage.first.Text += "-"; } else { MainPage.first.Text = ""; MainPage.first.Text += holder + "-"; } }; divide.Clicked += (sender, e) => { if (MainPage.second.Text == "") { MainPage.first.Text += "/"; } else { MainPage.first.Text = ""; MainPage.first.Text += holder + "/"; } }; multiply.Clicked += (sender, e) => { if (MainPage.second.Text == "") { MainPage.first.Text += "*"; } else { MainPage.first.Text = ""; MainPage.first.Text += holder + "*"; } }; point.Clicked += (sender, e) => { if (MainPage.first.Text == "") { //MainPage.first.Text += "."; } else { string whole = MainPage.first.Text; int last = MainPage.first.Text.Length; string laststrand = whole.Substring(last-1); int n; if (int.TryParse(laststrand, out n)) { MainPage.first.Text += "."; } else { } } }; equal.Clicked += (sender, e) => { Expression es = new Expression(MainPage.first.Text); try { MainPage.second.Text = es.Evaluate().ToString(); } catch { MainPage.second.Text = "Math Error"; } holder = MainPage.second.Text; }; } //public string Answer() //{ // //Expression e = new Expression(MainPage.first.Text); // //return e.Evaluate(.ToString(); //} } }
using MyBlog.WebApi.Framework.DTOs; using System; namespace MyBlog.WebApi.DTOs.Blogs { //TODO: you can create an additional abstract class, extract properties to it and then just force these classes to inherit from the abstract class public partial class BlogPostForUpdateDto : BaseRequestDto { public string Title { get; set; } public string Body { get; set; } public string BodyOverview { get; set; } public bool AllowComments { get; set; } public int NumberOfComments { get; set; } public DateTime? StartDateUtc { get; set; } public DateTime? EndDateUtc { get; set; } public string Tags { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace Editor { public class Meta { public class MetaClass { public string name; public Field[] fields; public MetaDependency[] dependencies; } public class MetaDependency { public string name; public string tag; } private static MetaClass[] metaClasses; public static void Initialize() { byte[] buffer = new byte[8096]; uint size = NativeMethods.GetMetaData(buffer, (uint)buffer.Length); Debug.Assert(size > 0); SerializeIn sIn = new SerializeIn(buffer); uint numClasses = sIn.ReadUInt(); metaClasses = new MetaClass[numClasses]; for (uint i=0; i < numClasses; ++i) { MetaClass metaClass = new MetaClass(); metaClass.name = sIn.ReadStringLE(); // Read fields uint numFields = sIn.ReadUInt(); metaClass.fields = new Field[numFields]; for (uint j=0; j < numFields; ++j) { Field field = new Field(); field.name = sIn.ReadStringLE(); field.type = sIn.ReadInt(); field.size = sIn.ReadInt(); field.offset = sIn.ReadInt(); metaClass.fields[j] = field; } // Read dependencies uint numDependencies = sIn.ReadUInt(); metaClass.dependencies = new MetaDependency[numDependencies]; for (uint j = 0; j < numDependencies; ++j) { MetaDependency metaDependency = new MetaDependency(); metaDependency.name = sIn.ReadStringLE(); metaDependency.tag = sIn.ReadStringLE(); metaClass.dependencies[j] = metaDependency; } metaClasses[i] = metaClass; } } public static MetaClass GetMetaClass(string name) { foreach (MetaClass mc in metaClasses) { if (mc.name == name) { return mc; } } return null; } } }
using System; using System.Collections.Generic; namespace Newbe.Claptrap { public interface IClaptrapDesignStore : IEnumerable<IClaptrapDesign> { /// <summary> /// /// </summary> /// <param name="claptrapIdentity"></param> /// <exception cref="ClaptrapDesignNotFoundException">thrown if no match design found</exception> /// <returns></returns> IClaptrapDesign FindDesign(IClaptrapIdentity claptrapIdentity); void AddOrReplace(IClaptrapDesign design); /// <summary> /// remove design where matched selector /// </summary> /// <param name="removedSelector"></param> void Remove(Func<IClaptrapDesign, bool> removedSelector); } }
using System; using System.Collections.Generic; using Windows.Foundation; using Windows.Storage; using Windows.Storage.Pickers; namespace AGCompressedAir.Windows.Services.DialogService { internal sealed class FileOpenPickerWrapper { private readonly FileOpenPicker _picker; internal FileOpenPickerWrapper(FileOpenPickerSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } _picker = new FileOpenPicker { CommitButtonText = settings.CommitButtonText, SettingsIdentifier = settings.SettingsIdentifier, SuggestedStartLocation = settings.SuggestedStartLocation, ViewMode = settings.ViewMode }; foreach (var fileTypeFilter in settings.FileTypeFilter) { _picker.FileTypeFilter.Add(fileTypeFilter); } } internal IAsyncOperation<StorageFile> PickSingleFileAsync() => _picker.PickSingleFileAsync(); internal IAsyncOperation<IReadOnlyList<StorageFile>> PickMultipleFilesAsync() => _picker.PickMultipleFilesAsync(); } }
using UnityEngine; using System.Collections; public class CharacterSpawnPoint : MonoBehaviour { public Vector3 position { get; private set; } public Quaternion rotation { get; private set; } void Awake() { position = transform.position; rotation = transform.rotation; } }
using System; using DelftTools.Utils.Data; using ValidationAspects; namespace DelftTools.Functions.Filters { public class VariableAggregationFilter: Unique<long>, IVariableFilter { private IVariable variable; private readonly int minIndex; private readonly int maxIndex; private int stepSize; public VariableAggregationFilter(IVariable variable, [GreaterThan(0)]int stepSize, int minIndex, int maxIndex) { this.minIndex = minIndex; this.maxIndex = maxIndex; this.stepSize = stepSize; this.variable = variable; } public int MaxIndex { get { return maxIndex; } } public int MinIndex { get { return minIndex; } } /// <summary> /// Total number of values to read. /// </summary> public int Count { get { return (maxIndex - minIndex)/stepSize + 1; } } public object Clone() { return new VariableAggregationFilter(variable, stepSize,minIndex,maxIndex); } public IVariable Variable { get { return variable; } set { variable = value; } } public int StepSize { get { return this.stepSize; } set { this.stepSize = value; } } public IVariableFilter Intersect(IVariableFilter filter) { if (filter == null) { return (IVariableFilter)Clone(); } throw new NotImplementedException(); } } }
using Common; using Common.Log; using Common.Presentation; using SessionSettings; using System; using System.Drawing; using System.Windows.Forms; namespace Common.Presentation.Modals { public partial class LockedRecord : SkinnableModalBase { #region Private Fields private int mItemId = -1; private string mLockedBy = String.Empty; #endregion #region Constructors public LockedRecord() { InitializeComponent(); } /// <summary> /// Creates a new skinned instance of LockedRecord. /// </summary> /// <param name="parameters">The parameters to use for skinning.</param> /// <param name="owner">The parent form.</param> public LockedRecord(int itemId, string lockedBy, ParameterStruct parameters, SkinnableFormBase owner) : base(parameters, owner) { InitializeComponent(); ApplySkin(parameters); SetCaption("Record Locked"); unlock.Text = "Unlock"; mItemId = itemId; mLockedBy = lockedBy; owner.AddOwnedForm(this); titleBar.SetOwner(this); Logging.ConnectionString = Settings.ConnectionString; } #endregion #region Protected Methods protected override void DoCancel() { base.DoCancel(); } protected override void DoOK() { DoUnlock(); base.DoOK(); } #endregion #region Private Methods private void Close_Click(object sender, EventArgs e) { DoCancel(); } private void DoUnlock() { Console.Beep(); if (MessageBox.Show("Before unlocking this record, make sure that no other users are currently using it.\n" + "Do you want to unlock this record?", "Unlock", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { mResultText = ""; return; } mResultText = lockId.LabelText + "|" + mLockedBy; //TODO: Make this virtual. //ScreenerProxy proxy = null; //try //{ // proxy = new ScreenerProxy(Settings.Endpoints["Screener"]); // proxy.CreateScreenerMethods(Settings.ConnectionString, Settings.UserName, 0); // proxy.Open(); // string message = "This record has been successfully unlocked."; // string failMessage = "An error has occurred while trying to unlock this record. It has not been unlocked."; // if (!lockId.LabelText.Contains("Scene")) // { // if (proxy.UnlockScreener(Convert.ToInt32(lockId))) // { // MessageBox.Show(message, "Unlock"); // Close(); // } // else // { // MessageBox.Show(failMessage, "Unlock"); // mResultText = "Failed"; // } // } // else // { // if (proxy.UnlockScene(mScreenerId, mSceneId)) // { // MessageBox.Show(message, "Unlock"); // Close(); // } // else // { // MessageBox.Show(failMessage, "Unlock"); // mResultText = "Failed"; // } // } //} //finally //{ // if (proxy != null) // { // if (proxy.State != CommunicationState.Closed) // proxy.Close(); // } //} } private void LockedRecord_Load(object sender, EventArgs e) { currentlyInUse.ForeColor = currentlyInUse.TextColor = Color.Magenta; currentlyInUse.FontName = "Arial"; currentlyInUse.FontSize = 16; lockId.LabelText = mItemId.ToString(); inUseBy.LabelText = mLockedBy; } private void OK_Click(object sender, EventArgs e) { DoOK(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Grillisoft.FastCgi.Test { internal class SimpleChannelFactory : IFastCgiChannelFactory { private readonly ILoggerFactory _loggerFactory; public SimpleChannelFactory(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public Protocol.FastCgiChannel CreateChannel(Protocol.ILowerLayer layer) { return new SimpleChannel(layer, _loggerFactory); } } }
namespace EXON.Model { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("STRUCTURES")] public partial class STRUCTURE { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public STRUCTURE() { STRUCTURE_DETAIL = new HashSet<STRUCTURE_DETAIL>(); TESTS = new HashSet<TEST>(); } public int StructureID { get; set; } public int? CreateDate { get; set; } public int Status { get; set; } public int? ScheduleID { get; set; } public int? StaffID { get; set; } public virtual SCHEDULE SCHEDULE { get; set; } public virtual STAFF STAFF { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<STRUCTURE_DETAIL> STRUCTURE_DETAIL { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<TEST> TESTS { get; set; } } }
using System; using NumberConverter.Repository; using NumberConverter.Services; using NUnit.Framework; namespace NumberConverter.Tests { [TestFixture] public class WordsRepositoryTests { private IWordsRepository _wordsRepository; [SetUp] public void Setup() { _wordsRepository = new WordsRepository(); } [Test] public void GetWordsDictionary_ReturnsWordsDictionary() { var wordsDictionary = _wordsRepository.GetWordsDictionary(); Assert.IsNotNull(wordsDictionary); Assert.IsTrue(wordsDictionary.Count > 0); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class Run { private GameObject m_owner; // @ Constructor public Run (GameObject owner) { this.m_owner = owner; } public void Listen () { Animator animator = m_owner.GetComponent<Animator>(); animator.SetBool(Constants.IS_RUNNING, Input.GetButton(Constants.RUN)); } // @ AI Methods public void Dispatch () { Animator animator = m_owner.GetComponent<Animator>(); animator.SetBool(Constants.IS_RUNNING, true); } public void Stop () { Animator animator = m_owner.GetComponent<Animator>(); animator.SetBool(Constants.IS_RUNNING, false); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Jose; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Security; #if NET5_0_OR_GREATER using System.Net.Http.Json; #endif namespace Zitadel.Authentication.Credentials { /// <summary> /// <para> /// A Zitadel <see cref="ServiceAccount"/> can be loaded from a json file /// and helps with authentication on a Zitadel IAM. /// </para> /// <para> /// The mechanism is defined here: /// <a href="https://docs.zitadel.ch/docs/apis/openidoauth/grant-types#json-web-token-jwt-profile">JSON Web Token (JWT) Profile</a>. /// <a href="https://docs.zitadel.ch/docs/guides/serviceusers#2-create-a-jwt-and-sign-with-private-key">Create a JWT and sigh it with the private key</a>. /// </para> /// </summary> public record ServiceAccount { private static readonly HttpClient HttpClient = new(); /// <summary> /// The key type. /// </summary> public const string Type = "serviceaccount"; /// <summary> /// The user id associated with this service account. /// </summary> #if NET5_0_OR_GREATER public string UserId { get; init; } = string.Empty; #elif NETCOREAPP3_1_OR_GREATER public string UserId { get; set; } = string.Empty; #endif /// <summary> /// This is unique ID (on Zitadel) of the key. /// </summary> #if NET5_0_OR_GREATER public string KeyId { get; init; } = string.Empty; #elif NETCOREAPP3_1_OR_GREATER public string KeyId { get; set; } = string.Empty; #endif /// <summary> /// The private key generated by Zitadel for this <see cref="ServiceAccount"/>. /// </summary> #if NET5_0_OR_GREATER public string Key { get; init; } = string.Empty; #elif NETCOREAPP3_1_OR_GREATER public string Key { get; set; } = string.Empty; #endif /// <summary> /// Load a <see cref="ServiceAccount"/> from a file at a given (relative or absolute) path. /// </summary> /// <param name="pathToJson">The relative or absolute filepath to the json file.</param> /// <returns>The parsed <see cref="ServiceAccount"/>.</returns> /// <exception cref="FileNotFoundException">When the file does not exist.</exception> /// <exception cref="InvalidDataException">When the deserializer returns 'null'.</exception> /// <exception cref="System.Text.Json.JsonException"> /// Thrown when the JSON is invalid, /// the <see cref="ServiceAccount"/> type is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> public static async Task<ServiceAccount> LoadFromJsonFileAsync(string pathToJson) { var path = Path.GetFullPath( Path.IsPathRooted(pathToJson) ? pathToJson : Path.Join(Directory.GetCurrentDirectory(), pathToJson)); if (!File.Exists(path)) { throw new FileNotFoundException($"File not found: {path}.", path); } await using var stream = File.OpenRead(path); return await LoadFromJsonStreamAsync(stream); } /// <inheritdoc cref="LoadFromJsonFileAsync"/> public static ServiceAccount LoadFromJsonFile(string pathToJson) => LoadFromJsonFileAsync(pathToJson).Result; /// <summary> /// Load a <see cref="ServiceAccount"/> from a given stream (FileStream, MemoryStream, ...). /// </summary> /// <param name="stream">The stream to read the json from.</param> /// <returns>The parsed <see cref="ServiceAccount"/>.</returns> /// <exception cref="InvalidDataException">When the deserializer returns 'null'.</exception> /// <exception cref="System.Text.Json.JsonException"> /// Thrown when the JSON is invalid, /// the <see cref="ServiceAccount"/> type is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> public static async Task<ServiceAccount> LoadFromJsonStreamAsync(Stream stream) => await JsonSerializer.DeserializeAsync<ServiceAccount>( stream, new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) ?? throw new InvalidDataException("The json file yielded a 'null' result for deserialization."); /// <inheritdoc cref="LoadFromJsonStreamAsync"/> public static ServiceAccount LoadFromJsonStream(Stream stream) => LoadFromJsonStreamAsync(stream).Result; /// <summary> /// Load a <see cref="ServiceAccount"/> from a string that contains json. /// </summary> /// <param name="json">Json string.</param> /// <returns>The parsed <see cref="ServiceAccount"/>.</returns> /// <exception cref="InvalidDataException">When the deserializer returns 'null'.</exception> /// <exception cref="System.Text.Json.JsonException"> /// Thrown when the JSON is invalid, /// the <see cref="ServiceAccount"/> type is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> public static async Task<ServiceAccount> LoadFromJsonStringAsync(string json) { await using var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json), 0, json.Length); return await LoadFromJsonStreamAsync(memoryStream); } /// <inheritdoc cref="LoadFromJsonStringAsync"/> public static ServiceAccount LoadFromJsonString(string json) => LoadFromJsonStringAsync(json).Result; /// <summary> /// Authenticate the given service account against the issuer in the options. /// As example, this token can be used to communicate with API applications or /// with the Zitadel API itself. /// </summary> /// <param name="authOptions"><see cref="AuthOptions"/> that contain the parameters for the authentication.</param> /// <returns>An opaque access token which can be used to communciate with relying parties.</returns> public async Task<string> AuthenticateAsync(AuthOptions authOptions) { var manager = new ConfigurationManager<OpenIdConnectConfiguration>( DiscoveryEndpoint(authOptions.DiscoveryEndpoint ?? authOptions.Endpoint), new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever(HttpClient)); var oidcConfig = await manager.GetConfigurationAsync(); var jwt = await GetSignedJwtAsync(authOptions.Endpoint); var request = new HttpRequestMessage(HttpMethod.Post, oidcConfig.TokenEndpoint) { Content = new FormUrlEncodedContent( new[] { new KeyValuePair<string?, string?>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"), new KeyValuePair<string?, string?>( "assertion", $"{jwt}"), new KeyValuePair<string?, string?>("scope", authOptions.CreateOidcScopes()), }), }; var response = await HttpClient.SendAsync(request); #if NET5_0_OR_GREATER var token = await response .EnsureSuccessStatusCode() .Content .ReadFromJsonAsync<AccessTokenResponse>(); #elif NETCOREAPP3_1_OR_GREATER var content = await response .EnsureSuccessStatusCode() .Content .ReadAsStringAsync(); var token = JsonSerializer.Deserialize<AccessTokenResponse>(content); #endif return token?.AccessToken ?? throw new("Access token could not be parsed."); } /// <inheritdoc cref="AuthenticateAsync"/> public string Authenticate(AuthOptions authOptions) => AuthenticateAsync(authOptions).Result; private static string DiscoveryEndpoint(string discoveryEndpoint) => discoveryEndpoint.EndsWith(ZitadelDefaults.DiscoveryEndpointPath) ? discoveryEndpoint : discoveryEndpoint.TrimEnd('/') + ZitadelDefaults.DiscoveryEndpointPath; private string GetSignedJwt(string issuer) => GetSignedJwtAsync(issuer).Result; private async Task<string> GetSignedJwtAsync(string issuer) { using var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(await GetRsaParametersAsync()); return JWT.Encode( new Dictionary<string, object> { { "iss", UserId }, { "sub", UserId }, { "iat", DateTimeOffset.UtcNow.AddSeconds(-1).ToUnixTimeSeconds() }, { "exp", ((DateTimeOffset)DateTime.UtcNow.AddMinutes(1)).ToUnixTimeSeconds() }, { "aud", issuer }, }, rsa, JwsAlgorithm.RS256, new Dictionary<string, object> { { "kid", KeyId }, }); } private async Task<RSAParameters> GetRsaParametersAsync() { var bytes = Encoding.UTF8.GetBytes(Key); await using var ms = new MemoryStream(bytes); using var sr = new StreamReader(ms); var pemReader = new PemReader(sr); if (!(pemReader.ReadObject() is AsymmetricCipherKeyPair keyPair)) { throw new("RSA Keypair could not be read."); } return DotNetUtilities.ToRSAParameters(keyPair.Private as RsaPrivateCrtKeyParameters); } #if NET5_0_OR_GREATER private record AccessTokenResponse { [JsonPropertyName("access_token")] public string AccessToken { get; init; } = string.Empty; } #elif NETCOREAPP3_1_OR_GREATER private record AccessTokenResponse { [JsonPropertyName("access_token")] public string AccessToken { get; set; } = string.Empty; } #endif /// <summary> /// Options for the authentication with a <see cref="ServiceAccount"/>. /// </summary> public record AuthOptions { /// <summary> /// Endpoint which will be called on the "token endpoint" to get an access token. /// Defaults to <see cref="ZitadelDefaults.Issuer"/>. /// </summary> #if NET5_0_OR_GREATER public string Endpoint { get; init; } = ZitadelDefaults.Issuer; #elif NETCOREAPP3_1_OR_GREATER public string Endpoint { get; set; } = ZitadelDefaults.Issuer; #endif /// <summary> /// If set, overwrites the discovery endpoint for <see cref="Endpoint"/>. /// This may be used, if the discovery endpoint is not on the well-known url /// of the endpoint. Beware that the well-known part ("/.well-known/openid-configuration") /// is still attached to the url. /// </summary> #if NET5_0_OR_GREATER public string? DiscoveryEndpoint { get; init; } #elif NETCOREAPP3_1_OR_GREATER public string? DiscoveryEndpoint { get; set; } #endif /// <summary> /// If set, the scope for a primary domain ("urn:zitadel:iam:org:domain:primary:{PrimaryDomain}") /// will be attached to the list of scopes for the access token of the service account. /// </summary> #if NET5_0_OR_GREATER public string? PrimaryDomain { get; init; } #elif NETCOREAPP3_1_OR_GREATER public string? PrimaryDomain { get; set; } #endif /// <summary> /// Set a list of roles that must be attached to this service account to be /// successfully authenticated. Translates to the role scope ("urn:zitadel:iam:org:project:role:{Role}"). /// </summary> #if NET5_0_OR_GREATER public IList<string> RequiredRoles { get; init; } = new List<string>(); #elif NETCOREAPP3_1_OR_GREATER public IList<string> RequiredRoles { get; set; } = new List<string>(); #endif /// <summary> /// Set a list of audiences that are attached to the returned access token. /// Translates to the additional audience scope ("urn:zitadel:iam:org:project:id:{ProjectId}:aud"). /// </summary> #if NET5_0_OR_GREATER public IList<string> ProjectAudiences { get; init; } = new List<string>(); #elif NETCOREAPP3_1_OR_GREATER public IList<string> ProjectAudiences { get; set; } = new List<string>(); #endif /// <summary> /// List of arbitrary additional scopes that are concatenated into the scope. /// </summary> #if NET5_0_OR_GREATER public IList<string> AdditionalScopes { get; init; } = new List<string>(); #elif NETCOREAPP3_1_OR_GREATER public IList<string> AdditionalScopes { get; set; } = new List<string>(); #endif internal string CreateOidcScopes() => string.Join( ' ', new[] { "openid", PrimaryDomain != null ? $"urn:zitadel:iam:org:domain:primary:{PrimaryDomain}" : string.Empty, } .Union(AdditionalScopes) .Union(ProjectAudiences.Select(p => $"urn:zitadel:iam:org:project:id:{p}:aud")) .Union(RequiredRoles.Select(r => $"urn:zitadel:iam:org:project:role:{r}")) .Where(s => !string.IsNullOrWhiteSpace(s))); } } }
using System; namespace interfaces { public class Minivan : IVehicle, ILand { public int Doors { get; set; } = 5; public int PassengerCapacity { get; set; } = 7; public double EngineVolume { get; set; } = 25.0; public int Wheels { get; set; } = 4; public string TransmissionType { get; set; } = "Automatic"; public double MaxLandSpeed { get; set; } = 84.3; public void Drive() { Console.WriteLine("The minivan moseys its way down the road"); } } }
using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DoodleReplacement { class AnswerEntity : TableEntity { public string Name { get; set; } public string AdditionalMessage { get; set; } public string SelectedDatesString { get; set; } public AnswerEntity() {} public AnswerEntity(string key, string name) { PartitionKey = key; RowKey = name.Trim().Replace(" ", "").ToLower(); } } class AnswerAM { public string Name { get; set; } public IEnumerable<DateTime> SelectedDates { get; set; } public string AdditionalMessage { get; set; } [JsonIgnore] public bool IsValid => !string.IsNullOrWhiteSpace(Name) && SelectedDates?.Any() == true; public static AnswerAM FromEntity(AnswerEntity entity) { return new AnswerAM { Name = entity.Name, SelectedDates = entity.SelectedDatesString?.Split(',').Select(d => DateTime.Parse(d)).ToList(), AdditionalMessage = entity.AdditionalMessage }; } } }
using System; namespace Sharp.Pipeline { public interface IPipelineBuilder { IPipelineBuilder Use(Func<PipelineDelegate, PipelineDelegate> middleware); PipelineDelegate Build(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using NetOffice; namespace NetOffice.DeveloperToolbox { class CommandBarsWrapper : IEnumerable { COMObject _commandBars; public CommandBarsWrapper(COMObject innerObject) { _commandBars = innerObject; } private IEnumerator GetProxyEnumeratorAsProperty(COMObject comObject) { object enumProxy = Invoker.PropertyGet(comObject, "_NewEnum"); COMObject enumerator = new COMObject(comObject, enumProxy, true); Invoker.MethodWithoutSafeMode(enumerator, "Reset", null); bool isMoveNextTrue = (bool)Invoker.MethodReturnWithoutSafeMode(enumerator, "MoveNext", null); while (true == isMoveNextTrue) { object itemProxy = Invoker.PropertyGetWithoutSafeMode(enumerator, "Current", null); COMObject returnClass = new COMObject(enumerator, itemProxy); isMoveNextTrue = (bool)Invoker.MethodReturnWithoutSafeMode(enumerator, "MoveNext", null); yield return returnClass; } } public IEnumerator GetEnumerator() { return GetProxyEnumeratorAsProperty(_commandBars); } } }
// QuickCuts Copyright (c) 2017 C. Jared Cone jared.cone@gmail.com // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. using System; using System.Text; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media.Animation; using System.Windows.Threading; using System.Collections.Generic; using System.Linq; namespace QuickCutsUI.controls { public partial class ConsoleWindow : Window { // polls mouse position DispatcherTimer mouseTimer; List<string> commands; public ConsoleWindow() { InitializeComponent(); commands = new List<string>(); this.Closing += HandleClosing; // we need to close the window when it gets deactivated, // so it will properly get focus when the user presses the shortcut keys next time this.Activated += HandleActivated; Application.Current.Deactivated += HandleAppDeactivated; txtInput.KeyDown += txtInput_KeyDown; txtInput.TextChanged += txtInput_TextChanged; txtInput.Focus(); //CacheCommands(); } private void HandleClosing(object sender, System.ComponentModel.CancelEventArgs e) { Application.Current.Deactivated -= HandleAppDeactivated; } void HandleActivated(object sender, EventArgs e) { txtInput.Focus(); CacheCommands(); } void HandleAppDeactivated(object sender, EventArgs e) { Close(); } void CacheCommands() { Commands.LoadCommandListAsync(HandleCommandList); } void HandleCommandList(Commands.CommandListResult result) { if (result.Exception != null) { ShowErrorDialog(result.Exception); return; } commands = result.Commands; } void txtInput_KeyDown(object sender, KeyEventArgs e) { var textBox = (TextBox)sender; switch(e.Key) { case Key.Enter: string text = textBox.Text; textBox.Text = ""; e.Handled = true; if (!String.IsNullOrEmpty(text)) { Commands.ExecuteUserCommandAsync(text, HandleExecuteCommandResult); } else { Close(); } break; case Key.Tab: if (!String.IsNullOrEmpty(textBox.Text)) { textBox.SelectionLength = 0; textBox.CaretIndex = textBox.Text.Length; UpdateAutoComplete(textBox.Text); } break; case Key.Escape: Close(); break; } } void HandleExecuteCommandResult(Commands.ExecuteCommandResult result) { // something went wrong while trying to execute the command if (result.Exception != null) { ShowErrorDialog(result.Exception); return; } // command executed successfully if (result.Success) { AddHistory(result.Text); Visibility = System.Windows.Visibility.Hidden; Close(); return; } // command was not found, do error flash FlashError(); } void AddHistory(string text) { if (QuickCutsUI.Properties.Settings.Default.History == null) { QuickCutsUI.Properties.Settings.Default.History = new System.Collections.Specialized.StringCollection(); } QuickCutsUI.Properties.Settings.Default.History.Remove(text); QuickCutsUI.Properties.Settings.Default.History.Insert(0, text); QuickCutsUI.Properties.Settings.Default.Save(); } void FlashError() { var storyboard = FindResource("ErrorAnimation") as Storyboard; var anim1 = storyboard.Children[0]; var anim2 = storyboard.Children[1]; Storyboard.SetTargetName(anim1, MainBorder.Name); Storyboard.SetTargetName(anim2, txtInput.Name); storyboard.Begin(this); } void ShowErrorDialog(Exception thrownException) { StringBuilder sb = new StringBuilder(); for (var ex = thrownException; ex != null; ex = ex.InnerException) { sb.AppendLine(ex.Message); } ShowErrorDialog(sb.ToString()); } void ShowErrorDialog(string text) { this.Activated -= HandleActivated; var button = MessageBoxButton.OK; var icon = MessageBoxImage.Warning; MessageBox.Show(this, text, "Error", button, icon); this.Activated += HandleActivated; Close(); } void txtInput_TextChanged(object sender, TextChangedEventArgs e) { if (e.Changes.Any(c => c.AddedLength > 0)) { var textBox = (TextBox)sender; UpdateAutoComplete(textBox.Text); } } void UpdateAutoComplete(string text) { if (!String.IsNullOrEmpty(text)) { AutoComplete.AutoCompleteAsync(commands, text, HandleAutoCompleteResult); } } void HandleAutoCompleteResult(AutoComplete.AutoCompleteResult result) { if (!String.IsNullOrEmpty(result.OutputText)) { var currentText = GetUnHighlightedText(txtInput); // don't update the textbox if it's changed since autocomplete started if (currentText.Equals(result.InputText)) { txtInput.Text = result.OutputText; // select/highlight the autocompleted part so the user can easily skip or delete it txtInput.Select(result.InputText.Length, result.OutputText.Length - result.InputText.Length); } } } /** * Get the part of the text that is not highlighted. * This part is what the user has actually typed, the rest is guess */ static string GetUnHighlightedText(TextBox textbox) { if (!String.IsNullOrEmpty(textbox.SelectedText)) { if (textbox.Text.EndsWith(textbox.SelectedText)) { return textbox.Text.Substring(0, textbox.Text.LastIndexOf(textbox.SelectedText)); } } return textbox.Text; } void ContextMenuAbout_Click(object sender, RoutedEventArgs e) { var aboutWindow = new AboutWindow(); aboutWindow.Show(); aboutWindow.Owner = Owner; } public void ContextMenuHelp_Click(object sender, RoutedEventArgs e) { try { System.Diagnostics.Process.Start(QuickCutsUI.Properties.Settings.Default.HelpURL, ""); } catch (System.Exception ex) { ShowErrorDialog(ex); } } public void ContextMenuOptions_Click(object sender, RoutedEventArgs e) { var optionsWindow = new OptionsWindow(); optionsWindow.Show(); } public void ContextMenuExit_Click(object sender, RoutedEventArgs e) { Owner.Close(); } public void ContextMenuMove_Click(object sender, RoutedEventArgs e) { WatchMouseEvents(true); } public void ContextMenuResize_Click(object sender, RoutedEventArgs e) { WatchMouseEvents(false); } public void ContextMenuReset_Click(object sender, RoutedEventArgs e) { QuickCutsUI.Properties.Settings.Default.Reset(); QuickCutsUI.Properties.Settings.Default.Save(); } void WatchMouseEvents(bool bDragging) { this.CaptureMouse(); this.MouseDown += MainWindow_MouseDown; if ( mouseTimer == null ) { mouseTimer = new DispatcherTimer(); mouseTimer.Interval = TimeSpan.FromMilliseconds(16); mouseTimer.Start(); } if (bDragging) { mouseTimer.Tick += MainWindow_DragMouseMove; } else { mouseTimer.Tick += MainWindow_ResizeMouseMove; } } void IgnoreMouseEvents() { this.MouseDown -= MainWindow_MouseDown; this.mouseTimer.Stop(); this.mouseTimer = null; this.ReleaseMouseCapture(); QuickCutsUI.Properties.Settings.Default.Save(); } void MainWindow_DragMouseMove(object sender, EventArgs e) { var point = WinAPI.GetCursporPos(); Top = point.Y - (Height / 2); Left = point.X - (Width / 2); } void MainWindow_ResizeMouseMove(object sender, EventArgs e) { var topLeftPoint = PointToScreen(new Point(0, 0)); var mousePoint = WinAPI.GetCursporPos(); Width = Math.Max(10, mousePoint.X - topLeftPoint.X) + 5; Height = Math.Max(10, mousePoint.Y - topLeftPoint.Y) + 5; } void MainWindow_MouseDown(object sender, MouseButtonEventArgs e) { IgnoreMouseEvents(); } void MainWindow_ResizeMouseMove(object sender, MouseEventArgs e) { var position = e.GetPosition(this); Width = position.X + 25; Height = position.Y + 25; e.Handled = true; } } public class SettingsBinding : Binding { public SettingsBinding() { Initialize(); } public SettingsBinding(string path) : base(path) { Initialize(); } private void Initialize() { this.Source = QuickCutsUI.Properties.Settings.Default; this.Mode = BindingMode.TwoWay; } } }
using System; namespace LatihanArray { class Program { static void Main(string[] args) { // deklarasi int[] a = new int[3]; a[0] = 1; a[1] = 2; a[2] = 3; Console.WriteLine(a[0]); a[0] = 13; Console.WriteLine(a[0]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace testService { [ServiceContract] interface IMyService { [OperationContract] string GetData(); [OperationContract] string GetMessage(string name); [OperationContract] string GetResult(Student S); [OperationContract] int GetMax(int[] ar); [OperationContract] int[] GetSorted(int[] ar); [OperationContract] Student GetTopper(List<Student> sList); [OperationContract] List<Country> GetCountries(); } [DataContract] public class Country { [DataMember] public int CountryId { get; set; } [DataMember] public string CountryName { get; set; } } [DataContract] class Student { [DataMember] public int Sid {get; set; } [DataMember] public string StudentName { get; set; } [DataMember] public int M1 { get; set; } [DataMember] public int M2 { get; set; } [DataMember] public int M3 { get; set; } [DataMember] public double Avg { get; set; } } }
namespace BattleEngine.Output { public class DamageApplyEvent : OutputEvent { public double x; public double y; public double z; public int targetId; public int units; public int damageId; public DamageApplyEvent() { } } }
using System; using DataAccessLayer.EfStructures.Context; using DataAccessLayer.EfStructures.Entities; using DataAccessLayer.EfStructures.Extensions; using Microsoft.EntityFrameworkCore; using Xunit; namespace DataAccessLayerTests.C_PersistChanges.D_ServerGenerated { public class ServerGeneratedTests : IDisposable { private readonly AdventureWorksContext _context; public ServerGeneratedTests() { _context = new AdventureWorksContext(); } public void Dispose() { _context.Dispose(); } [Fact] public void ShouldSetDefaultValuesForKeysWhenCreatedAndUniqueWhenTracked() { var prod1 = TestHelpers.CreateProduct("1"); var prod2 = TestHelpers.CreateProduct("2"); var prod3 = TestHelpers.CreateProduct("3"); Assert.Equal(0, prod1.ProductId); Assert.Equal(0, prod2.ProductId); Assert.Equal(0, prod3.ProductId); _context.Product.Add(prod1); _context.Product.Add(prod2); _context.Product.Add(prod3); Assert.True(prod1.ProductId < 0); Assert.True(prod2.ProductId < 0); Assert.True(prod3.ProductId < 0); Assert.NotEqual(prod1.ProductId, prod2.ProductId); Assert.NotEqual(prod2.ProductId, prod3.ProductId); Assert.NotEqual(prod1.ProductId, prod3.ProductId); } [Fact] public void ShouldSetDefaultValuesWhenAddingRecordsAndUpdateFromDatabaseAfterAdd() { using (var trans = _context.Database.BeginTransaction()) { var product = TestHelpers.CreateProduct("1"); _context.Product.Add(product); Assert.True(product.ProductId < 0); Assert.Equal(Guid.Empty, product.Rowguid); _context.SaveChanges(); Assert.True(product.ProductId > 0); Assert.NotEqual(Guid.Empty, product.Rowguid); trans.Rollback(); } } [Fact] public void ShouldAllowSettingServerGeneratedProperties() { using (var trans = _context.Database.BeginTransaction()) { var product = TestHelpers.CreateProduct("1"); var g = Guid.NewGuid(); product.Rowguid = g; _context.Product.Add(product); Assert.Equal(g, product.Rowguid); _context.SaveChanges(); Assert.Equal(g, product.Rowguid); trans.Rollback(); } } [Fact] public void ShouldAllowSettingServerGeneratedPropertiesWithIdentityInsert() { using (var trans = _context.Database.BeginTransaction()) { var product = TestHelpers.CreateProduct("1"); var g = Guid.NewGuid(); product.Rowguid = g; product.ProductId = 99999; _context.Product.Add(product); Assert.Equal(g, product.Rowguid); var sql = $"SET IDENTITY_INSERT " + $"{_context.GetSqlServerTableName<Product>()} ON"; _context.Database.ExecuteSqlCommand(sql); _context.SaveChanges(); sql = $"SET IDENTITY_INSERT " + $"{_context.GetSqlServerTableName<Product>()} OFF"; _context.Database.ExecuteSqlCommand(sql); Assert.Equal(g, product.Rowguid); Assert.Equal(99999, product.ProductId); trans.Rollback(); } } } }
using System; using System.Configuration; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using Nito.AsyncEx; namespace AzureServiceBusForms { public partial class TopicSubscriptionsWithRules : Form { private readonly MessageSender _messageSender; private AsyncLock _mutex; private readonly string _subscription1 = "jobs\\subscriptions\\job1"; private readonly string _subscription2 = "jobs\\subscriptions\\job2"; private readonly string _subscription3 = "jobs\\subscriptions\\job3"; public TopicSubscriptionsWithRules() { InitializeComponent(); _mutex = new AsyncLock(); var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]; var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.TopicExists("jobs")) { namespaceManager.CreateTopic("jobs"); } var factory = MessagingFactory.CreateFromConnectionString(connectionString); _messageSender = factory.CreateMessageSender("jobs"); if (!namespaceManager.SubscriptionExists("jobs", "job1")) { namespaceManager.CreateSubscription("jobs", "job1", new SqlFilter("JobID = '1'")); } if (!namespaceManager.SubscriptionExists("jobs", "job2")) { namespaceManager.CreateSubscription("jobs", "job2", new SqlFilter("JobID = '2'")); } if (!namespaceManager.SubscriptionExists("jobs", "job3")) { namespaceManager.CreateSubscription("jobs", "job3", new SqlFilter("JobID = '3'")); } InitializeReceiver(factory.CreateMessageReceiver(_subscription1)); InitializeReceiver(factory.CreateMessageReceiver(_subscription2)); InitializeReceiver(factory.CreateMessageReceiver(_subscription3)); } private void InitializeReceiver(MessageReceiver receiver) { receiver.OnMessageAsync(async message => { var jobId = message.Properties["JobID"] as string; MemoEdit targetControl = null; if (jobId == "1") { targetControl = job1Memo; } else if (jobId == "2") { targetControl = job2Memo; } else if (jobId == "3") { targetControl = job3Memo; } var body = message.GetBody<string>(); var stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Receiving Message..."); stringBuilder.AppendLine(string.Format("Subscription: {0}", receiver.Path)); stringBuilder.AppendLine(string.Format("Message ID: {0}", message.MessageId)); stringBuilder.AppendLine(string.Format("Message Body: {0}", body)); stringBuilder.AppendLine(string.Format("Job ID: {0}", jobId)); stringBuilder.AppendLine(); if (targetControl.InvokeRequired) { targetControl.Invoke(async () => { using (await _mutex.LockAsync()) { targetControl.Text += stringBuilder.ToString(); } }); } await message.CompleteAsync(); }, new OnMessageOptions {AutoComplete = false, MaxConcurrentCalls = 1}); } private async void simpleButton1_Click(object sender, EventArgs e) { var body = textEdit1.EditValue; textEdit1.EditValue = string.Empty; var message = new BrokeredMessage(body); var jobId = radioGroup.EditValue as string; message.Properties["JobID"] = jobId; var stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Sending Message..."); stringBuilder.AppendLine(string.Format("Message ID: {0}", message.MessageId)); stringBuilder.AppendLine(string.Format("Message Body: {0}", body)); stringBuilder.AppendLine(string.Format("Job ID: {0}", jobId)); stringBuilder.AppendLine(); serverMemo.Text += stringBuilder.ToString(); await _messageSender.SendAsync(message); } } }
namespace P10InfernoInfinity.Models.Gems.GemTypes { using System; using Enums; public class AmethystGemType : GemType { private const GemEnumerationType GemType = GemEnumerationType.Amethyst; private const int DefaultStrength = 2; private const int DefaultAgility = 8; private const int DefaultVitality = 4; public AmethystGemType(string gemType) : base( DefaultStrength, DefaultAgility, DefaultVitality) { base.TypeOfGem = base.ParseGemType(this.ValidateGemType(gemType)); } public AmethystGemType() : base( GemType, DefaultStrength, DefaultAgility, DefaultVitality) { } protected override sealed string ValidateGemType(string type) { if (type != GemType.ToString()) { throw new ArgumentException(DefaultErrorGemTypeMessage); } return type; } } }
using Cs_IssPrefeitura.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_IssPrefeitura.Aplicacao.Interfaces { public interface IAppServicoConfiguracoes: IAppServicoBase<Config> { } }
// <summary> All task demonstration. </summary> // <copyright file="AllTaskDemonstration.cs" company="MyCompany.com"> // Contains the solutions to the tasks of the 'Encapsulation. Inheritance. Polymorphism' module. // </copyright> // <author>Daryn Akhmetov</author> namespace Encapsulation._Inheritance._Polymorphism { using System; /// <summary> /// Contains the demonstrations of the solutions to the tasks. /// </summary> public class AllTaskDemonstration { /// <summary> /// The project should contain Main() method. /// </summary> public static void Main() { // Demonstration of the solution of the first task. Console.WriteLine("------------ First task ------------"); var array = new int[][] { new[] { 11, 34, 67, -89, 8 }, new[] { 1, 4, 3, 2, 5 }, new[] { 89, 23, 39, 12, -54 }, new[] { 0, 0, 0, 0, 0 }, new[] { -3, -54, -99, 81, 66 } }; // Create Matrix object from array. var matrix = new FirstTask.Matrix(array); // Print the two dimensional array. Console.WriteLine($"Unsorted array:"); Console.WriteLine(matrix); // Initialize the visitor. FirstTask.IVisitor visitor = new FirstTask.IncreasingSumsOfRowElements(); // Matrix object is visited which leads to calling that implementation of Visit method that corresponds to visitor. matrix.Accept(visitor); // Print the sorted array. Console.WriteLine("Array sorted in order of increasing sums of row elements:"); Console.WriteLine(matrix); // Change visitor. visitor = new FirstTask.DecreasingSumsOfRowElements(); matrix.Accept(visitor); Console.WriteLine("Array sorted in order of decreasing sums of row elements:"); Console.WriteLine(matrix); visitor = new FirstTask.IncreasingMaximumElement(); matrix.Accept(visitor); Console.WriteLine("Array sorted in order of increasing maximum elements in a row:"); Console.WriteLine(matrix); visitor = new FirstTask.IncreasingMinimumElement(); matrix.Accept(visitor); Console.WriteLine("Array sorted in order of increasing minimum elements in a row:"); Console.WriteLine(matrix); // Demonstration of the solution of the second task. Console.WriteLine("------------ Second task ------------"); var circle = new SecondTask.Circle(3.0); var triangle = new SecondTask.Triangle(3, 4, 5); var square = new SecondTask.Square(4.0); var rectangle = new SecondTask.Rectangle(5.0, 6.0); Console.WriteLine($"The perimeter of the circle with a radius of {circle.Radius} cm is {circle.CalculatePerimeter()}"); Console.WriteLine($"The perimeter of the triangle with sides {triangle.FirstSide}, {triangle.SecondSide}, {triangle.ThirdSide} cm is {triangle.CalculatePerimeter()}"); Console.WriteLine($"The perimeter of the square with a side of {square.Side} cm is {square.CalculatePerimeter()}"); Console.WriteLine($"The perimeter of the rectangle with sides {rectangle.FirstSide}, {rectangle.SecondSide} cm is {rectangle.CalculatePerimeter()}"); Console.WriteLine($"The area of the circle with a radius of {circle.Radius} cm is {circle.CalculateArea()} cm2"); Console.WriteLine($"The area of the triangle with sides {triangle.FirstSide}, {triangle.SecondSide}, {triangle.ThirdSide} cm is {triangle.CalculateArea()} cm2"); Console.WriteLine($"The area of the square with a side of {square.Side} cm is {square.CalculateArea()} cm2"); Console.WriteLine($"The area of the rectangle with sides {rectangle.FirstSide}, {rectangle.SecondSide} cm is {rectangle.CalculateArea()} cm2"); // Demonstration of the solution of the third task. Console.WriteLine("------------ Third task ------------"); // Initialize polynomial f(x) = 1 + 2x + 3x^3 + 4x^4. var polynomial1 = new ThirdTask.Polynomial(1, 2, 3, 4); // Initialize polynomial f(x) = 4 + 3x + 2x^3 + 1x^4. var polynomial2 = new ThirdTask.Polynomial(4, 3, 2, 1); Console.WriteLine("Two polynomial:"); Console.WriteLine(polynomial1); Console.WriteLine(polynomial2); Console.WriteLine($"Check for equality of two polynomial: p1.Equals(p2) = {polynomial1.Equals(polynomial2)}"); Console.WriteLine($"The value of the first polynomial at the point x = 2 is {polynomial1.Evaluate(2)}"); Console.WriteLine($"The value of the second polynomial at the point x = 2 is {polynomial2.Evaluate(2)}"); Console.WriteLine("Sum of two polynomial:"); Console.WriteLine(polynomial1 + polynomial2); Console.WriteLine("Subtraction of two polynomial:"); Console.WriteLine(polynomial1 - polynomial2); Console.WriteLine("Multiplying the first polynomial by 5:"); Console.WriteLine(5 * polynomial1); Console.WriteLine("Division of the first polynomial by 5:"); Console.WriteLine(polynomial1 / 5); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace _3_hetedik_feladat { class Program { struct Tanulo { public string nev; public double atlag; public string CSVFormatumba() { return nev + ";" + atlag + Environment.NewLine; } } static void Main(string[] args) { Tanulo tanuloAdatai = new Tanulo(); StreamWriter bekertTanuloAdatok = new StreamWriter("tanuloadatok.csv", true); do { Console.WriteLine("Adja meg a tanuló nevét!"); tanuloAdatai.nev = Console.ReadLine(); if (tanuloAdatai.nev.ToLower() != "exit") { Console.WriteLine("Adja meg a tanuló átlagát!"); tanuloAdatai.atlag = Convert.ToDouble(Console.ReadLine()); bekertTanuloAdatok.Write(tanuloAdatai.CSVFormatumba()); } Console.Clear(); } while (tanuloAdatai.nev.ToLower() != "exit"); bekertTanuloAdatok.Close(); } } }
using System; using System.Collections; using UnityEngine; public class SlowMotion : MonoBehaviour { public static SlowMotion Instance { get; private set; } void Awake() { Instance = this; } public void StartSlowMotion(float duration) { StartCoroutine(SlowMotionTimer(duration)); } public void StartSlowMotion(float duration, float delay) { StartCoroutine(SlowMotionTimer(duration, delay)); } private IEnumerator SlowMotionTimer(float duration, float delay = 0) { float myTime = 0; while (myTime < delay) { myTime += Time.unscaledDeltaTime; yield return null; } Time.timeScale = 0.05f; myTime = 0; while (myTime < duration) { myTime += Time.unscaledDeltaTime; yield return null; } Time.timeScale = 1; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using IRAPORM; using IRAPShared; namespace BatchSystemMNGNT_Asimco { public class TBLStockDetails { private static List<Entities.TTableStockDetail> GetDataRecord( string strSQL, IList<IDataParameter> paramList) { try { using (IRAPSQLConnection conn = new IRAPSQLConnection(SysParams.Instance.DBConnectionString)) { IList<Entities.TTableStockDetail> lstDatas = conn.CallTableFunc<Entities.TTableStockDetail>(strSQL, paramList); return lstDatas.ToList(); } } catch (Exception error) { error.Data["ErrCode"] = 999999; error.Data["ErrText"] = string.Format( "在获取四班库存记录时发生错误:[{0}]", error.Message); throw error; } } public static List<Entities.TTableStockDetail> Get( string itemNumber, string lotNumber) { string strSQL = "SELECT * FROM ERP.FSDBMR.dbo.StockDetail " + "WHERE STK_ROOM=@STK_ROOM AND ITEM=@ITEM AND {0} " + "ORDER BY LOT"; IList<IDataParameter> paramList = new List<IDataParameter>(); if (lotNumber.Length == 14) strSQL = string.Format(strSQL, "LOT=@LOT"); else { strSQL = string.Format(strSQL, "LOT LIKE @LOT"); lotNumber = string.Format("%{0}%", lotNumber); } paramList.Add(new IRAPProcParameter("@STK_ROOM", DbType.String, "28")); paramList.Add(new IRAPProcParameter("@ITEM", DbType.String, itemNumber)); paramList.Add(new IRAPProcParameter("@LOT", DbType.String, lotNumber)); try { List<Entities.TTableStockDetail> rlt = GetDataRecord(strSQL, paramList); return rlt; } catch (Exception error) { throw error; } } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using WebAPI.Core.DomainModels.Base; using WebAPI.Core.DomainModels.Transactions; namespace WebAPI.Core.DomainModels.Customers { public class Customer: EntityBase<int> { public string Name { get; set; } public string Email { get; set; } public string MobileNo { get; set; } public ICollection<Transaction> Transactions { get; set; } = new List<Transaction>(); public CustomerDTO toCustomerDTO() { return new CustomerDTO() { customerID = Id, Name = Name, Email = Email, Mobile = MobileNo, Transactions = Transactions.Select(x => x.toTransactionDTO()).ToList() }; } public CustomerDTO toCustomerAndOneTransactionDTO() { return new CustomerDTO() { customerID = Id, Name = Name, Email = Email, Mobile = MobileNo, Transactions = Transactions.Take(1).Select(x => x.toTransactionDTO()).ToList() }; } } }
using UnityEngine; using System.Collections; public class nk : MonoBehaviour { public float thrust; public Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); rb.AddForce (200f, 300f, 0); } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; namespace CodeX { public static class ModuleDef { //C#的业务模块 public const string LaunchModule = "LaunchModule"; //Lua的业务模块 public const string LuaGameModule = "GameModule"; } }
using System; using System.Collections.Generic; using System.Net; using System.Text; namespace Etherama.Common { public class CustomWebClient : System.Net.WebClient { public int Timeout { get; set; } public CustomWebClient() : base() { Timeout = 60 * 1000; } protected override System.Net.WebRequest GetWebRequest(Uri uri) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; var webRequest = base.GetWebRequest(uri); webRequest.Timeout = Timeout; webRequest.Headers[HttpRequestHeader.UserAgent] = "Chrome"; ((HttpWebRequest)webRequest).ReadWriteTimeout = Timeout; return webRequest; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kingdee.CAPP.Model { /// <summary> /// 类型说明:工艺文件版本实体类 /// 作 者:jason.tang /// 完成时间:2013-08-23 /// </summary> public class ProcessVersion { public string VerId { get; set; } public string BaseId { get; set; } public string VerCode { get; set; } public string VerName { get; set; } public string Code { get; set; } public string Name { get; set; } public string CategoryId { get; set; } public int MajorVer { get; set; } public int MinorVer { get; set; } public int State { get; set; } public string Creator { get; set; } public string CreateDate { get; set; } public string Updater { get; set; } public string UpdateDate { get; set; } public string CheckOutPerson { get; set; } public string CheckOutDate { get; set; } public string ArchiveDate { get; set; } public string ReleaseDate { get; set; } public string Remark { get; set; } public bool IsChange { get; set; } public bool IsEffective { get; set; } public bool IsInFlow { get; set; } public int IsShow { get; set; } public string FolderId { get; set; } public string ObjectStatePath { get; set; } public string ObjectIconPath { get; set; } } }
using System.Net.Mail; using System.Web.Services; using com.Sconit.Service; namespace com.Sconit.WebService { [WebService(Namespace = "http://com.Sconit.WebService.SMSService/")] public class SMSService : BaseWebService { [WebMethod] public void AsyncSend(string mobilePhones, string msg) { //smsManager.AsyncSendMessage(mobilePhones, msg); } [WebMethod] public void Send(string mobilePhones, string msg) { //smsManager.SendMessage(mobilePhones, msg); } } }
namespace Aria.Engine.Objects { public abstract class Object { // Private static reference to counter for generating IDs. // TODO: Move this to thread-safe class if multi-threading. private static int _counter; // Unique instance ID for this object. internal int InstanceID; /// <summary> /// Constructor: Create a new empty object. /// </summary> protected Object() { Name = "object"; InstanceID = ++_counter; } /// <summary> /// Constructor: Create a new named empty object. /// </summary> /// <param name="name"></param> protected Object(string name) { Name = name; InstanceID = ++_counter; } /// <summary> /// This objects assigned. name. /// </summary> public string Name { get; private set; } /// <summary> /// Dispose of this object. /// </summary> public virtual void Dispose() { Name = null; InstanceID = -1; } /// <summary> /// Rich ToString text. /// </summary> /// <returns>Rich formatting for object output.</returns> public override string ToString() { return "Object InstanceID_" + InstanceID + " '" + Name + "'"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Boundary { public float yMin, yMax; } public class playerRazonar : MonoBehaviour { public float speed; public Boundary boundary; public GameObject bullets; public GameObject shot; public Transform shotSpawn; public float fireRate; private float nextFire; private Vector3 inicialPosition; private void Start() { inicialPosition = transform.position; } private void FixedUpdate() { float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(0.0f, moveVertical, 0.0f); GetComponent<Rigidbody>().velocity = movement * speed; transform.position = new Vector3 ( inicialPosition.x, Mathf.Clamp (transform.position.y, boundary.yMin, boundary.yMax), inicialPosition.z ); } private void Update() { if (Input.GetButton("Jump") && Time.time > nextFire) { nextFire = Time.time + fireRate; GameObject clone = Instantiate(shot, shotSpawn.position, shotSpawn.rotation); clone.transform.parent = bullets.transform; } } }
using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.Network.Algorthm; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace gView.Framework.Network.Tracers { class Helper { public static List<int> NodeIds(Dijkstra.Nodes nodes) { List<int> ids = new List<int>(); foreach (Dijkstra.Node node in nodes) { ids.Add(node.Id); } return ids; } async public static Task AppendNodeFlags(INetworkFeatureClass network, GraphTable gt, List<int> nodeIds, NetworkTracerOutputCollection output/*, IProgressReporterEvent reportEvent, ProgressReport report*/) { try { Dictionary<int, string> fcNames = new Dictionary<int, string>(); //int counter = 0; //if (report != null) //{ // report.Message = "Add Nodes..."; // report.featurePos = 0; // report.featureMax = nodeIds.Count; // reportEvent.reportProgress(report); //} foreach (int nodeId in nodeIds) { int fcId = gt.GetNodeFcid(nodeId); if (fcId >= 0) { IFeature nodeFeature = await network.GetNodeFeature(nodeId); if (nodeFeature != null && nodeFeature.Shape is IPoint) { if (!fcNames.ContainsKey(fcId)) { fcNames.Add(fcId, await network.NetworkClassName(fcId)); } string fcName = fcNames[fcId]; output.Add(new NetworkFlagOutput(nodeFeature.Shape as IPoint, new NetworkFlagOutput.NodeFeatureData(nodeId, fcId, Convert.ToInt32(nodeFeature["OID"]), fcName))); } } //counter++; //if (report != null && counter % 1000 == 0) //{ // report.featurePos = counter; // reportEvent.reportProgress(report); //} } } catch { } } } }
using System; using System.Windows.Forms; using UserNamespace; using GameCore; using System.Collections.Generic; namespace UNO__ { public partial class mainForm : Form { public static User user = new User(); public mainForm() { InitializeComponent(); } private void mainForm_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Escape: this.Close(); break; } } private void 关于ToolStripMenuItem1_Click(object sender, EventArgs e) { About about = new About { StartPosition = FormStartPosition.CenterScreen }; about.Show(); } private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void 游戏规则ToolStripMenuItem_Click(object sender, EventArgs e) { Rules rules = new Rules { StartPosition = FormStartPosition.CenterScreen }; rules.Show(); } private void button2_Click(object sender, EventArgs e) { this.Hide(); PersonnalMessage personnalMessage = new PersonnalMessage { StartPosition = FormStartPosition.CenterScreen, Owner = this }; personnalMessage.SetText(user); personnalMessage.ReturnEvent += new PersonnalMessage.ReturnUser(getUser); personnalMessage.Show(); } private void getUser(User usr) { if (!user.Equals(usr)) { user = usr; userset = true; } } private void 用户设置ToolStripMenuItem_Click(object sender, EventArgs e) { this.Hide(); PersonnalMessage personnalMessage = new PersonnalMessage { StartPosition = FormStartPosition.CenterScreen, Owner = this }; personnalMessage.SetText(user); personnalMessage.ReturnEvent += new PersonnalMessage.ReturnUser(getUser); personnalMessage.Show(); } private void button3_Click(object sender, EventArgs e) { if (!userset) { MessageBox.Show("你还没有设置用户!", "提示"); return; } this.Hide(); Createroom createroom = new Createroom { StartPosition = FormStartPosition.CenterScreen, }; createroom.SetUser(user); createroom.Show(); } private void mainForm_FormClosed(object sender, FormClosedEventArgs e) { Environment.Exit(0); } bool userset = false; private void button4_Click(object sender, EventArgs e) { if (!userset) { MessageBox.Show("你还没有设置用户!", "提示"); return; } this.Hide(); Joinroom joinroom = new Joinroom { StartPosition = FormStartPosition.CenterScreen, Owner = this, clientuser = user }; joinroom.Show(); } private void button1_Click(object sender, EventArgs e) { Playgame playgame = new Playgame { StartPosition = FormStartPosition.CenterScreen }; playgame.SetText(user); playgame.hostuser = user; playgame.users = new List<User>(); playgame.users.Add(user); Core.n = 1; Core.InitGame(1); Core.get_card(1, 7); Core.SinglePlayerMode = true; playgame.RefreshCard(); playgame.RefreshUsers(); playgame.SetNameLabel(); playgame.tableLayoutPanel4.Show(); playgame.SendCardEvent += new Playgame.SendCardDelegate((Card card, int id, string s, int t) => { }); playgame.Show(); } } }
namespace Cs_Gerencial.Infra.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class ParticipantesUpdate : DbMigration { public override void Up() { AddColumn("dbo.Participantes", "Distribuicao", c => c.String(nullable: false, maxLength: 1, unicode: false)); DropColumn("dbo.Participantes", "Ditribuicao"); } public override void Down() { AddColumn("dbo.Participantes", "Ditribuicao", c => c.String(nullable: false, maxLength: 1, unicode: false)); DropColumn("dbo.Participantes", "Distribuicao"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HotelManagement.DataObject; using System.Data; using System.Windows.Forms; namespace HotelManagement.Controller { public class BaoCaoDoanhThuPhongControl { BaoCaoDoanhThuPhongData data = new BaoCaoDoanhThuPhongData(); public void HienThi(DataGridView dgv, BindingNavigator bn) { BindingSource bs = new BindingSource(); bs.DataSource = data.LayBaoCaoData(); dgv.DataSource = bs; bn.BindingSource = bs; } public DataRow NewRow() { return this.data.NewRow(); } public void Add(DataRow row) { this.data.Add(row); } public bool Save() { return data.Save(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using RealEstate.Models; using System.IO; namespace RealEstate.Controllers { [CHAA] public class GalleriesController : Controller { private RealEstateEntities db = new RealEstateEntities(); BL bl = new BL(); // GET: Galleries public ActionResult Index() { return View(bl.GalleryList()); } // GET: Galleries/Details/5 //public ActionResult Details(int? id) //{ // if (id == null) // { // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // } // tblGallery tblGallery = db.tblGalleries.Find(id); // if (tblGallery == null) // { // return HttpNotFound(); // } // return View(tblGallery); //} // GET: Galleries/Create public ActionResult Create() { return View(); } // POST: Galleries/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "RowID,Title,Description")] GalleryVM mod) { if (ModelState.IsValid) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetExtension(file.FileName); tblGallery tbl = new tblGallery { Description = mod.Description, Title = mod.Title, Status = true, Transdate = DateTime.Now.AddHours(12), UserID = bl.GetUserID(System.Web.HttpContext.Current), ImagePath = fileName }; db.tblGalleries.Add(tbl); db.SaveChanges(); var path = Path.Combine(Server.MapPath("~/Images/"), "gal" + tbl.RowID + fileName); file.SaveAs(path); return RedirectToAction("Index"); } else { ModelState.AddModelError("", "No Image Found"); } } return View(mod); } // GET: Galleries/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } tblGallery tblGallery = db.tblGalleries.Find(id); if (tblGallery == null) { return HttpNotFound(); } GalleryVM mod = new GalleryVM { Description = tblGallery.Description, Title = tblGallery.Title, ImagePath = tblGallery.ImagePath, RowID = tblGallery.RowID, Status = tblGallery.Status }; return View(mod); } // POST: Galleries/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "RowID,Title,Description,Status")] GalleryVM mod) { if (ModelState.IsValid) { tblGallery tbl = db.tblGalleries.Find(mod.RowID); tbl.Description = mod.Description; tbl.Title = mod.Title; tbl.Status = true; var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetExtension(file.FileName); tbl.ImagePath = fileName; var path = Path.Combine(Server.MapPath("~/Images/"), "gal" + tbl.RowID + fileName); file.SaveAs(path); } db.SaveChanges(); return RedirectToAction("Index"); } return View(mod); } // GET: Galleries/Delete/5 //public ActionResult Delete(int? id) //{ // if (id == null) // { // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // } // tblGallery tblGallery = db.tblGalleries.Find(id); // if (tblGallery == null) // { // return HttpNotFound(); // } // return View(tblGallery); //} // POST: Galleries/Delete/5 //[HttpPost, ActionName("Delete")] //[ValidateAntiForgeryToken] //public ActionResult DeleteConfirmed(int id) //{ // tblGallery tblGallery = db.tblGalleries.Find(id); // db.tblGalleries.Remove(tblGallery); // db.SaveChanges(); // return RedirectToAction("Index"); //} protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleImage { class Program { static void Main(string[] args) { Console.SetWindowSize(100, 50); Console.SetBufferSize(100, 50); var invertColor = false; using (var bitmap = (Bitmap)Bitmap.FromFile("image.bmp")) { int windowWidth = 0; int windowHeight = 0; while (true) { if (Console.WindowWidth != windowWidth || Console.WindowHeight != windowHeight) { Console.Clear(); DrawToWindow(bitmap, Console.WindowWidth, Console.WindowHeight, invertColor); windowWidth = Console.WindowWidth; windowHeight = Console.WindowHeight; } Thread.Sleep(50); } } } static void DrawToWindow(Bitmap bitmap, int width, int height, bool invertColors) { using (var smallerImage = (Bitmap)bitmap.GetThumbnailImage(width - 1, height - 1, null, IntPtr.Zero)) { var lockRect = new Rectangle(0, 0, smallerImage.Width, smallerImage.Height); var bitmapData = smallerImage.LockBits(lockRect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); try { for (int y = 0; y < smallerImage.Height; ++y) { for (int x = 0; x < smallerImage.Width; ++x) { var pixel = Marshal.ReadInt32(bitmapData.Scan0, y * bitmapData.Stride + x * 4); Console.SetCursorPosition(x, y); Console.BackgroundColor = MapPixelToConsoleColor(pixel, invertColors); Console.Write(" "); } } } finally { smallerImage.UnlockBits(bitmapData); } } } static int GetPixelComponent(int pixel, PixelComponent component) { switch (component) { case PixelComponent.Red: return (pixel >> 16) & 0xff; case PixelComponent.Green: return (pixel >> 8) & 0xff; case PixelComponent.Blue: return pixel & 0xff; } throw new Exception("Invalid component"); } static ConsoleColor MapPixelToConsoleColor(int pixel, bool invertColors) { var colors = new List<KeyValuePair<int, ConsoleColor>>(); colors.Add(new KeyValuePair<int, ConsoleColor>(0xff0000, ConsoleColor.Red)); colors.Add(new KeyValuePair<int, ConsoleColor>(0x00ff00, ConsoleColor.Green)); colors.Add(new KeyValuePair<int, ConsoleColor>(0x0000ff, ConsoleColor.Blue)); colors.Add(new KeyValuePair<int, ConsoleColor>(0xffff00, ConsoleColor.Yellow)); colors.Add(new KeyValuePair<int, ConsoleColor>(0xff00ff, ConsoleColor.Magenta)); colors.Add(new KeyValuePair<int, ConsoleColor>(0x00ffff, ConsoleColor.Cyan)); colors.Add(new KeyValuePair<int, ConsoleColor>(0xffffff, ConsoleColor.White)); colors.Add(new KeyValuePair<int, ConsoleColor>(0x000000, ConsoleColor.Black)); colors.Sort((a, b) => { var px_r = GetPixelComponent(pixel, PixelComponent.Red); var px_g = GetPixelComponent(pixel, PixelComponent.Green); var px_b = GetPixelComponent(pixel, PixelComponent.Blue); var a_r = GetPixelComponent(a.Key, PixelComponent.Red); var a_g = GetPixelComponent(a.Key, PixelComponent.Green); var a_b = GetPixelComponent(a.Key, PixelComponent.Blue); var b_r = GetPixelComponent(b.Key, PixelComponent.Red); var b_g = GetPixelComponent(b.Key, PixelComponent.Green); var b_b = GetPixelComponent(b.Key, PixelComponent.Blue); #if true int a_dist = (int)Math.Sqrt(Math.Pow(px_r - a_r, 2) + Math.Pow(px_g - a_g, 2) + Math.Pow(px_b - a_b, 2)); int b_dist = (int)Math.Sqrt(Math.Pow(px_r - b_r, 2) + Math.Pow(px_g - b_g, 2) + Math.Pow(px_b - b_b, 2)); if (invertColors) { if (a_dist < b_dist) return 1; if (a_dist > b_dist) return -1; } else { if (a_dist < b_dist) return -1; if (a_dist > b_dist) return 1; } return 0; #else int cmp_r = (a_r - px_r) + (a_b - px_g) + (a_b - px_b); int cmp_g = (a_g - px_g) + (a_b - px_g) + (a_b - px_b); int cmp_b = (a_b - px_b) + (a_b - px_g) + (a_b - px_b); return (cmp_r + cmp_g + cmp_b) / 3; #endif }); return colors[0].Value; //var red = ((pixel >> 16) & 0xff) / 127; //var green = ((pixel >> 8) & 0xff) / 127; //var blue = (pixel & 0xff) / 127; } } enum PixelComponent { Red, Green, Blue } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Collections; using System.Security.Cryptography; namespace ShengUI.Helper.payCls { /** * * 作用:微信支付公用参数,微信支付版本V3.3.7 * 作者:shihai * 编写日期:2015-4-1 * 备注:请正确填写相关参数 * * */ public class PayConfig { /// <summary> /// 人民币 /// </summary> public static string Tenpay = "1"; /// <summary> /// mchid , 微信支付商户号 /// </summary> public static string MchId = WeChatConfig.GetKeyValue("mchid"); /// <summary> /// appid,应用ID, 在微信公众平台中 “开发者中心”栏目可以查看到 /// </summary> public static string AppId = WeChatConfig.GetKeyValue("appid"); /// <summary> /// appsecret ,应用密钥, 在微信公众平台中 “开发者中心”栏目可以查看到 /// </summary> public static string AppSecret = WeChatConfig.GetKeyValue("appsecret"); /// <summary> /// paysignkey,API密钥,在微信商户平台中“账户设置”--“账户安全”--“设置API密钥”,只能修改不能查看 /// </summary> public static string AppKey = WeChatConfig.GetKeyValue("apisecret"); /// <summary> /// 支付页面,请注意测试阶段设置授权目录,在微信公众平台中“微信支付”---“开发配置”--修改测试目录 /// 注意目录的层次,比如我的: /// </summary> public static string PayUrl = WeChatConfig.GetKeyValue("shareurl") + "AoShaCar/PayOrder"; /// <summary> /// 支付通知页面,请注意测试阶段设置授权目录,在微信公众平台中“微信支付”---“开发配置”--修改测试目录 /// 支付完成后的回调处理页面,替换成notify_url.asp所在路径 /// </summary> public static string NotifyUrl = WeChatConfig.GetKeyValue("shareurl") + "AoShaCar/Notify";//参与签名 #region 获取微信支付数据包 /// <summary> /// 微信JSAPI支付数据包 含有非必须参数 /// </summary> /// <param name="attach">附加数据,原样返回</param> /// <param name="body">商品描述</param> /// <param name="device_info">微信支付分配的终端设备号 不是必备参数</param> /// <param name="nonce_str">随机字符串,不长于 32 位</param> /// <param name="out_trade_no">户系统内部的订单号 ,32个字符内、可包含字母, 确保唯一</param> /// <param name="spbill_create_ip">订单生成的机器 IP</param> /// <param name="total_fee">总金额</param> /// <param name="sign">签名</param> /// <param name="openid">用户在公众平台下的唯一标识</param> /// <param name="trade_type">支付类型:JSAPI、 NATIVE、 APP</param> /// <returns></returns> public static string GetPayData(string attach, string body, string device_info, string nonce_str, string out_trade_no, string spbill_create_ip, int total_fee, string sign, string openid, string trade_type = "JSAPI") { StringBuilder sb = new StringBuilder(); sb.Append(@"<xml>"); sb.Append(@"<appid>" + AppId + "</appid>"); sb.Append(@"<attach><![CDATA[" + attach + "]]></attach>");//附加数据,原样返回 sb.Append(@"<body><![CDATA[" + body + "]]></body>");//商品描述 sb.Append(@"<device_info>" + device_info + "</device_info>");//微信支付分配的终端设备号 不是必备参数 sb.Append(@"<mch_id>" + MchId + "</mch_id>");//微信支付分配的商户号 sb.Append(@"<nonce_str>" + nonce_str + "</nonce_str>");//随机字符串,不长于 32 位 sb.Append(@"<notify_url>" + NotifyUrl.ToString().Replace("#", "") + "</notify_url>");//接收微信支付成功通知 sb.Append(@"<out_trade_no>" + out_trade_no + "</out_trade_no>");//商户系统内部的订单号 ,32个字符内、可包含字母, 确保唯一 sb.Append(@"<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>");//订单生成的机器 IP sb.Append(@"<total_fee>" + total_fee + "</total_fee>");//总金额 sb.Append(@"<trade_type>" + trade_type + "</trade_type>");//JSAPI、 NATIVE、 APP sb.Append(@"<openid>" + openid + "</openid>");//openId JSAPI支付模式,参数必备 sb.Append(@"<sign><![CDATA[" + sign + "]]></sign>");//签名 sb.Append(@"</xml>"); return sb.ToString(); } /// <summary> /// 微信JSAPI支付数据包 仅仅包含必备参数 JSAPI /// </summary> /// <param name="attach">附加数据,原样返回</param> /// <param name="body">商品描述</param> /// <param name="device_info">微信支付分配的终端设备号 不是必备参数</param> /// <param name="nonce_str">随机字符串,不长于 32 位</param> /// <param name="out_trade_no">户系统内部的订单号 ,32个字符内、可包含字母, 确保唯一</param> /// <param name="spbill_create_ip">订单生成的机器 IP</param> /// <param name="total_fee">总金额</param> /// <param name="sign">签名</param> /// <param name="openid">用户在公众平台下的唯一标识</param> /// <param name="trade_type">支付类型:JSAPI、 NATIVE、 APP</param> /// <returns></returns> public static string GetPayData(string attach, string body, string nonce_str, string out_trade_no, string spbill_create_ip, int total_fee, string sign, string openid, string trade_type = "JSAPI") { StringBuilder sb = new StringBuilder(); sb.Append(@"<xml>"); sb.Append(@"<appid>" + AppId + "</appid>"); sb.Append(@"<attach><![CDATA[" + attach + "]]></attach>");//附加数据,原样返回 sb.Append(@"<body><![CDATA[" + body + "]]></body>");//商品描述 sb.Append(@"<mch_id>" + MchId + "</mch_id>");//微信支付分配的商户号 sb.Append(@"<nonce_str>" + nonce_str + "</nonce_str>");//随机字符串,不长于 32 位 sb.Append(@"<notify_url>" + NotifyUrl.ToString().Replace("#", "") + "</notify_url>");//接收微信支付成功通知 sb.Append(@"<out_trade_no>" + out_trade_no + "</out_trade_no>");//商户系统内部的订单号 ,32个字符内、可包含字母, 确保唯一 sb.Append(@"<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>");//订单生成的机器 IP sb.Append(@"<total_fee>" + total_fee + "</total_fee>");//总金额 sb.Append(@"<trade_type>" + trade_type + "</trade_type>");//JSAPI、 NATIVE、 APP sb.Append(@"<openid>" + openid + "</openid>");//openId JSAPI支付模式,参数必备 sb.Append(@"<sign><![CDATA[" + sign + "]]></sign>");//签名 sb.Append(@"</xml>"); return sb.ToString(); } #endregion } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Alabo.Extensions; using Alabo.Framework.Basic.PostRoles.Domain.Entities; using Alabo.Framework.Basic.PostRoles.Domain.Services; using Alabo.Framework.Basic.PostRoles.Dtos; using Alabo.Framework.Core.WebApis.Controller; using Alabo.Framework.Core.WebApis.Filter; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; using ZKCloud.Open.ApiBase.Models; namespace Alabo.Framework.Basic.PostRoles.Controllers { [ApiExceptionFilter] [Route("Api/PostRole/[action]")] public class ApiPostRoleController : ApiBaseController<PostRole, ObjectId> { public ApiPostRoleController() { BaseService = Resolve<IPostRoleService>(); } /// <summary> /// 权限编辑 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public ApiResult Edit([FromBody] PostRoleInput model) { if (!this.IsFormValid()) { return ApiResult.Failure(this.FormInvalidReason()); } var result = Resolve<IPostRoleService>().Edit(model); return ToResult(result); } /// <summary> /// 岗位树形菜单 /// </summary> /// <returns></returns> [HttpGet] public ApiResult Tree() { var result = Resolve<IPostRoleService>().RoleTrees(); return ApiResult.Success(result); } /// <summary> /// 获取岗位信息 /// </summary> /// <param name="id"></param> /// <returns></returns> //[HttpGet] //public new ApiResult<PostRole> ViewById(string id) //{ // return ApiResult.Failure<PostRole>("呵呵哒"); //} /// <summary> /// 根据ID获取视图 /// </summary> /// <param name="id">标识</param> [HttpGet] [Display(Description = "根据Id获取单个实例")] public override ApiResult<PostRole> ViewById(string id) { if (BaseService == null) { return ApiResult.Failure<PostRole>("请在控制器中定义BaseService"); } var result = Resolve<IPostRoleService>().GetViewById(id); var tree = Resolve<IPostRoleService>().RoleTrees(); //判断第一级 是否勾选,如果勾选 判断第二季是否全选 //取出所有一级有勾选的菜单 var roleIds = result.RoleIds; result.RoleIds = new List<ObjectId>(); var one = tree.Select(s => s.Id).Where(s => roleIds.Contains(s)); result.RoleIds = GetPostRoleId(tree, roleIds); return ApiResult.Success(result); } /// <summary> /// 获取选中的id ,如果下级未全选则上级不返回 /// </summary> /// <param name="input"></param> /// <param name="ids"></param> /// <returns></returns> private List<ObjectId> GetPostRoleId(IList<PlatformRoleTreeOutput> input, IList<ObjectId> ids) { var result = new List<ObjectId>(); if (ids == null || input == null) { return result; } foreach (var item in input) { foreach (var items in item.AppItems) { foreach (var itemNode in items.AppItems) { var id = ids.SingleOrDefault(s => s == itemNode.Id); if (id != null && ObjectId.Empty != id) { result.Add(itemNode.Id); //第三级全部加入 } } //如果全选则把上级写入 if (items.AppItems.Count == items.AppItems.Count(s => ids.Contains(s.Id))) { result.Add(items.Id); } } if (item.AppItems.Count == item.AppItems.Count(s => ids.Contains(s.Id))) { result.Add(item.Id); } } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Snow { class XML { public XML{ } } private void createNode(string url,DateTime Date, XmlTextWriter writer) { writer.WriteStartElement("WebPage"); writer.WriteStartElement("URL"); writer.WriteString(url); //end <URL> writer.WriteEndElement(); writer.WriteStartElement("Date Visited"); writer.WriteString(Convert.ToString(Date)); //end <Date Visited> writer.WriteEndElement(); //end <Web Page> writer.WriteEndElement(); } }
using Automatonymous; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleDistributedSystem.Coordination { public class ExecuteTransactionState : SagaStateMachineInstance { public MassTransit.IServiceBus Bus { get; set; } public Guid CorrelationId { get; private set; } public ExecuteTransactionState(Guid referenceTransactionId) { CorrelationId = referenceTransactionId; } public ExecuteTransactionState() { } public State CurrentState { get; set; } public string TransactionName { get; set; } public string AccountNumber { get; set; } public decimal TransactionAmount { get; set; } public DateTime? TransactionRequestTime { get; set; } public DateTime? TransactionExecutionTime { get; set; } public string CustomerMobileNumber { get; set; } public string CustomerEmailAddress { get; set; } public string TransactionReferenceNumberOnHost { get; set; } public string TransactionSourceChannel { get; set; } public string ErrorCode { get; set; } public string ErrorDescription { get; set; } public string FailureStep { get; set; } public DateTime? TransactionFailureTime { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; [CreateAssetMenu(menuName = "Create Text Sequence")] public class TextSequence : ScriptableObject { public float TotalTime; [Serializable] public class Dialog { public float TimeCondition; public float LockoutTime; public string Sender; public string SenderMessage; public string CorrectResponse; public List<string> WrongResponses; } public List<Dialog> DialogList; [ContextMenu("SortByTime")] private void SortByTime() { DialogList.Sort((x, y) => { return (x.TimeCondition.CompareTo(y.TimeCondition)); }); } [ContextMenu("RefreshTotalTime")] public void RefreshTotalTime() { TotalTime = 0; foreach (var dialog in DialogList) { TotalTime = Mathf.Max(dialog.TimeCondition, TotalTime) + dialog.LockoutTime; } } }
using HROADS_WebApi.Domains; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HROADS_WebApi.Interfaces { interface ITiposDeHabilidadesRepository { /// <summary> /// Lista todos os TipoDeHabilidade /// </summary> /// <returns> Uma lista de TiposDeHabilidade</returns> List<TiposDeHabilidade> Listar(); /// <summary> /// Busca um TipoDeHabilidade pelo id /// </summary> /// <param name="id"> id do TipoDeHabilidade buscado </param> /// <returns> TipoDeHabilidade buscado</returns> TiposDeHabilidade BuscarPorId(int id); /// <summary> /// Cadastra um novo TipoDeHabilidade /// </summary> /// <param name="novoTipo">Objeto novoTipoDeHabilidade que sera cadastrado</param> void Cadastrar(TiposDeHabilidade novoTipo); /// <summary> /// Atualiza um TipoDeHabilidade /// </summary> /// <param name="id"> ID do TipoDeHabilidade que sera atualizado</param> /// <param name="tipoAtualizado">Objeto TipoDeHabilidade com as novas informacoes</param> void Atualizar(int id, TiposDeHabilidade tipoAtualizado); /// <summary> /// Deleta um TipoDeHabilidade /// </summary> /// <param name="id">id do TipoDeHabilidade que sera deletado </param> void Deletar(int id); List<TiposDeHabilidade> ListarHabilidades(); } }
using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.system; using gView.GraphicsEngine.Abstraction; using System; using System.Collections.Generic; using System.Drawing; using System.Threading.Tasks; using System.Windows.Forms; namespace gView.Framework.UI.Controls { [gView.Framework.system.RegisterPlugIn("3143FA90-587B-4cd0-B508-1BE88882E6B3")] public partial class PreviewControl : UserControl, IExplorerTabPage { private IExplorerObject _exObject = null; private ToolButton _activeToolButton; private MapDocument _mapDocument; private IMap _map; private List<ITool> _tools = new List<ITool>(); private bool _exObjectInvokeRequired = false; public PreviewControl() { InitializeComponent(); } #region IExplorerTabPage Members public Control Control { get { return this; } } public void OnCreate(object hook) { if (hook is IGUIApplication) { _mapDocument = new MapDocument(new ExplorerMapApplication((IGUIApplication)hook, this, mapView1)); _map = new Map(); _map.Display.refScale = 0; _map.DrawingLayer += new DrawingLayerEvent(DrawingLayer); _mapDocument.AddMap(_map); _mapDocument.FocusMap = _map; PlugInManager compMan = new PlugInManager(); ITool zoomin = compMan.CreateInstance(KnownObjects.Tools_DynamicZoomIn) as ITool; ITool zoomout = compMan.CreateInstance(KnownObjects.Tools_DynamicZoomOut) as ITool; ITool smartNav = compMan.CreateInstance(KnownObjects.Tools_SmartNavigation) as ITool; ITool pan = compMan.CreateInstance(KnownObjects.Tools_Pan) as ITool; //ITool zoomextent = compMan.CreateInstance(KnownObjects.Tools_Zoom2Extent) as ITool; //ITool toc = compMan.CreateInstance(KnownObjects.Tools_TOC) as ITool; ITool identify = compMan.CreateInstance(KnownObjects.Tools_Identify) as ITool; ITool queryCombo = compMan.CreateInstance(KnownObjects.Tools_QueryThemeCombo) as ITool; if (zoomin != null) { zoomin.OnCreate(_mapDocument); } if (zoomout != null) { zoomout.OnCreate(_mapDocument); } if (smartNav != null) { smartNav.OnCreate(_mapDocument); } if (pan != null) { pan.OnCreate(_mapDocument); } if (identify != null) { identify.OnCreate(_mapDocument); identify.OnCreate(this); } if (queryCombo != null) { queryCombo.OnCreate(_mapDocument); } //if (zoomextent != null) zoomextent.OnCreate(_mapDocument); //if (toc != null) toc.OnCreate(_mapDocument); if (zoomin != null) { toolStrip.Items.Add(new ToolButton(zoomin)); } if (zoomout != null) { toolStrip.Items.Add(new ToolButton(zoomout)); } if (smartNav != null) { toolStrip.Items.Add(_activeToolButton = new ToolButton(smartNav)); } if (pan != null) { toolStrip.Items.Add(new ToolButton(pan)); } //if(zoomextent!=null) toolStrip.Items.Add(new ToolButton(zoomextent)); //if(toc!=null) toolStrip.Items.Add(new ToolButton(toc)); if (identify != null) { toolStrip.Items.Add(new ToolButton(identify)); } if (queryCombo is IToolItem) { toolStrip.Items.Add(((IToolItem)queryCombo).ToolItem); } if (zoomin != null) { _tools.Add(zoomin); } if (zoomout != null) { _tools.Add(zoomout); } if (smartNav != null) { _tools.Add(smartNav); } if (pan != null) { _tools.Add(pan); } //if (zoomextent != null) _tools.Add(zoomextent); //if (toc != null) _tools.Add(toc); if (identify != null) { _tools.Add(identify); } if (queryCombo != null) { _tools.Add(queryCombo); } _activeToolButton.Checked = true; mapView1.Map = _map; _map.NewBitmap += InvokeNewBitmapCreated; _map.DoRefreshMapView += InvokeDoRefreshMapView; mapView1.Tool = _activeToolButton.Tool; } } private void InvokeDoRefreshMapView() { mapView1.MakeMapViewRefresh(); } private void InvokeNewBitmapCreated(IBitmap image) { mapView1.NewBitmapCreated(image); } public Task<bool> OnShow() { // Starts Refresh in the background, do NOT await!!!! Otherwise it blocks UI Task.Run(async () => { if (_exObjectInvokeRequired) { await InvokeSetExplorerObject(); } await Task.Delay(100); mapView1.RefreshMap(DrawPhase.Geography); }); return Task.FromResult(true); } public void OnHide() { mapView1.CancelDrawing(DrawPhase.All); } async private Task InvokeSetExplorerObject() { _exObjectInvokeRequired = false; mapView1.CancelDrawing(DrawPhase.All); foreach (IDatasetElement element in _map.MapElements) { _map.RemoveLayer(element as ILayer); } if (_exObject != null) { var instance = await _exObject.GetInstanceAsync(); if (instance is IFeatureClass && ((IFeatureClass)instance).Envelope != null) { mapView1.Map = _map; _map.AddLayer(LayerFactory.Create(instance as IClass)); _map.Display.Limit = ((IFeatureClass)instance).Envelope; _map.Display.ZoomTo(((IFeatureClass)instance).Envelope); } else if (instance is IRasterClass && ((IRasterClass)instance).Polygon != null) { mapView1.Map = _map; _map.AddLayer(LayerFactory.Create(instance as IClass)); _map.Display.Limit = ((IRasterClass)instance).Polygon.Envelope; _map.Display.ZoomTo(((IRasterClass)instance).Polygon.Envelope); } else if (instance is IWebServiceClass && ((IWebServiceClass)instance).Envelope != null) { mapView1.Map = _map; _map.AddLayer(LayerFactory.Create(instance as IClass)); _map.Display.Limit = ((IWebServiceClass)instance).Envelope; _map.Display.ZoomTo(((IWebServiceClass)instance).Envelope); } else if (instance is IFeatureDataset) { mapView1.Map = _map; IFeatureDataset dataset = (IFeatureDataset)instance; foreach (IDatasetElement element in await dataset.Elements()) { ILayer layer = LayerFactory.Create(element.Class) as ILayer; if (layer == null) { continue; } _map.AddLayer(layer); } _map.Display.Limit = await dataset.Envelope(); _map.Display.ZoomTo(await dataset.Envelope()); } else if (instance is Map) { Map map = (Map)instance; map.NewBitmap -= InvokeNewBitmapCreated; map.DoRefreshMapView -= InvokeDoRefreshMapView; map.NewBitmap += InvokeNewBitmapCreated; map.DoRefreshMapView += InvokeDoRefreshMapView; mapView1.Map = (Map)instance; } } } public IExplorerObject GetExplorerObject() { return _exObject; } public Task SetExplorerObjectAsync(IExplorerObject value) { if (_exObject == value || _map == null) { return Task.CompletedTask; } _exObject = value; _exObjectInvokeRequired = true; return Task.CompletedTask; } public Task<bool> ShowWith(IExplorerObject exObject) { if (exObject == null) { return Task.FromResult(false); } if (TypeHelper.Match(exObject.ObjectType, typeof(IFeatureClass)) || TypeHelper.Match(exObject.ObjectType, typeof(IRasterClass)) || TypeHelper.Match(exObject.ObjectType, typeof(IWebServiceClass)) || TypeHelper.Match(exObject.ObjectType, typeof(IFeatureDataset)) || TypeHelper.Match(exObject.ObjectType, typeof(Map))) { return Task.FromResult(true); } return Task.FromResult(false); } public string Title { get { return "Preview"; } } async public Task<bool> RefreshContents() { if (_exObjectInvokeRequired) { await InvokeSetExplorerObject(); } mapView1.CancelDrawing(DrawPhase.All); mapView1.RefreshMap(DrawPhase.All); return true; } #endregion private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (!(e.ClickedItem is ToolButton) || _activeToolButton == e.ClickedItem) { return; } _activeToolButton.Checked = false; _activeToolButton = (ToolButton)e.ClickedItem; _activeToolButton.Checked = true; mapView1.Tool = _activeToolButton.Tool; } internal ITool Tool(Guid guid) { foreach (ITool tool in _tools) { if (PlugInManager.PlugInID(tool) == guid) { return tool; } } return null; } public Task RefreshMap() { mapView1.RefreshMap(DrawPhase.All); return Task.CompletedTask; } #region IOrder Members public int SortOrder { get { return 10; } } #endregion #region mapView private delegate void DrawingLayerCallback(string layerName); private void DrawingLayer(string layerName) { if (statusStrip1.InvokeRequired) { DrawingLayerCallback d = new DrawingLayerCallback(DrawingLayer); statusStrip1.Invoke(d, new object[] { layerName }); } else { if (layerName == "") { toolStripStatusLabel1.Text = ""; } else { toolStripStatusLabel1.Text = "Drawing Layer " + layerName + "..."; } } } private void mapView1_AfterRefreshMap() { DrawingLayer(""); } private delegate void CursorMoveCallback(int x, int y, double X, double Y); private void mapView1_CursorMove(int x, int y, double X, double Y) { if (statusStrip1.InvokeRequired) { CursorMoveCallback d = new CursorMoveCallback(mapView1_CursorMove); statusStrip1.Invoke(d, new object[] { x, y, X, Y }); } else { toolStripStatusLabel2.Text = "X: " + Math.Round(X, 2); toolStripStatusLabel3.Text = "Y: " + Math.Round(Y, 2); } } #endregion } internal class ToolButton : ToolStripButton { private ITool _tool; public ToolButton(ITool tool) : base((Image)tool.Image) { _tool = tool; } public ITool Tool { get { return _tool; } } } }
using System; using Utilities; namespace EddiEvents { [PublicAPI] public class FighterRebuiltEvent : Event { public const string NAME = "Fighter rebuilt"; public const string DESCRIPTION = "Triggered when a ship's fighter is rebuilt in the hangar"; public const string SAMPLE = "{\"timestamp\":\"2016-07-22T10:53:19Z\",\"event\":\"FighterRebuilt\",\"Loadout\":\"four\", \"ID\":134}"; [PublicAPI("The loadout of the fighter")] public string loadout { get; private set; } [PublicAPI("The fighter's id")] public int id { get; private set; } public FighterRebuiltEvent(DateTime timestamp, string loadout, int id) : base(timestamp, NAME) { this.loadout = loadout; this.id = id; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using CreateUser.Attributes; namespace CreateUser.Models { public class Tag { public Tag() { this.Albums = new HashSet<Album>(); } public int Id { get; set; } [Required, Tag] public string Name { get; set; } public virtual ICollection<Album> Albums { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio4 { class RaizesEq2 { static void Main(string[] args) { { Console.Write("Digite o coef. de x^2 "); double A = Convert.ToDouble(Console.ReadLine()); Console.Write("Digite o coef. de x "); double B = Convert.ToDouble(Console.ReadLine()); Console.Write("Digite o coef. independente "); double C = Convert.ToDouble(Console.ReadLine()); double Disc = Math.Pow(B, 2) - 4 * A * C; if (Disc > 0) { Console.WriteLine("x1={0:F2}", (-B + Math.Sqrt(Disc)) / (2 * A)); Console.WriteLine("x1={0:F2}", (-B - Math.Sqrt(Disc)) / (2 * A)); } else if (Disc == 0) Console.WriteLine("x1=x2 {0} ", -B / (2 * A)); else Console.WriteLine(" Raízes imaginárias"); } } } }
using Microsoft.SqlServer.Management.Smo; using SqlServerWebAdmin.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SqlServerWebAdmin { public partial class CreateTable : System.Web.UI.Page { public CreateTable() { Page.Init += new System.EventHandler(Page_Init); } protected void Page_Load(object sender, System.EventArgs e) { ErrorCreatingLabel.Visible = false; } protected void CreateNewTableButton_Click(object sender, System.EventArgs e) { if (TableNameTextBox.Text.Length == 0) { ErrorCreatingLabel.Visible = true; ErrorCreatingLabel.Text = "The new table name cannot be blank"; return; } Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer; try { server.Connect(); } catch (System.Exception ex) { //Response.Redirect("Error.aspx?errorPassCode=" + 2002); Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace))); } Database database = server.Databases[HttpContext.Current.Server.HtmlDecode(HttpContext.Current.Request["database"])]; ErrorCreatingLabel.Visible = false; Microsoft.SqlServer.Management.Smo.Table table = server.Databases[database.Name].Tables[TableNameTextBox.Text]; // Ensure that the table doesn't exist yet if (table == null) { // Now we have to do a quick check and see if it's a valid name for a table // The only reliable way to do this is to try to create the table and see what happens // In order to find out whether the table name is valid, we create a temporary dummy table // and see what happens. Microsoft.SqlServer.Management.Smo.Table dummyTable = null; try { dummyTable = new Microsoft.SqlServer.Management.Smo.Table(database, TableNameTextBox.Text); Column colName = new Column(dummyTable, "ID", DataType.VarChar(50)); colName.Nullable = true; dummyTable.Columns.Add(colName); dummyTable.Create(); } catch (Exception ex) { if(dummyTable != null) dummyTable.Drop(); server.Disconnect(); ErrorCreatingLabel.Visible = true; ErrorCreatingLabel.Text = "There was an error creating the table:<br>" + Server.HtmlEncode(ex.Message).Replace("\n", "<br>"); return; } // Delete the dummy table dummyTable.Drop(); server.Disconnect(); Response.Redirect(String.Format("~/Modules/Column/editcolumn.aspx?database={0}&table={1}", Server.UrlEncode(database.Name), Server.UrlEncode(TableNameTextBox.Text))); } else { server.Disconnect(); ErrorCreatingLabel.Visible = true; ErrorCreatingLabel.Text = "A table with this name already exists."; } } protected void Page_Init(object sender, EventArgs e) { if (Page.User.Identity.IsAuthenticated) { Page.ViewStateUserKey = Page.Session.SessionID; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WebAppAdvocacia.Models; using PagedList; using Rotativa; namespace Areas.Administracao.Controllers { public class ProcessoController : Controller { private ContextoEF db = new ContextoEF(); public ActionResult GerarPDF(int? pagina) { int tamanhoPagina = 2; int numeroPagina = pagina ?? 1; var modelo = db.Processos.OrderBy(e => e.Situacao).ToPagedList(numeroPagina, tamanhoPagina); var pdf = new ViewAsPdf { ViewName = "IndexParaImpressao", Model = modelo }; return pdf; } public ActionResult GerarPDFEmDetalhes(int? id) { var modelo = db.Processos.Find(id); var pdf = new ViewAsPdf { ViewName = "IndexParaImpressaoEmDetalhes", Model = modelo }; return pdf; } public ActionResult ConsultarProcesso(int? pagina, string NumeroProcesso = null) { int tamanhoPagina = 2; int numeroPagina = pagina ?? 1; var Processo = new object(); if (!string.IsNullOrEmpty(NumeroProcesso)) { Processo = db.Processos .Where(e => e.NumeroProcesso.ToString() == (NumeroProcesso)) .OrderBy(e => e.NumeroProcesso).ToPagedList(numeroPagina, tamanhoPagina); } else { Processo = db.Processos.OrderBy(e => e.NumeroProcesso).ToPagedList(numeroPagina, tamanhoPagina); } return View("Index", Processo); } // GET: Processo public ActionResult Index(string ordenacao, int? pagina) { var processos = db.Processos.Include(p => p.Pessoa).Include(p => p.Vara); ViewBag.OrdenacaoAtual = ordenacao; ViewBag.SituacaoParam = string.IsNullOrEmpty(ordenacao) ? "Situacao_Desc" : ""; ViewBag.DataAberturaParam = ordenacao == "DataAbertura" ? "DataAbertura_Desc" : "DataAbertura"; int tamanhoPagina = 2; int numeroPagina = pagina ?? 1; //var Processo = from e in db.Processos select e; switch (ordenacao) { case "Situacao_Desc": processos = db.Processos.Include(e => e.Pessoa).Include(e => e.Vara).OrderByDescending(s => s.Situacao); break; case "DataAbertura": processos = db.Processos.Include(e => e.Pessoa).Include(e => e.Vara).OrderBy(s => s.DataAbertura); break; case "DataAbertura_Desc": processos = db.Processos.Include(e => e.Pessoa).Include(e => e.Vara).OrderByDescending(s => s.DataAbertura); break; default: processos = db.Processos.Include(e => e.Pessoa).Include(e => e.Vara).OrderBy(s => s.Situacao); break; } return View(processos.ToPagedList(numeroPagina, tamanhoPagina)); } // GET: Processo/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Processo processo = db.Processos.Find(id); if (processo == null) { return HttpNotFound(); } return View(processo); } // GET: Processo/Create public ActionResult Create() { ViewBag.PessoaID = new SelectList(db.Pessoas, "PessoaID", "Nome"); ViewBag.VaraID = new SelectList(db.Varas, "VaraID", "Descricao"); return View(); } // POST: Processo/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Processo processo) { if(processo.DataAbertura > processo.DataConclusao) { ModelState.AddModelError("", "A data de abertura deve ser menor ou igual a data de conclusão"); } if (ModelState.IsValid) { db.Processos.Add(processo); db.SaveChanges(); TempData["Mensagem"] = "Processo Cadastrado Com Sucesso!"; return RedirectToAction("Index"); } ViewBag.PessoaID = new SelectList(db.Pessoas, "PessoaID", "Nome", processo.PessoaID); ViewBag.VaraID = new SelectList(db.Varas, "VaraID", "Descricao", processo.VaraID); return View(processo); } // GET: Processo/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Processo processo = db.Processos.Find(id); if (processo == null) { return HttpNotFound(); } ViewBag.PessoaID = new SelectList(db.Pessoas, "PessoaID", "Nome", processo.PessoaID); ViewBag.VaraID = new SelectList(db.Varas, "VaraID", "Descricao", processo.VaraID); return View(processo); } // POST: Processo/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ProcessoID,NumeroProcesso,DataAbertura,DataConclusao,Situacao,PessoaID,VaraID,Descricao")] Processo processo) { if (ModelState.IsValid) { db.Entry(processo).State = EntityState.Modified; db.SaveChanges(); TempData["Mensagem"] = "Processo Atualizado Com Sucesso!"; return RedirectToAction("Index"); } ViewBag.PessoaID = new SelectList(db.Pessoas, "PessoaID", "Nome", processo.PessoaID); ViewBag.VaraID = new SelectList(db.Varas, "VaraID", "Descricao", processo.VaraID); return View(processo); } // GET: Processo/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Processo processo = db.Processos.Find(id); if (processo == null) { return HttpNotFound(); } return View(processo); } // POST: Processo/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Processo processo = db.Processos.Find(id); db.Processos.Remove(processo); db.SaveChanges(); TempData["Mensagem"] = "Processo Excluido Com Sucesso!"; return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using PersonInfo.Model; using System.Threading.Tasks; namespace PersonInfo.Services.Interface { public interface IProcessPersonInfoService { Task<PersonInfoModel> GetPersonInfoFromApi(string personInfo); } }
using System; using Musical_WebStore_BlazorApp.Server.Data.Models; namespace Admin.Models { public class Review: Entity { public string UserId {get;set;} public virtual User User {get;set;} public int CompanyId {get;set;} public virtual Company Company {get;set;} public int ServiceId {get;set;} public virtual Service Service {get;set;} public string Text {get;set;} public int Mark {get;set;} } }
using UnityEngine; using UnityEditor; using Ardunity; [CustomEditor(typeof(BitFlagInput))] public class BitFlagInputEditor : ArdunityObjectEditor { bool foldout = false; SerializedProperty script; SerializedProperty bitCombine; void OnEnable() { script = serializedObject.FindProperty("m_Script"); bitCombine = serializedObject.FindProperty("bitCombine"); } public override void OnInspectorGUI() { this.serializedObject.Update(); BitFlagInput bridge = (BitFlagInput)target; GUI.enabled = false; EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]); GUI.enabled = true; foldout = EditorGUILayout.Foldout(foldout, "Mask: " + BitFlagInput.ToMaskString(bridge.bitMask)); if(foldout) { EditorGUI.indentLevel++; for(int i=0; i<16; i++) { bool bit = false; if((bridge.bitMask & (1 << i)) > 0) bit = true; bit = EditorGUILayout.Toggle(string.Format("Bit{0:d}", i), bit); if(bit) bridge.bitMask |= (1 << i); else bridge.bitMask &= ~(1 << i); } EditorGUI.indentLevel--; } EditorGUILayout.PropertyField(bitCombine, new GUIContent("Bit Combine")); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Value", GUILayout.Width(80f)); int index = 0; if(bridge.Value) index = 1; GUILayout.SelectionGrid(index, new string[] {"FALSE", "TRUE"}, 2); EditorGUILayout.EndHorizontal(); if(Application.isPlaying) EditorUtility.SetDirty(target); this.serializedObject.ApplyModifiedProperties(); } static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func) { string menuName = "Unity/Add Bridge/Input/BitFlagInput"; if(Selection.activeGameObject != null) menu.AddItem(new GUIContent(menuName), false, func, typeof(BitFlagInput)); else menu.AddDisabledItem(new GUIContent(menuName)); } }
using System; using System.Collections.Generic; using Flunt.Notifications; namespace Projeto.Models { public class DataResult { public DataResult() { } public DataResult(bool success, string message, IReadOnlyCollection<Notification> notifications, Object objeto) { Success = success; Message = message; Notifications = notifications; Objeto = objeto; } public bool Success { get; set; } public string Message { get; set; } public IReadOnlyCollection<Notification> Notifications { get; set; } // Retornar uma lista com notificações public Object Objeto { get; set; } // Retorna o objeto cadastrado, atualizado ou excluído. } }
using Lucene.Net.Documents; using System; using System.Collections.Generic; namespace Masuit.LuceneEFCore.SearchEngine.Interfaces { /// <summary> /// 搜索引擎 /// </summary> public interface ILuceneIndexSearcher { /// <summary> /// 分词 /// </summary> /// <param name="keyword"></param> /// <returns></returns> List<string> CutKeywords(string keyword); /// <summary> /// 搜索单条记录 /// </summary> /// <param name="options"></param> /// <returns></returns> Document ScoredSearchSingle(SearchOptions options); /// <summary> /// 按权重搜索 /// </summary> /// <param name="options"></param> /// <returns></returns> ILuceneSearchResultCollection ScoredSearch(SearchOptions options); /// <summary> /// 按权重搜索 /// </summary> /// <param name="keywords">关键词</param> /// <param name="fields">限定检索字段</param> /// <param name="maximumNumberOfHits">最大检索量</param> /// <param name="boosts">多字段搜索时,给字段的搜索加速</param> /// <param name="type">文档类型</param> /// <param name="sortBy">排序字段</param> /// <param name="skip">跳过多少条</param> /// <param name="take">取多少条</param> /// <returns></returns> ILuceneSearchResultCollection ScoredSearch(string keywords, string fields, int maximumNumberOfHits, Dictionary<string, float> boosts, Type type, string sortBy, int? skip, int? take); } }
using UnityEngine; using System.Collections; namespace VolumetricFogAndMist { [AddComponentMenu("")] public class FogAreaCullingManager : MonoBehaviour { public VolumetricFog fog; void OnEnable() { if (fog == null) { fog = GetComponent<VolumetricFog>(); if (fog == null) { fog = gameObject.AddComponent<VolumetricFog>(); } } } void OnBecameVisible() { if (fog != null) fog.enabled = true; } void OnBecameInvisible() { if (fog != null) fog.enabled = false; } } }
using System; using System.Collections.Generic; using System.Linq; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; using StardewValley.Menus; namespace ThreeHeartDancePartner { public class Mod : StardewModdingAPI.Mod { /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { helper.Events.Display.MenuChanged += onMenuChanged; } /// <summary>Raised after a game menu is opened, closed, or replaced.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void onMenuChanged(object sender, MenuChangedEventArgs e) { // get dialog box if (!(e.NewMenu is DialogueBox dialogBox)) return; // get festival Event festival = Game1.currentLocation?.currentEvent; if (Game1.currentLocation?.Name != "Temp" || festival?.FestivalName != "Flower Dance") return; // check if rejection dialogue Dialogue dialog = this.Helper.Reflection.GetField<Dialogue>(dialogBox, "characterDialogue").GetValue(); NPC npc = dialog.speaker; if (!npc.datable.Value || npc.HasPartnerForDance) return; string rejectionText = new Dialogue(Game1.content.Load<Dictionary<string, string>>($"Characters\\Dialogue\\{dialog.speaker.Name}")["danceRejection"], dialog.speaker).getCurrentDialogue(); if (dialog.getCurrentDialogue() != rejectionText) return; // replace with accept dialog // The original stuff, only the relationship point check is modified. (1000 -> 750) if (!npc.HasPartnerForDance && Game1.player.getFriendshipLevelForNPC(npc.Name) >= 750) { string s = ""; switch (npc.Gender) { case NPC.male: s = Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1633"); break; case NPC.female: s = Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1634"); break; } try { Game1.player.changeFriendship(250, Game1.getCharacterFromName(npc.Name)); } catch (Exception) { } Game1.player.dancePartner.Value = npc; npc.setNewDialogue(s); foreach (NPC actor in festival.actors) { if (actor.CurrentDialogue != null && actor.CurrentDialogue.Count > 0 && actor.CurrentDialogue.Peek().getCurrentDialogue().Equals("...")) actor.CurrentDialogue.Clear(); } // Okay, looks like I need to fix the current dialog box Game1.activeClickableMenu = new DialogueBox(new Dialogue(s, npc) { removeOnNextMove = false }); } } } }
using System.Threading.Tasks; namespace FeriaVirtual.App.Desktop.Services.SignIn { public interface ISigninService { Task SigninAsync(string username, string password); } }
namespace AudioText.Models.DataModels { public class CustomerOrderDetails { public CustomerOrderDetails(string address2, string address1, string countryCode, string firstName, string city, string lastName, string state, string zip) { Address2 = address2; Address1 = address1; CountryCode = countryCode; FirstName = firstName; City = city; LastName = lastName; State = state; Zip = zip; } public string Address1 { get; private set; } public string Address2 { get; private set; } public string City { get; private set; } public string CountryCode { get; private set; } public string FirstName { get; private set; } public string LastName { get; private set; } public string State { get; private set; } public string Zip { get; private set; } } }
using CQRSWebAPI.DTOs; using MediatR; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace CQRSWebAPI.Caching { public class CachingBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : ICacheable where TResponse : ResponseDto { private readonly IMemoryCache memoryCache; private readonly ILogger<CachingBehaviour<TRequest, TResponse>> logger; public CachingBehaviour(IMemoryCache memoryCache, ILogger<CachingBehaviour<TRequest, TResponse>> logger) { this.memoryCache = memoryCache; this.logger = logger; } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { var reqName = request.GetType(); logger.LogInformation("{Request} is configured for caching.", reqName); TResponse response; if (memoryCache.TryGetValue(request.CacheKey, out response)) { logger.LogInformation("Returning cached value for {Request}.", reqName); return response; } logger.LogInformation("{Request} CacheKey: {Key} is not inside the cache , executing request.", reqName, request.CacheKey); response = await next(); memoryCache.Set(request.CacheKey, response); return response; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Linq; using System.Threading; using PlanMGMT.Model; using System.Windows; using PlanMGMT.Utility; using System.Diagnostics; namespace PlanMGMT.BLL { public class PlanBLL { private static PlanBLL _instance; private static object _lock = new object();//使用static object作为互斥资源 private static readonly object _obj = new object(); private BLL.PlanBaseBLL _bllPlan = new BLL.PlanBaseBLL(); private BLL.SysLogBLL _bllLog = new BLL.SysLogBLL(); public List<Plan> CurrentPlanList = new List<Plan>(); public List<string> Expanded = new List<string>(); #region 单例 /// <summary> /// /// </summary> public PlanBLL() { } /// <summary> /// 返回唯一实例 /// </summary> public static PlanBLL Instance { get { if (_instance == null) { //lock (_obj) //{ //if (_instance == null) //{ _instance = new PlanBLL(); //} //} } return _instance; } } #endregion /// <summary> /// 获取任务列表 /// </summary> /// <returns></returns> public List<PlanMGMT.Model.Plan> GetPlanList(string wheresql,string orderbysql) { List<PlanMGMT.Model.Plan> list = _bllPlan.GetList<Plan>(wheresql, orderbysql); CurrentPlanList = list; return CurrentPlanList; } public void StartPlan(int planid) { string sql = $"update utb_plan set Status = 1,ActualStart ='{DateTime.Now}' where PlanID ={planid}"; Mysql.Instance.ExecuteSql(sql); } public void StopPlan(int planid) { string sql = $"update utb_plan set Status = 3 where PlanID ={planid}"; Mysql.Instance.ExecuteSql(sql); } public void ContinuePlan(int planid) { string sql = $"update utb_plan set Status = 1 where PlanID ={planid}"; Mysql.Instance.ExecuteSql(sql); } public void CompeletePlan(int planid) { string sql = $"update utb_plan set Status = 2,ActualEnd ='{DateTime.Now}' where PlanID ={planid}"; Mysql.Instance.ExecuteSql(sql); } public void ItemClick(string type, Model.Plan mod) { Error error = GetEnableChange(mod); if (error.ErrCode != 0) { Helper.Instance.AlertError(error.ErrText); return; } // 1:查看 2:删除 3:开始/结束 if (type == "1") { View.PlanEdit vPlan = new View.PlanEdit(); vPlan.ID = mod.PlanID; vPlan.ShowDialog(); } else if (type == "2") { Helper.Instance.AlertConfirm(null, "确定删除?", () => { try { _bllPlan.Delete(" PlanID=" + mod.PlanID); Helper.Instance.AlertSuccess("操作成功!"); } catch (Exception ex) { Helper.Instance.AlertError("操作失败!"); MSL.Tool.LogHelper.Instance.WriteLog("MainWindow DropList 删除选中项\r\n" + ex.ToString()); } }); } } public Error GetEnableChange(Model.Plan plan) { Error e = new Error(); if (Utility.ProU.Instance.PspUser.RoleID > 1) { e.ErrCode = 0; e.ErrText = ""; } else { if (plan.InCharge == Utility.ProU.Instance.PspUser.UserCode) { if (plan.ChangeCount == 0) { e.ErrCode = 0; e.ErrText = ""; } else { e.ErrCode = 9999; e.ErrText = "你的计划修改次数已达上限,请联系主管修改"; } } else { e.ErrCode = 9999; e.ErrText = "您不能编辑他人的计划"; } } return e; } public Error GetEnableTimer(Model.Plan plan) { Error e = new Error(); if (plan.InCharge != Utility.ProU.Instance.PspUser.UserCode) { e.ErrCode = 9999; e.ErrText = "您无法操作他人的计划"; } else { e.ErrCode = 0; e.ErrText = ""; } return e; } /// <summary> /// 进行中任务数量 /// </summary> /// <returns></returns> public int RunningTaskCnt() { int c = 0; string sql = $"select Count(*) from utb_plan where Status = 1 and InCharge='{ProU.Instance.PspUser.UserCode}'"; object o = Mysql.Instance.GetSingle(sql); if(o!=null) { try { c = int.Parse(o.ToString()); } catch(Exception e) { Helper.Instance.AlertError(e.Message); } } else { c = 0; } return c; } public int UnStartTaskCnt() { int c = 0; string sql = $"select Count(*) from utb_plan where Status = 0 and InCharge='{ProU.Instance.PspUser.UserCode}'"; object o = Mysql.Instance.GetSingle(sql); if (o != null) { try { c = int.Parse(o.ToString()); } catch (Exception e) { Helper.Instance.AlertError(e.Message); } } else { c = 0; } return c; } /// <summary> /// 暂停任务数量 /// </summary> /// <returns></returns> public int StopTaskCnt() { int c = 0; string sql = $"select Count(*) from utb_plan where Status = 3 and InCharge='{ProU.Instance.PspUser.UserCode}'"; object o = Mysql.Instance.GetSingle(sql); if (o != null) { try { c = int.Parse(o.ToString()); } catch (Exception e) { Helper.Instance.AlertError(e.Message); } } else { c = 0; } return c; } /// <summary> /// 延期任务数量 /// </summary> /// <returns></returns> public int PastTaskCnt() { int c = 0; string sql = $"select Count(*) from utb_plan where Status <> 2 and InCharge='{ProU.Instance.PspUser.UserCode}' and PlanEnd<'{DateTime.Now}'"; object o = Mysql.Instance.GetSingle(sql); if (o != null) { try { c = int.Parse(o.ToString()); } catch (Exception e) { Helper.Instance.AlertError(e.Message); } } else { c = 0; } return c; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class BaseQuestBoolRequirement { public int boolID; public string boolDescription; public bool objectiveFulfilled; }
using System; using System.Collections.Generic; namespace POSServices.Models { public partial class DiscountRetail { public int Id { get; set; } public int DiscountCategory { get; set; } public string DiscountCode { get; set; } public string DiscountName { get; set; } public int CustomerGroupId { get; set; } public string DiscountPartner { get; set; } public string Description { get; set; } public int? DiscountType { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public bool? Status { get; set; } public int? DiscountPercent { get; set; } public bool? TriggerSt { get; set; } public decimal? DiscountCash { get; set; } public int? Qty { get; set; } public decimal? Amount { get; set; } public int? Priority { get; set; } public DateTime? CreatedDate { get; set; } public DateTime? ApprovedDate { get; set; } public int? QtyMin { get; set; } public int? QtyMax { get; set; } public decimal? AmountMin { get; set; } public decimal? AmountMax { get; set; } public virtual CustomerGroup CustomerGroup { get; set; } } }
namespace DChild.Gameplay.Systems.Serialization { [System.Serializable] public struct PlayerProgress { public bool hasVisitedSS; } }
using System; using System.Collections.Generic; using System.Linq; using DelftTools.Shell.Core; using DelftTools.Shell.Core.Workflow; using DelftTools.Tests.Core.Mocks; using DelftTools.TestUtils; using DelftTools.Utils; using DelftTools.Utils.Collections.Generic; using DelftTools.Utils.Workflow; using log4net.Config; using NUnit.Framework; using Rhino.Mocks; namespace DelftTools.Tests.Core.WorkFlow { [TestFixture] public class CompositeModelTest { [TestFixtureSetUp] public void TestFixtureSetUp() { LogHelper.ConfigureLogging(); } [TestFixtureTearDown] public void TestFixtureTearDown() { LogHelper.ResetLogging(); } [Test] public void TestProgressIndication() { string result = ""; var model1 = new SimplerModel { Name = "source" }; model1.Executing += (s, e) => result += ((SimplerModel)s).Name; var model2 = new SimplerModel { Name = "target" }; model2.Executing += (s, e) => result += ((SimplerModel)s).Name; var compositeModel = new CompositeModel { Name = "composite model", Models = { model1, model2 } }; var progressList = new List<string>(); compositeModel.ProgressChanged += delegate { progressList.Add(compositeModel.GetProgressText()); }; compositeModel.Initialize(); compositeModel.Execute(); Assert.AreEqual("50.00 %", progressList[0]); Assert.AreEqual("100.00 %", progressList[1]); } [Test] public void TestSequenceLinkFirstSourceThenTarget() { string result = ""; SimplerModel sourceModel = new SimplerModel {Name = "source"}; sourceModel.Executing += (s, e) => result += ((SimplerModel)s).Name; SimplerModel targetModel = new SimplerModel { Name = "target" }; targetModel.Executing += (s, e) => result += ((SimplerModel)s).Name; IDataItem sourceInput = new DataItem { Name = "SI", Tag = "SI", Value = new object(), Role = DataItemRole.Input }; IDataItem sourceOutput = new DataItem { Name = "SO", Tag = "SO", Value = new object(), Role = DataItemRole.Output }; IDataItem targetInput = new DataItem { Name = "TI", Tag = "TI", Value = new object(), Role = DataItemRole.Input }; IDataItem targetOutput = new DataItem { Name = "TO", Tag = "TO", Value = new object(), Role = DataItemRole.Output }; sourceModel.DataItems.Add(sourceInput); sourceModel.DataItems.Add(sourceOutput); targetModel.DataItems.Add(targetInput); targetModel.DataItems.Add(targetOutput); var compositeModel = new CompositeModel { Name = "composite model", Models = { sourceModel, targetModel } }; targetInput.LinkTo(sourceOutput); compositeModel.Initialize(); compositeModel.Execute(); Assert.AreEqual("sourcetarget", result); } [Test] public void TestSequenceLinkFirstTargetThenSource() { string result = ""; SimplerModel sourceModel = new SimplerModel { Name = "source" }; sourceModel.Executing += (s, e) => result += ((SimplerModel)s).Name; SimplerModel targetModel = new SimplerModel { Name = "target" }; targetModel.Executing += (s, e) => result += ((SimplerModel)s).Name; IDataItem sourceInput = new DataItem { Name = "SI", Tag = "SI", Value = new object(), Role = DataItemRole.Input }; IDataItem sourceOutput = new DataItem { Name = "SO", Tag = "SO", Value = new object(), Role = DataItemRole.Output }; IDataItem targetInput = new DataItem { Name = "TI", Tag = "TI", Value = new object(), Role = DataItemRole.Input }; IDataItem targetOutput = new DataItem { Name = "TO", Tag = "TO", Value = new object(), Role = DataItemRole.Output }; sourceModel.DataItems.Add(sourceInput); sourceModel.DataItems.Add(sourceOutput); targetModel.DataItems.Add(targetInput); targetModel.DataItems.Add(targetOutput); var compositeModel = new CompositeModel { Name = "composite model", Models = { sourceModel, targetModel } }; sourceInput.LinkTo(targetOutput); compositeModel.Initialize(); compositeModel.Execute(); Assert.AreEqual("targetsource", result); } [Test] public void TestSequenceLinkFirstSourceThenTargetUseDataSets() { string result = ""; SimplerModel sourceModel = new SimplerModel { Name = "source" }; sourceModel.Executing += (s, e) => result += ((SimplerModel)s).Name; SimplerModel targetModel = new SimplerModel { Name = "target" }; targetModel.Executing += (s, e) => result += ((SimplerModel)s).Name; IDataItemSet sourceInputSet = new DataItemSet { Name = "input", Tag = "intput", Role = DataItemRole.Input }; IDataItem sourceInput = new DataItem { Name = "SI", Tag = "SI", Value = new object(), Role = DataItemRole.Input }; sourceInputSet.DataItems.Add(sourceInput); IDataItemSet sourceOutputSet = new DataItemSet { Name = "output", Tag = "output", Role = DataItemRole.Output }; IDataItem sourceOutput = new DataItem { Name = "SO", Tag = "SO", Value = new object(), Role = DataItemRole.Output }; sourceOutputSet.DataItems.Add(sourceOutput); IDataItemSet targetInputSet = new DataItemSet { Name = "input", Tag = "intput", Role = DataItemRole.Input }; IDataItem targetInput = new DataItem { Name = "TI", Tag = "TI", Value = new object(), Role = DataItemRole.Input }; targetInputSet.DataItems.Add(targetInput); IDataItemSet targetOutputSet = new DataItemSet { Name = "output", Tag = "output", Role = DataItemRole.Output }; IDataItem targetOutput = new DataItem { Name = "TO", Tag = "TO", Value = new object(), Role = DataItemRole.Output }; targetOutputSet.DataItems.Add(targetOutput); sourceModel.DataItems.Add(sourceInputSet); sourceModel.DataItems.Add(sourceOutputSet); targetModel.DataItems.Add(targetInputSet); targetModel.DataItems.Add(targetOutputSet); var compositeModel = new CompositeModel { Name = "composite model", Models = { sourceModel, targetModel } }; targetInput.LinkTo(sourceOutput); compositeModel.Initialize(); compositeModel.Execute(); Assert.AreEqual("sourcetarget", result); } [Test] public void TestSequenceLinkFirstTargetThenSourceUseDataSets() { string result = ""; SimplerModel sourceModel = new SimplerModel { Name = "source" }; sourceModel.Executing += (s, e) => result += ((SimplerModel)s).Name; SimplerModel targetModel = new SimplerModel { Name = "target" }; targetModel.Executing += (s, e) => result += ((SimplerModel)s).Name; IDataItemSet sourceInputSet = new DataItemSet { Name = "input", Tag = "intput", Role = DataItemRole.Input }; IDataItem sourceInput = new DataItem { Name = "SI", Tag = "SI", Value = new object(), Role = DataItemRole.Input }; sourceInputSet.DataItems.Add(sourceInput); IDataItemSet sourceOutputSet = new DataItemSet { Name = "output", Tag = "output", Role = DataItemRole.Output }; IDataItem sourceOutput = new DataItem { Name = "SO", Tag = "SO", Value = new object(), Role = DataItemRole.Output }; sourceOutputSet.DataItems.Add(sourceOutput); IDataItemSet targetInputSet = new DataItemSet { Name = "input", Tag = "intput", Role = DataItemRole.Input }; IDataItem targetInput = new DataItem { Name = "TI", Value = new object(), Role = DataItemRole.Input }; targetInputSet.DataItems.Add(targetInput); IDataItemSet targetOutputSet = new DataItemSet { Name = "output", Tag = "output", Role = DataItemRole.Output }; IDataItem targetOutput = new DataItem { Name = "TO", Tag = "TO", Value = new object(), Role = DataItemRole.Output }; targetOutputSet.DataItems.Add(targetOutput); sourceModel.DataItems.Add(sourceInputSet); sourceModel.DataItems.Add(sourceOutputSet); targetModel.DataItems.Add(targetInputSet); targetModel.DataItems.Add(targetOutputSet); var compositeModel = new CompositeModel { Name = "composite model", Models = { sourceModel, targetModel } }; sourceInput.LinkTo(targetOutput); compositeModel.Initialize(); compositeModel.Execute(); Assert.AreEqual("targetsource", result); } /// <summary> /// Links models as model2 to model1 and runs parent composition model. /// Composition model should detect correct order to run models: model2 then model1 /// </summary> /* move to TestPlugin1.Tests [Test] public void LinkModelDataAndRun() { var sourceModel = new SimpleModel {Name = "source model"}; var targetModel = new SimpleModel {Name = "target model"}; var compositeModel = new CompositeModel { Name = "composite model", Models = {targetModel, sourceModel}, // note that models are added in reverse order StartTime = new DateTime(2009, 1, 1, 0, 0, 0), StopTime = new DateTime(2009, 1, 1, 5, 0, 0), TimeStep = new TimeSpan(1, 0, 0) }; // define input for model2 var time = compositeModel.StartTime; sourceModel.InputTimeSeries[time] = 1.0; sourceModel.InputTimeSeries[time.AddHours(1)] = 2.0; sourceModel.InputTimeSeries[time.AddHours(2)] = 3.0; sourceModel.InputTimeSeries[time.AddHours(3)] = 4.0; sourceModel.InputTimeSeries[time.AddHours(4)] = 5.0; // link model2.OutputTimeSeries -> model1.InputTimeSeries var outputDataItem = sourceModel.GetDataItemByValue(sourceModel.OutputTimeSeries); var inputTimeSeries = targetModel.GetDataItemByValue(targetModel.InputTimeSeries); inputTimeSeries.LinkTo(outputDataItem); Assert.AreEqual(sourceModel.OutputTimeSeries, targetModel.InputTimeSeries, "Linking should set value of InputTimeSeries of target model to OutputTimeSeries of source model"); // initialize compositeModel.Initialize(); Assert.AreEqual(0, sourceModel.OutputTimeSeries.Components[0].Values.Count, "Output values of the source model after initialize are not filled in yet"); Assert.AreEqual(0, targetModel.OutputTimeSeries.Components[0].Values.Count, "Output values of the target model after initialize are not filled in yet"); // run model compositeModel.Execute(); Assert.AreEqual(ActivityStatus.Executing, compositeModel.Status); Assert.AreEqual(ActivityStatus.Executing, sourceModel.Status); Assert.AreEqual(ActivityStatus.Executing, targetModel.Status); Assert.AreEqual(1, sourceModel.OutputTimeSeries.Components[0].Values.Count, "Source model should fill in a new value in the output time series"); Assert.AreEqual(1, targetModel.OutputTimeSeries.Components[0].Values.Count, "Target model should fill in a new value in the output time series"); } */ private static readonly MockRepository mocks = new MockRepository(); /// <summary> /// Composite model should clone contained model (deep clone) /// </summary> [Test] public void CloneModel() { var compositeModel = new CompositeModel(); var containedModel = mocks.StrictMock<IModel>(); var modelClone = mocks.StrictMock<IModel>(); using (mocks.Record()) { Expect.Call(containedModel.Owner = compositeModel); Expect.Call(containedModel.DataItems).Return(new EventedList<IDataItem>()).Repeat.Any(); Expect.Call(containedModel.GetDirectChildren()).Return(new EventedList<object>()).Repeat.Any(); Expect.Call(containedModel.DeepClone()).Return(modelClone); containedModel.StatusChanged += null; LastCall.IgnoreArguments(); //containedModel.StatusChanged -= null; //LastCall.IgnoreArguments(); Expect.Call(modelClone.Owner = null).IgnoreArguments(); modelClone.StatusChanged += null; LastCall.IgnoreArguments(); Expect.Call(modelClone.DataItems).Return(new EventedList<IDataItem>()).Repeat.Any(); Expect.Call(modelClone.GetDirectChildren()).Return(new EventedList<object>()).Repeat.Any(); } CompositeModel clonedModel; using (mocks.Playback()) { compositeModel.Models.Add(containedModel); clonedModel = (CompositeModel) compositeModel.DeepClone(); } Assert.AreEqual(compositeModel.Models.Count, clonedModel.Models.Count); } [Test] public void CloneShouldUpdateLinksWithinModel() { //Situation // CompositeModel // |-SourceModel // |-LinkedModel (->SourceModel) //Clone this composite model and expect the c-linkedmodel to be connected to the cloned-sourcemodel. var compositeModel = new CompositeModel(); IModel sourceModel = new TestModel("source"); IDataItem sourceDataItem = new DataItem(new Url(), "sourceItem"); sourceModel.DataItems.Add(sourceDataItem); compositeModel.Models.Add(sourceModel); IModel linkedModel = new TestModel("linked"); IDataItem linkedDataItem = new DataItem {Name = "linkedItem"}; linkedModel.DataItems.Add(linkedDataItem); compositeModel.Models.Add(linkedModel); linkedDataItem.LinkTo(sourceDataItem); var clonedModel = (CompositeModel) compositeModel.DeepClone(); IModel clonedSourceModel = clonedModel.Models.Where(m => m.Name == "source").First(); IModel clonedLinkedModel = clonedModel.Models.Where(m => m.Name == "linked").First(); IDataItem clonedLinkedItem = clonedLinkedModel.DataItems.Where(d => d.Name == "linkedItem").First(); IDataItem clonedSourceItem = clonedSourceModel.DataItems.Where(d => d.Name == "sourceItem").First(); //the cloned sourceitem should not be the the sourcedataitem. Assert.AreNotEqual(clonedSourceItem.Value, sourceDataItem.Value); Assert.IsTrue(clonedLinkedItem.IsLinked); Assert.AreEqual(clonedSourceItem, clonedLinkedItem.LinkedTo); } /// <summary> /// Composite model should clone contained model (deep clone) /// </summary> /* [Test] TODO: move to integration tests? public void CloneModelWithLinkedModels() { var compositeModel = new CompositeModel(); var model1 = new SimpleModel { Name = "model1" }; var model2 = new SimpleModel { Name = "model2" }; compositeModel.Models.Add(model1); compositeModel.Models.Add(model2); // link model input to model output var sourceDataItem = model1.GetDataItemByValue(model1.OutputTimeSeries); var targetDataItem = model2.GetDataItemByValue(model2.InputTimeSeries); targetDataItem.LinkTo(sourceDataItem); var compositeModelClone = (CompositeModel) compositeModel.DeepClone(); Assert.AreEqual(compositeModel.DataItems.Count, compositeModelClone.DataItems.Count); var model1Clone = (SimpleModel) compositeModelClone.Models[0]; var model2Clone = (SimpleModel) compositeModelClone.Models[1]; var sourceDataItemClone = model1Clone.GetDataItemByValue(model1Clone.OutputTimeSeries); var targetDataItemClone = model2Clone.GetDataItemByValue(model2Clone.InputTimeSeries); Assert.AreEqual(sourceDataItemClone, targetDataItemClone.LinkedTo); } */ [Test] public void GetAllItemsRecursiveShouldReturnModels() { var compositeModel = new CompositeModel(); var model = new SimplerModel(); compositeModel.Models.Add(model); IEnumerable<object> enumerable = compositeModel.GetAllItemsRecursive(); Assert.IsTrue(enumerable.Contains(model)); Assert.AreEqual( 1 + compositeModel.DataItems.Count*2 +model.GetAllItemsRecursive().Count(), enumerable.Count()); } [Test] public void CompositeModelBubblesStatusChangesOfChildModels() { var compositeModel = new CompositeModel(); var childModel = new TestModel(); compositeModel.Models.Add(childModel); int callCount = 0; compositeModel.StatusChanged += (s, e) => { Assert.AreEqual(s, childModel); callCount++; }; //action change status of child model childModel.Status = ActivityStatus.Initialized; Assert.AreEqual(1, callCount); compositeModel.Models.Remove(childModel); childModel.Status = ActivityStatus.None; } [Test] public void CompositeModelUnSubscribesFromChildModelsWhenRemoved() { var compositeModel = new CompositeModel(); var childModel = new TestModel(); compositeModel.Models.Add(childModel); compositeModel.Models.Remove(childModel); compositeModel.StatusChanged += (s, e) => Assert.Fail("Should have unsubscribed!"); childModel.Status = ActivityStatus.Initializing; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Account { public sealed class IAccountDetail : AccountDetail { } /// <summary> /// 帐户信息 不可继承 /// </summary> [Attribute.Table(TableName = "AccountInfo")] public class AccountDetail : IModelBase { /// <summary> /// 帐号类型 /// 用以区分不同业务的帐号 /// 如,商家,会员 /// </summary> [Attribute.Field(FieldIndexType = Attribute.FieldIndexType.非聚集)] public int AccountType { get; set; } /// <summary> /// 对应的帐号 /// </summary> [Attribute.Field(FieldIndexType = Attribute.FieldIndexType.非聚集)] public string Account { get; set; } /// <summary> /// 流水种类 /// </summary> [Attribute.Field(FieldIndexType = Attribute.FieldIndexType.非聚集)] public int TransactionType { get; set; } /// <summary> /// 锁定金额 /// </summary> public decimal LockedAmount { get; set; } /// <summary> /// 当前金额 /// </summary> public decimal CurrentBalance { get; set; } /// <summary> /// 可用余额 /// </summary> public decimal AvailableBalance { get { return CurrentBalance - LockedAmount; } } } }
using Nailhang.Display.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nailhang.Display.Controllers { public class IndexController { private readonly IndexBase.Storage.IModulesStorage modulesStorage; public IndexController(IndexBase.Storage.IModulesStorage modulesStorage) { this.modulesStorage = modulesStorage; } DateTime? lmtime; ModuleModel[] lastModules; public IndexModel Get(string rootNamespace) { if (lmtime == null || DateTime.UtcNow > lmtime.Value.Add(TimeSpan.FromMinutes(1))) { lastModules = modulesStorage.GetModules() .Select(w => new ModuleModel { Module = w }) .ToArray(); lmtime = DateTime.UtcNow; } var model = new IndexModel(); var rootDeep = 3; var allModules = lastModules; model.Modules = allModules; model.AllModules = allModules; model.RootNamespaces = allModules .SelectMany(w => GetNamespaces(w.Module.FullName)) .Distinct() .Where(w => w.Split('.').Length <= rootDeep) .OrderBy(w => w) .ToArray(); if (!string.IsNullOrEmpty(rootNamespace)) model.Modules = allModules.Where(w => w.Module.FullName.StartsWith(rootNamespace)); return model; } private IEnumerable<string> GetNamespaces(string @namespace) { while (@namespace.Contains('.')) yield return @namespace = StringUtils.GetNamespace(@namespace); } } }
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityStandardAssets.Characters.FirstPerson; using zm.Common; using zm.Questioning; using zm.Users; using zm.Util; namespace zm.Levels { public class LevelsUI : MonoBehaviour { #region Fields and Properties [SerializeField] private Text lblUserName; [SerializeField] private Text lblPoints; [SerializeField] private Text lblNumOfQuestions; [SerializeField] private GameObject pauseMenu; [SerializeField] private FirstPersonController fpController; [SerializeField] private GameObject Wand; #region Question [SerializeField] private GameObject questionComponent; [SerializeField] private Text lblQuestion; [SerializeField] private Text lblTimer; [SerializeField] private VerticalLayoutGroup lstAnswers; [SerializeField] private AnswerRenderer answerRendererPrefab; [SerializeField] public MainAlertPopup MainAlerPopup; [SerializeField] private QuestionableObjectView questionableObjectViewPrefab; /// <summary> /// Dictionary holding all questions mapped by id. /// </summary> private readonly Dictionary<int, QuestionableObjectView> questionableObjectViews = new Dictionary<int, QuestionableObjectView>(); #endregion Question /// <summary> /// Flag indicating if pause menu is displayed. /// </summary> public bool PauseMenuShown { get { return pauseMenu.gameObject.activeInHierarchy; } } #region End Game [SerializeField] private Text lblUserNameEndGame; [SerializeField] private Text lblPointsEndGame; [SerializeField] private GameObject endGameComponent; #endregion End Game #endregion Fields and Properties #region Public Methods public void Initialize(Level level, UserResult userResult) { UpdateUser(level, userResult); for (int i = 0; i < level.MaxNumQuestions; i++) { AddQuestion(level.GetQuestion()); } } public void UpdateUser(Level level, UserResult userResult) { lblUserName.text = userResult.UserName; lblPoints.text = userResult.Points.ToString(); lblNumOfQuestions.text = userResult.NumOfAnsweredQuestions + "/" + level.NumOfQuestions; } /// <summary> /// Display pause menu. /// </summary> public void ShowPauseMenu() { pauseMenu.gameObject.SetActive(true); ShowCursor(); } /// <summary> /// Hide pause menu. /// </summary> public void ClosePauseMenu() { pauseMenu.gameObject.SetActive(false); HideCursor(); } /// <summary> /// Display component for passed question. Second parameter represents callback that should be triggered when user clicks on any /// answer. /// </summary> public void ShowQuestion(Question question, Action<Answer> onClickAnswerHandler) { questionComponent.gameObject.SetActive(true); lblQuestion.text = question.Text; // Initialize list with levels lstAnswers.transform.Clear(); foreach (Answer answer in question.Answers) { AnswerRenderer answerRenderer = Instantiate(answerRendererPrefab); answerRenderer.Initialize(answer, onClickAnswerHandler); answerRenderer.transform.SetParent(lstAnswers.transform, false); } UpdateTime(question.TimeLimit); ShowCursor(); } public void UpdateTime(float time) { lblTimer.text = (Math.Round(time) < 0 ? 0 : Math.Round(time)).ToString(); } public void HideQuestion() { questionComponent.gameObject.SetActive(false); HideCursor(); } public void AddQuestion(Question question) { QuestionableObjectView view = Instantiate(questionableObjectViewPrefab); view.Initialize(question); view.transform.position = question.Position; questionableObjectViews.Add(question.Id, view); } public void RemoveQuestion(Question question) { QuestionableObjectView view = questionableObjectViews[question.Id]; questionableObjectViews.Remove(question.Id); Destroy(view.gameObject); } /// <summary> /// Returns Question that was hit. If no question is hit - it will return null. /// Also if question is not triggered hit will be treated as miss. /// </summary> /// <returns></returns> public Question GetHitQuestion() { Question question = null; RaycastHit hit; Ray ray = new Ray(Wand.transform.position, Wand.transform.TransformDirection(Vector3.forward)); if (Physics.Raycast(ray, out hit, int.MaxValue)) { if (hit.collider != null && hit.transform.gameObject.tag.Equals(QuestionableObjectView.QuestionsTag)) { QuestionableObjectView view = hit.transform.gameObject.GetComponent<QuestionableObjectView>(); if (view == null) { view = hit.transform.gameObject.GetComponentInParent<QuestionableObjectView>(); } if (view.IsTriggered) { question = view.Question; } } } return question; } /// <summary> /// Display end game component with basic information from last game. /// </summary> public void ShowEndGame(UserResult userResult, Level level) { lblUserNameEndGame.text = userResult.UserName; lblPointsEndGame.text = "Points: " + userResult.Points + "/" + level.MaxPoints; endGameComponent.gameObject.SetActive(true); ShowCursor(); } #endregion Public Methods #region Private Methods /// <summary> /// Unlocks cursor and disables player controller. /// </summary> private void ShowCursor() { fpController.enabled = false; Cursor.visible = true; Cursor.lockState = CursorLockMode.None; fpController.m_MouseLook.lockCursor = false; } private void HideCursor() { fpController.enabled = true; Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; fpController.m_MouseLook.lockCursor = true; } #endregion Private Methoids } }
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json;// Json转换 using System.Data; using BizService.Common; using IWorkFlow.Host; using System; using IWorkFlow.ORM;// namespace BizService.Services.FX_RYLXInfoSvc { // created by zhoushing // FX_RYLXInfoSvc class FX_RYLXInfoSvc : BaseDataHandler { public override string Key { get { return "FX_RYLXInfoSvc"; } } [DataAction("GetData", "content")] public string GetData(string content) { try { var data = new GetDataModel();// 获取数据 FX_RYLXInfo sourceList = new FX_RYLXInfo(); StringBuilder strSql = new StringBuilder(); strSql.Append(@"SELECT A.ryid,A.UserID,A.UserType,A.UserNumber,B.CnName AS UserName,C.FullName AS DepartmentName, (CASE A.UserType WHEN 1 THEN '调查人员' WHEN 2 THEN '询问人员' ELSE '执法人员' END) AS UserTypeText FROM FX_RYLXInfo A LEFT JOIN FX_UserInfo B ON A.UserID = B.UserID LEFT JOIN FX_Department C ON C.DPID = B.DPID ORDER BY A.ryid"); string jsonData = JsonConvert.SerializeObject(Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]); data.sourceList = (List<FX_RYLXInfo>)JsonConvert.DeserializeObject(jsonData, typeof(List<FX_RYLXInfo>)); // 初始化一空行 data.sourceListEdit = new FX_RYLXInfo(); return JsonConvert.SerializeObject( data); } catch (Exception ex) { ComBase.Logger(ex); return Utility.JsonMsg(false, ex.Message); } } //保存 [DataAction("Save", "content")] public string Save(string content) { try { SaveDataModel data = JsonConvert.DeserializeObject<SaveDataModel>(content); StringBuilder strSql = new StringBuilder(); DataTable dt = new DataTable(); if (Convert.ToInt32(data.baseInfo.ryid) == 0) { strSql.Append(@"SELECT A.ryid,A.UserID,A.UserType,A.UserNumber,B.CnName AS UserName, (CASE A.UserType WHEN 1 THEN '调查人员' WHEN 2 THEN '询问人员' ELSE '执法人员' END) AS UserTypeText FROM FX_RYLXInfo A LEFT JOIN FX_UserInfo B ON A.UserID = B.UserID WHERE A.UserID = '" + data.baseInfo.UserID + "' AND A.UserType = " + data.baseInfo.UserType); dt = Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]; if (dt.Rows.Count > 0) return Utility.JsonMsg(false, dt.Rows[0]["UserName"].ToString() + " 类型:" + dt.Rows[0]["UserTypeText"].ToString() + " 已存在,不能重复新增"); } else { strSql.Append(@"SELECT A.ryid,A.UserID,A.UserType,A.UserNumber,B.CnName AS UserName, (CASE A.UserType WHEN 1 THEN '调查人员' WHEN 2 THEN '询问人员' ELSE '执法人员' END) AS UserTypeText FROM FX_RYLXInfo A LEFT JOIN FX_UserInfo B ON A.UserID = B.UserID WHERE A.UserID = '" + data.baseInfo.UserID + "' AND A.UserType = " + data.baseInfo.UserType + " AND A.ryid <> " + data.baseInfo.ryid); dt = Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]; if (dt.Rows.Count > 0) return Utility.JsonMsg(false, dt.Rows[0]["UserName"].ToString() + " 类型:" + dt.Rows[0]["UserTypeText"].ToString() + " 已存在,不能重复新增"); } SaveData(data); var retContent = GetData(""); return retContent; } catch (Exception ex) { return Utility.JsonMsg(false, "保存失败:" + ex.Message.Replace(":", " ")); } } //保存数据 public void SaveData(SaveDataModel data) { data.baseInfo.Condition.Add("ryid=" + data.baseInfo.ryid); if (Utility.Database.Update<FX_RYLXInfo>(data.baseInfo) <= 0) { Utility.Database.Insert<FX_RYLXInfo>(data.baseInfo); } } [DataAction("DeleteData", "content")] public string DeleteData(string content) { var delEnt = new FX_RYLXInfo(); delEnt.Condition.Add("ryid=" + content); if (Utility.Database.Delete(delEnt) > 0) return GetData(""); else return Utility.JsonMsg(false, "删除失败"); } } /// <summary> /// 获取数据模型 /// </summary> public class GetDataModel { public FX_RYLXInfo baseInfo; public List<FX_RYLXInfo> sourceList; public FX_RYLXInfo sourceListEdit; } /// <summary> /// 保存数据模型 /// </summary> public class SaveDataModel { public FX_RYLXInfo baseInfo; public KOGridEdit<FX_RYLXInfo> sourceList; } }
// Copyright © 2020 Void-Intelligence All Rights Reserved. using System; using Vortex.Cost.Utility; using Nomad.Core; namespace Vortex.Cost.Kernels.Legacy { /// <summary> /// "Hellinger Distance": needs to have positive values, and ideally values between 0 and 1. The same is true for the following divergences. /// </summary> public sealed class HellingerDistance : BaseCost { public override double Evaluate(Matrix actual, Matrix expected) { return Forward(actual, expected); } public override double Forward(Matrix actual, Matrix expected) { var error = 0.0; for (var i = 0; i < actual.Rows; i++) for (var j = 0; j < actual.Columns; j++) error += Math.Pow(Math.Sqrt(actual[i, j]) - Math.Sqrt(expected[i, j]), 2); error *= 1 / Math.Sqrt(2); error /= actual.Rows * actual.Columns; BatchCost += error; return error; } public override Matrix Backward(Matrix actual, Matrix expected) { var gradMatrix = new Matrix(actual.Rows, actual.Columns); for (var i = 0; i < actual.Rows; i++) for (var j = 0; j < actual.Columns; j++) gradMatrix[i, j] = (Math.Sqrt(actual[i, j]) - Math.Sqrt(expected[i, j])) / (Math.Sqrt(2) * Math.Sqrt(actual[i, j])); return gradMatrix; } public override ECostType Type() { return ECostType.LegacyHellingerDistance; } } }
using UnityEngine; using UnityEditor; using UnityEngine.Playables; using UnityEngine.Timeline; [System.Serializable] public class LabelClip : PlayableAsset { public LabelBehaviour Behaviour = new LabelBehaviour(); public string Label = string.Empty; public float Min = 0.0f; public float Max = 0.5f; public override Playable CreatePlayable(PlayableGraph graph, GameObject owner) { return ScriptPlayable<LabelBehaviour>.Create(graph, Behaviour); } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Administration.Properties; using Administration.ViewModel; using DataAccess; using DataAccess.Model; using DataAccess.Repository; namespace Administration.Editors { public partial class ShowtimeEditorWindow { private readonly ShowtimeEditorWindowViewModel viewModel; public ShowtimeEditorWindow(Showtime showtime) { InitializeComponent(); var connectionString = ConnectionStringBuilder.Build( Settings.Default.server, Settings.Default.database, Settings.Default.user, Settings.Default.password); var movieRepository = new MovieRepository(connectionString); var showtimeRepository = new ShowtimeRepository(connectionString); viewModel = new ShowtimeEditorWindowViewModel(this, showtime, movieRepository, showtimeRepository); DataContext = viewModel; } public int SelectedMovieIndex { get { return MovieBox.SelectedIndex; } set { MovieBox.SelectedIndex = value; } } public DateTime Time { set { HoursBox.Text = value.Hour.ToString(); MinutesBox.Text = value.Minute.ToString(); } get { var hours = int.Parse(HoursBox.Text); var minutes = int.Parse(MinutesBox.Text); return DateBox.DisplayDate.Date.AddHours(hours).AddMinutes(minutes); } } public int SelectedAuditoriumIndex { get { return AuditoriumBox.SelectedIndex; } set { AuditoriumBox.SelectedIndex = value; } } private void SaveButton_Click(object sender, RoutedEventArgs e) { try { viewModel.Save(); DialogResult = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void CancelButton_Click(object sender, RoutedEventArgs e) { DialogResult = false; } private void HoursBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e) { var text = ((TextBox) sender).Text + e.Text; e.Handled = !ValidateNumberIsCorrectAndBetween(0, 23, text); } private void MinutesBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e) { var text = ((TextBox) sender).Text + e.Text; e.Handled = !ValidateNumberIsCorrectAndBetween(0, 59, text); } private void PriceBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e) { var text = ((TextBox)sender).Text + e.Text; e.Handled = !ValidateNumberIsCorrectAndBetween(0, 15000, text); } private static bool ValidateNumberIsCorrectAndBetween(int from, int to, string text) { int value; if (int.TryParse(text, out value)) { if (value >= from && value <= to) { return true; } } return false; } } }
/* * @lc app=leetcode id=559 lang=csharp * * [559] Maximum Depth of N-ary Tree * * https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/ * * algorithms * Easy (64.62%) * Total Accepted: 35.5K * Total Submissions: 54.9K * Testcase Example: '{"$id":"1","children":[{"$id":"2","children":[{"$id":"5","children":[],"val":5},{"$id":"6","children":[],"val":6}],"val":3},{"$id":"3","children":[],"val":2},{"$id":"4","children":[],"val":4}],"val":1}' * * Given a n-ary tree, find its maximum depth. * * The maximum depth is the number of nodes along the longest path from the * root node down to the farthest leaf node. * * For example, given a 3-ary tree: * * * * * * * We should return its max depth, which is 3. * * * * Note: * * * The depth of the tree is at most 1000. * The total number of nodes is at most 5000. * * */ /* // Definition for a Node. public class Node { public int val; public IList<Node> children; public Node(){} public Node(int _val,IList<Node> _children) { val = _val; children = _children; } */ public class Solution { public int MaxDepth(Node root) { if (root == null) return 0; if (root.children == null || root.children.Count == 0) { return 1; } var depth = 1; var childDepth = 0; foreach (var rootChild in root.children) { var d = MaxDepth(rootChild); if (childDepth < d) childDepth = d; } return depth+childDepth; } }
using Common; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Configuration; using System; namespace Data.Extensions { public static class DbContextOptionsBuilderExtensions { public static DbContextOptionsBuilder Build(this DbContextOptionsBuilder builder, IConfiguration config) { BuildInternal(builder, config); return builder; } public static DbContextOptionsBuilder<TContext> Build<TContext>(this DbContextOptionsBuilder<TContext> builder, IConfiguration config) where TContext : DbContext { BuildInternal(builder, config); return builder; } private static void BuildInternal(DbContextOptionsBuilder builder, IConfiguration config) { var connectionString = config.GetConnectionString(Constants.Data.ConnectionStringName); builder.UseSqlServer(connectionString, sqlServerOptions => { var maxRetryCount = config.GetValue<int>(Constants.SqlServerSettings.MaxRetryCount); var maxRetryDelayInSeconds = config.GetValue<int>(Constants.SqlServerSettings.MaxRetryDelayInSeconds); sqlServerOptions.EnableRetryOnFailure(maxRetryCount, TimeSpan.FromSeconds(maxRetryDelayInSeconds), null); }); builder.ConfigureWarnings(x => x.Ignore(RelationalEventId.AmbientTransactionWarning)); builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using TableroComando.GUIWrapper; using Dominio; using Repositorios; using TableroComando.Dominio; namespace TableroComando.Formularios { public partial class Form_AccionesCorrectivas : Form { BindingSource _accionesSource = new BindingSource(); BindingList<EstadoTarea> _estadoTareasBinding = new BindingList<EstadoTarea>(Enum.GetValues(typeof(EstadoTarea)).Cast<EstadoTarea>().ToList()); Indicador _indicador; // Esta columna contiene solo el código del indicador y solo se crea y muestra cuando se listan todas las acciones correctivas DataGridViewTextBoxColumn CodigoIndicadorColumn; /* Este contructor es usado para mostrar cualquier listado de acciones correctivas */ public Form_AccionesCorrectivas(IList<AccionCorrectiva> acciones) { InitializeComponent(); _accionesSource.DataSource = acciones.Select(a => new AccionDataGridViewWrapper(a)).ToList(); AccionesDataGrid.AllowUserToAddRows = false; CodigoIndicadorColumn = new DataGridViewTextBoxColumn(); CodigoIndicadorColumn.Name = "Indicador"; CodigoIndicadorColumn.HeaderText = "Indicador"; CodigoIndicadorColumn.DataPropertyName = "Indicador"; } /* Este contructor es usado para mostrar todas las acciones correctivas de un indicador en particular */ public Form_AccionesCorrectivas(Indicador indicador) { InitializeComponent(); _indicador = indicador; _accionesSource.DataSource = indicador.Acciones.Select(a => new AccionDataGridViewWrapper(a)).ToList(); } private void Form_AccionesCorrectivas_Load(object sender, EventArgs e) { AccionesDataGrid.DataSource = _accionesSource; AccionesDataGrid.Columns["FechaFin"].DefaultCellStyle.Format = "dd"; if (CodigoIndicadorColumn != null) AccionesDataGrid.Columns.Add(CodigoIndicadorColumn); AccionesDataGrid.Columns.Remove("Responsable"); // Se crea una nueva columna de Responsable de las acciones DataGridViewComboBoxColumn ColumnaResponsable = new DataGridViewComboBoxColumn(); ColumnaResponsable.DataPropertyName = "Responsable"; ColumnaResponsable.DataSource = new BindingList<Responsable>(ResponsableRepository.Instance.All()); ColumnaResponsable.Name = "Responsable"; ColumnaResponsable.HeaderText = "Responsable"; AccionesDataGrid.Columns.Add(ColumnaResponsable); AccionesDataGrid.Columns.Remove("Estado"); // Se elimina la columna autogenerada por default // Se crea una nueva columna de estado de las acciones DataGridViewComboBoxColumn ColumnaEstado = new DataGridViewComboBoxColumn(); ColumnaEstado.DataPropertyName = "Estado"; ColumnaEstado.DataSource = _estadoTareasBinding; ColumnaEstado.Name = "Estado"; ColumnaEstado.HeaderText = "Estado"; AccionesDataGrid.Columns.Add(ColumnaEstado); AccionesDataGrid.Columns["Indicador"].Visible = false; AccionesDataGrid.Columns["FechaFin"].DefaultCellStyle.Format = "dd"; AccionesDataGrid.Columns["FechaFin"].HeaderText = "Fecha límite"; AccionesDataGrid.Columns["FechaFin"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; AccionesDataGrid.Columns["Responsable"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; AccionesDataGrid.Columns["Estado"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; AccionesDataGrid.Columns["Descripcion"].HeaderText = "Descripción del desvío"; AccionesDataGrid.Columns["Objetivo"].HeaderText = "Acción de mejora a implementar"; } private void GuardarBtn_Click(object sender, EventArgs e) { IEnumerable<AccionCorrectiva> acciones = ((IList<AccionDataGridViewWrapper>)_accionesSource.DataSource) .Select(wrapper => wrapper.GetAccionCorrectiva()); if (_indicador == null) { AccionCorrectivaRepository.Instance.SaveAll(acciones); } else { foreach (AccionCorrectiva accion in acciones) { if (accion.Indicador == null) accion.Indicador = _indicador; AccionCorrectivaRepository.Instance.Save(accion); } } } // Estos eventos están para que retornen objetos cuando una opción es seleccionada. private void AccionesDataGrid_CellParsing(object sender, DataGridViewCellParsingEventArgs e) { if (AccionesDataGrid.CurrentCell.OwningColumn is DataGridViewComboBoxColumn) { DataGridViewComboBoxEditingControl editingControl = (DataGridViewComboBoxEditingControl)AccionesDataGrid.EditingControl; e.Value = editingControl.SelectedItem; e.ParsingApplied = true; } } private void AccionesDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.Value != null) { e.Value = e.Value.ToString(); } } } }
using System.Collections.Generic; using System.Linq; namespace TestDataGenerator.Core { public class NamedPatterns { public List<NamedPattern> Patterns { get; set; } public NamedPatterns() { Patterns = new List<NamedPattern>(); } public NamedPattern GetPattern(string name) { return Patterns.FirstOrDefault(n => n.Name.Equals(name)); } public bool HasPattern(string name) { return Patterns.Any(n => n.Name.Equals(name)); } } public class NamedPattern { public string Name { get; set; } public string Pattern { get; set; } } }
using System; using FacadePattern.Equipments; using FacadePattern.Facades; namespace FacadePattern { class Program { static void Main(string[] args) { var facade = new HomeTheaterFacade(new Amplifier(), new DvdPlayer(), new Projector(), new TheaterLights(), new Screen(), new PopcornPopper()); facade.WatchMovie("Ready Player One"); facade.EndMovie(); Console.ReadKey(); } } }
// ReSharper disable All using System; namespace iSukces.Code.Tests.EqualityGenerator { partial struct TestStructWithSpecialHashCodeField : iSukces.Code.AutoCode.IAutoEquatable<TestStructWithSpecialHashCodeField> { public override bool Equals(object other) { if (other is null) return false; if (other.GetType() != typeof(TestStructWithSpecialHashCodeField)) return false; return Equals((TestStructWithSpecialHashCodeField)other); } public bool Equals(TestStructWithSpecialHashCodeField other) { if (IsEmpty) return other.IsEmpty; if (other.IsEmpty) return false; return StringComparer.OrdinalIgnoreCase.Equals(Name, other.Name); } public override int GetHashCode() { return IsEmpty ? 0 : HashCode; } public static bool operator !=(TestStructWithSpecialHashCodeField left, TestStructWithSpecialHashCodeField right) { return !Equals(left, right); } public static bool operator ==(TestStructWithSpecialHashCodeField left, TestStructWithSpecialHashCodeField right) { return Equals(left, right); } } }
using System; using Pe.Stracon.SGC.Infraestructura.CommandModel.Base; namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual { /// <summary> /// Clase que representa la entidad Contrato Parrafo Variable /// </summary> /// <remarks> /// Creación : GMD 20150511 <br /> /// Modificación : <br /> /// </remarks> public class ContratoParrafoVariableEntity : Entity { /// <summary> /// Codigo Contrato de Parrafo Variable /// </summary> public Guid CodigoContratoParrafoVariable { get; set; } /// <summary> /// Codigo Contrato de Parrafo /// </summary> public Guid CodigoContratoParrafo { get; set; } /// <summary> /// Codigo de Variable /// </summary> public Guid CodigoVariable { get; set; } /// <summary> /// Valor de Texto /// </summary> public string ValorTexto { get; set; } /// <summary> /// Valor de Numero /// </summary> public decimal? ValorNumero { get; set; } /// <summary> /// Valor de Fecha /// </summary> public DateTime? ValorFecha { get; set; } /// <summary> /// ValorImagen /// </summary> public byte[] ValorImagen { get; set; } /// <summary> /// Valor de Tabla /// </summary> public string ValorTabla { get; set; } /// <summary> /// Valor de Tabla Editable /// </summary> public string ValorTablaEditable { get; set; } /// <summary> /// Valor de Bien /// </summary> public string ValorBien { get; set; } /// <summary> /// Valor de Bien Editable /// </summary> public string ValorBienEditable { get; set; } /// <summary> /// Valor de Firmante /// </summary> public string ValorFirmante { get; set; } /// <summary> /// Valor de Firmante Editable /// </summary> public string ValorFirmanteEditable { get; set; } /// <summary> /// Codigo de valor de la variable tipo lista /// </summary> public Guid? ValorLista { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mongooz.Scheduler { class SchedulingService { } }
using UnityEngine; using System.Collections; public class BeiGongJiInfoCtrl : MonoBehaviour { AudioSource AudioBeiGongJi; UISprite BeiGongJiSprite; public static BeiGongJiInfoCtrl _Instance; public static BeiGongJiInfoCtrl GetInstance() { return _Instance; } // Use this for initialization void Start() { _Instance = this; BeiGongJiSprite = GetComponent<UISprite>(); BeiGongJiSprite.enabled = false; AudioBeiGongJi = audio; gameObject.SetActive(false); } public void ShowGongJiInfo() { if (gameObject.activeSelf) { return; } BeiGongJiSprite.enabled = true; gameObject.SetActive(true); if (AudioBeiGongJi != null) { AudioBeiGongJi.Play(); } } public void HiddenGongJiInfo() { if (!gameObject.activeSelf) { return; } BeiGongJiSprite.enabled = false; gameObject.SetActive(false); if (AudioBeiGongJi != null) { AudioBeiGongJi.Stop(); } } }
using Alabo.Datas.Ef.Map; namespace Alabo.Datas.Ef.SqlServer { /// <summary> /// 实体映射配置 /// </summary> /// <typeparam name="TEntity">实体类型</typeparam> public abstract class MsSqlEntityMap<TEntity> : MapBase<TEntity>, IMsSqlMap where TEntity : class { } }
using System.Collections.Generic; using System.Linq; using Data; using Data.Infrastructure; using Model.Models; using Model.ViewModels; using Core.Common; using System; using Model; using System.Threading.Tasks; using Data.Models; using Model.ViewModel; namespace Service { public interface IRolesMenuService : IDisposable { RolesMenu Create(RolesMenu pt); void Delete(int id); void Delete(RolesMenu pt); RolesMenu Find(int ptId); void Update(RolesMenu pt); RolesMenu Add(RolesMenu pt); IEnumerable<RolesMenu> GetRolesMenuList(); RolesMenu Find(int MenuId, string RoleId); IEnumerable<RolesMenuViewModel> GetRolesMenuList(string RoleId); int GetPermittedActionsCountForMenuId(int MenuId, string RoleId); } public class RolesMenuService : IRolesMenuService { ApplicationDbContext db = new ApplicationDbContext(); private readonly IUnitOfWorkForService _unitOfWork; private readonly Repository<RolesMenu> _RolesMenuRepository; RepositoryQuery<RolesMenu> RolesMenuRepository; public RolesMenuService(IUnitOfWorkForService unitOfWork) { _unitOfWork = unitOfWork; _RolesMenuRepository = new Repository<RolesMenu>(db); RolesMenuRepository = new RepositoryQuery<RolesMenu>(_RolesMenuRepository); } public RolesMenu Find(int pt) { return _unitOfWork.Repository<RolesMenu>().Find(pt); } public RolesMenu Create(RolesMenu pt) { pt.ObjectState = ObjectState.Added; _unitOfWork.Repository<RolesMenu>().Insert(pt); return pt; } public void Delete(int id) { _unitOfWork.Repository<RolesMenu>().Delete(id); } public void Delete(RolesMenu pt) { _unitOfWork.Repository<RolesMenu>().Delete(pt); } public void Update(RolesMenu pt) { pt.ObjectState = ObjectState.Modified; _unitOfWork.Repository<RolesMenu>().Update(pt); } public IEnumerable<RolesMenu> GetRolesMenuList() { var pt = _unitOfWork.Repository<RolesMenu>().Query().Get(); return pt; } public RolesMenu Add(RolesMenu pt) { _unitOfWork.Repository<RolesMenu>().Insert(pt); return pt; } public RolesMenu Find(int MenuId, string RoleId) { return _unitOfWork.Repository<RolesMenu>().Query().Get().Where(m=>m.RoleId==RoleId && m.MenuId==MenuId).FirstOrDefault(); } public IEnumerable<RolesMenuViewModel> GetRolesMenuList(string RoleId) { return (from p in db.RolesMenu where p.RoleId == RoleId select new RolesMenuViewModel { MenuId = p.MenuId, RoleId = p.RoleId, RolesMenuId = p.RolesMenuId, MenuName = p.Menu.MenuName, RoleName = p.Role.Name, FullHeaderPermission=p.FullHeaderPermission, FullLinePermission=p.FullLinePermission }); } public RolesMenu GetRoleMenuForRoleId(string RoleId,int MenuId) { return (from p in db.RolesMenu where p.RoleId == RoleId && p.MenuId == MenuId select p).FirstOrDefault(); } public int GetPermittedActionsCountForMenuId(int MenuId, string RoleId) { int ControllerId = (from p in db.Menu join t in db.ControllerAction on p.ControllerActionId equals t.ControllerActionId join t2 in db.MvcController on t.ControllerId equals t2.ControllerId where p.MenuId == MenuId select t2.ControllerId ).FirstOrDefault(); int list = (from p in db.ControllerAction join t in db.RolesControllerAction.Where(m => m.RoleId == RoleId) on p.ControllerActionId equals t.ControllerActionId where p.ControllerId == ControllerId select t).Count(); return list; } public int GetChildPermittedActionsCountForMenuId(int MenuId, string RoleId) { string ControllerId= string.Join(",",(from p in db.Menu join t in db.MvcController on p.ControllerAction.ControllerId equals t.ParentControllerId join t2 in db.MvcController on t.ControllerId equals t2.ControllerId where p.MenuId == MenuId select t2.ControllerId ).ToList()); int list = (from p in db.ControllerAction join t in db.RolesControllerAction.Where(m => m.RoleId == RoleId) on p.ControllerActionId equals t.ControllerActionId where ControllerId.Contains(p.ControllerId.ToString()) select t).Count(); return list; } public void Dispose() { } } }
using System; using System.Globalization; using System.Threading.Tasks; using DurianCode.PlacesSearchBar; using Plugin.LocalNotifications; using Plugin.Notifications; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace ParPorApp.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddEventPage : ContentPage { private static readonly string ApiKey = Device.OS == TargetPlatform.iOS ? "AIzaSyA3nX3DIcGkRyA4-LnNC_BYH9DedK3GYTs" : TargetPlatform.Android != TargetPlatform.Other ? "AIzaSyA3nX3DIcGkRyA4-LnNC_BYH9DedK3GYTs" : TargetPlatform.WinPhone != TargetPlatform.Other ? "AIzaSyA3nX3DIcGkRyA4-LnNC_BYH9DedK3GYTs" : "...etc..."; public AddEventPage() { InitializeComponent(); search_bar.ApiKey = ApiKey; search_bar.Type = PlaceType.Address; //search_bar.Components = new Components("country:us"); // Restrict results to USA search_bar.PlacesRetrieved += Search_Bar_PlacesRetrieved; search_bar.TextChanged += Search_Bar_TextChanged; search_bar.MinimumSearchText = 2; results_list.ItemSelected += Results_List_ItemSelected; } private void DatePicker_DateSelected(object sender, DateChangedEventArgs e) { var eventDate = (e.NewDate.Date).ToShortDateString(); var pickertime = EventTime.Time; var dt = Convert.ToDateTime(pickertime.ToString()); var time = dt.ToShortTimeString(); SelectedDate.Text = eventDate + " " + time; } private async void ReturnEventPage_Clicked(object sender, EventArgs e) { await Navigation.PopAsync(); } private void Search_Bar_PlacesRetrieved(object sender, AutoCompleteResult result) { results_list.ItemsSource = result.AutoCompletePlaces; spinner.IsRunning = false; spinner.IsVisible = false; if (result.AutoCompletePlaces != null && result.AutoCompletePlaces.Count > 0) results_list.IsVisible = true; } private void Search_Bar_TextChanged(object sender, TextChangedEventArgs e) { if (!string.IsNullOrEmpty(e.NewTextValue)) { results_list.IsVisible = false; spinner.IsVisible = true; spinner.IsRunning = true; } else { results_list.IsVisible = true; spinner.IsRunning = false; spinner.IsVisible = false; } } private async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e) { if (e.SelectedItem == null) return; var prediction = (AutoCompletePrediction) e.SelectedItem; results_list.SelectedItem = null; var place = await Places.GetPlace(prediction.Place_ID, ApiKey); if (place != null) { selectedLocation.Text = prediction.Description; locPlaceId.Text = prediction.Place_ID; locLatitude.Text = place.Latitude.ToString(CultureInfo.InvariantCulture); locLongitude.Text = place.Longitude.ToString(CultureInfo.InvariantCulture); Task.WaitAll(); } results_list.IsVisible = false; } } }
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; namespace Multibase { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Clientes clienteObj = new Clientes(); Cuentas cuentaObj = new Cuentas(); Habitacion habitacionObj = new Habitacion(); Reservacion reservacionObj = new Reservacion(); Usuarios usuarioObj = new Usuarios(); stackClient.Children.Add(clienteObj); stackCuentas.Children.Add(cuentaObj); stackHab.Children.Add(habitacionObj); stackRes.Children.Add(reservacionObj); stackUser.Children.Add(usuarioObj); } private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { } } }
using System; namespace SFA.DAS.ProviderCommitments.Interfaces { public interface ICacheModel { Guid CacheKey { get; } } }
using System; using System.Collections.Generic; namespace TrainEngine { public class TrackDescription { public int NumberOfTrackParts { get; set; } } }
using Cottle.Functions; using EddiSpeechResponder.Service; using JetBrains.Annotations; using System; using System.Linq; namespace EddiSpeechResponder.CustomFunctions { [UsedImplicitly] public class StartsWithVowel : ICustomFunction { public string name => "StartsWithVowel"; public FunctionCategory Category => FunctionCategory.Utility; public string description => Properties.CustomFunctions_Untranslated.StartsWithVowel; public Type ReturnType => typeof( string ); public NativeFunction function => new NativeFunction((values) => { string Entree = values[0].AsString; if (Entree == "") { return ""; } char[] vowels = { 'a', 'à', 'â', 'ä', 'e', 'ê', 'é', 'è', 'ë', 'i', 'î', 'ï', 'o', 'ô', 'ö', 'u', 'ù', 'û', 'ü', 'œ' }; char firstCharacter = Entree.ToLower().ToCharArray().ElementAt(0); bool result = vowels.Contains(firstCharacter); return result; }, 1); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Data.Models; using Services.Controllers; using Services.Representers; using Services.Test.DataAccess; using Services.Test.Factories; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http.Results; namespace Services.Test.Controllers { /// <summary> /// This is the Unit test class for the Users Controller. /// /// It implements all tests using Microsoft Fakes /// Tests have been duplicated to showcase the use of Stubs with dependancy injection and /// Shims to prevent any connections to the DB /// </summary> //[TestClass] public class UsersControllerTest { #region Properties private readonly FakeUnitOfWork _fakeUnitOfWork; #endregion public UsersControllerTest() { _fakeUnitOfWork = new FakeUnitOfWork(); } // Note: this block no longer works, as i currently have VS2015 Prof, which does not support Fakes // But it still exists as a demonstration //#region Get Users using Microsoft Fakes //[TestMethod] //public void GetUsers_ShouldReturn_EmptyList() //{ // var stubedUnitOfWork = new Data.Interfaces.Fakes.StubIUnitOfWork // { // UserRepositoryGet = () => new Data.Interfaces.Fakes.StubIRepository<User> // { // All = () => null // } // }; // var controller = new UsersController(stubedUnitOfWork); // var result = controller.GetUsers(); // Assert.IsNotNull(result); // Assert.AreEqual(0, result.Count()); //} //[TestMethod] //public void GetUsers_ShouldReturn_SingleElementRoleList() //{ // var userRepresentors = new UserFactory().BuildList(); // var testUsers = AutoMapper.Mapper.Map(userRepresentors, new List<User>()); // var stubedUnitOfWork = new Data.Interfaces.Fakes.StubIUnitOfWork // { // UserRepositoryGet = () => new Data.Interfaces.Fakes.StubIRepository<User> // { // All = () => testUsers.AsQueryable() // } // }; // var controller = new UsersController(stubedUnitOfWork); // var result = controller.GetUsers().ToList(); // Assert.IsNotNull(result); // Assert.AreEqual(1, result.Count); // PerformCommonAsserts(userRepresentors.First(), result.First()); //} //[TestMethod] //public void GetUsers_ShouldReturn_ExtendedRoleList() //{ // var userRepresentors = new UserFactory(0).WithExtendedList(1).BuildList(); // var testUsers = AutoMapper.Mapper.Map(userRepresentors, new List<User>()); // var stubedUnitOfWork = new Data.Interfaces.Fakes.StubIUnitOfWork // { // UserRepositoryGet = () => new Data.Interfaces.Fakes.StubIRepository<User> // { // All = () => testUsers.AsQueryable() // } // }; // var controller = new UsersController(stubedUnitOfWork); // var result = controller.GetUsers().ToList(); // Assert.IsNotNull(result); // Assert.AreEqual(2, result.Count); // foreach (var userRepresentor in userRepresentors) // { // var role = result.First(roleType => roleType.Id == userRepresentor.Id); // PerformCommonAsserts(userRepresentor, role); // } //} //[TestMethod] //public async Task GetUser_ShouldReturn_NotFoundResult() //{ // var taskCompletionSource = new TaskCompletionSource<User>(); // taskCompletionSource.SetResult(null); // var stubedUnitOfWork = new Data.Interfaces.Fakes.StubIUnitOfWork // { // UserRepositoryGet = () => new Data.Interfaces.Fakes.StubIRepository<User> // { // FindAsyncInt32 = id => taskCompletionSource.Task // } // }; // var controller = new UsersController(stubedUnitOfWork); // var result = await controller.GetUser(9); // Assert.IsNotNull(result); // Assert.IsInstanceOfType(result, typeof(NotFoundResult)); //} //[TestMethod] //public async Task GetUser_ShouldReturn_SingleRole() //{ // var userRepresentor = new UserFactory().Build(); // var user = AutoMapper.Mapper.Map(userRepresentor, new User()); // var taskCompletionSource = new TaskCompletionSource<User>(); // taskCompletionSource.SetResult(user); // var stubedUnitOfWork = new Data.Interfaces.Fakes.StubIUnitOfWork // { // UserRepositoryGet = () => new Data.Interfaces.Fakes.StubIRepository<User> // { // FindAsyncInt32 = id => taskCompletionSource.Task // } // }; // var controller = new UsersController(stubedUnitOfWork); // var result = await controller.GetUser(9) as OkNegotiatedContentResult<UserRepresentor>; // Assert.IsNotNull(result); // PerformCommonAsserts(userRepresentor, result.Content); //} //#endregion //#region Get Users //[TestMethod] //public void GetUsers_ShouldReturn_EmptyList() //{ // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).ModelList = null; // var controller = new UsersController(_fakeUnitOfWork); // var result = controller.GetUsers(); // Assert.IsNotNull(result); // Assert.AreEqual(0, result.Count()); //} //[TestMethod] //public void GetUsers_ShouldReturn_SingleElementUserList() //{ // var userRepresentors = new UserFactory().BuildList(); // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).ModelList = global::AutoMapper.Mapper.Map(userRepresentors, new List<User>()); // var controller = new UsersController(_fakeUnitOfWork); // var result = controller.GetUsers().ToList(); // Assert.IsNotNull(result); // Assert.AreEqual(1, result.Count); // PerformCommonAsserts(userRepresentors.First(), result.First()); //} //[TestMethod] //public void GetUsers_ShouldReturn_ExtendedUserList() //{ // var userRepresentors = new UserFactory(0).WithExtendedList(1).BuildList(); // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).ModelList = global::AutoMapper.Mapper.Map(userRepresentors, new List<User>()); // var controller = new UsersController(_fakeUnitOfWork); // var result = controller.GetUsers().ToList(); // Assert.IsNotNull(result); // Assert.AreEqual(2, result.Count); // foreach (var userRepresentor in userRepresentors) // { // var role = result.First(roleType => roleType.Id == userRepresentor.Id); // PerformCommonAsserts(userRepresentor, role); // } //} //[TestMethod] //public async Task GetUser_ShouldReturn_NotFoundResult() //{ // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).ModelList = global::AutoMapper.Mapper.Map(new UserFactory().BuildList(), new List<User>()); // var controller = new UsersController(_fakeUnitOfWork); // var result = await controller.GetUser(9); // Assert.IsNotNull(result); // Assert.IsInstanceOfType(result, typeof(NotFoundResult)); //} //[TestMethod] //public async Task GetUser_ShouldReturn_SingleUser() //{ // var userRepresentors = new UserFactory().BuildList(); // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).ModelList = global::AutoMapper.Mapper.Map(userRepresentors, new List<User>()); // var controller = new UsersController(_fakeUnitOfWork); // var result = await controller.GetUser(0) as OkNegotiatedContentResult<UserRepresenter>; // Assert.IsNotNull(result); // PerformCommonAsserts(userRepresentors.First(), result.Content); //} //#endregion //#region Put User //[TestMethod] //public async Task PutUser_ShouldReturn_BadRequestResult() //{ // var testUser = new UserFactory().Build(); // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).Model = global::AutoMapper.Mapper.Map(testUser, new User()); // var controller = new UsersController(_fakeUnitOfWork); // var result = await controller.PutUser(9, testUser) as BadRequestErrorMessageResult; // Assert.IsNotNull(result); // Assert.IsInstanceOfType(result, typeof(BadRequestErrorMessageResult)); // Assert.AreEqual(result.Message, "The User Id passed in the URL and Body, do not match."); //} //[TestMethod] //public async Task PutUser_ShouldReturn_InvalidModel() //{ // var key = "key"; // var errorMessage = "model is invalid"; // var testUser = new UserFactory().Build(); // var controller = new UsersController(_fakeUnitOfWork); // controller.ModelState.AddModelError(key, errorMessage); //Causes ModelState.IsValid to return false // var result = await controller.PutUser(testUser.Id, testUser) as InvalidModelStateResult; // Assert.IsNotNull(result); // Assert.IsTrue(result.ModelState.ContainsKey(key)); // Assert.AreEqual(1, result.ModelState[key].Errors.Count()); // Assert.AreEqual(errorMessage, result.ModelState[key].Errors.First().ErrorMessage); //} //[TestMethod] //public async Task PutUser_ShouldReturn_NoContent() //{ // var testUser = new UserFactory().Build(); // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).Model = global::AutoMapper.Mapper.Map(testUser, new User()); // var controller = new UsersController(_fakeUnitOfWork); // var result = await controller.PutUser(testUser.Id, testUser) as StatusCodeResult; // Assert.IsNotNull(result); // Assert.AreEqual(result.StatusCode, HttpStatusCode.NoContent); //} //#endregion //#region Post User //[TestMethod] //public async Task PostUser_ShouldReturn_InvalidModel() //{ // const string key = "key"; // const string errorMessage = "model is invalid"; // var testUser = new UserFactory().Build(); // var controller = new UsersController(_fakeUnitOfWork); // controller.ModelState.AddModelError(key, errorMessage); //Causes ModelState.IsValid to return false // var result = await controller.PostUser(testUser) as InvalidModelStateResult; // Assert.IsNotNull(result); // Assert.IsTrue(result.ModelState.ContainsKey(key)); // Assert.AreEqual(1, result.ModelState[key].Errors.Count()); // Assert.AreEqual(errorMessage, result.ModelState[key].Errors.First().ErrorMessage); //} //[TestMethod] //public async Task PostUser_ShouldReturn_CreatedAtRouteNegotiatedContentResult() //{ // var testUser = new UserFactory().Build(); // var controller = new UsersController(_fakeUnitOfWork); // var result = await controller.PostUser(testUser) as CreatedAtRouteNegotiatedContentResult<UserRepresenter>; // Assert.IsNotNull(result); // Assert.IsTrue(result.RouteValues.ContainsKey("Id")); // Assert.AreEqual(testUser.Id, result.RouteValues["Id"]); // Assert.IsTrue(((FakeRepository<User>)_fakeUnitOfWork.UserRepository).IsCreated); // Assert.IsTrue(((FakeRepository<User>)_fakeUnitOfWork.UserRepository).IsSaved); //} //#endregion //#region Delete User //[TestMethod] //public async Task DeleteUser_ShouldReturn_NotFoundResult() //{ // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).ModelList = null; // var controller = new UsersController(_fakeUnitOfWork); // var result = await controller.DeleteUser(9); // Assert.IsNotNull(result); // Assert.IsInstanceOfType(result, typeof(NotFoundResult)); //} //[TestMethod] //public async Task DeleteUser_ShouldReturn_OkNegotiatedContentResult() //{ // var testUsers = new UserFactory().BuildList(); // //'FakeUnitOfWork.UserRepository' must be cast to 'FakeRepository<User>', as 'FakeRepository' exposes some properties that 'IRepository' does not // ((FakeRepository<User>)_fakeUnitOfWork.UserRepository).ModelList = global::AutoMapper.Mapper.Map(testUsers, new List<User>()); // var controller = new UsersController(_fakeUnitOfWork); // var result = await controller.DeleteUser(testUsers.First().Id); // Assert.IsNotNull(result); // Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<UserRepresenter>)); // Assert.IsTrue(((FakeRepository<User>)_fakeUnitOfWork.UserRepository).IsDeleted); // Assert.IsTrue(((FakeRepository<User>)_fakeUnitOfWork.UserRepository).IsSaved); //} //#endregion //#region Common Asserts //private static void PerformCommonAsserts(UserRepresenter expected, UserRepresenter actual) //{ // Assert.AreEqual(expected.Email, actual.Email); // Assert.AreEqual(expected.Id, actual.Id); // Assert.AreEqual(expected.Name, actual.Name); // Assert.AreEqual(expected.Password, actual.Password); // Assert.AreEqual(expected.Username, actual.Username); // Assert.AreEqual(expected.RoleRepresentors.Count, actual.RoleRepresentors.Count); // Assert.AreEqual(expected.RoleRepresentors.First().Id, actual.RoleRepresentors.First().Id); // Assert.AreEqual(expected.RoleRepresentors.First().Title, actual.RoleRepresentors.First().Title); //} //#endregion //[TestMethod] //public void GetRole_fakes_ShouldReturn_SingleRole() //{ // var roleRepresentor = new RoleFactory().Build(); // var testRole = AutoMapper.Mapper.Map(roleRepresentor, new Role()); // var stubedUnitOfWork = new Data.Interfaces.Fakes.StubIUnitOfWork // { // RoleRepositoryGet = () => new Data.Interfaces.Fakes.StubIRepository<Role> // { // FindInt32 = id => testRole // } // }; // var controller = new RolesController(stubedUnitOfWork); // var result = controller.GetRole(roleRepresentor.Id) as OkNegotiatedContentResult<RoleRepresentor>; ; // Assert.IsNotNull(result); // PerformCommonAsserts(roleRepresentor, result.Content); //} //#endregion } }