text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; public class CreateBoulder : Creator { private bool isCreating; public float cooldown; // Spawning public float spawnDuration = 0.3f; private float spawnStart; private float lastSpawn; private Vector2 spawnDir; private Vector2 spawnPosition; public float jumpHeight = 10; public GameObject boulderPrefab; private GameObject lastBoulder; private Collider2D creatableCollider; float speed; // Start is called before the first frame update public UnityEvent OnCreateEvent; void Start() { speed = Controller2D.GetJumpSpeed(jumpHeight); } public void OnBoulder(InputAction.CallbackContext context) { return; switch (context.phase) { case InputActionPhase.Started: StartCreate(); break; case InputActionPhase.Canceled: StopCreate(); break; } } public void StartCreate() { if (lastBoulder) { Destroy(lastBoulder); //return; } if(Time.time - lastSpawn < cooldown) return; if(!create.canCreate) return; isCreating = false; //HOTFIX RaycastController.CollisionInfo collisionInfo = new RaycastController.CollisionInfo(); // Below if (RaycastController.HasFlag(collisionInfo.bottomWhiskers) && !isCreating) { Vector2 dir = Vector2.down * 1f; Create.CreatableHit creatableHit = create.RaycastHit(dir); if (creatableHit != null && creatableHit.creatable) { spawnDir = -dir; spawnPosition = creatableHit.hit.point; isCreating = true; creatableCollider = creatableHit.hit.collider; } } // Left if (RaycastController.HasFlag(collisionInfo.leftWhiskers)&& !isCreating) { Vector2 dir = Vector2.left * 1f; Create.CreatableHit creatableHit = create.RaycastHit(dir); if (creatableHit != null && creatableHit.creatable) { spawnDir = -dir; spawnPosition = creatableHit.hit.point; isCreating = true; creatableCollider = creatableHit.hit.collider; } } // Right if (RaycastController.HasFlag(collisionInfo.rightWhiskers) && !isCreating) { Vector2 dir = Vector2.right * 1f; Create.CreatableHit creatableHit = create.RaycastHit(dir); if (creatableHit != null && creatableHit.creatable) { spawnDir = -dir; spawnPosition = creatableHit.hit.point; isCreating = true; creatableCollider = creatableHit.hit.collider; } } // Above if (RaycastController.HasFlag(collisionInfo.topWhiskers) && !isCreating) { Vector2 dir = Vector2.up * 1f; Create.CreatableHit creatableHit = create.RaycastHit(dir); if (creatableHit != null && creatableHit.creatable) { spawnDir = -dir; spawnPosition = creatableHit.hit.point; isCreating = true; creatableCollider = creatableHit.hit.collider; } } if (isCreating) { spawnPosition -= spawnDir * boulderPrefab.transform.localScale.y * 0.5f; player.Freeze(); aimAssist.SetTargetArrowPosition(spawnPosition); aimAssist.SetTargetArrowDirection(spawnDir); aimAssist.ShowTargetArrow(); spawnStart = Time.time; } } public void Update() { if(isCreating) Creating(); } public void Creating() { float percent = 1; if (spawnDuration != 0) percent = (Time.time - spawnStart) / spawnDuration; percent = Mathf.Clamp01(percent); aimAssist.SetTargetArrowDirection(spawnDir.normalized * percent); if(percent>=1) StopCreate(); } public void StopCreate() { if(!isCreating) return; // Percent float percent = (Time.time - spawnStart) / spawnDuration; percent = Mathf.Clamp01(percent); if (percent <= 0.8f) { player.UnFreeze(); isCreating = false; aimAssist.HideTargetArrow(); return; } //Angle var dir = spawnDir; var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg + 90; //Create GameObject boulderObj = Instantiate(boulderPrefab, spawnPosition, Quaternion.Euler(0, 0, angle)); Boulder boulder = boulderObj.GetComponent<Boulder>(); boulder.speed = speed; boulder.Setup(creatableCollider,dir); //Effects EffectManager.CreateRockCreateEffect(spawnPosition, dir); CameraController.Shake(0.3f); // Size //boulder.transform.localScale = Vector3.one * 2f; OnCreateEvent?.Invoke(); lastBoulder = boulderObj; lastSpawn = Time.time; player.UnFreeze(); isCreating = false; aimAssist.HideTargetArrow(); } private void OnDrawGizmosSelected() { //Darker Green Gizmos.color = Color.Lerp(Create.debugColor, Color.black,0.3f); Vector2 spawnPos = (Vector2)transform.position + Create.debugOffset * 2; //Trail Gizmos.DrawLine(spawnPos, spawnPos + Vector2.up * jumpHeight); //Boulder Gizmos.DrawWireCube(spawnPos + Vector2.up * (1f), new Vector3(1, 2, 1)); //Player Gizmos.color = PlayerController.debugColor; Gizmos.DrawWireCube(spawnPos + Vector2.up * (jumpHeight + 0.5f), new Vector3(1, 1, 1)); } }
using Hayaa.BaseModel; using System; using System.Collections.Generic; using System.Text; namespace Hayaa.CompanyWebSecurity.Client.Model { [Serializable] internal class AppFunction : BaseData { public int AppFuntionId { set; get; } public int AppId { set; get; } public String FunctionName { set; get; } public String ClassFullName { set; get; } public String InterfaceFullName { set; get; } public String Remark { set; get; } public String WebApiPath { set; get; } public byte Status { set; get; } public int AppServiceId { set; get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SistemaFacturacionWeb { public partial class CambioClave : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e,string email) { string Label = email; if (email==null) { Label1.Text = "nulo"; Console.WriteLine("1"); } else { Label1.Text = "no null"; } } public string Email(string email) { Label1.Text = "X"; Console.WriteLine("2"); return ("Y"); } } }
using Framework.Core.Common; using Tests.Data.Van.Input; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace Tests.Pages.Van.Main.VirtualPhoneBankPages.VirtualPhoneBankDetailsPageComponents { public class TimeAndDateFieldsVpbDetailsPageComponent :VirtualPhoneBankDetailsPageComponent { private readonly Driver _driver; #region Element Declarations public IWebElement StartDateField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemDateToStart_VANInputItemDetailsItemDateToStart_DateToStart")); } } public IWebElement EndDateField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemDateToEnd_VANInputItemDetailsItemDateToEnd_DateToEnd")); } } public IWebElement TimeAvailableFromField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemvdiTimeRange_timeRange_timeFrom_timeFrom_timeText_tb_timeFrom_timeText")); } } public IWebElement TimeAvailableToField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemvdiTimeRange_timeRange_timeTo_timeTo_timeText_tb_timeTo_timeText")); } } public IWebElement TimeLimitField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemTimeLimit_VANInputItemDetailsItemTimeLimit_TimeLimit")); } } public IWebElement ContactLimitField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemContactLimit_VANInputItemDetailsItemContactLimit_ContactLimit")); } } public IWebElement ContactLimitDropdown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemContactLimit_VANInputItemContactLimitType_ContactLimitType")); } } #endregion public TimeAndDateFieldsVpbDetailsPageComponent(Driver driver) { _driver = driver; } public override void SetFields(VirtualPhoneBank vpb) { _driver.ClearAndSendKeysIfStringNotNullOrEmpty(StartDateField, vpb.StartDate); _driver.ClearAndSendKeysIfStringNotNullOrEmpty(EndDateField, vpb.EndDate); _driver.ClearAndSendKeysIfStringNotNullOrEmpty(TimeAvailableFromField, vpb.TimeAvailableFrom); _driver.ClearAndSendKeysIfStringNotNullOrEmpty(TimeAvailableToField, vpb.TimeAvailableTo); _driver.ClearAndSendKeysIfStringNotNullOrEmpty(TimeLimitField, vpb.TimeLimit); _driver.ClearAndSendKeysIfStringNotNullOrEmpty(ContactLimitField, vpb.ContactLimitNumber); _driver.SelectOptionByTextIfStringNotNullOrEmpty(ContactLimitDropdown, vpb.ContactLimitType); } public override bool Validate(VirtualPhoneBank vpb) { var errorCount = 0; if (!StartDateField.GetAttribute("value").Equals(vpb.StartDate)) { errorCount++; WriteVirtualPhoneBankValidationToConsole(StartDateField, vpb.StartDate, StartDateField.GetAttribute("value")); } if (!EndDateField.GetAttribute("value").Equals(vpb.EndDate)) { errorCount++; WriteVirtualPhoneBankValidationToConsole(EndDateField, vpb.EndDate, EndDateField.GetAttribute("value")); } if (!TimeAvailableFromField.GetAttribute("value").Equals(vpb.TimeAvailableFrom)) { errorCount++; WriteVirtualPhoneBankValidationToConsole(TimeAvailableFromField, vpb.TimeAvailableFrom, TimeAvailableFromField.GetAttribute("value")); } if (!TimeAvailableToField.GetAttribute("value").Equals(vpb.TimeAvailableTo)) { errorCount++; WriteVirtualPhoneBankValidationToConsole(TimeAvailableToField, vpb.TimeAvailableTo, TimeAvailableToField.GetAttribute("value")); } if (!TimeLimitField.GetAttribute("value").Equals(vpb.TimeLimit)) { errorCount++; WriteVirtualPhoneBankValidationToConsole(TimeLimitField, vpb.TimeLimit, TimeLimitField.GetAttribute("value")); } if (!ContactLimitField.GetAttribute("value").Equals(vpb.ContactLimitNumber)) { errorCount++; WriteVirtualPhoneBankValidationToConsole(ContactLimitField, vpb.ContactLimitNumber, ContactLimitField.GetAttribute("value")); } var contactLimitTypeText = new SelectElement(ContactLimitDropdown).SelectedOption.Text; if (!contactLimitTypeText.Equals(vpb.ContactLimitType)) { errorCount++; WriteVirtualPhoneBankValidationToConsole(ContactLimitDropdown, vpb.ContactLimitType, contactLimitTypeText); } return errorCount < 1; } } }
namespace BettingSystem.Application.Common { using System; using System.Reflection; using Behaviours; using Mapping; using MassTransit; using MediatR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Settings; public static class ApplicationConfiguration { public static IServiceCollection AddCommonApplication( this IServiceCollection services, IConfiguration configuration, Assembly assembly) => services .Configure<ApplicationSettings>( configuration.GetSection(nameof(ApplicationSettings)), options => options.BindNonPublicProperties = true) .AddMediatR(assembly) .AddAutoMapperProfile(assembly) .AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>)); public static IServiceCollection AddEventConsumers( this IServiceCollection services, Assembly assembly) => services .Scan(scan => scan .FromAssemblies(assembly) .AddClasses(classes => classes .AssignableTo(typeof(IConsumer<>))) .AsImplementedInterfaces() .WithTransientLifetime()); private static IServiceCollection AddAutoMapperProfile( this IServiceCollection services, Assembly assembly) => services .AddAutoMapper( (_, config) => config .AddProfile(new MappingProfile(assembly)), Array.Empty<Assembly>()); } }
using System; using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnostics.Windows.Configs; using BenchmarkDotNet.Running; using Microsoft.AspNetCore.Http; namespace CodingMilitia.PlayBall.WebFrontend.BackForFront.Benchmarks.ProxiedApiRouteEndpointLookup { public class Program { static void Main(string[] args) { DoSanityCheck(); var summary = BenchmarkRunner.Run<ProxiedApiRouteEndpointLookupBenchmark>(); } [RankColumn] [MemoryDiagnoser] //[InliningDiagnoser(logFailuresOnly: false)] //uncomment to see inlining results public class ProxiedApiRouteEndpointLookupBenchmark { [Params(10, 100, 1000)] public int MaxRoutes { get; set; } private PathString _path; private static Attempt01DictionaryPlusStringManipulation _attempt01; private static Attempt02ArrayIterationPlusPathBeginsWith _attempt02; private static Attempt03HashCodeBasedDoubleDictionaryPlusSpanManipulation _attempt03; private static Attempt04HashCodeBasedDictionaryWithComplexValuePlusSpanManipulation _attempt04; private static Attempt0504WithAggressiveInlining _attempt05; [GlobalSetup] public void Setup() { var routeMap = CreateRouteMap(MaxRoutes); _path = $"/route{MaxRoutes - 1}/some/more/things/in/the/path"; _attempt01 = new Attempt01DictionaryPlusStringManipulation(routeMap); _attempt02 = new Attempt02ArrayIterationPlusPathBeginsWith(routeMap); _attempt03 = new Attempt03HashCodeBasedDoubleDictionaryPlusSpanManipulation(routeMap); _attempt04 = new Attempt04HashCodeBasedDictionaryWithComplexValuePlusSpanManipulation(routeMap); _attempt05 = new Attempt0504WithAggressiveInlining(routeMap); } [Benchmark(Baseline = true)] public string Attempt01DictionaryPlusStringManipulation() { _attempt01.TryGet(_path, out var result); return result; } [Benchmark] public string Attempt02ArrayIterationPlusPathBeginsWith() { _attempt02.TryGet(_path, out var result); return result; } [Benchmark] public string Attempt03HashCodeBasedDoubleDictionaryPlusSpanManipulation() { _attempt03.TryGet(_path, out var result); return result; } [Benchmark] public string Attempt04HashCodeBasedDictionaryWithComplexValuePlusSpanManipulation() { _attempt04.TryGet(_path, out var result); return result; } [Benchmark] public string Attempt0504WithAggressiveInlining() { _attempt05.TryGet(_path, out var result); return result; } } private static void DoSanityCheck() { const int maxRoutes = 100; var route = $"/route{maxRoutes - 1}/some/more/things/in/the/path"; var routeMap = CreateRouteMap(maxRoutes); var results = typeof(Program) .Assembly .GetTypes() .Where(t => t.IsClass && typeof(IProxiedApiRouteEndpointLookup).IsAssignableFrom(t)) .ToDictionary( t => t.Name, t => { var lookup = t .GetConstructor(new[] {routeMap.GetType()}) .Invoke(new object[] {routeMap}) as IProxiedApiRouteEndpointLookup; return lookup.TryGet(route, out var endpoint) ? endpoint : null; }); var expectedEndpoint = $"route{maxRoutes - 1}endpoint"; if (results.Values.Any(r => r != expectedEndpoint)) { var wrongResults = string.Join(Environment.NewLine, results.Where(r => r.Value != expectedEndpoint).Select(r => $"{r.Key}: {r.Value}")); Console.WriteLine( $"The following lookups are not working correctly:{Environment.NewLine}{wrongResults}"); throw new Exception("Something's not right!"); } } private static Dictionary<string, string> CreateRouteMap(int maxRoutes) => Enumerable .Range(0, maxRoutes) .ToDictionary(i => $"route{i}", i => $"route{i}endpoint"); } }
using System.Collections.Generic; using System.Linq; using System.Text; namespace Euler_Logic.Problems.AdventOfCode.Y2016 { public class Problem14 : AdventOfCodeBase { public override string ProblemName => "Advent of Code 2016: 14"; public override string GetAnswer() { return Answer1("yjdafjpo").ToString(); } public override string GetAnswer2() { return Answer2("yjdafjpo").ToString(); } private int Answer1(string input) { return Find64(input, false); } private int Answer2(string input) { return Find64(input, true); } private int Find64(string input, bool additionalLoop) { int keyNum = 0; var looking = new List<LookingFor>(); var completed = new List<LookingFor>(); do { string key = GetMD5(input + keyNum.ToString()); if (additionalLoop) { for (int count = 1; count <= 2016; count++) { key = GetMD5(key); } } bool doneWith3 = false; for (int index = 0; index < key.Length - 2; index++) { if (key[index] == key[index + 1] && key[index] == key[index + 2]) { if (!doneWith3) { doneWith3 = true; looking.Add(new LookingFor() { DigitToFind = key[index], StartNum = keyNum }); } if (index < key.Length - 5 && key[index] == key[index + 3] && key[index] == key[index + 4]) { for (int lookIndex = 0; lookIndex < looking.Count; lookIndex++) { var nextLooking = looking[lookIndex]; if (keyNum - nextLooking.StartNum > 1000) { looking.RemoveAt(lookIndex); lookIndex--; } else if (nextLooking.DigitToFind == key[index] && nextLooking.StartNum != keyNum) { completed.Add(nextLooking); completed = completed.OrderBy(x => x.StartNum).ToList(); nextLooking.EndNum = keyNum; looking.RemoveAt(lookIndex); lookIndex--; } } } } } keyNum++; } while (completed.Count < 64 || keyNum > 1000 + completed[63].StartNum); return completed.OrderBy(x => x.StartNum).ElementAt(63).StartNum; } private string GetMD5(string key) { using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create()) { byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(key); byte[] hashBytes = md5.ComputeHash(inputBytes); // Convert the byte array to hexadecimal string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sb.Append(hashBytes[i].ToString("X2").ToLower()); } return sb.ToString(); } } private class LookingFor { public int StartNum { get; set; } public int EndNum { get; set; } public char DigitToFind { get; set; } } } }
using Cafe.API.Data; using Cafe.API.Models.Entities; using Cafe.API.Models.Repository; using System; using System.Collections.Generic; using System.Linq; namespace Cafe.API.Models.DataManager { public class ClientDataManager: IDataRepository<Client> { readonly CafeDbContext _context; public ClientDataManager(CafeDbContext context) { this._context = context; } public Client GetLast() { return _context.Clients .Where(x => x.IsHungry == true) .OrderBy(x => x.TimeOfComing) .First(); //return _context.Clients.Last(); } public IEnumerable<Client> GetAll() { return _context.Clients; } public Client Get(int id) { var client = _context.Clients.Find(id); return client; } public void Add(Client client) { client.TimeOfComing = DateTime.Now; _context.Clients.Add(client); _context.SaveChanges(); } public void Update(Client clientToUpdate, Client client) { clientToUpdate.Name = client.Name; clientToUpdate.SecondName = client.SecondName; clientToUpdate.Age = client.Age; clientToUpdate.IsHungry = client.IsHungry; clientToUpdate.TimeOfComing = client.TimeOfComing; _context.SaveChanges(); } public void Delete(Client client) { _context.Remove(client); _context.SaveChanges(); } public IEnumerable<Client> GetSales(int clientId) { return _context.Clients; } public int Count() { return _context.Clients.Count(); } } }
using System; using Autofac; using Framework.Core.Common; using Tests.Data.Van; using Tests.Data.Van.Input.Filters; using Tests.Pages.Van.LogIn; using Tests.Pages.Van.Main.Common.DefaultPage; using Tests.Pages.Van.Main.List; using Tests.Pages.Van.Main.Turf; using NUnit.Framework; namespace Tests.Projects.Van.TurfManagementTests.TurfTests { public class EditTurf : BaseTest { #region Test Pages private LoginPage LogInPage { get { return Scope.Resolve<LoginPage>(); } } private VoterDefaultPage HomePage { get { return Scope.Resolve<VoterDefaultPage>(); } } private TurfListPage TurfListPage { get { return Scope.Resolve<TurfListPage>(); } } private SaveListSearchDetailsPage SaveListSearchDetailsPage { get { return Scope.Resolve<SaveListSearchDetailsPage>();} } #endregion #region Test Case Data #region TestCase: Edit Single Turf private static readonly VanTestUser User1 = new VanTestUser { UserName = "TurfTester7", Password = "@uT0Te$t7InG2" }; private static readonly TurfListPageFilter Filter1 = new TurfListPageFilter { Name = "Test_Region3 Turf 09" }; private static readonly string NewDescription1 = String.Format("Description_{0}", DateTimeData.CurrentSortableTime()); #endregion private static readonly object[] TestData = { new object[] { User1, Filter1, NewDescription1 } }; #endregion /// <summary> /// Tests the functionality of the Edit Turf feature for a single Turf. /// Opens the SaveListSerchDetails page for a single Turf by clicking the Edit Turf link. /// Then changes and saves a new description. /// Finally, validates that the description was updated. /// </summary> [Test, TestCaseSource("TestData")] [Category("van"), Category("van_smoketest"), Category("van_turfmanagement")] public void EditTurfTest(VanTestUser user, TurfListPageFilter filter, string newDescription) { LogInPage.Login(user); HomePage.ClickMyTurfsLink(); TurfListPage.ClickResultsGridIcon("Edit Turf", filter); SaveListSearchDetailsPage.ChangeDescription(newDescription); TurfListPage.ClickResultsGridIcon("Edit Turf", filter); Assert.That(SaveListSearchDetailsPage.ValidateDescription(newDescription), Is.True, "The Description Field on the SaveListSearchDetails page was not updated correctly"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chest : MonoBehaviour { [SerializeField] private Sprite opened; private GameObject diamond; public GameObject spawnItemPrefab; public Transform transformObj; private bool isOpened = false; private void Start() { //diamond.SetActive(false); } private void OnTriggerStay2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { if (!isOpened) { Debug.Log("Player touched me.. (" + gameObject.name + ")"); if (Input.GetKeyDown(KeyCode.E)) { isOpened = true; Debug.LogError("Spawning"); this.gameObject.GetComponent<SpriteRenderer>().sprite = opened; diamond = GameObject.Instantiate(spawnItemPrefab, this.transform.position, this.transform.rotation); diamond.transform.position = transformObj.position; //diamond.SetActive(true); } } } } public void OpenChest() { isOpened = true; Debug.LogError("Spawning"); this.gameObject.GetComponent<SpriteRenderer>().sprite = opened; diamond = GameObject.Instantiate(spawnItemPrefab, this.transform.position, this.transform.rotation); diamond.transform.position = transformObj.position; } }
namespace KRFTemplateApi.Domain.CQRS.Sample.Query { using KRFCommon.CQRS.Query; public class SampleInput : IQueryRequest { } }
using System; using System.Diagnostics; namespace Leprechaun.Model { [DebuggerDisplay("{Path} ({Id})")] public class TemplateInfo { public string Path { get; set; } public Guid Id { get; set; } public string Name { get; set; } public string HelpText { get; set; } public Guid[] BaseTemplateIds { get; set; } public TemplateFieldInfo[] OwnFields { get; set; } } }
using Android.App; using Android.OS; using Android.Runtime; using Caliburn.Micro; using Plugin.CurrentActivity; using System; using System.Collections.Generic; using System.Reflection; namespace RRExpress.Droid { [Application(LargeHeap = true)] [MetaData("JPUSH_CHANNEL", Value = "developer-default")] [MetaData("JPUSH_APPKEY", Value = "8050b214eadc221a5ad3c161")]//APPKEY public class Application : CaliburnApplication, Android.App.Application.IActivityLifecycleCallbacks { private SimpleContainer container; public Application(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { //TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; } void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { } void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e) { //线程取消异常, 不好捕捉,在这里可以处理掉. //System.Threading.Tasks.TaskCanceledException: A task was canceled. e.Handled = true; } public override void OnCreate() { base.OnCreate(); Initialize(); RegisterActivityLifecycleCallbacks(this); } public override void OnTerminate() { base.OnTerminate(); UnregisterActivityLifecycleCallbacks(this); } /// <summary> /// 用于加载不同DLL内的View /// </summary> protected override void StartRuntime() { base.StartRuntime(); var asms = App.UsedAssemblies; foreach (var asm in asms) { if (!AssemblySource.Instance.Contains(asm)) { AssemblySource.Instance.Add(asm); } } } protected override void Configure() { container = new SimpleContainer(); container.Instance(container); // https://github.com/Caliburn-Micro/Caliburn.Micro/issues/298 container.Singleton<App>(); } protected override IEnumerable<Assembly> SelectAssemblies() { return new[] { GetType().Assembly, typeof (App).Assembly }; } protected override void BuildUp(object instance) { container.BuildUp(instance); } protected override IEnumerable<object> GetAllInstances(Type service) { return container.GetAllInstances(service); } protected override object GetInstance(Type service, string key) { return container.GetInstance(service, key); } public void OnActivityCreated(Activity activity, Bundle savedInstanceState) { CrossCurrentActivity.Current.Activity = activity; } public void OnActivityDestroyed(Activity activity) { } public void OnActivityPaused(Activity activity) { } public void OnActivityResumed(Activity activity) { CrossCurrentActivity.Current.Activity = activity; } public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { } public void OnActivityStarted(Activity activity) { CrossCurrentActivity.Current.Activity = activity; } public void OnActivityStopped(Activity activity) { } } }
using System.ComponentModel.DataAnnotations; namespace SciVacancies.WebApp.ViewModels { /// <summary> /// членство в профессиональных сообществах /// </summary> public class MembershipDetailsViewModel : MembershipEditViewModel { } /// <summary> /// членство в профессиональных сообществах /// </summary> public class MembershipEditViewModel { [MaxLength(1500, ErrorMessage = "ƒлина строки не более 1500 символов")] public string org { get; set; } [MaxLength(1500, ErrorMessage = "ƒлина строки не более 1500 символов")] public string position { get; set; } //public DateTime updated { get; set; } public int year_from { get; set; } public int year_to { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; #if UNITY_EDITOR using UnityEditor; #endif namespace BanSupport { public static partial class Tools { #region 时间相关 public static System.Diagnostics.Stopwatch StartWatch() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); return stopwatch; } public static double StopWatch(System.Diagnostics.Stopwatch watch) { watch.Stop(); return watch.Elapsed.TotalMilliseconds; } /// <summary> /// 把总秒转化为时分秒 /// </summary> public static void TransSecondsToHoursMinutesSeconds(uint totalSeconds, out uint hours, out uint minutes, out uint seconds) { seconds = totalSeconds % 60; totalSeconds /= 60; minutes = totalSeconds % 60; totalSeconds /= 60; hours = totalSeconds; } /// <summary> /// 以秒作为单位 /// </summary> public static long GetUnixStamp() { return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; } /// <summary> /// 到每天的几点多少秒 /// </summary> public static uint GetSecondsFromWantHour(int wantHour) { var now = System.DateTime.Now; var year = now.Year; var month = now.Month; var day = now.Day; var wantTime = new System.DateTime(year, month, day, wantHour, 0, 0); var offset = (wantTime - now).Ticks; Debug.Log("offset :" + offset); if (offset >= 0) { return (uint)(offset / 10000000); } else { return (uint)(offset / 10000000 + (24 * 60 * 60)); } } #endregion #region UI坐标相关 //WorldPos:世界坐标 //UIPos:在UI层的世界坐标 //ScreenPos:屏幕坐标 //AnchoredPos:锚点坐标 public static Vector3 GetUIPosByScreenPos(Vector2 screenPos, Canvas canvas) { Vector3 UIPos; RectTransformUtility.ScreenPointToWorldPointInRectangle( canvas.transform as RectTransform, screenPos, canvas.worldCamera, out UIPos); return UIPos; } public static Vector3 GetUIPosByWorldPos(Vector3 worldPos, Canvas canvas, Camera worldCamera) { Vector3 screenPos = worldCamera.WorldToScreenPoint(worldPos); return GetUIPosByScreenPos(screenPos, canvas); } public static Vector3 GetUIPosByAnchoredPos(RectTransform rectTransform, Vector2 anchoredPosition, Vector2 anchors) { return new Vector3( ((-rectTransform.pivot.x + anchors.x) * rectTransform.rect.width + anchoredPosition.x) * rectTransform.lossyScale.x + rectTransform.position.x, ((1 - rectTransform.pivot.y - (1 - anchors.y)) * rectTransform.rect.height + anchoredPosition.y) * rectTransform.lossyScale.y + rectTransform.position.y, rectTransform.position.z); } public static Vector2 GetAnchoredPosByUIPos(RectTransform rectTransform, Vector3 uiPos, Vector2 anchors) { return new Vector2( (uiPos.x - rectTransform.position.x) / rectTransform.lossyScale.x + (rectTransform.pivot.x - anchors.x) * rectTransform.rect.width, (uiPos.y - rectTransform.position.y) / rectTransform.lossyScale.y + (rectTransform.pivot.y - anchors.y) * rectTransform.rect.height); } #endregion #region 2D计算相关 /// <summary> /// 是否使用弧度制,默认不使用 /// angle是否在from到to的这段 /// </summary> public static bool IsBetweenAngle(float angle, float from, float to, bool useArcOrNot = false) { FormatAngle(from, ref to, useArcOrNot); FormatAngle(from, ref angle, useArcOrNot); return angle >= from && angle <= to; } /// <summary> /// 根据From来标准化To,To永远只会比From大,但是不会超过一圈 /// </summary> public static void FormatAngle(float from, ref float to, bool useArcOrNot = false) { float addAmount; if (useArcOrNot) { addAmount = 2 * Mathf.PI; } else { addAmount = 360; } var minus = (to - from) / addAmount; if (minus < 0) { to += Mathf.CeilToInt(-minus) * addAmount; } else if (minus > 1) { to -= (int)minus * addAmount; } } public static float GetAngle2D(Vector3 center, Vector3 target) { return GetAngle2D(center.x, center.y, target.x, target.y); } public static float GetAngle2D(float centerX, float centerY, float targetX, float targetY) { var returnAngle = Mathf.Atan2(targetX - centerX, targetY - centerY) * 180 / Mathf.PI; if (returnAngle < 0) { returnAngle += 360; } return returnAngle; } /// <summary> /// 获得2D线段的长度 /// </summary> public static float GetLineMagnitude2D(float x1, float y1, float x2, float y2) { return Mathf.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } /// <summary> /// 获得2D环境下围绕点(x1,y1)旋转,使得跟随该点旋转的点(x2,y2)向量(a,b),可以指向目标点(x3,y3)所需的旋转角度 /// </summary> public static float GetRotateShootAngle2D(float x1, float y1, float x2, float y2, float a, float b, float x3, float y3) { float rotateAngle = 0; float crossX, crossY; GetPointVerticalCrossToLine2D(x1, y1, x2, y2, a, b, out crossX, out crossY); float dist1 = GetLineMagnitude2D(crossX, crossY, x1, y1); float dist2 = GetLineMagnitude2D(x1, y1, x3, y3); var angle1 = GetTriangleAngleAB_AC(GetLineMagnitude2D(crossX, crossY, x3, y3), dist1, dist2); if (dist1 < dist2) { var angle2 = Mathf.Acos(dist1 / dist2) * 180 / Mathf.PI; int leftOrRight = GetPointPlaceLineLeftOrRight2D(x1, y1, crossX, crossY, a, b); rotateAngle = leftOrRight * (angle1 - angle2); } else { int leftOrRight = GetPointPlaceLineLeftOrRight2D(x3, y3, x1, y1, crossX - x1, crossY - y1); rotateAngle = leftOrRight * angle1; } return rotateAngle; } /// <summary> /// 获得2D环境下点(x,y)距离直线的(x1,y1) 向量(a,b)的距离 /// </summary> public static float GetPointDistanceToLine2D(float x, float y, float x1, float y1, float a, float b) { return (b * x - a * y + a * y1 - b * x1) / Mathf.Sqrt(a * a + b * b); } /// <summary> /// 获得2D环境下点(x,y)距离直线的(x1,y1) 向量(a,b)左侧还是右侧 /// </summary> public static int GetPointPlaceLineLeftOrRight2D(float x, float y, float x1, float y1, float a, float b) { return (int)Mathf.Sign(b * x - a * y + a * y1 - b * x1); } /// <summary> /// 获得2D环境下的,点(x,y)到直线(x1,y1)向量(a,b)的垂线交点坐标 /// </summary> public static void GetPointVerticalCrossToLine2D(float x, float y, float x1, float y1, float a, float b, out float crossX, out float crossY) { //float c = a * y2 - b * x2; //crossX = (a * a * x1 + a * b * y1 - b * c) / (a * a + b * b); //crossY = (b * crossX + c) / a; //第二种方法 var distance = GetPointDistanceToLine2D(x, y, x1, y1, a, b); var c = Mathf.Sqrt(a * a + b * b); crossX = x + -b / c * distance; crossY = y + a / c * distance; } /// <summary> /// 获得直线与圆的相交点 /// </summary> public static Vector2 GetLineCrossCirclePos2D(float x1, float y1, float a_by_c, float b_by_c, float radius, float circleX, float circleY) { float crossX, crossY; GetPointVerticalCrossToLine2D(circleX, circleY, x1, y1, a_by_c, b_by_c, out crossX, out crossY); var distance = Mathf.Sqrt(radius * radius - (crossX - circleX) * (crossX - circleX) - (crossY - circleY) * (crossY - circleY)); return new Vector2(crossX + a_by_c * distance, crossY + b_by_c * distance); } #endregion #region Transform Vector Quaternion相关 /// <summary> /// 过该点并且与平面XZ相垂直的相交点 /// </summary> public static bool GetPosFromLineCrossPlane(Vector3 pos, Transform planeTrans, out Vector3 crossPos) { return GetPosFromLineCrossPlane(pos, planeTrans.up, planeTrans.position, planeTrans.up, out crossPos); } /// <summary> /// 点与平面的垂直点 /// </summary> public static bool GetPosFromLineCrossPlane(Vector3 linePos, Vector3 lineDir, Vector3 planePos, Vector3 planeNormal, out Vector3 crossPos) { float a, b, c; float a2, b2, c2; float a3, b3, c3; float a4, b4, c4; a = linePos.x; b = linePos.y; c = linePos.z; a2 = lineDir.x; b2 = lineDir.y; c2 = lineDir.z; a3 = planePos.x; b3 = planePos.y; c3 = planePos.z; a4 = planeNormal.x; b4 = planeNormal.y; c4 = planeNormal.z; float param = a2 * a4 + b2 * b4 + c2 * c4; if (param > 0 || param > 0) { float n = (-a * a4 + a3 * a4 - b * b4 + b3 * b4 - c * c4 + c3 * c4) / param; crossPos = linePos + lineDir * n; return true; } else { crossPos = Vector3.zero; return false; } } /// <summary> /// 获得为了让子物体curTrans保持在某角度时所需的父物体targetTrans角度 /// </summary> public static Quaternion GetInvserseRotation(Transform curTrans, Transform targetTrans) { var returnRotation = Quaternion.identity; while (curTrans != targetTrans) { returnRotation = returnRotation * Quaternion.Inverse(curTrans.localRotation); curTrans = curTrans.parent; } return returnRotation; } /// <summary> /// 在XZ平面下返回一个从Dir2旋转到Dir1所需的旋转角度 /// </summary> /// <param name="dir1">目标角度</param> /// <param name="dir2">当前角度</param> /// <returns></returns> public static bool GetRotateAngleFromDir2ToDir1XZ(Vector3 dir1, Vector3 dir2, out float angle) { dir1.y = 0; dir2.y = 0; if (Vector3.SqrMagnitude(dir1 - dir2) > 0) { angle = Vector3.Angle(dir1, dir2) * (Vector3.Cross(dir1, dir2).y > 0 ? -1 : 1); return true; } else { angle = 0; return false; } } /// <summary> /// 得到三角形AB,AC的夹角 /// </summary> public static float GetTriangleAngleAB_AC(Vector3 A, Vector3 B, Vector3 C) { return GetTriangleAngleAB_AC(Vector3.Distance(B, C), Vector3.Distance(A, C), Vector3.Distance(A, B)); } /// <summary> /// 得到三角形AB,AC的夹角 /// </summary> public static float GetTriangleAngleAB_AC(float a, float b, float c) { var cosValue = (b * b + c * c - a * a) / (2 * b * c); if (cosValue >= 1) { return 0; } else { return Mathf.Acos(cosValue) * 180 / Mathf.PI; } } /// <summary> /// 根据摇杆的输入值以及当前摄像机的位置方向,得到理想的世界方向 /// </summary> public static Vector3 GetWorldDir(Vector2 v2) { return GetWorldDir(v2.x, v2.y); } /// <summary> /// 根据摇杆的输入值以及主摄像机的位置方向,得到理想的世界方向 /// </summary> /// <param name="x">摇杆水平值</param> /// <param name="y">摇杆垂直值</param> /// <returns></returns> public static Vector3 GetWorldDir(float x, float y) { var forwardDir = Vector3.Scale(Camera.main.transform.forward, new Vector3(1, 0, 1)); var rightDir = Vector3.Cross(forwardDir, Vector3.down); var wantDir = forwardDir * y + rightDir * x; return wantDir.normalized; } #endregion #region Draw相关 /// <summary> /// Gizmos画出一个BoxCollider /// </summary> public static void GizmosDrawBoxCollider(BoxCollider boxCollider) { var transform = boxCollider.transform; var oldMatrix = Gizmos.matrix; Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, (transform.lossyScale)); Gizmos.DrawCube(Vector3.zero + boxCollider.center, boxCollider.size); Gizmos.matrix = oldMatrix; } /// <summary> /// Gizmos画出一个BoxCollider /// </summary> public static void GizmosDrawBoxCollider(BoxCollider boxCollider, Color color) { var transform = boxCollider.transform; var oldColor = Gizmos.color; var oldMatrix = Gizmos.matrix; Gizmos.color = color; Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, (transform.lossyScale)); Gizmos.DrawCube(Vector3.zero + boxCollider.center, boxCollider.size); Gizmos.matrix = oldMatrix; Gizmos.color = oldColor; } /// <summary> /// Gizmos画出一个交叉点 /// </summary> public static void GizmosDrawCrossPoint(Vector3 pos, float size, Color color) { var oldColor = Gizmos.color; Gizmos.color = color; Gizmos.DrawLine(pos + Vector3.left * size, pos + Vector3.right * size); Gizmos.DrawLine(pos + Vector3.up * size, pos + Vector3.down * size); Gizmos.DrawLine(pos + Vector3.forward * size, pos + Vector3.back * size); Gizmos.color = oldColor; } /// <summary> /// 用于绘制角色骨骼信息 /// </summary> public static void GizmosDrawBone(Transform rootTrans, List<Transform> ignoreTrans = null) { var trans = rootTrans.GetComponentsInChildren<Transform>(); for (int i = 0; i < trans.Length; i++) { if (ignoreTrans != null && (ignoreTrans.Contains(trans[i]) || ignoreTrans.Contains(trans[i].parent))) { continue; } //Debug.Log(trans[i].name + " :" + trans[i].parent); GizmosDrawRectangle(trans[i].position, trans[i].parent.position); } } /// <summary> /// 画出一个长方体,以pos1 pos2作为首尾点,默认为红色 /// </summary> public static void GizmosDrawRectangle(Vector3 pos1, Vector3 pos2, float radius = 0.02f) { var oldMatrix = Gizmos.matrix; var oldColor = Gizmos.color; Gizmos.color = new Color(1, 0, 0, 0.5f); var distance = Vector3.Distance(pos1, pos2); if (distance > 0.001f) { Gizmos.matrix = Matrix4x4.TRS((pos1 + pos2) / 2, Quaternion.LookRotation(pos2 - pos1), Vector3.one); Gizmos.DrawCube(Vector3.zero, new Vector3(radius, radius, distance)); } Gizmos.matrix = oldMatrix; Gizmos.color = oldColor; } /// <summary> /// Debug.DrawLine画出一个交叉点 /// </summary> public static void DrawCrossPoint(Vector3 pos, float size, Color color, float during = 0) { if (during < 0) { Debug.DrawLine(pos + Vector3.left * size, pos + Vector3.right * size, color); Debug.DrawLine(pos + Vector3.up * size, pos + Vector3.down * size, color); Debug.DrawLine(pos + Vector3.forward * size, pos + Vector3.back * size, color); } else { Debug.DrawLine(pos + Vector3.left * size, pos + Vector3.right * size, color, during); Debug.DrawLine(pos + Vector3.up * size, pos + Vector3.down * size, color, during); Debug.DrawLine(pos + Vector3.forward * size, pos + Vector3.back * size, color, during); } } #endregion #region String操作 /// <summary> /// 返回带颜色的String /// </summary> public static string GetRichStr(string str, Color color) { var colorStr = ColorUtility.ToHtmlStringRGB(color); return string.Format("<color=#{0}>{1}</color>", colorStr, str); } /// <summary> /// 返回一个str的repeat /// </summary> public static string GetRepeatStr(string str, int repeatCount) { string resultStr = ""; for (int i = 0; i < repeatCount; i++) { resultStr += str; } return resultStr; } /// <summary> /// 用于在Debug中使用 /// color 必须为 #000000 格式 /// </summary> public static string GetRichText(string str, string color) { return string.Format("<color={0}>{1}</color>", color, str); } /// <summary> /// 得到一个uint数组的字符串 /// </summary> public static string GetArrayText(uint[] array) { if (array == null) { return "null"; } string returnStr = "["; for (int i = 0; i < array.Length; i++) { returnStr += array[i] + ","; } if (array.Length > 0) { returnStr = returnStr.Substring(0, returnStr.Length - 1); } return returnStr + "]"; } #endregion #region WorldText private static Transform _WorldTextTrans; private static Transform WorldTextTrans { get { if (_WorldTextTrans == null) { _WorldTextTrans = new GameObject("WorldText").transform; } return _WorldTextTrans; } } public static TextMesh CreateWorldText(string str, Vector3 position, int fontSize = 40) { var textMesh = new GameObject(WorldTextTrans.childCount.ToString()).AddComponent<TextMesh>(); textMesh.anchor = TextAnchor.MiddleCenter; textMesh.transform.SetParent(WorldTextTrans); textMesh.transform.position = position; textMesh.fontSize = fontSize; textMesh.text = str; return textMesh; } #endregion #region Others public static bool AddComponent<T>(GameObject go, out T t) where T : Component { t = go.GetComponent<T>(); if (t == null) { t = go.AddComponent<T>(); return true; } else { return false; } } public static bool AddComponent<T>(GameObject go) where T : Component { var t = go.GetComponent<T>(); if (t == null) { go.AddComponent<T>(); return true; } else { return false; } } public static bool RemoveComponent<T>(GameObject go) where T : Component { var t = go.GetComponent<T>(); if (t != null) { if (Application.isPlaying) { GameObject.Destroy(t); } else { GameObject.DestroyImmediate(t); } return true; } else { return false; } } /// <summary> /// Vector3直接打印出来精度不高,故使用本方法 /// </summary> public static void PrintVector3(Vector3 v3) { Debug.Log(v3.x.ToString("0.00000") + " y:" + v3.y.ToString("0.00000") + " z:" + v3.z.ToString("0.00000")); } #endregion #region Scene public static void ReloadScene() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public static void LoadScene(string sceneName) { SceneManager.LoadScene(sceneName); } #endregion public static GameObject CreateObj(GameObject prefab, Transform trans) { return GameObject.Instantiate<GameObject>(prefab, trans.position, Quaternion.identity, trans); } public static GameObject CreateObj(GameObject prefab, Transform trans, Vector3 position) { return GameObject.Instantiate<GameObject>(prefab, position, Quaternion.identity, trans); } public static Vector3 GetRandomCirclePos(Vector3 originPos, float maxRadius) { var random = UnityEngine.Random.insideUnitCircle; var finalPos = new Vector3(random.x * maxRadius, 0, random.y * maxRadius) + originPos; return finalPos; } public static Vector3 GetRandomCirclePos(Vector3 originPos, float minRadius, float maxRadius) { float radius = UnityEngine.Random.Range(minRadius, maxRadius); float angle = UnityEngine.Random.Range(0, Mathf.PI * 2); var finalPos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius + originPos; return finalPos; } public static void GetDeviceWidthAndHeight(out int width, out int height) { #if UNITY_EDITOR System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor"); System.Reflection.MethodInfo GetMainGameView = T.GetMethod("GetMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); object Res = GetMainGameView.Invoke(null, null); var gameView = (UnityEditor.EditorWindow)Res; var prop = gameView.GetType().GetProperty("currentGameViewSize", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var gvsize = prop.GetValue(gameView, new object[0] { }); var gvSizeType = gvsize.GetType(); height = (int)gvSizeType.GetProperty("height", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).GetValue(gvsize, new object[0] { }); width = (int)gvSizeType.GetProperty("width", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).GetValue(gvsize, new object[0] { }); #else width = Screen.width; height = Screen.height; #endif } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; namespace DAL.Contracts { public class Repository<T> : IRepository<T> where T : class { protected readonly DbContext Context; public Repository(DbContext ctx) { Context = ctx; } protected DbSet<T> DbSet => Context.Set<T>(); public int Count => DbSet.Count(); public virtual IEnumerable<T> All() { return DbSet.AsEnumerable(); } public bool Contains(Expression<Func<T, bool>> predicate) { return DbSet.Count(predicate) > 0; } public virtual T Create(T t) { var newEntry = DbSet.Add(t); return newEntry; } public virtual void Delete(T t) { DbSet.Remove(t); } public virtual int Delete(Expression<Func<T, bool>> predicate) { var remObjects = Filter(predicate); DbSet.RemoveRange(remObjects); return remObjects.Count(); } public void Dispose() { throw new NotImplementedException(); } public virtual IEnumerable<T> Filter(Expression<Func<T, bool>> predicate) { return DbSet.Where(predicate); } public virtual IEnumerable<T> Filter<TKey>(Expression<Func<T, bool>> filter, out int total, int index = 0, int size = 50) { int skipCount = index * size; var resetSet = filter != null ? DbSet.Where(filter).AsQueryable() : DbSet.AsQueryable(); resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size); total = resetSet.Count(); return resetSet.AsQueryable(); } public virtual T Find(params object[] keys) { return DbSet.Find(keys); } public virtual T Find(Expression<Func<T, bool>> predicate) { return DbSet.FirstOrDefault(predicate); } public virtual int Update(T t) { var entry = Context.Entry(t); DbSet.Attach(t); entry.State = EntityState.Modified; return 1; } public IEnumerable<T> CreateRange(IEnumerable<T> entities) { foreach (var item in entities) { var entry = Context.Entry(item); DbSet.Attach(item); entry.State = EntityState.Modified; } return entities; //should be modified by ref } } }
using System; using System.Collections.Generic; class AverageLoadTimeCalculator { static void Main() { Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!"); while (true) { Console.WriteLine("Enter line, for end pres ENTER :"); Dictionary<string,double> dUrlTime = new Dictionary<string, double>(); Dictionary<string,uint> dUrlCount = new Dictionary<string, uint>(); string sTmpStr = Console.ReadLine(); while (sTmpStr != string.Empty) { string[] aTmpStr = sTmpStr.Split(' '); string sURL = aTmpStr[2]; double dTime = double.Parse(aTmpStr[3]); if (!dUrlTime.ContainsKey(sURL)) { dUrlTime[sURL] = dTime; dUrlCount[sURL] = 1; } else { dUrlCount[sURL]++; dUrlTime[sURL] = dUrlTime[sURL] + dTime; } Console.WriteLine("Enter line, for end pres ENTER :"); sTmpStr = Console.ReadLine(); } foreach (string sUrl in dUrlTime.Keys) { Console.WriteLine("{0} -> {1}",sUrl,dUrlTime[sUrl]/dUrlCount[sUrl]); } } } }
using Models; namespace DataAccesLayer.Repositories { public interface IKategoriRepository<T> : IRepository<T> where T : Kategori { } }
namespace ClusteringDemo { using System; using System.Collections.Generic; using System.Linq; using System.Numerics; class Program { static void Main(string[] args) { //k-Means clustering with 3 centroids //randomly assign all data items to a cluster //loop until no change in cluster assignments // compute centroids for each cluster // reassign each data item to cluster of closest centroid //end //Expected results { 67.3, 97.0 }, { 74.0, 77.1 }, { 61.3, 57.5 } } private static List<Vector2> GetRawData() { return new List<Vector2> { new Vector2(73, 72.6f), new Vector2(61, 54.4f), new Vector2(67, 99.9f), new Vector2(68, 97.3f), new Vector2(62, 59.0f), new Vector2(75, 81.6f), new Vector2(74, 77.1f), new Vector2(66, 97.3f), new Vector2(68, 93.3f), new Vector2(61, 59.0f) }; } private static Vector2 CalculateCentroid(List<Vector2> items) { var result = items.Aggregate(Vector2.Zero, (current, point) => current + point); result /= items.Count; return result; } private static int[] GetRandomStart() { var rand = new Random(); var rtnlist = new List<int>(); for (int i = 0; i < 10; i++) { rtnlist.Add(rand.Next(3)); } return rtnlist.ToArray(); } } }
namespace Sentry; /// <summary> /// The Data Source Name of a given project in Sentry. /// </summary> /// <remarks> /// <see href="https://develop.sentry.dev/sdk/overview/#parsing-the-dsn"/> /// </remarks> internal sealed class Dsn { /// <summary> /// Source DSN string. /// </summary> public string Source { get; } /// <summary> /// The project ID which the authenticated user is bound to. /// </summary> public string ProjectId { get; } /// <summary> /// An optional path of which Sentry is hosted. /// </summary> public string? Path { get; } /// <summary> /// The optional secret key to authenticate the SDK. /// </summary> public string? SecretKey { get; } /// <summary> /// The required public key to authenticate the SDK. /// </summary> public string PublicKey { get; } /// <summary> /// Sentry API's base URI. /// </summary> private Uri ApiBaseUri { get; } private Dsn( string source, string projectId, string? path, string? secretKey, string publicKey, Uri apiBaseUri) { Source = source; ProjectId = projectId; Path = path; SecretKey = secretKey; PublicKey = publicKey; ApiBaseUri = apiBaseUri; } public Uri GetStoreEndpointUri() => new(ApiBaseUri, "store/"); public Uri GetEnvelopeEndpointUri() => new(ApiBaseUri, "envelope/"); public override string ToString() => Source; public static bool IsDisabled(string? dsn) => Constants.DisableSdkDsnValue.Equals(dsn, StringComparison.OrdinalIgnoreCase); public static Dsn Parse(string dsn) { var uri = new Uri(dsn); // uri.UserInfo returns empty string instead of null when no user info data is provided if (string.IsNullOrWhiteSpace(uri.UserInfo)) { throw new ArgumentException("Invalid DSN: No public key provided."); } var keys = uri.UserInfo.Split(':'); var publicKey = keys[0]; if (string.IsNullOrWhiteSpace(publicKey)) { throw new ArgumentException("Invalid DSN: No public key provided."); } var secretKey = keys.Length > 1 ? keys[1] : null; var path = uri.AbsolutePath[..uri.AbsolutePath.LastIndexOf('/')]; var projectId = uri.AbsoluteUri[(uri.AbsoluteUri.LastIndexOf('/') + 1)..]; if (string.IsNullOrWhiteSpace(projectId)) { throw new ArgumentException("Invalid DSN: A Project Id is required."); } var apiBaseUri = new UriBuilder { Scheme = uri.Scheme, Host = uri.DnsSafeHost, Port = uri.Port, Path = $"{path}/api/{projectId}/" }.Uri; return new Dsn( dsn, projectId, path, secretKey, publicKey, apiBaseUri); } public static Dsn? TryParse(string? dsn) { if (string.IsNullOrWhiteSpace(dsn)) { return null; } try { return Parse(dsn); } catch { // Parse should not throw though! return null; } } }
namespace DFC.ServiceTaxonomy.ContentPickerPreview.ViewModels { public class VueMultiselectBannerItemViewModel { public string? Id { get; set; } public string? DisplayText { get; set; } public bool HasPublished { get; set; } public bool? IsActive { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace MainWebApplication.Models { public class BleMacJsonConverter : JsonConverter<byte[]> { public override byte[] Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader .GetString() .Split(':') .Select(b => Convert.ToByte(b, 16)) .ToArray(); public override void Write( Utf8JsonWriter writer, byte[] blemac, JsonSerializerOptions options) => writer.WriteStringValue(string.Join(":", blemac.Select(b => b.ToString("X2")))); } }
using EAN.GPD.Infrastructure.Database; using System; namespace EAN.GPD.Domain.Entities { public class MovimentoEntity : BaseEntity { private const string tableName = "Movimento"; public MovimentoEntity(long idUsuario) : base(tableName, idUsuario) { } public MovimentoEntity() : base(tableName) { } [Column] public long IdMovimento { get; set; } [Column] public long IdProjeto { get; set; } [Column] public long IdIndicador { get; set; } [Column] public DateTime DataLancamento { get; set; } [Column] public decimal ValorMeta { get; set; } [Column] public decimal ValorRealizado { get; set; } [JoinColumn("IdProjeto")] public ProjetoEntity Projeto { get; private set; } [JoinColumn("IdIndicador")] public IndicadorEntity Indicador { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Data.Contracts { public interface IGenericRepository<T> where T : class { public Task<T> AddAsync(T entity); //public Task<int> Delete(T entity); public Task<bool> DeleteByIdAsync(int id); //public Task<int> DeleteAll(IEnumerable<T> entities); public Task<IEnumerable<T>> GetAsync(); //public Task<T> FindById(int id); } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace ztm_otwartedane { public partial class BusEstimatedTimeParser { [JsonProperty("delay")] public List<BusEstimatedTime> allArrives { get; set; } } public partial class BusEstimatedTime { [JsonProperty("delayInSeconds")] public long delayInSeconds { get; set; } [JsonProperty("estimatedTime")] public string estimatedTime { get; set; } [JsonProperty("headsign")] public string direction { get; set; } [JsonProperty("routeId")] public long number { get; set; } [JsonProperty("status")] public string status { get; set; } } public partial class BusEstimatedTimeParser { public static BusEstimatedTimeParser FromJson(string json) => JsonConvert.DeserializeObject<BusEstimatedTimeParser>(json); } public static class Serialize { public static string ToJson(this BusEstimatedTimeParser self) => JsonConvert.SerializeObject(self); } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; using OnlineClinic.Core.DTOs; using OnlineClinic.Core.Services; namespace BlazorUI.Pages.People.Create { public partial class PersonCreate: ComponentBase { private PersonCreateDto createDto; private EditContext editContext; [Inject] protected IPersonService PersonService { get; set; } [Inject] protected NavigationManager NavigationManager { get; set; } protected override void OnInitialized() { createDto = new PersonCreateDto(PersonService); editContext = new EditContext(createDto); base.OnInitialized(); } private async Task SubmitForm() { DateTime dobDate = DateTime.MinValue; if(!DateTime.TryParse(createDto.DOBString,out dobDate)) createDto.DOB = DateTime.MinValue; createDto.DOB = dobDate; var isValid = editContext.Validate(); if(isValid) { await createDto.Save(); NavigationManager.NavigateTo("People"); } } } }
using System.Collections.Generic; using System.Linq; using System.Reflection; using AutoTests.Framework.Core.Exceptions; using Newtonsoft.Json.Linq; namespace AutoTests.Framework.Web.Configurators { public class LocatorsConfigurator { private readonly ConfiguratorsDependencies dependencies; public LocatorsConfigurator(ConfiguratorsDependencies dependencies) { this.dependencies = dependencies; } public virtual string LocatorsFileName => "Locators.json"; public virtual void Configure(PageObject pageObject) { if (DoLocatorsExist(pageObject)) { ConfigureLocators(pageObject); } } private void ConfigureLocators(PageObject pageObject) { var properties = dependencies.PageObjectPropertiesProvider.GetAllProperties(pageObject).ToList(); var locators = dependencies.Utils.Resources.GetJsonResource(pageObject, LocatorsFileName); ConfigureLocators(pageObject, properties, locators); } private void ConfigureLocators(PageObject pageObject, List<PropertyInfo> properties, JObject locators) { foreach (var propertyName in GetNodeNames(locators)) { ConfigureLocators(pageObject, properties, locators, propertyName); } } private void ConfigureLocators(PageObject pageObject, List<PropertyInfo> properties, JObject locators, string propertyName) { var property = properties.SingleOrDefault(x => x.Name == propertyName); CheckProperty(pageObject, propertyName, property); var token = locators.GetValue(propertyName); ConfigureLocators(pageObject, property, token); } private void ConfigureLocators(PageObject pageObject, PropertyInfo property, JToken token) { if (property.PropertyType.IsSubclassOf(typeof(Element))) { ConfigureElementLocators(pageObject, property, token); } else { ConfigureObjectProperty(pageObject, property, token); } } private void ConfigureElementLocators(PageObject pageObject, PropertyInfo property, JToken token) { var element = (Element) property.GetValue(pageObject); ConfigureLocators(element, token); } private void ConfigureObjectProperty(PageObject pageObject, PropertyInfo property, JToken token) { property.SetValue(pageObject, token.ToObject(property.PropertyType)); } private void ConfigureLocators(Element element, JToken locators) { if (locators.Type == JTokenType.String) { dependencies.ElementLocatorConfigurator.Configure(element, locators.ToObject<string>()); } else { ConfigureMultipleLocators(element, locators); } } private void ConfigureMultipleLocators(Element element, JToken locators) { var properties = dependencies.PageObjectPropertiesProvider.GetAllProperties(element).ToList(); foreach (var propertyName in GetNodeNames(locators.ToObject<JObject>())) { ConfigureLocators(element, propertyName, locators, properties); } } private void ConfigureLocators(Element element, string propertyName, JToken locators, List<PropertyInfo> properties) { var property = properties.SingleOrDefault(x => x.Name == propertyName); CheckProperty(element, propertyName, property); var locator = locators[propertyName].ToObject(property.PropertyType); property.SetValue(element, locator); } private void CheckProperty(PageObject pageObject, string propertyName, PropertyInfo property) { if (property == null) { throw new ClassConstraintException(pageObject.GetType(), $"PageObject '{{0}}' doesn't contains property with name '{propertyName}'. Check your Locators.json"); } } private IEnumerable<string> GetNodeNames(JObject locators) { return locators.Properties().Select(x => x.Name); } private bool DoLocatorsExist(PageObject pageObject) { return dependencies.Utils.Resources.CheckResource(pageObject, LocatorsFileName); } } }
namespace MySurveys.Web.Areas.Surveys.ViewModels.Filling { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using AutoMapper; using Models; using MvcTemplate.Web.Infrastructure.Mapping; public class PossibleAnswerViewModel : IMapFrom<PossibleAnswer>, IHaveCustomMappings { [HiddenInput(DisplayValue = false)] public int Id { get; set; } [Display(Name = "Possible answer")] public string Content { get; set; } public int QuestionId { get; set; } public virtual Question Question { get; set; } public ICollection<AnswerViewModel> Answers { get; set; } public void CreateMappings(IMapperConfiguration configuration) { configuration.CreateMap<PossibleAnswer, PossibleAnswerViewModel>() .ForMember(s => s.QuestionId, opt => opt.MapFrom(u => u.Question.Id)) .ReverseMap(); } } }
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base; namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.BandejaContrato { /// <summary> /// Modelo de vista para la Bandeja Contrato Formulario /// </summary> /// <remarks> /// Creación: GMD 20150319 </br> /// Modificación: </br> /// </remarks> public class BandejaContratoFormulario : GenericViewModel { } }
using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Enyim.Caching.Memcached; namespace Enyim.Caching { public interface IMemcachedClient : IDisposable { event Action<IMemcachedNode> NodeFailed; /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <remarks>The item does not expire unless it is removed due memory pressure.</remarks> /// <returns>true if the item was successfully stored in the cache; false otherwise.</returns> bool Store(StoreMode mode, string key, object value); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <returns>true if the item was successfully stored in the cache; false otherwise.</returns> bool Store(StoreMode mode, string key, object value, TimeSpan validFor); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <returns>true if the item was successfully stored in the cache; false otherwise.</returns> bool Store(StoreMode mode, string key, object value, DateTime expiresAt); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <remarks>The item does not expire unless it is removed due memory pressure.</remarks> /// <returns>true if the item was successfully stored in the cache; false otherwise.</returns> Task<bool> StoreAsync(StoreMode mode, string key, object value, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <returns>true if the item was successfully stored in the cache; false otherwise.</returns> Task<bool> StoreAsync(StoreMode mode, string key, object value, TimeSpan validFor, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <returns>true if the item was successfully stored in the cache; false otherwise.</returns> Task<bool> StoreAsync(StoreMode mode, string key, object value, DateTime expiresAt, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <remarks>The item does not expire unless it is removed due memory pressure. The text protocol does not support this operation, you need to Store then GetWithCas.</remarks> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> CasResult<bool> Cas(StoreMode mode, string key, object value); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <remarks>The item does not expire unless it is removed due memory pressure.</remarks> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> CasResult<bool> Cas(StoreMode mode, string key, object value, ulong cas); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> CasResult<bool> Cas(StoreMode mode, string key, object value, DateTime expiresAt, ulong cas); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> CasResult<bool> Cas(StoreMode mode, string key, object value, TimeSpan validFor, ulong cas); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <remarks>The item does not expire unless it is removed due memory pressure. The text protocol does not support this operation, you need to Store then GetWithCas.</remarks> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> Task<CasResult<bool>> CasAsync(StoreMode mode, string key, object value, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> Task<CasResult<bool>> CasAsync(StoreMode mode, string key, object value, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> Task<CasResult<bool>> CasAsync(StoreMode mode, string key, object value, DateTime expiresAt, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location and returns its version. /// </summary> /// <param name="mode">Defines how the item is stored in the cache.</param> /// <param name="key">The key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise).</returns> Task<CasResult<bool>> CasAsync(StoreMode mode, string key, object value, TimeSpan validFor, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="cacheMinutes"></param> /// <returns>true if the item was successfully added in the cache; false otherwise.</returns> bool Set(string key, object value, int cacheMinutes); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="cacheMinutes"></param> /// <returns>true if the item was successfully added in the cache; false otherwise.</returns> Task<bool> SetAsync(string key, object value, int cacheMinutes, CancellationToken cancellationToken = default); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="cacheMinutes"></param> /// <returns>true if the item was successfully added in the cache; false otherwise.</returns> bool Add(string key, object value, int cacheMinutes); /// <summary> /// Inserts an item into the cache with a cache key to reference its location. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="cacheMinutes"></param> /// <returns>true if the item was successfully added in the cache; false otherwise.</returns> Task<bool> AddAsync(string key, object value, int cacheMinutes, CancellationToken cancellationToken = default); /// <summary> /// Replaces an item into the cache with a cache key to reference its location. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="cacheMinutes"></param> /// <returns>true if the item was successfully replaced in the cache; false otherwise.</returns> bool Replace(string key, object value, int cacheMinutes); /// <summary> /// Replaces an item into the cache with a cache key to reference its location. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="cacheMinutes"></param> /// <returns>true if the item was successfully replaced in the cache; false otherwise.</returns> Task<bool> ReplaceAsync(string key, object value, int cacheMinutes, CancellationToken cancellationToken = default); /// <summary> /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> ulong Increment(string key, ulong defaultValue, ulong delta); /// <summary> /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> ulong Increment(string key, ulong defaultValue, ulong delta, DateTime expiresAt); /// <summary> /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> ulong Increment(string key, ulong defaultValue, ulong delta, TimeSpan validFor); /// <summary> /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<ulong> IncrementAsync(string key, ulong defaultValue, ulong delta, CancellationToken cancellationToken = default); /// <summary> /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<ulong> IncrementAsync(string key, ulong defaultValue, ulong delta, DateTime expiresAt, CancellationToken cancellationToken = default); /// <summary> /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<ulong> IncrementAsync(string key, ulong defaultValue, ulong delta, TimeSpan validFor, CancellationToken cancellationToken = default); /// <summary> /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> CasResult<ulong> Increment(string key, ulong defaultValue, ulong delta, ulong cas); /// <summary> /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> CasResult<ulong> Increment(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas); /// <summary> /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> CasResult<ulong> Increment(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas); /// <summary> /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<CasResult<ulong>> IncrementAsync(string key, ulong defaultValue, ulong delta, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<CasResult<ulong>> IncrementAsync(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to increase the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<CasResult<ulong>> IncrementAsync(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> ulong Decrement(string key, ulong defaultValue, ulong delta); /// <summary> /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> ulong Decrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt); /// <summary> /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> ulong Decrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor); /// <summary> /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<ulong> DecrementAsync(string key, ulong defaultValue, ulong delta, CancellationToken cancellationToken = default); /// <summary> /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<ulong> DecrementAsync(string key, ulong defaultValue, ulong delta, DateTime expiresAt, CancellationToken cancellationToken = default); /// <summary> /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<ulong> DecrementAsync(string key, ulong defaultValue, ulong delta, TimeSpan validFor, CancellationToken cancellationToken = default); /// <summary> /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> CasResult<ulong> Decrement(string key, ulong defaultValue, ulong delta, ulong cas); /// <summary> /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> CasResult<ulong> Decrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas); /// <summary> /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> CasResult<ulong> Decrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas); /// <summary> /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<CasResult<ulong>> DecrementAsync(string key, ulong defaultValue, ulong delta, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="expiresAt">The time when the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<CasResult<ulong>> DecrementAsync(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="defaultValue">The value which will be stored by the server if the specified item was not found.</param> /// <param name="delta">The amount by which the client wants to decrease the item.</param> /// <param name="validFor">The interval after the item is invalidated in the cache.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <returns>The new value of the item or defaultValue if the key was not found.</returns> /// <remarks>If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a <see cref="System.String"/>. Moreover the Text protocol only works with <see cref="System.UInt32"/> values, so return value -1 always indicates that the item was not found.</remarks> Task<CasResult<ulong>> DecrementAsync(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas, CancellationToken cancellationToken = default); /// <summary> /// Appends the data to the end of the specified item's data on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="data">The data to be appended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> bool Append(string key, ArraySegment<byte> data); /// <summary> /// Appends the data to the end of the specified item's data on the server, but only if the item's version matches the CAS value provided. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <param name="data">The data to be prepended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> CasResult<bool> Append(string key, ulong cas, ArraySegment<byte> data); /// <summary> /// Appends the data to the end of the specified item's data on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="data">The data to be appended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> Task<bool> AppendAsync(string key, ArraySegment<byte> data, CancellationToken cancellationToken = default); /// <summary> /// Appends the data to the end of the specified item's data on the server, but only if the item's version matches the CAS value provided. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <param name="data">The data to be prepended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> Task<CasResult<bool>> AppendAsync(string key, ulong cas, ArraySegment<byte> data, CancellationToken cancellationToken = default); /// <summary> /// Inserts the data before the specified item's data on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="data">The data to be appended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> bool Prepend(string key, ArraySegment<byte> data); /// <summary> /// Appends the data to the end of the specified item's data on the server, but only if the item's version matches the CAS value provided. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <param name="data">The data to be prepended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> CasResult<bool> Prepend(string key, ulong cas, ArraySegment<byte> data); /// <summary> /// Inserts the data before the specified item's data on the server. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="data">The data to be appended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> Task<bool> PrependAsync(string key, ArraySegment<byte> data, CancellationToken cancellationToken = default); /// <summary> /// Appends the data to the end of the specified item's data on the server, but only if the item's version matches the CAS value provided. /// </summary> /// <param name="key">The key used to reference the item.</param> /// <param name="cas">The cas value which must match the item's version.</param> /// <param name="data">The data to be prepended to the item.</param> /// <returns>true if the data was successfully stored; false otherwise.</returns> Task<CasResult<bool>> PrependAsync(string key, ulong cas, ArraySegment<byte> data, CancellationToken cancellationToken = default); /// <summary> /// Tries to get an item from the cache. /// </summary> /// <param name="key">The identifier for the item to retrieve.</param> /// <param name="value">The retrieved item or null if not found.</param> /// <returns>The <value>true</value> if the item was successfully retrieved.</returns> bool TryGet(string key, out object value); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <param name="key">The identifier for the item to retrieve.</param> /// <returns>The retrieved item, or <value>null</value> if the key was not found.</returns> object Get(string key); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The identifier for the item to retrieve.</param> /// <returns>The retrieved item, or <value>default(T)</value> if the key was not found.</returns> T Get<T>(string key); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <param name="key">The identifier for the item to retrieve.</param> /// <returns>The retrieved item, or <value>null</value> if the key was not found.</returns> Task<object> GetAsync(string key, CancellationToken cancellationToken = default); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The identifier for the item to retrieve.</param> /// <returns>The retrieved item, or <value>default(T)</value> if the key was not found.</returns> Task<T> GetAsync<T>(string key, CancellationToken cancellationToken = default); /// <summary> /// Tries to get an item from the cache with CAS. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> bool TryGetWithCas(string key, out CasResult<object> value); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <param name="key"></param> /// <returns></returns> CasResult<object> GetWithCas(string key); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> CasResult<T> GetWithCas<T>(string key); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <param name="key"></param> /// <returns></returns> Task<CasResult<object>> GetWithCasAsync(string key, CancellationToken cancellationToken = default); /// <summary> /// Retrieves the specified item from the cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> Task<CasResult<T>> GetWithCasAsync<T>(string key, CancellationToken cancellationToken = default); /// <summary> /// Retrieves multiple items from the cache. /// </summary> /// <param name="keys">The list of identifiers for the items to retrieve.</param> /// <returns>a Dictionary holding all items indexed by their key.</returns> IDictionary<string, object> Get(IEnumerable<string> keys); /// <summary> /// Retrieves multiple items from the cache. /// </summary> /// <param name="keys">The list of identifiers for the items to retrieve.</param> /// <returns>a Dictionary holding all items indexed by their key.</returns> Task<IDictionary<string, object>> GetAsync(IEnumerable<string> keys, CancellationToken cancellationToken = default); /// <summary> /// Retrieves multiple items from the cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="keys">The list of identifiers for the items to retrieve.</param> /// <returns>a Dictionary holding all items indexed by their key.</returns> IDictionary<string, T> Get<T>(IEnumerable<string> keys); /// <summary> /// Retrieves multiple items from the cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="keys">The list of identifiers for the items to retrieve.</param> /// <returns>a Dictionary holding all items indexed by their key.</returns> Task<IDictionary<string, T>> GetAsync<T>(IEnumerable<string> keys, CancellationToken cancellationToken = default); /// <summary> /// Retrieves multiple items from the cache with CAS. /// </summary> /// <param name="keys"></param> /// <returns></returns> IDictionary<string, CasResult<object>> GetWithCas(IEnumerable<string> keys); /// <summary> /// Retrieves multiple items from the cache with CAS. /// </summary> /// <param name="keys"></param> /// <returns></returns> Task<IDictionary<string, CasResult<object>>> GetWithCasAsync(IEnumerable<string> keys, CancellationToken cancellationToken = default); /// <summary> /// Removes the specified item from the cache. /// </summary> /// <param name="key">The identifier for the item to delete.</param> /// <returns>true if the item was successfully removed from the cache; false otherwise.</returns> bool Remove(string key); /// <summary> /// Removes the specified item from the cache. /// </summary> /// <param name="key">The identifier for the item to delete.</param> /// <returns>true if the item was successfully removed from the cache; false otherwise.</returns> Task<bool> RemoveAsync(string key, CancellationToken cancellationToken = default); /// <summary> /// Determines whether an item that associated with the key is exists or not /// </summary> /// <param name="key">The key</param> /// <returns>Returns a boolean value indicating if the object that associates with the key is cached or not</returns> bool Exists(string key); /// <summary> /// Determines whether an item that associated with the key is exists or not /// </summary> /// <param name="key">The key</param> /// <returns>Returns a boolean value indicating if the object that associates with the key is cached or not</returns> Task<bool> ExistsAsync(string key, CancellationToken cancellationToken = default); /// <summary> /// Removes all data from the cache. Note: this will invalidate all data on all servers in the pool. /// </summary> void FlushAll(); /// <summary> /// Removes all data from the cache. Note: this will invalidate all data on all servers in the pool. /// </summary> Task FlushAllAsync(CancellationToken cancellationToken = default); /// <summary> /// Gets statistics about the servers. /// </summary> /// <returns></returns> ServerStats Stats(); /// <summary> /// Gets statistics about the servers. /// </summary> /// <param name="type"></param> /// <returns></returns> ServerStats Stats(string type); /// <summary> /// Gets statistics about the servers. /// </summary> /// <returns></returns> Task<ServerStats> StatsAsync(CancellationToken cancellationToken = default); /// <summary> /// Gets statistics about the servers. /// </summary> /// <param name="type"></param> /// <returns></returns> Task<ServerStats> StatsAsync(string type, CancellationToken cancellationToken = default); } } #region [ License information ] /* ************************************************************ * * © 2010 Attila Kiskó (aka Enyim), © 2016 CNBlogs, © 2022 VIEApps.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************/ #endregion
using System.IO; using Mono.Options; namespace MonoCov { public class MonoCovOptions { public MonoCovOptions() { optionSet = new OptionSet (); optionSet.Add ("export-xml=", "Export coverage data as XML into specified directory", v => exportXmlDir = v); optionSet.Add ("export-html=", "Export coverage data as HTML into specified directory", v => exportHtmlDir = v); optionSet.Add ("stylesheet=", "Use the specified XSL stylesheet for XML->HTML conversion", v => exportHtmlDir = v); optionSet.Add ("minClassCoverage=", "If a code coverage of a class is less than specified, the application exits with return code 1.", v => float.TryParse(v, out minClassCoverage)); optionSet.Add ("minMethodeCoverage=", "If a code coverage of a methode is less than specified, the application exits with return code 1.", v => float.TryParse(v, out minMethodeCoverage)); optionSet.Add ("no-progress", "No progress messages during the export process", v => quiet = v != null); optionSet.Add ("h|help", "Show this message and exit", v => showHelp = v != null); } private OptionSet optionSet; public string exportXmlDir; public string exportHtmlDir; public string styleSheet; public float minClassCoverage = -1f; public float minMethodeCoverage = -1f; public bool quiet = false; public bool showHelp = false; public void ProcessArgs (string[] args) { remainingArguments = optionSet.Parse (args).ToArray (); } public string[] RemainingArguments { get { return remainingArguments; } } private string[] remainingArguments = new string[0]; public void WriteHelp(TextWriter textWriter) { textWriter.WriteLine("Usage: monocov [OPTIONS]+ [<DATAFILE>]"); textWriter.WriteLine(); textWriter.WriteLine("Options:"); optionSet.WriteOptionDescriptions(textWriter); } } }
using System; using System.Collections.Generic; using System.Linq; using DFC.ServiceTaxonomy.VersionComparison.Models; using DFC.ServiceTaxonomy.VersionComparison.Models.Parts; using Newtonsoft.Json.Linq; namespace DFC.ServiceTaxonomy.VersionComparison.Services.PropertyServices { public class AddBannerPropertyService : IPropertyService { private readonly IContentNameService _contentServiceHelper; public AddBannerPropertyService(IContentNameService contentServiceHelper) { _contentServiceHelper = contentServiceHelper; } public bool CanProcess(JToken? jToken, string? propertyName = null) { return propertyName?.Replace(" ", string.Empty).Equals("Addabanner", StringComparison.CurrentCultureIgnoreCase) ?? false; } public IList<PropertyExtract> Process(string propertyName, JToken? jToken) { var properties = new List<PropertyExtract>(); var addBanner = jToken?.ToObject<AddBanner>(); if (addBanner?.ContentItemIds?.Any() ?? false) { var linkInfo = addBanner.ContentItemIds.Select(c => new {Id = c, Name = _contentServiceHelper.GetContentNameAsync(c).Result}) .ToDictionary(k => k.Id, v => v.Name); properties.Add(new PropertyExtract { Name = propertyName, Links = linkInfo}); } return properties; } } }
using System.Web.Mvc; namespace Profiling2.Web.Mvc.Areas.Screening { public class ScreeningAreaRegistration : AreaRegistration { public override string AreaName { get { return "Screening"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Initiate request remove unit", "Screening/Initiate/{requestId}/RemoveUnit/{unitId}", new { controller = "Initiate", action = "RemoveUnit", requestId = UrlParameter.Optional, unitId = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Initiate request attach unit", "Screening/Initiate/{requestId}/AttachUnit/{unitId}", new { controller = "Initiate", action = "AttachUnit", requestId = UrlParameter.Optional, unitId = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Undo request response", "Screening/Requests/UndoResponse/{id}/{screeningEntityName}", new { controller = "Requests", action = "UndoResponse", id = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Validate Request action", "Screening/Validate/Request/{id}", new { controller = "Validate", action = "RequestAction", id = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Finalize Request action", "Screening/Finalize/Request/{id}", new { controller = "Finalize", action = "RequestAction", id = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Initiate request remove proposed person", "Screening/Initiate/{requestId}/RemoveProposedPerson/{proposedPersonId}", new { controller = "Initiate", action = "RemoveProposedPerson", requestId = UrlParameter.Optional, proposedPersonId = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Initiate request remove person", "Screening/Initiate/{requestId}/RemovePerson/{personId}", new { controller = "Initiate", action = "RemovePerson", requestId = UrlParameter.Optional, personId = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Initiate request attach person", "Screening/Initiate/{requestId}/AttachPerson/{personId}", new { controller = "Initiate", action = "AttachPerson", requestId = UrlParameter.Optional, personId = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Consolidate Request action", "Screening/Consolidate/Request/{id}", new { controller = "Consolidate", action = "RequestAction", id = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "RequestAttachments", "Screening/Requests/{requestId}/Attachments/{action}/{id}", new { controller = "Attachments", action = "Index", id = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); context.MapRoute( "Screening_default", "Screening/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, null, new string[] { "Profiling2.Web.Mvc.Areas.Screening.Controllers" } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cracking { class StringRotation { public static bool isRotation(string s1, string s2) { string s1s1 = s1 + s1; if (s1s1.Contains(s2)) return true; return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Schip { class Disassembler { SchipMachine machine; public Disassembler(SchipMachine machine) { this.machine = machine; } public string DecodeInstruction() { //se lee la proxima instrucción ushort pc = machine.Cpu.Pc; ushort byte1 = machine.Ram.ReadByte(pc); ushort byte2 = machine.Ram.ReadByte(pc + 1U); ushort instruction = (ushort)(byte1 << 8 | byte2); //Se extraen los opcodes y otros registros byte opcode1 = (byte)(instruction >> 12); byte opcode2 = (byte)((instruction & 0x0F00) >> 8); byte opcode3 = (byte)((instruction & 0x00F0) >> 4); byte opcode4 = (byte)(instruction & 0x000F); byte kk = (byte)(instruction & 0x00FF); ushort nnn = (ushort)(instruction & 0x0FFF); // Se ejecuta la operación de acuerdo a opocode1 string hexOpCode = Convert.ToString(instruction, 16).PadLeft(4, '0').ToUpper(); switch (opcode1) { case 0x0: switch(instruction){ case 0x00E0: //Clear display return hexOpCode + " -> CLS --Clear display"; case 0x00EE: //Return from subroutine call return hexOpCode + " -> RET --Return from subroutine call"; case 0x00FB: //Scroll display 4 pixels right return hexOpCode + " -> SCR --Scroll display 4 pixels right"; case 0x00FC: //Scroll display 4 pixels left return hexOpCode + " -> SCL --Scroll display 4 pixels left"; case 0x00FD: //Exit CHIP interpreter return hexOpCode + " -> EXIT --Exit CHIP interpreter"; case 0x00FE: //Disable extended screen mode (64x32) return hexOpCode + " -> LOW --Disable extended screen mode"; case 0x00FF: //Enable extended screen mode for full-screen graphics (128x64) return hexOpCode + " -> HIGH --Enable extended screen mode"; default: if (opcode3 == 0xC && opcode2 == 0) //Scroll down N lines { return hexOpCode + " -> SCD " + opcode4 + " --Scroll down " + opcode4 + " lines "; } else if ((instruction & 0xFFF) != 0) { //0nnn - SYS addr //Jump to a machine code routine at nnn. //This instruction is only used on the old computers on which Chip-8 was originally implemented. It is ignored by modern interpreters. return hexOpCode + "SYS -> " + nnn + " --Jump to a machine code routine at " + nnn; } else { //throw new Exception("Unknown Opcode: 0x" + Convert.ToString(instruction, 16) + " at 0x" + Convert.ToString(pc - 0x202, 16)); return hexOpCode + " -> Unknown instruction"; } } case 0x1: //Jump to NNN return hexOpCode + " -> JP " + nnn + " --Jump to " + nnn; case 0x2: //Call subroutine at NNN return hexOpCode + " -> CALL " + nnn + " --Call subroutine at " + nnn; case 0x3: //Skip next instruction if VX == KK return hexOpCode + " -> SE V" + opcode2 + ", " + kk + " --Skip next instruction if V" + opcode2 + " == " + kk; case 0x4: //Skip next instruction if VX <> KK return hexOpCode + " -> SNE V" + opcode2 + ", " + kk + " --Skip next instruction if V" + opcode2 + " != " + kk; case 0x5: //Skip next instruction if VX == VY return hexOpCode + " -> SE V" + opcode2 + ", V" + opcode3 + " --Skip next instruction if V" + opcode2 + " == V" + opcode3; case 0x6: //VX := KK return hexOpCode + " -> LD V" + opcode2 + ", " + kk + " --V" + opcode2 + " := " + kk; case 0x7: //VX := VX + KK return hexOpCode + " -> ADD V" + opcode2 + ", " + kk + " --V" + opcode2 + " := V" + opcode2 + " + "+ kk; case 0x8: switch(opcode4){ case 0x0: //VX := VY, VF may change return hexOpCode + " -> LD V" + opcode2 + ", V" + opcode3 + " --V" + opcode2 + " := V" + opcode3; case 0x1: //VX := VX or VY, VF may change return hexOpCode + " -> OR V" + opcode2 + ", V" + opcode3 + " --V" + opcode2 + " := V" + opcode2 + " or V"+ opcode3; case 0x2: //VX := VX and VY, VF may change return hexOpCode + " -> AND V" + opcode2 + ", V" + opcode3 + " --V" + opcode2 + " := V" + opcode2 + " and V"+ opcode3; case 0x3: //VX := VX xor VY, VF may change return hexOpCode + " -> XOR V" + opcode2 + ", V" + opcode3 + " --V" + opcode2 + " := V" + opcode2 + " xor V"+ opcode3; case 0x4: //VX := VX + VY, VF := carry return hexOpCode + " -> ADD V" + opcode2 + ", V" + opcode3 + " --V" + opcode2 + " := V" + opcode2 + " + V"+ opcode3 + ", VF := carry"; case 0x5: //VX := VX - VY, VF := not borrow return hexOpCode + " -> SUB V" + opcode2 + ", V" + opcode3 + " --V" + opcode2 + " := V" + opcode2 + " - V"+ opcode3 + ", VF := !borrow"; case 0x6: //VX := VX shr 1, VF := carry return hexOpCode + " -> SHR V" + opcode2 + " --V" + opcode2 + " := V" + opcode2 + " shr 1, VF := carry"; case 0x7: //VX := VY - VX, VF := not borrow return hexOpCode + " -> SUBN V" + opcode2 + ", V" + opcode3 + " --V" + opcode2 + " := V" + opcode3 + " - V"+ opcode2 + ", VF := !borrow"; case 0xE: //VX := VX shl 1, VF := carry return hexOpCode + " -> SHL V" + opcode2 + " --V" + opcode2 + " := V" + opcode2 + " shl 1, VF := carry"; default: return hexOpCode + " -> Unknown instruction"; } case 0x9: //Skip next instruction if VX <> VY return hexOpCode + " -> SNE V" + opcode2 + ", V" + opcode3 + " --Skip next instruction if V" + opcode2 + " != V" + opcode3; case 0xA: //I := NNN return hexOpCode + " -> LD I, " + nnn + " --I := " + nnn; case 0xB: //Jump to NNN+V0 return hexOpCode +"JP V0, " + nnn + "Jump to V0 + " + nnn; case 0xC: //VX := pseudorandom_number and KK return hexOpCode + " -> RND V" + opcode2 + ", " + kk + " --V" + opcode2 + " := rand(256) and "+ kk; case 0xD: //Show N-byte sprite from M(I) at coords (VX,VY), VF :=collision. return hexOpCode + " -> DRW V" + opcode2 + ", V" + opcode3 + ", " + opcode4 + " -- Draw sprite M(I) at (V" + opcode2 + ", V" + opcode3 + "). VF := collision"; case 0xE: switch(kk){ case 0x9E: //Skip next instruction if key VX pressed return hexOpCode + " -> SKP V" + opcode2 + " --Skip next instruction if key V" + opcode2 + " is pressed"; case 0xA1: //Skip next instruction if key VX not pressed return hexOpCode + " -> SKNP V" + opcode2 + " --Skip next instruction if key V" + opcode2 + " is not pressed"; default: //throw new Exception("Unknown Opcode: 0x" + Convert.ToString(currentInstruction, 16) + " at 0x" + Convert.ToString(pc - 0x202, 16)); return hexOpCode + " -> Unknown instruction"; } case 0xF: switch(kk){ case 0x07: //VX := delay_timer return hexOpCode + " -> LD V" + opcode2 + ", DT --V" + opcode2 + " := DT"; case 0x0A: //wait for keypress, store hex value of key in VX return hexOpCode + " -> LD V" + opcode2 + ", KP --V" + opcode2 + " := KeyPressed"; case 0x15: //delay_timer := VX return hexOpCode + " -> LD DT, V" + opcode2 + " --DT := V" + opcode2 ; case 0x18: //sound_timer := VX return hexOpCode + " -> LD ST, V" + opcode2 + " --DT := V" + opcode2 ; case 0x1E: //I := I + VX return hexOpCode + " -> ADD I, V" + opcode2 + " --I := I + V" + opcode2; case 0x29: //Point I to 5-byte font sprite for hex character VX return hexOpCode + " -> LD I, LF(V" + opcode2 + ") --Set I to Chip8 Font V" + opcode2; case 0x30: //Point I to 10-byte font sprite for digit VX (0..9) return hexOpCode +" -> LD I, HF(V" + opcode2 + ") --Set I to SChip8 Font V" + opcode2; case 0x33: //Store BCD representation of VX in M(I)..M(I+2) return hexOpCode + " -> BCD V" + opcode2 + " --Store BCD representation of V" + opcode2 + " in M(I)..M(I+2)"; case 0x55: //Store V0..VX in memory starting at M(I) return hexOpCode + " -> LD [I], V" + opcode2 + " --Store V0..V" + opcode2 + " in memory starting at I"; case 0x65: //Read V0..VX from memory starting at M(I) return hexOpCode + " -> LD V" + opcode2 + ", [i]" + " --Read V0..V" + opcode2 + " from memory starting at I"; case 0x75: //Store V0..VX in RPL user flags (X <= 7) return hexOpCode + " -> LD R, V" + opcode2 + " --Store V0..V" + opcode2 + " in RPL user flags"; case 0x85: //Read V0..VX from RPL user flags (X <= 7) return hexOpCode + " -> LD V, R" + opcode2 + " --Read V0..V" + opcode2 + " from RPL user flags"; default: //throw new Exception("Unknown Opcode: 0x" + Convert.ToString(currentInstruction, 16) + " at 0x" + Convert.ToString(pc - 0x202, 16)); return hexOpCode + " -> Unknown instruction"; } default: //throw new Exception("Unknown Opcode: 0x" + Convert.ToString(currentInstruction, 16) + " at 0x" + Convert.ToString(pc - 0x202, 16)); return hexOpCode + " -> Unknown instruction"; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyController : MonoBehaviour { private UnityEngine.AI.NavMeshAgent agent; private Animation anim; private Collider col; private AudioSource audio; // private string walkAnim; // private string deathAnim; // private string idleAnim; //This is a native function to handle innate collision logic public void Hurt() { audio.Play(); anim.Play("zombie_death_standing"); enabled = false; col.enabled = false; //To disabled the enemies navigation logic agent.enabled = false; //Trigger the gain kill score function in gamecontroller class GameController.GainKillScore(); } // Start is called before the first frame update void Start() { anim = GetComponent<Animation>(); // foreach(AnimationState state in anim) { // Debug.Log(state.name); // } agent = GetComponent<UnityEngine.AI.NavMeshAgent>(); col = GetComponent<Collider>(); audio = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { agent.destination = PlayerController.GetPos(); } void OnTriggerEnter (Collider col) { if(col.GetComponent<BulletController>()) { // anim.Play("zombie_death_standing"); //Bullet destroy Destroy(col.gameObject); //Zombie destroy // Destroy(gameObject); // Debug.Log("Enter"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace gsbRapports2019 { public partial class FormGererMedecin : Form { mission3Entities mesDonnees; public FormGererMedecin(mission3Entities mesDonnees) { InitializeComponent(); this.mesDonnees = mesDonnees; var nomMedecin = (from medecins in mesDonnees.medecins select medecins.nom).ToList(); this.cmbListMed.DataSource = nomMedecin; } private void cmbListMed_SelectedIndexChanged(object sender, EventArgs e) { } private void btnValider_Click(object sender, EventArgs e) { string medecin = (string)cmbListMed.Text; FormAfficherMedecin f = new FormAfficherMedecin(mesDonnees,medecin); f.Show(); } private void button1_Click(object sender, EventArgs e) { FormAjoutMedecin f = new FormAjoutMedecin(mesDonnees); f.Show(); } } }
using Assets.Scripts; using ChatMultiplayerDemoShared; using KingNetwork.Client; using KingNetwork.Shared; using System.Threading; using UnityEngine; using UnityEngine.UI; public class ChatDemo : MonoBehaviour { [SerializeField] [Tooltip("The InputField the user can type in.")] InputField input; [SerializeField] [Tooltip("The transform to place new messages in.")] Transform chatWindow; [SerializeField] [Tooltip("The scrollrect for the chat window (if present).")] ScrollRect scrollRect; [SerializeField] [Tooltip("The message prefab where messages will be added.")] GameObject messagePrefab; private void Start() { Thread.Sleep(100); NetworkManager.GetClient().PutHandler(MyPackets.Message, OnMessageReceived); } public void OnMessageReceived(IKingBuffer kingBuffer) { AddMessage(kingBuffer.ReadString()); } void AddMessage(string message) { var messageObj = Instantiate(messagePrefab) as GameObject; messageObj.transform.SetParent(chatWindow); var text = messageObj.GetComponentInChildren<Text>(); if (text != null) text.text = message; else Debug.LogError("Message object does not contain a Text component!"); if (scrollRect != null) { Canvas.ForceUpdateCanvases(); scrollRect.verticalNormalizedPosition = 0f; } } public void MessageEntered() { using (var kingBuffer = new KingBuffer()) { kingBuffer.WriteMessagePacket(MyPackets.Message); kingBuffer.WriteString(input.text); NetworkManager.GetClient().SendMessage(kingBuffer); } } }
/*********************************************************************** * Module: SecretaryService.cs * Author: Sladjana Savkovic * Purpose: Definition of the Class Service.SecretaryService ***********************************************************************/ using Model.Users; using Repository; using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Service.UsersAndWorkingTime { public class SecretaryService { public SecretaryRepository secretaryRepository = new SecretaryRepository(); public Secretary RegisterSecretary(Secretary secretary) { if(!IsUsernameValid(secretary.Username) || !IsPasswordValid(secretary.Password)) { return null; } return secretaryRepository.NewSecretary(secretary); } public Secretary EditProfile(Secretary secretary) { if (!IsUsernameValid(secretary.Username) || !IsPasswordValid(secretary.Password)) { return null; } return secretaryRepository.SetSecretary(secretary); } public Secretary ViewProfile(string jmbg) { return secretaryRepository.GetSecretary(jmbg); } public List<Secretary> ViewSecretaries() { return secretaryRepository.GetAllSecretaries(); } public bool DeleteProfile(string jmbg) { return secretaryRepository.DeleteSecretary(jmbg); } public Secretary SignIn(string username, string password) { return secretaryRepository.CheckUsernameAndPassword(username,password); } private bool IsUsernameValid(string username) { Regex regex = new Regex(@"^[a-zA-Z0-9\.\-_]{5,13}$"); Match match = regex.Match(username); return match.Success; } private bool IsPasswordValid(string password) { Regex regex = new Regex(@"^[a-zA-Z0-9\.\-_]{8,30}$"); Match match = regex.Match(password); return match.Success; } } }
using System.Collections.Generic; using System.Linq; namespace Uintra.Core.Search.Entities { public class SearchableMember : SearchableBase, ISearchableTaggedActivity { public string Photo { get; set; } public string FullName { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Department { get; set; } public IEnumerable<string> UserTagNames { get; set; } = Enumerable.Empty<string>(); public bool TagsHighlighted { get; set; } public bool Inactive { get; set; } public IEnumerable<SearchableMemberGroupInfo> Groups { get; set; } = Enumerable.Empty<SearchableMemberGroupInfo>(); } }
// Math utils: useful mathematical methods using Godot; using System; namespace BaseProject.Utils { public static class Math { // TODO - figure out HOW THIS WORKS!!! taken from godot Qs // https://godotengine.org/qa/5770/how-to-lerp-between-two-angles public static float LerpAngle(float a, float b, float t) { if ((float)System.Math.Abs (a - b) >= (float)System.Math.PI) { if (a > b) a = (float)NormaliseAngle (a) - 2.0f * (float)System.Math.PI; else b = (float)NormaliseAngle (b) - 2.0f * (float)System.Math.PI; } return (Lerp (a, b, t)); } // how does this work? what is posmod? public static float NormaliseAngle(float x) { return (float)Mathf.PosMod (x + (float)System.Math.PI, 2.0f * (float)System.Math.PI) - (float)System.Math.PI; } public static float Lerp(float p1, float p2, float fraction) { return p1 + (p2 - p1) * fraction; } public static Vector2 Lerp(Vector2 p1, Vector2 p2, float fraction) { return p1 + (p2 - p1) * fraction; } public static Vector2 PerpendicularClockwise(Vector2 vec) { return new Vector2(-vec.y, vec.x); } public static Vector2 PerpendicularCounterClockwise(Vector2 vec) { return new Vector2(vec.y, -vec.x); } } }
namespace QStore.Tests.QStringMapTests { using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using QStore.Strings; using QStore.Tests.Comparers; [TestClass] public class GetByPrefixWithValueTests { public static void GetByPrefixWithValueTestHelper( IComparer<char> comparer, string prefix, params string[] words) { var map = QStringMap<int>.Create(words, comparer); foreach (var word in words) { map[word] = word.GetHashCode(); } var sequenceComparer = new SequenceComparer<char>(comparer); var expected = words.Where(s => s.StartsWith(prefix, StringComparison.Ordinal)) .OrderBy(s => s, sequenceComparer) .Select(s => new KeyValuePair<string, int>(s, s.GetHashCode())) .ToArray(); var actual = map.EnumerateByPrefixWithValue(prefix).ToArray(); CollectionAssert.AreEqual(expected, actual); } public static void GetByPrefixWithValueTestHelper(string prefix, params string[] words) { GetByPrefixWithValueTestHelper(Comparer<char>.Default, prefix, words); } [TestMethod] public void GetByPrefixWithValueEmptySequence() { GetByPrefixWithValueTestHelper(string.Empty, "aa", "bb", "abc", string.Empty); } [TestMethod] public void GetByPrefixWithValueSimple1() { GetByPrefixWithValueTestHelper("a", "aa", "ab", "ac", "abc"); } [TestMethod] public void GetByPrefixWithValueSimple2() { GetByPrefixWithValueTestHelper("a", "aa", "bb", "abc", string.Empty); } [TestMethod] public void GetByPrefixWithValueSimple3() { GetByPrefixWithValueTestHelper("ab", "aa", "ab", "ac", "abc"); } } }
using System; using hurb_sap.Domain.Services.Payments; using hurb_sap.Models; namespace hurb_sap.Services.Payments { public class PaymentsService: IPaymentsService { public ResponseModel Add(PaymentsModel payment){ //************************** // add di-api code here ^-^ //************************** var response = new ResponseModel{ Id = payment.DocEntry, Status = "Sucesso", Message = "Pagamento cadastrado", Objects = payment }; return response; } public ResponseModel Read(int id){ //************************** // add your data source here ^-^ //************************** var rng = new Random(); var response = new ResponseModel{ Id = id, Status = "Sucesso", Message = "Pagamento resgatado", Objects = new PaymentsModel(){ DocEntry = id, PayDay = DateTime.Now, DocTotal = rng.Next(1, 10000)} }; return response; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SongDuration { class SongDuration { private int minutes; private int seconds; public int Minutes { get => minutes; set => minutes = value; } public int Seconds { get => seconds; set => seconds = value; } public SongDuration() { Minutes = 0; Seconds = 0; } public SongDuration(int _minutes, int _seconds) { if (_minutes < 0 || _minutes > 20 || _minutes == 20 && _seconds > 0) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } } else { Minutes = _minutes; } if (_seconds < 0 || _seconds > 59) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } } else { Seconds = _seconds; } } public override string ToString() { return string.Format("{0} minutes {1} seconds", Minutes, Seconds); } //Operator overloading public static bool operator !=(SongDuration a, SongDuration b) { if (a.Minutes == b.Minutes && a.Seconds == b.Seconds) { return false; } else { return true; } } public static bool operator ==(SongDuration a, SongDuration b) { if (a.Minutes == b.Minutes && a.Seconds == b.Seconds) { return true; } else { return false; } } public static bool operator <=(SongDuration a, SongDuration b) { if (a.Minutes < b.Minutes) { return true; } else if (a.Minutes == b.Minutes && a.Seconds <= b.Seconds) { return true; } else { return false; } } public static bool operator >=(SongDuration a, SongDuration b) { if (a.Minutes > b.Minutes) { return true; } else if (a.Minutes == b.Minutes && a.Seconds >= b.Seconds) { return true; } else { return false; } } public static bool operator >(SongDuration a, SongDuration b) { if (a.Minutes > b.Minutes) { return true; } else if (a.Minutes == b.Minutes && a.Seconds > b.Seconds) { return true; } else { return false; } } public static bool operator <(SongDuration a, SongDuration b) { if (a.Minutes < b.Minutes) { return true; } else if (a.Minutes == b.Minutes && a.Seconds < b.Seconds) { return true; } else { return false; } } public static SongDuration operator +(SongDuration a, SongDuration b) { SongDuration tempSong = new SongDuration(); tempSong.Minutes = a.Minutes + b.Minutes; tempSong.Seconds = a.Seconds + b.Seconds; if (tempSong.Seconds > 59) { tempSong.Minutes++; tempSong.Seconds -= 60; } if (tempSong.Minutes > 20 || tempSong.Minutes == 20 && tempSong.Seconds > 0) { Console.WriteLine("Error: The result is greater than 20 minutes 0 seconds. Setting to that instead."); tempSong.Minutes = 20; tempSong.Seconds = 0; } return tempSong; } public static SongDuration operator -(SongDuration a, SongDuration b) { SongDuration tempSong = new SongDuration(); tempSong.Minutes = a.Minutes - b.Minutes; tempSong.Seconds = a.Seconds - b.Seconds; if (tempSong.Seconds < 0) { tempSong.Minutes--; tempSong.Seconds += 60; } if (tempSong.Minutes < 0 || tempSong.Seconds < 0) { Console.WriteLine("Error: The result is less than 0 minutes 0 seconds. Setting to that instead."); tempSong.Minutes = 0; tempSong.Seconds = 0; } return tempSong; } //End operator overloading } }
using System; using System.Windows.Forms; using System.Collections.Generic; using Caelum.Banco.Clientes; using Caelum.Banco.CustomExceptions; using Caelum.Banco.Contas; namespace Banco { public partial class Form1 : Form { private List<Conta> contas; int index = 0; //private int indice = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.contas = new List<Conta>(); Cliente cliente = new Cliente("Rodrigo"); Cliente cliente2 = new Cliente("Diego"); this.AdicionaConta(new ContaCorrente(cliente)); this.AdicionaConta(new ContaPoupanca(cliente2)); this.contas[0].Deposita(1000); //ContaPoupanca conta = new ContaPoupanca(cliente, 3); //conta.Deposita(200.0); //MessageBox.Show("imposto da conta corrente = " + conta.CalculaTributo()); //ITributavel t = conta; //MessageBox.Show("imposto da conta pela interface = " + t.CalculaTributo()); } private void BtnDeposita_Click(object sender, EventArgs e) { double valorDigitado = double.Parse(txtValor.Text); try { this.contas[index].Deposita(valorDigitado); txtSaldo.Text = this.contas[index].Saldo.ToString("F2"); MessageBox.Show("Sucesso!"); } catch (ArgumentException err) { MessageBox.Show("Não é possível depositar um valor negativo"); } } private void BtnSaque_Click(object sender, EventArgs e) { double valorDigitado = double.Parse(txtValor.Text); try { this.contas[index].Saca(valorDigitado); txtSaldo.Text = this.contas[index].Saldo.ToString("F2"); MessageBox.Show("Sucesso!"); } catch (SaldoInsuficienteException err) { MessageBox.Show("Saldo insuficiente"); }catch(ArgumentException err) { MessageBox.Show("Não é possível sacar um valor negativo"); } } private void CBoxBusca_SelectedIndexChanged(object sender, EventArgs e) { index = cBoxBusca.SelectedIndex; txtTitular.Text = this.contas[index].Titular.Nome; txtSaldo.Text = this.contas[index].Saldo.ToString("F2"); txtNumero.Text = this.contas[index].Numero.ToString(); } public void AdicionaConta(Conta conta) { this.contas.Add(conta); //this.indice++; cBoxBusca.Items.Add(conta); } private void BtnNovaConta_Click(object sender, EventArgs e) { FormCadastrarConta formCadastrarConta = new FormCadastrarConta(this); formCadastrarConta.ShowDialog(); } private void BtnRelatorios_Click(object sender, EventArgs e) { FormRelatorios formRelatorios = new FormRelatorios(this.contas); formRelatorios.ShowDialog(); } } }
using System; using System.Collections.Generic; using System.Web.Mvc; using TAiMStore.Domain; using TAiMStore.Model.Repository; using TAiMStore.Model.UnitOfWork; using TAiMStore.Model.ViewModels; using TAiMStore.Classes; namespace TAiMStore.Model.Classes { public class UserManager { private readonly IUserRepository _userRepository; private readonly IUnitOfWork _unitOfWork; private readonly IRoleRepository _roleRepository; private readonly IContactsRepository _contactsRepository; public UserManager(IUserRepository userRepository, IRoleRepository roleRepository, IContactsRepository contactsRepository, IUnitOfWork unitOfWork) { _userRepository = userRepository; _roleRepository = roleRepository; _contactsRepository = contactsRepository; _unitOfWork = unitOfWork; _roleRepository.GetAll(); } #region User public User GetUserByName(string name) { return _userRepository.Get(u => u.Name == name); } public UserViewModel GetUserViewModelByName(string userName) { var user = _userRepository.Get(u => u.Name == userName); return new UserViewModel { Name = user.Name, Email = user.Email }; } public string ToLowerUserName(string userName) { return userName.Replace("_", "-").Replace(".", "-").ToLower(); } public User GetUserByEmail(string email) { return _userRepository.Get(u => u.Email == email); } public UserViewModel RegisterUser(string userName, string email, string pass) { var user = new User(); var userViewModel = new UserViewModel(); user.Name = userName; user.Email = email; user.Password = Hash.HashPassword(pass); user.Role = _roleRepository.Get(r => r.Name == ConstantStrings.CustomerRole); if (user.Role.Name == ConstantStrings.CustomerRole) user.isActivate = false; else user.isActivate = true; _userRepository.Add(user); _unitOfWork.Commit(); userViewModel.Name = userName; userViewModel.Email = email; return userViewModel; } public bool ValidateUser(string userName, string password) { var user = _userRepository.Get(u => u.Name == userName); if (user == null) return false; else { if (user.Password != Hash.HashPassword(password)) { return false; } else return true; } } public bool ChangePassword(string userName, string oldPassword, string newPassword, string confirmPassword) { if (ValidateUser(userName, oldPassword)) { var user = _userRepository.Get(u => u.Name == userName); if (newPassword.Equals(confirmPassword)) { user.Password = Hash.HashPassword(newPassword); _userRepository.Update(user); _unitOfWork.Commit(); return true; } else return false; } else return false; } #endregion #region Role public bool UserIsInRole(string userName, string roleName) { var user = _userRepository.Get(u => u.Name == userName); if (user.Role.Name == roleName) return true; else return false; } public void UserEdit(string userId, string roleName, bool activate) { var id = Convert.ToInt32(userId); var user = _userRepository.Get(u => u.Id == id); user.Role = _roleRepository.Get(r => r.Name == roleName); user.Contacts = _contactsRepository.Get(c => c.User.Id == user.Id); user.isActivate = activate; _userRepository.Update(user); _unitOfWork.Commit(); } #endregion #region Profile public ProfileViewModel GetProfileViewModelByName(string userName) { var user = GetUserByName(userName); var contacts = _contactsRepository.Get(c => c.Id == user.Id); if (contacts == null) return null; else { var profile = new ProfileViewModel { City = contacts.City, //Email = ConstantStrings.LabelForEmailStart + user.Email + ConstantStrings.LabelForEmailEnd, EmailForTextBox = user.Email, House = contacts.House, PostZip = contacts.PostZip.ToString(), PersonFullName = contacts.PersonFullName, Room = contacts.Room, Street = contacts.Street, Telephone = contacts.Telephone }; return profile; } } public void ContactsAdd(string userName, ProfileViewModel profile) { var user = GetUserByName(userName); var contact = new Contacts { PersonFullName = profile.PersonFullName, City = profile.City, Street = profile.Street, House = profile.House, PostZip = Convert.ToInt32(profile.PostZip), Room = profile.Room, Telephone = profile.Telephone }; user.Contacts = contact; _userRepository.Update(user); _unitOfWork.Commit(); } public void ContactsEdit(string userName, ProfileViewModel profile) { var user = GetUserByName(userName); _contactsRepository.GetAll(); var contact = user.Contacts; contact.PersonFullName = profile.PersonFullName; contact.City = profile.City; contact.Street = profile.Street; contact.House = profile.House; contact.PostZip = Convert.ToInt32(profile.PostZip); contact.Room = profile.Room; contact.Telephone = profile.Telephone; user.Email = profile.Email; _userRepository.Update(user); _contactsRepository.Update(contact); _unitOfWork.Commit(); } #endregion #region Admin public List<UserViewModel> GetUsers() { var users = new List<UserViewModel>(); var userEntities = _userRepository.GetAll(); var roles = _roleRepository.GetAll(); var contacts = _contactsRepository.GetAll(); foreach (var userEntity in userEntities) { var tmp = new UserViewModel(); tmp.Id = userEntity.Id; tmp.Name = userEntity.Name; tmp.Email = userEntity.Email; var list = new List<SelectListItem>(); list.Add(new SelectListItem { Selected = true, Text = userEntity.Role.Name, Value = userEntity.Role.Name }); foreach (var role in roles) { if (role.Name != userEntity.Role.Name) list.Add(new SelectListItem { Selected = false, Text = role.Name, Value = role.Name }); } tmp.Roles = list; users.Add(tmp); } return users; } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace CollectionHierarchy.Interfaces { interface IAddCollection { public int Add(string item); } }
using SuperMario.Desktop; namespace SuperMario.Commands { public class QuittingCommand : ICommand { readonly Game1 game; public QuittingCommand(Game1 game) { this.game = game; } public void Execute() { game.Exit(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public class Empleado : Persona { private string usuario; private string password; private double sueldo; private EPuesto puesto; private string[] diasLaborales; private DateTime horarioEntrada; private DateTime horarioSalida; private int idEmpleado; private static int idCliente = 0; private static int idProducto = 0; #region Constructor /// <summary> /// Inicializa los datos de un empleado /// </summary> /// <param name="usuario">Usuario del empleado</param> /// <param name="password">Password del empleado</param> /// <param name="sueldo">Sueldo del empleado</param> /// <param name="puesto">Puesto del empleado</param> /// <param name="diasLaborales">Dias laborales del empleado</param> /// <param name="horarioEntrada">Horario de llegada del empleado</param> /// <param name="horarioSalida">Horario de llegada del empleado</param> /// <param name="idEmpleado">ID del empleado</param> /// <param name="nombre">Nombre del empleado</param> /// <param name="apellido">Apellido del empleado</param> /// <param name="fechaNacimiento">Fecha de nacimiento del empleado</param> /// <param name="dni">DNI del empleado</param> /// <param name="sexo">Sexo del empleado</param> /// <param name="nacionalidad">Nacionalidad del empleado</param> /// <param name="domicilio">Domicilio del empleado</param> public Empleado(string usuario, string password, double sueldo, EPuesto puesto, string[] diasLaborales, DateTime horarioEntrada, DateTime horarioSalida, int idEmpleado, string nombre, string apellido, DateTime fechaNacimiento, long dni, string sexo, string nacionalidad, string domicilio) : base(nombre, apellido, fechaNacimiento, dni, sexo, nacionalidad, domicilio) { this.Usuario = usuario; this.Password = password; this.Sueldo = sueldo; this.Puesto = puesto; this.DiasLaborales = diasLaborales; this.HorarioEntrada = horarioEntrada; this.HorarioSalida = horarioSalida; this.IdEmpleado = idEmpleado; } #endregion #region AdministrarCliente /// <summary> /// Crea un nuevo cliente /// </summary> /// <param name="saldo">Cantidad de plata que tiene el cliente</param> /// <param name="nombre">Nombre del cliente</param> /// <param name="apellido">Apellido del cliente</param> /// <param name="fechaNacimiento">Fecha de nacimiento del cliente</param> /// <param name="dni">DNI del cliente</param> /// <param name="sexo">Sexo del cliente</param> /// <param name="nacionalidad">Nacionalidad del cliente</param> /// <param name="domicilio">Domicilio del cliente</param> public static Cliente AltaCliente(double saldo, string nombre, string apellido, DateTime fechaNacimiento, long dni, string sexo, string nacionalidad, string domicilio) { idCliente++; Cliente clienteNuevo = new Cliente(saldo, idCliente, nombre, apellido, fechaNacimiento, dni, sexo, nacionalidad, domicilio); return clienteNuevo; } /// <summary> /// Elimina un cliente de una lista de clientes /// </summary> /// <param name="listaClientes">Lista de clientes</param> /// <param name="cliente">Cliente a eliminar</param> public static void BajaCliente(List<Cliente> listaClientes, Cliente cliente) { listaClientes.Remove(cliente); } /// <summary> /// Muestra los datos de un cliente /// </summary> /// <param name="cliente">Cliente a mostrar</param> /// <returns>Retorna un string con todos los datos</returns> public static string MostrarCliente(Cliente cliente) { StringBuilder st = new StringBuilder(); st.AppendLine($"Nombre y apellido: {cliente.Nombre} {cliente.Apellido}"); st.AppendLine($"Fecha de nacimiento: {cliente.FechaNacimiento.Day}/{cliente.FechaNacimiento.Month}/{cliente.FechaNacimiento.Year}"); st.AppendLine($"DNI: {cliente.Dni}"); st.AppendLine($"Sexo: {cliente.Sexo}"); st.AppendLine($"Nacionalidad: {cliente.Nacionalidad}"); st.AppendLine($"Domicilio: {cliente.Domicilio}"); return st.ToString(); } #endregion #region AdministrarProductos /// <summary> /// Crea un nuevo producto /// </summary> /// <param name="nombre">Nombre del producto</param> /// <param name="marca">Marca del producto</param> /// <param name="precio">Precio del producto</param> /// <param name="peso">Peso del producto</param> /// <param name="stock">Stock del producto</param> /// <returns>Retorna el producto creado</returns> public static Producto AltaProducto(string nombre, string marca, ETipo tipo, double precio, double peso, int stock) { idProducto++; Producto productoNuevo = new Producto(nombre, marca, tipo, precio, peso, stock, idProducto); return productoNuevo; } /// <summary> /// Elimina un producto de una lista de productos /// </summary> /// <param name="listaProductos">Lista de productos</param> /// <param name="producto">Producto a eliminar</param> public static void BajaProducto(List<Producto> listaProductos, Producto producto) { listaProductos.Remove(producto); } #endregion /// <summary> /// Muestra los datos de un producto empleado /// </summary> /// <returns>Retorna un string con todos los datos</returns> public override string Mostrar() { StringBuilder st = new StringBuilder(); st.AppendLine($"Sueldo: {this.Sueldo}"); st.AppendLine($"Puesto: {this.Puesto}"); st.Append("Días laborales: "); for (int j = 0; j < this.DiasLaborales.Length; j++) { st.Append(this.DiasLaborales[j] + " "); } st.AppendLine(""); st.AppendLine($"Horario de entrada: {this.HorarioEntrada.Hour}:{this.HorarioEntrada.Minute}hs."); st.AppendLine($"Horario de salida: {this.HorarioSalida.Hour}:{this.HorarioSalida.Minute}hs."); return base.Mostrar() + st.ToString(); } #region Sobrecarga de operadores /// <summary> /// Compara dos empleados y retorna el que tenga mayor sueldo /// </summary> /// <param name="empleado1">Primer empleado a comparar</param> /// <param name="empleado2">Segundo empleado a comparar</param> /// <returns>Retorna el empleado con mayor sueldo</returns> public static Empleado operator + (Empleado empleado1, Empleado empleado2) { Empleado empleadoMasPagado; if (empleado1.Sueldo > empleado2.Sueldo) { empleadoMasPagado = empleado1; } else { empleadoMasPagado = empleado2; } return empleadoMasPagado; } /// <summary> /// Compara dos empleados y retorna el que tenga menor sueldo /// </summary> /// <param name="empleado1">Primer empleado a comparar</param> /// <param name="empleado2">Segundo empleado a comparar</param> /// <returns>Retorna el empleado con menor sueldo</returns> public static Empleado operator - (Empleado empleado1, Empleado empleado2) { Empleado empleadoMasPagado; if (empleado1.Sueldo < empleado2.Sueldo) { empleadoMasPagado = empleado1; } else { empleadoMasPagado = empleado2; } return empleadoMasPagado; } #endregion #region Getters/Setters /// <summary> /// Devuelve o establece el valor de usuario /// </summary> public string Usuario { get { return this.usuario; } set { this.usuario = value; } } /// <summary> /// Devuelve o establece el valor de password /// </summary> public string Password { get { return this.password; } set { this.password = value; } } /// <summary> /// Devuelve o establece el valor de sueldo /// </summary> public double Sueldo { get { return this.sueldo; } set { if (ValidarSueldo(value)) { this.sueldo = value; } } } /// <summary> /// Devuelve o establece el puesto /// </summary> public EPuesto Puesto { get { return this.puesto; } set { this.puesto = value; } } /// <summary> /// Devuelve o establece los diasLaborales /// </summary> public string[] DiasLaborales { get { return this.diasLaborales; } set { this.diasLaborales = value; } } /// <summary> /// Devuelve o establece el horarioEntrada /// </summary> public DateTime HorarioEntrada { get { return this.horarioEntrada; } set { this.horarioEntrada = value; } } /// <summary> /// Devuelve o establece el horarioSalida /// </summary> public DateTime HorarioSalida { get { return this.horarioSalida; } set { this.horarioSalida = value; } } /// <summary> /// Devuelve el idEmpleado /// </summary> public int IdEmpleado { get { return this.idEmpleado; } set { this.idEmpleado = value; } } #endregion #region Validaciones /// <summary> /// Valida que el sueldo sea mayor o igual a 0 /// </summary> /// <param name="sueldo">Número a validar</param> /// <returns>Retorna true si el sueldo es válido o false si no</returns> public static bool ValidarSueldo(double sueldo) { bool retorno = false; if (sueldo >= 0) { retorno = true; } return retorno; } /// <summary> /// Valida que el sueldo sea mayor o igual a 0 /// </summary> /// <param name="sueldo">Número a validar</param> /// <returns>Retorna true si el sueldo es válido o false si no</returns> public static bool ValidarHora(string horaMinutos) { bool retorno = false; int hora; int minutos; string[] arrayHorasMinutos = horaMinutos.Split(":"); if (int.TryParse(arrayHorasMinutos[0], out hora) && hora < 24 && int.TryParse(arrayHorasMinutos[1], out minutos) && minutos < 60) { retorno = true; } return retorno; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AISpots : MonoBehaviour { [Header("READ ONLY")] public bool availability = true; }
using DotNetCoreIdentity.Application.BlogServices; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DotNetCoreIdentity.Web.ViewComponents { [ViewComponent] public class PostListViewComponent : ViewComponent { private readonly IPostService _postService; public PostListViewComponent(IPostService postService) { _postService = postService; } public async Task<IViewComponentResult> InvokeAsync() { var postList = await _postService.GetAll(); return View(postList.Result); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class HookReceiver : MonoBehaviour { PlayerInputAction controls; public Material idleMaterial; public Material focusMaterial; public Material activeMaterial; public GameObject mCamera; public GameObject mPlayer; public GameObject[] mWayPoints; public GameObject mPlate; public int step; public bool isReady; public bool isVisible; public bool testBool; enum States { Idle = 0, Focus = 1, Active = 2, Finished = 3 } public int State; public float speed = 0.1f; void Awake() { controls = new PlayerInputAction(); controls.PlayerControls.ActivateHook.performed += ctx => Grapple(); controls.PlayerControls.Enable(); } void Start() { mPlayer = GameObject.Find("Character"); mCamera = GameObject.Find("CameraBody"); } // Update is called once per frame void Update() { if(isReady) { this.GetComponent<MeshRenderer>().material = focusMaterial; } else this.GetComponent<MeshRenderer>().material = idleMaterial; switch (State) { case 0: Debug.Log("Entered Idle State"); if (mPlate.GetComponent<HookPlate>().isActive) { if (IsVisibleToCamera(transform)) { isVisible = true; isReady = true; } else isVisible = false; } else isReady = false; break; case 1: mPlayer.GetComponent<Rigidbody>().useGravity = false; mPlayer.transform.LookAt(mWayPoints[0].transform.position); float step = speed * Time.deltaTime; this.GetComponent<MeshRenderer>().material = activeMaterial; if (Vector3.Distance(mWayPoints[0].transform.position, mPlayer.transform.position) < 1.5f) { State++; } else { if (speed < 1.0f) speed += 0.01f; mPlayer.transform.position = Vector3.MoveTowards(mPlayer.transform.position, mWayPoints[0].transform.position, speed); } break; case 2: // mPlayer.transform.LookAt(mWayPoints[1].transform.position); if (Vector3.Distance(mWayPoints[1].transform.position, mPlayer.transform.position) < 1.5f) { State++; } else mPlayer.transform.position = Vector3.MoveTowards(mPlayer.transform.position, mWayPoints[1].transform.position, 0.35f); break; case 3: // mPlayer.transform.LookAt(mWayPoints[2].transform.position); if (Vector3.Distance(mWayPoints[2].transform.position, mPlayer.transform.position) < 1.5f) { State++; } else mPlayer.transform.position = Vector3.MoveTowards(mPlayer.transform.position, mWayPoints[2].transform.position, 0.35f); break; case 4: // mPlayer.transform.LookAt(mWayPoints[3].transform.position); if (Vector3.Distance(mWayPoints[3].transform.position, mPlayer.transform.position) < 1.5f) { State++; } else mPlayer.transform.position = Vector3.MoveTowards(mPlayer.transform.position, mWayPoints[3].transform.position, 0.35f); break; case 5: // Complete mPlayer.GetComponent<Rigidbody>().useGravity = true; speed = 0.1f; if (Vector3.Distance(mWayPoints[2].transform.position, mCamera.transform.position) < 11.501f) { State=0; } else mCamera.transform.position = Vector3.MoveTowards(mCamera.transform.position, mWayPoints[1].transform.position, 3.25f); this.GetComponent<MeshRenderer>().material = idleMaterial; Debug.Log("GRAPPLE COMPLETE"); break; default: break; } } public static bool IsVisibleToCamera(Transform transform) { //Check if this object is in the bounds of the viewport, Z included. Vector3 visTest = Camera.main.WorldToViewportPoint(transform.position); return (visTest.x >= 0 && visTest.y >= 0) && (visTest.x <= 1 && visTest.y <= 1) && visTest.z >= 0; } void Grapple() { if(isReady) { speed = 0; mPlayer.GetComponent<Rigidbody>().useGravity = false; State++; isReady = false; } } void onEnable() { controls.PlayerControls.Enable(); } void onDisable() { controls.PlayerControls.Disable(); } }
using System; using System.IO; using NUnit.Framework; namespace MinMaxSearch { public class SearcherTests { private readonly string path = @"D:\Учёба\ДО\MinMaxPath\TestMinMax"; [TestCase("Test1.txt",9,"1 3 2 4 5")] [TestCase("Test2.txt",13,"1 4")] [TestCase("Test3.txt",10,"1 4")] [TestCase("Test4.txt",15,"1 3 5 4")] [TestCase("Test5.txt",60, "1 2 4")] [TestCase("Test6.txt",70, "1 2 3 5")] [TestCase("Test7.txt",60,"1 2 3")] [TestCase("Test8.txt",60,"1 2")] [TestCase("Test9.txt",60,"1 2 4")] [TestCase("Test10.txt",0,"")] [TestCase("Test11.txt",60,"1 2 3 6")] [TestCase("Test12.txt",60,"3 6")] [TestCase("Test13.txt",60,"3 6")] [TestCase("Test14.txt",50,"3 5 6")] [TestCase("Test15.txt",15,"3 1 2 4")] [TestCase("Test16.txt",8,"3 5 6 4")] public void Test(string input, int expectedWeight, string expectedWay) { var superPath = Path.Combine(path, input); var searchResult = Searcher.SearchMaxMin(superPath); Assert.AreEqual(expectedWeight,searchResult.weight); Assert.AreEqual(expectedWay, string.Join(" ",searchResult.way)); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace DotNetCoreIdentity.Application.CategoryServices.Dtos { public class CreateCategoryInput { [Required] [Display(Name = "Kategori Adı")] public string Name { get; set; } [Required] [Display(Name = "SEO Dostu Url")] public string UrlName { get; set; } public string CreatedById { get; set; } public string CreatedBy { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class QuizPiece : ScriptableObject { public abstract string getPieceType(); }
// <copyright file="ActiveDirectoryUserDetailsResponse.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> namespace SmartLibrary.Models { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// User Login with Active Directory Model /// </summary> /// <CreatedBy>Bhargav Aboti</CreatedBy> /// <CreatedDate>26-Dec-2018</CreatedDate> public class ActiveDirectoryUserDetailsResponse : ActiveDirectoryResponseBase { /// <summary> /// Gets or sets the Data list. /// </summary> public ActiveDirectoryUserData Data { get; set; } } }
using C1.Win.C1FlexGrid; using Clients.Common; using Clients.MPD; using Common; using Common.Business; using Common.Extensions; using Common.Log; using Common.Presentation; using Common.Presentation.Controls; using Entity; using SessionSettings; using System; using System.Data; using System.ServiceModel; using System.Threading; using System.Windows.Forms; namespace MPD { public partial class XmlMTPTitles : SkinnableFormBase { #region Private Fields private string mChannel = String.Empty; private string mConnectionString = String.Empty; private string mDbLiveStaging = String.Empty; private int mId = 0; private MPDProxy mProxy = null; private DateTime mScheduleDate = DateTime.Now; private Users mUserData = null; private string mUserName = String.Empty; private UsersProxy mUserProxy = null; #endregion #region Constructors public XmlMTPTitles(int id, string channel, DateTime date) { InitializeComponent(); mId = id; mChannel = channel; mScheduleDate = date; } #endregion #region Public Properties public ClientPresentation ClientPresentation { get { if (mClientPresentation == null) mClientPresentation = new ClientPresentation(); return mClientPresentation; } set { mClientPresentation = value; } } #endregion #region Protected Methods /// <summary> /// Sets the size of the form as specified by the user. /// </summary> protected override void SetFormSize() { base.SetFormSize(); FormSize formSize = Settings.GetFormSize(mConnectionString, mUserName, this.Name); //Create a default size for the AddendumForm form in case the user is not in the database. //Use the MinimumSize set in the designer. if (formSize == null) { formSize = new FormSize() { Form_Left = 0, Form_Top = 0, Form_Width = 200, Form_Height = 200 }; } Left = formSize.Form_Left.Value; Top = formSize.Form_Top.Value; Width = formSize.Form_Width.Value; Height = formSize.Form_Height.Value; WindowState = FormWindowState.Normal; } #endregion #region Private Methods private void CloseProxy() { if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted) { Thread.Sleep(30); mProxy.Close(); } mProxy = null; } private void FillGrid(DateTime date, int id, string channel, string type) { using (DataTable dataTable = mProxy.GetXmlMTPData(id, channel, date)) { if (dataTable.HasRows()) { foreach (DataRow dr in dataTable.Rows) { int row = xmlMTPGrid.Rows.Add().Index; xmlMTPGrid.SetData(row, 0, id); xmlMTPGrid.SetData(row, 1, dr["xml_mtp"].ToString()); xmlMTPGrid.SetData(row, 2, dr["xml_section"].ToString()); xmlMTPGrid.SetData(row, 3, dr["title_type"].ToString()); xmlMTPGrid.SetData(row, 4, dr["title_value"].ToString()); if (!String.IsNullOrEmpty(type)) xmlMTPGrid.SetData(row, 5, type); } } } } /// <summary> /// Creates the synchronous proxy. /// </summary> private void OpenProxy() { if (mProxy == null || mProxy.State == CommunicationState.Closed) { mProxy = new MPDProxy(Settings.Endpoints["MPD"]); mProxy.Open(); mProxy.CreateMPDMethods(Settings.ConnectionString, Settings.UserName); } } private void SetUpForm() { mParameters = mUserData.ToParameterStruct(); mUserProxy = new UsersProxy(Settings.Endpoints["User"]); DetachableTabControl.TabPages.RemoveByKey("add"); detachPage.Text = "XML/MTP"; ApplySkin(mParameters); SetFormSize(); channels.Items.Clear(); channels.Items.Add(mChannel); channels.SelectedIndex = 0; string dateString = mScheduleDate.ToString("y"); dateString = dateString.Remove(dateString.IndexOf(",")) + " " + mScheduleDate.Year.ToString(); period.LabelText = dateString; id.LabelText = mId.ToString(); LoadXmlMTPTitles(); } private void Load_Click(object sender, EventArgs e) { LoadXmlMTPTitles(); } private void LoadXmlMTPTitles() { string dateString = period.LabelText.Insert(3, "01,"); DateTime date = StringOperations.DateTimeFromString(dateString, "MMM", " "); int idValue = Convert.ToInt32(id.LabelText); string channel = channels.Text; int previewGId = 0; int previewRId = 0; xmlMTPGrid.BeginUpdate(); xmlMTPGrid.AutoResize = false; xmlMTPGrid.Redraw = false; OpenProxy(); try { FillGrid(date, idValue, channel, ""); previewGId = mProxy.GetPreviewId(idValue, channel, date, "G"); if (previewGId > 0) FillGrid(date, previewGId, channel, "G"); previewRId = mProxy.GetPreviewId(idValue, channel, date, "R"); if (previewRId > 0) FillGrid(date, previewRId, channel, "R"); } catch (Exception e) { Logging.Log(e, "MPD", "XmlMTPTitles.LoadXmlMTPTitles"); ClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); } finally { xmlMTPGrid.EndUpdate(); xmlMTPGrid.AllowEditing = false; xmlMTPGrid.AutoResize = true; xmlMTPGrid.Redraw = true; CloseProxy(); } } private void XmlMTPGrid_DoubleClick(object sender, EventArgs e) { HitTestInfo hti = xmlMTPGrid.HitTest(xmlMTPGrid.PointToClient(MousePosition)); if (hti.Row < 1) return; object data = xmlMTPGrid.GetData(hti.Row, 0); if (data == null) return; int id = Convert.ToInt32(data); Settings.OpenOCX(Module.MovieInfo, id.ToString().PadLeft(8,'0')); } private void XmlMTPTitles_FormClosing(object sender, FormClosingEventArgs e) { CloseProxy(); FormSize formSize = new FormSize() { Form_Height = this.Height, Form_Width = this.Width, Form_Left = this.Left, Form_Top = this.Top, Form_Name = this.Name, Username = mUserName }; if (!Settings.SaveFormSize(mConnectionString, formSize)) ClientPresentation.ShowError("Unable to save XML/MTP form size."); } private void XmlMTPTitles_Load(object sender, EventArgs e) { if (DesignMode) return; Softgroup.NetResize.License.LicenseName = Constants.LicenseName; Softgroup.NetResize.License.LicenseUser = Constants.LicenseUser; Softgroup.NetResize.License.LicenseKey = Constants.LicenseKey; SetUpForm(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dominio.EntidadesNegocio; namespace Dominio.EntidadesNegocio { public class ItemPedido { public int Cantidad{ get; set; } public decimal PrecioVenta{ get; set; } public Producto producto; public decimal CalcularTotal() { return 0; } } }
using System; using Atc.Helpers; using Xunit; namespace Atc.Tests.Helpers { public class SimpleTypeHelperTests { [Theory] [InlineData("bool", typeof(bool))] [InlineData("byte", typeof(byte))] [InlineData("char", typeof(char))] [InlineData("DateTime", typeof(DateTime))] [InlineData("DateTimeOffset", typeof(DateTimeOffset))] [InlineData("decimal", typeof(decimal))] [InlineData("double", typeof(double))] [InlineData("float", typeof(float))] [InlineData("Guid", typeof(Guid))] [InlineData("int", typeof(int))] [InlineData("long", typeof(long))] [InlineData("object", typeof(object))] [InlineData("sbyte", typeof(sbyte))] [InlineData("short", typeof(short))] [InlineData("string", typeof(string))] [InlineData("uint", typeof(uint))] [InlineData("ulong", typeof(ulong))] [InlineData("ushort", typeof(ushort))] [InlineData("void", typeof(void))] [InlineData("bool?", typeof(bool?))] [InlineData("byte?", typeof(byte?))] [InlineData("char?", typeof(char?))] [InlineData("DateTime?", typeof(DateTime?))] [InlineData("DateTimeOffset?", typeof(DateTimeOffset?))] [InlineData("decimal?", typeof(decimal?))] [InlineData("double?", typeof(double?))] [InlineData("float?", typeof(float?))] [InlineData("Guid?", typeof(Guid?))] [InlineData("int?", typeof(int?))] [InlineData("long?", typeof(long?))] [InlineData("sbyte?", typeof(sbyte?))] [InlineData("short?", typeof(short?))] [InlineData("uint?", typeof(uint?))] [InlineData("ulong?", typeof(ulong?))] [InlineData("ushort?", typeof(ushort?))] public void GetBeautifyTypeName(string expected, Type type) => Assert.Equal(expected, SimpleTypeHelper.GetBeautifyTypeName(type)); [Theory] [InlineData(typeof(bool))] public void GetBeautifyTypeNameByRef(Type type) { // Act Exception exception = null; try { SimpleTypeHelper.GetBeautifyTypeNameByRef(type); } catch (Exception ex) { exception = ex; } // Assert Assert.NotNull(exception); Assert.IsType<ArgumentException>(exception); } [Theory] [InlineData("bool[]", typeof(bool[]))] [InlineData("byte[]", typeof(byte[]))] [InlineData("char[]", typeof(char[]))] [InlineData("DateTime[]", typeof(DateTime[]))] [InlineData("DateTimeOffset[]", typeof(DateTimeOffset[]))] [InlineData("decimal[]", typeof(decimal[]))] [InlineData("double[]", typeof(double[]))] [InlineData("float[]", typeof(float[]))] [InlineData("Guid[]", typeof(Guid[]))] [InlineData("int[]", typeof(int[]))] [InlineData("long[]", typeof(long[]))] [InlineData("object[]", typeof(object[]))] [InlineData("sbyte[]", typeof(sbyte[]))] [InlineData("short[]", typeof(short[]))] [InlineData("string[]", typeof(string[]))] [InlineData("uint[]", typeof(uint[]))] [InlineData("ulong[]", typeof(ulong[]))] [InlineData("ushort[]", typeof(ushort[]))] public void GetBeautifyArrayTypeName(string expected, Type type) => Assert.Equal(expected, SimpleTypeHelper.GetBeautifyArrayTypeName(type)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Java.Lang; namespace Goosent.Adapters { class AvalibleStreamingPlatformsArrayAdapter : BaseAdapter { private List<string> _platforms; private Context mContext; public AvalibleStreamingPlatformsArrayAdapter(Context context, List<string> platforms) { mContext = context; _platforms = platforms; } public override int Count { get { return _platforms.Count; } } public override Java.Lang.Object GetItem(int position) { throw new NotImplementedException(); } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { row = LayoutInflater.From(mContext).Inflate(Resource.Layout.PlatformsSpinnerRow, null, false); } TextView platformNameTextView = (TextView)row.FindViewById(Resource.Id.platformSpinner_platformName_TextView); platformNameTextView.Text = _platforms[position]; return row; } public override View GetDropDownView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { row = LayoutInflater.From(mContext).Inflate(Resource.Layout.PlatformsSpinnerDropRow, null, false); } TextView chatName = (TextView)row.FindViewById(Resource.Id.platformSpinner_platformName_TextView); chatName.Text = _platforms[position]; return row; } } }
using NCMB; using System.Collections.Generic; namespace NCMB { public class HighScore { public const int RANKING_MAX = 20; public int score { get; set; } public int stage { get; set; } public int time { get; set; } public string name { get; private set; } public bool isCorrect { get; set; } public bool isCorrectFinish { get; set; } public string errorCode { get; set; } // コンストラクタ ----------------------------------- public HighScore(int _score, int _stage, string _name) { score = _score; stage = _stage; name = _name; Init (); } public void Init() { isCorrectFinish = false; isCorrect = false; } // ランキングで表示するために文字列を整形 ----------- public string print() { return name + " " + score; } // サーバーにハイスコアを保存 ------------------------- public void save() { isCorrect = true; errorCode = null; // データストアの「HighScore」クラスから、Nameをキーにして検索 NCMBQuery<NCMBObject> query = new NCMBQuery<NCMBObject> ("HighScore"); query.WhereEqualTo ("Name", name); query.FindAsync ((List<NCMBObject> objList ,NCMBException e) => { //検索成功したら if (e == null) { objList[0]["Score"] = score; objList[0]["Stage"] = stage; objList[0].SaveAsync(); isCorrectFinish = true; errorCode = null; } else { errorCode = e.ErrorCode; } }); } // サーバーからハイスコアを取得 ----------------- public void fetch() { isCorrect = true; errorCode = null; // データストアの「HighScore」クラスから、Nameをキーにして検索 NCMBQuery<NCMBObject> query = new NCMBQuery<NCMBObject> ("HighScore"); query.WhereEqualTo ("Name", name); query.FindAsync ((List<NCMBObject> objList ,NCMBException e) => { //検索成功したら if (e == null) { // ハイスコアが未登録だったら if( objList.Count == 0 ) { NCMBObject obj = new NCMBObject("HighScore"); obj["Name"] = name; obj["Score"] = 0; obj["Stage"] = 0; obj.SaveAsync(); } // ハイスコアが登録済みだったら else { score = System.Convert.ToInt32( objList[0]["Score"] ); stage = System.Convert.ToInt32( objList[0]["Stage"] ); } isCorrectFinish = true; errorCode = null; } else { errorCode = e.ErrorCode; } }); } } public class LeaderBoard { public int currentRank = 0; public List<NCMB.HighScore> topRankers = null; public List<NCMB.HighScore> neighbors = null; public bool isCorrect { get; set; } public bool isfetchRankFinish { get; set; } public bool isfetchTopRankersFinish { get; set; } public string errorCode { get; set; } public void Init() { isfetchRankFinish = false; isfetchTopRankersFinish = false; isCorrect = false; } // 現プレイヤーのハイスコアを受けとってランクを取得 --------------- public void fetchRank( int currentScore ) { isCorrect = true; errorCode = null; isfetchRankFinish = false; // データスコアの「HighScore」から検索 NCMBQuery<NCMBObject> rankQuery = new NCMBQuery<NCMBObject> ("HighScore"); rankQuery.WhereGreaterThan("Score", currentScore); rankQuery.CountAsync((int count , NCMBException e )=>{ if(e != null){ //件数取得失敗 errorCode = e.ErrorCode; }else{ //件数取得成功 currentRank = count+1; // 自分よりスコアが上の人がn人いたら自分はn+1位 } isfetchRankFinish = true; }); } // サーバーからTop10を取得 --------------- public void fetchTopRankers() { isCorrect = true; errorCode = null; isfetchTopRankersFinish = false; // データストアの「HighScore」クラスから検索 NCMBQuery<NCMBObject> query = new NCMBQuery<NCMBObject> ("HighScore"); query.OrderByDescending ("Score"); query.Limit = HighScore.RANKING_MAX; query.FindAsync ((List<NCMBObject> objList ,NCMBException e) => { if (e != null) { //検索失敗時の処理 errorCode = e.ErrorCode; } else { //検索成功時の処理 List<NCMB.HighScore> list = new List<NCMB.HighScore>(); // 取得したレコードをHighScoreクラスとして保存 foreach (NCMBObject obj in objList) { int score = System.Convert.ToInt32(obj["Score"]); int stage = System.Convert.ToInt32(obj["Stage"]); string name = System.Convert.ToString(obj["Name"]); list.Add( new HighScore( score, stage, name ) ); } topRankers = list; } isfetchTopRankersFinish = true; }); } // サーバーからrankの前後2件を取得 --------------- public void fetchNeighbors() { neighbors = new List<NCMB.HighScore>(); isCorrect = true; errorCode = null; // スキップする数を決める(ただし自分が1位か2位のときは調整する) int numSkip = currentRank - 3; if(numSkip < 0) numSkip = 0; // データストアの「HighScore」クラスから検索 NCMBQuery<NCMBObject> query = new NCMBQuery<NCMBObject> ("HighScore"); query.OrderByDescending ("Score"); query.Skip = numSkip; query.Limit = HighScore.RANKING_MAX; query.FindAsync ((List<NCMBObject> objList ,NCMBException e) => { if (e != null) { //検索失敗時の処理 errorCode = e.ErrorCode; } else { //検索成功時の処理 List<NCMB.HighScore> list = new List<NCMB.HighScore>(); // 取得したレコードをHighScoreクラスとして保存 foreach (NCMBObject obj in objList) { int score = System.Convert.ToInt32(obj["Score"]); int stage = System.Convert.ToInt32(obj["Stage"]); string name = System.Convert.ToString(obj["Name"]); list.Add( new HighScore( score, stage, name ) ); } neighbors = list; } }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using TenmoClient.Data; namespace TenmoClient { class ConsoleServices { public void PrintAccounts(List<Account> list) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(@" "); Console.WriteLine(@"::: ::: :::::::: ::: ::: ::::::::: ::: :::::::: :::::::: :::::::: ::: ::: :::: ::: ::::::::::: :::::::: "); Console.WriteLine(@":+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+:+: :+: :+: :+: :+: "); Console.WriteLine(@" +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ "); Console.WriteLine(@" +#++: +#+ +:+ +#+ +:+ +#++:++#: +#++:++#++: +#+ +#+ +#+ +:+ +#+ +:+ +#+ +:+ +#+ +#+ +#++:++#++ "); Console.WriteLine(@" +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+ "); Console.WriteLine(@" #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+#+# #+# #+# #+# "); Console.WriteLine(@" ### ######## ######## ### ### ### ### ######## ######## ######## ######## ### #### ### ######## "); Console.WriteLine(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.White; foreach (Account a in list) { Console.WriteLine($"Your balance is {a.Balance}, in account {a.AccountId}."); } } public void PrintBalance(Account account) { Console.WriteLine($"Current Balance: {account.Balance}"); } public void PrintTransfers(Dictionary<int, Transfer> transfers, API_User user) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(@"::::::::::: ::::::::: ::: :::: ::: :::::::: :::::::::: :::::::::: ::::::::: :::::::: "); Console.WriteLine(@" :+: :+: :+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:"); Console.WriteLine(@" +:+ +:+ +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ "); Console.WriteLine(@" +#+ +#++:++#: +#++:++#++: +#+ +:+ +#+ +#++:++#++ :#::+::# +#++:++# +#++:++#: +#++:++#++"); Console.WriteLine(@" +#+ +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+ +#+ +#+ +#+ +#+ "); Console.WriteLine(@" #+# #+# #+# #+# #+# #+# #+#+# #+# #+# #+# #+# #+# #+# #+# #+# "); Console.WriteLine(@" ### ### ### ### ### ### #### ######## ### ########## ### ### ######## "); Console.WriteLine(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("id from/to name amount"); foreach (KeyValuePair<int, Transfer> t in transfers) { Console.ForegroundColor = ConsoleColor.White; if (t.Value.AccountFrom.AccountId == user.UserId) { Console.WriteLine($"{t.Key} --> {t.Value.ToUsername} ${t.Value.Amount} "); } else { Console.WriteLine($"{t.Key} <-- {t.Value.FromUsername} ${t.Value.Amount} "); } } Console.ForegroundColor = ConsoleColor.Blue; } public void PrintRequests(Dictionary<int, Transfer> transfers, API_User user) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("id name amount"); foreach (KeyValuePair<int, Transfer> t in transfers) { if (t.Value.TransferStatusID == 1 && t.Value.AccountFrom.AccountId == user.UserId) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"{t.Key} {t.Value.ToUsername} ${t.Value.Amount} "); } } Console.ForegroundColor = ConsoleColor.Blue; } public void TransferDetails(Transfer transfer, API_User user) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("---"); Console.WriteLine($"ID No. {transfer.TransferID}"); Console.WriteLine($"FROM: {transfer.FromUsername}"); Console.WriteLine($"TO: {transfer.ToUsername}"); if (transfer.TransferTypeID == 1) { Console.WriteLine("TYPE: REQUEST"); } else { Console.WriteLine("TYPE: SEND"); } if (transfer.TransferStatusID == 1) { Console.WriteLine("STATUS: PENDING"); } else if (transfer.TransferStatusID == 2) { Console.WriteLine("STATUS: APPROVED"); } else { Console.WriteLine("STATUS: REJECTED"); } Console.WriteLine($"AMOUNT: ${transfer.Amount}"); Console.WriteLine($"---"); Console.ForegroundColor = ConsoleColor.Blue; } public Dictionary<int, API_User> NamesToDiction(List<API_User> list) { Dictionary<int, API_User> names = new Dictionary<int, API_User> { }; foreach (API_User name in list) { names.Add(name.UserId, name); } return names; } public void PrintUsers(List<API_User> names, API_User user) { foreach (API_User name in names) { if (name.Username == user.Username) { continue; } Console.WriteLine($"{name.UserId} || {name.Username}"); } } public void TransferRequest(int newId) { Console.WriteLine($"\n||Request Completed|| Transfer ID No. : {newId}"); } public void TransferComplete(decimal newBal) { Task.Run(() => Console.Beep(1245, 100)); Task.Run(() => Console.Beep(1245, 100)); Task.Run(() => Console.Beep(1245, 100)); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(); Console.WriteLine(); Console.WriteLine(@" :::::::: ::: ::: :::::::: :::::::: :::::::::: :::::::: :::::::: :::"); Console.WriteLine(@" :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: "); Console.WriteLine(@" +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ "); Console.WriteLine(@" +#++:++#++ +#+ +:+ +#+ +#+ +#++:++# +#++:++#++ +#++:++#++ +#+ "); Console.WriteLine(@" +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ "); Console.WriteLine(@" #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# "); Console.WriteLine(@" ######## ######## ######## ######## ########## ######## ######## ### "); Console.WriteLine(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine($"\n||Transfer completed||\nCurrent Balance: ${newBal}"); Console.ForegroundColor = ConsoleColor.Blue; } public void ErrorMessage() { Task.Run(() => Console.Beep(523, 200)); Task.Run(() => Console.Beep(494, 200)); Task.Run(() => Console.Beep(466, 200)); Task.Run(() => Console.Beep(440, 800)); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(@":::::::::: ::::::::: ::::::::: :::::::: ::::::::: ::: ::::::::::: :::: ::: ::: ::: ::: ::: ::::::::::: :::::::::"); Console.WriteLine(@":+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:"); Console.WriteLine(@"+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+"); Console.WriteLine(@"+#++:++# +#++:++#: +#++:++#: +#+ +:+ +#++:++#: +#+ +#+ +#+ +:+ +#+ +#+ +:+ +#++:++#++: +#+ +#+ +#+ +:+"); Console.WriteLine(@"+#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+"); Console.WriteLine(@"#+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+#+# #+#+#+# #+# #+# #+# #+# #+# #+#"); Console.WriteLine(@"########## ### ### ### ### ######## ### ### ### ########### ### #### ### ### ### ########## ########### #########"); Console.WriteLine(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Blue; } } }
using Alabo.Datas.Stores; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Entities; using Alabo.Domains.Services.Add; using Alabo.Runtime.Config; using System; namespace Alabo.Domains.Services.Attach { public abstract class AttachBase<TEntity, TKey> : AddBase<TEntity, TKey>, IAttach<TEntity, TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> { public AttachBase(IUnitOfWork unitOfWork, IStore<TEntity, TKey> store) : base(unitOfWork, store) { } public string GetTableName() { throw new NotImplementedException(); // return Store.GetTableName(); } public DatabaseType GetDatabaseType() { throw new NotImplementedException(); //return Store.GetDatabaseType(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PopUpWindown : MonoBehaviour { public GameObject window; public Text messageField; // Start is called before the first frame update public void Show(string message) { messageField.text = message; } public void Hide() { window.SetActive(false); } }
 namespace SMG.Common.Exceptions { public enum ErrorCode { SyntaxError = 1, ConditionNeverSatisfied, AmbigousPreCondition, AmbigousPostCondition, TypeRedefinition, GuardNameReused, UndefinedVariable, VariableRedefinition, InvalidStateName, UndefinedType, BadCondition, Unsupported } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IRAPShared; namespace IRAP.Entity.IRAP { [Serializable()] [IRAPDB(TableName ="IRAP..stb052")] public class Stb052 { [IRAPKey()] public long PartitioningKey { get; set; } public int TreeID { get; set; } [IRAPKey()] public int NodeID { get; set; } public string Code { get; set; } public int NameID { get; set; } public string NodeName { get; set; } public int Father { get; set; } public double UDFOrdinal { get; set; } public int NodeDepth { get; set; } public int NodeStatus { get; set; } public int CSTRoot { get; set; } public int IconID { get; set; } public Stb052 Clone() { return MemberwiseClone() as Stb052; } } }
using System; using System.ComponentModel.DataAnnotations; namespace MyProject.Models { public class Game { [Key] [ScaffoldColumn(false)] public int GameID { get; set; } [Display(Name = "Game Logo/Cover")] public string Picture { get; set; } [Required] [StringLength(60)] public string Title { get; set; } [StringLength(500)] [DataType(DataType.MultilineText)] public string Description { get; set; } [Url] [Display(Name = "Game Link")] public string GameLink { get; set; } [Display(Name = "Age Rating")] [StringLength(3)] public string AgeRating { get; set; } [StringLength(60)] public string Genre { get; set; } [Display(Name = "Number of Players")] [Range(1, 10)] public int NumberOfPlayers { get; set; } [Display(Name = "Available Platform")] public string AvailablePlatforms { get; set; } [Display(Name = "Reviews Required")] [Range(1,100)] public int ReviewQuantity { get; set; } [Display(Name = "Reward for review (£)")] [DataType(DataType.Currency)] [DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)] [Range(0.01,20.00)] public decimal ReviewReward { get; set; } [Display(Name = "Budget (£)")] [DataType(DataType.Currency)] [DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)] public decimal Budget { get; set; } [Display(Name = "Date Posted")] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public DateTime DatePosted { get; set; } public ApplicationUser Developer { get; set; } } }
// <copyright file="GetBundlePathFixture.cs" company="Morten Larsen"> // Copyright (c) Morten Larsen. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> using System.ComponentModel; using System.Threading.Tasks; using FluentAssertions; namespace AspNetWebpack.AssetHelpers.Testing { /// <summary> /// Fixture for testing GetBundlePathAsync function in AssetService. /// </summary> public class GetBundlePathFixture : AssetServiceBaseFixture { /// <summary> /// Valid bundle name with extension. /// </summary> public static readonly string ValidBundleWithExtension = $"{ValidBundleWithoutExtension}.js"; /// <summary> /// Invalid bundle name with extension. /// </summary> public static readonly string InvalidBundleWithExtension = $"{InvalidBundle}.js"; /// <summary> /// Initializes a new instance of the <see cref="GetBundlePathFixture"/> class. /// </summary> /// <param name="bundle">The bundle name param to be used in GetBundlePathAsync.</param> /// <param name="fileType">The file type param to be used in GetBundlePathAsync.</param> public GetBundlePathFixture(string bundle, FileType? fileType = null) : base(ValidBundleWithExtension) { Bundle = bundle; FileType = fileType; SetupGetFromManifest(); } private string Bundle { get; } private FileType? FileType { get; } private string BundleWithCssExtension => $"{Bundle}.css"; private string BundleWithJsExtension => $"{Bundle}.js"; /// <summary> /// Calls GetBundlePathAsync with provided parameters. /// </summary> /// <returns>The result of GetBundlePathAsync.</returns> public async Task<string?> GetBundlePathAsync() { return await AssetService .GetBundlePathAsync(Bundle, FileType) .ConfigureAwait(false); } /// <summary> /// Verify that GetBundlePathAsync was called with an empty string. /// </summary> /// <param name="result">The result to assert.</param> public void VerifyEmpty(string? result) { result.Should().BeNull(); VerifyDependencies(); VerifyNoOtherCalls(); } /// <summary> /// Verify that GetBundlePathAsync was called with an invalid bundle. /// </summary> /// <param name="result">The result to assert.</param> public void VerifyNonExisting(string? result) { result.Should().BeNull(); VerifyDependencies(); VerifyGetFromManifest(); VerifyNoOtherCalls(); } /// <summary> /// Verify that GetBundlePathAsync was called with a valid bundle. /// </summary> /// <param name="result">The result to assert.</param> public void VerifyExisting(string? result) { result.Should().NotBeNull() .And.Be(ValidBundleResultPath); VerifyDependencies(); VerifyGetFromManifest(); VerifyNoOtherCalls(); } private void VerifyGetFromManifest() { switch (FileType) { case AssetHelpers.FileType.CSS: VerifyGetFromManifest(BundleWithCssExtension); break; case AssetHelpers.FileType.JS: VerifyGetFromManifest(BundleWithJsExtension); break; case null: VerifyGetFromManifest(Bundle); break; default: throw new InvalidEnumArgumentException(nameof(FileType), (int)FileType, typeof(FileType)); } } } }
namespace CheckIt.Compilation.Custom { public class CustomCompilationInfoBase : CompilationInfoBase { public CustomCompilationInfoBase(CustomProject project) { this.Project = project; } } }
using Models; using Repository; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BAL { public class EmployeeManager { EmployeeCommandRepository ecr = new EmployeeCommandRepository(); EmployeeQueryRepository eqr = new EmployeeQueryRepository(); CalEmpBonusAndHourlypay clp = new CalEmpBonusAndHourlypay(); public void SaveEmployeeData(Employees emp) { IEmployeeManager imp = clp.DecideAndCalculate(emp.EmployeeTypeId); emp.Bonusinc = imp.GetBonus(); emp.HourlyPay = imp.GetHourlyPay(); ecr.SaveEmployee(emp); } public void UpdateEmployeeData(Employees emp) { IEmployeeManager imp = clp.DecideAndCalculate(emp.EmployeeTypeId); emp.Bonusinc = imp.GetBonus(); emp.HourlyPay = imp.GetHourlyPay(); ecr.UpdateEmployee(emp); } public Employees SearchEmployeeData(int empId) { Employees emp = eqr.SearchResult(empId); return emp; } public void DeleteEmployeeData(int empId) { ecr.DeleteEmployee(empId); } public DataTable ShowEmployeeData() { DataTable emp = eqr.ShowEmployees(); return emp; } } }
using System; using System.Collections.Generic; using System.Text; namespace Core { public class Calc { public int Add(int a, int b) { return a + b; } public int Multiply(int a, int b) { return a * b; } } }
using EddiSpeechService; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTests { [TestClass] public class HumanizeTests { [TestMethod] public void TestNullInput() { Assert.IsNull(Translations.Humanize(null)); } [DataTestMethod] [DataRow(0, "zero")] [DataRow(456, "456")] [DataRow(-1000, "minus 1,000")] [DataRow(100000, "100,000")] [DataRow(51000001, "51,000,000")] [DataRow(-51000000, "minus 51,000,000")] [DataRow(-12345, "well over minus 12 thousand")] [DataRow(1800001, "1.8 million")] [DataRow(-1999001, "nearly minus 2 million")] public void TestIntToFloatingMantissa(int number, string expected) { Assert.AreEqual(expected, Translations.Humanize(number, false)); } [DataTestMethod] [DataRow(0, "zero")] [DataRow(456, "456")] [DataRow(-1000, "minus 1,000")] [DataRow(100000, "100,000")] [DataRow(51000001, "51,000,000")] [DataRow(-51000000, "minus 51,000,000")] [DataRow(94500, "94,500")] [DataRow(9450000, "nearly 9 and a half million")] [DataRow(94500000, "94,500,000")] [DataRow(-12345, "well over minus 12 thousand")] [DataRow(1800001, "1,800,000")] [DataRow(-1999001, "nearly minus 2 million")] [DataRow(-1100001, "minus 1,100,000")] [DataRow(-1110001, "just over minus 1 million")] [DataRow(-1210001, "over minus 1 million")] [DataRow(-1310001, "well over minus 1 million")] [DataRow(-1410001, "nearly minus 1 and a half million")] [DataRow(-1510001, "around minus 1 and a half million")] [DataRow(-1610001, "over minus 1 and a half million")] [DataRow(-1810001, "well over minus 1 and a half million")] [DataRow(-1999001, "nearly minus 2 million")] public void TestIntToIntegerMantissa(int number, string expected) { Assert.AreEqual(expected, Translations.Humanize(number, true)); } [DataTestMethod] [DataRow(-12345.0, "well over minus 12 thousand")] [DataRow(0.15555555, "0.16")] [DataRow(0.015555555, "0.016")] [DataRow(0.0015555555, "0.0016")] [DataRow(-0.15555555, "minus 0.16")] [DataRow(-0.015555555, "minus 0.016")] [DataRow(-0.0015555555, "minus 0.0016")] [DataRow(-12.1, "minus 12.1")] [DataRow(-12.01, "minus 12")] [DataRow(6.459E5, "over 640 thousand")] [DataRow(1.8E6, "1.8 million")] [DataRow(9.4571E11, "over 940 billion")] [DataRow(4.36156E14, "over 430 trillion")] [DataRow(9.1235E17, "over 912 quadrillion")] public void TestDoubleToFloatingMantissa(double number, string expected) { Assert.AreEqual(expected, Translations.Humanize((decimal)number, false)); } [DataTestMethod] [DataRow(-12345.0, "well over minus 12 thousand")] [DataRow(0.15555555, "0.16")] [DataRow(0.015555555, "0.016")] [DataRow(0.0015555555, "0.0016")] [DataRow(-0.15555555, "minus 0.16")] [DataRow(-0.015555555, "minus 0.016")] [DataRow(-0.0015555555, "minus 0.0016")] [DataRow(-12.1, "minus 12.1")] [DataRow(-12.01, "minus 12")] [DataRow(6.459E5, "over 640 thousand")] [DataRow(1.8E6, "1,800,000")] [DataRow(9.4571E11, "over 940 billion")] [DataRow(4.36156E14, "over 430 trillion")] [DataRow(9.1235E17, "over 912 quadrillion")] public void TestDoubleToIntegerMantissa(double number, string expected) { Assert.AreEqual(expected, Translations.Humanize((decimal)number, true)); } [DataTestMethod] [DataRow(1100001, "1.1 million")] [DataRow(1110001, "just over 1 million")] [DataRow(1210001, "over 1 million")] [DataRow(1310001, "well over 1 million")] [DataRow(1410001, "nearly 1 and a half million")] [DataRow(1510001, "around 1 and a half million")] [DataRow(1610001, "over 1 and a half million")] [DataRow(1810001, "well over 1 and a half million")] [DataRow(1999001, "nearly 2 million")] public void Test2ndDigitRangePositive(int number, string expected) { Assert.AreEqual(expected, Translations.Humanize(number, false)); } [DataTestMethod] [DataRow(-1100001, "minus 1.1 million")] [DataRow(-1110001, "just over minus 1 million")] [DataRow(-1210001, "over minus 1 million")] [DataRow(-1310001, "well over minus 1 million")] [DataRow(-1410001, "nearly minus 1 and a half million")] [DataRow(-1510001, "around minus 1 and a half million")] [DataRow(-1610001, "over minus 1 and a half million")] [DataRow(-1810001, "well over minus 1 and a half million")] [DataRow(-1999001, "nearly minus 2 million")] public void Test2ndDigitRangeNegative(int number, string expected) { Assert.AreEqual(expected, Translations.Humanize(number, false)); } [DataTestMethod] [DataRow(111000, "111,000")] [DataRow(111100, "just over 111 thousand")] [DataRow(111200, "over 111 thousand")] [DataRow(111700, "nearly 112 thousand")] public void TestNumbersWith3DigitMantissa(int number, string expected) { Assert.AreEqual(expected, Translations.Humanize(number, false)); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using Olive.Data; using System.Linq.Expressions; using Olive.Web.MVC.ViewModels; using Olive.Web.MVC.Areas.Administration.ViewModels; using Olive.Data.Uow; using System.Diagnostics; using System.Windows.Forms; using System.Threading; using Olive.Web.MVC.Helpers; using Olive.Web.MVC.ActionFilters; using CloudinaryDotNet; using System.Configuration; using CloudinaryDotNet.Actions; using System.IO; namespace Olive.Web.MVC.Areas.Administration.Controllers { public class AdminRecipesController : BaseAdminController { //protected static readonly Expression<Func<Recipe, AdminRecipeIndexViewModel>> AsAdminRecipeIndexViewModel = //entity => new AdminRecipeIndexViewModel //{ // RecipeID = entity.RecipeID, // Title = entity.Title, // ImageURL = entity.ImageURL, // PreparationTime = (int)entity.PreparationTime, // CookingTime = (int)entity.CookingTime, // Serves = (int)entity.Serves, // Date = (DateTime)entity.Date, // Rating = (int)entity.Rating, // NumberOfHits = (int)entity.NumberOfHits, // NumberOfLikes = (int)entity.NumberOfLikes, // Category = entity.Categories.FirstOrDefault().Name, // ParentCategory = entity.Categories.Select(x => x.Category1.Name).FirstOrDefault() //}; private UowData db = new UowData(); private AdminRecipeViewModel newRecipeVM; private AdminRecipeViewModel editRecipeVM; private int[] minutes; private int[] hours; private int[] servesArray; private int[] rating; private string[] recommendationArray; public AdminRecipesController() { this.hours = new int[] { 0,1,2,3,4,5,6,7,8,9,10,11,12 }; this.minutes = new int[] { 0,5,10,15,20,25,30,35,40,45,50,55 }; this.servesArray = new int[] { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; this.rating = new int[] { 1,2,3,4,5 }; this.recommendationArray = new string[] { "Да","Не" }; this.newRecipeVM = new AdminRecipeViewModel(); //newRecipeVM.Recipe = new Recipe(); //List<Step> stepsList = new List<Step>(); //stepsList.Add(new Step()); //List<RecipeItems_Ingredients> ingredientsList = new List<RecipeItems_Ingredients>(); //ingredientsList.Add(new RecipeItems_Ingredients()); //newRecipeVM.Recipe.RecipeItems.Add(new RecipeItem() { Steps = stepsList, RecipeItems_Ingredients = ingredientsList }); //newRecipeVM.Recipe.Date = DateTime.Now; //newRecipeVM.Title = ""; newRecipeVM.ImageURL = @"http://res.cloudinary.com/hqz5ohs1v/image/upload/v1413825708/null_image.png"; newRecipeVM.ParentCategories = db.Categories.AllParentCategories(); newRecipeVM.ChildrenCategories = db.Categories.AllChildrenCategories(); newRecipeVM.PrepTimeHours = this.hours; newRecipeVM.SelectedPrepTimeHours = -1; newRecipeVM.PrepTimeMinutes = this.minutes; newRecipeVM.SelectedPrepTimeMinutes = -1; newRecipeVM.CookTimeHours = this.hours; newRecipeVM.SelectedCookTimeHours = -1; newRecipeVM.CookTimeMinutes = this.minutes; newRecipeVM.SelectedCookTimeMinutes = -1; newRecipeVM.Serves = this.servesArray; newRecipeVM.SelectedServes = 0; newRecipeVM.Rating = this.rating; newRecipeVM.SelectedRating = 0; newRecipeVM.Sources = this.db.Sources.All(); newRecipeVM.SelectedSource = 0; newRecipeVM.Recommendation = this.recommendationArray.ToList(); newRecipeVM.SelectedRecommendation = "--- избери дали да е препоръчана ---"; newRecipeVM.PublishedDate = DateTime.Now; ViewBag.UnitsList = this.db.Units.All().ToList(); ViewBag.IngredientsList = this.db.Ingredients.All().ToList(); RecipeItem recipeItem = new RecipeItem(); recipeItem.Steps = new List<Step>(); recipeItem.RecipeItems_Ingredients = new List<RecipeItems_Ingredients>(); newRecipeVM.RecipeItems.Add(recipeItem); } // // GET: /Administration/Recipes/ public ViewResult Index() { //var recipes = db.Recipes.Include(r => r.Source); var recipes = db.Recipes.All(); return View(recipes.ToList()); } // GET: /Administration/Recipes/Details/5 public ViewResult Details(int id) { Recipe recipe = db.Recipes.GetById(id); return View(recipe); } // GET: /Administration/Recipes/Create public ActionResult Create() { return View(this.newRecipeVM); } // POST: /Administration/Recipes/Create [HttpPost] public ActionResult Create(AdminRecipeViewModel recipeModel) { //HttpPostedFileBase img = recipeModel.Image; //UploadRecipeImage(recipeModel.Image,recipeModel.Title); if (ModelState.IsValid) { Recipe newRecipe = ParseRecipeVMToRecipeModel(recipeModel); this.db.Recipes.Add(newRecipe); int result = this.db.SaveChanges(); if (result != 0) { return RedirectToAction("Index"); } } this.newRecipeVM.RecipeItems = recipeModel.RecipeItems; return View(this.newRecipeVM); } // GET: /Administration/Recipes/Edit/5 //[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id) { //ViewData["RecipeItemID"] = Request.Form["recipeItems.index"]; Recipe recipeForEdit = db.Recipes.GetById(id); this.editRecipeVM = ParseRecipeModelToRecipeVM(recipeForEdit); return View(this.editRecipeVM); } // POST: /Administration/Recipes/Edit/5 [HttpPost] public ActionResult Edit(AdminRecipeViewModel recipeEditModel) { //if (ModelState.IsValid) //{ //} #region Delete old RecipeItems var recipe = this.db.Recipes.All() .Include(r => r.Categories) .Include(r => r.RecipeItems) .FirstOrDefault(r => r.RecipeID == recipeEditModel.RecipeID); var recipeItems = recipe.RecipeItems; foreach (var recipeItem in recipeItems.ToList()) { foreach (var step in recipeItem.Steps.ToList()) { this.db.Steps.Delete(step); } foreach (var ingredient in recipeItem.RecipeItems_Ingredients.ToList()) { this.db.RecipeItems_Ingredients.Delete(ingredient); } this.db.RecipeItems.Delete(recipeItem); } db.SaveChanges(); #endregion Recipe recipeForEdit = this.db.Recipes.GetById(recipeEditModel.RecipeID); recipeForEdit = ParseRecipeVMToRecipeModel_Update(recipeForEdit, recipeEditModel); this.db.Recipes.Update(recipeForEdit); int result = this.db.SaveChanges(); if (result != 0) { return RedirectToAction("Details", "Recipes", new { recipeID = recipeEditModel.RecipeID, title = recipeEditModel.Title.Replace(' ', '-'), area = "" }); } //ViewData["RecipeItemID"] = Request.Form["recipeItems.index"]; recipeEditModel.ParentCategories = db.Categories.AllParentCategories(); recipeEditModel.ChildrenCategories = db.Categories.AllChildrenCategories(); recipeEditModel.PrepTimeHours = this.hours; recipeEditModel.PrepTimeMinutes = this.minutes; recipeEditModel.CookTimeHours = this.hours; recipeEditModel.CookTimeMinutes = this.minutes; recipeEditModel.Serves = this.servesArray; recipeEditModel.Rating = this.rating; recipeEditModel.Sources = this.db.Sources.All(); recipeEditModel.Recommendation = this.recommendationArray; return View(recipeEditModel); } public ActionResult Delete(int id) { //Recipe recipe = db.Recipes.Find(id); Recipe recipe = db.Recipes.GetById(id); return View(recipe); } // // POST: /Administration/Recipes/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { var recipe = this.db.Recipes.All() .Include(r => r.Categories) .Include(r => r.RecipeItems) .FirstOrDefault(r => r.RecipeID == id); var recipeItems = recipe.RecipeItems; foreach (var recipeItem in recipeItems.ToList()) { foreach (var step in recipeItem.Steps.ToList()) { this.db.Steps.Delete(step); } foreach (var ingredient in recipeItem.RecipeItems_Ingredients.ToList()) { this.db.RecipeItems_Ingredients.Delete(ingredient); } this.db.RecipeItems.Delete(recipeItem); } db.Recipes.Delete(recipe); int result=db.SaveChanges(); if (result!=0) { DeleteRecipeImage(recipe.ImageURL); } return RedirectToAction("Index"); } public ActionResult GetChildrenCategories(int? id) { var childrenCategories = db.Categories.GetChildrenCategoriesByParentID((int)id); var childrenCategoriesJSON = childrenCategories.Select(x => new { ID = x.CategoryID, Name = x.Name }); //Add JsonRequest behavior to allow retrieving states over http get return Json(childrenCategoriesJSON, JsonRequestBehavior.AllowGet); //return Content(childrenCategoriesJSON.ToString(), "application/json"); } public ActionResult AddIngredient(string recipeItemID) { RecipeItems_Ingredients recipeItemIngredient = new RecipeItems_Ingredients(); recipeItemIngredient.Quantity = 0; recipeItemIngredient.Unit = new Unit(); recipeItemIngredient.Ingredient = new Ingredient(); //ViewBag.UnitsList = this.db.Units.All().ToList(); if (Request.IsAjaxRequest()) { //ViewBag.UnitsList = this.db.Units.All().ToList(); //ViewBag.IngredientsList = this.db.Ingredients.All().ToList(); ViewBag.RecipeItemID = recipeItemID; ViewData["RecipeItemID"] = recipeItemID; return PartialView("_IngredientEditor", recipeItemIngredient); //return PartialView("_StepEditor", newStep, new ViewDataDictionary { { "RecipeItemID", recipeItemID } }); } else { return RedirectToAction("Create"); //return PartialView("_StepPartial", newStep); } } public ActionResult AddStep(string recipeItemID) { Step newStep = new Step(); if (Request.IsAjaxRequest()) { ViewBag.RecipeItemID = recipeItemID; ViewData["RecipeItemID"] = recipeItemID; return PartialView("_StepEditor", newStep); //return PartialView("_StepEditor", newStep, new ViewDataDictionary { { "RecipeItemID", recipeItemID } }); } else { return RedirectToAction("Create"); //return PartialView("_StepPartial", newStep); } } public ActionResult AddSection(AdminRecipeViewModel recipeModel) { if (Request.IsAjaxRequest()) { RecipeItem recipeItem = new RecipeItem(); recipeItem.Steps = new List<Step>(); //recipeItem.Steps.Add(new Step() { Description = "bbb" }); newRecipeVM.RecipeItems.Add(recipeItem); return PartialView("_RecipeItemEditor", recipeItem); } else { //return RedirectToAction("Create"); //return PartialView("_StepPartial", newStep); return View(@"~/Areas/Administration/Views/AdminRecipes/Create.cshtml", this.newRecipeVM); } } //For Create Action private Recipe ParseRecipeVMToRecipeModel(AdminRecipeViewModel recipeVM) { Recipe newRecipe = new Recipe(); HMLToRTFConverter converter = new HMLToRTFConverter(); ImageUploadResult recipeImgUploadResult = new ImageUploadResult(); newRecipe.Title = recipeVM.Title; Category newRecipeParentCategory = this.db.Categories.GetById(recipeVM.SelectedParentCategory); newRecipe.Categories.Add(newRecipeParentCategory); Category newRecipeChildrenCategory = null; if (recipeVM.SelectedChildrenCategory != null) { newRecipeChildrenCategory = this.db.Categories.GetById((int)(recipeVM.SelectedChildrenCategory)); newRecipe.Categories.Add(newRecipeChildrenCategory); } if ((recipeVM.Image!=null&&(recipeVM.Image.FileName != "null_image.png" || recipeVM.Image.FileName != "null_image"))) { if (newRecipeChildrenCategory == null) { recipeImgUploadResult = UploadRecipeImage(recipeVM.Image, recipeVM.Title, newRecipeParentCategory.Name, null); } else { recipeImgUploadResult = UploadRecipeImage(recipeVM.Image, recipeVM.Title, newRecipeParentCategory.Name, newRecipeChildrenCategory.Name); } newRecipe.ImageVersion = "v" + recipeImgUploadResult.Version; newRecipe.ImageURL = "http://res.cloudinary.com/" + recipeImgUploadResult.Uri.AbsolutePath; //newRecipe.ImageURL = recipeVM.Title.Replace(" ", "-") + ".jpg"; } else { newRecipe.ImageURL = "http://res.cloudinary.com/hqz5ohs1v/image/upload/v1413825708/null_image.png"; } newRecipe.PreparationTime = recipeVM.SelectedPrepTimeHours * 60 + recipeVM.SelectedPrepTimeMinutes; newRecipe.CookingTime = recipeVM.SelectedCookTimeHours * 60 + recipeVM.SelectedCookTimeMinutes; newRecipe.Serves = recipeVM.SelectedServes; newRecipe.Rating = recipeVM.SelectedRating; newRecipe.Source = this.db.Sources.GetById(recipeVM.SelectedSource); if (recipeVM.SelectedRecommendation == "Да") { newRecipe.Recommended = true; } //if (recipeVM.SelectedRecommendation == "Не") else { newRecipe.Recommended = false; } DateTime dt = recipeVM.PublishedDate; dt.AddHours(DateTime.Now.Hour); dt.AddMinutes(DateTime.Now.Minute); dt.AddSeconds(DateTime.Now.Second); newRecipe.Date = dt; //newRecipe.Date = recipeVM.PublishedDate; newRecipe.Description = converter.ConvertHTMLToRTF(recipeVM.Description); newRecipe.NumberOfHits = 1; newRecipe.NumberOfLikes = 1; foreach (var recipeItem in recipeVM.RecipeItems) { RecipeItem newRecipeItem = new RecipeItem(); newRecipeItem.RecipeItemName = recipeItem.RecipeItemName; foreach (var recipeItem_ingredient in recipeItem.RecipeItems_Ingredients) { RecipeItems_Ingredients newRecipeItem_ingredient = new RecipeItems_Ingredients(); Unit newUnit = this.db.Units.GetById(recipeItem_ingredient.Unit.UnitID); Ingredient newIngredient = this.db.Ingredients.GetById(recipeItem_ingredient.Ingredient.IngredientID); newRecipeItem_ingredient.Quantity = recipeItem_ingredient.Quantity; newRecipeItem_ingredient.Unit = newUnit; newRecipeItem_ingredient.Ingredient = newIngredient; newRecipeItem.RecipeItems_Ingredients.Add(newRecipeItem_ingredient); } foreach (var step in recipeItem.Steps) { newRecipeItem.Steps.Add(step); } newRecipe.RecipeItems.Add(newRecipeItem); } //newRecipe.RecipeItems = recipeVM.RecipeItems; return newRecipe; } //For GET Edit Action private AdminRecipeViewModel ParseRecipeModelToRecipeVM(Recipe recipeForEdit) { AdminRecipeViewModel editRecipeVM = new AdminRecipeViewModel(); RTFToHTMLConverter converter = new RTFToHTMLConverter(); editRecipeVM.RecipeID = recipeForEdit.RecipeID; editRecipeVM.Title = recipeForEdit.Title; editRecipeVM.ImageURL = recipeForEdit.ImageURL; editRecipeVM.ParentCategories = db.Categories.AllParentCategories(); editRecipeVM.SelectedParentCategory = recipeForEdit.Categories.Where(cat => cat.ParentCategoryID == null).Select(cat => cat.CategoryID).FirstOrDefault(); editRecipeVM.ChildrenCategories = db.Categories.AllChildrenCategories(); editRecipeVM.SelectedChildrenCategory = recipeForEdit.Categories.Where(cat => cat.ParentCategoryID != null).Select(cat => cat.CategoryID).FirstOrDefault(); editRecipeVM.PrepTimeHours = this.hours.ToList(); editRecipeVM.SelectedPrepTimeHours = (int)recipeForEdit.PreparationTime / 60; editRecipeVM.PrepTimeMinutes = this.minutes; editRecipeVM.SelectedPrepTimeMinutes = (int)recipeForEdit.PreparationTime % 60; editRecipeVM.CookTimeHours = this.hours; editRecipeVM.SelectedCookTimeHours = (int)recipeForEdit.CookingTime / 60; editRecipeVM.CookTimeMinutes = this.minutes; editRecipeVM.SelectedCookTimeMinutes = (int)recipeForEdit.CookingTime % 60; editRecipeVM.Serves = this.servesArray; editRecipeVM.SelectedServes = (int)recipeForEdit.Serves; editRecipeVM.Rating = this.rating; editRecipeVM.SelectedRating = (int)recipeForEdit.Rating; editRecipeVM.Sources = this.db.Sources.All(); editRecipeVM.SelectedSource = recipeForEdit.Source.SourceID; editRecipeVM.Recommendation = this.recommendationArray; //editRecipeVM.SelectedRecommendation = recipeForEdit.Recommended; if (recipeForEdit.Recommended == true) { editRecipeVM.SelectedRecommendation = "Да"; } else { editRecipeVM.SelectedRecommendation = "Не"; } editRecipeVM.PublishedDate = (DateTime)recipeForEdit.Date; editRecipeVM.Description = RtfHelper.PlainText(recipeForEdit.Description); //editRecipeVM.RecipeItems = recipeForEdit.RecipeItems.ToList(); foreach (var recipeItem in recipeForEdit.RecipeItems) { RecipeItem newRecipeItem = new RecipeItem(); newRecipeItem.RecipeItemName = recipeItem.RecipeItemName; foreach (var recipeItem_ingredient in recipeItem.RecipeItems_Ingredients) { RecipeItems_Ingredients newRecipeItem_ingredient = new RecipeItems_Ingredients(); Unit newUnit = this.db.Units.GetById(recipeItem_ingredient.Unit.UnitID); Ingredient newIngredient = this.db.Ingredients.GetById(recipeItem_ingredient.Ingredient.IngredientID); newRecipeItem_ingredient.Quantity = recipeItem_ingredient.Quantity; newRecipeItem_ingredient.Unit = newUnit; newRecipeItem_ingredient.Ingredient = newIngredient; newRecipeItem.RecipeItems_Ingredients.Add(newRecipeItem_ingredient); } foreach (var step in recipeItem.Steps) { newRecipeItem.Steps.Add(step); } editRecipeVM.RecipeItems.Add(newRecipeItem); } return editRecipeVM; } //For POST Edit Action private Recipe ParseRecipeVMToRecipeModel_Update(Recipe recipeModel, AdminRecipeViewModel recipeVM) { Recipe recipeForEdit = recipeModel; ImageUploadResult recipeImgUploadResult = new ImageUploadResult(); //var recipeForEdit = this.db.Recipes.All() // .Include(r => r.Categories) // .Include(r => r.RecipeItems) // .FirstOrDefault(r => r.RecipeID == recipeVM.RecipeID); HMLToRTFConverter converter = new HMLToRTFConverter(); recipeForEdit.Title = recipeVM.Title; //recipeForEdit.ImageURL = "null_image.png"; Category newRecipeParentCategory = this.db.Categories.GetById(recipeVM.SelectedParentCategory); recipeForEdit.Categories.Clear(); recipeForEdit.Categories.Add(newRecipeParentCategory); Category newRecipeChildrenCategory = null; if (recipeVM.SelectedChildrenCategory != null) { newRecipeChildrenCategory = this.db.Categories.GetById((int)(recipeVM.SelectedChildrenCategory)); recipeForEdit.Categories.Add(newRecipeChildrenCategory); } if (recipeVM.Image != null && (recipeVM.Image.FileName != "null_image.png" || recipeVM.Image.FileName != "null_image")) { if (newRecipeChildrenCategory == null) { DeleteRecipeImage(recipeVM.ImageURL); recipeImgUploadResult = UploadRecipeImage(recipeVM.Image, recipeVM.Title, newRecipeParentCategory.Name, null); } else { DeleteRecipeImage(recipeVM.ImageURL); recipeImgUploadResult = UploadRecipeImage(recipeVM.Image, recipeVM.Title, newRecipeParentCategory.Name, newRecipeChildrenCategory.Name); } recipeForEdit.ImageVersion = "v" + recipeImgUploadResult.Version; recipeForEdit.ImageURL = "http://res.cloudinary.com" + recipeImgUploadResult.Uri.AbsolutePath; //newRecipe.ImageURL = recipeVM.Title.Replace(" ", "-") + ".jpg"; } else { RenameResult renameResult = null; if (newRecipeChildrenCategory!=null) { renameResult = RenameRecipeImage(recipeVM.ImageURL, newRecipeParentCategory.Name, newRecipeChildrenCategory.Name); } else { renameResult = RenameRecipeImage(recipeVM.ImageURL, newRecipeParentCategory.Name); } if (renameResult!=null) { recipeForEdit.ImageURL = HttpUtility.UrlDecode(renameResult.Url); } } recipeForEdit.PreparationTime = recipeVM.SelectedPrepTimeHours * 60 + recipeVM.SelectedPrepTimeMinutes; recipeForEdit.CookingTime = recipeVM.SelectedCookTimeHours * 60 + recipeVM.SelectedCookTimeMinutes; recipeForEdit.Serves = recipeVM.SelectedServes; recipeForEdit.Rating = recipeVM.SelectedRating; recipeForEdit.Source = this.db.Sources.GetById(recipeVM.SelectedSource); if (recipeVM.SelectedRecommendation == "Да") { recipeForEdit.Recommended = (bool?)true; } //if (recipeVM.SelectedRecommendation == "Не") else { recipeForEdit.Recommended = (bool?)false; } recipeForEdit.Date = recipeVM.PublishedDate; recipeForEdit.Description = converter.ConvertHTMLToRTF(recipeVM.Description); //recipeForEdit.RecipeItems = recipeVM.RecipeItems; foreach (var recipeItem in recipeVM.RecipeItems) { RecipeItem newRecipeItem = new RecipeItem(); newRecipeItem.RecipeItemName = recipeItem.RecipeItemName; foreach (var recipeItem_ingredient in recipeItem.RecipeItems_Ingredients) { RecipeItems_Ingredients newRecipeItem_ingredient = new RecipeItems_Ingredients(); Unit newUnit = this.db.Units.GetById(recipeItem_ingredient.Unit.UnitID); Ingredient newIngredient = this.db.Ingredients.GetById(recipeItem_ingredient.Ingredient.IngredientID); newRecipeItem_ingredient.Quantity = recipeItem_ingredient.Quantity; newRecipeItem_ingredient.Unit = newUnit; newRecipeItem_ingredient.Ingredient = newIngredient; newRecipeItem.RecipeItems_Ingredients.Add(newRecipeItem_ingredient); } foreach (var step in recipeItem.Steps) { newRecipeItem.Steps.Add(step); } recipeForEdit.RecipeItems.Add(newRecipeItem); } //newRecipe.RecipeItems = recipeVM.RecipeItems; return recipeForEdit; } static string cloudinaryAccount = ConfigurationManager.AppSettings["CLOUDINARY_URL"]; static string cloudinaryStoreURL = ConfigurationManager.AppSettings["RecipesStoreURL"]; static string cloudinaryRecipesFolder = ConfigurationManager.AppSettings["RecipesFolderName"]; //private static string UploadRecipeImage(HttpPostedFileBase imageUploader, string categoryName, string recipeName) private static ImageUploadResult UploadRecipeImage(HttpPostedFileBase imageUploader, string recipeTitle, string parentCategoryName, string childCategoryName) { Cloudinary cloudinary = new Cloudinary(cloudinaryAccount); string folderName = cloudinaryRecipesFolder; if (childCategoryName != null) { folderName = folderName + "/" + parentCategoryName + "/" + childCategoryName; } else { folderName = folderName + "/" + parentCategoryName; } var uploadParams = new ImageUploadParams() { File = new FileDescription(imageUploader.FileName, imageUploader.InputStream), //Folder = folderName, PublicId = folderName+"/"+recipeTitle.Replace(" ", "-"), Invalidate = true }; var uploadResult = cloudinary.Upload(uploadParams); return uploadResult; } private static void DeleteRecipeImage(string recipeImageURL) { Cloudinary cloudinaryDelete = new Cloudinary(cloudinaryAccount); string recipeImageURLWithoutExtension = recipeImageURL.Substring(0, recipeImageURL.LastIndexOf('.')); string recipeImagePublicID = recipeImageURLWithoutExtension.Substring(recipeImageURLWithoutExtension.IndexOf("Recipes")); var delParams = new DelResParams() { PublicIds = new List<string>() { recipeImagePublicID }, Invalidate = true }; DelResResult result = cloudinaryDelete.DeleteResources(delParams); } private static RenameResult RenameRecipeImage(string recipeImageURL, string parentCategory, string childCategory=null) { Cloudinary cloudinaryRename = new Cloudinary(cloudinaryAccount); recipeImageURL = recipeImageURL.Substring(0, recipeImageURL.LastIndexOf('.')); string imageName = Path.GetFileNameWithoutExtension(recipeImageURL); string oldName = recipeImageURL.Substring(recipeImageURL.IndexOf("Recipes")); oldName = HttpUtility.UrlDecode(oldName); string newName = ""; if (childCategory != null) { newName = String.Format(@"Recipes/{0}/{1}/{2}", parentCategory, childCategory, imageName); } else { newName = String.Format(@"Recipes/{0}/{1}", parentCategory, imageName); } if (!oldName.Equals(newName)) { RenameResult renameResult = cloudinaryRename.Rename(oldName, newName, true); return renameResult; } return null; } } }
namespace Alabo.Tool.Payment.WeiXinMp.Models { /// <summary> /// 微信分享 /// </summary> public class WeiXinShare { public string AppId { get; set; } /// <summary> /// 时间戳 /// </summary> public string Timestamp { get; set; } public string AccessToken { get; set; } public string Ticket { get; set; } public string NonceStr { get; set; } public string Signature { get; set; } /// <summary> /// 图片链接地址 /// </summary> public string ImageUrl { get; set; } /// <summary> /// 网址 /// </summary> public string Link { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 描述 /// </summary> public string Description { get; set; } } /// <summary> /// 分享内容 /// </summary> public class WeiXinShareInput { /// <summary> /// 网址 /// </summary> public string Url { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 描述 /// </summary> public string Description { get; set; } /// <summary> /// 图片 /// </summary> public string ImageUrl { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class enemyAimDouble : MonoBehaviour { public Transform firePointTransform; public Transform firePointTransform2; public float shootSpeed = 1; private float timer; private bool isPlayerHere = false; private Transform targetTransform; private Transform emptyTransform; private Transform playerTransform; private Vector3 direction; public GameObject bulletPreFab; void Start() { playerTransform = GameObject.Find("Player").transform; timer = shootSpeed; //set the initial timer } void OnTriggerEnter2D(Collider2D hitInfo) { if (hitInfo.tag == "Player") { isPlayerHere = true; targetTransform = playerTransform; } } void OnTriggerExit2D(Collider2D hitInfo) { if (hitInfo.tag == "Player") { isPlayerHere = false; targetTransform = emptyTransform; } } void Update() { if (isPlayerHere) { direction = new Vector3( targetTransform.position.x - this.transform.position.x, targetTransform.position.y - this.transform.position.y ); this.transform.up = direction; Attack(); } } void shoot() { Instantiate(bulletPreFab, firePointTransform.position, firePointTransform.rotation); Instantiate(bulletPreFab, firePointTransform2.position, firePointTransform2.rotation); } void Attack() { timer -= Time.deltaTime; if (timer <= 0) { shoot(); timer = shootSpeed; } } }
using ExitGames.Client.Photon; namespace Source.Code.Extensions { public class PhotonExtensions { public static T GetValueOrReturnDefault<T> (Hashtable properites, string key) { if (properites.TryGetValue(key, out object property)) { return (T)property; } return default; } } }
using System; namespace Uintra.Features.Tagging.UserTags.Models { public class UserTag { public Guid Id { get; } public string Text { get; } public UserTag(Guid id, string text) { Id = id; Text = text; } } }
using Pe.Stracon.Politicas.Infraestructura.CommandModel.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.Politicas.Infraestructura.CommandModel.General { /// <summary> /// Clase que representa la entidad de unidad operativa staff /// </summary> /// <remarks> /// Creación: GMD 20150107 <br /> /// Modificación: <br /> /// </remarks> public class UnidadOperativaStaffEntity : Entity { /// <summary> /// Código de unidad operativa /// </summary> public Guid? CodigoUnidadOperativa { get; set; } /// <summary> /// Código de Identificación de la unidad operativa /// </summary> public Guid? CodigoUnidadOperativaStaff { get; set; } /// <summary> /// CodigoSistema /// </summary> public Guid? CodigoSistema { get; set; } /// <summary> /// CodigoTrabajador /// </summary> public Guid? CodigoTrabajador { get; set; } } }
using System; using System.Runtime.InteropServices; namespace ScriptKit { internal static class NativeMethods { private const string lib = "ChakraCore"; [DllImport(lib)] internal static extern JsErrorCode JsCreateRuntime( JsRuntimeAttributes attributes, JsThreadServiceCallback threadService, out IntPtr runtime); [DllImport(lib)] internal static extern JsErrorCode JsDisposeRuntime( IntPtr runtime); [DllImport(lib)] internal static extern JsErrorCode JsCollectGarbage(IntPtr runtime); [DllImport(lib)] internal static extern JsErrorCode JsGetRuntimeMemoryUsage( IntPtr runtime, out IntPtr memoryUsage); [DllImport(lib)] internal static extern JsErrorCode JsSetRuntimeMemoryLimit( IntPtr runtime, IntPtr memoryLimit); [DllImport(lib)] internal static extern JsErrorCode JsGetRuntimeMemoryLimit( IntPtr runtime, out IntPtr memoryLimit); [DllImport(lib)] internal static extern JsErrorCode JsCreateContext( IntPtr runtime, out IntPtr newContext); [DllImport(lib)] internal static extern JsErrorCode JsGetCurrentContext( out IntPtr currentContext); [DllImport(lib)] internal static extern JsErrorCode JsSetCurrentContext( IntPtr context); [DllImport(lib)] internal static extern JsErrorCode JsCreateFunction( JsNativeFunction nativeFunction, IntPtr callbackState, out IntPtr function); [DllImport(lib)] internal static extern JsErrorCode JsCallFunction( IntPtr function, IntPtr arguments, ushort argumentCount, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsConstructObject( IntPtr function, IntPtr arguments, ushort argumentCount, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsConvertValueToObject( IntPtr value, out IntPtr obj); [DllImport(lib)] internal static extern JsErrorCode JsRun( IntPtr script, IntPtr sourceContext, IntPtr sourceUrl, JsParseScriptAttributes parseAttributes, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsCreateStringUtf16( IntPtr content, IntPtr length, out IntPtr value); [DllImport(lib)] internal static extern JsErrorCode JsSetProperty( IntPtr obj, IntPtr propertyId, IntPtr value, bool useStrictRules); [DllImport(lib)] internal static extern JsErrorCode JsCreatePropertyId( IntPtr name, IntPtr length, out IntPtr propertyId); [DllImport(lib)] internal static extern JsErrorCode JsGetProperty( IntPtr obj, IntPtr propertyId, out IntPtr value); [DllImport(lib)] internal static extern JsErrorCode JsGetGlobalObject( out IntPtr globalObject); [DllImport(lib)] internal static extern JsErrorCode JsGetValueType( IntPtr value, out JsValueType type); [DllImport(lib)] internal static extern JsErrorCode JsGetPrototype( IntPtr obj, out IntPtr prototypeObject); [DllImport(lib)] internal static extern JsErrorCode JsSetPrototype( IntPtr obj, IntPtr prototypeObject); [DllImport(lib)] internal static extern JsErrorCode JsGetOwnPropertyNames( IntPtr obj, out IntPtr propertyNames); [DllImport(lib)] internal static extern JsErrorCode JsGetUndefinedValue(out IntPtr undefinedValue); [DllImport(lib)] internal static extern JsErrorCode JsGetNullValue(out IntPtr nullValue); [DllImport(lib)] internal static extern JsErrorCode JsGetTrueValue(out IntPtr trueValue); [DllImport(lib)] internal static extern JsErrorCode JsGetFalseValue(out IntPtr falseValue); [DllImport(lib)] internal static extern JsErrorCode JsGetContextOfObject( IntPtr obj, out IntPtr context); [DllImport(lib)] internal static extern JsErrorCode JsBoolToBoolean( bool value, out IntPtr booleanValue); [DllImport(lib)] internal static extern JsErrorCode JsBooleanToBool( IntPtr value, out bool boolValue); [DllImport(lib)] internal static extern JsErrorCode JsConvertValueToBoolean( IntPtr value, out IntPtr booleanValue); [DllImport(lib)] internal static extern JsErrorCode JsDoubleToNumber( double doubleValue, out IntPtr value); [DllImport(lib)] internal static extern JsErrorCode JsIntToNumber( int intValue, out IntPtr value); [DllImport(lib)] internal static extern JsErrorCode JsNumberToDouble( IntPtr value, out double doubleValue); [DllImport(lib)] internal static extern JsErrorCode JsNumberToInt( IntPtr value, out int intValue); [DllImport(lib)] internal static extern JsErrorCode JsConvertValueToNumber( IntPtr value, out IntPtr numberValue); [DllImport(lib)] internal static extern JsErrorCode JsGetStringLength( IntPtr stringValue, out int length); [DllImport(lib)] internal static extern JsErrorCode JsConvertValueToString( IntPtr value, out IntPtr stringValue); [DllImport(lib)] internal static extern JsErrorCode JsCopyStringUtf16( IntPtr value, int start, int length, IntPtr buffer, out IntPtr written); [DllImport(lib)] internal static extern JsErrorCode JsEquals( IntPtr object1, IntPtr object2, out bool result); [DllImport(lib)] internal static extern JsErrorCode JsStrictEquals( IntPtr object1, IntPtr object2, out bool result); [DllImport(lib)] internal static extern JsErrorCode JsCreateTypedArray( JsTypedArrayType arrayType, IntPtr baseArray, uint byteOffset, uint elementLength, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsGetIndexedProperty( IntPtr obj, IntPtr index, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsSetIndexedProperty( IntPtr obj, IntPtr index, IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsDeleteIndexedProperty( IntPtr obj, IntPtr index); [DllImport(lib)] internal static extern JsErrorCode JsDeleteProperty( IntPtr obj, IntPtr propertyId, bool useStrictRules, out bool result); [DllImport(lib)] internal static extern JsErrorCode JsDefineProperty( IntPtr obj, IntPtr propertyId, IntPtr propertyDescriptor, out bool result); [DllImport(lib)] internal static extern JsErrorCode JsCreateArray( uint length, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsCreateObject(out IntPtr obj); [DllImport(lib)] internal static extern JsErrorCode JsInstanceOf( IntPtr obj, IntPtr constructor, out bool result); [DllImport(lib)] internal static extern JsErrorCode JsGetOwnPropertyDescriptor( IntPtr obj, IntPtr propertyId, out IntPtr propertyDescriptor); [DllImport(lib)] internal static extern JsErrorCode JsAddRef( IntPtr obj, out uint count); [DllImport(lib)] internal static extern JsErrorCode JsRelease( IntPtr obj, out uint count); [DllImport(lib)] internal static extern JsErrorCode JsCreateWeakReference( IntPtr value, out IntPtr weakRef); [DllImport(lib)] internal static extern JsErrorCode JsGetWeakReferenceValue( IntPtr weakRef, out IntPtr value); [DllImport(lib)] internal static extern JsErrorCode JsCreateExternalArrayBuffer( IntPtr data, uint byteLength, JsFinalizeCallback finalizeCallback, IntPtr callbackState, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsCreateArrayBuffer( uint byteLength, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsHasException( out bool hasException); [DllImport(lib)] internal static extern JsErrorCode JsGetAndClearException( out IntPtr exception); [DllImport(lib)] internal static extern JsErrorCode JsSetException( IntPtr exception); [DllImport(lib)] internal static extern JsErrorCode JsDisableRuntimeExecution( IntPtr runtime); [DllImport(lib)] internal static extern JsErrorCode JsEnableRuntimeExecution( IntPtr runtime); [DllImport(lib)] internal static extern JsErrorCode JsIsRuntimeExecutionDisabled( IntPtr runtime, out bool isDisabled); [DllImport(lib)] internal static extern JsErrorCode JsGetPromiseState( IntPtr promise, out JsPromiseState state); [DllImport(lib)] internal static extern JsErrorCode JsGetPromiseResult( IntPtr promise, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsCreatePromise( out IntPtr promise, out IntPtr PtrresolveFunction, out IntPtr PtrrejectFunction); [DllImport(lib)] internal static extern JsErrorCode JsDiagStartDebugging( IntPtr runtimeHandle, JsDiagDebugEventCallback debugEventCallback, IntPtr callbackState); [DllImport(lib)] internal static extern JsErrorCode JsDiagStopDebugging( IntPtr runtimeHandle, IntPtr callbackState); [DllImport(lib)] internal static extern JsErrorCode JsDiagRequestAsyncBreak( IntPtr runtimeHandle); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetBreakpoints( out IntPtr breakpoints); [DllImport(lib)] internal static extern JsErrorCode JsDiagSetBreakpoint( uint scriptId, uint lineNumber, uint columnNumber, out IntPtr breakpoint); [DllImport(lib)] internal static extern JsErrorCode JsDiagRemoveBreakpoint( uint breakpointId); [DllImport(lib)] internal static extern JsErrorCode JsDiagSetBreakOnException( IntPtr runtimeHandle, JsDiagBreakOnExceptionAttributes exceptionAttributes); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetBreakOnException( IntPtr runtimeHandle, out JsDiagBreakOnExceptionAttributes exceptionAttributes); [DllImport(lib)] internal static extern JsErrorCode JsDiagSetStepType( JsDiagStepType stepType); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetScripts( out IntPtr scriptsArray); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetSource( uint scriptId, out IntPtr source); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetFunctionPosition( IntPtr function, out IntPtr functionPosition); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetStackTrace( out IntPtr stackTrace); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetStackProperties( uint stackFrameIndex, out IntPtr properties); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetProperties( uint objectHandle, uint fromCount, uint totalCount, out IntPtr propertiesObject); [DllImport(lib)] internal static extern JsErrorCode JsDiagGetObjectFromHandle( uint objectHandle, out IntPtr handleObject); [DllImport(lib)] internal static extern JsErrorCode JsDiagEvaluate( IntPtr expression, uint stackFrameIndex, JsParseScriptAttributes parseAttributes, bool forceSetValueProp, out IntPtr evalResult); [DllImport(lib)] internal static extern JsErrorCode JsSetObjectBeforeCollectCallback( IntPtr obj, IntPtr callbackState, JsObjectBeforeCollectCallback objectBeforeCollectCallback); [DllImport(lib)] internal static extern JsErrorCode JsIdle(out uint nextIdleTick); [DllImport(lib)] internal static extern JsErrorCode JsGetArrayBufferStorage( IntPtr arrayBuffer, out IntPtr buffer, out uint bufferLength); [DllImport(lib)] internal static extern JsErrorCode JsGetTypedArrayStorage( IntPtr typedArray, out IntPtr buffer, out uint bufferLength, out JsTypedArrayType arrayType, out int elementSize); [DllImport(lib)] internal static extern JsErrorCode JsCreateExternalObject( IntPtr data, JsFinalizeCallback finalizeCallback, out IntPtr obj); [DllImport(lib)] internal static extern JsErrorCode JsGetExternalData( IntPtr obj, out IntPtr externalData); [DllImport(lib)] internal static extern JsErrorCode JsGetExtensionAllowed( IntPtr obj, out bool value); [DllImport(lib)] internal static extern JsErrorCode JsPreventExtension(IntPtr obj); [DllImport(lib)] internal static extern JsErrorCode JsCreateSymbol( IntPtr description, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsGetOwnPropertySymbols( IntPtr obj, out IntPtr propertySymbols); [DllImport(lib)] internal static extern JsErrorCode JsGetSymbolFromPropertyId( IntPtr propertyId, out IntPtr symbol); [DllImport(lib)] internal static extern JsErrorCode JsGetPropertyIdType( IntPtr propertyId, out JsPropertyIdType propertyIdType); [DllImport(lib)] internal static extern JsErrorCode JsGetPropertyIdFromSymbol( IntPtr symbol, out IntPtr propertyId); [DllImport(lib)] internal static extern JsErrorCode JsCreateDataView( IntPtr arrayBuffer, uint byteOffset, uint byteLength, out IntPtr result); [DllImport(lib)] internal static extern JsErrorCode JsGetTypedArrayInfo( IntPtr typedArray, out JsTypedArrayType arrayType, out IntPtr arrayBuffer, out uint byteOffset, out uint byteLength); [DllImport(lib)] internal static extern JsErrorCode JsGetDataViewStorage( IntPtr dataView, out IntPtr buffer, out uint bufferLength); [DllImport(lib)] internal static extern JsErrorCode JsSetPromiseContinuationCallback( JsPromiseContinuationCallback promiseContinuationCallback, IntPtr callbackState); [DllImport(lib)] internal static extern JsErrorCode JsParse( IntPtr script, IntPtr sourceContext, IntPtr sourceUrl, JsParseScriptAttributes parseAttributes, out IntPtr result); } }
using System; using System.Collections.Generic; using System.Linq; namespace RuthAaronChallenge { class Program { static void Main(string[] args) { string userNum = Console.ReadLine(); string userNum2 = Console.ReadLine(); int num = Int32.Parse(userNum); //converts string input to type int int num2 = Int32.Parse(userNum2); List<int> results = findPrimeFactors(num); //calls findPrimeFactors method List<int> results2 = findPrimeFactors(num2); int sum = results.Sum(); int sum2 = results2.Sum(); if(sum == sum2) { Console.WriteLine("Ruth Aaron twins!"); } else { Console.WriteLine("Not twins :("); } } static List<int> findPrimeFactors(int num) { List<int> results = new List<int>(); //stores prime factors while (num % 2 == 0) //factors 2 from input { results.Add(2); num /= 2; } int nextFactor = 3; while (nextFactor * nextFactor <= num) //checks other prime numbers starting with three, adds two { if (num % nextFactor == 0) { results.Add(nextFactor); num /= nextFactor; } else { nextFactor += 2; } } if (num > 1) { results.Add(num); } return results; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ResetPosition : MonoBehaviour { Vector3 startPos; private void Awake() { startPos = transform.position; } // Use this for initialization void Start() { startPos = this.transform.position; } private void Update() { if (Input.GetKeyDown("r")) { transform.position = startPos; print("Position resetted"); } } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.MonoHooks.Editor { /// <summary> /// Constant property drawer of type `Collision2DGameObject`. Inherits from `AtomDrawer&lt;Collision2DGameObjectConstant&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(Collision2DGameObjectConstant))] public class Collision2DGameObjectConstantDrawer : VariableDrawer<Collision2DGameObjectConstant> { } } #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using DevExpress.XtraEditors; using IRAP.Global; using IRAP.Client.User; using IRAP.Entities.FVS; using IRAP.Entity.MDM; using IRAP.WCF.Client.Method; namespace IRAP.Client.GUI.FVS { public partial class frmMethodAndQualityStandardsWithProduct : IRAP.Client.Global.frmCustomBase { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private PWOSurveillance pwo = null; private List<MethodStandard> methodStandards = new List<MethodStandard>(); private List<QualityStandard> qualityStandards = new List<QualityStandard>(); public frmMethodAndQualityStandardsWithProduct() { InitializeComponent(); } public PWOSurveillance PWO { get { return pwo; } set { pwo = value; if (pwo != null) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { Text = string.Format("[{0}]的工艺参数和质量标准", pwo.ProductName); int errCode = 0; string errText = ""; try { IRAPMDMClient.Instance.ufn_GetList_MethodStandard( IRAPUser.Instance.CommunityID, pwo.T102LeafID, pwo.T216LeafID, "", IRAPUser.Instance.SysLogID, ref methodStandards, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { grdMethodStandards.DataSource = methodStandards; for (int i = 0; i < grdvMethodStandards.Columns.Count; i++) { grdvMethodStandards.Columns[i].BestFit(); } } else { XtraMessageBox.Show( errText, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error); } IRAPMDMClient.Instance.ufn_GetList_QualityStandard( IRAPUser.Instance.CommunityID, pwo.T102LeafID, pwo.T216LeafID, "", IRAPUser.Instance.SysLogID, ref qualityStandards, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { grdQualityStandards.DataSource = qualityStandards; for (int i = 0; i < grdvQualityStandards.Columns.Count; i++) { grdvQualityStandards.Columns[i].BestFit(); } } else { XtraMessageBox.Show( errText, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); XtraMessageBox.Show( error.Message, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } } } }
using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace sha256 { public partial class Form1 : Form { MemoryStream ms = new MemoryStream(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Calculate(lblInt2, lblHex2, lblTime2, lblAvg2, lblHash2); } private string GetRandom() { RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); var byteArray2 = new byte[8]; provider.GetBytes(byteArray2); var random64 = BitConverter.ToInt64(byteArray2, 0); return random64.ToString("x16"); } private void Calculate(Label _lblInt, Label _lblHex, Label _lblTime, Label _lblAvg, Label _lblHash) { var i = 0; var secs = 0.0; var start = DateTime.Now; var hash = ""; var strm = new MemoryStream(); var max = Convert.ToInt64(txtCount.Text); //FileStream fs = File.Open("c:\\temp\\all." + DateTime.Now.ToString("yyyyMMddHHmmss.fffffff") + ".txt", FileMode.OpenOrCreate); //FileStream fs1 = File.Open("c:\\temp\\txt." + DateTime.Now.ToString("yyyyMMddHHmmss.fffffff") + ".txt", FileMode.OpenOrCreate); FileStream fs2 = File.Open("c:\\temp\\hash." + DateTime.Now.ToString("yyyyMMddHHmmss.fffffff") + ".txt", FileMode.OpenOrCreate); for (; i < max * 1000;) { var hex = GetRandom(); hash = ComputeSha256Hash(hex); //byte[] buffer = Encoding.UTF8.GetBytes(hex + ":" + hash + Environment.NewLine); //fs.Write(buffer, 0, buffer.Length); //byte[] buffer1 = Encoding.UTF8.GetBytes(hex + Environment.NewLine); //fs1.Write(buffer1, 0, buffer1.Length); byte[] buffer2 = Encoding.UTF8.GetBytes(hash + Environment.NewLine); fs2.Write(buffer2, 0, buffer2.Length); i++; if (i % 100000 == 0) { secs = (DateTime.Now - start).TotalMilliseconds / 1000; _lblInt.Text = i.ToString("###,##0"); _lblHex.Text = hex; _lblTime.Text = secs.ToString("###,##0.0###"); _lblAvg.Text = (i / secs).ToString("###,##0.0###"); _lblHash.Text = hash; Refresh(); } Application.DoEvents(); } //fs.Close(); //fs1.Close(); fs2.Close(); } static string ComputeSha256Hash(string rawData) { // Create a SHA256 using (SHA256 sha256Hash = SHA256.Create()) { // ComputeHash - returns byte array byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData)); // Convert byte array to a string StringBuilder builder = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { builder.Append(bytes[i].ToString("x2")); } return builder.ToString(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Xml; using System.Data; using System.Globalization; using System.Web.Script.Serialization; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using RouteScheduler.Logic; using System.Threading.Tasks; using System.Net.Http; using System.Threading; using System.Text; using System.Web.Mvc; namespace RouteScheduler.Models { public class APILogic { private WebClient webClient = new WebClient(); private readonly ApplicationDbContext Context = new ApplicationDbContext(); private APIKeys apikeys = new APIKeys(); public List<double> GeocodeAddress(string Address, string City, string State) { List<double> list = new List<double>(); var address = ParseAddressString(Address); var city = ParseAddressString(City); var state = ParseAddressString(State); string getGeocode = webClient.DownloadString($"https://maps.googleapis.com/maps/api/geocode/json?address={address},+{city},+{state}&key=" + apikeys.ApiKey); var obj = JsonConvert.DeserializeObject<dynamic>(getGeocode); var lat = obj.results[0].geometry.location.lat.Value; var lng = obj.results[0].geometry.location.lng.Value; list.Add(lat); list.Add(lng); return (list); } public double DistanceBetweenTwoPlaces(double LatOne, double LongOne, double LatTwo, double LongTwo) { string GetDistance = webClient.DownloadString($"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={LatOne},{LongOne}&destinations={LatTwo}%2C{LongTwo}&key=" + apikeys.ApiKey); var obj = JsonConvert.DeserializeObject<dynamic>(GetDistance); var DistanceString = obj.results[0].elements.distance.text; List<string> DistanceParse = DistanceString.Split(' ').ToList(); double Distance = Convert.ToDouble(DistanceParse[0]); return Distance; } private string ParseAddressString(string ParseLine) { List<string> ParsedIs = ParseLine.Split(' ').ToList(); var CombinedAddress = string.Join("+", ParsedIs); return CombinedAddress; } public List<EventsHolder> GetEventsByIdAndDay(int id, DateTime day) { List<EventsHolder> list = new List<EventsHolder>(); string getEvents = webClient.DownloadString("http://localhost:58619/api/events"); var obj = JsonConvert.DeserializeObject<dynamic>(getEvents); EventsHolder events; foreach(var item in obj) { DateTime startDate = item.StartDate; events = new EventsHolder(); if (item.UserId == id && startDate.Day == day.Day) { events.CustomerId = item.CustomerId; events.UserId = item.UserId; events.StartDate = item.StartDate; events.EndDate = item.EndDate; events.Latitude = item.Latitude; events.Longitude = item.Longitude; events.TemplateId = item.TemplateId; events.EventName = item.EventName; list.Add(events); } } return list; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoinCollision : MonoBehaviour { public LayerMask playerLayer; public float radius; public GameController _gamecontroller; public float coinPoints; public void Set_Gamecontroller(GameController localgamecontroller) { _gamecontroller = localgamecontroller; } private void Update() { if (Physics2D.OverlapCircle(this.transform.position, radius, playerLayer)) { _gamecontroller.Add_Coins(coinPoints); // this function in gamecontroller assigns the points for one coin this.gameObject.SetActive(false); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class StatusEffect { public EnemyBehavior eb; public HeroStateMachine hsm; public Color elementColor; public void ProcessEffect(string effectName, string effectType, int baseVal, GameObject thisObject) { String target = ""; //checks if thisObject has HeroStateMachine or EnemyStateMachine attached if ((thisObject.GetComponent("HeroStateMachine") as HeroStateMachine) != null) //is hero { target = "Hero"; } if ((thisObject.GetComponent("EnemyStateMachine") as EnemyStateMachine) != null) //is enemy { target = "Enemy"; } if (target == "") { Debug.LogWarning("Something went wrong with status effect - hero and enemy not found"); } //process effects if (effectType == "POISON") { Poison(thisObject, baseVal, target); } } void Poison(GameObject thisObject, int baseVal, string target) { if (target == "Enemy") { Debug.Log("Processing poison to enemy"); Debug.Log(thisObject.GetComponent<EnemyStateMachine>().enemy.name + " HP: " + thisObject.GetComponent<EnemyStateMachine>().enemy.curHP + " / " + thisObject.GetComponent<EnemyStateMachine>().enemy.baseHP); Debug.Log(thisObject.GetComponent<EnemyStateMachine>().enemy.name + " taking " + baseVal + " damage from poison."); thisObject.GetComponent<EnemyStateMachine>().enemyBehavior.TakeDamage(baseVal); Debug.Log(thisObject.GetComponent<EnemyStateMachine>().enemy.name + " HP: " + thisObject.GetComponent<EnemyStateMachine>().enemy.curHP + " / " + thisObject.GetComponent<EnemyStateMachine>().enemy.baseHP); } if (target == "Hero") { Debug.Log("Processing poison to hero"); Debug.Log(thisObject.GetComponent<HeroStateMachine>().hero.name + " HP: " + thisObject.GetComponent<HeroStateMachine>().hero.curHP + " / " + thisObject.GetComponent<HeroStateMachine>().hero.baseHP); Debug.Log(thisObject.GetComponent<HeroStateMachine>().name + " taking " + baseVal + " damage from poison."); thisObject.GetComponent<HeroStateMachine>().TakeDamage(baseVal); Debug.Log(thisObject.GetComponent<HeroStateMachine>().hero.name + " HP: " + thisObject.GetComponent<HeroStateMachine>().hero.curHP + " / " + thisObject.GetComponent<HeroStateMachine>().hero.baseHP); } elementColor = new Color(0, 0.75f, 0); SetDamage(baseVal); } void SetDamage(int damage) { if (hsm != null) { hsm.effectDamage = damage; } else if (eb != null) { eb.effectDamage = damage; } } }
using DChild.Gameplay.Environment.Item; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoingBomb : TimeBomb { protected override void ApplyBombEffect(Collider2D collider) { } }
using System; using System.Collections; using System.Text; using System.IO; using System.Xml; namespace MonoCov { public class XmlExporter { public class ProgressEventArgs { public CoverageItem item; public string fileName; public int pos; public int itemCount; public ProgressEventArgs (CoverageItem item, string fileName, int pos, int itemCount) { this.item = item; this.fileName = fileName; this.pos = pos; this.itemCount = itemCount; } } public delegate void ProgressEventHandler (Object sender, ProgressEventArgs e); public string DestinationDir; public string StyleSheet; public event ProgressEventHandler Progress; private XmlTextWriter writer; private CoverageModel model; private static string DefaultStyleSheet = "style.xsl"; private int itemCount; private int itemsProcessed; public void Export (CoverageModel model) { this.model = model; if (model.hit + model.missed == 0) return; if (StyleSheet == null) { // Use default stylesheet using (StreamReader sr = new StreamReader (typeof (XmlExporter).Assembly.GetManifestResourceStream ("style.xsl"))) { using (StreamWriter sw = new StreamWriter (Path.Combine (DestinationDir, "style.xsl"))) { string line; while ((line = sr.ReadLine ()) != null) sw.WriteLine (line); } } using (Stream s = typeof (XmlExporter).Assembly.GetManifestResourceStream ("trans.gif")) { using (FileStream fs = new FileStream (Path.Combine (DestinationDir, "trans.gif"), FileMode.Create)) { byte[] buf = new byte[1024]; int len = s.Read (buf, 0, buf.Length); fs.Write (buf, 0, len); } } StyleSheet = DefaultStyleSheet; } // Count items itemCount = 1 + model.Classes.Count + model.Namespaces.Count; itemsProcessed = 0; WriteProject (); WriteNamespaces (); WriteClasses (); } private void WriteStyleSheet () { // The standard says text/xml, while IE6 only understands text/xsl writer.WriteProcessingInstruction ("xml-stylesheet", "href=\"" + StyleSheet + "\" type=\"text/xsl\""); } private void WriteProject () { string fileName = Path.Combine (DestinationDir, "project.xml"); // If I use Encoding.UTF8 here, the file will start with strange // characters writer = new XmlTextWriter (fileName, Encoding.ASCII); writer.Formatting = Formatting.Indented; writer.WriteStartDocument (); WriteStyleSheet (); WriteItem (model, typeof (ClassCoverageItem), 999); writer.WriteEndDocument (); writer.WriteRaw ("\n"); writer.Close (); itemsProcessed ++; if (Progress != null) Progress (this, new ProgressEventArgs (model, fileName, itemsProcessed, itemCount)); } private void WriteItem (CoverageItem item, Type stopLevel, int level) { if (item.filtered) return; if (item.hit + item.missed == 0) // Filtered return; if (level == 0) return; if (item.GetType () == stopLevel) return; if (item is CoverageModel) { writer.WriteStartElement ("project"); writer.WriteAttributeString ("name", "Project"); } else if (item is NamespaceCoverageItem) { NamespaceCoverageItem ns = (NamespaceCoverageItem)item; writer.WriteStartElement ("namespace"); if (ns.ns == "<GLOBAL>") writer.WriteAttributeString ("name", "GLOBAL"); else writer.WriteAttributeString ("name", ns.ns); } else if (item is ClassCoverageItem) { ClassCoverageItem klass = (ClassCoverageItem)item; writer.WriteStartElement ("class"); writer.WriteAttributeString ("name", klass.name); writer.WriteAttributeString ("fullname", klass.FullName.Replace('/', '.')); } WriteCoverage (item); if (item.ChildCount > 0) foreach (CoverageItem child in item.children) WriteItem (child, stopLevel, level - 1); writer.WriteEndElement (); } private void WriteNamespaces () { foreach (NamespaceCoverageItem ns in model.Namespaces.Values) { bool filtered = false; string fileSuffix = ns.ns; if (ns.ns == "<GLOBAL>") fileSuffix = "GLOBAL"; string fileName = Path.Combine (DestinationDir, String.Format ("namespace-{0}.xml", fileSuffix)); if (ns.hit + ns.missed == 0) // Filtered filtered = true; if (!filtered) { writer = new XmlTextWriter (fileName, Encoding.ASCII); writer.Formatting = Formatting.Indented; writer.WriteStartDocument (); WriteStyleSheet (); WriteItem (ns, typeof (MethodCoverageItem), 2); writer.WriteEndDocument (); writer.WriteRaw ("\n"); writer.Close (); } else fileName = null; itemsProcessed ++; if (Progress != null) Progress (this, new ProgressEventArgs (ns, fileName, itemsProcessed, itemCount)); } } private void WriteClasses () { foreach (ClassCoverageItem item in model.Classes.Values) { bool filtered = false; string fileName = Path.Combine (DestinationDir, String.Format ("class-{0}.xml", item.FullName.Replace('/', '.'))); if (item.filtered) filtered = true; if (item.hit + item.missed == 0) // Filtered filtered = true; if (!filtered) { writer = new XmlTextWriter (fileName, Encoding.ASCII); writer.Formatting = Formatting.Indented; writer.WriteStartDocument (); WriteStyleSheet (); WriteClass (item); writer.WriteEndDocument (); writer.WriteRaw ("\n"); writer.Close (); } else fileName = null; itemsProcessed ++; if (Progress != null) Progress (this, new ProgressEventArgs (item, fileName, itemsProcessed, itemCount)); } } private void WriteClass (ClassCoverageItem item) { if (item.filtered) return; writer.WriteStartElement ("class"); writer.WriteAttributeString ("name", item.name); writer.WriteAttributeString ("fullname", item.FullName.Replace('/', '.')); writer.WriteAttributeString ("namespace", item.Namespace); WriteCoverage (item); writer.WriteStartElement ("source"); if (item.sourceFile != null) { writer.WriteAttributeString ("sourceFile", item.sourceFile.sourceFile); StreamReader infile = new StreamReader (item.sourceFile.sourceFile, Encoding.ASCII); int[] coverage = item.sourceFile.Coverage; int pos = 1; while (infile.Peek () > -1) { int count; if ((coverage != null) && (pos < coverage.Length)) count = coverage [pos]; else count = -1; writer.WriteStartElement ("l"); writer.WriteAttributeString ("line", "" + pos); writer.WriteAttributeString ("count", "" + count); string line = infile.ReadLine (); writer.WriteString (line); writer.WriteEndElement (); pos ++; } } writer.WriteEndElement (); } private void WriteCoverage (CoverageItem item) { double coverage; if (item.hit + item.missed == 0) coverage = 1.0; else coverage = (double)item.hit / (item.hit + item.missed); string coveragePercent = String.Format ("{0:###0}", coverage * 100); writer.WriteStartElement ("coverage"); writer.WriteAttributeString ("hit", item.hit.ToString ()); writer.WriteAttributeString ("missed", item.missed.ToString ()); writer.WriteAttributeString ("coverage", coveragePercent); writer.WriteEndElement (); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; using Microsoft.WindowsAzure.Server.AdminManagement; using Microsoft.WindowsAzure.Server.Management; using Microsoft.WindowsAzure.Management.Models; using WAPWrapper.SPFGallery; using WAPWrapper.SPFVMM; using WAPWrapper.SPFVMM.MicrosoftCompute; using Newtonsoft.Json; using System.Web.Script.Serialization; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Formatting; using Newtonsoft.Json.Linq; namespace WAPWrapper { /// <summary> /// A disposable class to perform Virtual Machine and other VMM operations (Cloud, User Role) for a User role (Administrator or Tenant or Self-Service User) /// </summary> public class WAPTenantOperation : IDisposable { private string TenantUserName { get; set; } private string TenantPassword { get; set; } private string TenantUserRoleName { get; set; } private string TenantSubscriptionID { get; set; } private Guid TenantUserRoleID { get; set; } private string TenantHeaderValue { get; set; } private AuthType TenantAuthType { get; set; } private static string WAPADAuthEndpoint { get; set; } private static string WAPASPAuthEndpoint { get; set; } private static string WAPTenantEndpoint { get; set; } private WAPAuthService WAPAuth { get; set; } private WAPTenantService WAPTenant { get; set; } public VMMOperation VMMTenant { get; set; } /// <summary> /// Instantiates VMOperation /// </summary> public WAPTenantOperation() { WAPAuth = WAPAuthService.Instance; WAPTenant = new WAPTenantService(); } /// <summary> /// Sets the WAP Auth Endpoints for issuing admin and tenant tokens /// </summary> /// <param name="adAuthEndpoint"></param> /// <param name="aspAuthEndpoint"></param> public void SetWAPAuthContext(string adAuthEndpoint, string aspAuthEndpoint) { WAPADAuthEndpoint = adAuthEndpoint; WAPASPAuthEndpoint = aspAuthEndpoint; WAPAuth.SetWAPAuthEndpoint(WAPADAuthEndpoint, WAPASPAuthEndpoint); } /// <summary> /// Sets the WAP Tenent context for Authentication and Tenant User detail /// </summary> /// <param name="tenantEndpoint"></param> /// <param name="authenticationType"></param> /// <param name="tenantUserName"></param> /// <param name="tenantPassword"></param> /// <param name="adfsEndpoint"></param> public void SetWAPTenantContext(string tenantEndpoint, AuthType authenticationType, string tenantUserName, string tenantPassword, string adfsEndpoint = "") { WAPTenantEndpoint = tenantEndpoint; TenantUserName = tenantUserName; TenantPassword = tenantPassword; TenantAuthType = authenticationType; switch (authenticationType) { case AuthType.WindowsAuth: TenantHeaderValue = WAPAuth.PerformADAuth(TenantUserName, TenantPassword); break; case AuthType.ASPAuth: TenantHeaderValue = WAPAuth.PerformASPAuth(TenantUserName, TenantPassword); break; case AuthType.ADFSAuth: TenantHeaderValue = WAPAuth.PerformADFSAuth(TenantUserName, TenantPassword); break; case AuthType.ADASPAuth: TenantHeaderValue = WAPAuth.PerformADFSASPAuth(adfsEndpoint, TenantUserName, TenantPassword); break; } if (TenantHeaderValue != null) { WAPTenant.SetWAPEndpoint(WAPTenantEndpoint, TenantUserName, TenantHeaderValue); WAPTenant.WAPServiceHttpClient(); } else { throw new Exception("Failed to set the WAP Tenant Context for user..." + TenantUserName); } } /// <summary> /// Gets VMM context for a particular subscription /// </summary> /// <param name="subscriptionID"></param> public void GetVMMContextForSubscription(string subscriptionID) { VMMTenant = new VMMOperation(); VMMTenant.GetVMMContextForTenant(WAPTenantEndpoint, TenantUserName, subscriptionID, TenantHeaderValue); } /// <summary> /// Get Tenant user detail /// </summary> /// <param name="userID"></param> /// <returns></returns> public User GetTenantUser() { Uri requestUri = WAPTenant.CreateRequestUri(string.Format(CultureInfo.InvariantCulture, Constants.RelativePaths.User, TenantUserName)); var user = WAPTenant.GetWAPAsync<User>(requestUri); return user.Result; } /// <summary> /// creates wap user /// </summary> /// <param name="username"></param> /// <param name="email"></param> /// <returns></returns> public async Task<User> CreateUser(string username, string email) { Uri requestUri = WAPTenant.CreateRequestUri(string.Format(CultureInfo.InvariantCulture, Constants.RelativePaths.Users)); var userInfo = new User() { Name = username, Email = email, State = UserState.Active, }; return await WAPTenant.SendAsync<User, User>(requestUri, new System.Net.Http.HttpMethod(Constants.HttpMethods.Post), userInfo); } /// <summary> /// updates wap user /// </summary> /// <param name="username"></param> /// <param name="email"></param> /// <returns></returns> public async Task<User> UpdateUser(string username, string email) { Uri requestUri = WAPTenant.CreateRequestUri(string.Format(CultureInfo.InvariantCulture, Constants.RelativePaths.User, username)); var userInfo = new User() { Name = username, Email = email, }; return await WAPTenant.SendAsync<User, User>(requestUri, new System.Net.Http.HttpMethod(Constants.HttpMethods.Put), userInfo); } /// <summary> /// Gets all available plans /// </summary> /// <returns></returns> public PlanList GetAvailablePlans() { Uri requestUri = WAPTenant.CreateRequestUri(Constants.RelativePaths.Plans); var plans = WAPTenant.GetWAPAsync<PlanList>(requestUri); return plans.Result; } /// <summary> /// Gets all tenant subscriptions /// </summary> /// <returns></returns> public AdminSubscriptionList GetSubscriptions() { Uri requestUri = WAPTenant.CreateRequestUri(Constants.RelativePaths.Subscriptions); var subscriptions = WAPTenant.GetWAPAsync<AdminSubscriptionList>(requestUri); return subscriptions.Result; } /// <summary> /// Creates subscription for a plan /// </summary> /// <param name="userId"></param> /// <param name="offerCategory"></param> /// <returns></returns> public async Task<Subscription> CreateSubscription(string planId, string planName) { Uri requestUri = WAPTenant.CreateRequestUri(Constants.RelativePaths.Subscriptions); // Create a subscription for the above user account var subscriptionInfo = new AzureProvisioningInfo() { SubscriptionId = Guid.NewGuid(), FriendlyName = planName, AccountAdminLiveEmailId = TenantUserName, ServiceAdminLiveEmailId = TenantUserName, AccountAdminLivePuid = TenantUserName, ServiceAdminLivePuid = TenantUserName, OfferCategory = planName, PlanId = planId }; return await WAPTenant.SendAsync<AzureProvisioningInfo, Subscription>(requestUri, new HttpMethod(Constants.HttpMethods.Post), subscriptionInfo); } /// <summary> /// Updates the specified subscription. /// </summary> /// <param name="subscriptionId">The subscription id.</param> /// <param name="friendlyName">The friendly name.</param> /// <returns>Async task.</returns> public async Task<Subscription> UpdateSubscriptionNameAsync(string subscriptionId, string subscriptionName) { var subscription = new Subscription { SubscriptionID = subscriptionId, SubscriptionName = subscriptionName, CoAdminNames = null, // null means won't change for PATCH State = SubscriptionState.Active }; Uri requestUri = WAPTenant.CreateRequestUri(string.Format(CultureInfo.InvariantCulture, Constants.RelativePaths.Subscription, subscriptionId)); return await WAPTenant.SendAsync<Subscription, Subscription>(requestUri, new HttpMethod(Constants.HttpMethods.Patch), subscription); } /// <summary> /// Gets usage summary data for a tenant subscriptions /// </summary> /// <returns></returns> public UsageSummaryList GetTenantQuotaForSubscription(string subscriptionId) { Uri requestUri = WAPTenant.CreateRequestUri(String.Format(CultureInfo.InvariantCulture, Constants.RelativePaths.SubscriptionUsageSummaries, subscriptionId)); var usageSummary = WAPTenant.GetWAPAsync<UsageSummaryList>(requestUri); return usageSummary.Result; } /// <summary> /// Gets Cloud Service /// </summary> /// <param name="subscriptionId"></param> /// <param name="cloudServiceName"></param> /// <returns></returns> public CloudService GetCloudService(string subscriptionId, string cloudServiceName) { Uri requestUri = WAPTenant.CreateRequestUri(String.Format(CultureInfo.InvariantCulture, Constants.ServiceProviderFoundation.SubCloudService, subscriptionId, cloudServiceName), //"{0}/{1}/{2}", subscriptionId, Constants.ServiceProviderFoundation.CloudServices, //cloudServiceName), new KeyValuePair<string, string>("api-version", "2013-03")); var response = WAPTenant.SendAsyncString(requestUri, new HttpMethod(Constants.HttpMethods.Get)); var result = Parser.FromJSONString<CloudService>(response.Result).FirstOrDefault(); return result; } /// <summary> /// Creates cloud service for a subscription /// </summary> /// <param name="userId"></param> /// <param name="offerCategory"></param> /// <returns></returns> public async Task<CloudService> CreateCloudService(string subscriptionId, CloudService cloudService) { Uri requestUri = WAPTenant.CreateRequestUri(String.Format(CultureInfo.InvariantCulture, Constants.ServiceProviderFoundation.SubCloudServices, subscriptionId), //"{0}/{1}", subscriptionId, Constants.ServiceProviderFoundation.CloudServices), new KeyValuePair<string, string>("api-version", "2013-03")); String jsonString = Parser.ToJSON(cloudService); var response = await WAPTenant.SendAsyncString(requestUri, new HttpMethod(Constants.HttpMethods.Post), jsonString, TenantUserName, true); return Parser.FromJSONString<CloudService>(response).FirstOrDefault(); } /// <summary> /// Gets all gallery items for a subscription /// </summary> /// <param name="subscriptionId"></param> /// <returns></returns> public IEnumerable<VMRoleGalleryItem> GetVMRoleGalleryItems(string subscriptionId) { Uri requestUri = WAPTenant.CreateRequestUri(String.Format(CultureInfo.InvariantCulture, Constants.ServiceProviderFoundation.SubVMRoleGalleryItems, subscriptionId), //"{0}/{1}", subscriptionId, Constants.ServiceProviderFoundation.GalleryItems), new KeyValuePair<string, string>("api-version", "2013-03")); var response = WAPTenant.SendAsyncString(requestUri, new HttpMethod(Constants.HttpMethods.Get)); return Parser.FromJSONString<VMRoleGalleryItem>(response.Result); } /// <summary> /// Gets all resource definitions for a subscription /// </summary> /// <param name="subscriptionId"></param> /// <param name="relativePath"></param> /// <returns></returns> public VMRoleResourceDefinition GetCloudServiceResourceDefinition(string subscriptionId, string relativePath) { Uri requestUri = WAPTenant.CreateRequestUri(String.Format(CultureInfo.InvariantCulture, "{0}/{1}", subscriptionId, relativePath), new KeyValuePair<string, string>("api-version", "2013-03")); var response = WAPTenant.SendAsyncString(requestUri, new HttpMethod(Constants.HttpMethods.Get)); return Parser.FromJSONString<VMRoleResourceDefinition>(response.Result).FirstOrDefault(); } /// <summary> /// Creates VM Role for a subscription /// </summary> /// <param name="subscriptionId"></param> /// <param name="cloudServiceName"></param> /// <param name="vmRole"></param> /// <returns></returns> public async Task<VMRole> CreateVMRole(string subscriptionId, string cloudServiceName, VMRole vmRole) { Uri requestUri = WAPTenant.CreateRequestUri(String.Format(CultureInfo.InvariantCulture, Constants.ServiceProviderFoundation.SubCloudServiceVMRoles, subscriptionId, cloudServiceName), //"{0}/{1}/{2}/{3}", subscriptionId, Constants.ServiceProviderFoundation.CloudServices, //cloudServiceName, Constants.ServiceProviderFoundation.VMRoles), new KeyValuePair<string, string>("api-version", "2013-03")); String jsonString = Parser.ToJSON(vmRole); var response = await WAPTenant.SendAsyncString(requestUri, new HttpMethod(Constants.HttpMethods.Post), jsonString, TenantUserName, true); return Parser.FromJSONString<VMRole>(response).FirstOrDefault(); } private bool disposed = false; /// <summary> /// Dispose the object for system/users call /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { //WAPAuth = null; WAPTenant = null; VMMTenant.Dispose(); } } this.disposed = true; } /// <summary> /// Dispose the object per users call /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Mvc; using TinhLuong.Models; using TinhLuongBLL; using TinhLuongINFO; namespace TinhLuong.Controllers { public class UpdateKhoanThanhToanController : BaseController { SaveLog sv = new SaveLog(); // GET: UpdateKhoanThanhToan [CheckCredential(RoleID = "NHAP_LUONGKY1")] public ActionResult Index() { //sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Cac khoan thanh toan"); drpThang(); drpNam(); return View(); } [CheckCredential(RoleID = "NHAP_LUONGKY1")] public ActionResult IndexDetail(int Thang, int Nam) { //sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Cac khoan thanh toan-thang-" + Thang + "-nam-" + Nam); drpNam(Nam.ToString()); drpThang(Thang.ToString()); var bangluongk1 = new UpdateKhoanThanhToanBLL().GetBangLuongKyIDonVi(Session[SessionCommon.DonViID].ToString(), Thang, Nam); return View(bangluongk1); } [CheckCredential(RoleID = "NHAP_LUONGKY1")] [HttpGet] public ActionResult Details(string NhanSuID, int Thang, int Nam) { DataTable dt = new DataTable(); //sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Cac khoan thanh toan-> Detail-thang-" + Thang + "-nam-" + Nam + "-NhanSuID-+" + NhanSuID); //var bangluongk1_nhanvien = new UpdateKhoanThanhToanBLL().GetBangLuongKy1_ByNhanVien(NhanSuID, Thang, Nam); var bangluongk1_nhanvien = new UpdateKhoanThanhToanBLL().GetBangLuongKyIDonVi(Session[SessionCommon.DonViID].ToString(), Thang, Nam); var ok = bangluongk1_nhanvien.Select("NhanSuID='" + NhanSuID+"'").CopyToDataTable(); loadDrpDonVi(ok.Rows[0]["DonViID"].ToString()); return View(ok); } [CheckCredential(RoleID = "NHAP_LUONGKY1")] public ActionResult UpdateKhoanThanhToan(decimal Thang, decimal Nam, string NhanSuID, string SOTK, decimal ANCA, decimal CTP_KHOANTH, decimal TT_THEMGIO, decimal CHENUOC, decimal CTP_KHAC, decimal BOIDUONGK3, decimal THUNHAP1, decimal LUONGKY1, decimal THUNHAP12) { if (new ImportExcelBLL().GetChotSo(Thang, Nam, Session[SessionCommon.DonViID].ToString(), "BangLuongKy1") == false) { setAlert("Dữ liệu đã chốt, không tiếp tục cập nhật được!", "error"); } else { var rs = new UpdateKhoanThanhToanBLL().BangLuongKy1_Update(Thang, Nam, NhanSuID, SOTK, ANCA, CTP_KHOANTH, TT_THEMGIO, CHENUOC, CTP_KHAC, BOIDUONGK3, THUNHAP1, LUONGKY1, THUNHAP12); if (rs > 0) { sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Cac khoan thanh toan->UpdateKhoanThanhtoan-thang-" + Thang + "-nam-" + Nam + "-NhanSuID-" + NhanSuID + "->Success"); setAlert("Cập nhật thành công", "success"); } else { sv.save(Session[SessionCommon.Username].ToString(), "Cap nhat luong->Cac khoan thanh toan->UpdateKhoanThanhtoan-thang-" + Thang + "-nam-" + Nam + "-NhanSuID-" + NhanSuID + "->Fail"); setAlert("Cập nhật không thành công", "error"); } } return Redirect("/update-khoan-thanh-toan/thang-" + Thang + "-nam-" + Nam); } public void loadDrpDonVi(string selected = null) { var rs = new BangLuongDonViBLL().SelectByDonVi(Session[SessionCommon.DonViID].ToString()); ViewBag.DonViID = new SelectList(rs, "DonViID", "TenDonVi", selected); } public void drpThang(string selected = null) { List<SelectListItem> listItems = new List<SelectListItem>(); listItems.Add(new SelectListItem { Text = "1", Value = "1" }); listItems.Add(new SelectListItem { Text = "2", Value = "2", }); listItems.Add(new SelectListItem { Text = "3", Value = "3" }); listItems.Add(new SelectListItem { Text = "4", Value = "4" }); listItems.Add(new SelectListItem { Text = "5", Value = "5" }); listItems.Add(new SelectListItem { Text = "6", Value = "6" }); listItems.Add(new SelectListItem { Text = "7", Value = "7" }); listItems.Add(new SelectListItem { Text = "8", Value = "8" }); listItems.Add(new SelectListItem { Text = "9", Value = "9" }); listItems.Add(new SelectListItem { Text = "10", Value = "10" }); listItems.Add(new SelectListItem { Text = "11", Value = "11" }); listItems.Add(new SelectListItem { Text = "12", Value = "12" }); ViewBag.drpThang = new SelectList(listItems, "Value", "Text", selected); } public void drpNam(string selected = null) { List<SelectListItem> listItems = new List<SelectListItem>(); listItems.Add(new SelectListItem { Text =(DateTime.Now.Year-2).ToString(), Value = (DateTime.Now.Year - 2).ToString() }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year - 1).ToString(), Value = (DateTime.Now.Year - 1).ToString(), }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year).ToString(), Value = (DateTime.Now.Year ).ToString() }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year +1).ToString(), Value = (DateTime.Now.Year +1).ToString() }); listItems.Add(new SelectListItem { Text = (DateTime.Now.Year +2).ToString(), Value = (DateTime.Now.Year +2).ToString() }); ViewBag.drpNam = new SelectList(listItems, "Value", "Text", selected); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SC.AsyncSamples { /// <summary> /// 同步 /// 如果需要共享数据,就必须使用同步技术,确保一次只有一个线程访问和改变共享状态。 /// 可以用于多个线程的同步技术: /// ● lock /// ● Interlocked /// ● Monitor /// ● SpinLock /// ● WaitHandle /// ● Mutex /// ● Semaphore /// ● Event /// ● Barrier /// ● ReadWriterLockSlim /// lock、Interlocked、Monitor可用于进程内部的同步; /// Mutex、Event、Semaphore、ReadWriterLockSlim提供了多个进程之间的线程同步 /// 最佳实践:使用锁定需要时间,且并不总是必须的。 /// 可以创建类的两个版本,一个同步版本,一个异步版本。<see cref="Demo"/> /// /// </summary> class SyncSkill { #region 1、lock /// <summary> /// C#为多个线程的同步提供了自己的关键字:lock语句。lock语句是设置锁定和解除锁定的一种简单方式。 /// </summary> static void SyncSample() { // 创建一个SharedState对象,并把它传递给20个Task对象的构造函数 int numTasks = 20; var state = new SharedState(); var tasks = new Task[numTasks]; // 因为执行了50000次循环,有20个任务,所以写入控制台的值应是1000000。但是,事实常常并非如此 for (int i = 0; i < numTasks; i++) { tasks[i] = Task.Run(() => new Job(state).DoTheJob()); } for (int i = 0; i < numTasks; i++) { tasks[i].Wait(); } Console.WriteLine("summarized {0}", state.State); } #endregion #region 2、Interlocked /// <summary> /// Interlocked类用于使变量的简单语句原子化,它的操作包括从内存中获取一个值,给该值递增1,再将它存储回内存。 /// Interlocked类提供了以线程安全的方式递增、递减、交换和读取值的方法。 /// 与其他同步技术相比,使用Interlocked类会快得多。但是,它只能用于简单的同步问题。 /// 例如,这里不使用lock语句锁定对someState变量的访问,把它设置为一个新值,以防它是空的,而可以使用Interlocked类,它比较快: /// </summary> public class InterlockDemo { string someState; string newState; int state; public void lockTest() { lock (this) { if (someState == null) { someState = newState; } } } public void InterlockTest() { Interlocked.CompareExchange(ref someState, newState, null); } // 不是像下面这样在lock语句中执行递增操作 //public int State //{ // get // { // lock (this) // { // return ++state; // } // } //} // 而使用较快的Interlocked.Increment()方法 public int State { get { return Interlocked.Increment(ref state); } } } #endregion #region 3、Monitor /// <summary> /// lock 语句由 C# 编译器解析为使用 Monitor 类。 /// 使用 Monitor 类的形式,与使用 lock 关键字基本上是一样的, /// 不过与 lock 关键字不同的是,Monitor 类还具有 TryEnter、Wait、Pulse 以及 PulseAll 方法。 /// </summary> public class SimpleMonitorClass { protected ClassCounter m_protectedResource = new ClassCounter(); protected void IncrementProtectedResourceMethod() { //lock (m_protectedResource) //{ // //synchronized region for obj //} Monitor.Enter(m_protectedResource); try { m_protectedResource.Increment(); } finally { Monitor.Exit(m_protectedResource); } } /// <summary> /// TryEnter 方法与 Enter 方法的区别很简单,就是 Enter 方法在返回之前,会无限时等待受保护部分的锁定释放。 /// 可以添加一个等待被锁定的超时值,这样就不会无限期地等待被锁定。 /// 可以像下面的例子那样使用 TryEnter 方法,其中给它传递一个超时值,指定等待被锁定的最长时间。 /// 如果 obj 被锁定,TryEnter() 方法就把布尔型的引用参数设置为 true,并同步地访问由对象 obj 锁定的状态。 /// 如果另一个钱程锁定 obj 的时间超过了500毫秒,TryEnter 方法就把变量 lockTaken 设置为 false,线程不再等待,而是用于执行其他操作。 /// 也许在以后,该线程会尝试再次获得锁定。 /// </summary> protected void IncrementProtectedResourceMethod2() { bool lockTaken = false; Monitor.TryEnter(m_protectedResource, 500, ref lockTaken); if (lockTaken) { try { m_protectedResource.Increment(); } finally { Monitor.Exit(m_protectedResource); } } } public static void Demo() { SimpleMonitorClass exampleClass = new SimpleMonitorClass(); exampleClass.IncrementProtectedResourceMethod(); } } #endregion #region 4、SpinLock /** * 如果基于对象的锁定对象(Monitor)的系统开销由于垃圾回收而过高,就可以使用SpinLock结构。 * SpinLock 结构是在 .NET 4 开始引入的。如果有大量的锁定(例如,列表中的每个节点都有一个锁定),且锁定的时间总是非常短,SpinLock结构就很有用。 * 应避免使用多个 SpinLock 结构,也不要调用任何可能阻塞的内容。 * 除了体系结构上的区别之外,SpinLock 结构的用法非常类似于 Monitor 类。获得锁定使用 Enter() 或 TryEnter() 方法,释放锁定使用 Exist 方法。 * SpinLock 结构还提供了属性 IsHeld 和 IsHeldByCurrentThread,指定它当前是否是锁定的。 * 传送 SpinLock 实例时要小心,因为 SpinLock 定义为结构,把一个变量赋予另一个变量会创建一个副本,所以应该总是通过引用传送 SpinLock 实例。 */ #endregion #region 5、WaitHandle delegate int TakesAWhileDelegate(int a, int b); /// <summary> /// WaitHandle 是一个抽象基类,用于等待一个信号的设置。可以等待不同的信号,因为 WaitHandle 是一个基类,可以从中派生一些类。 /// 在描述异步委托时,已经使用了 WaitHandle 基类。异步委托的 BeginInvoke() 方法返回一个实现了 IAsycResult 接口的对象。 /// 使用 IAsycResult 接口,可以用 AsycWaitHandle 属性访问 WaitHandle 基类。 /// 在调用 WaitOne() 方法时,线程会等待接收一个与等待句柄相关的信号。 /// 使用 WaitHandle 基类可以等待一个信号的出现(WaitOne()方法)、等待必须发出信号的多个对象(WaitAll()方法)、或者等待多个对象中的一个(WaitAny()方法)。 /// WaitAll() 和 WaitAny() 是 WaitHandle 类的静态方法,接收一个 WaitHandle 参数数组。 /// WaitHandle 基类有一个 SafeWaitHandle 属性,其中可以将一个本机句柄赋予一个操作系统资源,并等待该句柄。 /// 例如,可以指定一个 SafeFileHandle 等待文件 I/O 操作的完成,或者指定自定义的 SafeTransactionHandle。 /// 因为Murex、EventWaitHandle 和 Semapbore 类派生自 WaitHandle 基类,所以可以在等待时使用它们。 /// </summary> public void WaitHandleDemo() { TakesAWhileDelegate d1 = TakesAWhile; IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null); while (true) { Console.Write("."); if (ar.AsyncWaitHandle.WaitOne(50, false)) { Console.WriteLine("Can get the result now"); break; } } int result = d1.EndInvoke(ar); Console.WriteLine("result: {0}", result); } public int TakesAWhile(int a, int b) { return a + b; } #endregion #region 6、Mutex /// <summary> /// Mutex(mutual exclusion,互斥)是.NET Framework 中提供跨多个进程同步访问的一个类。 /// 它非常类似于Monitor类,因为它们都只有一个线程能拥有锁定。只有一个线程能获得互斥锁定,访问受互斥保护的同步代码区域。 /// 在 Mutex 类的构造函数中,可以指定互斥是否最初应由主调线程拥有,定义互斥的名称,获得互斥是否已存在的信息。 /// 使用 Mutex 同步,避免多个线程在同一时刻访问同一共享资源 Mutex /// </summary> public void MutexDemo() { bool createdNew; /** * 接收一个表示互斥是否为新建的布尔值(createdNew)。如果返回的值是false,就表示互斥己经定义。 * 互斥可以在另一个进程中定义,因为操作系统能够识别有名称的互斥,它由不同的进程共享。 * 如果没有给互斥指定名称,互斥就是未命名的,不在不同的进程之间共享。 */ Mutex mutex = new Mutex(false, "ProCSharpMutex", out createdNew); // 由于系统能识别有名称的互斥,因此可以使用它禁止应用程序启动两次 if (!createdNew) { // 程序关闭 } /** * 要打开己有的互斥,还可以使用 Mutex.OpenExisting() 方法,它不需要用构造函数创建互斥时需要的相同 .NET 权限。 * 由于 Mutex 类派生自基类 WaitHandle,因此可以利用 WaitOne() 方法获得互斥锁定,在该过程中成为该互斥的拥有者。 * 调用 ReleaseMutex() 方法,即可释放互斥。 */ if (mutex.WaitOne()) { try { //synchronized region } finally { mutex.ReleaseMutex(); } } else { //some problem happened while waiting } } #endregion #region 7、Semaphore /// <summary> /// Semaphore 信号灯同步限制了访问同一共享资源的线程数量。 /// 信号量非常类似于互斥,其区别是,信号量可以同时由多个线程使用。信号量是一种计数的互斥锁定。 /// 使用信号量,可以定义允许同时访问受旗语锁定保护的资源的线程个数。如果需要限制可以访问可用资源的线程数,信号量就很有用。 /// 例如,如果系统有 3 个物理端口可用,就允许 3 个线程同时访问 I/O 端口,但第 4 个线程需要等待前 3 个线程中的一个释放资源。 /// .NET4.5 为信号量功能提供了两个类 Semaphore 和 SemaphoreSlim。 /// Semaphore 类可以命名,使用系统范围内的资源,允许在不同进程之间同步。 /// SemaphoreSlim 类是对较短等待时间进行了优化的轻型版本。 /// </summary> public void SemaphoreDemo() { int taskCount = 6; int semaphoreCount = 3; // 创建一个计数为3的信号量 // 最初释放的锁定数(第一个参数),锁定个数的计数(第二个参数) // 如果参数1小于参数2,它们的差就是已经分配线程的计数值 // 与互斥一样,也可以给信号量指定名称,使之在不同的进程之间共享。 // 这里定义信号量时没有指定名称,所以它只能在这个进程中使用。 var semaphore = new SemaphoreSlim(semaphoreCount, semaphoreCount); // 创建6个任务 var tasks = new Task[taskCount]; for (int i = 0; i < taskCount; i++) { // 启动的6个任务都获得了相同的信号量 tasks[i] = Task.Run(() => TaskMain(semaphore)); } Task.WaitAll(tasks); Console.WriteLine("All tasks finished"); } /// <summary> /// 任务利用 Wait() 方法锁定信号量,信号量的计数是3,所以有3个任务可以获得锁定。 /// 第4个任务必须等待,这里还定义了最长的等待时间为600毫秒。如果在该等待时间过后未能获得锁定,任务就把一条消息写入控制台,在循环中继续等待。 /// 只要获得了锁定,任务就把一条消息写入控制台,睡眠一段时间,然后解除锁定。 /// 在解除锁定时,在任何情况下一定要解除资源的锁定,这一点很重要。这就是在 finally 处理程序中调用 Semaphote 类的 Release() 方法的原因。 /// </summary> /// <param name="semaphore"></param> static void TaskMain(SemaphoreSlim semaphore) { bool isCompleted = false; while (!isCompleted) { if (semaphore.Wait(600)) { try { Console.WriteLine("Task {0} locks the semaphore", Task.CurrentId); Thread.Sleep(2000); } finally { Console.WriteLine("Task {0} releases the semaphore", Task.CurrentId); semaphore.Release(); isCompleted = true; } } else { Console.WriteLine("Timeout for task {0}; wait again", Task.CurrentId); } } } #endregion #region 8、Event /// <summary> /// Critical Section 临界区同步的作用与 mutex 是一样的,但临界区同步不能跨进程(lock、Monitor、Interlocked、ReaderWriterLock) /// Event 事件同步能够通知其他线程执行指定操作(AutoResetEvent、ManualResetEvent、WaitHandle) /// /// 与互斥和信号量对象一样,事件也是一个系统范围内的资源同步方法。 /// 为了从托管代码中使用系统事件,.NET Framework 在 System.Threading 名称空间中提供了 ManualResetEvent、AutoResetEvent、ManualResetEventSlim 和 CountdownEvent 类。 /// ManualResetEventSlim 和 CountdownEvent 类是 .NET4 新增的。 /// C# 中的 event 关键字基于委托,和 System.Threading 名称空间中的 event 类没有关系。 /// 可以使用事件通知其他任务:这里有一些数据,并完成了一些操作等。事件可以发信号,也可以不发信号。 /// 使用前面介绍的 WaitHandle 类,任务可以等待处于发信号状态的事件。 /// 调用 Set() 方法,即可向 ManualResetEventSlim 发信号。 /// 调用 Reset() 方法,可以使之返回不发信号的状态。 /// 如果多个线程等待向一个事件发信号,并调用了 Set() 方法,就释放所有等待的线程。 /// 另外,如果一个线程刚刚调用了 WaitOne() 方法,但事件己经发出信号,等待的线程就可以继续等待。 /// 也可以通过调用 Set() 方法向 AutoResetEvent 发信号。也可以使用 Reset() 方法使之返回不发信号的状态。 /// 但是,如果一个线程在等待自动重置的事件发信号,当第一个线程的等待状态结束时,该事件会自动变为不发信号的状态。 /// 这样,如果多个线程在等待向事件发信号,就只有一个线程结束其等待状态,它不是等待时间最长的线程,而是优先级最高的线程。 /// 在一个类似的场景中,为了把一些工作分支到多个任务中,并在以后合并结果,使用新的 CountdownEvent 类很有用。 /// 不需要为每个任务创建一个单独的事件对象,而只需要创建一个事件对象。 /// CountdownEvent 类为所有设置了事件的任务定义了个初始数字,在到达该计数后,就向 CountdownEvent 类发信号。 /// 示例方法现在可以简化,使它只需要等待一个事件。如果不像前面那样单独处理结果,这个新版本就很不错。 /// </summary> static void EventDemo() { const int taskCount = 4; // 定义包含 4 个 ManualResetEventSlim 对象的数组 var mEvents = new ManualResetEventSlim[taskCount]; var waitHandles = new WaitHandle[taskCount]; // 包含 4 个 Calculator 对象的数组 var calcs = new Calculator[taskCount]; for (int i = 0; i < taskCount; i++) { int i1 = i; mEvents[i] = new ManualResetEventSlim(false); /** * 与 ManualResetEvent 对象不同,ManualResetEventSlim 对象不派生自 WaitHandle 类。 * 因此有一个 WaitHandle 对象的集合,它在 ManualResetEventSlim 类的 WaitHandle 属性中填充。 */ waitHandles[i] = mEvents[i].WaitHandle; // 每个 Calculator 在构造函数中用一个 ManualResetEventSlim 对象初始化 // 这样每个任务在完成时都有自己的事件对象来发信号 calcs[i] = new Calculator(mEvents[i]); // 使用Task,让不同的任务执行计算任务 Task.Run(() => calcs[i1].Calculation(i1 + 1, i1 + 3)); } for (int i = 0; i < taskCount; i++) { // WaitHandle 类现在用于等待数组中的任意一个事件。WaitAny() 方法等待向任意一个事件发信号 int index = WaitHandle.WaitAny(waitHandles); if (index == WaitHandle.WaitTimeout) { Console.WriteLine("Timeout!!"); } else { // 从 WaitAny 方法返回的 index 值匹配传递给 WaitAny() 方法的事件数组的索引,以提供发信号的事件的相关信息,使用该索引可以从这个事件中读取结果。 mEvents[index].Reset(); Console.WriteLine("finished task for {0}, result: {1}", index, calcs[index].Result); } } } public class Calculator { private ManualResetEventSlim mEvent; public int Result { get; private set; } public Calculator(ManualResetEventSlim ev) { this.mEvent = ev; } /// <summary> /// 任务入口点 /// </summary> /// <param name="x"></param> /// <param name="y"></param> public void Calculation(int x, int y) { Console.WriteLine("Task {0} starts calculation", Task.CurrentId); Thread.Sleep(new Random().Next(3000)); // 在随机的一段时间后完成计算 Result = x + y; // signal the event—completed! Console.WriteLine("Task {0} is ready", Task.CurrentId); // 向事件发信号 mEvent.Set(); // cEvent.Signal(); } } #endregion #region 9、Barrier #endregion } #region ... internal class ClassCounter { internal void Increment() { throw new NotImplementedException(); } } public class SharedState { private int state = 0; public int State { get; set; } } public class Job { SharedState sharedState; static SharedState staticSharedState; private object syncRoot = new object(); public Job(SharedState sharedState) { this.sharedState = sharedState; } public void DoTheJob() { /** * 必须在这个程序中添加同步功能,这可以用lock关键宇实现。 * 用lock语句定义的对象表示,要等待指定对象的锁定。只能传递引用类型。 * 锁定值类型只是锁定了一个副本,这没有什么意义。如果对值类型使用了lock语句,C#编译器就会发出个错误。 * 进行了锁定后(只锁定了一个线程),就可以运行lock语句块。在lock语句块的最后,对象的锁定被解除,另一个等待锁定的线程就可以获得该锁定块了。 */ //var syncObj = new object(); //lock (syncObj) /** * 使用lock关键字可以将类的实例成员设置为线程安全的。这样,一次只有一个线程能访问相同实例的方法。 * 但是,因为实例的对象也可以用于外部的同步访问(锁定实例后,实例的同步方法都无法访问!), * 而且我们不能在类自身中控制这种访问,所以应采用SyncRoot模式。 * 通过SyncRoot模式,创建一个私有对象syncRoot,将这个对象用于lock语句。 */ //lock(this) //lock (syncRoot) { for (int i = 0; i < 50000; i++) { sharedState.State += 1; } } } public static void DoStaticJob() { lock (typeof(Job)) // 要锁定静态成员,可以把锁放在object类型上 { for (int i = 0; i < 50000; i++) { staticSharedState.State += 1; } } } } /// <summary> /// Demo类本身不是同步的,但是该类定义了一个内部类SynchronizedDemo /// 必须注意,在使用SynchronizedDemo类时,只有方法是同步的,对两个成员的调用没有同步 /// </summary> public class Demo { private class SynchronizedDemo : Demo { private object syncRoot = new object(); private Demo d; public SynchronizedDemo(Demo d) { this.d = d; } public override bool IsSynchronized { get { return true; } } public override void DoThat() { lock (syncRoot) { d.DoThat(); } } public override void DoThis() { lock (syncRoot) { d.DoThis(); } } } public virtual bool IsSynchronized { get { return false; } } public static Demo Synchronized(Demo d) { if (!d.IsSynchronized) { return new SynchronizedDemo(d); } return d; } public virtual void DoThis() { } public virtual void DoThat() { } } #endregion }
using System; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.IO; using System.Windows.Forms; using System.Web; using DMS.DataAccessObject; using DMS.BusinessObject; using DMS.Utils; namespace DMS.BusinessObject { /// <summary> /// Summary description for CustomerBO. /// </summary> public class clsParameterBO:clsBaseBO { private static log4net.ILog log = log4net.LogManager.GetLogger(typeof(clsParameterBO)); protected clsParameterDAO dao = new clsParameterDAO(); public clsParameterBO() { } /// <summary> /// Return DataTable to Combobox /// </summary> /// <remarks> /// Author: Nguyen Minh Khoa G3 /// Modified: 18-Apr-2011 /// </remarks> public DataTable LoadAll() { return dao.GetDataTable("SELECT DISTINCT PARAM_GROUP FROM GENERAL_PARAMETERS ORDER BY PARAM_GROUP DESC"); } /// <summary> /// Return DataTable to Set Source for DAtaGrid /// </summary> /// <remarks> /// Author: Nguyen Minh Khoa G3 /// Modified: 18-Apr-2011 /// </remarks> public DataTable GetOne(string ParamterGroup, string param) { return dao.GetOne(ParamterGroup, param); } /// <summary> /// Update Parameter value /// </summary> /// <remarks> /// Author: Nguyen Minh Khoa G3 /// Modified: 18-Apr-2011 /// </remarks> public bool Update(string m_value, string m_name) { return dao.UpdateValue(m_value, m_name); } /// <summary> /// Check Parameter value /// </summary> /// <remarks> /// Author: Nguyen Minh Khoa G3 /// Modified: 18-Apr-2011 /// </remarks> public bool Validate(string strType, string strValue) { if(strType=="s") { // if(Directory.Exists(strValue)==false) // { return false; } strValue=strValue.Replace(":", ""); if(isNumeric(strValue)) { return false; } } // else if(strType=="t"||strType=="n") { strValue=strValue.Replace(":", "0"); if( !isNumeric(strValue)) { return false; } } else if(strType=="b") { if(!(strValue=="Y"||strValue=="y" || strValue== "N"||strValue=="n")) return false; } else if(strType == "d") { // Modified by: TuanDH // Date: 19/07/2010 int intCheck = 0; string[] strDate = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; for(int i = 0; i < strDate.Length; i++) { if (strValue.ToUpper() == strDate[i].ToUpper()) return true; intCheck += 1; } //if(intCheck == strDate.Length) return false; return false; } return true; } /// <summary> /// Check chuoi co phai la numeric hay ko /// </summary> /// <remarks> /// Author: Nguyen Minh Khoa G3 /// Modified: 18-Apr-2011 /// </remarks> public bool isNumeric(string val) { try { Double.Parse(val); return true; } catch { return false; } } /// <summary> /// Export Parameter /// </summary> /// <remarks> /// Author : Nguyen Bao Nguyen G3 /// Created day : 24-Apr-2011 /// </remarks> public string ExportParameter(string strRRWeek, string strMaxPPO, string strMinPPO) { string strParamPath = ""; try { strParamPath = dao.ExportParameter(strRRWeek, strMaxPPO, strMinPPO); if (strParamPath != "") // khac rong co nghia la export param thanh cong ZipFileParam(strParamPath); return strParamPath; } catch (Exception ex) { throw ex; } } //-- tuannh2 added 20080822: export param cua nhung cust_code dat hang daily public string ExportDailyParameter() { try { string path = ""; DataTable dt = dao.GetDataTable("select distinct cust_code from GENERAL_DISTRIBUTOR_HIERARCHY where PPO_TYPE = 'D' AND STATUS = 'AC'"); string strExportPath = dao.GetExportParamPath(); foreach(DataRow drow in dt.Rows) { string strCustCode = drow["CUST_CODE"].ToString(); path = dao.ExportDailyParameter(strCustCode, strExportPath); } ZipFileParam(path); return path; } catch(Exception ex) { throw ex; } } //-- end tuannh2 /// <summary> /// Get Status of Stock Paramters /// </summary> /// <remarks> /// //true: exported , false : unexported /// Author: Nguyen Bao Nguyen G3 /// Modified: 24-Apr-2011 /// </remarks> /// <returns></returns> public bool ExistUnexportedParam() { try { return dao.ExistUnexportedParam(); } catch (Exception ex) { log.Error(ex.Message, ex); throw ex; } } /// <summary> /// Zip file /// </summary> /// <remarks> /// Author : Nguyen Bao Nguyen G3 /// Created day : 24-Apr-2011 /// </remarks> public void ZipFileParam(string strParamPath) { try { //string strFileNameToEncode = ""; string strZipFilename = ""; string strPass = ""; string strPath = strParamPath; string[] filenames = Directory.GetFiles(strPath, "*.xml"); clsCryptography genPass = new clsCryptography(); foreach (string file in filenames) { strZipFilename = file.Substring(0, file.Length -4)+".zip"; //strFileNameToEncode = file.Substring(0, file.Length -4); strPass = genPass.GenPWDByFilename(strZipFilename); clsZip.ZipFiles(file, strZipFilename, strPass); File.Delete(file); } } catch (Exception ex) { throw ex; } } // Author: TuanDH // Created Date: 02/07/2010 public DayOfWeek GetFirstDayOfWeek() { string firstDayOfWeek = dao.GetFirstDayOfWeek(); switch (firstDayOfWeek) { case "MON": return DayOfWeek.Monday; case "TUE": return DayOfWeek.Tuesday; case "WED": return DayOfWeek.Wednesday; case "THU": return DayOfWeek.Thursday; case "FRI": return DayOfWeek.Friday; case "SAT": return DayOfWeek.Saturday; case "SUN": return DayOfWeek.Sunday; } return DayOfWeek.Monday; } // Author: TuanDH // Created Date: 02/07/2010 public DayOfWeek GetEndDayOfWeek() { string endDayOfWeek = dao.GetEndDayOfWeek(); switch (endDayOfWeek.ToUpper()) { case "MON": return DayOfWeek.Monday; case "TUE": return DayOfWeek.Tuesday; case "WED": return DayOfWeek.Wednesday; case "THU": return DayOfWeek.Thursday; case "FRI": return DayOfWeek.Friday; case "SAT": return DayOfWeek.Saturday; case "SUN": return DayOfWeek.Sunday; } return DayOfWeek.Sunday; } // Author: TuanDH // Created Date: 08/07/2010 public int GetMaxDaysOfFirstWeek() { try { string maxDays = dao.GetMaxDaysOfFirstWeek(); return int.Parse(maxDays); } catch { return 13; } } } }
using System.Data.Entity; using Microsoft.AspNet.Identity.EntityFramework; namespace ApartmentApps.Data { //public class ApplicationDbContext2 : DbContext //{ // public virtual IDbSet<MaintenanceRequestStatus> MaintenanceRequestStatuses { get; set; } // public virtual IDbSet<Corporation> Corporations { get; set; } // public virtual IDbSet<Property> Properties { get; set; } // public virtual DbSet<Building> Buildings { get; set; } // public virtual IDbSet<Unit> Units { get; set; } // public virtual IDbSet<MaitenanceRequest> MaitenanceRequests { get; set; } // public virtual IDbSet<MaintenanceRequestCheckin> MaintenanceRequestCheckins { get; set; } // public virtual IDbSet<MaitenanceRequestType> MaitenanceRequestTypes { get; set; } // public virtual IDbSet<PropertyEntrataInfo> PropertyEntrataInfos { get; set; } // public virtual IDbSet<PropertyYardiInfo> PropertyYardiInfos { get; set; } // public virtual IDbSet<ApplicationUser> ApplicationUsers { get; set; } // public virtual IDbSet<IdentityRole> Roles { get; set; } // public ApplicationDbContext2() // { // } // protected override void OnModelCreating(DbModelBuilder modelBuilder) // { // base.OnModelCreating(modelBuilder); // //modelBuilder.Entity<Unit>().Property(p => p.Latitude); // //modelBuilder.Entity<Unit>().Property(p => p.Longitude).HasPrecision(9, 6); // //modelBuilder.Entity<CourtesyOfficerLocation>().Property(p => p.Latitude).HasPrecision(9, 6); // //modelBuilder.Entity<CourtesyOfficerLocation>().Property(p => p.Longitude).HasPrecision(9, 6); // modelBuilder.Entity<ApplicationUser>().HasKey<string>(l => l.Id); // modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId); // modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id); // // modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId }); // modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles); // modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) => // new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles"); // } // public System.Data.Entity.DbSet<ApartmentApps.Data.MaintenanceRequestStatus> MaintenanceRequestStatus { get; set; } // public virtual IDbSet<CourtesyOfficerLocation> CourtesyOfficerLocations { get; set; } // public virtual IDbSet<IncidentReport> IncidentReports { get; set; } // public virtual IDbSet<IncidentReportCheckin> IncidentReportCheckins { get; set; } // public virtual IDbSet<IncidentReportStatus> IncidentReportStatuses { get; set; } // public System.Data.Entity.DbSet<ApartmentApps.Data.IncidentReportStatus> IncidentReportStatus { get; set; } //} }
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual; using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base; using Pe.Stracon.SGC.Presentacion.Recursos.Base; using System.Collections.Generic; using System.Web.Mvc; using System.Linq; using Pe.GyM.Security.Account.Model; namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.VariablePlantillaRequerimiento { /// <summary> /// Modelo de vista Variable Plantilla /// </summary> /// <remarks> /// Creación: GMD 20150709 /// Modificación: /// </remarks> public class VariablePlantillaRequerimientoBusqueda : GenericViewModel { /// <summary> /// Constructor Variable Plantilla Busqueda /// </summary> /// <param name="plantilla">Plantilla</param> /// <param name="tipoVariable">Tipo Variable</param> public VariablePlantillaRequerimientoBusqueda(List<PlantillaRequerimientoResponse> plantilla, List<CodigoValorResponse> tipoVariable) { var listaPlantilla = plantilla.Select(x => new CodigoValorResponse() { Codigo = x.CodigoPlantilla, Valor = x.Descripcion }).ToList(); this.Plantilla = this.GenerarListadoOpcioneGenericoFiltro(listaPlantilla); this.Tipo = this.GenerarListadoOpcioneGenericoFiltro(tipoVariable); this.AplicaPlantillas = this.GenerarListadoOpcionesSiNoFiltro(); this.variableResponse = new VariableResponse(); } #region Propiedades /// <summary> /// Lista Plantilla /// </summary> public List<SelectListItem> Plantilla { get; set; } /// <summary> /// Lista Tipo /// </summary> public List<SelectListItem> Tipo { get; set; } /// <summary> /// Lista Aplica todas las plantillas /// </summary> public List<SelectListItem> AplicaPlantillas { get; set; } /// <summary> /// Clases con campos Variable /// </summary> public VariableResponse variableResponse { get; set; } /// <summary> /// Controles de Permiso /// </summary> public Control ControlPermisos { get; set; } #endregion } }
/* * Company: * Motto: Talk more to loved ones! * Assignment: A book shelf application * Deadline: 2012-01-02 * Programmer: Baran Topal * Solution name: .BookShelfWeb * Folder name: .Util * Project name: .BookShelfWeb.ConverterManager * File name: BookShelfConverter.cs * Status: Finished */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace BookShelfWeb.ConverterManager { /// <summary> /// converts data types between each other /// </summary> public sealed class BookShelfConverter { #region Data Type Conversion /// <summary> /// convert DateTime to long /// </summary> /// <param name="timepoint"></param> /// <returns></returns> public static long ConvertDateTime2Tick(DateTime timepoint) { return Convert.ToInt64(timepoint.Subtract(new DateTime(1970, 01, 01)).TotalMilliseconds); } /// <summary> /// Convert long to DateTime /// </summary> /// <param name="tick"></param> /// <returns></returns> public static DateTime ConvertTick2DateTime(long tick) { return new DateTime(1970, 01, 01).AddMilliseconds(tick); } #endregion } }
using Inventor; using InventorServices.Persistence; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DynamoInventor { internal abstract class Button { #region Private fields private ButtonDefinition buttonDefinition; private ButtonDefinitionSink_OnExecuteEventHandler ButtonDefinition_OnExecuteEventDelegate; #endregion Private fields #region Public properties public Inventor.ButtonDefinition ButtonDefinition { get { return buttonDefinition; } } #endregion Public properties #region Public constructors public Button(string displayName, string internalName, CommandTypesEnum commandType, string clientId, string description, string tooltip, Icon standardIcon, Icon largeIcon, ButtonDisplayEnum buttonDisplayType) { try { stdole.IPictureDisp standardIconIPictureDisp; standardIconIPictureDisp = PictureDispConverter.ToIPictureDisp(standardIcon); stdole.IPictureDisp largeIconIPictureDisp; largeIconIPictureDisp = PictureDispConverter.ToIPictureDisp(largeIcon); buttonDefinition = PersistenceManager.InventorApplication.CommandManager.ControlDefinitions.AddButtonDefinition(displayName, internalName, commandType, clientId, description, tooltip, standardIconIPictureDisp, largeIconIPictureDisp, buttonDisplayType); buttonDefinition.Enabled = true; ButtonDefinition_OnExecuteEventDelegate = new ButtonDefinitionSink_OnExecuteEventHandler(ButtonDefinition_OnExecute); buttonDefinition.OnExecute += ButtonDefinition_OnExecuteEventDelegate; } catch (Exception e) { throw new ApplicationException(e.ToString()); } } public Button(string displayName, string internalName, CommandTypesEnum commandType, string clientId, string description, string tooltip, ButtonDisplayEnum buttonDisplayType) { try { buttonDefinition = PersistenceManager.InventorApplication.CommandManager.ControlDefinitions.AddButtonDefinition(displayName, internalName, commandType, clientId, description, tooltip, Type.Missing, Type.Missing, buttonDisplayType); buttonDefinition.Enabled = true; ButtonDefinition_OnExecuteEventDelegate = new ButtonDefinitionSink_OnExecuteEventHandler(ButtonDefinition_OnExecute); buttonDefinition.OnExecute += ButtonDefinition_OnExecuteEventDelegate; } catch (Exception e) { throw new ApplicationException(e.ToString()); } } abstract protected void ButtonDefinition_OnExecute(NameValueMap context); #endregion Public constructors } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EasyDev.BL; using System.Data; using EasyDev.Util; using EasyDev.SQMS; namespace SQMS.Services { public class EmployeeService : GenericService { public PassportService PassportService { get; private set; } public RoleService RoleService { get; private set; } public EnumerationService EnumService { get; private set; } public OrganizationService OrganizationService { get; private set; } public EquipmentService EquipmentService { get; private set; } public UserRoleService UserRoleService { get; private set; } protected override void Initialize() { this.BOName = "EMPLOYEE"; PassportService = ServiceManager.CreateService<PassportService>(); RoleService = ServiceManager.CreateService<RoleService>(); EnumService = ServiceManager.CreateService<EnumerationService>(); OrganizationService = ServiceManager.CreateService<OrganizationService>(); EquipmentService = ServiceManager.CreateService<EquipmentService>(); UserRoleService = ServiceManager.CreateService<UserRoleService>(); base.Initialize(); } public DataSet GetRoles() { DataSet ds = RoleService.LoadAll(); foreach (DataRow item in ds.Tables["ROLE"].Rows) { if (ConvertUtil.ToStringOrDefault(item["memo"]).Length > 0) { item["rolename"] = ConvertUtil.ToStringOrDefault(item["rolename"]) + ":" + ConvertUtil.ToStringOrDefault(item["memo"]); } } return ds; } public DataTable GetSex() { return EnumService.GetSex(); } public DataSet GetDepartments() { return OrganizationService.LoadByCondition( "orgtype='department' and organizationid='" + CurrentUser.OrganizationID + "'"); } public DataSet GetEquipments() { return EquipmentService.LoadAll(); } public string GetPassport(string empid) { return PassportService.GetPassport(empid); } public DataSet GetPassportByEmployeeID(string empid) { return PassportService.GetPassportByEmployeeID(empid); } public DataSet LoadPassportByKey(string key) { return PassportService.LoadByKey(key, true); } public override void Save(DataSet dsSave) { //将其它职员的设备绑定信息设置为无效 string equid = ConvertUtil.ToStringOrDefault(DataSetUtil.GetFirstRowFromDataSet(dsSave, BOName)["EQUID"]); DefaultSession.ExecuteCommand("update employee set isequactivate='N' where equid=:equid and organizationid=:orgid", equid, CurrentUser.OrganizationID); base.Save(dsSave); //调用本当前服务的基类保存,用于保存职员 dsSave.Tables.Remove(this.BOName); string passportid = ""; if (dsSave.Tables.Contains(PassportService.BOName)) { PassportService.Save(dsSave); passportid = ConvertUtil.ToStringOrDefault(dsSave.Tables[PassportService.BOName].Rows[0]["passportid"]); dsSave.Tables.Remove(PassportService.BOName); } if (dsSave.Tables.Contains(UserRoleService.BOName)) { //删除角色分配 int effectRows = DefaultSession.ExecuteCommand(@"delete from userrole ur where ur.passportid=:passportid", passportid); UserRoleService.Save(dsSave); dsSave.Tables.Remove(UserRoleService.BOName); } } public void Delete(DataSet ds) { DataRow drEmployee = DataSetUtil.GetFirstRowFromDataSet(ds, "EMPLOYEE"); string employeeId = ""; string passportid = ""; if (drEmployee != null) { employeeId = ConvertUtil.ToStringOrDefault(drEmployee["EMPID"]); } //删除USERROLE DataRow drPassport = DataSetUtil.GetFirstRowFromDataSet(PassportService.GetPassportByEmployeeID(employeeId), "PASSPORT"); if (drPassport != null) { passportid = ConvertUtil.ToStringOrDefault(drPassport["PASSPORTID"]); UserRoleService.DefaultSession.ExecuteCommand("delete from userrole ur where ur.passportid=:passportid", passportid); } //删除职员账号 PassportService.DeleteByKey(passportid); //删除职员 base.DeleteByKey(employeeId); } public override void DeleteByKey(object key) { DataSet ds = LoadByKey(key.ToString()); DataSet tmp = PassportService.GetPassportByEmployeeID(key.ToString()); if (tmp != null && tmp.Tables.Count > 0) { ds.Merge(tmp); tmp = RoleService.GetRolesView(key.ToString()); if (tmp != null && tmp.Tables.Count > 0) { ds.Merge(tmp); } } Delete(ds); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PADIbookCommonLib { [Serializable] public class SignedLookupResponse : SignedMessage { public List<RedirectionFile> FileList { get; set; } public string Username { get; set; } public string Uri { get; set; } public SignedLookupResponse(string username, string uri, List<RedirectionFile> filelist, byte[] signature) : base(signature) { Username = username; Uri = uri; FileList = filelist; } public SignedLookupResponse() : base() { } } }
using Microsoft.Extensions.Configuration; using System.Collections.Generic; using Microsoft.Data.SqlClient; using Sunnie.Models; using Sunnie.Utils; namespace Sunnie.Repositories { public class FavoriteRepository : BaseRepository, IFavoriteRepository { public FavoriteRepository(IConfiguration configuration) : base(configuration) { } public List<Favorite> GetAllFavoritesForUser(int id) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @" SELECT f.Id AS FavoriteId, f.ProductId, f.UserProfileId, p.Id, p.Name AS ProductName, p.ImageLocation AS ProductImage, p.Spf, p.Comment, p.UserProfileId, p.ProductTypeId, up.Id, pt.Id, pt.Type FROM Favorite f LEFT JOIN Product p ON p.Id = f.ProductId LEFT JOIN UserProfile up ON up.Id = f.UserProfileId LEFT JOIN ProductType pt ON pt.Id = p.ProductTypeId WHERE f.UserProfileId = @UserProfileId"; DbUtils.AddParameter(cmd, "@UserProfileId", id); SqlDataReader reader = cmd.ExecuteReader(); var favorites = new List<Favorite>(); while (reader.Read()) { favorites.Add(new Favorite() { Id = DbUtils.GetInt(reader, "FavoriteId"), UserProfileId = id, UserProfile = new UserProfile() { Id = reader.GetInt32(reader.GetOrdinal("Id")), }, ProductId = DbUtils.GetInt(reader, "ProductId"), Product = new Product() { Id = DbUtils.GetInt(reader, "ProductId"), Name = DbUtils.GetString(reader, "ProductName"), ImageLocation = DbUtils.GetNullableString(reader, "ProductImage"), Spf = DbUtils.GetNullableInt(reader, "Spf"), Comment = DbUtils.GetNullableString(reader, "Comment"), UserProfileId = DbUtils.GetInt(reader, "UserProfileId"), ProductTypeId = DbUtils.GetInt(reader, "ProductTypeId"), ProductType = new ProductType() { Id = DbUtils.GetInt(reader, "ProductTypeId"), Type = DbUtils.GetString(reader, "Type") } }, }); } reader.Close(); return favorites; } } } public Favorite GetFavoriteById(int id) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @" SELECT Id, ProductId, UserProfileId FROM Favorite WHERE Id = @id"; cmd.Parameters.AddWithValue("@id", id); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { Favorite favorite = new Favorite() { Id = reader.GetInt32(reader.GetOrdinal("Id")), ProductId = reader.GetInt32(reader.GetOrdinal("ProductId")), UserProfileId = reader.GetInt32(reader.GetOrdinal("UserProfileId")) }; reader.Close(); return favorite; } reader.Close(); return null; } } } public Favorite Add(Favorite favorite) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @" INSERT INTO Favorite(ProductId, UserProfileId) OUTPUT INSERTED.ID VALUES (@productId, @userProfileId)"; cmd.Parameters.AddWithValue("@productId", favorite.ProductId); cmd.Parameters.AddWithValue("@userProfileId", favorite.UserProfileId); int id = (int)cmd.ExecuteScalar(); favorite.Id = id; return favorite; } } } public void Delete(int favoriteId) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @" DELETE FROM Favorite WHERE Id = @favoriteId"; cmd.Parameters.AddWithValue("@favoriteId", favoriteId); cmd.ExecuteNonQuery(); } } } } }