text
stringlengths
13
6.01M
namespace CustomerApp.UnitTests { using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using Controllers.APIv1; using FluentAssertions; using NUnit.Framework; [TestFixture] public class VerifyMefCompositionTests { [Test] public void VerifyContracts() { var container = MefContainer.ConfigureContainer(true); AssertCanCompose<CustomersController>(container); AssertCanCompose<NotesController>(container); } private static void AssertCanCompose<TType>(ExportProvider container, int howMany = 1) { Action sut = () => { var exports = container.GetExportedValues<TType>().ToList(); if (exports.Count() == howMany) return; var exportNames = string.Join(",", exports.Select(e => e.GetType().Name)); throw new CompositionException($"Expected {howMany} exports, but found {exports.Count}: {exportNames}"); }; sut.Should().NotThrow(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Toggle))] public class BackpackUICaptainToggle : MonoBehaviour { [Tooltip("Toggle开启时")]public Sprite on; [Tooltip("Toggle关闭时")] public Sprite off; AudioSourceController audioSourceController; private void Start() { transform.GetComponent<Toggle>().targetGraphic.GetComponent<Image>().sprite = off; transform.GetComponent<Toggle>().targetGraphic.GetComponent<Image>().color = new Color(0.5f, 0.5f, 0.5f, 1); } public void BackpackToggle() { if (transform.GetComponent<Toggle>().isOn) { transform.GetComponent<Toggle>().targetGraphic.GetComponent<Image>().sprite = on; transform.GetComponent<Toggle>().targetGraphic.GetComponent<Image>().color = new Color(1, 1, 1, 1); } else { transform.GetComponent<Toggle>().targetGraphic.GetComponent<Image>().sprite = off; transform.GetComponent<Toggle>().targetGraphic.GetComponent<Image>().color = new Color(0.5f, 0.5f, 0.5f, 1); } if(audioSourceController==null) audioSourceController = AudioSourcesManager.ApplyAudioSourceController(); audioSourceController.Play("按钮",transform); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data; using System.Data.SqlClient; using WindowsFormsApplication2; using System.IO; /// <summary> /// qyxxkDaochu 的摘要说明 /// </summary> public class QyxxkDaochu : System.Web.UI.Page { SqlServerDataBase sdb = new SqlServerDataBase(); public QyxxkDaochu() { } private DataView dataView(String sql) { DataSet ds = new DataSet(); ds = sdb.Select(sql, null); return ds.Tables[0].DefaultView; } public void SaveToWord(string id, string Saveasfilename) { string strfilename = Server.MapPath("~/Word文档/入园企业信息表(空).docx"); //string sql = "select qyID,tbsj,qymc,qylx,sshy,sfdxs,zczj,zcsj,zcdz,nzfmj,frdb,fryddh,frqq,lxr,lxryddh,lxrqq,czbl,zycp,qyjyfw,csyj,zjyj,zjyj2,zjyj3,kjyyj,ryzt,bz,rzyq,gszcd,qynb,tzxx,cstg,zjtg,zjtg2,zjtg3,kjytg,qytp from nryqyxxk where qyID='" + id + "'"; string sql = "select * from nryqyxxk where qyID='" + id + "'"; DataView dv = dataView(sql); foreach (DataRowView drv in dv) { string qyID = drv["qyID"].ToString(); string tbsj = drv["tbsj"].ToString(); string qymc = drv["qymc"].ToString(); string qylx = drv["qylx"].ToString(); string sshy = drv["sshy"].ToString(); string sfdxs = drv["sfdxs"].ToString(); string zczj = drv["zczj"].ToString(); string zcsj = drv["zcsj"].ToString(); string zcdz = drv["zcdz"].ToString(); string nzfmj = drv["nzfmj"].ToString(); string frdb = drv["frdb"].ToString(); string fryddh = drv["fryddh"].ToString(); string frqq = drv["frqq"].ToString(); string lxr = drv["lxr"].ToString(); string lxryddh = drv["lxryddh"].ToString(); string lxrqq = drv["lxrqq"].ToString(); string czbl = drv["czbl"].ToString(); string zycp = drv["zycp"].ToString(); string qyjyfw = drv["qyjyfw"].ToString(); string csyj = drv["csyj"].ToString(); string zjyj = drv["zjyj"].ToString(); string zjyj2 = drv["zjyj2"].ToString(); string zjyj3 = drv["zjyj3"].ToString(); string kjyyj = drv["kjyyj"].ToString(); string ryzt = drv["ryzt"].ToString(); string bz = drv["bz"].ToString(); string rzyq = drv["rzyq"].ToString(); string gszcd = drv["gszcd"].ToString(); string qynb = drv["qynb"].ToString(); string tzxx = drv["tzxx"].ToString(); string cstg = drv["cstg"].ToString(); string zjtg = drv["zjtg"].ToString(); string zjtg2 = drv["zjtg2"].ToString(); string zjtg3 = drv["zjtg3"].ToString(); string kjytg = drv["kjytg"].ToString(); string qytp = drv["qytp"].ToString(); string sfbxjs = drv["sfbxjs"].ToString(); string sfybxhz = drv["sfybxhz"].ToString(); string spzjID = drv["spzjID"].ToString(); string spzjID2 = drv["spzjID2"].ToString(); string spzjID3 = drv["spzjID3"].ToString(); cstg = gettg(cstg); zjtg = gettg(zjtg); zjtg2 = gettg(zjtg2); zjtg3 = gettg(zjtg3); kjytg = gettg(kjytg); tbsj = tbsj.Replace("0:00:00", ""); zcsj = zcsj.Replace("0:00:00", ""); DataSet ds = new DataSet(); string zjxm = ""; string zjxm2 = ""; string zjxm3 = ""; if (spzjID != null && spzjID != "") { sql = "select zjxm from zjk where zjID='" + spzjID + "'"; ds = sdb.Select(sql, null); zjxm = ds.Tables[0].Rows[0][0].ToString(); } if (spzjID2 != null && spzjID2 != "") { sql = "select zjxm from zjk where zjID='" + spzjID2 + "'"; ds = sdb.Select(sql, null); zjxm2 = ds.Tables[0].Rows[0][0].ToString(); } if (spzjID3 != null && spzjID3 != "") { sql = "select zjxm from zjk where zjID='" + spzjID3 + "'"; ds = sdb.Select(sql, null); zjxm3 = ds.Tables[0].Rows[0][0].ToString(); } WordTableRead wr = new WordTableRead(strfilename); try { wr.Open(); int len = 0; int row = 1; wr.WriteWord(1, row, 2, qyID, len); wr.WriteWord(1, row, 4, tbsj, len); row++; wr.WriteWord(1, row, 3, qymc, len); wr.WriteWord(1, row, 5, qylx, len); row++; wr.WriteWord(1, row, 3, sshy, len); wr.WriteWord(1, row, 5, sfdxs, len); row++; wr.WriteWord(1, row, 3, sfbxjs, len); wr.WriteWord(1, row, 5, sfybxhz, len); row++; wr.WriteWord(1, row, 3, zczj, len); wr.WriteWord(1, row, 5, zcsj, len); row++; wr.WriteWord(1, row, 3, zcdz, len); wr.WriteWord(1, row, 5, nzfmj, len); row++; wr.WriteWord(1, row, 3, frdb, len); wr.WriteWord(1, row, 5, fryddh, len); wr.WriteWord(1, row, 7, frqq, len); row++; wr.WriteWord(1, row, 3, lxr, len); wr.WriteWord(1, row, 5, lxryddh, len); wr.WriteWord(1, row, 7, lxrqq, len); row++; wr.WriteWord(1, row, 2, czbl, len); row++; wr.WriteWord(1, row, 2, zycp, len); row++; wr.WriteWord(1, row, 2, qyjyfw, len); row++; wr.WriteWord(1, row, 2, bz, len); row++; wr.WriteWord(1, row, 2, tzxx, len); row++; wr.WriteWord(1, row, 2, rzyq, len); row++; wr.WriteWord(1, row, 2, gszcd, len); row++; wr.WriteWord(1, row, 2, qynb, len); row++; if (qytp != "") { FileUtil file = new FileUtil(); string strFile = file.getFileByFileID(qytp).realPath; wr.WriteImage(1, row, 2, strFile, len); } row++; row++; wr.WriteWord(1, row, 2, csyj, len, "justify"); wr.WriteWord(1, row, 4, cstg, len); row++; wr.WriteWord(1, row, 2, zjyj, len, "justify"); wr.WriteWord(1, row, 4, zjxm == "" ? "" : "专家" + zjxm + "审核" + zjtg, len); row++; wr.WriteWord(1, row, 2, zjyj2, len, "justify"); wr.WriteWord(1, row, 4, zjxm2 == "" ? "" : "专家" + zjxm2 + "审核" + zjtg2, len); row++; wr.WriteWord(1, row, 2, zjyj3, len, "justify"); wr.WriteWord(1, row, 4, zjxm3 == "" ? "" : "专家" + zjxm3 + "审核" + zjtg3, len); row++; wr.WriteWord(1, row, 2, kjyyj, len, "justify"); wr.WriteWord(1, row, 4, kjytg, len); row++; wr.SaveasWord(Saveasfilename); } catch { } finally { wr.Close(); } } } protected string gettg(string tg) { if (tg == "1") { return "通过"; } else if (tg == "2") { return "不通过"; } else { return ""; } } protected string chkexport(string str, string bstr) { for (int m = 0; m < str.Length; m++) { int count = 0; switch (str[m]) { case 'a': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 1) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; case 'b': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 2) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; case 'c': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 3) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; case 'd': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 4) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; case 'e': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 5) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; case 'f': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 6) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; case 'g': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 7) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; case 'h': for (int n = 0; n < bstr.Length; n++) { if (bstr[n] == '□' || bstr[n] == 'R') count++; if (count == 8) { char[] cs = bstr.ToCharArray(); cs[n] = 'R'; string res = new string(cs); bstr = res; count = 0; break; } }; break; default: break; } } return bstr; } }
using ApiTemplate.Common.Markers.DependencyRegistrar; namespace ApiTemplate.Service.RabbitMq { public class ProducerService : IProducerService,IScopedDependency { #region Fields private readonly IRabbitMqService _rabbitMqService; #endregion #region Constructors public ProducerService(IRabbitMqService rabbitMqService) { _rabbitMqService = rabbitMqService; } #endregion #region Methods public void SendMessage() { } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace FoodApp.Models { public class Recipe { public int Id { get; set; } [Required] [StringLength(50, MinimumLength = 3, ErrorMessage = "Must be between 3 and 50 characters")] public string Title { get; set; } [Required] [StringLength(500, MinimumLength = 20, ErrorMessage = "Must be between 50 and 500 characters")] public string Description { get; set; } [Required] [DataType(DataType.MultilineText)] public string Ingredients { get; set; } [Required] public string Author { get; set; } public virtual ICollection<Tag> Tags { get; set; } public string Picture { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; #if NET5_0_OR_GREATER using System.Runtime.CompilerServices; #endif namespace NStandard { public static class ArrayEx { private static ArgumentException Exception_InsufficientElements(string paramName) => new("Insufficient elements in source array.", paramName); private static ArgumentException Exception_CopyingOverflow(string paramName) => new("Copying the specified array results in overflow.", paramName); #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER #else private static class EmptyArray<T> { #pragma warning disable CA1825 // this is the implementation of Array.Empty<T>() internal static readonly T[] Value = new T[0]; #pragma warning restore CA1825 } public static T[] Empty<T>() { return EmptyArray<T>.Value; } #endif /// <summary> /// Assign values to arrays of indeterminate dimensions using one-dimensional arrays. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="destination"></param> /// <param name="source"></param> public static void Assign<T>(Array destination, IEnumerable<T> source) { var count = source.Count(); if (destination.GetSequenceLength() < count) throw Exception_CopyingOverflow(nameof(source)); var stepper = new IndicesStepper(0, destination.GetLengths()); foreach (var (value, indices) in Any.Zip(source, stepper)) { destination.SetValue(value, indices); } } /// <summary> /// Assign values to arrays of indeterminate dimensions using one-dimensional arrays. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="destination"></param> /// <param name="destinationIndex"></param> /// <param name="source"></param> /// <param name="sourceIndex"></param> /// <param name="length"></param> public static void Assign<T>(Array destination, int destinationIndex, T[] source, int sourceIndex, int length) { if ((source.Length - sourceIndex) < length) throw Exception_InsufficientElements(nameof(source)); if ((destination.GetSequenceLength() - destinationIndex) < length) throw Exception_CopyingOverflow(nameof(source)); var stepper = new IndicesStepper(destinationIndex, destination.GetLengths()); foreach (var (value, indices) in Any.Zip(source.Skip(sourceIndex).Take(length), stepper)) { destination.SetValue(value, indices); } } #if NETCOREAPP3_0_OR_GREATER /// <summary> /// Assign values to arrays of indeterminate dimensions using one-dimensional arrays. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="destination"></param> /// <param name="source"></param> /// <param name="length"></param> public static unsafe void Assign<T>(T* destination, T* source, int length) where T : unmanaged { Unsafe.CopyBlock(destination, source, (uint)(length * sizeof(T))); } /// <summary> /// Assign values to arrays of indeterminate dimensions using one-dimensional arrays. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="destination"></param> /// <param name="destinationIndex"></param> /// <param name="source"></param> /// <param name="sourceIndex"></param> /// <param name="length"></param> public static unsafe void Assign<T>(T* destination, int destinationIndex, T* source, int sourceIndex, int length) where T : unmanaged { Unsafe.CopyBlock(destination + destinationIndex, source + sourceIndex, (uint)(length * sizeof(T))); } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BELCORP.GestorDocumental.DDP.TJ_ActualizarListaMaestra { public static class ProgressUpdater { public static TJ_ActualizarListaMaestra Job { get; set; } public static void Update(int percentage) { if (Job == null) { // throw or return return; } if (percentage >= 0 && percentage <= 100) Job.UpdateProgress(percentage); } } }
using System; namespace DataRetriever { public class ConfigurationFilesRoutes { public static string GetQueueConfigRoute() { return String.Format(@"{0}ConfigurationFiles\QueueConfig.txt", AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.LastIndexOf("bin"))); } public static string GetConsumerConfigRoute() { return String.Format(@"{0}ConfigurationFiles\ConsumerConfig.txt", AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.LastIndexOf("bin"))); } public static string GetPublisherConfigRoute() { return String.Format(@"{0}ConfigurationFiles\PublisherConfig.txt", AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.LastIndexOf("bin"))); } } }
namespace ForumSystem.Web.ViewModels.Posts { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using ForumSystem.Data.Models; using ForumSystem.Services.Mapping; using Ganss.XSS; public class PostEditModel : IMapFrom<Post> { public int Id { get; set; } [Required] [MaxLength(300)] public string Title { get; set; } public string UrlTitle => this.Title.Replace(" ", "_"); public string Content { get; set; } [Required] [Display(Name = "Content")] [MinLength(50, ErrorMessage = "Content is way to short. Tell me more.")] public string SanitizeContent => new HtmlSanitizer().Sanitize(this.Content); [Display(Name = "Category")] public int CategoryId { get; set; } public string CategoryName { get; set; } public string CategoryImageUrl { get; set; } public int CommentsCount { get; set; } public bool IsFromAdminPanel { get; set; } public IEnumerable<CategoryDropDownViewModel> Categories { get; set; } public int FromPage { get; set; } } }
using UnityEngine; using System.Collections; public class pp_indicator : MonoBehaviour { public pointpulser myGun; public Rect myRect; public NetworkShipGUI nsg; void OnGUI () { if (myGun.ready) {if (nsg.nsc.capacity>=myGun.energy) GUI.DrawTexture(myRect,nsg.ind_green); else GUI.DrawTexture(myRect,nsg.ind_red);} else {GUI.DrawTexture(myRect,nsg.ind_yellow,ScaleMode.StretchToFill);} GUI.DrawTexture(myRect,nsg.module_icons[3],ScaleMode.StretchToFill); }}
using System; using System.Collections.Generic; namespace OrangeApple.WPF.ViewModels { class ComparisonStrategyFactory : IComparisonStrategyFactory { public IComparisonStrategy Create(string id, List<ComparisonItemViewModel> items) { switch (id) { case ThoroughCompareStrategy.Name: return new ThoroughCompareStrategy(items); case FastCompareStrategy.Name: return new FastCompareStrategy(items); default: throw new ArgumentException("Not a valid comparison strategy", nameof(id)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using log4net.Appender; using log4net.Layout; using log4net.Core; using log4net.Config; namespace AutomationFramework.logger { /// <summary> /// Log4Net appender implementation. /// </summary> public class Log4NetHelper { private static ILog _logger; private static ConsoleAppender _consoleAppender; private static FileAppender _fileAppender; private static string layout = "%date{dd.MM.yyyy}[%class][%method][%level]-%message-%newline"; public static string Layout { set { layout = value;} } private static PatternLayout GetPatternLayout() { var patternLayout = new PatternLayout() { ConversionPattern = layout }; patternLayout.ActivateOptions(); return patternLayout; } private static ConsoleAppender GetConsoleAppender() { var consoleAppnder = new ConsoleAppender() { Name = "ConsoleAppender", Layout = GetPatternLayout(), Threshold = Level.All }; consoleAppnder.ActivateOptions(); return consoleAppnder; } private static FileAppender GetFileAppender() { var fileAppender = new FileAppender() { Name = "fileAppender", Layout=GetPatternLayout(), Threshold=Level.All, AppendToFile=true, File="FileLogger.log", }; fileAppender.ActivateOptions(); return fileAppender; } public static ILog GetLogger(Type type) { if (_consoleAppender == null) _consoleAppender = GetConsoleAppender(); if (_fileAppender == null) _fileAppender = GetFileAppender(); if (_logger != null) return _logger; BasicConfigurator.Configure(_consoleAppender); BasicConfigurator.Configure(_fileAppender); _logger = LogManager.GetLogger(type); return _logger; } //ILog Logger = Log4NetHelper.GetLogger(typeof(Log4NetHelper)); //Logger.Debug("This is Debug Information"); //Logger.Info("This is Info Information"); //Logger.Warn("This is Warn Information"); //Logger.Error("This is Error Information"); //Logger.Fatal("This is Fatal Information"); } }
using System; using System.Text; namespace PaswordGenerator { class Program { private const int PASSWORD_LENGTH = 10; private static string answerUser; private static string generatedPassword = ""; private delegate char MyDelegate(); private static MyDelegate[] generateSembolFunction; static void Main() { generateSembolFunction = new MyDelegate[] { GeneratingLowerСharacters, GeneratingUpperCharacters, GenerationSpecialСharacters, GenerationNumberСharacters }; try { Console.Write("Password generation with repeats? (Y/N):"); answerUser = Console.ReadLine(); bool isRepiting = IsRepitSymbol(answerUser); Console.Write("Use a sign in the password? (Y/N):"); answerUser = Console.ReadLine(); bool isSing = IsSingPassword(answerUser); Random random = new Random(); GeneratRandomSymbols(isRepiting, isSing, random); generatedPassword = AddHyphen(); Console.WriteLine("Generated password: " + generatedPassword); } catch(Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Press key to close"); Console.ReadKey(); } private static void GeneratRandomSymbols(bool repitingSybol, bool singPassword, Random random) { int typeSymbol = -1; while (generatedPassword.Length != PASSWORD_LENGTH) { if (singPassword) { typeSymbol++; } else { typeSymbol = random.Next(0, 4); } if (repitingSybol) { generatedPassword += generateSembolFunction[typeSymbol](); if (typeSymbol == 3) { typeSymbol = -1; } } else { CheckRepitSymbols(typeSymbol); if (typeSymbol == 3) { typeSymbol = -1; } } } } private static void CheckRepitSymbols(int typeSymbol) { char receivedChar = generateSembolFunction[typeSymbol](); for (int i = 0; i < generatedPassword.Length; i++) { if (generatedPassword[i] == receivedChar) { return; } } generatedPassword += receivedChar; } private static bool IsSingPassword(string answerUser) { return answerUser == "Y" ? true : answerUser == "N" ? false : throw new Exception("Wrong command"); } private static bool IsRepitSymbol(string answerUser) { return answerUser == "Y" ? true : answerUser == "N" ? false : throw new Exception("Wrong command"); } private static char GeneratingLowerСharacters() { Random random = new Random(); int symbolCode = random.Next(97, 123); return Convert.ToChar(symbolCode); } private static char GeneratingUpperCharacters() { Random random = new Random(); int symbolCode = random.Next(65, 91); return Convert.ToChar(symbolCode); } private static char GenerationSpecialСharacters() { Random random = new Random(); int symbolCode = random.Next(33, 39); while (symbolCode == 34) { symbolCode = random.Next(33, 39); } return Convert.ToChar(symbolCode); } private static char GenerationNumberСharacters() { Random random = new Random(); int symbolCode = random.Next(48, 58); return Convert.ToChar(symbolCode); } private static string AddHyphen() { StringBuilder resultPassword = new StringBuilder(generatedPassword); resultPassword.Insert(2, "-"); resultPassword.Insert(5, "-"); resultPassword.Insert(9, "-"); return resultPassword.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; using VendingMachine.Domain.Models; namespace VendingMachine.Domain.Business.Contracts.Business { public interface IProductService { List<Product> GetProducts(); } }
/*************************************** * * Body for Objects that has no Dependents * ***************************************/ namespace DChild.Gameplay.Objects { public class VisualBody : IsolatedTime, IVisualBody, IVisualTime { private float m_deltaTime; public float deltaTime => m_deltaTime; public void UpdateDeltaTime(float deltaTime) { m_deltaTime = deltaTime * totalTimeScale; } protected override void UpdateComponents() { } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Text; using VendingMachine.Domain.Models; namespace VendingMachine.Repository { public class MachineContext : DbContext { public virtual DbSet<Product> Products { get; set; } public virtual DbSet<Voorraad> Voorraads { get; set; } public MachineContext() : base(@"Data Source=(LocalDb)\SoftwareDevelopment;Initial Catalog=VendingMachine;User Id=VendingUser;Password=VendingUser;MultipleActiveResultSets=true;Connect Timeout=60;") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Mapping to diffrent tables modelBuilder.Entity<Product>().ToTable("Producten", "Machine"); modelBuilder.Entity<Bestelling>().ToTable("Bestellingen", "Machine"); modelBuilder.Entity<Geld>().ToTable("Voorraad_Geld", "Machine"); modelBuilder.Entity<Voorraad>().ToTable("Voorraad_Producten", "Machine"); } } }
using CodeX; using LuaFramework; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; public class DownloadUpdateHistory : Singleton<DownloadUpdateHistory> { private Dictionary<string, bool> m_download_history = new Dictionary<string, bool>(); private float m_last_save_download_history_time = 0f; private int m_last_save_download_history_count = 0; public void ReadDownloadHistory() { string res_file = AppUtil.DataPath + "downloadhistory.temp"; if (File.Exists(res_file)) { StreamReader sr = new StreamReader(res_file); string str; while ((str = sr.ReadLine()) != null) { this.m_download_history.Add(str, true); } sr.Dispose(); sr = null; } } public void AddDownloadHistory(string file_path) { string file_name = Path.GetFileNameWithoutExtension(file_path); bool temp; if (!this.m_download_history.TryGetValue(file_name, out temp)) { this.m_download_history.Add(file_name, true); } } public bool ExistDownloadHistory(string file_path) { if (this.m_download_history.Count == 0) return false; string file_name = Path.GetFileNameWithoutExtension(file_path); return this.m_download_history.ContainsKey(file_name); } public void UpdateSaveDownloadHistory() { if (!(Time.time - this.m_last_save_download_history_time < 10f)) { SaveDownloadHistory(); } } public void SaveDownloadHistory() { if (!(this.m_download_history.Count == 0 || this.m_download_history.Count == this.m_last_save_download_history_count)) { this.m_last_save_download_history_time = Time.time; this.m_last_save_download_history_count = this.m_download_history.Count; StringBuilder temp = new StringBuilder(); foreach (KeyValuePair<string, bool> resdata in this.m_download_history) { string key = resdata.Key; temp.AppendFormat("{0}\n", key); } string data_file = string.Format("{0}/downloadhistory.temp", AppUtil.DataPath); string content = temp.ToString(); if (content.Length > 0) { content = content.Substring(0, content.Length - 1); } File.WriteAllText(data_file, content); } } }
namespace StringReplicator.Core.Helpers { public interface IConfig { string GetRootPath(); string CurrentFilePath(); string GetUdlPath(); } }
using System.Collections.Generic; namespace DChild.Gameplay.Systems.Serialization { public class ZoneSerializationHandler : ISerializer { private List<ZoneSerializer> m_zoneSerializers; public ZoneSerializationHandler() { m_zoneSerializers = new List<ZoneSerializer>(); } public void Register(ZoneSerializer serializer) { m_zoneSerializers.Add(serializer); } public void Unregister(ZoneSerializer serializer) { m_zoneSerializers.Remove(serializer); } public void Save() { for (int i = 0; i < m_zoneSerializers.Count; i++) { m_zoneSerializers[i].Save(); } } public void Load() { for (int i = 0; i < m_zoneSerializers.Count; i++) { m_zoneSerializers[i].Load(); } } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiCoin.Wallet.Win.Biz; using FiiiCoin.Wallet.Win.Models; using FiiiCoin.Wallet.Win.ViewModels; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace FiiiCoin.Wallet.Win.Common { public abstract class VmBase : ViewModelBase { public VmBase() { OnLoaded(); } private string PageName { get { return GetPageName(); } } protected void ShowMessage(string msg) { StaticViewModel.GlobalViewModel.IsLoading = false; Initializer.Default.ShowMessage(msg); } protected void Send(SendMessageTopic msg, string pageName) { Messenger.Default.Send(msg, pageName); } public virtual void OnClosePopup() { PopUpParams popUpParams = new PopUpParams { IsOpen = false }; Messenger.Default.Send(popUpParams, MessageTopic.ChangedPopupViewState); } private void GetSendMsg(SendMessageTopic msg) { switch (msg) { case SendMessageTopic.Refresh: Refresh(); break; default: break; } } protected void UpdatePage(string pageName, PageModel pageModel = PageModel.DialogPage) { switch (pageModel) { case PageModel.MainPage: Messenger.Default.Send(pageName, MessageTopic.UpdateMainView); break; case PageModel.DialogPage: Messenger.Default.Send(pageName, MessageTopic.UpdatePopupView); PopUpParams popUpParams = new PopUpParams { IsOpen = true }; Messenger.Default.Send(popUpParams, MessageTopic.ChangedPopupViewState); break; case PageModel.TabPage: Messenger.Default.Send(pageName, Pages.MainPage); break; case PageModel.MessagePage: break; default: break; } } protected virtual void Refresh() { } protected virtual string GetPageName() { return null; } protected virtual void OnLoaded() { RegeistMessenger<SendMessageTopic>(GetSendMsg); } protected void SendMessenger<T>(string pageName, T param) { Messenger.Default.Send(param, pageName); } protected void RegeistMessenger<T>(Action<T> action) { var pageName = GetPageName(); if (string.IsNullOrEmpty(pageName)) return; Messenger.Default.Register<T>(this, GetPageName(), action); } } public enum PageModel { MainPage, DialogPage, TabPage, MessagePage } }
using Microsoft.ServiceFabric.Data.Collections; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Microsoft.ServiceFabric.Data { internal class StatefulServiceStateManager : IReliableStateManager { ConcurrentDictionary<string, object> state; public ITransaction CreateTransaction() { return new Transaction(); } //public Task<T> GetOrAddAsync<T>(string key) //{ // return Task.Run(() => { // var t = CreateInstance<T>(); // state.GetOrAdd(key, t); // return t; // }); //} public T CreateInstance<T>() where T: class, IReliableState // IReliableDictionary<string, string> { //TODO: Hack. replace it with a factory and use dependecy injection for the different types if (typeof(T) == typeof(IReliableDictionary<string, string>)) { var instance = new ReliableDictionary<string, string>(); return instance as T; } return default(T); } public Task<T> GetOrAddAsync<T>(string name) where T : class, IReliableState { return Task.Run(() => { var t = CreateInstance<T>(); state.GetOrAdd(name, t); return t; }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace KartObjects { /// <summary> /// Отчет остатки /// </summary> public class RestReport:Entity { public override string FriendlyName { get { return "Отчет остатки"; } } /// <summary> /// Список записей отчета /// </summary> public List<RestReportRecord> Records { get; set; } public RestReport() { Records = new List<RestReportRecord>(); } /// <summary> /// Запускаем отчет об остатках на текущее время, по ассортиментной позиции, по всем складам /// </summary> /// <param name="IdAssortment"></param> public void ExecReport(long IdAssortment) { string query = "select * from SP_REPORT_REST_BY_ASSORTMENT ( " + IdAssortment.ToString() +",null)"; bool result; DataTable dataTable = new DataTable(); try { Loader.DataContext.Fill(query, ref dataTable); result = true; } catch (Exception) { result = false; } if (result) foreach (DataRow row in dataTable.Rows) { RestReportRecord rr = new RestReportRecord() { idAssortment=IdAssortment, Rest=Convert.ToDecimal(row["rest"]), Name=row["wh_name"].ToString() }; Records.Add(rr); } } /// <summary> /// Возвращает строки отчета /// </summary> /// <returns></returns> public List<RestReportRecord> GetRecords() { return Records; } public long IdGood { get; set; } public long IdAssortment { get; set; } public int IdPosDevice { get; set; } public void ExecReport() { string query =""; if (IdAssortment==0) query = "select * from SP_REPORT_REST_BY_good ( " + IdGood.ToString() + ",null)"; else query = "select * from SP_REPORT_REST_BY_ASSORTMENT ( " + IdAssortment.ToString() + ",null)"; bool result; DataTable dataTable = new DataTable(); try { Loader.DataContext.Fill(query, ref dataTable); result = true; } catch (Exception) { result = false; } if (result) foreach (DataRow row in dataTable.Rows) { RestReportRecord rr = new RestReportRecord() { idAssortment = IdAssortment, Rest = Convert.ToDecimal(row["rest"]), Name = row["wh_name"].ToString() }; Records.Add(rr); } } } }
using System.Collections; using System.Collections.Generic; using System; using System.Text; using UnityEngine; using UnityEngine.Windows.Speech; using UnityEngine.UI; public class UserInputVoiceRecognizer : MonoBehaviour { bool teclaPulsada = false; float windowTime = 1; [SerializeField] private Text m_Hypotheses; [SerializeField] private Text m_Recognitions; private DictationRecognizer m_DictationRecognizer; [SerializeField] private string[] m_Keywords; private KeywordRecognizer m_Recognizer; //el que le pasas la lista de palabras a reconocer // Start is called before the first frame update void Start() { } // Update is called once per frame private void OnPhraseRecognized(PhraseRecognizedEventArgs args){ StringBuilder builder = new StringBuilder(); builder.AppendFormat("{0} ({1}){2}", args.text, args.confidence, Environment.NewLine); builder.AppendFormat("\tTimestamp: {0}{1}", args.phraseStartTime, Environment.NewLine); builder.AppendFormat("\tDuration: {0} seconds{1}", args.phraseDuration.TotalSeconds, Environment.NewLine); Debug.Log(builder.ToString()); } // Update is called once per frame void Update() { if (Time.time - windowTime >= 1){ if(Input.GetKey(KeyCode.UpArrow)){ if(teclaPulsada == false){ teclaPulsada = true; m_Keywords = new string[4]; m_Keywords.SetValue("Hello",0); m_Keywords.SetValue("Good",1); m_Keywords.SetValue("Football",2); m_Keywords.SetValue("Interfaces",3); m_Recognizer = new KeywordRecognizer(m_Keywords); m_Recognizer.OnPhraseRecognized += OnPhraseRecognized; Debug.Log("Estoy empezando a escuchar "); m_Recognizer.Start(); Debug.Log("Estoy terminando de escuchar "); } else if(teclaPulsada == true){ m_DictationRecognizer.Stop(); m_Recognizer.Dispose(); Debug.Log("Tecla Pulsada,en m_Recognizer, true"); teclaPulsada = false; } windowTime = Time.time; } else if(Input.GetKey(KeyCode.DownArrow)) { if(teclaPulsada == false){ teclaPulsada = true; m_DictationRecognizer = new DictationRecognizer(); m_DictationRecognizer.DictationResult += (text, confidence) => { try{ Debug.LogFormat("Dictation result: {0}", text); m_Recognitions.text += text + "\n"; } catch(Exception e){} }; m_DictationRecognizer.DictationHypothesis += (text) => { try{ Debug.LogFormat("Dictation hypothesis: {0}", text); m_Hypotheses.text += text; } catch(Exception e){} }; m_DictationRecognizer.DictationComplete += (completionCause) => { if (completionCause != DictationCompletionCause.Complete) Debug.LogErrorFormat("Dictation completed unsuccessfully: {0}.", completionCause); }; m_DictationRecognizer.DictationError += (error, hresult) => { Debug.LogErrorFormat("Dictation error: {0}; HResult = {1}.", error, hresult); }; m_DictationRecognizer.Start(); } else if(teclaPulsada == true){ m_DictationRecognizer.Stop(); m_DictationRecognizer.Dispose(); Debug.Log("Tecla pulsada,m_DictationRecognizer,true"); teclaPulsada = false; } windowTime = Time.time; } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using caiJiDll; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace caiJiDll.Tests { [TestClass()] public class Class1Tests { [TestMethod()] public void convertHrefTest() { Class1.sURL = "https://www.sephora.cn/?rsour=sephoraUS&rmeth=test"; string href= Class1.convertHref(@"/hot/t"); Assert.AreEqual(href, @"https://www.sephora.cn/hot/t"); } [TestMethod()] public void caiJiTest() { caiJiDll.Class1.sURL = "https://www.sephora.cn/?rsour=sephoraUS&rmeth=test"; string s = "<a class=\"\" href=\"/hot\">"; string sre = caiJiDll.Class1.caiJi(s); Assert.AreEqual(sre, "a\t href\t href path\n<a class=\"\" href=\"/hot\">\t/hot\thttps://www.sephora.cn/hot\n"); } [TestMethod()] public void caiJiURLTest() { Class1.caiJiURL("https://www.sephora.cn/?rsour=sephoraUS&rmeth=test"); } } }
using System; using UnityEngine; using UnityEngine.UI; namespace XDebug { [Serializable] public class Icon: IEquatable<Icon> { [SerializeField] private float m_Width; [SerializeField] private float m_Height; [SerializeField] private Color m_Color; public Button button { get; set; } public float width { get { return m_Width; } set { m_Width = value; } } public float height { get { return m_Height; } set { m_Height = value; } } public Color color { get { return m_Color; } set { m_Color = value; } } public static Icon defaultIcon { get { return new Icon() { m_Width = 50, m_Height = 50, m_Color = Color.white }; } } public void Copy(Icon icon) { m_Width = icon.width; m_Height = icon.height; m_Color = icon.color; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } else if (obj is Icon) { return Equals((Icon)obj); } else { return false; } } public bool Equals(Icon other) { if (ReferenceEquals(null, other)) { return false; } return width == other.width && height == other.height && color == other.color; } public static bool operator ==(Icon left, Icon right) { if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) { return true; } else if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } return Equals(left, right); } public static bool operator !=(Icon left, Icon right) { return !(left == right); } public override int GetHashCode() { return base.GetHashCode(); } } }
using UnityEngine; using System.Collections; public class StatsManager : MonoBehaviour { public static string playerName; public static int styleChoice; public static int frustration; public static bool empCamera; public static bool shootCamera; public static bool pickDoor; public static bool saveData; public static bool knockOutMan; public static bool killMan; public static bool footEscape; public static bool swimEscape; }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OnlineShopping.Models { public class FilterViewModel { public string SortBy { get; set; } public string Search { get; set; } public int MaxPrice { get; set; } public int MinPrice { get; set; } } }
public class Solution { public bool IsMatch(string s, string p) { bool[,] helperArray = new bool[s.Length+1,p.Length+1]; helperArray[s.Length,p.Length] = true; for (int i = s.Length ; i >= 0; i --) { for (int j = p.Length - 1; j >= 0; j--) { bool firstMatch = (i < s.Length) && (s[i] == p[j] || p[j] == '.'); if (j < p.Length - 1 && p[j+1] == '*') { helperArray[i,j] = (firstMatch && helperArray[i+1,j]) || helperArray[i,j+2]; } else { helperArray[i,j] = firstMatch && helperArray[i+1,j+1]; } } } return helperArray[0,0]; } }
using System; using System.Windows.Data; using Cradiator.Converters; using NUnit.Framework; using Shouldly; namespace Cradiator.Tests.Converters { [TestFixture] public class BuildNameAndMessageConverter_Test { private readonly IMultiValueConverter _converter = new BuildNameToMessageConverter(); private object DoConvert(object[] obj) { return _converter.Convert(obj, typeof(string), null, null); } [Test] public void BuildBrokenOK_JohnDoeBrokeIt() { DoConvert(new object[] {"foo_bar_yo", "Breakers : Johndoe"}) .ShouldBe("foo bar yo\nBreakers : Johndoe"); } [Test] public void BuildBrokenOK_JohnDoeIsFixingIt() { DoConvert(new object[] {"foo_bar_yo", "Johndoe is fixing the build"}) .ShouldBe("foo bar yo\nJohndoe is fixing the build"); } [Test] public void BuildOK_name_with_underscores_has_them_removed() { DoConvert(new object[] {"foo_bar_yo", ""}) .ShouldBe("foo bar yo"); } [Test] public void TestName() { Assert.Throws<NotImplementedException>(() => _converter.ConvertBack("ThomasTheTankEngine", null, null, null) ); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.DataAccess.AccountEntity { public class InvoiceDetail { public int Id { get; set; } public string InvoiceId { get; set; } public int ServiceTypeId { get; set; } public virtual ServiceType ServiceType { get; set; } public string ServiceDesc { get; set; } public int Quantity { get; set; } public double? Unitprice { get; set; } public double? Total { get; set; } public string InvoiceType { get; set; } public DateTime? CreateDate { get; set; } public string CreateBy { get; set; } public DateTime? UpdateDate { get; set; } public string UpdateBy { get; set; } } public class InvoiceDetailConfig : EntityTypeConfiguration<InvoiceDetail> { public InvoiceDetailConfig() { ToTable("InvoiceDetail"); Property(t => t.Id).HasColumnName("id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(t => t.InvoiceId).HasColumnName("InvoiceID"); Property(t => t.ServiceTypeId).HasColumnName("service_type_id"); Property(t => t.ServiceDesc).HasColumnName("service_desc"); Property(t => t.Quantity).HasColumnName("quantity"); Property(t => t.Unitprice).HasColumnName("unitprice"); Property(t => t.Total).HasColumnName("total"); Property(t => t.InvoiceType).HasColumnName("invoice_type"); Property(t => t.CreateDate).HasColumnName("createDate"); Property(t => t.CreateBy).HasColumnName("createBy"); Property(t => t.UpdateDate).HasColumnName("updateDate"); Property(t => t.UpdateBy).HasColumnName("updateBy"); HasRequired(t => t.ServiceType).WithMany().HasForeignKey(f => f.ServiceTypeId); HasKey(t => t.Id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HVCheck.Models { public class DuLieuSanPham { private static DuLieuSanPham _instance = null; public static DuLieuSanPham Instance() { if (_instance == null) _instance = new DuLieuSanPham(); return _instance; } public int ID { get; set; } public string TimeStamp { get; set; } public string Time { get; set; } public string MaDL { get; set; } public string TenDL { get; set; } public string MaSP { get; set; } } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace XWebService { public partial class PostsPage : ContentPage { public PostsPage(int id) { InitializeComponent(); BindData(id); BindComment(id); } private async void BindData(int id) { ServiceManager manager = new ServiceManager(); var post = await manager.GetPostInfo(id); lblBody.BindingContext = post; lblTitle.BindingContext = post; } private async void BindComment(int id) { ServiceManager manager = new ServiceManager(); var comments = await manager.GetPostComments(id); lstComments.BindingContext = comments; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using LitJson; using System.Security.Cryptography; using System.IO; using System.IO.Compression; using System.Data; public class CsString { static string SqlStr = @"like|and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators"; public static bool ProcessSqlStr(string inputString) { // try // { // if ((inputString != null) && (inputString != String.Empty)) // { // string str_Regex = @"\b(" + SqlStr + @")\b"; // Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase); // if (true == Regex.IsMatch(inputString)) // return false; // } // } // catch // { // return false; // } return true; } public static string DecodeOutputString(string outputstring) { //要替换的敏感字 try { if ((outputstring != null) && (outputstring != String.Empty)) { string str_Regex = @"\[\b(" + SqlStr + @")\b\]"; Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase); MatchCollection matches = Regex.Matches(outputstring); for (int i = 0; i < matches.Count; i++) outputstring = outputstring.Replace(matches[i].Value, matches[i].Value.Substring(1, matches[i].Value.Length - 2)); } } catch { return ""; } return outputstring; } public CsString(string _Value) { Data = _Value; } public CsString() { Data = ""; } public CsString Fill(int _Value) { Data += string.Format("{0},", _Value); return this; } public CsString Fill(uint _Value) { Data += string.Format("{0},", _Value); return this; } public CsString Fill(short _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(bool _Value) { Data += string.Format("{0},", _Value ? 1 : 0); return this; } public CsString Fill(ushort _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(char _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(byte _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(byte[] _Value) { Data += string.Format("{0},", Convert.ToBase64String(_Value)); ; return this; } public CsString Fill(Int64 _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(UInt64 _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(float _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(double _Value) { Data += string.Format("{0},", _Value); ; return this; } public CsString Fill(string _Value) { if (_Value == null) _Value = ""; Data += " '"; Data += _Value; Data += "',"; return this; } public CsString FillJson(string _Value) { if (_Value == null) _Value = ""; else _Value = _Value.Replace("\\u", "\\\\u"); Data += " '"; Data += _Value; Data += "',"; return this; } public CsString FillEx(string _Value) { if (_Value == null) _Value = ""; Data += "'"; Data += _Value; Data += "'"; return this; } public CsString FillEx(int _Value) { Data += _Value.ToString(); return this; } public CsString FillEx(uint _Value) { Data += _Value.ToString(); return this; } public CsString FillEx(float _Value) { Data += _Value.ToString(); return this; } public CsString FillEx(double _Value) { Data += _Value.ToString(); return this; } public CsString FillJsonEx(string _Value) { if (_Value == null) _Value = ""; else _Value = _Value.Replace("\\u", "\\\\u"); Data += "'"; Data += _Value; Data += "'"; return this; } public CsString EndInsertJson(string _Value) { if (_Value == null) _Value = ""; else _Value = _Value.Replace("\\u", "\\\\u"); Data += "'"; Data += _Value; Data += "')"; return this; } public CsString EndInsert(string _Value) { if (_Value == null) _Value = ""; Data += "'"; Data += _Value; Data += "')"; return this; } public CsString EndInsert(int _Value) { Data += _Value; Data += ")"; return this; } public static string SqlString(string str) { return string.Format("'{0}'", str); } public static CsString InstertSql(string TableName, string colum, string _value) { CsString newStr = new CsString("INSERT INTO " + TableName + " (" + colum + ") " + "VALUES(" + _value + ")"); return newStr; } public static CsString UpdateSql(string TableName) { CsString newStr = new CsString("UPDATE " + TableName + " SET "); return newStr; } //-------------------------------- public static CsString operator <<(CsString My, int _Value) { My.Data += string.Format("{0},", _Value); return My; } public static CsString operator +(CsString My, CsString Other) { My.Data += Other.Data; return My; } public static CsString operator +(CsString My, string _Value) { My.Data += _Value; return My; } public static CsString operator +(CsString My, int _Value) { My.Data += _Value + " "; return My; } public static CsString operator +(CsString My, uint _Value) { My.Data += _Value + " "; return My; } public static CsString operator +(CsString My, short _Value) { My.Data += _Value + " "; return My; } public static CsString operator +(CsString My, byte _Value) { My.Data += _Value + " "; return My; } public static CsString operator +(CsString My, char _Value) { My.Data += _Value + " "; return My; } public static CsString operator +(CsString My, float _Value) { My.Data += _Value + " "; return My; } public string Data; public string GetStr() { return Data; } public override string ToString() { return Data; } public string JsonString() { Data = Data.Replace("\\u", "\\\\u"); return Data; } } public class CsTxtToCn { class CsRemoveString { public int startIndex = 0; public int endIndex = 0; public string Strs = ""; } public static bool IsQQNum(char _char) { if ( _char == '0' || _char == '1' || _char == '2' || _char == '3' || _char == '4' || _char == '5' || _char == '6' || _char == '7' || _char == '8' || _char == '9'|| _char == '0' || _char == '1' || _char == '2' || _char == '3' || _char == '4' || _char == '5' || _char == '6' || _char == '7' || _char == '8' || _char == '9' ) return true; return false; } public static bool IsQQNumString(string txt, int startIndex, out int Len) { Len = IsQQNumString(txt, startIndex); return Len != -1; } public static int IsQQNumString(string txt, int startIndex) { int i = 0; for (i = 0; i < txt.Length - startIndex&&i<12; i++) { if (!IsQQNum(txt[startIndex + i])) break; } if (i <= 5) return -1; return i; } public static string Convert(string txt, out int len) { len = 0; if (txt == null) return null; txt = txt.Replace("www", ""); txt = txt.Replace("http", ""); txt = txt.Replace("net", ""); txt = txt.Replace("版主", ""); txt = txt.Replace("div", ""); txt = txt.Replace("\n\n", "\n"); txt = txt.Replace("\n\n\n", "\n"); txt = txt.Replace("\n\n\n\n", "\n"); txt = txt.Replace("\n\n\n\n\n", "\n"); txt = txt.Replace("\r\n\r\n", "\n"); txt = txt.Replace("\r\n", "\n"); txt = txt.Replace("\r\n\r\n\r\n", "\n"); txt = txt.Replace("\r\n\r\n\r\n\r\n", "\n"); txt = txt.Replace("\r\n\r\n\r\n\r\n\r\n", "\n"); List<CsRemoveString> removes = new List<CsRemoveString>(); CsRemoveString newCsRemoveString = null; // string newTxt = ""; // for (int i = 0; i < txt.Length; i++) // { // if (txt[i] == '<') // { // newCsRemoveString = new CsRemoveString(); // newCsRemoveString.startIndex = i; // newCsRemoveString.Strs+=txt[i]; // } // else if (txt[i] == '>') // { // if (newCsRemoveString != null) // { // newCsRemoveString.Strs+=txt[i]; // newCsRemoveString.endIndex = i; // newCsRemoveString = null; // } // } // if (newCsRemoveString == null) // { // newCsRemoveString.Strs += txt[i]; // newTxt += txt[i]; // } // } // txt = newTxt; int _Len = 0; string txtString = ""; int QQNum = -1; txt += " "; for (int i = 0; i < txt.Length - 1; i++) { if (txt[i] == '<' || txt[i] == '>' || txt[i] == '/' || txt[i] == '\\' || txt[i] == 'C' || txt[i] == 'W' || txt[i] == 'O' || txt[i] == 'M' || txt[i] == 'c' || txt[i] == 'o' || txt[i] == 'm' || txt[i] == 'w' || txt[i] == 'N' || txt[i] == 'E' || txt[i] == 'T' || txt[i] == 'B' || txt[i] == 'Z' || txt[i] == 'A' || txt[i] == 'E' || txt[i] == 'O' || txt[i] == 'U' || txt[i] == 'I' || txt[i] == ' ' || txt[i] == ' ' || txt[i] == 'Q' || txt[i] == '$' || txt[i] == '}' || txt[i] == '{' || txt[i] == '}' || txt[i] == '%' || txt[i] == '|' || txt[i] == '#' || txt[i] == '@' || txt[i] == '&' || txt[i] == '^' || txt[i] == '~' || txt[i] == '-' || txt[i] == '=' || txt[i] == '+' || txt[i] == '^' || txt[i] == '*' || txt[i] == '`' || txt[i] == '《' || txt[i] == '》' || txt[i] == ' ' || txt[i] == ' ') { continue; } else if (txt[i] == '(') txtString += "("; else if (txt[i] == ')') txtString += ")"; else if (txt[i] == '[') txtString += "【"; else if (txt[i] == ']') txtString += "】"; else if (txt[i] == '?') txtString += "?"; else if (txt[i] == ',') txtString += ","; else if (txt[i] == '.') txtString += "。"; else if (txt[i] == '!') txtString += "!"; else if (txt[i] == '0') txtString += "0"; else if (txt[i] == '1') txtString += "1"; else if (txt[i] == '2') txtString += "2"; else if (txt[i] == '3') txtString += "3"; else if (txt[i] == '4') txtString += "4"; else if (txt[i] == '5') txtString += "5"; else if (txt[i] == '6') txtString += "6"; else if (txt[i] == '7') txtString += "7"; else if (txt[i] == '8') txtString += "8"; else if (txt[i] == '9') txtString += "9"; else if (IsQQNumString(txt, i, out QQNum)) { i += QQNum-1; continue; } else if (txt[i] == '\n') { // if (txt[i - 1] == '。' || txt[i - 1] == '?' || txt[i - 1] == '”' || txt[i - 1] == '!') txtString += "\n  "; } else { txtString += txt[i]; _Len++; } } len = _Len; txt = txt.Replace(":\"", ":“"); txt = txt.Replace("。\"", "。”"); return "  " + txtString; } }
using UnityEngine; using System.Collections; public class SortParticleSystem : MonoBehaviour { public string LayerName; }
using Application.Services; using Domain.Enums; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using WebApi.DataContracts; using WebApi.DataContracts.Users.Mappers; namespace WebApi.Controllers { [Authorize] [ApiController] [Route("[controller]")] public class UserController : ControllerBase { private readonly IUserService userService; private readonly ILogger<UserController> logger; public UserController(ILogger<UserController> logger, IUserService userService) { this.logger = logger; this.userService = userService; } [HttpGet()] public async Task<IActionResult> Get() { var userIdClaim = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; Guid userId; if(!Guid.TryParse(userIdClaim, out userId)) { return BadRequest("No user exist in the system"); } var user = await userService.GetById(userId); if(user == null) { return BadRequest("No user exist in the system"); } return Ok(UserMapper.MapUserEntityToUserDetails(user)); } [HttpPost()] [AllowAnonymous] public async Task<IActionResult> Post(UserRegister model) { return Ok(await this.userService.RegisterAsync(UserMapper.MapDataContractToEntity(model))); } } }
using FichaTecnica.Dominio; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace FichaTecnica.Models { public class ComentarioModel { [Required] public string Assunto{ get; set; } [Required] public string Texto { get; set; } [Required] public Tipo Tipo { get; set; } public DateTime DataCriacao { get; set; } public int IdUsuario { get; set; } [Required] public int IdProjeto { get; set; } public int IdMembro { get; set; } public ComentarioModel() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Attribute { /// <summary> /// 字段类型 /// </summary> public enum FieldType { NONE, 数据库字段, 虚拟字段, 关联字段, 关联对象 } }
namespace DangerousFloor { using System; using System.Linq; public class Startup { static int n = 8; public static void Main(string[] args) { Execute(); } private static void Execute() { var matrix = new char[n][]; for (int i = 0; i < n; i++) { matrix[i] = Console.ReadLine() .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p[0]).ToArray(); } var line = Console.ReadLine(); while (line != "END") { MoveFigure(line, matrix); line = Console.ReadLine(); } } private static void MoveFigure(string line, char[][] matrix) { var figure = line[0]; var startRow = line[1] - '0'; var startCol = line[2] - '0'; var endRow = line[4] - '0'; var endCol = line[5] - '0'; if (!InMatrix(startRow, startCol) || matrix[startRow][startCol] != figure) { Console.WriteLine("There is no such a piece!"); return; } if (!InMatrix(endRow, endCol)) { Console.WriteLine("Move go out of board!"); return; } var movedFigure = false; switch (figure) { case 'K': movedFigure = MoveKing(startRow, startCol, endRow, endCol, matrix); break; case 'R': movedFigure = MoveRook(startRow, startCol, endRow, endCol, matrix); break; case 'B': movedFigure = MoveBishop(startRow, startCol, endRow, endCol, matrix); break; case 'Q': movedFigure = MoveQueen(startRow, startCol, endRow, endCol, matrix); break; case 'P': movedFigure = MovePawn(startRow, startCol, endRow, endCol, matrix); break; default: break; } if (!movedFigure) { Console.WriteLine("Invalid move!"); } } private static bool MovePawn(int startRow, int startCol, int endRow, int endCol, char[][] matrix) { if (startRow - 1 == endRow) { if (startCol - 1 == endCol && InMatrix(startRow - 1, startCol - 1)) { matrix[endRow][endCol] = 'P'; matrix[startRow][startCol] = 'x'; return true; } if (startCol == endCol && InMatrix(startRow - 1, startCol)) { matrix[endRow][endCol] = 'P'; matrix[startRow][startCol] = 'x'; return true; } if (startCol + 1 == endCol && InMatrix(startRow - 1, startCol + 1)) { matrix[endRow][endCol] = 'P'; matrix[startRow][startCol] = 'x'; return true; } } return false; } private static bool MoveRook(int startRow, int startCol, int endRow, int endCol, char[][] matrix) { if ((startRow != endRow && startCol != endCol) || matrix[endRow][endCol] != 'x') { return false; } matrix[endRow][endCol] = 'R'; matrix[startRow][startCol] = 'x'; return true; } private static bool MoveQueen(int startRow, int startCol, int endRow, int endCol, char[][] matrix) { if (matrix[endRow][endCol] != 'x') { return false; } for (int i = 1; i <= n; i++) { if (startRow - i == endRow && startCol == endCol && InMatrix(startRow - i, startCol)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } if (startRow + i == endRow && startCol == endCol && InMatrix(startRow + i, startCol)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } if (startRow == endRow && startCol - i == endCol && InMatrix(startRow, startCol - i)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } if (startRow == endRow && startCol + i == endCol && InMatrix(startRow, startCol + i)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } if (startRow - i == endRow && startCol - i == endCol && InMatrix(startRow - i, startCol - i)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } if (startRow - i == endRow && startCol + i == endCol && InMatrix(startRow - i, startCol + i)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } if (startRow + i == endRow && startCol - i == endCol && InMatrix(startRow + i, startCol - i)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } if (startRow + i == endRow && startCol + i == endCol && InMatrix(startRow + i, startCol + i)) { matrix[endRow][endCol] = 'Q'; matrix[startRow][startCol] = 'x'; return true; } } return false; } private static bool MoveBishop(int startRow, int startCol, int endRow, int endCol, char[][] matrix) { if (matrix[endRow][endCol] != 'x') { return false; } for (int i = 1; i <= n; i++) { if (startRow - i == endRow && startCol - i == endCol && InMatrix(startRow - i, startCol - i)) { matrix[endRow][endCol] = 'B'; matrix[startRow][startCol] = 'x'; return true; } if (startRow - i == endRow && startCol + i == endCol && InMatrix(startRow - i, startCol + i)) { matrix[endRow][endCol] = 'B'; matrix[startRow][startCol] = 'x'; return true; } if (startRow + i == endRow && startCol - i == endCol && InMatrix(startRow + i, startCol - i)) { matrix[endRow][endCol] = 'B'; matrix[startRow][startCol] = 'x'; return true; } if (startRow + i == endRow && startCol + i == endCol && InMatrix(startRow + i, startCol + i)) { matrix[endRow][endCol] = 'B'; matrix[startRow][startCol] = 'x'; return true; } } return false; } private static bool MoveKing(int startRow, int startCol, int endRow, int endCol, char[][] matrix) { if (InMatrix(startRow - 1, startCol) && endRow == startRow - 1 && endCol == startCol) { matrix[startRow][startCol] = 'x'; matrix[startRow - 1][startCol] = 'K'; return true; } if (InMatrix(startRow + 1, startCol) && endRow == startRow + 1 && endCol == startCol) { matrix[startRow][startCol] = 'x'; matrix[startRow + 1][startCol] = 'K'; return true; } if (InMatrix(startRow - 1, startCol - 1) && endRow == startRow - 1 && endCol == startCol - 1) { matrix[startRow][startCol] = 'x'; matrix[startRow - 1][startCol - 1] = 'K'; return true; } if (InMatrix(startRow - 1, startCol + 1) && endRow == startRow - 1 && endCol == startCol + 1) { matrix[startRow][startCol] = 'x'; matrix[startRow - 1][startCol + 1] = 'K'; return true; } if (InMatrix(startRow, startCol - 1) && endRow == startRow && endCol == startCol - 1) { matrix[startRow][startCol] = 'x'; matrix[startRow][startCol - 1] = 'K'; return true; } if (InMatrix(startRow, startCol + 1) && endRow == startRow && endCol == startCol + 1) { matrix[startRow][startCol] = 'x'; matrix[startRow][startCol + 1] = 'K'; return true; } if (InMatrix(startRow + 1, startCol - 1) && endRow == startRow + 1 && endCol == startCol - 1) { matrix[startRow][startCol] = 'x'; matrix[startRow + 1][startCol - 1] = 'K'; return true; } if (InMatrix(startRow + 1, startCol + 1) && endRow == startRow + 1 && endCol == startCol + 1) { matrix[startRow][startCol] = 'x'; matrix[startRow + 1][startCol + 1] = 'K'; return true; } return false; } private static bool InMatrix(int row, int col) { return row >= 0 && row < n && col >= 0 && col < n; } } }
using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; namespace com.Sconit.Entity.INV { [Serializable] public partial class StockTakeLocation : EntityBase, IAuditable { #region O/R Mapping Properties //[Display(Name = "Id", ResourceType = typeof(Resources.INV.StockTakeLocation))] public Int32 Id { get; set; } //[Display(Name = "StNo", ResourceType = typeof(Resources.INV.StockTakeLocation))] public string StNo { get; set; } [Display(Name = "StockTakeLocation_Location", ResourceType = typeof(Resources.INV.StockTakeLocation))] public string Location { get; set; } [Display(Name = "StockTakeLocation_LocationName", ResourceType = typeof(Resources.INV.StockTakeLocation))] public string LocationName { get; set; } //[Display(Name = "CreateUserId", ResourceType = typeof(Resources.INV.StockTakeLocation))] public Int32 CreateUserId { get; set; } //[Display(Name = "CreateUserName", ResourceType = typeof(Resources.INV.StockTakeLocation))] public string CreateUserName { get; set; } //[Display(Name = "CreateDate", ResourceType = typeof(Resources.INV.StockTakeLocation))] public DateTime CreateDate { get; set; } //[Display(Name = "LastModifyUserId", ResourceType = typeof(Resources.INV.StockTakeLocation))] public Int32 LastModifyUserId { get; set; } //[Display(Name = "LastModifyUserName", ResourceType = typeof(Resources.INV.StockTakeLocation))] public string LastModifyUserName { get; set; } //[Display(Name = "LastModifyDate", ResourceType = typeof(Resources.INV.StockTakeLocation))] public DateTime LastModifyDate { get; set; } [Display(Name = "StockTakeLocation_Bin", ResourceType = typeof(Resources.INV.StockTakeLocation))] public string Bins { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { StockTakeLocation another = obj as StockTakeLocation; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class projectile_controller : MonoBehaviour { Rigidbody2D rb; public int damageToDeal; void Start() { rb = GetComponent<Rigidbody2D>(); } void OnTriggerEnter2D(Collider2D other) { if(other.CompareTag("Player")) { other.GetComponent<damage_manager>().TakeDamage(damageToDeal,rb.velocity); Destroy(gameObject); } } }
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 CarInsurance1.Models; namespace CarInsurance1.Controllers { public class InsureeController : Controller { private InsuranceEntities db = new InsuranceEntities(); // GET: Insuree public ActionResult Index() { return View(db.Insurees.ToList()); } public ActionResult Admin() { return View(db.Insurees.ToList()); } public ActionResult CustomerQuote() { return View(db.Insurees); } // GET: Insuree/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Insuree insuree = db.Insurees.Find(id); if (insuree == null) { return HttpNotFound(); } return View(insuree); } // GET: Insuree/Create public ActionResult Create() { return View(); } // POST: Insuree/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType,Quote")] Insuree insuree) { if (string.IsNullOrEmpty(insuree.FirstName) || string.IsNullOrEmpty(insuree.LastName) || string.IsNullOrEmpty(insuree.EmailAddress) || string.IsNullOrEmpty(Convert.ToString(insuree.DateOfBirth)) || string.IsNullOrEmpty(Convert.ToString(insuree.CarYear)) || string.IsNullOrEmpty(insuree.CarMake) || string.IsNullOrEmpty(insuree.CarModel) || string.IsNullOrEmpty(Convert.ToString(insuree.SpeedingTickets))) { return View("~/Views/Shared/Error.cshtml"); } DateTime age = Convert.ToDateTime(insuree.DateOfBirth); int year = DateTime.Now.Year - age.Year; decimal quote = insuree.Quote + 50m; //This is for the age portion of the exercise. if(year < 18) { quote = quote + 100m; } else if (year < 25) { quote = quote + 25m; } else if (year > 100) { quote = quote + 25m; } //This is for the cars age portion int carAge = Convert.ToInt16(insuree.CarYear); if(carAge < 2000) { quote = quote + 25m; } else if(carAge > 2015) { quote = quote + 25m; } //This is for the car make string carMake = insuree.CarMake.ToLower(); if(carMake == "porsche") { quote = quote + 25m; } //This is for the car model string carModel = insuree.CarModel.ToLower(); if(carModel == "911 carrera" || carModel == "911" || carModel == "carrera") { quote = quote + 25m; } int speedTix = Convert.ToInt16(insuree.SpeedingTickets); if(speedTix > 0) { quote = quote + (speedTix * 10m); } //Dui bool dui = insuree.DUI; if(dui == true) { quote = quote * 1.25m; } //Coverage bool coverage = insuree.CoverageType; if(coverage == true) { quote = quote * 1.50m; } insuree.Quote = quote; if (ModelState.IsValid) { db.Insurees.Add(insuree); db.SaveChanges(); return RedirectToAction("CustomerQuote"); } return View(insuree); } // GET: Insuree/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Insuree insuree = db.Insurees.Find(id); if (insuree == null) { return HttpNotFound(); } return View(insuree); } // POST: Insuree/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType,Quote")] Insuree insuree) { if (ModelState.IsValid) { db.Entry(insuree).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(insuree); } // GET: Insuree/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Insuree insuree = db.Insurees.Find(id); if (insuree == null) { return HttpNotFound(); } return View(insuree); } //[HttpPost] ////Admin quote //public ActionResult Quote(string firstName, string lastName, string emailAddress, string dateOfBirth, string carYear, string carMake, string carModel, bool dui, string tickets, bool coverage, decimal iQuote) //{ // if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName) || string.IsNullOrEmpty(emailAddress) || string.IsNullOrEmpty(dateOfBirth) // || string.IsNullOrEmpty(carYear) || string.IsNullOrEmpty(carMake) || string.IsNullOrEmpty(carModel) || string.IsNullOrEmpty(tickets)) // { // return View("~/Views/Shared/Error.cshtml"); // } // else // { // using (InsuranceEntities db = new InsuranceEntities()) // { // var adminQuote = new Insuree(); // adminQuote.FirstName = firstName; // adminQuote.LastName = lastName; // adminQuote.EmailAddress = emailAddress; // adminQuote.Quote = iQuote; // } // return View(); // } //} // POST: Insuree/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Insuree insuree = db.Insurees.Find(id); db.Insurees.Remove(insuree); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using Microsoft.Xna.Framework; namespace OpenOracle.Old { public class MapOld : IUpdatableOld { private float _timeElapsed; public MapOld(string name, int width, int height, SpriteSheetWithAnimationOld spriteSheet) { Screens = new ScreenOld[width, height]; Name = name; SpriteSheet = spriteSheet; } public bool CrystalSwitchPosition { get; private set; } public int FrameIndex { get; private set; } public float TimeToUpdate { get; set; } public int Height => Screens.GetHeight(); public int Width => Screens.GetWidth(); public Point ScreenIndex { get; set; } public SpriteSheetWithAnimationOld SpriteSheet { get; } public string Name { get; } public ScreenOld CurrentScreen => Screens[ScreenIndex.X, ScreenIndex.Y]; public ScreenOld[,] Screens { get; set; } public float Fps { get { return 1f / TimeToUpdate; } set { TimeToUpdate = 1f / value; } } #region IUpdatable Members public void Update(GameTime gameTime) { _timeElapsed += (float)gameTime.ElapsedGameTime.TotalSeconds; if (!(_timeElapsed > TimeToUpdate)) return; _timeElapsed -= TimeToUpdate; FrameIndex = FrameIndex < SpriteSheet.AnimatedSheetWidth - 1 ? FrameIndex + 1 : 0; } #endregion public void AddCollision(int[,] staticCollision, int[,] animatedCollision) { SpriteSheet.AddCollision(staticCollision, animatedCollision); } public void ToggleCrystalSwitch() { CrystalSwitchPosition = !CrystalSwitchPosition; } } }
public class Solution { public int TrailingZeroes(int n) { int k = (int) Math.Log(n, 5); int res = 0; for (int i=1; i<=k; i++) { res += (int) (n / (Math.Pow(5, i))); } return res; } }
using System; using Tomelt.Events; using Tomelt.Messaging.Models; namespace Tomelt.Messaging.Events { [Obsolete] public interface IMessageEventHandler : IEventHandler { void Sending(MessageContext context); void Sent(MessageContext context); } }
using BHLD.Model.Models; using BHLD.Services; using BHLD.Web.Infrastructure.Core; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace BHLD.Web.Api { [RoutePrefix("api/SeUserOrgAccess")] public class SeUserOrgAccessController : APIControllerBase { Ise_user_org_accessServices _User_Org_AccessServices; public SeUserOrgAccessController(IErrorService errorService, Ise_user_org_accessServices org_AccessServices) : base(errorService) { this._User_Org_AccessServices = org_AccessServices; } [Route("Post")] public HttpResponseMessage Post(HttpRequestMessage request, se_user_org_access se_User_Org_Access) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (ModelState.IsValid) { request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { var district = _User_Org_AccessServices.Add(se_User_Org_Access); _User_Org_AccessServices.SaveChanges(); response = request.CreateResponse(HttpStatusCode.Created, district); } return response; } ); } [Route("Put")] public HttpResponseMessage Put(HttpRequestMessage request, se_user_org_access se_User_Org_Access) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (ModelState.IsValid) { request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { _User_Org_AccessServices.Update(se_User_Org_Access); _User_Org_AccessServices.SaveChanges(); response = request.CreateResponse(HttpStatusCode.OK); } return response; } ); } public HttpResponseMessage Delete(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (ModelState.IsValid) { request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { _User_Org_AccessServices.Delete(id); _User_Org_AccessServices.SaveChanges(); response = request.CreateResponse(HttpStatusCode.OK); } return response; } ); } [Route("getall")] public HttpResponseMessage Get(HttpRequestMessage request) { return CreateHttpResponse(request, () => { var listTitle = _User_Org_AccessServices.GetAll(); HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, listTitle); return response; } ); } } }
using System; using System.ComponentModel; using System.Linq; using System.Reflection; namespace RRExpress.Common { public static class EnumHelper { /// <summary> /// 获取 DescriptionAttribute 中的 Description /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TA"></typeparam> /// <param name="value"></param> /// <returns></returns> public static TA GetAttribute<T, TA>(T value) where T : struct, IComparable, IFormattable where TA : Attribute { var type = typeof(T); var field = type.GetRuntimeField(value.ToString()); return field.GetCustomAttributes(false).OfType<TA>().FirstOrDefault(); } /// <summary> /// /// </summary> /// <param name="e"></param> /// <returns></returns> public static string GetDescription(this Enum e) { var desc = ""; if (!string.IsNullOrWhiteSpace(desc)) return desc; FieldInfo fi = e.GetType().GetTypeInfo() .GetDeclaredField(e.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) return attributes[0].Description; else return e.ToString(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace GraphicalEditor.Converters { class NegativeEquipmentQuantityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { String quantity = value.ToString(); if (String.IsNullOrEmpty(quantity)) { return ""; } if (quantity.Contains("-")) quantity = quantity.Replace("-", ""); return quantity; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using ConsoleApplication1.Implementations; using ConsoleApplication1.Interfaces; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ConsoleApplication1.Tests.Implementations { [TestClass] public class MakelaarDomainModelBuilderTests : BaseTest { private readonly IMakelaarDomainModelBuilder builder = new MakelaarDomainModelBuilder(); [TestMethod] public void DependencyInjectionTest() { var result = this.DiContainer.GetInstance<IMakelaarDomainModelBuilder>(); Assert.AreEqual(typeof(MakelaarDomainModelBuilder), result.GetType()); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void ArgumentOutOfRangeExceptionWhenCreatedWithNullAsIdArgumentTest() { this.builder.Create(null, "naam", 0); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void ArgumentOutOfRangeExceptionWhenCreatedWithNullAsNaamArgumentTest() { this.builder.Create("id", null, 0); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void ArgumentOutOfRangeExceptionWhenCreatedWithEmptyStringAsIdArgumentTest() { this.builder.Create(string.Empty, "naam", 0); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void ArgumentOutOfRangeExceptionWhenCreatedWithEmptyStringAsNaamArgumentTest() { this.builder.Create("id", string.Empty, 0); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void ArgumentOutOfRangeExceptionWhenCreatedWithNegativeNumberAsTotaalAantalObjectenArgumentTest() { this.builder.Create("id", "naam", -1); } [TestMethod] public void CreatedWithExpectedValuesForArgumentsTest() { const string Id = "id"; const string Naam = "naam"; const int AantalObjecten = int.MaxValue; var result = this.builder.Create(Id, Naam, AantalObjecten); Assert.AreEqual(Id, result.Id); Assert.AreEqual(Naam, result.Naam); Assert.AreEqual(AantalObjecten, result.TotaalAantalObjecten); } } }
using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Networking; public class WebCamTextureSender : NetworkBehaviour { public WebCamTexture webCamTexture; public Color32[] data; public Texture2D texture; // Use this for initialization void OnEnable () { if (hasAuthority == false) { return; } } // Update is called once per frame void Update () { if (hasAuthority == false) { return; } webCamTexture = new WebCamTexture(); webCamTexture.Play(); data = new Color32[webCamTexture.width * webCamTexture.height]; texture = new Texture2D(webCamTexture.width, webCamTexture.height); if (webCamTexture.isPlaying) { webCamTexture.GetPixels32(data); texture.SetPixels32(data); texture.Apply(); var bytes = texture.EncodeToJPG(); } } void SendTexture(byte [] bytes) { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Menu : MonoBehaviour { public GameObject mainMenu; public GameObject optionsMenu; public Slider[] volumen; void Start() { this.MainMenu(); volumen[0].value = AudioManager.instance.masterVolumen; volumen[1].value = AudioManager.instance.musicVolumen; volumen[2].value = AudioManager.instance.sfxVolumen; AudioManager.instance.PlayMusic(MusicLibrary.Scene.MENU); } public void Play() { Loading.LoadScene(Loading.Scenes.SELECTION); } public void Quit() { Application.Quit(); } public void OptionsMenu() { mainMenu.SetActive(false); optionsMenu.SetActive(true); } public void MainMenu() { mainMenu.SetActive(true); optionsMenu.SetActive(false); } public void GoToShop() { Loading.LoadScene(Loading.Scenes.SHOP); } public void setMasterVolumen(float value) { AudioManager.instance.SetVolumen(value, AudioManager.AudioChannel.Master); } public void setMusicVolumen(float value) { AudioManager.instance.SetVolumen(value, AudioManager.AudioChannel.Music); } public void setSfxVolumen(float value) { AudioManager.instance.SetVolumen(value, AudioManager.AudioChannel.Sfx); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JustRipeFarm { public class Order { private int id; private string description; private int product_id; private int quantity_box; private double weight; private int palletAllocation; private int customer_id; private DateTime order_date; private DateTime collection_date; private double price; private string status; private string remark; public int Id { get => id; set => id = value; } public string Description { get => description; set => description = value; } public int Product_id { get => product_id; set => product_id = value; } public int Quantity_box { get => quantity_box; set => quantity_box = value; } public double Weight { get => weight; set => weight = value; } public int PalletAllocation { get => palletAllocation; set => palletAllocation = value; } public int Customer_id { get => customer_id; set => customer_id = value; } public DateTime Order_date { get => order_date; set => order_date = value; } public DateTime Collection_date { get => collection_date; set => collection_date = value; } public double Price { get => price; set => price = value; } public string Status { get => status; set => status = value; } public string Remark { get => remark; set => remark = value; } } }
using System; using System.Collections.Generic; using System.Text; using MvvmCross.Navigation; using MvvmCross.ViewModels; using ColoringApp.Core.Models; using MvvmCross.Commands; using MvvmCross.Views; using System.Threading.Tasks; using System.Drawing; using ColoringApp.Core.Services; using System.IO; namespace ColoringApp.Core.ViewModels { public class CharacterListViewModel : MvxViewModel { private (byte[], string) _characterphoto; private CharactersService _charactersService; public (byte[], string) CharacterPhoto { get { _characteritems[0].CharacterName = _characterphoto.Item2; _charactersService.SavePhoto(_characterphoto.Item1, _characterphoto.Item2); return _characterphoto; } set { _characterphoto = value; _characteritems[0].CharacterName = _characterphoto.Item2; _charactersService.SavePhoto(_characterphoto.Item1, _characterphoto.Item2); } } private MvxObservableCollection<Character> _characteritems; public MvxObservableCollection<Character> CharacterItems { get { return _characteritems; } private set { /*_characteritems = value; RaisePropertyChanged(() => CharacterItems);*/ } } public void ShowCharacterCommand(Character item) { if (!item.CharacterEnabled) { return; } _navigationService.Navigate<CharacterViewModel>(); } private readonly IMvxNavigationService _navigationService; public CharacterListViewModel(IMvxNavigationService navigationService) { _navigationService = navigationService; _charactersService = new CharactersService(); _characteritems = new MvxObservableCollection<Character>(); LoadCharacters(); } public MvxNotifyTask LoadCharactersTask { get; private set; } private async void LoadCharacters() { var result = await _charactersService.GetCharactersAsync(); for (int i = 0; i < result.Count; i++) { _characteritems.Add(new Character {CharacterName = result[i].CharacterName, CharacterEnabled = result[i].CharacterEnabled, DrawName = result[i].DrawName}); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using GDS.Entity; using SqlSugar; using GDS.Comon; namespace GDS.Dal { public class ImplProjectType : ImplDaoBase<ProjectType>, IProjectTypeDao<ProjectType> { public List<ProjectType> GetProjectTypesByDepartId(int DepartId) { List<ProjectType> li = new List<ProjectType>(); try { using (var db = SugarDao.GetInstance()) { db.IsNoLock = true; li = db.Queryable<ProjectType>().Where(x => x.DepartId == DepartId).ToList(); } } catch (Exception ex) { Loger.LogErr(ex); return null; } return li; } public List<TempProjectType> GetTempProjectTypeList() { List<TempProjectType> li = new List<TempProjectType>(); try { using (var db = SugarDao.GetInstance()) { db.IsNoLock = true; li = db.SqlQuery<TempProjectType>(@" select a.id departid, a.name departname, b.id projectypeid, b.name projecttypename from department a inner join projecttype b on a.id = b.departid "); } } catch (Exception ex) { Loger.LogErr(ex); return null; } return li; } public List<ProjectType> GetDataByName(string Name) { try { using (var db = SugarDao.GetInstance()) { db.IsNoLock = true; var li = db.Queryable<ProjectType>().Where(x => x.Name == Name).ToList(); return li; } } catch (Exception ex) { return null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using my_new_app.Data; namespace my_new_app.Models { public class PieRepository : IPieRepository { private readonly ApplicationDbContext _appDbContext; public PieRepository(ApplicationDbContext appDbContext) { _appDbContext = appDbContext; } public IEnumerable<Pie> GetAllPies() { return _appDbContext.Pies; } public Pie GetPieById(int pieid) { return _appDbContext.Pies.FirstOrDefault(p => p.Id == pieid); } public Pie Add(Pie Pie) { _appDbContext.Pies.Add(Pie); _appDbContext.SaveChanges(); return Pie; } public bool Remove(int id) { Pie Pie = _appDbContext.Pies.Find(id); if (Pie == null) return false; _appDbContext.Pies.Remove(Pie); _appDbContext.SaveChanges(); return true; } public bool Update(Pie newPie) { Pie existPie =_appDbContext.Pies.Find(newPie.Id); if (newPie == null) return false; existPie.Name = newPie.Name; existPie.ShortDescription=newPie.ShortDescription; existPie.Price = newPie.Price; existPie.ImageUrl=newPie.ImageUrl; existPie.ImageThumbnailUrl = newPie.ImageUrl; _appDbContext.SaveChanges(); return true; } } }
using MarcusW.SharpUtils.Core.Cryptography; using MarcusW.SharpUtils.Core.Extensions; using Xunit; namespace MarcusW.SharpUtils.Core.Tests { public class RSAKeyLoaderTests { private const string TestCertFileName = "Files/test-cert.pfx"; private const string TestKeyFileName = "Files/test-key.pfx"; private const string TestKeyPassword = "123456"; [Fact] public void LoadsPublicKeyFromCertFile() { var rsa = RSAKeyLoader.LoadFromCertificate(TestCertFileName); Assert.True(rsa.GetHasPublicKey()); Assert.False(rsa.GetHasPrivateKey()); } [Fact] public void LoadsPrivateKeyFromKeyFile() { var rsa = RSAKeyLoader.LoadFromCertificate(TestKeyFileName, TestKeyPassword); Assert.True(rsa.GetHasPublicKey()); Assert.True(rsa.GetHasPrivateKey()); } } }
using StreetFighter.dominio; using StreetFighter.Dominio; using System; using System.Activities.Statements; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Transactions; namespace StreetFighter.Repositorio { public class PersonagemRepositorio : IPersonagemRepositorio { const string CaminhoArquivo = @"C:\Users\Arthur\Documents\Projeto Crescer\GitHub\crescer-2016-2\src\modulo-05-C#-prt1\listaPersonagens.csv"; public List<Personagem> ListaPersonagens { get; private set; } public PersonagemRepositorio() { this.ListaPersonagens = new List<Personagem>(); this.ListaPersonagens = ListarPersonagens(null); } public Personagem GetPersonagemById(int id) { string connectionString = ConfigurationManager.ConnectionStrings["StreetFighter"] .ConnectionString; Personagem result = new Personagem(); using (var connection = new SqlConnection(connectionString)) { connection.Open(); string sql = $"SELECT * FROM Personagem WHERE Id =" + id; var command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { Personagem personagem = ConverterReaderToPersonagem(reader); result = personagem; } connection.Close(); } return result; } public List<Personagem> GetPersonagemByNome(string nome) { string connectionString = ConfigurationManager.ConnectionStrings["StreetFighter"] .ConnectionString; List<Personagem> result = new List<Personagem>(); using (var connection = new SqlConnection(connectionString)) { connection.Open(); string sql = ""; if (nome == null) sql = "SELECT * FROM Personagem"; else sql = $"SELECT * FROM Personagem WHERE Nome LIKE '%" + nome + "%'"; var command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Personagem personagem = ConverterReaderToPersonagem(reader); result.Add(personagem); } connection.Close(); } return result; } private Personagem ConverterReaderToPersonagem(SqlDataReader reader) { int idRow = Convert.ToInt32(reader["Id"]); string nomeRow = reader["Nome"].ToString(); DateTime dataNascimentoRow = Convert.ToDateTime(reader["DataNascimento"]); int alturaRow = Convert.ToInt32(reader["Altura"]); decimal pesoRow = Convert.ToDecimal(reader["Peso"]); string origenRow = reader["Origen"].ToString(); string golpesEspeciaisRow = reader["GolpesEspeciais"].ToString(); bool personagemOcultoRow = Convert.ToBoolean(reader["PersonagemOculto"]); string imagemRow = reader["Imagem"].ToString(); var personagem = new Personagem( id: idRow, nome: nomeRow, dataNascimento: dataNascimentoRow, altura: alturaRow, peso: pesoRow, origem: origenRow, golpesEspeciais: golpesEspeciaisRow, personagemOculto: personagemOcultoRow, imagem: imagemRow ); return personagem; } public List<Personagem> ListarPersonagens(string filtroNome) { return GetPersonagemByNome(filtroNome); } public void IncluirPersonagem(Personagem personagem) { string connectionString = ConfigurationManager.ConnectionStrings["StreetFighter"] .ConnectionString; Personagem result = new Personagem(); if (RegraDeNegocio(personagem)) { using (var transaction = new System.Transactions.TransactionScope(TransactionScopeOption.Required)) using (var connection = new SqlConnection(connectionString)) { try { connection.Open(); string sql = ""; var parameters = new List<SqlParameter>(); if (personagem.Id > 0) { sql = $"UPDATE Personagem SET Nome=@param_nome, DataNascimento=@param_data, Altura=@param_altura, Peso=@param_peso, Origen=@param_origem, GolpesEspeciais=@param_golpes, PesonagemOculto=@param_personagemOculto, Imagem=@param_imagem WHERE Id = @param_id"; parameters.Add(new SqlParameter("param_id", personagem.Id)); parameters.Add(new SqlParameter("param_nome", personagem.Nome)); parameters.Add(new SqlParameter("param_data", personagem.DataNascimento)); parameters.Add(new SqlParameter("param_altura", personagem.Altura)); parameters.Add(new SqlParameter("param_peso", personagem.Peso)); parameters.Add(new SqlParameter("param_origem", personagem.Origem)); parameters.Add(new SqlParameter("param_golpes", personagem.GolpesEspeciais)); parameters.Add(new SqlParameter("param_personagemOculto", personagem.PersonagemOculto)); parameters.Add(new SqlParameter("param_imagem", personagem.Imagem)); // Aplicar o resto dos parâmetros } else { sql = $"INSERT INTO Personagem(Nome, DataNascimento, Altura, Peso, Origen, GolpesEspeciais, PersonagemOculto, Imagem) VALUES(@param_nome, @param_data, @param_altura, @param_peso, @param_origem, @param_golpes, @param_personagemOculto, @param_imagem); "; parameters.Add(new SqlParameter("param_nome", personagem.Nome)); parameters.Add(new SqlParameter("param_data", personagem.DataNascimento)); parameters.Add(new SqlParameter("param_altura", personagem.Altura)); parameters.Add(new SqlParameter("param_peso", personagem.Peso)); parameters.Add(new SqlParameter("param_origem", personagem.Origem)); parameters.Add(new SqlParameter("param_golpes", personagem.GolpesEspeciais)); parameters.Add(new SqlParameter("param_personagemOculto", personagem.PersonagemOculto)); parameters.Add(new SqlParameter("param_imagem", personagem.Imagem)); } var command = new SqlCommand(sql, connection); foreach (SqlParameter param in parameters) { command.Parameters.Add(param); } command.ExecuteNonQuery(); transaction.Complete(); } catch { Console.Write("Deu ruim. Erro ao cadastrar!"); // Melhorar isso } finally { connection.Close(); } } } } public void EditarPersonagem(Personagem personagem) { var propriedades = GerarPersonagemEmString(personagem); for (int i = 0; i < ListaPersonagens.Count; i++) { if (ListaPersonagens[i].Nome.Equals(personagem.Nome)) { ExcluiDaListaDePersonagem(ListaPersonagens[i]); ListaPersonagens.Insert(i, personagem); IncluirPersonagem(personagem); } } } public void ExcluirPersonagem(Personagem personagem) { List<string> listaString = new List<string>(); ExcluiDaListaDePersonagem(personagem); foreach (Personagem personagemDaVez in ListaPersonagens) { listaString.Add(GerarPersonagemEmString(personagemDaVez)); } File.WriteAllLines(CaminhoArquivo, listaString); } public Personagem BuscarPersonagemPorNome(string nome) { List<Personagem> listaDePersonagens = ListarPersonagens(null); foreach (Personagem personagem in listaDePersonagens) { if (personagem.Nome.Equals(nome)) { return personagem; } } return null; } public void ExcluiDaListaDePersonagem(Personagem personagem) { for (int i = 0; i < ListaPersonagens.Count; i++) { if (personagem.Nome.Equals(ListaPersonagens[i].Nome)) ListaPersonagens.RemoveAt(i); } } public string GerarPersonagemEmString(Personagem personagem) { return $"{personagem.Id};{personagem.Nome};{personagem.DataNascimento.ToString("yyyy/MM/dd")};{personagem.Altura};{personagem.Peso}; {personagem.Origem};{ personagem.GolpesEspeciais};{ personagem.Imagem};{personagem.PersonagemOculto};"; } public bool RegraDeNegocio(Personagem personagem) { if (personagem.Nome.ToUpper().Equals("NUNES") || personagem.Origem.Equals("MP")) return false; return true; } } }
using System; using System.Linq; using System.Reflection; using Harmony; namespace FunnySnek.AntiCheat.Server.Framework { //Remember Prefix/Postfix should be public and static! Do not use lambdas internal abstract class Patch { /********* ** Properties *********/ protected abstract PatchDescriptor GetPatchDescriptor(); /********* ** Public methods *********/ public static void PatchAll(string id) { HarmonyInstance harmonyInstance = HarmonyInstance.Create(id); var types = ( from type in Assembly.GetExecutingAssembly().GetTypes() where type.IsClass && type.BaseType == typeof(Patch) select type ); foreach (Type type in types) ((Patch)Activator.CreateInstance(type)).ApplyPatch(harmonyInstance); } /********* ** Private methods *********/ private void ApplyPatch(HarmonyInstance harmonyInstance) { var patchDescriptor = this.GetPatchDescriptor(); MethodBase targetMethod = string.IsNullOrEmpty(patchDescriptor.TargetMethodName) ? (MethodBase)patchDescriptor.TargetType.GetConstructor(patchDescriptor.TargetMethodArguments ?? new Type[0]) : (patchDescriptor.TargetMethodArguments != null ? patchDescriptor.TargetType.GetMethod(patchDescriptor.TargetMethodName, patchDescriptor.TargetMethodArguments) : patchDescriptor.TargetType.GetMethod(patchDescriptor.TargetMethodName, (BindingFlags)62) ); harmonyInstance.Patch(targetMethod, new HarmonyMethod(this.GetType().GetMethod("Prefix")), new HarmonyMethod(this.GetType().GetMethod("Postfix"))); } } }
using System; using System.Data.Common; using System.Data.SqlClient; using System.Threading.Tasks; namespace SQLServerBackupTool.Lib { public class SqlServerBackupProvider : ISqlBackupProvider { public const string BackupCommandTemplate = @" BACKUP DATABASE [{0}] TO DISK = N'{1}' WITH NOFORMAT, NOINIT, NAME = N'{0} - {2}', SKIP, NOREWIND, NOUNLOAD, STATS = 10; "; private readonly DbConnection _co; private bool _disposed; public SqlServerBackupProvider(string connectionString) { _co = new SqlConnection(connectionString); } /// <summary> /// Indicates if the underlying SQL Connection is opened /// </summary> public bool IsConnectionOpened { get; protected set; } /// <summary> /// Opens the underlying SQL Connection /// </summary> public void Open() { if (_disposed) { throw new ObjectDisposedException( "Unable to open a data connection from a disposed BackupUtil", innerException: null ); } _co.Open(); IsConnectionOpened = true; } /// <summary> /// Async proxy to <see cref="Open"/> /// </summary> public Task OpenAsync() { return Task.Factory.StartNew(Open); } /// <summary> /// Closes the underlaying SQL Connection /// </summary> public void Close() { if (!IsConnectionOpened) { return; } _co.Close(); } /// <summary> /// Instructs SQL Server to make a backup of the given database, path with specified timestamp /// </summary> /// <param name="databaseName">Name of the database</param> /// <param name="backupPath">Full destination file name of the database backup</param> /// <param name="ts">Timestamp, used for indicative purposes inside the resulting backup metadata</param> /// <returns>Return value of <see cref="SqlCommand.ExecuteNonQuery"/></returns> public int BackupDatabase(string databaseName, string backupPath, DateTime ts) { if (!IsConnectionOpened) { Open(); } var q = _co.CreateCommand(); q.CommandTimeout = 0; // Backups can take a long time for big databases q.CommandText = string.Format( BackupCommandTemplate, databaseName, backupPath, string.Format("{0} {1}", ts.ToShortDateString(), ts.ToShortTimeString() )); return q.ExecuteNonQuery(); } /// <summary> /// Async proxy to <see cref="BackupDatabase"/> /// </summary> public Task<int> BackupDatabaseAsync(string databaseName, string backupPath, DateTime ts) { return Task.Factory.StartNew(() => BackupDatabase(databaseName, backupPath, ts)); } /// <summary> /// Exécute les tâches définies par l'application associées à la libération ou à la redéfinition des ressources non managées. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { Close(); _co.Dispose(); _disposed = true; } } }
using gView.Framework.Geometry; using System; using System.Collections; using System.Text; using System.Xml; namespace gView.Framework.XML { internal enum featureQueryMethode { Geometry, Query, ID, None, Buffer } /// <summary> /// Stellt die Ergebnisse einer Feature-Abfrage dar. Die Klasse ServiceManager stellt /// mehrere Instanzen die Klasse in einem Array bereit, wobei eine Instanz /// die Ergebnisse einer Selektion, eine zweite Instanz die Ergebnisse aus Identifyabfragen /// enthalten kann. /// </summary> internal class FeatureQueryResponse { /// <summary> /// Die Geometrie der Feature-Abfrage /// </summary> public selectionGeometry selGeometry; protected featureQueryMethode m_bufferMethode; protected featureQueryMethode m_highlightMethod, m_selectionMethode, m_queryMethode; protected bool m_selectFeatures; protected string m_queryResponseAXL = ""; protected double m_bufferDist; protected int m_highlightID; protected int m_bufferID; protected bool m_dispBuffer; protected string m_selQuery = "", m_appendWhereFilter = ""; protected ArrayList m_sortedFeatures; protected string m_bufferIDs = "", m_queryName; protected int m_beginrecord = 1; protected int m_sourceID; // für Bufferung (was waren die ursprünglichen pufferFeatures protected int m_maxQueryResults = 2; protected int m_maxQueryResultsFactor = 1; protected int m_featureCount, m_lastQueryMaximum; protected bool m_hasmore = false; protected ArrayList m_joinIDs = new ArrayList(), m_domainsReplaced = new ArrayList(); protected bool m_queryGeometry = false; protected AXLLayer m_layer; public FeatureQueryResponse() { highlightMethode = selectionMethode = featureQueryMethode.None; bufferMethode = featureQueryMethode.None; selectFeatures = false; selGeometry = new selectionGeometry(); selGeometry.createNew(); bufferDist = 30.0; highlightID = bufferID = -1; dispBuffer = false; m_sortedFeatures = new ArrayList(); queryMethode = featureQueryMethode.None; } public int maxQueryResults { get { return m_maxQueryResults; } set { m_maxQueryResults = m_lastQueryMaximum = value; } } public int maxQueryResultsFactor { get { return m_maxQueryResultsFactor; } set { m_maxQueryResultsFactor = value; } } public string queryName { get { return m_queryName; } set { m_queryName = value; } } public string bufferIDs { get { return m_bufferIDs; } set { m_bufferIDs = value; } } public ArrayList sortedFeatures { get { return m_sortedFeatures; } } public AXLLayer layer { get { return m_layer; } set { m_layer = value; } } public int sourceID { get { return m_sourceID; } set { m_sourceID = value; } } public bool queryGeometry { get { return m_queryGeometry; } set { m_queryGeometry = value; } } public string appendWhereFilter { get { return m_appendWhereFilter; } set { m_appendWhereFilter = value; } } public int beginrecord { get { return m_beginrecord; } set { m_beginrecord = value; if (m_beginrecord < 1) { m_beginrecord = 1; } } } public featureQueryMethode highlightMethode { get { return m_highlightMethod; } set { m_highlightMethod = value; } } public featureQueryMethode selectionMethode { get { return m_selectionMethode; } set { m_selectionMethode = value; } } public featureQueryMethode queryMethode { get { return m_queryMethode; } set { m_queryMethode = value; beginrecord = 1; m_lastQueryMaximum = maxQueryResults; } } public featureQueryMethode bufferMethode { get { return m_bufferMethode; } set { m_bufferMethode = value; } } public bool selectFeatures { get { return m_selectFeatures; } set { m_selectFeatures = value; } } public string queryResponseAXL { get { return m_queryResponseAXL; } set { m_featureCount = 0; try { XmlDocument doc = new XmlDocument(); doc.LoadXml(value); XmlNodeList node = doc.GetElementsByTagName("FEATURECOUNT"); if (node.Count > 0) { m_featureCount = Convert.ToInt32(node[0].Attributes["count"].Value); m_hasmore = Convert.ToBoolean(node[0].Attributes["hasmore"].Value); } } catch { } finally { m_queryResponseAXL = value; } m_joinIDs = new ArrayList(); m_domainsReplaced = new ArrayList(); //Join(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source =C:\ARCIMS\database\fuerstenfeld\rminfoPASS.mdb; Jet OLEDB:Database Password=PASS", // @"oledb", // "SELECT RMD_GDB_Eigentuemer.Zaehler, RMD_GDB_Eigentuemer.Nenner, RMD_GDB_Eigentuemer.Vorname, RMD_GDB_Eigentuemer.Nachname FROM RMD_GDB_Grundstuecke INNER JOIN (RMD_GDB_Eigentuemer INNER JOIN RMD_GDB_Einlagezahlen ON RMD_GDB_Eigentuemer.ID_Einlagezahl = RMD_GDB_Einlagezahlen.ID_Einlagezahl) ON RMD_GDB_Grundstuecke.ID_Einlagezahl = RMD_GDB_Einlagezahlen.ID_Einlagezahl WHERE (((RMD_GDB_Grundstuecke.KG)=\"[KG]\") AND ((RMD_GDB_Grundstuecke.BauFlPkt)=\" \") AND ((RMD_GDB_Grundstuecke.StammNr)=[S]) AND ((RMD_GDB_Grundstuecke.UnterteilungsNr)=[u]));"); } } public double bufferDist { get { return m_bufferDist; } set { m_bufferDist = value; } } public int highlightID { get { return m_highlightID; } set { m_highlightID = value; } } public int bufferID { get { return m_bufferID; } set { m_bufferID = value; } } public bool dispBuffer { get { return m_dispBuffer; } set { m_dispBuffer = value; } } public string selQuery { get { return m_selQuery; } set { m_selQuery = value; } } public void appendFeatures(string newFeatures) { if (queryResponseAXL == null || queryResponseAXL == "") { queryResponseAXL = newFeatures; return; } try { XmlDocument oldxml = new XmlDocument(), newxml = new XmlDocument(); oldxml.LoadXml(queryResponseAXL); newxml.LoadXml(newFeatures); XmlNodeList newfeat = newxml.SelectNodes("//FEATURES"); XmlNodeList featList = oldxml.SelectNodes("//FEATURES"); // Features anhängen //foreach(XmlNode feat in newfeat) // featList[0].AppendChild(feat); featList[0].InnerXml += newfeat[0].InnerXml; //FeatureCount anpassen... newfeat = oldxml.SelectNodes("//FEATURE"); XmlNodeList node1 = oldxml.GetElementsByTagName("FEATURECOUNT"); node1[0].Attributes["count"].Value = newfeat.Count.ToString(); XmlNodeList node2 = newxml.GetElementsByTagName("FEATURECOUNT"); node1[0].Attributes["hasmore"].Value = node2[0].Attributes["hasmore"].Value; queryResponseAXL = oldxml.OuterXml; } catch { } } public int featureCount { get { return m_featureCount; } } public bool hasmore { get { return m_hasmore; } } public int lastQueryMaximum { get { return m_lastQueryMaximum; } set { m_lastQueryMaximum = value; } } protected string getGeometryFromAXL(XmlNode feature) { foreach (XmlNode child in feature.ChildNodes) { if (child.Name == "POLYGON" || child.Name == "POLYLINE" || child.Name == "POINT" || child.Name == "MULTIPOINT") { return child.OuterXml; } } return ""; } public string getAttributeString(int index, string attributes, int colwidth) { try { XmlDocument doc = new XmlDocument(); doc.LoadXml(queryResponseAXL); XmlNodeList features = doc.SelectNodes("//FEATURE"); if (index < 0 || index >= features.Count) { return ""; } XmlDocument featDoc = new XmlDocument(); featDoc.LoadXml(features[index].OuterXml); XmlNodeList fields = featDoc.SelectNodes("//FIELD"); string[] attr = attributes.Split(';'); StringBuilder sb = new StringBuilder(); foreach (string a in attr) { foreach (XmlNode field in fields) { string name = field.Attributes["name"].Value; if (a == name) { sb.Append(field.Attributes["value"].Value.PadLeft(colwidth, ' ')); } } } return sb.ToString(); } catch { return ""; } } public string getTomTomAttributeString(int index, string attributes) { return getTomTomAttributeString(index, attributes, -1); } public string getTomTomAttributeString(int index, string attributes, int max) { try { XmlDocument doc = new XmlDocument(); doc.LoadXml(queryResponseAXL); XmlNodeList features = doc.SelectNodes("//FEATURE"); if (index < 0 || index >= features.Count) { return "\"\""; } XmlDocument featDoc = new XmlDocument(); featDoc.LoadXml(features[index].OuterXml); XmlNodeList fields = featDoc.SelectNodes("//FIELD"); string[] attr = attributes.Split(';'); StringBuilder sb = new StringBuilder(); int counter = 0; foreach (string a in attr) { if (max > 0 && max >= counter) { break; } foreach (XmlNode field in fields) { string name = field.Attributes["name"].Value; if (a == name) { if (sb.Length != 0) { sb.Append(" "); } sb.Append(field.Attributes["value"].Value.Replace(" ", "-")); } } counter++; } return "\"" + sb.ToString() + "\""; } catch { return "\"\""; } } public string getGeometryFromAXL() { return getGeometryFromAXL(-1); } public string getGeometryFromAXL(int index) { try { XmlDocument doc = new XmlDocument(); doc.LoadXml(queryResponseAXL); XmlNodeList features = doc.SelectNodes("//FEATURE"); if (index >= 0 && index < features.Count) { return "<GEOMETRY>" + getGeometryFromAXL(features[index]) + "</GEOMETRY>"; } StringBuilder sb = new StringBuilder(); foreach (XmlNode feature in features) { sb.Append("<GEOMETRY>" + getGeometryFromAXL(feature) + "</GEOMETRY>"); } return sb.ToString(); } catch { return ""; } } public string getAttributeList(string attname) { if (queryResponseAXL == null) { return ""; } if (queryResponseAXL == "") { return ""; } StringBuilder sb = new StringBuilder(); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(queryResponseAXL); XmlNodeList features = doc.SelectNodes("//FEATURE"); foreach (XmlNode feature in features) { XmlNodeList fields = feature.SelectNodes("FIELDS/FIELD"); foreach (XmlNode field in fields) { string name = field.Attributes["name"].Value; if (name == attname) { if (sb.Length == 0) { sb.Append(field.Attributes["value"].Value); } else { sb.Append(";" + field.Attributes["value"].Value); } } } } } catch { return ""; } return sb.ToString(); } } /* public enum geometryType { Envelope,Point,Line,Polygon,userdef } */ internal class selectionGeometry { protected GeometryType m_geomType; protected ArrayList m_points; protected string m_axl; double m_bufferDist; public selectionGeometry() { m_points = new ArrayList(); m_bufferDist = 30.0; } public void createNew() { m_points.Clear(); } public GeometryType GeometryType { get { return m_geomType; } set { m_geomType = value; } } public double bufferDist { get { return m_bufferDist; } set { m_bufferDist = value; } } public void addPoint(xyPoint point) { m_points.Add(point); } public void removeLastPoint() { if (m_points.Count == 0) { return; } m_points.RemoveAt(m_points.Count - 1); } public void addGeomFromCoords(string points) { string[] coords = points.Split(';'); for (int i = 0; i < coords.Length; i += 2) { try { xyPoint p = new xyPoint(Convert.ToDouble(coords[i].Replace(".", ",")), Convert.ToDouble(coords[i + 1].Replace(".", ","))); addPoint(p); } catch { } } } public bool isValid { get { if (GeometryType == GeometryType.Point && m_points.Count > 0) { return true; } if (GeometryType == GeometryType.Polyline && m_points.Count > 1) { return true; } if (GeometryType == GeometryType.Polygon && m_points.Count > 2) { return true; } if (GeometryType == GeometryType.Envelope && m_points.Count == 2) { return true; } if (GeometryType == GeometryType.Unknown) { return true; } return false; } } public string userdef_axl { set { m_axl = value; GeometryType = GeometryType.Unknown; } } private void createBufferAXL(ref XmlTextWriter xml) { xml.WriteStartElement("BUFFER"); xml.WriteAttributeString("distance", m_bufferDist.ToString()); xml.WriteAttributeString("bufferunits", "meters"); xml.WriteEndElement(); // BUFFER } public void createAXL(ref XmlTextWriter xml) { if (!isValid) { return; } switch (GeometryType) { case GeometryType.Envelope: xyPoint p1 = (xyPoint)m_points[0], p2 = (xyPoint)m_points[1]; double minx = Math.Min(p1.x, p2.x), miny = Math.Min(p1.y, p2.y), maxx = Math.Max(p1.x, p2.x), maxy = Math.Max(p1.y, p2.y); xml.WriteStartElement("ENVELOPE"); xml.WriteAttributeString("minx", minx.ToString()); xml.WriteAttributeString("miny", miny.ToString()); xml.WriteAttributeString("maxx", maxx.ToString()); xml.WriteAttributeString("maxy", maxy.ToString()); xml.WriteEndElement(); // Enveolpe break; case GeometryType.Point: if (m_bufferDist > 1e-7) { createBufferAXL(ref xml); } xml.WriteStartElement("MULTIPOINT"); foreach (xyPoint p in m_points) { axlShapes.Point(ref xml, p); } xml.WriteEndElement(); // MULTIPOINT break; case GeometryType.Polyline: if (m_bufferDist > 1e-7) { createBufferAXL(ref xml); } xml.WriteStartElement("POLYLINE"); xml.WriteStartElement("PATH"); foreach (xyPoint p in m_points) { axlShapes.Point(ref xml, p); } xml.WriteEndElement(); // PATH xml.WriteEndElement(); // POLYLINE break; case GeometryType.Polygon: if (m_bufferDist > 1e-7) { createBufferAXL(ref xml); } xml.WriteStartElement("POLYGON"); xml.WriteStartElement("RING"); foreach (xyPoint p in m_points) { axlShapes.Point(ref xml, p); } xml.WriteEndElement(); // RING xml.WriteEndElement(); // POLYGON break; case GeometryType.Unknown: if (m_bufferDist > 1e-7) { createBufferAXL(ref xml); } xml.WriteRaw(m_axl); break; } } public void createBufferACETATE(ref XmlTextWriter xml) { if (m_bufferDist < 1e-7) { return; } if (m_points.Count == 0) { return; } if (GeometryType == GeometryType.Envelope) { return; } xml.WriteStartElement("LAYER"); xml.WriteAttributeString("type", "acetate"); xml.WriteAttributeString("id", "selectionGeometryBuffer"); xml.WriteAttributeString("name", "selectionGeometryBuffer"); axlShapes.openObject(ref xml); axlShapes.PolygonSymbol(ref xml, "200,200,200", "0,0,0", 1.0, 0.5); //xml.WriteStartElement("SPATIALQUERY"); xml.WriteStartElement("BUFFER"); xml.WriteStartElement("distance", m_bufferDist.ToString()); xml.WriteEndElement(); // BUFFER; //xml.WriteStartElement("SPATIALFILTER"); xml.WriteStartElement("MULTIPOINT"); foreach (xyPoint p in m_points) { axlShapes.Point(ref xml, p); } xml.WriteEndElement(); // MULTIPOINT axlShapes.closeObject(ref xml); //xml.WriteEndElement(); // SPATIALFILTER //xml.WriteEndElement(); // SPATIALQUERY; xml.WriteEndElement(); // LAYER } public void createACETATE(ref XmlTextWriter xml) { if (m_points.Count == 0) { return; } if (GeometryType == GeometryType.Envelope) { return; } xml.WriteStartElement("LAYER"); xml.WriteAttributeString("type", "acetate"); xml.WriteAttributeString("id", "selectionGeometry"); xml.WriteAttributeString("name", "selectionGeometry"); // Punkte Zeichnen axlShapes.openObject(ref xml); axlShapes.PointSymbol(ref xml, 5.0, 0.6, "255,0,0"); xml.WriteStartElement("MULTIPOINT"); foreach (xyPoint p in m_points) { axlShapes.Point(ref xml, p); } xml.WriteEndElement(); // MULTIPOINT axlShapes.closeObject(ref xml); if ((GeometryType == GeometryType.Polyline && isValid) || (GeometryType == GeometryType.Polygon && m_points.Count == 2)) { axlShapes.openObject(ref xml); axlShapes.LineSymbol(ref xml, 3.0, "255,0,0"); xml.WriteStartElement("POLYLINE"); xml.WriteStartElement("PATH"); foreach (xyPoint p in m_points) { axlShapes.Point(ref xml, p); } xml.WriteEndElement(); // PATH xml.WriteEndElement(); // POLYLINE axlShapes.closeObject(ref xml); } if (GeometryType == GeometryType.Polygon && isValid) { axlShapes.openObject(ref xml); axlShapes.PolygonSymbol(ref xml, "255,255,0", "250,0,0", 1.0, 0.4); xml.WriteStartElement("POLYGON"); xml.WriteStartElement("RING"); foreach (xyPoint p in m_points) { axlShapes.Point(ref xml, p); } xml.WriteEndElement(); // RING xml.WriteEndElement(); // POLYGON axlShapes.closeObject(ref xml); } xml.WriteEndElement(); // LAYER } public xyPoint this[int index] { get { if (index < 0 || index >= m_points.Count) { return null; } return (xyPoint)m_points[index]; } } } internal class xyPoint { public xyPoint(double x_, double y_) { x = x_; y = y_; } public xyPoint(xyPoint p) { x = p.x; y = p.y; } public bool ident(xyPoint p) { if (p == null) { return false; } if (Math.Abs(p.x - x) < 1e-7 && Math.Abs(p.y - y) < 1e-7) { return true; } return false; } public double x = 0.0, y = 0.0, z = 0.0; public void Round(int digits) { x = Math.Round(x, digits); y = Math.Round(y, digits); } } }
using CryptoReaper.Simulation.CryptFeatures; using Microsoft.Xna.Framework; namespace CryptoReaper.Simulation { class Gameplay { protected Gameplay() { Crypt = new Crypt(); // Player = new Player(Crypt, new Crypt.Coords(9, 9)); for (int row = 0; row < 20; row++) for (int col = 0; col < 20; col++) { Crypt[row, col] = row == 3 && col == 3 ? new SoulSpire() : row == 3 && col == 16 ? new HellFireSpire() : row == 0 || row == 19 || col == 0 || col == 19 ? new Wall() as Crypt.Feature : new OpenSpace(); //if (row == 9 && col == 9 && Crypt[row, col] is GameTokenContainer gs) //{ // gs.SetGameToken(Player); //} } } public Crypt Crypt { get; } // public Player Player { get; } public void Update(GameTime gameTime, InputState input) { // Player.Update(gameTime, input); } public static Gameplay Create() { return new Gameplay(); } } }
using Microsoft.EntityFrameworkCore; using Abp.Zero.EntityFrameworkCore; using Dg.fifth.Authorization.Roles; using Dg.fifth.Authorization.Users; using Dg.fifth.MultiTenancy; namespace Dg.fifth.EntityFrameworkCore { public class fifthDbContext : AbpZeroDbContext<Tenant, Role, User, fifthDbContext> { /* Define a DbSet for each entity of the application */ public fifthDbContext(DbContextOptions<fifthDbContext> options) : base(options) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class ExplorationUIManager : SingletonBehaviour<ExplorationUIManager> { [System.Serializable] private struct ContentSlot { public Text eventText; public Image eventImage; } public GameObject panelExploration; public GameObject panelCollapseWarning; private List<ContentSlot> contentsEvent = new List<ContentSlot>(); [SerializeField] private Button[] buttonOptions = new Button[4]; private Button[] buttonWarning = new Button[2]; private Button ButtonContinue { get { return buttonWarning[0]; } } private Button ButtonCancel { get { return buttonWarning[1]; } } private void Start() { for (int i = 0; i < 5; i++) { ContentSlot contentSlot; contentSlot.eventText = panelExploration.transform.GetChild(0).GetChild(i).GetComponent<Text>(); contentSlot.eventImage = panelExploration.transform.GetChild(0).GetChild(5 + i).GetComponent<Image>(); contentsEvent.Add(contentSlot); } buttonWarning[0] = panelCollapseWarning.transform.GetChild(0).GetComponent<Button>(); buttonWarning[1] = panelCollapseWarning.transform.GetChild(1).GetComponent<Button>(); } protected override void Awake() { base.Awake(); } // for prototype public Image panelError; public void ButonComeBackHomeClicked() { panelError.gameObject.SetActive(false); panelExploration.SetActive(false); HomeUIManager.Inst.panelHome.SetActive(true); GameManager.Inst.ReturnHome(); } public void NoticeUnderDevelopment() { panelError.gameObject.SetActive(true); } #region ExplorationPanel methods #region Notice Event Methods /// <summary> /// UI에 @event에 관련한 텍스트, 이미지를 출력한다. /// </summary> public void NoticeEvent(ExplorationEvent @event) { Debug.Log("발생한 이벤트 : " + @event.titleText); NoticeEventText(@event.titleText); if(@event.phase == ExplorationEvent.EventPhase.SearchingItem) { ItemDiscoveryEvent itemDiscoveryEvent = (ItemDiscoveryEvent)@event; if(itemDiscoveryEvent.foundItem != null) NoticeEventItemImage(itemDiscoveryEvent.foundItem.itemImage); } NoticeEventText(@event.content); if (@event.name == "최초 탐사 시작" || @event.id == 100000) { NoticeEventText(" "); NoticeEventText(" "); NoticeEventText(" "); NoticeEventText(" "); } NoticeOptions(@event); } /// <summary> /// eventText를 UI의 마지막 줄에 출력한다. /// </summary> private void NoticeEventText(string eventText) { if(eventText != "") { ShiftEventContents(); if (contentsEvent[contentsEvent.Count - 1].eventText != null) { contentsEvent[contentsEvent.Count - 1].eventText.text = eventText; } else { Debug.LogError("eventContents[" + (contentsEvent.Count - 1) + "].eventText is null"); } } } /// <summary> /// 아이템 발견 이벤트의 발견한 아이템 이미지를 마지막 줄에 출력한다. /// </summary> /// <param name="itemImage"></param> private void NoticeEventItemImage(Sprite itemImage) { ShiftEventContents(); if(contentsEvent[contentsEvent.Count - 1].eventImage != null) { contentsEvent[contentsEvent.Count - 1].eventImage.gameObject.SetActive(true); contentsEvent[contentsEvent.Count - 1].eventImage.sprite = itemImage; } else { Debug.LogError("eventContents[" + (contentsEvent.Count - 1) + "].eventImage is null"); } } /// <summary> /// event의 optionTexts를 option 버튼에 표시한다. /// </summary> /// <param name="optionTexts"></param> private void NoticeOptions(ExplorationEvent @event) { List<string> optionTexts = @event.optionTexts; for(int i=0;i<optionTexts.Count;i++) { buttonOptions[i].interactable = @event.GetOptionEnable(i); buttonOptions[i].transform.GetChild(0).GetComponent<Text>().text = optionTexts[i]; } for(int i=optionTexts.Count;i<4;i++) { buttonOptions[i].interactable = false; buttonOptions[i].transform.GetChild(0).GetComponent<Text>().text = null; } } /// <summary> /// UI에 표시된 이벤트 텍스트와 이미지를 한 칸 위로 올린다. /// </summary> /// for debugging public을 private으로 변경 public void ShiftEventContents() { for(int i=0; i<contentsEvent.Count - 1;i++) { contentsEvent[i].eventText.text = contentsEvent[i + 1].eventText.text; if(contentsEvent[i + 1].eventImage.IsActive()) { contentsEvent[i].eventImage.gameObject.SetActive(true); contentsEvent[i].eventImage.sprite = contentsEvent[i + 1].eventImage.sprite; contentsEvent[i + 1].eventImage.gameObject.SetActive(false); } else { contentsEvent[i].eventImage.gameObject.SetActive(false); } } contentsEvent[contentsEvent.Count - 1].eventImage.sprite = null; contentsEvent[contentsEvent.Count - 1].eventImage.gameObject.SetActive(false); contentsEvent[contentsEvent.Count - 1].eventText.text = null; } #endregion #region Option Event Methods /// <summary> /// @event의 option을 선택했을 때 일어나는 일을 Button에 등록한다. /// </summary> /// <param name="event"></param> public void AddResultOptionsToButton(ExplorationEvent @event) { //AddResultTextsToButton(@event); AddResultEventsToButton(@event); } /// <summary> /// option을 선택했을 때 event의 결과를 Button에 등록한다. /// </summary> private void AddResultEventsToButton(ExplorationEvent @event) { Debug.Log(@event.name); if (@event.OptionNumber >= 0) { buttonOptions[0].onClick.AddListener(@event.Option0); if (@event.OptionNumber >= 1) { buttonOptions[1].onClick.AddListener(@event.Option1); if (@event.OptionNumber >= 2) { buttonOptions[2].onClick.AddListener(@event.Option2); if (@event.OptionNumber >= 3) { buttonOptions[3].onClick.AddListener(@event.Option3); } } } } } /// <summary> /// 선택지가 선택되었을 때 발생하는 결과 텍스트 출력 이벤트를 버튼에 등록한다. /// </summary> private void AddResultTextsToButton(ExplorationEvent @event) { //if (@event.phase != ExplorationEvent.EventPhase.FinishingExploration && !ExplorationManager.Inst.GetIsOverwork()) if (@event.phase != ExplorationEvent.EventPhase.FinishingExploration) { if (@event.OptionNumber >= 0) { buttonOptions[0].onClick.AddListener(() => NoticeEventText(@event.optionResultTexts[0])); if (@event.OptionNumber >= 1) { buttonOptions[1].onClick.AddListener(() => NoticeEventText(@event.optionResultTexts[1])); if (@event.OptionNumber >= 2) { buttonOptions[2].onClick.AddListener(() => NoticeEventText(@event.optionResultTexts[2])); if (@event.OptionNumber >= 3) { buttonOptions[3].onClick.AddListener(() => NoticeEventText(@event.optionResultTexts[3])); } } } } } } public void NoticeResultText(string resultText) { NoticeEventText(resultText); } /// <summary> /// option 버튼에 등록되어 있는 모든 이벤트를 제거한다. 버튼을 비활성화 한다. /// </summary> public void RemoveEventsFromButton() { for(int i=0;i<buttonOptions.Length;i++) { buttonOptions[i].interactable = false; buttonOptions[i].onClick.RemoveAllListeners(); } } #endregion public IEnumerator WaitForEncounter(float timeInterval) { NoticeEventText("탐사중."); yield return new WaitForSeconds(timeInterval / 3); contentsEvent[contentsEvent.Count - 1].eventText.text += "."; yield return new WaitForSeconds(timeInterval / 3); contentsEvent[contentsEvent.Count - 1].eventText.text += "."; } //public void ActiveCollapseWarningPanel(FinishExplorationEvent finishExplorationEvent, int option) //{ // panelCollapseWarning.SetActive(true); // ButtonCancel.onClick.AddListener(CloseCooapseWarningPanel); // if (option == 0) // { // ButtonContinue.onClick.AddListener(finishExplorationEvent.ExploreAnother); // ButtonContinue.onClick.AddListener(() => NoticeEventText(finishExplorationEvent.optionResultTexts[0])); // } // else if (option == 1) // { // ButtonContinue.onClick.AddListener(finishExplorationEvent.ExploreAgain); // ButtonContinue.onClick.AddListener(() => NoticeEventText(finishExplorationEvent.optionResultTexts[1])); // } // ButtonContinue.onClick.AddListener(CloseCooapseWarningPanel); //} public void CloseCooapseWarningPanel() { panelCollapseWarning.SetActive(false); ButtonContinue.onClick.RemoveAllListeners(); ButtonCancel.onClick.RemoveAllListeners(); } #endregion }
 using NotebookClient.Model; using NotebookClient.View; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; namespace NotebookClient.ViewModel { public class MainWindowViewModel:BaseCl { const string _baseAddress = "http://localhost:54619/"; RelayCommand addCommand; RelayCommand editCommand; RelayCommand deleteCommand; RelayCommand updateCommand; RelayCommand getContactsCommand; RelayCommand addContactCommand; RelayCommand editContactCommand; RelayCommand deleteContactCommand; ObservableCollection<Person> people; public ObservableCollection<Person> People { get { return people; } set { people = value; OnPropertyChanged("People"); } } ObservableCollection<Contact> contacts; public ObservableCollection<Contact> Contacts { get { return contacts; } set { contacts = value; OnPropertyChanged("Contacts"); } } Person selectedPerson; public Person SelectedPerson { get { return selectedPerson;} set { selectedPerson = value; OnPropertyChanged("SelectedPerson"); } } Contact selectedContact; public Contact SelectedContact { get { return selectedContact; } set { selectedContact = value; OnPropertyChanged("SelectedContact"); } } public MainWindowViewModel() { } #region Commands public void Update() { using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response; response = client.GetAsync("api/People").Result; if (response.IsSuccessStatusCode) { var res = response.Content.ReadAsAsync<ObservableCollection<Person>>().Result; People = res; } } } private void GetContacts() { if (SelectedPerson == null) { Contacts = null; return; } using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response; response = client.GetAsync("api/Contacts/" + SelectedPerson.Id).Result; if (response.IsSuccessStatusCode) { Contacts = response.Content.ReadAsAsync<ObservableCollection<Contact>>().Result; } } } public RelayCommand GetContactsCommand { get { return getContactsCommand ?? (getContactsCommand = new RelayCommand((o) => { GetContacts(); })); } } public RelayCommand UpdateCommand { get { return updateCommand ?? (updateCommand = new RelayCommand((o) => { Update(); GetContacts(); })); } } public RelayCommand AddCommand { get { return addCommand ?? (addCommand = new RelayCommand((o) => { PersonView personView = new PersonView(); PersonVeiwModel personViewModel = new PersonVeiwModel(new Person ()); personView.DataContext = personViewModel; if (personView.ShowDialog() == true) { Person person = personViewModel.Person; using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsJsonAsync("api/People", person).Result; } Update(); } })); } } public RelayCommand AddContactCommand { get { return addContactCommand ?? (addContactCommand = new RelayCommand((o) => { if (SelectedPerson == null) return; ContactView contactView = new ContactView(); ContactViewModel contactViewModel = new ContactViewModel(new Contact (), _baseAddress); contactView.DataContext = contactViewModel; if (contactView.ShowDialog() == true) { Contact contact = contactViewModel.Contact; contact.PersonId = SelectedPerson.Id; using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsJsonAsync("api/Contacts", contact).Result; } Update(); } })); } } public RelayCommand EditContactCommand { get { return editContactCommand ?? (editContactCommand = new RelayCommand((SelectedContact) => { if (SelectedContact == null) return; Contact contact = (Contact)SelectedContact; ContactView contactView = new ContactView(); ContactViewModel contactViewModel = new ContactViewModel( contact, _baseAddress); contactView.DataContext = contactViewModel; if (contactView.ShowDialog() == true) { contact = contactViewModel.Contact; contact.ContactTypeId = contact.ContactType.Id; using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PutAsJsonAsync("api/Contacts/" + contact.Id, contact).Result; } Update(); } })); } } public RelayCommand DeleteContactCommand { get { return deleteContactCommand ?? (deleteContactCommand = new RelayCommand((SelectedContact) => { if (SelectedContact == null) return; Contact contact = SelectedContact as Contact; using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.DeleteAsync("api/Contacts/" +contact.Id ).Result; } Update(); })); } } public RelayCommand EditCommand { get { return editCommand ?? (editCommand = new RelayCommand((SelectedPerson) => { if (SelectedPerson == null) return; Person person = SelectedPerson as Person; PersonView personView = new PersonView(); PersonVeiwModel personViewModel = new PersonVeiwModel(person); personView.DataContext = personViewModel; if (personView.ShowDialog() == true) { person = personViewModel.Person; using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PutAsJsonAsync("api/People/"+person.Id, person).Result; } Update(); } })); } } private void Delete(int delete) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.DeleteAsync("api/People/" + delete).Result; } } public RelayCommand DeleteCommand { get { return deleteCommand ?? (deleteCommand = new RelayCommand((SelectedPerson) => { if (SelectedPerson == null) return; Person person = SelectedPerson as Person; Delete(person.Id); Update(); })); } } #endregion } }
using System; using System.IO; using System.Reflection; /// <summary> /// EasyLogger Entry Point /// </summary> public static class EasyLogger { private static LogBase logger = null; /// <summary> /// The default directory used to store log files /// CommonApplicationData\\EasyLogger\\Name of your App\\User Name\\ /// </summary> public static string LogDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\EasyLogger\\" + Assembly.GetEntryAssembly().GetName().Name + "\\" + Environment.UserName + "\\"; /// <summary> /// The default file path to the log file used /// </summary> public static string LogFile = LogDirectory + Assembly.GetEntryAssembly().GetName().Name + ".log"; /// <summary> /// The default file path to the log file used /// </summary> internal static string LogFileBak = LogDirectory + "\\" + Assembly.GetEntryAssembly().GetName().Name + ".bak"; /// <summary> /// Backup log files to [FileName].bak; this is to prevent huge log files /// </summary> /// <param name="LogFilePath">Path to the log file</param> /// <param name="timeSpanInDays">Days until backed up; uses file creation time</param> public static void BackupLogs(string LogFilePath, int timeSpanInDays = 0) { LogFile = LogFilePath; logger = new FileLogger(); logger.BackupLogs(LogFile, timeSpanInDays); } /// <summary> /// Start the logging service /// </summary> /// <param name="LogFilePath">Path to the log file</param> public static void AddListener(string LogFilePath) { Directory.CreateDirectory(LogDirectory); LogFile = LogFilePath; logger = new FileLogger(); logger.AddListener(LogFile); } /// <summary> /// Stops and disposes of the logging service /// </summary> public static void RemoveListener() { logger = new FileLogger(); logger.RemoveListener(); } /// <summary> /// Insert [error] in the line /// </summary> /// <param name="message"></param> public static void Error(string message) { logger = new FileLogger(); logger.Error(message); } /// <summary> /// Insert [error] in the line /// </summary> /// <param name="ex"></param> public static void Error(Exception ex) { logger = new FileLogger(); logger.Error(ex); } /// <summary> /// Insert [warning] in the line /// </summary> /// <param name="message"></param> public static void Warning(string message) { logger = new FileLogger(); logger.Warning(message); } /// <summary> /// Insert [info] in the line /// </summary> /// <param name="message"></param> public static void Info(string message) { logger = new FileLogger(); logger.Info(message); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace PROnline.Models.Users { public class UserPTest { public Guid ID { get; set; } public Guid StudentID { get; set; } public virtual Student User { get; set; } [Display(Name = "测试时间")] [Required(ErrorMessage = "必须填写")] public DateTime TestDate { get; set; } [Display(Name = "想法总与别人不一样")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [Required(ErrorMessage = "必须填写")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Ta { get; set; } [Display(Name = "情绪不稳定(常发脾气或容易激动或容易哭泣)")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [Required(ErrorMessage = "必须填写")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Tb { get; set; } [Display(Name = "讨厌上学、讨厌写作业")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Tc { get; set; } [Display(Name = "伤害他人或打人")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Td { get; set; } [Display(Name = "从不与异性在一起")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Te { get; set; } [Display(Name = "平时成绩和考试成绩差距较大")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Tf { get; set; } [Display(Name = "时常与人争论、抬杠")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Tg { get; set; } [Display(Name = "不喜欢与他人交往")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Th { get; set; } [Display(Name = "学习成绩忽上忽下,很不稳定")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Ti { get; set; } [Display(Name = "和老师发生冲突")] [Required(ErrorMessage = "必须填写")] [Range(1, 10, ErrorMessage = "分数只能是1-10")] [RegularExpression("[0-9]+", ErrorMessage = "只能是数字")] public int Tj { get; set; } public int total { get; set; } public String result { get; set; } } }
//using System; //using System.Collections.Generic; //using System.IO; //using System.Linq; //using System.Reflection; //using System.Text.RegularExpressions; //using System.Web.Compilation; //namespace Atomic //{ // /// <summary> // /// 类型扫描抽象类 // /// </summary> // public abstract class TypeFinderBase : ITypeFinder // { // #region Variable // /// <summary> // /// 已跳过的程序集的策略正则表达式集合 // /// </summary> // private readonly List<string> _skipedAssemblyPatterns = new List<string>(); // /// <summary> // /// 指定扫描的DLL必须满足的条件约定,默认 .* // /// </summary> // private string _assemblyRestrictToLoadingPattern = ".*"; // /// <summary> // /// 约定额外的程序集【不在AppDomain中的程序集】 // /// </summary> // private readonly List<Assembly> _extraAssembliesDLL = new List<Assembly>(); // /// <summary> // /// 排除的程序集的FullName // /// </summary> // private readonly List<string> _excludeAssembliesName = new List<string>(); // #endregion // #region Constructor // /// <summary> // /// 默认构造函数(已过滤DOTNET的基础DLL,例如:System mscorlib Microsoft) // /// </summary> // public TypeFinderBase() // { // //Skip DOTNET DLL Patterns // this.AddSkipAssemblyPattern("^System."); // this.AddSkipAssemblyPattern("^mscorlib"); // this.AddSkipAssemblyPattern("^Microsoft"); // } // #endregion // #region Propertys // /// <summary> // /// 指定不允许加载的DLL的正则约定(即:不在那些程序集里进行扫描) // /// </summary> // public string AssemblySkipLoadingPattern // { // get // { // return string.Join("|", this._skipedAssemblyPatterns); // } // } // /// <summary> // /// 指定扫描的DLL必须满足的条件约定,默认 .* // /// </summary> // /// <remarks>例如:只在XXX名称开头的程序集里进行扫描,则设置为^XXX</remarks> // public string AssemblyRestrictToLoadingPattern // { // get { return this._assemblyRestrictToLoadingPattern; } // } // #endregion // #region ITypeFinder // /// <summary> // /// 当前接口实例下已加载的额外DLL // /// </summary> // public System.Collections.ObjectModel.ReadOnlyCollection<Assembly> ExtraAssembliesDLL // { // get { return this._extraAssembliesDLL.AsReadOnly(); } // } // /// <summary> // /// 已排除的程序集名称集合 // /// </summary> // public System.Collections.ObjectModel.ReadOnlyCollection<string> ExcludeAssembliesName // { // get { return this._excludeAssembliesName.AsReadOnly(); } // } // /// <summary> // /// 追加一个额外的程序集 // /// </summary> // /// <param name="assembly"></param> // public void AppendAssembly(Assembly assembly) // { // if (null == assembly) // { // return; // } // if (!this.Matches(assembly.FullName)) // { // return; // } // //如果追加的程序集在排除范围内,则将排除项进行清空 // if (this._excludeAssembliesName.Exists(d => d.Equals(assembly.FullName))) // { // this._excludeAssembliesName.Remove(assembly.FullName); // } // bool exists = false; // foreach (var item in this.GetAssemblies()) // { // if (item.FullName.Equals(assembly.FullName)) // { // exists = true; // break; // } // } // if (exists) // { // return; // } // this._extraAssembliesDLL.Add(assembly); // } // /// <summary> // /// 移除一个额外的程序集 // /// </summary> // /// <param name="assembly"></param> // public void RemoveAssembly(Assembly assembly) // { // if (null == assembly) // { // return; // } // //尝试从额外DLL中移除 // bool isReturn = false; // foreach (var item in this._extraAssembliesDLL) // { // if (item.FullName.Equals(assembly.FullName)) // { // this._extraAssembliesDLL.Remove(assembly); // isReturn = true; // break; // } // } // if (isReturn) // { // return; // } // //检索BuildManager中的程序集,如果存在标记为不扫描DLL // Assembly[] existedAssemblys = null; // if (AppDomain.CurrentDomain.ShadowCopyFiles) // existedAssemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray(); // else // existedAssemblys = (from name in Assembly.GetEntryAssembly().GetReferencedAssemblies() // select Assembly.Load(name)).ToArray(); // foreach (var item in existedAssemblys) // { // if (item.FullName.Equals(assembly.FullName) && this.Matches(assembly.FullName)) // { // this._excludeAssembliesName.Add(item.FullName); // break; // } // } // } // /// <summary> // /// 从所有的DLL进行筛选出匹配的类型 // /// </summary> // /// <param name="assignTypeFrom">指定接口类型</param> // /// <param name="onlyConcreteClasses">True:不包含抽象类型,False:包含抽象类型</param> // /// <returns></returns> // public IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses) // { // return this.FindClassesOfType(assignTypeFrom, null, onlyConcreteClasses); // } // /// <summary> // /// 从指定的程序集中筛选出匹配的类型 // /// </summary> // /// <param name="assignTypeFrom">指定接口类型</param> // /// <param name="assemblies">指定的查询的程序集范围</param> // /// <param name="onlyConcreteClasses">True:不包含抽象类型,False:包含抽象类型</param> // /// <returns></returns> // public IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) // { // List<Assembly> assemblyList = null == assemblies ? new List<Assembly>() : new List<Assembly>(assemblies); // //优先检测外部传入参数 // if (assemblyList.Count == 0) // { // //获取当前允许检测的程序集 // assemblyList = new List<Assembly>(this.GetAssemblies()); // if (assemblyList.Count == 0) // { // yield break; // } // } // foreach (var item in assemblyList) // { // Type[] types = item.GetTypes(); // if (null != types) // { // foreach (var t in types) // { // if (assignTypeFrom.IsAssignableFrom(t) || (assignTypeFrom.IsGenericTypeDefinition && DoesTypeImplementOpenGeneric(t, assignTypeFrom))) // { // if (!t.IsInterface) // { // if (onlyConcreteClasses) // { // if (t.IsClass && !t.IsAbstract) // { // yield return t; // } // } // else // { // yield return t; // } // } // } // } // } // } // } // /// <summary> // /// 从指定的程序集中筛选出匹配的类型 // /// </summary> // /// <typeparam name="T">指定接口类型</typeparam> // /// <param name="assemblies">指定的查询的程序集范围(默认:null 指从所有的程序集进行筛选)</param> // /// <param name="onlyConcreteClasses">True:不包含抽象类型,False:包含抽象类型</param> // /// <returns></returns> // public IEnumerable<Type> FindClassesOfType<T>(IEnumerable<System.Reflection.Assembly> assemblies, bool onlyConcreteClasses) // { // return this.FindClassesOfType(typeof(T), assemblies, onlyConcreteClasses); // } // /// <summary> // /// 获取所有的符合条件的程序集 // /// </summary> // /// <returns></returns> // public virtual IEnumerable<Assembly> GetAssemblies() // { // List<Assembly> assemblies = new List<Assembly>(); // List<string> addedAssemblyNames = new List<string>(); // //检索BuildManager中的程序集,如果存在标记为不扫描DLL // Assembly[] existedAssemblys = null; // if (AppDomain.CurrentDomain.ShadowCopyFiles) // existedAssemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray(); // else // existedAssemblys = (from name in Assembly.GetEntryAssembly().GetReferencedAssemblies() // select Assembly.Load(name)).ToArray(); // foreach (Assembly assembly in existedAssemblys) // { // if (this.Matches(assembly.FullName) && !addedAssemblyNames.Contains(assembly.FullName) && !this._excludeAssembliesName.Exists(d => d.Equals(assembly.FullName))) // { // assemblies.Add(assembly); // addedAssemblyNames.Add(assembly.FullName); // } // } // /* add assembly from app bin path reload test!! */ // string appBinPath = null; // if ("true".Equals(System.AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles, StringComparison.OrdinalIgnoreCase)) // appBinPath = System.AppDomain.CurrentDomain.SetupInformation.ShadowCopyDirectories; // else // appBinPath = appBinPath = System.AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; // FileInfo[] path_fs = new System.IO.DirectoryInfo(appBinPath).GetFiles("*.dll", SearchOption.TopDirectoryOnly); // foreach (var path_f in path_fs) // { // if (this.Matches(path_f.Name) && !addedAssemblyNames.Contains(path_f.Name) && !this._excludeAssembliesName.Exists(d => d.Equals(path_f.Name))) // { // assemblies.Add(Assembly.LoadFile(path_f.FullName)); // addedAssemblyNames.Add(path_f.Name); // } // } // //add assembly from extraAssemblies // foreach (Assembly extraDLL in this._extraAssembliesDLL) // { // if (this.Matches(extraDLL.FullName) && !addedAssemblyNames.Contains(extraDLL.FullName) && !this._excludeAssembliesName.Exists(d => d.Equals(extraDLL.FullName))) // { // assemblies.Add(extraDLL); // addedAssemblyNames.Add(extraDLL.FullName); // } // } // return assemblies; // } // #endregion // #region Virtual Protected Methods // /// <summary> // /// 判断指定的程序集是否满足验证规则【1.不包含在跳过配置,2.满足限制约束】 // /// </summary> // /// <param name="assemblyFullName">程序集名称</param> // /// <returns></returns> // protected virtual bool Matches(string assemblyFullName) // { // if (string.IsNullOrEmpty(assemblyFullName)) // { // return false; // } // return !Regex.IsMatch(assemblyFullName, this.AssemblySkipLoadingPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled) && Regex.IsMatch(assemblyFullName, this.AssemblyRestrictToLoadingPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); // } // /// <summary> // /// 是否表示可以用来构造其他泛型类型的泛型类型 // /// </summary> // /// <param name="type"></param> // /// <param name="openGeneric"></param> // /// <returns></returns> // protected virtual bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric) // { // try // { // var genericTypeDefinition = openGeneric.GetGenericTypeDefinition(); // foreach (var implementedInterface in type.FindInterfaces((objType, objCriteria) => true, null)) // { // if (!implementedInterface.IsGenericType) // continue; // var isMatch = genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition()); // return isMatch; // } // return false; // } // catch // { // return false; // } // } // #endregion // #region Set SkipPatterns // /// <summary> // /// 新增需要跳过的程序集正则 // /// </summary> // /// <param name="assemblyPattern">程序集正则</param> // protected void AddSkipAssemblyPattern(string assemblyPattern) // { // if (string.IsNullOrEmpty(assemblyPattern) || this._skipedAssemblyPatterns.Exists(d => d.Equals(assemblyPattern))) // { // return; // } // this._skipedAssemblyPatterns.Add(assemblyPattern); // } // /// <summary> // /// 删除需要跳过的程序集正则 // /// </summary> // /// <param name="assemblyPattern">程序集正则</param> // protected void RemoveSkipAssemblyPattern(string assemblyPattern) // { // if (string.IsNullOrEmpty(assemblyPattern) || !this._skipedAssemblyPatterns.Exists(d => d.Equals(assemblyPattern))) // { // return; // } // this._skipedAssemblyPatterns.Remove(assemblyPattern); // } // #endregion // #region Set RestrictPattern // /// <summary> // /// 设置限制加载的正则表达式 // /// </summary> // /// <param name="restrictToLoadingPattern">限制加载的表达式</param> // protected void SetRestrictPattern(string restrictToLoadingPattern) // { // this._assemblyRestrictToLoadingPattern = restrictToLoadingPattern; // } // #endregion // } //}
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "InGameThings/Cards/ItemCardType")] public class ItemCard : CardType { private const int _cardTypeID = 1; public override int CardTypeID { get { return _cardTypeID; } } public override string GetTypeString() { return "Item"; } public override void OnInitCard() { Debug.Log("this is an item card"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.Net.Mail; public partial class admin_email : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } string strPath = ""; protected void Button1_Click(object sender, EventArgs e) { MailMessage newMsg = new MailMessage(); foreach (GridViewRow gvRow in GridView1.Rows) { CheckBox cb = (CheckBox)gvRow.FindControl("chkEmail"); if (cb != null && cb.Checked) { lblMail.Text += gvRow.Cells[4].Text+gvRow.Cells[3].Text; newMsg.To.Add(new MailAddress(gvRow.Cells[3].Text, gvRow.Cells[0].Text)); } } newMsg.From = new MailAddress("fliu63@student.monash.edu", "Liu Feng"); newMsg.Subject = txtSubject.Text; newMsg.Body = txtMsg.Text; bool sendEmail = true; if (fileUpload.HasFile) { if (UpLoadFile(fileUpload.FileName)) { Attachment newAttach = new Attachment(strPath); newMsg.Attachments.Add(newAttach); } else { sendEmail = false; } } if (sendEmail) { try { SmtpClient smtp = new SmtpClient(); //qlhbhtuiiedqbjbi smtp.Host = "smtp.monash.edu.au"; //smtp.Credentials = new NetworkCredential("137255853@qq.com", "qlhbhtuiiedqbjbi"); //smtp.EnableSsl = true; smtp.Send(newMsg); lblMail.Text = "Mail Successfully Sent"; } catch (Exception exc) { lblMail.Text = exc.Message; txtMsg.Text = newMsg.From.Address + exc.StackTrace; } } } public bool UpLoadFile(string strFileName) { bool blnFileOK = false; string strExt = System.IO.Path.GetExtension(fileUpload.PostedFile.FileName); if ((strExt != ".gif") && (strExt != ".jpg")) { lblMail.Text = "Invalid File Type"; } else { blnFileOK = true; strPath = Server.MapPath(".") + "/UploadFiles/" + strFileName; fileUpload.PostedFile.SaveAs(strPath); } return blnFileOK; } void Page_PreInit(object sender, EventArgs e) { string theme = "default"; if (Request.QueryString["theme"] == null) { theme = "default"; } else { theme = Request.QueryString["theme"]; } Page.Theme = theme; } }
using System; using Framework.Core.Common; using Tests.Pages.Van.Main.Common; using OpenQA.Selenium; namespace Tests.Pages.Van.Main.UserPages { public class UserDetailsAssignVotersPage : VanBasePage { #region Page Element Declarations public IWebElement AssignByDropdown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemAssignedByID_VANInputItemDetailsItemAssignedByID_AssignedByID")); } } public IWebElement CheckAllLink { get { return _driver.FindElement(By.XPath("//a[contains(text(),'Check All')]")); } } public IWebElement UncheckAllLink { get { return _driver.FindElement(By.XPath("//a[contains(text(),'Un-Check All')]")); } } public IWebElement SaveButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_ButtonUserDetailsAssignVotersSubmit")); } } #endregion public UserDetailsAssignVotersPage(Driver driver) : base(driver) { } #region Methods /// <summary> /// Set the Assign By dropdown. Currently only supports option: "Statewide Access" /// </summary> /// <param name="assignBy"></param> public void Assign(string assignBy) { SetAssignByDropdown(assignBy); ClickSaveButton(); } /// <summary> /// Sets the Assign By dropdown /// </summary> /// <param name="assignment"></param> public void SetAssignByDropdown(string assignment) { _driver.SelectOptionByTextIfStringNotNullOrEmpty(AssignByDropdown, assignment); } /// <summary> /// Clicks the Save button /// </summary> public void ClickSaveButton() { _driver.Click(SaveButton); } #region Helper Methods /// <summary> /// Checks a checkbox on the UserDetailsAssignVoters page that has the passed label /// </summary> /// <param name="label"></param> public void CheckCheckboxByLabel(string label) { var checkboxXpathString = String.Format("//label[text() = '{0}']/preceding-sibling::input", label); var checkbox = _driver.FindElement(By.XPath(checkboxXpathString)); _driver.Check(checkbox); } /// <summary> /// Sets a dropdown on the UserDetailsAssignVoters page that has the passed dropdownName /// </summary> /// <param name="dropdownName"></param> /// <param name="optionToSelect"></param> public void SetDropdownByName(string dropdownName, string optionToSelect) { var dropdownXpathString = String.Format("//nobr[contains(text(),'{0}']/../following-sibling::td[@class='WizardResults']/select", dropdownName); var dropdown = _driver.FindElement(By.XPath(dropdownXpathString)); _driver.SelectOptionByTextIfStringNotNullOrEmpty(dropdown, optionToSelect); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; namespace KartSystem { public class Loading1CSpecRecord : DocGoodSpecRecord { public decimal RateNds { get; set; } } }
namespace SenseHat { // Font definitions for SenseLED // Format // ulong = 64 bits, 1 bit per LED // array contains: // 2 elements representing width and height respectively // 95 elements representing ASCII char (decimal) 32 to 126 // to save space, only LSBs are used (if font needs 40 bits, we use 40LSBs) // bit order is still MSB first public class SenseLEDFont { public const char startChar = ' '; // ASCII 32 public const char endChar = '~'; // ASCII 126 public const byte fontLen = endChar - startChar + 1; // Length of font def arrays public const ushort defaultFont = 0; // Hide internal arrays, external refs use ID so we can use it as a default val for params private static class Fonts { public static readonly ulong[] defaultFont = { 5, 8, 0x0, 0x108421004, 0x294a00000, 0x295f57d4a, 0x11f4717c4, 0x632222263, 0x32544564d, 0x308800000, 0x88842082, 0x208210888, 0x9575480, 0x84f9080, 0x3088, 0xf8000, 0x18c, 0x2222200, 0x3a33ae62e, 0x11842108e, 0x3a211111f, 0x7c441062e, 0x8ca97c42, 0x7e1e0862e, 0x1910f462e, 0x7c2221084, 0x3a317462e, 0x3a317844c, 0x18c03180, 0x18c03088, 0x88882082, 0x1f07c00, 0x208208888, 0x3a2111004, 0x3a216d6ae, 0x3a31fc631, 0x7a31f463e, 0x3a308422e, 0x72518c65c, 0x7e10f421f, 0x7e10f4210, 0x3a30bc62f, 0x4631fc631, 0x38842108e, 0x1c4210a4c, 0x4654c5251, 0x42108421f, 0x4775ac631, 0x4639ace31, 0x3a318c62e, 0x7a31f4210, 0x3a318d64d, 0x7a31f5251, 0x3e107043e, 0x7c8421084, 0x46318c62e, 0x46318c544, 0x4631ad771, 0x462a22a31, 0x462a21084, 0x7c222221f, 0x39084210e, 0x20820820, 0x38421084e, 0x115100000, 0x1f, 0x208000000, 0xe0be2f, 0x4216cc62e, 0xe8422e, 0x42d9c62f, 0xe8fe0e, 0x8a471084, 0xf8bc2e, 0x4216cc631, 0x100c2108e, 0x80210a4c, 0x210953149, 0x30842108e, 0x1aad6b5, 0x16cc631, 0xe8c62e, 0x1e8fa10, 0xf8bc21, 0xb62108, 0xf8383e, 0x8e210a2, 0x118c66d, 0x118c544, 0x118d6aa, 0x1931193, 0x1149898, 0x1f1111f, 0x88441082, 0x108421084, 0x208411088, 0xdb0000 }; } // For internal library use only. Gets font by internal id public static ulong[] getFontById(ushort id) { switch (id) { case 0: return Fonts.defaultFont; } return Fonts.defaultFont; } } }
using Anywhere2Go.DataAccess.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Claimdi.Web.MY.Models { public class TaskViewModel { public TaskPicture TaskPicture { get; set; } public List<TaskPicture> TaskPictureHistory { get; set; } } public class SurveyorModel { public Guid accId { get; set; } public string firstName { get; set; } public string lastName { get; set; } public string gender { get; set; } public string tel { get; set; } public string address { get; set; } public string email { get; set; } public string picture { get; set; } public string distance { get; set; } public string latitude { get; set; } public string longitude { get; set; } public List<Task> Task { get; set; } } }
using System; namespace FamilyAccounting.Web.Models { public class AuditPersonViewModel { public PersonViewModel Person { get; set; } public string Type { get; set; } public DateTime Time { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IRAPShared; namespace IRAP.Entity.MDM { public class CustomStandard { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 参数叶标识 /// </summary> public int T20LeafID { get; set; } /// <summary> /// 参数名称 /// </summary> public string ParameterName { get; set; } /// <summary> /// 低限值 /// </summary> public long LowLimit { get; set; } /// <summary> /// 标准 /// </summary> public string Criterion { get; set; } /// <summary> /// 高限值 /// </summary> public long HighLimit { get; set; } /// <summary> /// 放大数量级 /// </summary> public int Scale { get; set; } /// <summary> /// 计量单位 /// </summary> public string UnitOfMeasure { get; set; } /// <summary> /// 参数标准 /// </summary> [IRAPORMMap(ORMMap = false)] public string StandardString { get { double doubleLow = LowLimit / Math.Pow(10, Scale); double doubleHigh = HighLimit / Math.Pow(10, Scale); string low = ""; string high = ""; if (Scale > 0) { string strFormat = ""; low = doubleLow.ToString("0." + strFormat.PadLeft(Scale, '0')); high = doubleHigh.ToString("0." + strFormat.PadLeft(Scale, '0')); } else { low = doubleLow.ToString("0"); high = doubleHigh.ToString("0"); } switch (Criterion.ToUpper()) { case "EQ": return string.Format("= {0}{1}", low, UnitOfMeasure); case "NE": return string.Format("≠ {0}{1}", low, UnitOfMeasure); case "GELE": return string.Format("{0} ≤值≤ {1} {2}", low, high, UnitOfMeasure); case "GTLT": return string.Format("{0} <值< {1} {2}", low, high, UnitOfMeasure); case "GTLE": return string.Format("{0} <值≤ {1} {2}", low, high, UnitOfMeasure); case "GELT": return string.Format("{0} ≤值< {1} {2}", low, high, UnitOfMeasure); case "BOOL": return "通过"; case "GE": return string.Format("{0} ≤值 {1}", low, UnitOfMeasure); case "LE": return string.Format("{0} ≥值 {1}", high, UnitOfMeasure); case "GT": return string.Format("{0} <值 {1}", low, UnitOfMeasure); case "LT": return string.Format("{0} >值 {1}", high, UnitOfMeasure); default: return string.Format("未定义的标准代码[{0}]", Criterion); } } } /// <summary> /// 中值 /// </summary> [IRAPORMMap(ORMMap = false)] public string MiddleValue { get { switch (Criterion.ToUpper()) { case "GELE": case "GTLT": case "GTLE": case "GELT": double doubleLow = LowLimit / Math.Pow(10, Scale); double doubleHigh = HighLimit / Math.Pow(10, Scale); string middleValue = ""; if (Scale > 0) { string strFormat = ""; middleValue = ((doubleLow + doubleHigh) / 2).ToString("0." + strFormat.PadLeft(Scale, '0')); } else { middleValue = ((doubleLow + doubleHigh) / 2).ToString("0"); } return string.Format("{0} {1}", middleValue, UnitOfMeasure); default: return ""; } } } public CustomStandard Clone() { return MemberwiseClone() as CustomStandard; } } }
using System.Collections.Generic; using System.Net; using System.Net.Sockets; using Umbraco.Core.Models; using Umbraco.Web; public class IPAddressRange { readonly AddressFamily addressFamily; readonly byte[] lowerBytes; readonly byte[] upperBytes; public IPAddressRange(IPAddress lower, IPAddress upper) { byte[] inputLowerBytes = lower.GetAddressBytes(); byte[] inputUpperBytes = upper.GetAddressBytes(); bool isCorrect = true; for (int i = 0; i < inputLowerBytes.Length; i++) { if (inputLowerBytes[i] > inputUpperBytes[i]) { isCorrect = false; break; } } this.addressFamily = lower.AddressFamily; if (isCorrect) { this.lowerBytes = inputLowerBytes; this.upperBytes = inputUpperBytes; } else { this.lowerBytes = inputUpperBytes; this.upperBytes = inputLowerBytes; } } public bool IsInRange(IPAddress address) { if (address.AddressFamily != addressFamily) { return false; } byte[] addressBytes = address.GetAddressBytes(); bool lowerBoundary = true, upperBoundary = true; for (int i = 0; i < this.lowerBytes.Length && (lowerBoundary || upperBoundary); i++) { if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) || (upperBoundary && addressBytes[i] > upperBytes[i])) { return false; } lowerBoundary &= (addressBytes[i] == lowerBytes[i]); upperBoundary &= (addressBytes[i] == upperBytes[i]); } return true; } } public class IPWhiteList { List<IPAddressRange> ipAddressRangeList; public IPWhiteList() { ipAddressRangeList = new List<IPAddressRange>(); if (UmbracoContext.Current != null) { UmbracoHelper helper = new UmbracoHelper(UmbracoContext.Current); if (helper != null) { IPublishedContent container = helper.TypedContent(1873); if (container != null) { var ids = container.GetProperty("ipRangeList").Value.ToString().Split(','); foreach (var id in ids) { IPublishedContent ipRangeItem = helper.TypedContent(id); if (ipRangeItem != null) { IPAddress lower; IPAddress upper; IPAddress.TryParse(ipRangeItem.GetProperty("ipMin").Value.ToString(), out lower); IPAddress.TryParse(ipRangeItem.GetProperty("ipMax").Value.ToString(), out upper); if (lower != null && upper != null) ipAddressRangeList.Add(new IPAddressRange(lower, upper)); } } } } } } public bool Contains(string ipAddressString) { IPAddress ipAddress; if (IPAddress.TryParse(ipAddressString, out ipAddress)) { foreach (var item in ipAddressRangeList) { if (item.IsInRange(ipAddress)) return true; } } return false; } }
namespace ChatServer.Messaging.Commands { using System.Threading.Tasks; using ChatProtos.Networking; using ChatProtos.Networking.Messages; using Google.Protobuf; using HServer; using HServer.Networking; /// <inheritdoc /> /// <summary> /// The update display name command. /// </summary> public class UpdateDisplayNameCommand : IChatServerCommand { /// <inheritdoc /> public async Task ExecuteTaskAsync(HChatClient client, RequestMessage message) { if (!client.Authenticated) { // TODO: Send response. return; } var parsed = ProtobufHelper.TryParse(UpdateDisplayRequest.Parser, message.Message, out var request); if (!parsed) { // TODO: Send response. return; } client.UpdateDisplayName(request.DisplayName); var response = new UpdateDisplayResponse { UserId = client.Id.ToString(), DisplayName = client.GetDisplayName() }.ToByteString(); await client.SendResponseTaskAsync(ResponseStatus.Success, RequestType.UpdateDisplayName, response) .ConfigureAwait(false); } } }
using BestMeetingSpot.Model; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using System.Net.Http; #pragma warning disable CS1701 // Assuming assembly reference matches identity namespace BestMeetingSpot.Services { public class GoogleMapsService : IGoogleMapsService { private string key = ""; // Your key goes here. private HttpClient client; public GoogleMapsService() { client = new HttpClient(); } public async Task<Tuple<Place,Place>> GetBestMatch(string addressA, string meanA, string addressB, string meanB) { var gA = await GetGeopoint(addressA); var gB = await GetGeopoint(addressB); var midPoint = GetMidPoint(gA, gB); var places = await GetPlacesByPoint(midPoint); var distanceMatrix = await GetDistanceMatrix(gA,meanA,gB,meanB,places); List<Heuristics> hs = new List<Heuristics>(); for (int i = 0; i < distanceMatrix.rows[0].elements.Count; i++) { var h = new Heuristics(); h.Place = places[i]; h.ATime = distanceMatrix.rows[0].elements[i].duration.value; h.BTime = distanceMatrix.rows[1].elements[i].duration.value; h.ADistance = distanceMatrix.rows[0].elements[i].distance.value; h.BDistance = distanceMatrix.rows[1].elements[i].distance.value; hs.Add(h); } var bestMatchTime = hs.OrderBy(x => x.ATime + x.BTime).First().Place; var bestMatchDistance = hs.OrderBy(x => x.ADistance + x.BDistance).First().Place; return new Tuple<Place,Place>(bestMatchTime,bestMatchDistance); } private async Task<DistanceApiResults> GetDistanceMatrix(Geopoint gA, string meansA, Geopoint gB, string meansB, List<Place> places) { var baseUri = "https://maps.googleapis.com/maps/api/distancematrix/json?"; var uriDestinations = $"{baseUri}destinations="; foreach (var place in places) { uriDestinations = $"{uriDestinations}{Uri.EscapeDataString(place.geometry.location.lat.ToString())},{Uri.EscapeDataString(place.geometry.location.lng.ToString())}"; if (places.IndexOf(place) != places.Count - 1) uriDestinations = $"{uriDestinations}|"; } if (meansA == meansB) //if the means of transport are the same just make one request { var uriFinal = new Uri($"{uriDestinations}&origins={Uri.EscapeDataString(gA.Latitude.ToString())},{Uri.EscapeDataString(gA.Longitude.ToString())}|{Uri.EscapeDataString(gB.Latitude.ToString())},{Uri.EscapeDataString(gB.Longitude.ToString())}&mode={meansA}&key={key}"); var model = await GetResults<DistanceApiResults>(uriFinal); return model; } else { var uriFinalA = new Uri($"{uriDestinations}&origins={Uri.EscapeDataString(gA.Latitude.ToString())},{Uri.EscapeDataString(gA.Longitude.ToString())}&mode={meansA}&key={key}"); var modelA = await GetResults<DistanceApiResults>(uriFinalA); var uriFinalB = new Uri($"{uriDestinations}&origins={Uri.EscapeDataString(gB.Latitude.ToString())},{Uri.EscapeDataString(gB.Longitude.ToString())}&mode={meansB}&key={key}"); var modelB = await GetResults<DistanceApiResults>(uriFinalB); modelA.rows.Add(modelB.rows.First()); return modelA; } } private async Task<List<Place>> GetPlacesByPoint(Geopoint midPoint) { var uri = new Uri($"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={Uri.EscapeDataString(midPoint.Latitude.ToString())},{Uri.EscapeDataString(midPoint.Longitude.ToString())}&radius=1000&types=bar&key={key}"); var model = await GetResults<PlacesApiResults>(uri); return model.results; } private async Task<T> GetResults<T>(Uri uri){ var request = new HttpRequestMessage(HttpMethod.Get,uri); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); var stream = await response.Content.ReadAsStreamAsync(); var sr = new StreamReader(stream); var json = await sr.ReadToEndAsync(); return JsonConvert.DeserializeObject<T>(json); } private Geopoint GetMidPoint(Geopoint gA, Geopoint gB) { Geopoint midPoint = new Geopoint(); double dLon = Geopoint.DegreeToRadian(gB.Longitude - gA.Longitude); double Bx = Math.Cos(Geopoint.DegreeToRadian(gB.Latitude)) * Math.Cos(dLon); double By = Math.Cos(Geopoint.DegreeToRadian(gB.Latitude)) * Math.Sin(dLon); midPoint.Latitude = Geopoint.RadianToDegree(Math.Atan2( Math.Sin(Geopoint.DegreeToRadian(gA.Latitude)) + Math.Sin(Geopoint.DegreeToRadian(gB.Latitude)), Math.Sqrt( (Math.Cos(Geopoint.DegreeToRadian(gA.Latitude)) + Bx) * (Math.Cos(Geopoint.DegreeToRadian(gA.Latitude)) + Bx) + By * By))); midPoint.Longitude = gA.Longitude + Geopoint.RadianToDegree(Math.Atan2(By, Math.Cos(Geopoint.DegreeToRadian(gA.Latitude)) + Bx)); return midPoint; } public async Task<Geopoint> GetGeopoint(string address) { var requestUri = new Uri($"https://maps.googleapis.com/maps/api/geocode/json?address={Uri.EscapeDataString(address)}&key={key}"); var model = await GetResults<GeocodingApiResults>(requestUri); return new Geopoint(model.results.First().geometry.location.lat, model.results.First().geometry.location.lng); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EasyDev.EPS.Portal; using System.Data; using EasyDev.PL; using System.Reflection; using EasyDev.EPS.Attributes; namespace EasyDev.EPS.BusinessObject { /// <summary> /// 通用业务对象,此对象中使用的会话对象是默认会话对象 /// </summary> /// <typeparam name="TModel">业务对象对应的模型对象类型</typeparam> public class GenericBO<TModel> : AbstractBO where TModel : IModel, new() { private string _keyField; protected override string KeyField { get { if (_keyField == null || _keyField.Length == 0) { PropertyInfo[] properties = typeof(TModel).GetProperties(); PropertyInfo property = null; for (int i = 0; i < properties.Length; i++) { object[] attributes = properties[i].GetCustomAttributes(false); if (attributes.Count(p => p.GetType().Equals(typeof(KeyPropertyAttribute)))>0) { property = properties[i]; break; } } if (property != null) { return property.Name; } else { return string.Empty; } } else { return _keyField; } } set { this._keyField = value; } } protected override void Initialize() { Model = ModelFactory.CreateModel<TModel>(); base.Initialize(); } public virtual void SetModel(Type modelType) { } /// <summary> /// 保存方法 /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual bool Save(TModel entity) { try { return DefaultSession.ExecuteCommand(entity.InsertCommand(), entity.ToParamObjects()) > 0; } catch (DALCoreException e) { throw e; } } /// <summary> /// 保存方法(非泛型版本) /// </summary> /// <param name="entity"></param> /// <returns></returns> public override bool Save(IModel entity) { try { return DefaultSession.ExecuteCommand(entity.InsertCommand(), entity.ToParamObjects()) > 0; } catch (DALCoreException e) { throw e; } } public virtual bool Delete(TModel entity) { try { return DefaultSession.ExecuteCommand( entity.DeleteCommand(string.Format("{0}=#{0}", KeyField)), entity.ToParamObjects()) > 0; } catch (DALCoreException e) { throw e; } } public override bool Delete(IModel entity) { try { return DefaultSession.ExecuteCommand( entity.DeleteCommand(string.Format("{0}=#{0}", KeyField)), entity.ToParamObjects()) > 0; } catch (DALCoreException e) { throw e; } } public virtual bool Update(TModel entity) { try { PropertyInfo result = entity.GetType().GetProperties().First(p => p.Name.Equals(KeyField, StringComparison.CurrentCultureIgnoreCase)); string key = string.Empty; ; if (result != null) { key = result.GetValue(entity, null).ToString(); } IDictionary<string,object> values = entity.ToParamDictionary(); return DefaultSession.ExecuteCommand( entity.UpdateCommand(string.Format("{0}=#{0}", KeyField.ToLower())), values) > 0; } catch (DALCoreException e) { throw e; } } public override bool Update(IModel entity) { try { return DefaultSession.ExecuteCommand( entity.UpdateCommand(string.Format("{0}=#{0}", KeyField)), entity.ToParamObjects()) > 0; } catch (DALCoreException e) { throw e; } } public virtual IList<TModel> FindAll() { try { Model = Activator.CreateInstance<TModel>(); DataTable dt = this.DefaultSession.GetDataTableFromCommand(Model.SelectCommand()); return ModelFactory.CreateModels<TModel>(dt); } catch (DALCoreException e) { throw e; } } public override IList<IModel> FindAllInstance() { try { EnsureConcreteBO(); if (Model == null) { throw new ModelNullException("Model_is_not_initialized"); } DataTable dt = this.DefaultSession.GetDataTableFromCommand(Model.SelectCommand()); return ModelFactory.CreateModels(dt, typeof(TModel)); } catch (DALCoreException e) { throw e; } } private void EnsureConcreteBO() { if (this.GetType().Equals(typeof(GenericBO<TModel>))) { throw new NotSupportedException(@"This method is not supported in GenericBO. Please use a concrete BO which inherit from GenericBO, such as UserBO, RoleBO, NewsBO and so forth."); } } /// <summary> /// 查找实例是否存在 /// </summary> /// <typeparam name="TInstance"></typeparam> /// <param name="instance"></param> /// <returns></returns> public virtual TInstance FindByInstance<TInstance>(TInstance instance) where TInstance : AbstractModel, new() { try { string command = SQLBuilder.BuildSelectInstance(instance); DataTable dt = DefaultSession.GetDataTableFromCommand(command); if (dt.Rows.Count > 0) { return ModelFactory.CreateModel<TInstance>(dt); } else { return null; } } catch (DALCoreException e) { throw e; } catch (ModelNotFoundException e) { throw e; } } /// <summary> /// 查找实例是否存在 /// </summary> /// <typeparam name="TInstance"></typeparam> /// <param name="instance"></param> /// <returns></returns> public override IModel FindByInstance(IModel instance) { try { string command = SQLBuilder.BuildSelectInstance(instance); DataTable dt = DefaultSession.GetDataTableFromCommand(command); if (dt.Rows.Count > 0) { return ModelFactory.CreateModel(dt, Model.GetType()); } else { return null; } } catch (DALCoreException e) { throw e; } } /// <summary> /// 根据KEYFIELD查找模型对象 /// </summary> /// <typeparam name="TModel"></typeparam> /// <param name="id"></param> /// <returns></returns> public virtual TModel FindById(string id) { try { EnsureConcreteBO(); string cmd = Model.SelectCommand(string.Format("{0}=#{0}", KeyField)); DataTable dt = DefaultSession.GetDataTableFromCommand(cmd, id); return ModelFactory.CreateModel<TModel>(dt); } catch (Exception e) { throw e; } } } }
using Compent.Shared.Search.Elasticsearch; using Uintra.Core.Search.Entities; namespace Uintra.Core.Search.Queries.DeleteByType { public class DeleteSearchableActivityByTypeSpecificationFactory : IDeleteSpecificationFactory<SearchableActivity, DeleteSearchableActivityByTypeQuery> { public DeleteQuerySpecification<SearchableActivity> Create(DeleteSearchableActivityByTypeQuery query, string culture) { var spec = new DeleteSearchableActivityByTypeSpecification(query); return spec; } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace com.Sconit.Web.Models.SearchModels.ISS { public class IssueDetailSearchModel : SearchModelBase { public string IssueCode { get; set; } public string Content { get; set; } public string IssueLevel { get; set; } public string Email { get; set; } public string MobilePhone { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } } }
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual; using Pe.Stracon.SGC.Infraestructura.Core.Context; using Pe.Stracon.SGC.Infraestructura.Core.QueryContract.Contractual; using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual; using Pe.Stracon.SGC.Infraestructura.Repository.Base; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Infraestructura.Repository.Query.Contractual { /// <summary> /// Implementación del repositorio Contrato Documento /// </summary> public class ContratoDocumentoLogicRepository : QueryRepository<ContratoDocumentoLogic>, IContratoDocumentoLogicRepository { } }
using Microsoft.EntityFrameworkCore.Migrations; namespace ATeamFitness.Migrations { public partial class newMigration2 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DeleteData( table: "AspNetRoles", keyColumn: "Id", keyValue: "73b79cbe-58c4-49e2-846c-a28c3c507a4c"); migrationBuilder.DeleteData( table: "AspNetRoles", keyColumn: "Id", keyValue: "93c7b12a-4c51-4b87-b74d-4272f2e8f3cf"); migrationBuilder.AddColumn<int>( name: "ThumbsDown", table: "PersonalTrainers", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "ThumbsUp", table: "PersonalTrainers", nullable: false, defaultValue: 0); migrationBuilder.InsertData( table: "AspNetRoles", columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" }, values: new object[] { "52777df3-fe17-47f3-b400-39b0bcdaa170", "5b2bec87-2f6a-4235-8fcc-8c323007795b", "Customer", "CUSTOMER" }); migrationBuilder.InsertData( table: "AspNetRoles", columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" }, values: new object[] { "b50fd321-c629-41e6-a9fe-7d251340c2b2", "4b43ffae-3be3-4af8-b4f6-3c1348fe6b5f", "Trainer", "TRAINER" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DeleteData( table: "AspNetRoles", keyColumn: "Id", keyValue: "52777df3-fe17-47f3-b400-39b0bcdaa170"); migrationBuilder.DeleteData( table: "AspNetRoles", keyColumn: "Id", keyValue: "b50fd321-c629-41e6-a9fe-7d251340c2b2"); migrationBuilder.DropColumn( name: "ThumbsDown", table: "PersonalTrainers"); migrationBuilder.DropColumn( name: "ThumbsUp", table: "PersonalTrainers"); migrationBuilder.InsertData( table: "AspNetRoles", columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" }, values: new object[] { "73b79cbe-58c4-49e2-846c-a28c3c507a4c", "33967e83-e6ec-4be4-8340-538c561d5260", "Customer", "CUSTOMER" }); migrationBuilder.InsertData( table: "AspNetRoles", columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" }, values: new object[] { "93c7b12a-4c51-4b87-b74d-4272f2e8f3cf", "6665c9a0-bdb4-4aca-9f17-82d25b2ce461", "Trainer", "TRAINER" }); } } }
namespace TripDestination.Tests.Web.MVC.Controllers { using Common.Infrastructure.Mapping; using NUnit.Framework; using TripDestination.Web.MVC.Controllers; using Moq; using Services.Data.Contracts; using Data.Models; using System.Linq; using System.Collections.Generic; using Services.Web.Helpers.Contracts; using System; using TestStack.FluentMVCTesting; using TripDestination.Web.MVC.ViewModels.Home; using Services.Web.Services; using Services.Web.Providers.Contracts; using System.Web.Mvc; [TestFixture] public class HomeControllerTests { private const string fromTown = "Sofia"; private const string toTown = "Burgas"; private HomeController HomeController; [SetUp] public void Init() { AutoMapperConfig.Register(typeof(HomeController).Assembly); var tripServicesMock = new Mock<ITripServices>(); tripServicesMock.Setup(x => x.GetTodayTrips(It.IsAny<int>())) .Returns(new List<Trip> { new Trip() { From = new Town { Name = fromTown }, To = new Town { Name = toTown } } }.AsQueryable()); tripServicesMock.Setup(x => x.GetLatest(It.IsAny<int>())) .Returns(new List<Trip> { new Trip() { From = new Town { Name = fromTown }, To = new Town { Name = toTown } }, new Trip() { From = new Town { Name = toTown }, To = new Town { Name = fromTown } } }.AsQueryable()); var tripHelperMock = new Mock<ITripHelper>(); tripHelperMock.Setup(x => x.GetTopDestinations()) .Returns(new List<Tuple<string, string>>() { new Tuple<string, string>(fromTown, toTown) }); var townHelperMock = new Mock<ITownProvider>(); townHelperMock.Setup(x => x.GetCachedTowns()) .Returns(new List<SelectListItem>() { new SelectListItem { Text = "A", Value = "A" }, new SelectListItem { Text = "B", Value = "B" }, new SelectListItem { Text = "C", Value = "C" }, }); var homeController = new HomeController(tripServicesMock.Object, tripHelperMock.Object, townHelperMock.Object); homeController.Cache = new HttpCacheServices(); this.HomeController = homeController; } [Test] public void IndexShouldRenderCorrectView() { this.HomeController.WithCallTo(x => x.Index()) .ShouldRenderView("Index") .WithModel<HomepageViewModel>(); } [Test] public void IndexShouldRenderCorrectViewWithCorrectTopDestinations() { this.HomeController.WithCallTo(x => x.Index()) .ShouldRenderView("Index") .WithModel<HomepageViewModel>( vm => { Assert.AreEqual(fromTown, vm.TopDestinations.FirstOrDefault().FromTown); Assert.AreEqual(toTown, vm.TopDestinations.FirstOrDefault().ToTown); } ); } [Test] public void IndexShouldRenderCorrectViewWithCorrectLatestTripTownsSelectList() { this.HomeController.WithCallTo(x => x.Index()) .ShouldRenderView("Index") .WithModel<HomepageViewModel>( vm => { Assert.AreEqual("A", vm.TownsSelectList.FirstOrDefault().Text); Assert.AreEqual("B", vm.TownsSelectList.ElementAt(1).Text); Assert.AreEqual("C", vm.TownsSelectList.ElementAt(2).Text); } ); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BumperScript : MonoBehaviour { public float force = 20f; private Vector3 bounceDir; private void OnCollisionEnter(Collision other) { bounceDir = (transform.position - other.rigidbody.transform.position).normalized; //reverse object momentum var bumpVelocityX = bounceDir.x * -force; var bumpVelocityZ = bounceDir.y * -force; other.rigidbody.AddForce(bumpVelocityX, bounceDir.y, bumpVelocityZ, ForceMode.Impulse); } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Core.Enums.Enum { [ClassProperty(Name = "区时")] public enum ZoneTime { /// <summary> /// (UTC-12:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Dateline Standard Time -12:00")] UtcSubtract12 = -12, /// <summary> /// (UTC-11:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Coordinated Universal Time -11:00")] UtcSubtract11 = -11, /// <summary> /// (UTC-10:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Aleutian Standard Time -10:00")] UtcSubtract10 = -10, /// <summary> /// (UTC-9:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Alaskan Standard Time -9:00")] UtcSubtract9 = -9, /// <summary> /// (UTC-8:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Pacific Standard Time -8:00")] UtcSubtract8 = -8, /// <summary> /// (UTC-7:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Mountain Standard Time -7:00")] UtcSubtract7 = -7, /// <summary> /// (UTC-6:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Central Standard Time -6:00")] UtcSubtract6 = -6, /// <summary> /// (UTC-5:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "SA Pacific Standard Time -5:00")] UtcSubtract5 = -5, /// <summary> /// (UTC-4:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Paraguay Standard Time -4:00")] UtcSubtract4 = -4, /// <summary> /// (UTC-3:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Tocantins Standard Time -3:00")] UtcSubtract3 = -3, /// <summary> /// (UTC-2:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Mid-Atlantic Standard Time -2:00")] UtcSubtract2 = -2, /// <summary> /// (UTC-1:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Azores Standard Time -1:00")] UtcSubtract1 = -1, /// <summary> /// (UTC) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "UTC")] Utc = 0, /// <summary> /// (UTC+1:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Central Europe Standard Time +1:00")] UtcAdd1 = 1, /// <summary> /// (UTC+2:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Jordan Standard Time +2:00")] UtcAdd2 = 2, /// <summary> /// (UTC+3:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Arab Standard Time +3:00")] UtcAdd3 = 3, /// <summary> /// (UTC+4:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Arabian Standard Time +4:00")] UtcAdd4 = 4, /// <summary> /// (UTC+5:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Ekaterinburg Standard Time +5:00")] UtcAdd5 = 5, /// <summary> /// (UTC+6:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Central Asia Standard Time +6:00")] UtcAdd6 = 6, /// <summary> /// (UTC+7:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "SE Asia Standard Time +7:00")] UtcAdd7 = 7, /// <summary> /// (UTC+8:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "China Standard Time +8:00")] UtcAdd8 = 8, /// <summary> /// (UTC+9:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Korea Standard Time +9:00")] UtcAdd9 = 9, /// <summary> /// (UTC+10:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "West Pacific Standard Time +10:00")] UtcAdd10 = 10, /// <summary> /// (UTC+11:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Norfolk Standard Time +11:00")] UtcAdd11 = 11, /// <summary> /// (UTC+12:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "New Zealand Standard Time +12:00")] UtcAdd12 = 12, /// <summary> /// (UTC+13:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Tonga Standard Time +13:00")] UtcAdd13 = 13, /// <summary> /// (UTC+14:00) /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "Line Islands Standard Time +14:00")] UtcAdd14 = 14 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cat : MonoBehaviour { Transform cat; public float speed = 3.0f; public float distance = 50.0f; float moved = 0.0f; bool move = true; bool forward = true; // Use this for initialization void Start () { cat = GetComponent<Transform>(); } // Update is called once per frame void Update () { if (forward && moved < distance) { Vector3 move = cat.forward * Time.deltaTime * speed; cat.Translate(move); moved += Vector3.Magnitude(move); } else if(forward && moved >= distance) { forward = false; } if(!forward && moved > -distance) { Vector3 move = -cat.forward * Time.deltaTime * speed; cat.Translate(move); moved -= Vector3.Magnitude(move); } else if(!forward && moved <= -distance) { forward = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZM.TiledScreenDesigner { public interface IChildrens { void ChildAdd(object o); int ChildCount { get; } int ChildIndexOf(object o); void ChildInsert(int index, object o); void ChildRemove(object o); void ChildRemoveAt(int index); Type ChildType { get; } List<object> Childs { get; } } }
using PL.Integritas.Domain.Entities; using PL.Integritas.Domain.Interfaces.Repositories; using PL.Integritas.Infra.Data.Context; namespace PL.Integritas.Infra.Data.Repository { public class PurchaseRepository : Repository<Purchase>, IPurchaseRepository { public PurchaseRepository(IntegritasContext integritasContext) : base(integritasContext) { } } }
using System.Windows; namespace ModelViewViewModel_Voorbeeld { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { //private void Application_Startup(object sender, StartupEventArgs e) //{ // Stap2.Persoon model = new Stap2.Persoon(); // Stap2.PersoonViewModel viewmodel = new Stap2.PersoonViewModel(model); // Stap2.PersoonView view = new Stap2.PersoonView(); // view.DataContext = viewmodel; // view.Show(); //} private void Application_Startup(object sender, StartupEventArgs e) { MainWindowViewModel viewmodel = new MainWindowViewModel(); MainWindow view = new MainWindow(); view.DataContext = viewmodel; view.Show(); } } }
using System; using System.Collections.Generic; namespace SampleConsoleApp_01 { class Program { static List<int> PositiveList(List<int> list01) { List<int> resList = new List<int>(); for (int i = 0; i < list01.Count; i++) { if (list01[i] > 0) { resList.Add(list01[i]); } } return resList; } static List<int> PositiveListAndAdd(List<int> list01, int number) { List<int> resList = new List<int>(); for (int i = 0; i < list01.Count; i++) { if (list01[i] > 0) { resList.Add(list01[i]); resList.Add(number); } else resList.Add(list01[i]); } return resList; } static List<int> RemoveOdd(List<int> list01, int number) { for (int i = 0; i < list01.Count; i++) { if (list01[i] % 2 != 0) list01.RemoveAt(i); } return list01; } static List<int> ConversionToNumber(List<string> list) { List<int> listNumb = new List<int>(); for (int i = 0; i < list.Count; i++) { bool sucess = int.TryParse(list[i], out int number); if (sucess) { listNumb.Add(number); } } return listNumb; } static void Main(string[] args) { } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class HudController : MonoBehaviour { // Use this for initialization [SerializeField] private GameObject ready; private Button readyBtn; public static HudController instance; void Awake() { instance = this; } void Start () { Time.timeScale = 0; readyBtn = ready.GetComponent<Button>(); readyBtn.onClick.AddListener(() => startGame()); } // Update is called once per frame void startGame () { readyBtn.onClick.RemoveAllListeners(); ready.SetActive(false); Time.timeScale = 1; } }
// ----------------------------------------------------------------------- // <copyright file="ICultureRepository.cs"> // Copyright (c) Michal Pokorný. All Rights Reserved. // </copyright> // ----------------------------------------------------------------------- namespace Pentagon.Extensions.Localization.EntityFramework.Persistence { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Entities; public interface ICultureRetriever { Task<CultureResourceEntity> GetOneAsync(string cultureName, string key, CancellationToken cancellationToken = default); Task<IReadOnlyList<CultureResourceEntity>> GetAllAsync(string cultureName, CancellationToken cancellationToken = default); Task<IReadOnlyList<CultureEntity>> GetCulturesAsync(CancellationToken cancellationToken = default); Task<CultureEntity> GetCultureAsync(string name, CancellationToken cancellationToken = default); } }
using System; using System.Globalization; using Xamarin.Forms; namespace Bounce.Converters { public class CheckImageValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool bVal = (bool)value; return (bVal ? "row_check" : "row_nocheck"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
namespace Delegates { public interface IPicture { void Save(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TransitionMetalColourRevisionGame.TransMetals { class Chromium { public string name = "Chromium"; public string hexAqFormula = "[Cr(H₂O)₆]³⁺"; public string hexAqColour = "Ruby"; public string hexAqState = "Aqueous Solution"; public string saltRctColour = "Green"; public string saltRctFormula = "[Cr(H₂O)₄Cl₂]⁺"; public string saltRctState = "Aqueous Solution"; public string dilNaOHColour = "Green"; public string dilNaOHFormula = "[Cr(H₂O)₃(OH)₃]"; public string dilNaOHstate = "Precipitate"; public string excessNaOHRctColour = "Green"; public string excessNaOHRctFormula = "[Cr(H₂O)₂(OH)₄]⁻"; public string excessNaOHRctState = "Ppt dissolves to aq solution"; public string dilNH3RctColour = "Green"; public string dilNH3RctFormula = "[Cr(H₂O)₃(OH)₃]"; public string dilNH3RctState = "Precipitate"; public string ExcessNH3Colour = "Violet"; public string ExcessNH3Formula = "[Cr(NH₃)₆]²⁺"; public string ExcessNH3State = "Ppt dissolves to aq solution"; public string ClRctColour = "No Reaction"; public string ClRctFormula = "No Reaction"; public string ClRctState = "No Reaction"; public string Na2CO3RctColour = "Green"; public string Na2CO3RctFormula = "[Cr(H₂O)₃(OH)₃] + CO₂"; public string Na2CO3RctState = "Precipitate"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Microsoft.master2.assembly { class AssemblyInstance { private string assemblyName = "C://Users//Maz//Documents//Visual Studio 2012//Projects//WindowsFormsApplication3//WindowsFormsApplication3//bin//Debug//WindowsFormsApplication3.exe"; private Assembly assembly = null; public Assembly Assembly { get { if (assembly == null) { try { assembly = Assembly.LoadFile(assemblyName); } catch (Exception e) { } } return assembly; } set { assembly = value; } } } }
using Alabo.Data.People.Cities.Domain.Entities; using Alabo.Data.People.Cities.Domain.Services; using Alabo.Data.People.Users.Domain.Services; using Alabo.Framework.Core.Reflections.Interfaces; using Alabo.Helpers; namespace Alabo.Data.People.Cities { public class CityDefault : IDefaultInit { public bool IsTenant => false; public void Init() { #region 添加Admin为默认员工 var user = Ioc.Resolve<IUserService>().GetSingle("admin"); if (user != null) { var find = Ioc.Resolve<ICityService>().GetSingle(r => r.UserId == user.Id); if (find == null) { var city = new City { Name = user.GetUserName(), UserId = user.Id, RegionId = 0 }; Ioc.Resolve<ICityService>().Add(city); } } #endregion 添加Admin为默认员工 } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using TechnicalRadiation.Models.Dtos; using TechnicalRadiation.Models.Entities; using TechnicalRadiation.Models.InputModels; using TechnicalRadiation.Repositories.Data; using TechnicalRadiation.Repositories.Extensions; namespace TechnicalRadiation.Repositories { public class AuthorRepository { public IEnumerable<AuthorDto> GetAllAuthors(string urlStr) { return ListExtensions.ToAuthorLightWeight(DataContext.Authors, urlStr); } public AuthorDetailDto GetAuthorDetailById(int id, string urlStr) { return ListExtensions.ToAuthorDetail(DataContext.Authors.Where(x => x.Id == id).ToList(), urlStr).FirstOrDefault(); } public IEnumerable<NewsItemDto> GetAuthorNewsByAuthorId(int id, string urlStr) { return ListExtensions.ToNewsItemLightWeight(DataContext.NewsItems.Where(x => x.AuthorId == id).ToList(), urlStr); } public int CreateAuthor(AuthorInputModel author) { int nextId = DataContext.Authors.Max(x => x.Id) + 1; Author authorToAdd = Mapper.Map<Author>(author); authorToAdd.Id = nextId; DataContext.Authors.Add(authorToAdd); return nextId; } public void UpdateAuthorById(int id, AuthorInputModel author) { var authorToUpdate = DataContext.Authors.Where(x => x.Id == id).SingleOrDefault(); authorToUpdate.Name = author.Name; authorToUpdate.Bio = author.Bio; authorToUpdate.ProfileImgSource = author.ProfileImgSource; authorToUpdate.ModifiedBy = "authorMaker"; authorToUpdate.ModifiedDate = DateTime.Now; } public void DeleteAuthorById(int id) { // Set all news with this category to categoryId = 0. 0 = category unset. DataContext.NewsItems.Where(x => x.AuthorId == id).ToList().ForEach(x => x.AuthorId = 0); DataContext.Authors.RemoveAll(aut => aut.Id == id); } public Boolean LinkNewsItemToAuthorByIds(int authorId, int newsItemId) { Author author = DataContext.Authors.Where(x => x.Id == authorId).SingleOrDefault(); NewsItem newsItem = DataContext.NewsItems.Where(x => x.Id == newsItemId).SingleOrDefault(); if (author == null || newsItem == null) { return false; } DataContext.NewsItems.Where(x => x.Id == newsItemId).SingleOrDefault() .AuthorId = authorId; return true; } } }
using EntMob_Uni.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Jogging.Model; using Jogging.DAL; namespace Jogging.Test.Mocks { class MockUserService : IUserService { private IUserRepository userRepository = new MockUserRepository(); public Task<User> AddUser(User user) { throw new NotImplementedException(); } public Task<User> CheckCredentials(User user) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using birdepobenzin.dataaccess; namespace birdepobenzin.web.Controllers { public class SiteContentController : Controller { // // GET: /SiteContent/ public ActionResult Index(string rootUrl, string contentUrl) { birdepobenzin.dataaccess.Entities ents = new Entities(); string url = rootUrl; if (!string.IsNullOrEmpty(contentUrl)) { url += "/" + contentUrl; } CONTENT content = ents.CONTENT.FirstOrDefault(s=>s.Permalink == url && !s.IsDeleted); if (content == null) { return View("404"); } return View("Article", content); } public ActionResult ContentList() { birdepobenzin.dataaccess.Entities ents = new Entities(); return PartialView("ContentList", ents.CONTENT.Where(s => !s.IsDeleted).OrderByDescending(s=>s.CreDate).ToList()); } } }