text
stringlengths
13
6.01M
using AutoMapper; using AutoMapper.Extensions.ExpressionMapping; using Enrollment.AutoMapperProfiles; using Enrollment.Bsl.Business.Requests; using Enrollment.Bsl.Business.Responses; using Enrollment.Bsl.Flow.Cache; using Enrollment.BSL.AutoMapperProfiles; using Enrollment.Contexts; using Enrollment.Domain.Entities; using Enrollment.Repositories; using Enrollment.Stores; using LogicBuilder.RulesDirector; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; namespace Enrollment.Bsl.Flow.Integration.Tests.Rules { public class InsertAcademicTest { public InsertAcademicTest(ITestOutputHelper output) { this.output = output; Initialize(); } #region Fields private IServiceProvider serviceProvider; private readonly ITestOutputHelper output; #endregion Fields [Fact] public void SaveAcademic() { //arrange IFlowManager flowManager = serviceProvider.GetRequiredService<IFlowManager>(); var user = new UserModel { UserName = "NewName", EntityState = LogicBuilder.Domain.EntityStateType.Added }; flowManager.FlowDataCache.Request = new SaveEntityRequest { Entity = user }; flowManager.Start("saveuser"); Assert.True(user.UserId > 1); var academic = new AcademicModel { UserId = user.UserId, EntityState = LogicBuilder.Domain.EntityStateType.Added, AttendedPriorColleges = true, FromDate = new DateTime(2010, 10, 10), ToDate = new DateTime(2014, 10, 10), GraduationStatus = "H", EarnedCreditAtCmc = true, LastHighSchoolLocation = "NC", NcHighSchoolName = "NCSCHOOL1", Institutions = new List<InstitutionModel> { new InstitutionModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, HighestDegreeEarned = "BD", StartYear = "2015", EndYear = "2018", InstitutionName = "Florida Institution 1", InstitutionState = "FL", MonthYearGraduated = new DateTime(2020, 10, 10) } } }; flowManager.FlowDataCache.Request = new SaveEntityRequest { Entity = academic }; //act System.Diagnostics.Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew(); flowManager.Start("saveacademic"); stopWatch.Stop(); this.output.WriteLine("Saving valid academic = {0}", stopWatch.Elapsed.TotalMilliseconds); //assert Assert.True(flowManager.FlowDataCache.Response.Success); Assert.Empty(flowManager.FlowDataCache.Response.ErrorMessages); AcademicModel model = (AcademicModel)((SaveEntityResponse)flowManager.FlowDataCache.Response).Entity; Assert.Equal("NC", model.LastHighSchoolLocation); Assert.Equal("2018", model.Institutions.First().EndYear); } [Fact] public void SaveInvalidAcademic() { //arrange IFlowManager flowManager = serviceProvider.GetRequiredService<IFlowManager>(); var user = new UserModel { UserName = "NewName", EntityState = LogicBuilder.Domain.EntityStateType.Added }; flowManager.FlowDataCache.Request = new SaveEntityRequest { Entity = user }; flowManager.Start("saveuser"); Assert.True(user.UserId > 1); var academic = new AcademicModel { UserId = user.UserId, EntityState = LogicBuilder.Domain.EntityStateType.Added, AttendedPriorColleges = true, FromDate = new DateTime(), ToDate = new DateTime(), GraduationStatus = null, EarnedCreditAtCmc = true, LastHighSchoolLocation = null, NcHighSchoolName = "NCSCHOOL1", Institutions = new List<InstitutionModel> { new InstitutionModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, HighestDegreeEarned = "BD", StartYear = "2015", EndYear = null, InstitutionName = "Florida Institution 1", InstitutionState = "FL", MonthYearGraduated = new DateTime(2020, 10, 10) } } }; flowManager.FlowDataCache.Request = new SaveEntityRequest { Entity = academic }; //act System.Diagnostics.Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew(); flowManager.Start("saveacademic"); stopWatch.Stop(); this.output.WriteLine("Saving valid academic = {0}", stopWatch.Elapsed.TotalMilliseconds); //assert Assert.False(flowManager.FlowDataCache.Response.Success); Assert.Equal(5, flowManager.FlowDataCache.Response.ErrorMessages.Count); } #region Helpers static MapperConfiguration MapperConfiguration; private void Initialize() { if (MapperConfiguration == null) { MapperConfiguration = new MapperConfiguration(cfg => { cfg.AddExpressionMapping(); cfg.AddProfile<ParameterToDescriptorMappingProfile>(); cfg.AddProfile<DescriptorToOperatorMappingProfile>(); cfg.AddProfile<EnrollmentProfile>(); cfg.AddProfile<ExpansionParameterToDescriptorMappingProfile>(); cfg.AddProfile<ExpansionDescriptorToOperatorMappingProfile>(); }); } MapperConfiguration.AssertConfigurationIsValid(); serviceProvider = new ServiceCollection() .AddDbContext<EnrollmentContext> ( options => options.UseSqlServer ( @"Server=(localdb)\mssqllocaldb;Database=InsertAcademicTest;ConnectRetryCount=0" ), ServiceLifetime.Transient ) .AddLogging ( loggingBuilder => { loggingBuilder.ClearProviders(); loggingBuilder.Services.AddSingleton<ILoggerProvider> ( serviceProvider => new XUnitLoggerProvider(this.output) ); loggingBuilder.AddFilter<XUnitLoggerProvider>("*", LogLevel.None); loggingBuilder.AddFilter<XUnitLoggerProvider>("Enrollment.Bsl.Flow", LogLevel.Trace); } ) .AddTransient<IEnrollmentStore, EnrollmentStore>() .AddTransient<IEnrollmentRepository, EnrollmentRepository>() .AddSingleton<AutoMapper.IConfigurationProvider> ( MapperConfiguration ) .AddTransient<IMapper>(sp => new Mapper(sp.GetRequiredService<AutoMapper.IConfigurationProvider>(), sp.GetService)) .AddTransient<IFlowManager, FlowManager>() .AddTransient<FlowActivityFactory, FlowActivityFactory>() .AddTransient<DirectorFactory, DirectorFactory>() .AddTransient<ICustomActions, CustomActions>() .AddSingleton<FlowDataCache, FlowDataCache>() .AddSingleton<Progress, Progress>() .AddSingleton<IRulesCache>(sp => { return Bsl.Flow.Rules.RulesService.LoadRules().GetAwaiter().GetResult(); }) .BuildServiceProvider(); ReCreateDataBase(serviceProvider.GetRequiredService<EnrollmentContext>()); DatabaseSeeder.Seed_Database(serviceProvider.GetRequiredService<IEnrollmentRepository>()).Wait(); } private static void ReCreateDataBase(EnrollmentContext context) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); } #endregion Helpers } }
using UnityEngine; using System.Collections; public class AntiPhobicBox : MonoBehaviour { public bool IsReusable; private Animator animator; void Start() { animator = GetComponent<Animator>(); } void OnTriggerEnter(Collider other) { if (other.CompareTag("PhobicObject")) { animator.SetBool("IsOpen", false); StartCoroutine(WaitAndDestroy(other.gameObject)); } } IEnumerator WaitAndDestroy(GameObject phobicObject) { // Wait for the end of the animation yield return new WaitForSeconds(animator.GetCurrentAnimatorClipInfo(0).Length); Destroy(phobicObject); if(IsReusable) { yield return new WaitForSeconds(2f); animator.SetBool("IsOpen", true); } } }
using System; using Android.App; using Android.Content; using Android.OS; using Android.Widget; using Android.Appwidget; using System.Timers; namespace Daeseongwidget { [Service] public class UpdateService : Service { private RemoteViews updateViews; public override void OnStart(Intent intent, int startId) { this.updateViews = new RemoteViews(this.PackageName, Resource.Layout.widget); BuildUpdate(this); ComponentName thisWidget = new ComponentName(this, Java.Lang.Class.FromType(typeof(AppWidget)).Name); AppWidgetManager manager = AppWidgetManager.GetInstance(this); manager.UpdateAppWidget(thisWidget, updateViews); Timer timer = new Timer(); timer.Interval = 1000; timer.Elapsed += Timer_Elapsed; timer.Enabled = true; } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { this.updateViews = new RemoteViews(this.PackageName, Resource.Layout.widget); BuildUpdate(this); ComponentName thisWidget = new ComponentName(this, Java.Lang.Class.FromType(typeof(AppWidget)).Name); AppWidgetManager manager = AppWidgetManager.GetInstance(this); manager.UpdateAppWidget(thisWidget, updateViews); } public override IBinder OnBind(Intent intent) { return null; } public void BuildUpdate(Context context) { string sText = string.Format("{0:HH:mm:ss}", DateTime.Now); string text = $"{sText}"; this.updateViews.SetTextViewText(Resource.Id.textView1, text); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; using EntityFramework.Extensions; using SO.Urba.Models.ValueObjects; using SO.Urba.DbContexts; using SO.Utility.Models.ViewModels; using SO.Utility; using SO.Utility.Helpers; using SO.Utility.Extensions; using SO.Urba.Models.ViewModels; namespace SO.Urba.Managers.Base { public class ClientManagerBase { public ClientManagerBase() { } /// <summary> /// Find Client matching the contactMembershipId (primary key) /// </summary> public ClientVo get(int clientId) { using (var db = new MainDb()) { var res = db.clients .Include(i => i.contactInfo) .Include(a => a.clientOrganizationLookupses.Select(c => c.organization)) .FirstOrDefault(p => p.clientId == clientId); return res; } } /// <summary> /// Get First Item /// </summary> public ClientVo getFirst() { using (var db = new MainDb()) { var res = db.clients .Include(i => i.contactInfo) .Include(o => o.clientOrganizationLookupses) .FirstOrDefault(); return res; } } public SearchFilterVm search(SearchFilterVm input) { int keywordInt = 0; int.TryParse(input.keyword, out keywordInt); using (var db = new MainDb()) { var query = db.clients .Include(i => i.contactInfo) //.Include(o => o.clientOrganizationLookupses) .Include(a => a.clientOrganizationLookupses.Select(c => c.organization)) .Where(e => (input.isActive == null || e.isActive == input.isActive) && (e.contactInfo != null)); switch (input.searchField) { default: case SearchField.All: query = query .Where(e => string.IsNullOrEmpty(input.keyword) || e.contactInfo.firstName.Contains(input.keyword) || e.contactInfo.lastName.Contains(input.keyword) || e.contactInfo.address.Contains(input.keyword) || e.contactInfo.city.Contains(input.keyword) || e.contactInfo.state.Contains(input.keyword) || e.contactInfo.homePhone.Contains(input.keyword) || e.contactInfo.workPhone.Contains(input.keyword) || (keywordInt > 0 && e.clientId == keywordInt)); break; case SearchField.FirstName: query = query .Where(e => string.IsNullOrEmpty(input.keyword) || e.contactInfo.firstName.Contains(input.keyword)); break; case SearchField.LastName: query = query .Where(e => string.IsNullOrEmpty(input.keyword) || e.contactInfo.lastName.Contains(input.keyword)); break; case SearchField.MemberID: query = query .Where(e => keywordInt > 0 && e.clientId == keywordInt); break; } query = query .OrderByDescending(b => b.created); if (input.paging != null) { input.paging.totalCount = query.Count(); query = query .Skip(input.paging.skip) .Take(input.paging.rowCount); } input.result = query.ToList<object>(); return input; } } public List<ClientVo> getAll(bool? isActive=true) { using (var db = new MainDb()) { var list = db.clients .Include(i => i.contactInfo) .Include(o => o.clientOrganizationLookupses) .Where(e => isActive==null || e.isActive == isActive ) .OrderBy(i => i.contactInfo.firstName).ToList(); return list; } } public bool delete(int clientId) { using (var db = new MainDb()) { var res = db.clients .Include(i => i.contactInfo) .Include(o => o.clientOrganizationLookupses) .Where(e => e.clientId == clientId) .Delete(); return true; } } public ClientVo update(ClientVo input, int? clientId = null) { using (var db = new MainDb()) { if (clientId == null) clientId = input.clientId; var res = db.clients.FirstOrDefault(e => e.clientId == clientId); if (res == null) return null; input.created = res.created; // input.createdBy = res.createdBy; db.Entry(res).CurrentValues.SetValues(input); db.SaveChanges(); return res; } } public ClientVo insert(ClientVo input) { using (var db = new MainDb()) { db.clients.Add(input); db.SaveChanges(); return input; } } public int count() { using (var db = new MainDb()) { return db.clients.Count(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PowerUps : MonoBehaviour { public static PowerUps instance; [Header ("Other")] public float xPos; public float yPos; public float zPos; public float timeValue; private bool isCORn; [Header ("Soul Currency")] public GameObject soul; public float soulSpawnInterval; public int soulProbabilityFactor;//It's to check if a random number from 0-100 >= this number [Header ("Health PowerUp")] public GameObject healthPowerup; public float healthPowerupSpawnInterval; public int healthProbabilityFactor;//It's to check if a random number from 0-100 >= this number [Header ("Rage PowerUp")] public GameObject ragePowerup; public float ragePowerupSpawnInterval; public int rageProbabilityFactor;//It's to check if a random number from 0-100 >= this number void Start() { instance = this; //Health PH = GetComponent<Health> (); } public void Update() { int rando = Random.Range (0, 100); //Debug.Log(rando); if((rando >= healthProbabilityFactor) && !isCORn){ //Debug.Log("healthPowerup-"+isCORn); StartCoroutine(SpawnInterval(healthPowerup, healthPowerupSpawnInterval)); } rando = Random.Range (0, 100); if((rando >= rageProbabilityFactor) && !isCORn){ //Debug.Log("ragePowerup-"+isCORn); StartCoroutine(SpawnInterval(ragePowerup, ragePowerupSpawnInterval)); } rando = Random.Range (0, 100); if((rando >= soulProbabilityFactor) && !isCORn){ //Debug.Log("ragePowerup-"+isCORn); StartCoroutine(SpawnInterval(soul, soulSpawnInterval)); } } IEnumerator SpawnInterval(GameObject powerup, float powerupSpawnInterval){ isCORn = true; Vector3 spawnPosition = new Vector3 (Random.Range (-xPos, xPos), yPos, Random.Range (-zPos, zPos)); Instantiate (powerup, spawnPosition, Quaternion.identity); float randomTimeValue = Random.Range (-timeValue, timeValue); yield return new WaitForSeconds(powerupSpawnInterval + randomTimeValue); isCORn = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpAvanzado { class GenericList<T> { private class Node { public Node(T dato) { Dato = dato; Next = null; } public T Dato { get; set; } public Node Next { get; set; } } private Node head; public GenericList() { head = null; } public void Add(T dato) { Node node = new Node(dato); node.Next = head; head = node; } public IEnumerator<T> GetEnumerator() { Node actual = head; while (actual != null) { yield return actual.Dato; actual = actual.Next; } } } }
using nmct.ba.cashlessproject.model.ASP.NET; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace nmct.ba.cashlessproject.api.PresentationModels { public class PMOrganisations { public List<PMOrganisation> NewPMOrganisations { get; set; } } }
using Migration.Common; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; namespace JiraExport { public enum RevisionChangeType { Added, Removed } public class RevisionAction<T> { public RevisionChangeType ChangeType { get; set; } public T Value { get; set; } public override string ToString() { return $"{ChangeType.ToString()} {Value.ToString()}"; } } public class JiraRevision : ISourceRevision, IComparable<JiraRevision> { public DateTime Time { get; set; } public string Author { get; set; } public Dictionary<string, object> Fields { get; set; } public List<RevisionAction<JiraLink>> LinkActions { get; set; } public List<RevisionAction<JiraAttachment>> AttachmentActions { get; set; } public JiraItem ParentItem { get; private set; } public int Index { get; internal set; } public string OriginId => ParentItem.Key; public string Type => ParentItem.Type; public JiraRevision(JiraItem parentItem) { ParentItem = parentItem; } public int CompareTo(JiraRevision other) { int t = this.Time.CompareTo(other.Time); if (t != 0) return t; return this.ParentItem.Key.CompareTo(other.ParentItem.Key); } public string GetFieldValue(string fieldName) { return (string)(((IEnumerable<JiraRevision>)ParentItem.Revisions) .Reverse() .SkipWhile(r => r.Index > this.Index) .FirstOrDefault(r => r.Fields.ContainsKey(fieldName)) ?.Fields[fieldName]); } } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System; namespace Framework.Metadata { public class CxTabCustomizerData { //------------------------------------------------------------------------- private CxTabCustomizer m_Customizer; //------------------------------------------------------------------------- /// <summary> /// The customizer the data belongs to. /// </summary> public CxTabCustomizer Customizer { get { return m_Customizer; } set { m_Customizer = value; } } //------------------------------------------------------------------------- /// <summary> /// Ctor. /// </summary> /// <param name="customizer">the customizer the tab belongs to</param> public CxTabCustomizerData(CxTabCustomizer customizer) { Customizer = customizer; } //------------------------------------------------------------------------- /// <summary> /// Compares the data with another. /// </summary> /// <param name="otherData">the object to compare with</param> /// <returns>true if equal</returns> public bool Compare(CxTabCustomizerData otherData) { return true; } //------------------------------------------------------------------------- /// <summary> /// Returns a clone of the customizer data. /// </summary> public CxTabCustomizerData Clone() { CxTabCustomizerData clone = new CxTabCustomizerData(Customizer); return clone; } //------------------------------------------------------------------------- } }
using SetApi.Models; namespace Set.Api.Models { public class GameResult { public bool ValidGameID { get; set; } public Game GameObj { get; set; } public string Error { get; set; } } }
using LuizalabsWishesManager.Domains.Models; using LuizalabsWishesManager.Domains.Repositories; namespace LuizalabsWishesManager.Data.Repositories { public class UserRepository : RepositoryBase<User>, IUserRepository { } }
using System; namespace Relocation.Classes { /// <summary> /// 打印窗体接口 /// </summary> interface IPrintForm { /// <summary> /// 打印方法 /// </summary> void Print(); } }
using System.Threading.Tasks; using JwtApp.Core.DTOs; using JwtApp.Core.Utilities; using JwtApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace JwtApp.Controllers { [ApiController] [Route("api/[controller]")] public class AccountController : ControllerBase { private readonly IAccountService _accountService; public AccountController(IAccountService accountService) { _accountService = accountService; } [AllowAnonymous] [HttpPost("login")] public async Task<Result<UserDto>> Login(LoginDto loginDto) { return await _accountService.Login(loginDto); } [Authorize] [HttpPost("refreshToken")] public async Task<Result<UserDto>> RefreshToken() { return await _accountService.RefreshToken(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using asiakasrekisteri.Models; namespace asiakasrekisteri.Controllers { public class AccesLevelsController : Controller { private AsiakasrekisteriEntities1 db = new AsiakasrekisteriEntities1(); // GET: AccesLevels public ActionResult Index() { return View(db.AccesLevels.ToList()); } // GET: AccesLevels/Details/5 public ActionResult Details(short? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AccesLevels accesLevels = db.AccesLevels.Find(id); if (accesLevels == null) { return HttpNotFound(); } return View(accesLevels); } // GET: AccesLevels/Create public ActionResult Create() { return View(); } // POST: AccesLevels/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "AccesslevelID,AccessName,ALevel")] AccesLevels accesLevels) { if (ModelState.IsValid) { db.AccesLevels.Add(accesLevels); db.SaveChanges(); return RedirectToAction("Index"); } return View(accesLevels); } // GET: AccesLevels/Edit/5 public ActionResult Edit(short? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AccesLevels accesLevels = db.AccesLevels.Find(id); if (accesLevels == null) { return HttpNotFound(); } return View(accesLevels); } // POST: AccesLevels/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "AccesslevelID,AccessName,ALevel")] AccesLevels accesLevels) { if (ModelState.IsValid) { db.Entry(accesLevels).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(accesLevels); } // GET: AccesLevels/Delete/5 public ActionResult Delete(short? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AccesLevels accesLevels = db.AccesLevels.Find(id); if (accesLevels == null) { return HttpNotFound(); } return View(accesLevels); } // POST: AccesLevels/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(short id) { AccesLevels accesLevels = db.AccesLevels.Find(id); db.AccesLevels.Remove(accesLevels); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using DataAccess.Models; using System.Collections.Generic; using DataAccess.Repositories.Interfaces; using iQuest.VendingMachine.PresentationLayer.Views.Interfaces; using Microsoft.VisualStudio.TestTools.UnitTesting; using iQuest.VendingMachine.UseCases.Reports.UseCaseList; using iQuest.VendingMachine.UseCases.Reports.Interfaces; using Moq; namespace VendingMachine.Tests.UseCases.SalesReportUseCaseTest { [TestClass] public class ExecuteTests { private Mock<IReportsView> salesView; private Mock<IReportsSerializer> reportsSerializer; private Mock<ISoldProductRepository> soldProductRepo; private Mock<IFileService> fileService; private SalesReportUseCase salesUseCase; [TestInitialize] public void TestSetup() { salesView = new Mock<IReportsView>(); reportsSerializer = new Mock<IReportsSerializer>(); soldProductRepo = new Mock<ISoldProductRepository>(); fileService = new Mock<IFileService>(); salesUseCase = new SalesReportUseCase(reportsSerializer.Object, salesView.Object, soldProductRepo.Object, fileService.Object); } [TestMethod] public void HavingASalesReportUseCaseInstance_WhenExecuted_ThenShowFormat() { //arrange //act salesUseCase.Execute(); //assert salesView.Verify(x => x.TellFileFormat(It.IsAny<string>()), Times.Once); } [TestMethod] public void HavingASalesReportUseCase_WhenExecutedN_ThenCallSerializer() { //arrange //act salesUseCase.Execute(); //assert reportsSerializer.Verify(x => x.SerializeSalesReport(It.IsAny<IEnumerable<SoldProduct>>()), Times.Once); } [TestMethod] public void HavingASalesReportUseCase_WhenExecuted_ThenCallCreatedMessageMethod() { //arrange //act salesUseCase.Execute(); //assert salesView.Verify(x => x.CreatedMessage(It.IsAny<string>(), It.IsAny<string>()), Times.Once); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using NetCode; using NetcodeTest.Util; namespace NetcodeTest.Events { public abstract class Event { [Synchronisable(SyncFlags.Timestamp)] public long Timestamp { get; protected set; } public abstract bool Expired(); public abstract void Predict(long timestamp); public abstract void Draw(SpriteBatch batch); } }
using Ghost.Extensions; using System; using UnityEngine; namespace RO { public class CameraPointGroup : MonoBehaviour { public CameraPointGroupInfo[] groups; public void SetValidity(int index, bool valid) { if (this.groups == null || !this.groups.CheckIndex(index)) { return; } CameraPointGroupInfo cameraPointGroupInfo = this.groups[index]; cameraPointGroupInfo.enable = valid; cameraPointGroupInfo.ResetValidity(); } public void ResetValidity() { CameraPointGroupInfo[] array = this.groups; for (int i = 0; i < array.Length; i++) { CameraPointGroupInfo cameraPointGroupInfo = array[i]; cameraPointGroupInfo.ResetValidity(); } } private void Awake() { this.ResetValidity(); } private void Start() { if (!(null != SingleTonGO<CameraPointManager>.Me) || !SingleTonGO<CameraPointManager>.Me.SetGroup(this)) { Object.Destroy(base.get_gameObject()); } } private void OnDestroy() { if (null != SingleTonGO<CameraPointManager>.Me) { SingleTonGO<CameraPointManager>.Me.ClearGroup(this); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Text; using Breezy.Sdk.Objects; using Breezy.Sdk.Payloads; using Breezy.Sdk.Printing; using Newtonsoft.Json; namespace Breezy.Sdk { /// <summary> /// Operations with the Breezy API /// </summary> public partial class BreezyApiClient { private readonly string _clientKey; private readonly string _clientSecret; private readonly Uri _apiUri; public BreezyApiClient(string clientKey, string clientSecret, string apiUrl) { if (clientKey == null) throw new ArgumentNullException("clientKey"); if (clientSecret == null) throw new ArgumentNullException("clientSecret"); if (apiUrl == null) throw new ArgumentNullException("apiUrl"); _clientKey = clientKey; _clientSecret = clientSecret; _apiUri = new Uri(apiUrl); } public BreezyApiClient(string clientKey, string clientSecret) : this(clientKey, clientSecret, "https://api.breezy.com/") { } /// <summary> /// Authorizes the individual Breezy user /// </summary> /// <param name="mdmAuthKey">MDM Auth Key of the Breezy account</param> /// <param name="userEmail">email of the user being authorized</param> /// <returns>OAuth access token to use for subsequent calls to the API on behalf of the authorized user</returns> public OAuthToken Authorize(string mdmAuthKey, string userEmail) { if (mdmAuthKey == null) throw new ArgumentNullException("mdmAuthKey"); if (userEmail == null) throw new ArgumentNullException("userEmail"); var requestToken = GetRequestToken(); var oauthVerifier = GetOAuthVerifierWithMdmAuthKey(mdmAuthKey, userEmail, requestToken); var accessToken = GetAccessToken(requestToken, oauthVerifier); return accessToken; } /// <summary> /// Authorizes the individual Breezy user /// </summary> /// <param name="password">MDM Auth Key of the Breezy account</param> /// <param name="userEmail">email of the user being authorized</param> /// <returns>OAuth access token to use for subsequent calls to the API on behalf of the authorized user</returns> public OAuthToken AuthorizeWithPassword(string password, string userEmail) { if (password == null) throw new ArgumentNullException("password"); if (userEmail == null) throw new ArgumentNullException("userEmail"); var requestToken = GetRequestToken(); var oauthVerifier = GetOAuthVerifierWithPassword(password, userEmail, requestToken); var accessToken = GetAccessToken(requestToken, oauthVerifier); return accessToken; } /// <summary> /// Makes a request to the API endpoint /// </summary> /// <param name="userAccessToken">OAuth token which the user has been authorized with</param> /// <param name="endpoint">API endpoint</param> /// <param name="httpMethod">HTTP method of the request</param> /// <param name="payload">JSON payload for POST and PUT requests</param> /// <returns>content of the response</returns> public string MakeApiRequest(OAuthToken userAccessToken, string endpoint, HttpMethod httpMethod, string payload = null) { if (userAccessToken == null) throw new ArgumentNullException("userAccessToken"); if (endpoint == null) throw new ArgumentNullException("endpoint"); if ((httpMethod == HttpMethod.Post || httpMethod == HttpMethod.Put) && payload == null) throw new ArgumentException("Payload cannot be null for POST or PUT requests."); using (var http = new HttpClient()) { SignOAuthRequest(http, userAccessToken, httpMethod, endpoint); HttpResponseMessage response; if (httpMethod == HttpMethod.Get) { response = http.GetAsync(_apiUri.AbsoluteUri + endpoint).Result; } else if (httpMethod == HttpMethod.Post) { response = http.PostAsync(_apiUri.AbsoluteUri + endpoint, new StringContent(payload, Encoding.UTF8, "application/json")).Result; } else if (httpMethod == HttpMethod.Put) { response = http.PutAsync(_apiUri.AbsoluteUri + endpoint, new StringContent(payload, Encoding.UTF8, "application/json")).Result; } else if (httpMethod == HttpMethod.Delete) { response = http.DeleteAsync(_apiUri.AbsoluteUri + endpoint).Result; } else { throw new NotSupportedException(String.Format("HTTP method {0} not supported.", httpMethod)); } var responseBody = response.Content.ReadAsStringAsync().Result; if (response.StatusCode != HttpStatusCode.OK) throw new BreezyApiException( String.Format( "API request failed.\r\nEndpoint: {0}\r\nResponse status code: {1}.\r\nResponse: {2}", endpoint, response.StatusCode, responseBody)); return responseBody; } } /// <summary> /// Returns the list of the printers available for a Breezy user /// </summary> /// <param name="userAccessToken">OAuth token which the user has been authorized with</param> public List<Printer> GetPrinters(OAuthToken userAccessToken) { var responseBody = MakeApiRequest(userAccessToken, ApiEndpoints.GetUserPrinters, HttpMethod.Get); var printerList = JsonConvert.DeserializeObject<PrinterListMessage>(responseBody); return printerList.Printers; } /// <summary> /// Prints a document /// </summary> /// <param name="documentName">user friendly document name with a file extension</param> /// <param name="filePath">path to a file to print</param> /// <param name="printerId">id of a printer</param> /// <param name="userAccessToken">OAuth token which the user has been authorized with</param> /// <returns>id of a printed document</returns> public int Print(string documentName, string filePath, int? printerId, OAuthToken userAccessToken) { if (filePath == null) throw new ArgumentNullException("filePath"); if (!File.Exists(filePath)) throw new ArgumentException(String.Format("File {0} not found.", filePath)); using (var fs = File.OpenRead(filePath)) { return Print(documentName, fs, printerId, userAccessToken); } } /// <summary> /// Prints a document /// </summary> /// <param name="documentName">user friendly document name with a file extension</param> /// <param name="documentStream">data stream to print</param> /// <param name="printerId">id of a printer</param> /// <param name="userAccessToken">OAuth token the user has been authorized with</param> /// <returns>id of a printed document</returns> public int Print(string documentName, Stream documentStream, int? printerId, OAuthToken userAccessToken) { if (documentName == null) throw new ArgumentNullException("documentName"); if (documentStream == null) throw new ArgumentNullException("documentStream"); if (userAccessToken == null) throw new ArgumentNullException("userAccessToken"); var fileType = Path.GetExtension(documentName); var fileSize = (int)documentStream.Length; var finishingOptions = new PrinterSettings(); // POST document var documentUploadMessage = SubmitDocument(printerId, documentName, fileType, fileSize, finishingOptions, userAccessToken); // encrypt document SymmetricEncryptionParameters symmetricEncryptionParameters; using (var encryptedStream = EncryptStream(documentStream, documentUploadMessage.PublicKeyModulus, documentUploadMessage.PublicKeyExponent, out symmetricEncryptionParameters)) { // upload document UploadStreamToBuffer(encryptedStream, documentUploadMessage.UploadUrl); } // POST document/{document_id}/status UpdateDocumentStatusAfterFileUpload(documentUploadMessage.DocumentId, symmetricEncryptionParameters, documentName, fileType, fileSize, finishingOptions, userAccessToken); return documentUploadMessage.DocumentId; } } }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("PopularityEvaluatorTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TOWER Australia Limited")] [assembly: AssemblyProduct("PopularityEvaluatorTest")] [assembly: AssemblyCopyright("Copyright © TOWER Australia Limited 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("32d16cfc-56c6-46b7-9e5f-baa95225b13b")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using MonoGame.Extended.Serialization; using Newtonsoft.Json; namespace MonoGame.Extended.Particles.Serialization { public sealed class ParticleJsonSerializer : JsonSerializer { public ParticleJsonSerializer(ITextureRegionService textureRegionService, NullValueHandling nullValueHandling = NullValueHandling.Include) { Converters.Add(new Vector2JsonConverter()); Converters.Add(new Size2JsonConverter()); Converters.Add(new ColorJsonConverter()); Converters.Add(new TextureRegion2DJsonConverter(textureRegionService)); Converters.Add(new ProfileJsonConverter()); Converters.Add(new ModifierJsonConverter()); Converters.Add(new InterpolatorJsonConverter()); Converters.Add(new TimeSpanJsonConverter()); Converters.Add(new RangeJsonConverter<int>()); Converters.Add(new RangeJsonConverter<float>()); Converters.Add(new RangeJsonConverter<HslColor>()); Converters.Add(new HslColorJsonConverter()); Converters.Add(new ModifierExecutionStrategyJsonConverter()); ContractResolver = new ShortNameJsonContractResolver(); NullValueHandling = nullValueHandling; Formatting = Formatting.Indented; } } }
using Ef6_QuerySpeedTest.Models; using System.Data.Entity.ModelConfiguration; namespace Ef6_QuerySpeedTest.Configurations { internal class OrderConfiguration : EntityTypeConfiguration<Order> { public OrderConfiguration() { ToTable("Bestellungen"); HasKey(o => o.Id); Property(o => o.Id).HasColumnName("BNR"); Property(o => o.CustomerId) .HasColumnName("KDNR"); Property(o => o.OrderDate) .HasColumnName("BestellDatum") .HasColumnType("date") .IsRequired(); Property(o => o.Freight) .HasColumnName("Lieferkosten") .IsRequired(); HasMany(o => o.OrderDetails) .WithRequired(od => od.Order) .HasForeignKey(od => od.OrderId); } } }
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace TQVaultAE.Domain.Entities { /// <summary> /// Item requierement info /// </summary> public class RequirementInfo { public Item Item; public int? Lvl; public int? Str; public int? Dex; public int? Int; } }
using System; using FunctionCore.Helpers; using Microsoft.WindowsAzure.Storage.Table; namespace FunctionCore { public class ContactInfo : TableEntity { public ContactInfo() { Id = Guid.NewGuid().ToString("n"); CreatedTime = DateTime.UtcNow; PartitionKey = Settings.PARTITIONKEY; RowKey = Settings.ROWKEY; } public string Id {get;set;} public DateTime CreatedTime{get;set;} public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDay { get; set; } public string Number { get; set; } } public class ContactInfoUpdateDTO { public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDay { get; set; } public string Number { get; set; } } public class ContactInfoDTO { public string Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Number { get; set; } } }
using System; using System.Collections.Concurrent; using DryIoc; using Microsoft.Extensions.Options; namespace OmniSharp.Extensions.LanguageServer.Client { public class LanguageClientResolver : IDisposable { private readonly IOptionsMonitor<LanguageClientOptions> _monitor; private readonly IServiceProvider? _outerServiceProvider; private readonly ConcurrentDictionary<string, LanguageClient> _clients = new ConcurrentDictionary<string, LanguageClient>(); public LanguageClientResolver(IOptionsMonitor<LanguageClientOptions> monitor, IServiceProvider? outerServiceProvider) { _monitor = monitor; _outerServiceProvider = outerServiceProvider; } public LanguageClient Get(string name) { if (_clients.TryGetValue(name, out var client)) return client; var options = name == Options.DefaultName ? _monitor.CurrentValue : _monitor.Get(name); var container = LanguageClient.CreateContainer(options, _outerServiceProvider); client = container.Resolve<LanguageClient>(); _clients.TryAdd(name, client); return client; } public void Dispose() { foreach (var item in _clients.Values) item.Dispose(); } } }
using System; using System.Threading; using System.Threading.Tasks; using Xamarin.Media; using MCCForms.iOS; [assembly: Xamarin.Forms.Dependency (typeof (MediaPicker_iOS))] //How to use in Forms project: DependencyService.Get<IMediaPicker> ().GetPathToPictureFromCamera(); namespace MCCForms.iOS { public class MediaPicker_iOS : IMediaPicker { MediaPicker _mediaPicker; public MediaPicker_iOS() { _mediaPicker = new MediaPicker (); } public async Task<string> GetPathToPictureFromCamera() { return await MediaPickerHelper.PathToPictureFromCamera (_mediaPicker); } public async Task<string> GetPathToPictureFromGallery() { return await MediaPickerHelper.PathToPictureFromGallery (_mediaPicker); } public async Task<string> GetPathToVideoFromCamera() { return await MediaPickerHelper.PathToVideoFromCamera (_mediaPicker); } public async Task<string> PathToVideoFromGallery () { return await MediaPickerHelper.PathToVideoFromGallery (_mediaPicker); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin; using Owin; using EntitySetupApp.Data; using EntitySetupApp.Models; namespace EntitySetupApp { public class IdentityConfig { public void Configuration(IAppBuilder app) { string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DevBuildMovieDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; app.CreatePerOwinContext(() => new AppUserDbContext(connectionString)); //app.CreatePerOwinContext(() => new Models. DevBuildMovieDB1()); app.CreatePerOwinContext<UserStore<AppUser>>((options, context) => new UserStore<AppUser>(context.Get<AppUserDbContext>())); app.CreatePerOwinContext<UserManager<AppUser>>((options, context) => new UserManager<AppUser>(context.Get<UserStore<AppUser>>())); //app.CreatePerOwinContext<RoleManager<AppRole>>(AppRole.Create); app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) => new RoleManager<AppRole>( new RoleStore<AppRole>(context.Get<AppUserDbContext>()))); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Identity/Login"), //LoginPath = new Microsoft.Owin.PathString(), }); } } }
using BookStore.Model; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using BookStore; namespace BookStore.DAL { public class BookDAL { SqlDbHelper db = new SqlDbHelper(); /// <summary> /// 添加图书 /// </summary> /// <param name="book"></param> /// <returns></returns> public int AddBook(Book book) { //sql语句 String sql = "INSERT INTO books(id,name,author,price,store) VALUES(@id,@name,@author,@price,@store)"; //参数列表 MySqlParameter[] param = { new MySqlParameter("@id",MySqlDbType.Int32), new MySqlParameter("@name",MySqlDbType.VarChar), new MySqlParameter("@author",MySqlDbType.VarChar), new MySqlParameter("@price",MySqlDbType.Double), new MySqlParameter("@store",MySqlDbType.Int32), }; //参数赋值 param[0].Value = book.Id; param[1].Value = book.Name; param[2].Value = book.Author; param[3].Value = book.Price; param[4].Value = book.store; return db.ExecuteNonQuery(sql, param); } public int BookDeleteByinformation(int id, string name, string cbs, decimal prices, int store) { int count = 0; //DELETE FROM books WHERE NAME = '男人来自火星女人来自金星'; string sql = "DELETE FROM books WHERE id = @id"; MySqlParameter[] param = { new MySqlParameter("@id",MySqlDbType.Int32) }; param[0].Value = id; count = db.ExecuteNonQuery(sql, param); return count; } public int UpdateBook(Book book) { //1.sql语句 string sql = "UPDATE books SET Name=@name,Author=@author,Price=@price WHERE Id=@Id"; MySqlParameter[] param = { new MySqlParameter("@name",MySqlDbType.VarChar), new MySqlParameter("@author",MySqlDbType.VarChar), new MySqlParameter("@price",MySqlDbType.Decimal), new MySqlParameter("@Id",MySqlDbType.Int32) }; param[0].Value = book.Name; param[1].Value = book.Author; param[2].Value = book.Price; param[3].Value = book.Id; return db.ExecuteNonQuery(sql, param); } public List<Book> GetAllBooks() { //1 sql语句 string sql = "SELECT * FROM books "; //2 执行 DataTable dt = db.ExecuteDataTable(sql); //3 关系--》对象 List<Book> books = new List<Book>(); foreach (DataRow dr in dt.Rows) { //行转化成对象 Book book = DataRowToBook(dr); books.Add(book); } return books; } public List<Book> SelectBooks(string name) { //1 sql语句 string sql = "SELECT * FROM books WHERE name = @name"; //2 执行 MySqlParameter[] param = { new MySqlParameter("@name",MySqlDbType.VarChar) }; param[0].Value = name; DataTable dt = db.ExecuteDataTable(sql,param); //3 关系--》对象 List<Book> books = new List<Book>(); foreach (DataRow dr in dt.Rows) { //行转化成对象 Book book = DataRowToBook(dr); books.Add(book); } return books; } private Book DataRowToBook(DataRow dr) { Book book = new Book(); book.Id = Convert.ToInt32(dr["id"]); book.Name = Convert.ToString(dr["Name"]); book.Author= Convert.ToString(dr["Author"]); book.Price= Convert.ToDouble(dr["Price"]); book.store = Convert.ToInt32(dr["store"]); return book; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelManagerProto : MonoBehaviour { private List<Scene> sceneList; private void Start() { for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++) { // sceneList.Add(SceneManager.GetSceneByBuildIndex(i)); } Debug.Log(sceneList); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace GetLabourManager.Models { public class CostSheet { public int Id { get; set; } public DateTime DatePrepared { get; set; } public string CostSheetNumber { get; set; } public int RequestHeader { get; set; } public int PreparedBy { get; set; } public string Note { get; set; } public string Status { get; set; } public int Client { get; set; } public double HoursWorked { get; set; } public double OvertimeHours { get; set; } public List<CostSheetItems> SheetItems { get; set; } } }
using UnityEngine; using System.Collections; public class Shop : MonoBehaviour { Renderer _renderer; void Start () { _renderer = GetComponent<Renderer> (); } void OnMouseEnter(){ PlayerUIManager._Aim = true; } void OnMouseExit(){ PlayerUIManager._Aim = false; } void Update () { } }
using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace NameSearch.Utility.Interfaces { /// <summary> /// Interface for Export Utility /// </summary> public interface IExport { /// <summary> /// To the CSV. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="records">The records.</param> /// <param name="fullPath">The full path.</param> /// <param name="isAppend">if set to <c>true</c> [is append].</param> void ToCsv<T>(IEnumerable<T> records, string fullPath, bool isAppend); /// <summary> /// To the json. /// </summary> /// <param name="json">The json.</param> /// <param name="fullPath">The full path.</param> void ToJson(JObject json, string fullPath); /// <summary> /// To the json asynchronous. /// </summary> /// <param name="json">The json.</param> /// <param name="fullPath">The full path.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> Task ToJsonAsync(JObject json, string fullPath, CancellationToken cancellationToken); /// <summary> /// To the txt. /// </summary> /// <param name="text">The text.</param> /// <param name="fullPath">The full path.</param> void ToTxt(string text, string fullPath); /// <summary> /// To the txt asynchronous. /// </summary> /// <param name="text">The text.</param> /// <param name="fullPath">The full path.</param> /// <returns></returns> Task ToTxtAsync(string text, string fullPath); } }
using Liddup.Models; using Liddup.Services; using Plugin.MediaManager; using Plugin.MediaManager.Abstractions.Enums; using Plugin.MediaManager.Abstractions.Implementations; using PropertyChanged; using System; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; namespace Liddup.PageModels { [AddINotifyPropertyChangedInterface] public class MasterPlaylistPageModel : AppContainerPageModel { public ObservableCollection<Song> Songs { get; private set; } = new ObservableCollection<Song>(); public Song CurrentSong { get; private set; } public string CurrentPlayIcon { get; private set; } = "resource://Liddup.Resources.play_button.svg"; public int Ticks { get; set; } ICommand _navigateToHomePageCommand; public ICommand NavigateToHomePageCommand => _navigateToHomePageCommand ?? (_navigateToHomePageCommand = new Command(() => NavigateToHomePage())); ICommand _navigateToAddSongsPageCommand; public ICommand NavigateToAddSongsPageCommand => _navigateToAddSongsPageCommand ?? (_navigateToAddSongsPageCommand = new Command(() => NavigateToAddSongsPage())); ICommand _toggleRepeatSongVoteCommand; public ICommand ToggleRepeatSongVoteCommand => _toggleRepeatSongVoteCommand ?? (_toggleRepeatSongVoteCommand = new Command(() => ToggleRepeatSongVote())); ICommand _playPauseSongCommand; public ICommand PlayPauseSongCommand => _playPauseSongCommand ?? (_playPauseSongCommand = new Command(async () => await PlayPauseSong())); ICommand _toggleSkipSongVoteCommand; public ICommand ToggleSkipSongVoteCommand => _toggleSkipSongVoteCommand ?? (_toggleSkipSongVoteCommand = new Command(() => ToggleSkipSongVote())); public MasterPlaylistPageModel() { DatabaseManager.Host = DependencyService.Get<INetworkManager>().GetDecryptedIPAddress(Room.Code); DatabaseManager.StartListener(); StartReplications(); if (!User.IsHost) Songs = new ObservableCollection<Song>(DatabaseManager.GetSongs().OrderByDescending(s => s.Votes)); MessagingCenter.Subscribe<Song, Song>(this, "AddSong", AddSong); MessagingCenter.Subscribe<Song, Song>(this, "UpdateSong", UpdateSong); } private void ToggleSkipSongVote() { if (CurrentSong == null) return; CurrentSong.IsSkipVoted = !CurrentSong.IsSkipVoted; if (CurrentSong.IsRepeatVoted) { CurrentSong.IsRepeatVoted = false; CurrentSong.RepeatVotes--; } if (CurrentSong.IsSkipVoted) CurrentSong.SkipVotes++; else CurrentSong.SkipVotes--; } private async Task PlayPauseSong() { if (CurrentSong == null) return; CurrentSong.IsPlaying = !CurrentSong.IsPlaying; if (CurrentSong.IsPlaying) { CurrentPlayIcon = "resource://Liddup.Resources.pause_button.svg"; Device.StartTimer(TimeSpan.FromSeconds(1), () => { if (CurrentSong == null) return false; Ticks++; if (Ticks == CurrentSong.DurationInSeconds) PlayNextSong(); return Ticks <= CurrentSong.DurationInSeconds && CurrentSong.IsPlaying; }); await PlaySong(); } else { CurrentPlayIcon = "resource://Liddup.Resources.play_button.svg"; await PauseSong(); } } private async void PlayNextSong() { CurrentSong.IsPlaying = false; await PauseSong(); DatabaseManager.DeleteSong(CurrentSong); if (Songs.FirstOrDefault() == null) return; CurrentSong = Songs.FirstOrDefault(); Ticks = 0; CurrentSong.IsPlaying = true; Songs.RemoveAt(Songs.Count - 1); await PlaySong(); } private void ToggleRepeatSongVote() { if (CurrentSong == null) return; CurrentSong.IsRepeatVoted = !CurrentSong.IsRepeatVoted; if (CurrentSong.IsSkipVoted) { CurrentSong.IsSkipVoted = false; CurrentSong.SkipVotes--; } if (CurrentSong.IsRepeatVoted) CurrentSong.RepeatVotes++; else CurrentSong.RepeatVotes--; } private void NavigateToHomePage() { MessagingCenter.Send(this as FreshMvvm.FreshBasePageModel, "PositionChanged", 0); } private void NavigateToAddSongsPage() { MessagingCenter.Send(this as FreshMvvm.FreshBasePageModel, "PositionChanged", 2); } private async Task PlaySong() { switch (CurrentSong.Source) { case "Spotify": SpotifyApiManager.PlayTrack(CurrentSong.Uri); break; case "Library": var mediaFile = new MediaFile { Url = "file://" + CurrentSong.Uri, Metadata = new MediaFileMetadata { AlbumArt = CurrentSong.ImageUrl }, Type = MediaFileType.Audio, Availability = ResourceAvailability.Local }; await CrossMediaManager.Current.Play(mediaFile); break; default: break; } } private async Task PauseSong() { if (CurrentSong.Source.Equals("Spotify")) SpotifyApiManager.PauseTrack(); else if (CurrentSong.Source.Equals("Library")) await CrossMediaManager.Current.Pause(); } private async Task ResumeSong() { if (CurrentSong.Source.Equals("Spotify")) SpotifyApiManager.ResumeTrack(); else if (CurrentSong.Source.Equals("Library")) await CrossMediaManager.Current.Play(); } private void UpdateSong(object sender, Song song) { DatabaseManager.SaveSong(song); } private void StartReplications() { DatabaseManager.StartReplications(async (sender, e) => { var changes = e.Changes.ToList(); foreach (var change in changes) { if (change.IsDeletion) continue; if (Songs.Count == 0 && CurrentSong != null) continue; var song = DatabaseManager.GetSong(change.DocumentId); var indexOfExistingSong = Songs.IndexOf(Songs.FirstOrDefault(s => s.Id == song.Id)); if (indexOfExistingSong < 0) { if (song.Source.Equals("Library")) { song.Contents = DatabaseManager.GetSongContents(song); song.Uri = await FileSystemManager.WriteFileAsync(song.Contents, song.Id); } if (song.Id != CurrentSong.Id) Songs.Add(song); } else { Songs[indexOfExistingSong].Votes = song.Votes; Songs = new ObservableCollection<Song>(Songs.OrderByDescending(s => s.Votes)); } } }); } private void AddSong(object sender, Song song) { if (Songs?.FirstOrDefault(s => s.Uri.Equals(song.Uri)) != null) return; if (CurrentSong == null) CurrentSong = song; else Songs.Add(song); DatabaseManager.SaveSong(song); } } }
using System.Runtime.Serialization; namespace Azure.CosmosDB.Net.AzureDataFactory.Interfaces { public interface ISqlDataFactoryInitialize : IFactoryBaseInitialize { [DataMember]string AzureDbConnectionString { get; } [DataMember]string AzureDbTableName { get; } [DataMember]string AzureDbDataSetName { get; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using DesiClothing4u.Common.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using System.Net.Http.Headers; using System.Net.Http; namespace DesiClothing4u.UI.Controllers { public class CartsController : Controller { // GET: CartsController public ActionResult Index() { return View(); } //Added by SM on Nov 25, 2020 for cart public ActionResult AddCart(int Id, string Name, decimal Price) { Cart cart = new Cart { Id = Id, Name = Name, Price = Price }; if (HttpContext.Session.GetString("cart") == null) { List<Cart> li = new List<Cart>(); li.Add(cart); HttpContext.Session.SetString("cart", JsonConvert.SerializeObject(li)); ViewBag.cartcount = li.Count(); HttpContext.Session.SetInt32("count", 1); ViewBag.cart = cart; return View("MyCart", (List<Cart>)li); } else //not empty { var value = HttpContext.Session.GetString("cart"); List<Cart> li = JsonConvert.DeserializeObject<List<Cart>>(value); li.Add(cart); HttpContext.Session.SetString("cart", JsonConvert.SerializeObject(li)); HttpContext.Session.SetInt32("count", li.Count()); var a = HttpContext.Session.GetInt32("count"); return View("MyCart", li); } } // GET: Carts/MyCart public async Task<ActionResult> MyCart(string CustId) { if (HttpContext.Session.GetString("cart") != null) { var value = HttpContext.Session.GetString("cart"); List<Cart> li = JsonConvert.DeserializeObject<List<Cart>>(value); return View("MyCart", li); } if (CustId != null) { //if session["cart"] is empty Cart cart = new Cart(); var client = new HttpClient(); client.DefaultRequestHeaders.Clear(); //Define request data format client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Sending request to find web api REST service resource DeleteCart using HttpClient UriBuilder builder = new UriBuilder("https://localhost:44363/api/Carts/GetCartofBuyer?"); /*UriBuilder builder = new UriBuilder("https://localhost:44356/api/Carts/GetCartofBuyer?");*/ builder.Query = "CustId=" + CustId; HttpResponseMessage Res = await client.GetAsync(builder.Uri); if (Res.IsSuccessStatusCode) { var cart1 = Res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the cart list Cart[] c = JsonConvert.DeserializeObject<Cart[]>(cart1); ViewBag.Cart = c; if (HttpContext.Session.GetString("cart") != null) { var value = HttpContext.Session.GetString("cart"); List<Cart> li = JsonConvert.DeserializeObject<List<Cart>>(value); return View("MyCart", li); } else { List<Cart> li = new List<Cart>(c); HttpContext.Session.SetString("cart", JsonConvert.SerializeObject(li)); return View("MyCart", li); } }//if not successful else { Error err = new Error(); err.ErrorMessage = "Sorry there are no items in your cart " + CustId; ViewBag.Error = err; ViewBag.Cart = null; return View("Error", err); } } else //if customer not logged in { Error err = new Error(); err.ErrorMessage = "Sorry there are no items in your cart "; ViewBag.Error = err; ViewBag.Cart = null; return View("Error", err); } } // GET: CartsController/Details/5 public ActionResult Details(int id) { return View(); } // GET: CartsController/Create public ActionResult Create() { return View(); } // POST: CartsController/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: CartsController/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: CartsController/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: CartsController/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: CartsController/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } public async Task<ActionResult> CheckOut(string CustId) { if (HttpContext.Session.GetString("cart") != null) { var value = HttpContext.Session.GetString("cart"); List<Cart> li = JsonConvert.DeserializeObject<List<Cart>>(value); return View("checkout", li); } if (CustId != null) { //if session["cart"] is empty Cart cart = new Cart(); var client = new HttpClient(); client.DefaultRequestHeaders.Clear(); //Define request data format client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Sending request to find web api REST service resource DeleteCart using HttpClient UriBuilder builder = new UriBuilder("https://localhost:44363/api/Carts/GetCartofBuyer?"); /*UriBuilder builder = new UriBuilder("https://localhost:44356/api/Carts/GetCartofBuyer?");*/ builder.Query = "CustId=" + CustId; HttpResponseMessage Res = await client.GetAsync(builder.Uri); if (Res.IsSuccessStatusCode) { var cart1 = Res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the cart list Cart[] c = JsonConvert.DeserializeObject<Cart[]>(cart1); ViewBag.Cart = c; if (HttpContext.Session.GetString("cart") != null) { var value = HttpContext.Session.GetString("cart"); List<Cart> li = JsonConvert.DeserializeObject<List<Cart>>(value); return View("checkout", li); } else { List<Cart> li = new List<Cart>(c); HttpContext.Session.SetString("cart", JsonConvert.SerializeObject(li)); return View("checkout", li); } }//if not successful else { Error err = new Error(); err.ErrorMessage = "Sorry there are no items in your cart " + CustId; ViewBag.Error = err; ViewBag.Cart = null; return View("Error", err); } } else //if customer not logged in { Error err = new Error(); err.ErrorMessage = "Sorry there are no items in your cart "; ViewBag.Error = err; ViewBag.Cart = null; return View("Error", err); } /* return View("checkout");*/ } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SpawnManager : MonoBehaviour { [SerializeField] private GameObject _basicEnemyPrefab; [SerializeField] private GameObject _missileLauncherEnemyPrefab; [SerializeField] private GameObject _hammerheadEnemyPrefab; [SerializeField] private GameObject _stealthEnemyPrefab; [SerializeField] private GameObject _dodgerEnemyPrefab; [SerializeField] private GameObject _bossEnemyPrefab; [SerializeField] private GameObject[] _powerups; [SerializeField] private GameObject _enemyContainer; [SerializeField] private float spawnRate; [SerializeField] private GameObject _newWaveText; [SerializeField] private Text _newWaveCountdownText; [SerializeField] private GameObject _newWaveCountdownObject; private UIManager _uiManager; private int _basicEnemiesSpawnCount = 5; //The first wave starts with 5 enemies. private int _missileEnemiesSpawnCount = 1; private int _dodgerEnemiesSpawnCount = 2; private int _hammerheadEnemiesSpawnCount = 1; private int _stealthEnemiesSpawnCount = 1; private bool _stopSpawning = false; [SerializeField] private int _waveNumber = 1; private bool _spawnedMissileEnemies = false; private bool _spawnedHammerheadEnemies = false; private bool _spawnedStealthEnemies = false; private bool _spawnedDodgerEnemies = false; private bool _isFighitngBoss = false; private int _randomPowerup; private int randomPowerupID; private void Start() { _uiManager = GameObject.Find("Canvas").GetComponent<UIManager>(); } public void StartSpawning() //Called when you shoot the asteroid, or when you start a new wave. { StartCoroutine(SpawnBasicEnemyRoutine()); StartCoroutine(SpawnPowerupRoutine()); StartCoroutine(NewWaveManager()); if (_waveNumber > 5 && !_spawnedMissileEnemies) { int random = Random.Range(0, 2); if (random == 1) { _spawnedMissileEnemies = true; StartCoroutine(SpawnMissileEnemyRoutine()); } } if (_waveNumber > 3 && !_spawnedHammerheadEnemies) { int random = Random.Range(0, 2); if (random == 1) { _spawnedHammerheadEnemies = true; StartCoroutine(SpawnHammerheadEnemyRoutine()); } } if (_waveNumber > 4 && !_spawnedStealthEnemies) { int random = Random.Range(0, 2); if (random == 1) { _spawnedStealthEnemies = true; StartCoroutine(SpawnStealthEnemyRoutine()); } } if (_waveNumber > 2 && !_spawnedDodgerEnemies) { int random = Random.Range(0, 2); if (random == 1) { _spawnedDodgerEnemies = true; StartCoroutine(SpawnDodgerEnemyRoutine()); } } if (_waveNumber == 5 || _waveNumber == 10) { _isFighitngBoss = true; } } public IEnumerator SpawnPowerupRoutine() { yield return new WaitForSeconds(3.0f); while (!_stopSpawning) { _randomPowerup = Random.Range(1, 101); switch (_randomPowerup) { case int n when (n <= 60): commonPowerupUpSpawn(); break; case int n when (n >= 61 && n <= 90): uncommonPowerupUpSpawn(); break; case int n when (n >= 91 && n <= 100): rarePowerupUpSpawn(); break; } Vector3 posToSpawn = new Vector3(Random.Range(-8f, 8f), 8, 0); //Creates/Declares the Vector3 "posToSpawn". Instantiate(_powerups[randomPowerupID], posToSpawn, Quaternion.identity); yield return new WaitForSeconds(Random.Range(3, 8)); } } private void commonPowerupUpSpawn() //60% Chance To Spawn { randomPowerupID = Random.Range(0, 2); } private void uncommonPowerupUpSpawn() //30% Chance To Spawn { randomPowerupID = Random.Range(3, 5); } private void rarePowerupUpSpawn() //10% Chance To Spawn { randomPowerupID = Random.Range(6, 8); } public IEnumerator SpawnBasicEnemyRoutine() { yield return new WaitForSeconds(2.0f); //Gives an inital delay before spawning waves. while (!_stopSpawning) { for (int i = 0; i < _basicEnemiesSpawnCount; i++) { Vector3 posToSpawn = new Vector3(Random.Range(-8f, 8f), 8, 0); GameObject newEnemy = Instantiate(_basicEnemyPrefab, posToSpawn, Quaternion.identity); newEnemy.transform.parent = _enemyContainer.transform; yield return new WaitForSeconds(spawnRate); } _basicEnemiesSpawnCount += 2; break; } } public IEnumerator SpawnMissileEnemyRoutine() { yield return new WaitForSeconds(2.0f); //Gives an inital delay before spawning waves. while (!_stopSpawning) { for (int i = 0; i < _missileEnemiesSpawnCount; i++) { float randomY = Random.Range(1.5f, 5.5f); Vector3 posToSpawn = new Vector3(-11, randomY, 0); GameObject newEnemy = Instantiate(_missileLauncherEnemyPrefab, posToSpawn, Quaternion.identity); newEnemy.transform.parent = _enemyContainer.transform; yield return new WaitForSeconds(spawnRate); } _missileEnemiesSpawnCount++; break; } } public IEnumerator SpawnHammerheadEnemyRoutine() { yield return new WaitForSeconds(2.0f); //Gives an inital delay before spawning waves. while (!_stopSpawning) { for (int i = 0; i < _hammerheadEnemiesSpawnCount; i++) { Vector3 posToSpawn = new Vector3(Random.Range(-8f, 8f), 8, 0); GameObject newEnemy = Instantiate(_hammerheadEnemyPrefab, posToSpawn, Quaternion.identity); newEnemy.transform.parent = _enemyContainer.transform; yield return new WaitForSeconds(spawnRate); } _hammerheadEnemiesSpawnCount++; break; } } public IEnumerator SpawnStealthEnemyRoutine() { yield return new WaitForSeconds(2.0f); //Gives an inital delay before spawning waves. while (!_stopSpawning) { for (int i = 0; i < _stealthEnemiesSpawnCount; i++) { Vector3 posToSpawn = new Vector3(Random.Range(-8f, 8f), 8, 0); GameObject newEnemy = Instantiate(_stealthEnemyPrefab, posToSpawn, Quaternion.identity); newEnemy.transform.parent = _enemyContainer.transform; yield return new WaitForSeconds(spawnRate); } _stealthEnemiesSpawnCount++; break; } } public IEnumerator SpawnDodgerEnemyRoutine() { yield return new WaitForSeconds(2.0f); //Gives an inital delay before spawning waves. while (!_stopSpawning) { for (int i = 0; i < _dodgerEnemiesSpawnCount; i++) { Vector3 posToSpawn = new Vector3(Random.Range(-8f, 8f), 8, 0); GameObject newEnemy = Instantiate(_dodgerEnemyPrefab, posToSpawn, Quaternion.identity); newEnemy.transform.parent = _enemyContainer.transform; yield return new WaitForSeconds(spawnRate); } _dodgerEnemiesSpawnCount++; break; } } private void SpawnBoss() { Vector3 posToSpawn = new Vector3(0, 8.5f, 0); GameObject newEnemy = Instantiate(_bossEnemyPrefab, posToSpawn, Quaternion.identity); newEnemy.transform.parent = _enemyContainer.transform; _isFighitngBoss = false; StartCoroutine(NewWaveManager()); } private IEnumerator NewWaveManager() { yield return new WaitForSeconds(6f); while (_enemyContainer.transform.childCount > 0) //Continues checking for the enemies to all be dead before starting the next wave. { yield return new WaitForSeconds(.1f); } if (!_isFighitngBoss) { _stopSpawning = true; StartCoroutine(StartNewWave()); } else { SpawnBoss(); } } private IEnumerator StartNewWave() { _waveNumber++; _uiManager.UpdateWaveCount(_waveNumber); int waitTime = 4; for (int i = 0; i < waitTime; i++) { switch (i) { case 0: StartCoroutine(TextFlicker()); break; case 1: _newWaveCountdownText.text = "3"; _newWaveCountdownObject.SetActive(true); break; case 2: _newWaveCountdownText.text = "2"; break; case 3: _newWaveCountdownText.text = "1"; break; default: break; } yield return new WaitForSeconds(1.0f); } _newWaveCountdownObject.SetActive(false); _stopSpawning = false; _spawnedMissileEnemies = false; _spawnedHammerheadEnemies = false; StartSpawning(); } private IEnumerator TextFlicker() { for (int i = 0; i < 5; i++) { yield return new WaitForSeconds(.25f); _newWaveText.SetActive(false); yield return new WaitForSeconds(.25f); _newWaveText.SetActive(true); yield return new WaitForSeconds(.25f); _newWaveText.SetActive(false); yield return new WaitForSeconds(.25f); } } public void OnPlayerDeath() { _stopSpawning = true; } }
using System.Windows.Input; using Xamarin.Forms; namespace MCCForms { public class AppResetViewModel { public ICommand OpenPincodePageCommand { get { return new Command (() => OpenPincodePage ()); } } public int MaxNumberOfLoginAttempts { get { return AppConfigConstants.NumberOfLoginAttemptsBeforeAppWillBeReset; } } public AppResetViewModel () { } void OpenPincodePage() { App.Current.MainPage = new PincodePage (PincodePageType.NewPincode); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using OCodigoData; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace OCodigoWebApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { /* */ //Com Cache services.AddScoped<IDataAccess, CachedDataAccess>(); services.AddScoped<DataAccess>(); /* //Sem Cache services.AddScoped<IDataAccess, DataAccess>(); */ services.AddScoped<ConnectionManager>(); services.AddTransient<IDbConnection>(it => new SqlConnection(this.Configuration.GetConnectionString("sgdb"))); var redisConfiguration = new StackExchange.Redis.Extensions.Core.Configuration.RedisConfiguration(); Configuration.Bind("Data:Redis", redisConfiguration); services.AddStackExchangeRedisExtensions<StackExchange.Redis.Extensions.Newtonsoft.NewtonsoftSerializer>(redisConfiguration); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using System; using System.Text; using System.Text.RegularExpressions; using System.Threading; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LoadPage { [TestClass] public class LoadPage { static IWebDriver driver; [AssemblyInitialize] public static void Setup(TestContext Context) { driver = new FirefoxDriver(); } [TestMethod] public void THome() { driver.Navigate().GoToUrl("http://juntoz.com"); } } }
using Newtonsoft.Json; using System; /// <summary> /// Scribble.rs ♯ JSON converters namespace /// </summary> namespace ScribblersSharp.JSONConverters { /// <summary> /// A class used for convert characters to JSON and vice versa /// </summary> internal class CharacterJSONConverter : JsonConverter<char> { /// <summary> /// Reads JSON /// </summary> /// <param name="reader">JSON reader</param> /// <param name="objectType">Object type</param> /// <param name="existingValue">Existing value</param> /// <param name="hasExistingValue">Has existing value</param> /// <param name="serializer">JSON serializer</param> /// <returns>Character</returns> public override char ReadJson(JsonReader reader, Type objectType, char existingValue, bool hasExistingValue, JsonSerializer serializer) { char ret = existingValue; if (reader.Value is long value) { ret = (char)value; } return ret; } /// <summary> /// Writes JSON /// </summary> /// <param name="writer">JSON writer</param> /// <param name="value">Character value</param> /// <param name="serializer">JSON serializer</param> public override void WriteJson(JsonWriter writer, char value, JsonSerializer serializer) => writer.WriteValue((long)value); } }
using System.Collections.Generic; namespace TNBase.Objects { public static class ListenerTitles { public const string MR = "Mr."; public const string MS = "Ms."; public const string MRS = "Mrs."; public const string MISS = "Miss"; public const string SIR = "Sir"; public const string DOCTOR = "Doctor"; public const string MASTER = "Master"; public const string PROFESSOR = "Professor"; public const string REV = "Rev."; public const string LADY = "Lady"; public const string LORD = "Lord"; public static List<string> GetAllTitles() { return new List<string>() { MR, MS, MRS, MISS, SIR, DOCTOR, MASTER, PROFESSOR, REV, LADY, LORD }; } } }
 #region Usings using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Zengo.WP8.FAS.Controls; using System.Windows.Controls.Primitives; using System.ComponentModel; using Zengo.WP8.FAS.Helpers; using Zengo.WP8.FAS.Resources; #endregion namespace Zengo.WP8.FAS { public partial class RegisterPage : PhoneApplicationPage { #region Fields ApplicationBarIconButton registerButton; #endregion #region Constructors public RegisterPage() { InitializeComponent(); // Register for the control events that tell us the team selector button has been pressed RegisterControl.FirstFavouriteTeamPressed += RegisterControl_FirstFavouriteTeamPressed; RegisterControl.SecondFavouriteTeamPressed += RegisterControl_SecondFavouriteTeamPressed; RegisterControl.MyCountryPressed += RegisterControl_MyCountryPressed; RegisterControl.RegisterStarting += RegisterControl_RegisterStarting; RegisterControl.RegisterCompleted += RegisterControl_RegisterCompleted; PageHeaderControl.PageName = AppResources.RegistrationPage; PageHeaderControl.PageTitle = AppResources.ProductTitle; RegisterControl.Page = this; BuildApplicationBar(); // Get our register button so we can enable/disable it registerButton = (ApplicationBarIconButton)ApplicationBar.Buttons[0]; } private void BuildApplicationBar() { ApplicationBar = new ApplicationBar(); var button = new ApplicationBarIconButton(new Uri("/Images/AppBar/check.png", UriKind.RelativeOrAbsolute)) { Text = AppResources.AppBarRegister }; button.Click += AppBarMenuRegister_Click; ApplicationBar.Buttons.Add(button); } #endregion #region Page Event Handlers /// <summary> /// This also gets run when we navigate back from the clubs list and countries list /// </summary> protected override void OnNavigatedTo( NavigationEventArgs e) { // Fill in the hidden textbox in case they have changed favourite team RegisterControl.SetTeamsAndCountry(App.AppConstants.FirstFavTeam, App.AppConstants.SecondFavTeam, App.AppConstants.MyCountry); RegisterControl.ResetErrors(); } #endregion #region Event Handlers /// <summary> /// They have pressed the button to select a first favourite team /// </summary> void RegisterControl_FirstFavouriteTeamPressed(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Views/FavouriteClubPage.xaml?Team=1", UriKind.Relative)); } /// <summary> /// They have pressed the button to select a second favourite team /// </summary> void RegisterControl_SecondFavouriteTeamPressed(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Views/FavouriteClubPage.xaml?Team=2", UriKind.Relative)); } void RegisterControl_MyCountryPressed(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Views/MyCountryPage.xaml", UriKind.Relative)); } void RegisterControl_RegisterStarting(object sender, EventArgs e) { // Disable the button registerButton.IsEnabled = false; // Get rid of the keyboard this.Focus(); // turn on the progress bar SetProgressIndicator(true); } void RegisterControl_RegisterCompleted(object sender, RegisterControl.RegisterCompletedEventArgs e) { // turn off the progress bar SetProgressIndicator(false); // turn back on the button registerButton.IsEnabled = true; if (e.Success) { // show a success message MessageBox.Show("Registration complete! Don't forget to click on the link emailed to you to activate your account.", "Registration Success", MessageBoxButton.OK); //The new flow wants us to go to the shop page with instructions to remove the settings page from the back stack this.NavigationService.Navigate(new Uri("/Views/BuyVotesAfterRegistrationPage.xaml?removeBackStack=yes", UriKind.Relative)); } else { // Show a message MessageBox.Show(e.Message, "Registration Failed", MessageBoxButton.OK); } } #endregion #region App Bar Events private void AppBarMenuRegister_Click(object sender, EventArgs e) { RegisterControl.Register(RegisterScrollViewer); } #endregion #region Helpers void SetProgressIndicator(bool enabled) { ProgressIndicator progress = new ProgressIndicator { IsVisible = enabled, IsIndeterminate = true, Text = "Registering" }; SystemTray.SetProgressIndicator(this, progress); } #endregion } }
using Microsoft.Xna.Framework; using System; namespace GameLib { public struct Index3 { public readonly int X; public readonly int Y; public readonly int Z; public Index3(int x, int y, int z) { X = x; Y = y; Z = z; } public Index3(Index2 first, int z) { X = first.X; Y = first.Y; Z = z; } public Index3(Vector3 first) { X = (int)first.X; Y = (int)first.Y; Z = (int)first.Z; } public Index3 Abs() { return new Index3(Math.Abs(X), Math.Abs(Y), Math.Abs(Z)); } public Index2 ToIndex2() { return new Index2(X, Y); } public Vector3 ToVector3() { return new Vector3(X, Y, Z); } public static Index3 Zero => new Index3(0, 0, 0); public static Index3 One => new Index3(1, 1, 1); public static Index3 operator +(Index3 first, Index3 second) { return new Index3(first.X + second.X, first.Y + second.Y, first.Z + second.Z); } public static Index3 operator -(Index3 first, Index3 second) { return new Index3(first.X - second.X, first.Y - second.Y, first.Z - second.Z); } public static Index3 operator /(Index3 first, Index3 second) { return new Index3(first.X / second.X, first.Y / second.Y, first.Z / second.Z); } public static Index3 operator *(Index3 first, Index3 second) { return new Index3(first.X * second.X, first.Y * second.Y, first.Z * second.Z); } public static bool operator ==(Index3 first, Index3 second) { return first.X == second.X && first.Y == second.Y && first.Z == second.Z; } public static bool operator !=(Index3 first, Index3 second) { return first.X != second.X || first.Y != second.Y || first.Z != second.Z; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return X.GetHashCode() << Y.GetHashCode() << Z.GetHashCode(); } public override string ToString() { return "X: " + X + " Y: " + Y + " Z: " + Z; } } }
// ----------------------------------------------------------------------- // <copyright file="ContentTypeDetector.cs" company="Henric Jungheim"> // Copyright (c) 2012-2014. // <author>Henric Jungheim</author> // </copyright> // ----------------------------------------------------------------------- // Copyright (c) 2012-2014 Henric Jungheim <software@henric.org> // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using SM.Media.Web; namespace SM.Media.Content { public interface IContentTypeDetector { ICollection<ContentType> GetContentType(Uri url, HttpContentHeaders headers = null); } public class ContentTypeDetector : IContentTypeDetector { protected static readonly ContentType[] NoContent = new ContentType[0]; protected readonly ContentType[] ContentTypes; protected readonly ILookup<string, ContentType> ExtensionLookup; protected readonly ILookup<string, ContentType> MimeLookup; public ContentTypeDetector(IEnumerable<ContentType> contentTypes) { if (null == contentTypes) throw new ArgumentNullException("contentTypes"); ContentTypes = contentTypes.ToArray(); ExtensionLookup = ContentTypes .SelectMany(ct => ct.FileExts, (ct, ext) => new { ext, ContentType = ct }) .ToLookup(arg => arg.ext, x => x.ContentType, StringComparer.OrdinalIgnoreCase); var mimeTypes = ContentTypes .Select(ct => new { ct.MimeType, ContentType = ct }); var alternateMimeTypes = ContentTypes .Where(ct => null != ct.AlternateMimeTypes) .SelectMany(ct => ct.AlternateMimeTypes, (ct, mime) => new { MimeType = mime, ContentType = ct }); MimeLookup = alternateMimeTypes .Union(mimeTypes) .ToLookup(arg => arg.MimeType, x => x.ContentType, StringComparer.OrdinalIgnoreCase); } #region IContentTypeDetector Members public virtual ICollection<ContentType> GetContentType(Uri url, HttpContentHeaders headers = null) { var contentType = GetContentTypeByUrl(url); if (null != contentType && contentType.Any()) return contentType; if (null == headers) return NoContent; return GetContentTypeByContentHeaders(headers) ?? NoContent; } #endregion protected virtual ICollection<ContentType> GetContentTypeByUrl(Uri url) { var ext = url.GetExtension(); if (null == ext) return null; return ExtensionLookup[ext].ToArray(); } protected virtual ICollection<ContentType> GetContentTypeByContentHeaders(HttpContentHeaders httpHeaders) { if (null == httpHeaders || null == httpHeaders.ContentType) return null; return MimeLookup[httpHeaders.ContentType.MediaType].ToArray(); } } }
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; using App1.ViewModels; namespace App1.Views { internal class TodoPage : ContentPage { private Label TitleLabel; private Entry NewTaskEntry; private Button AddTaskButton; private Button ClearTasksButton; private ListView TodoListView; private TodoViewModel ViewModel = new TodoViewModel(); public TodoPage() { TitleLabel = new Label { Text = "TODO list", Font = Font.SystemFontOfSize(NamedSize.Large), HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.Center }; NewTaskEntry = new Entry { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.Center }; // Add two-way binding to TodoViewModel.NewTaskDraft NewTaskEntry.SetBinding<TodoViewModel>(Entry.TextProperty, model => model.NewTaskDraft, BindingMode.TwoWay); AddTaskButton = new Button { Text = "Add", }; AddTaskButton.Clicked += (object target, EventArgs args) => { ViewModel.AddTask(); }; ClearTasksButton = new Button { Text = "Clear all tasks", Font = Font.SystemFontOfSize(NamedSize.Large) }; ClearTasksButton.Clicked += async (object target, EventArgs args) => { bool answer = await DisplayAlert("Warning", "This action will clear ALL tasks. Are you sure?", "Yes", "No"); if (answer) { ViewModel.ClearAllTasks(); } }; TodoListView = new ListView { RowHeight = 40, VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; // Add two-way binding to TodoViewModel.Tasks which is list of strings // Whole ListView can be also filled using ObservableCollection, but purpose of this demo is two-way data binding TodoListView.SetBinding<TodoViewModel>(ListView.ItemsSourceProperty, model => model.Tasks, BindingMode.OneWay); TodoListView.ItemTapped += async (object target, ItemTappedEventArgs args) => { bool answer = await DisplayAlert("Done", "Delete this task?", "Yes", "No"); if (answer) { ViewModel.DeleteTask((string)args.Item); } }; StackLayout layout = new StackLayout { Children = { TitleLabel, NewTaskEntry, AddTaskButton, TodoListView, ClearTasksButton }, // Set binding context for layout, also can be set for whole page BindingContext = ViewModel }; Padding = new Thickness(1, Device.OnPlatform(20, 0, 0), 1, 5); Content = layout; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.SceneManagement; [InitializeOnLoad] public class SceneHierarchyViewer { public static bool scenePreviewing = false; static SceneHierarchyViewer() { EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI; } static void HierarchyWindowItemOnGUI(int instanceID, Rect selectionRect) { if (!scenePreviewing) { return; } GameObject currentGameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject; if(currentGameObject != null) { if (currentGameObject.scene == SceneManager.GetActiveScene()) { return; } } else { return; } MakePreviewHierarchyObject(currentGameObject, selectionRect); } static void MakePreviewHierarchyObject(GameObject activeObject, Rect m_rect) { Rect textRect = new Rect(m_rect); textRect.x += textRect.width - 65; GUIStyle textStyle = new GUIStyle(); textStyle.fontStyle = FontStyle.Italic; textStyle.font = EditorStyles.boldFont; textStyle.richText = true; GUI.Label(textRect, "<color=cyan>PREVIEW</color>",textStyle); Texture2D backgroundTex = new Texture2D(1, 1, TextureFormat.RGBA32, false); backgroundTex.SetPixel(0, 0, new Color(0.4f, 0.4f, 0.5f,0.5f)); backgroundTex.Apply(); GUI.DrawTexture(m_rect, backgroundTex); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Script.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using sfShareLib; using sfAPIService.Models; using StackExchange.Redis; using sfAPIService.Filter; using System.Security.Claims; using System.Threading; using System.Text; using Swashbuckle.Swagger.Annotations; using CDSShareLib.Helper; namespace sfAPIService.Controllers { [Authorize] [CustomAuthorizationFilter(ClaimType = "Roles", ClaimValue = "external")] [RoutePrefix("cdstudio")] public class ExternalApiController : CDSApiController { /// <summary> /// Client_Id : External - OK /// </summary> [HttpGet] [Route("Company")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(CompanyModel.Format_DetailForExternal))] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetCompanyById() { int companyId = Global.GetCompanyIdFromToken(); RedisKey cacheKey = "external_company_" + companyId; string cacheValue = null;// RedisCacheHelper.GetValueByKey(cacheKey); if (cacheValue == null) { try { CompanyModel model = new CompanyModel(); //RedisCacheHelper.SetKeyValue(cacheKey, JsonConvert.SerializeObject(company)); return Content(HttpStatusCode.OK, model.GetCompanyByIdForExternal(UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } else { return Ok(new JavaScriptSerializer().Deserialize<Object>(cacheValue)); } } /// <summary> /// Client_Id : External - OK /// </summary> [HttpGet] [Route("Factory")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<FactoryModel.Format_DetailForExternal>))] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAllFactoryByCompanyId() { try { //RedisCacheHelper.SetKeyValue(cacheKey, JsonConvert.SerializeObject(company)); FactoryModel model = new FactoryModel(); return Content(HttpStatusCode.OK, model.External_GetAllByCompanyId(UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Client_Id : External - OK /// </summary> [HttpGet] [Route("Factory/{factoryId}")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(FactoryModel.Format_DetailForExternal))] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetFactoryById(int factoryId) { try { FactoryModel model = new FactoryModel(); //RedisCacheHelper.SetKeyValue(cacheKey, JsonConvert.SerializeObject(company)); return Content(HttpStatusCode.OK, model.External_GetById(factoryId, UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Client_Id : External - OK /// </summary> /// <param name="metaData">Whether return MetaData or not, Default false</param> [HttpGet] [Route("Factory/{factoryId}/Equipment")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<EquipmentModel.Format_DetailForExternal>))] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAllEquipmentByFactoryId(int factoryId, [FromUri] bool metaData = false) { try { EquipmentModel model = new EquipmentModel(); return Content(HttpStatusCode.OK, model.External_GetAllByFactoryId(factoryId, metaData, UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Client_Id : External - OK /// </summary> [HttpGet] [Route("Factory/{factoryId}/IoTDevice")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<EquipmentModel.Format_DetailForExternal>))] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAllIoTDeviceByFactoryId(int factoryId) { try { IoTDeviceModel model = new IoTDeviceModel(); return Content(HttpStatusCode.OK, model.External_GetAllByFactoryId(factoryId, UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Roles : external /// </summary> /// <param name="top">default 10</param> /// <param name="hours">default 168</param> /// <param name="order">value = asc or desc, default desc</param> [HttpGet] [Route("Factory/{factoryId}/AlarmMessage")] [SwaggerResponse(HttpStatusCode.OK)] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAlarmMessageByFactoryId(int factoryId, [FromUri]int top = 10, [FromUri]int hours = 168, [FromUri]string order = "desc") { try { int companyId = Global.GetCompanyIdFromToken(); if (!General.IsFactoryUnderCompany(factoryId, companyId)) return Unauthorized(); CompanyModel companyModel = new CompanyModel(); CompanyModel.Format_Detail company = companyModel.GetById(companyId); var companySubscription = companyModel.GetValidSubscriptionPlanByCompanyId(companyId); if (companySubscription == null) throw new Exception("can't find valid subscription plan."); DocumentDBHelper docDBHelpler = new DocumentDBHelper(companyId, companySubscription.CosmosDBConnectionString); return Ok(docDBHelpler.GetAlarmMessageByFactoryId(factoryId, top, hours, order, companyId)); } catch (Exception ex) { StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Global._appLogger.Error(logAPI + logMessage); return InternalServerError(); } } /// <summary> /// Roles : external /// </summary> /// /// <param name="top">default 10</param> /// <param name="hours">default 168</param> /// <param name="order">value = asc or desc, default desc</param> [HttpGet] [Route("Factory/{factoryId}/Message")] [SwaggerResponse(HttpStatusCode.OK)] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetMessageByFactoryId(int factoryId, [FromUri]int top = 10, [FromUri]int hours = 168, [FromUri]string order = "desc") { try { int companyId = Global.GetCompanyIdFromToken(); if (!General.IsFactoryUnderCompany(factoryId, companyId)) return Unauthorized(); CompanyModel companyModel = new CompanyModel(); CompanyModel.Format_Detail company = companyModel.GetById(companyId); var companySubscription = companyModel.GetValidSubscriptionPlanByCompanyId(companyId); if (companySubscription == null) throw new Exception("can't find valid subscription plan."); DocumentDBHelper docDBHelpler = new DocumentDBHelper(companyId, companySubscription.CosmosDBConnectionString); return Ok(docDBHelpler.GetMessageByFactoryId(factoryId, top, hours, order, companyId)); } catch (Exception ex) { StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Global._appLogger.Error(logAPI + logMessage); return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Client_Id : External - OK /// </summary> /// <param name="metaData">Whether return MetaData or not, Default false</param> [HttpGet] [Route("Equipment")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<EquipmentModel.Format_DetailForExternal>))] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAllEquipmentByCompanyId([FromUri] bool metaData = false) { try { EquipmentModel equipmentModel = new EquipmentModel(); return Ok(equipmentModel.External_GetAllByCompanyId(UserToken.CompanyId, metaData)); } catch (Exception ex) { StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Global._appLogger.Error(logAPI + logMessage); return InternalServerError(); } } /// <summary> /// Client_Id : External - OK /// </summary> /// <param name="metaData">Whether return MetaData or not, Default false</param> [HttpGet] [Route("Equipment/{id}")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(EquipmentModel.Format_DetailForExternal))] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetEquipmentById(int id, [FromUri] bool metaData = false) { EquipmentModel model = new EquipmentModel(); try { return Content(HttpStatusCode.OK, model.External_GetById(id, metaData, UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Roles : external /// </summary> /// <param name="top">default 10</param> /// <param name="hours">default 168</param> /// <param name="order">value = asc or desc, default desc</param> [HttpGet] [Route("Equipment/{equipmentId}/AlarmMessage")] [SwaggerResponse(HttpStatusCode.OK)] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAlarmMessageByEquipmentId(int equipmentId, [FromUri]int top = 10, [FromUri]int hours = 168, [FromUri]string order = "desc") { try { int companyId = Global.GetCompanyIdFromToken(); if (!General.IsEquipmentUnderCompany(equipmentId, companyId)) return Unauthorized(); CompanyModel companyModel = new CompanyModel(); CompanyModel.Format_Detail company = companyModel.GetById(companyId); var companySubscription = companyModel.GetValidSubscriptionPlanByCompanyId(companyId); if (companySubscription == null) throw new Exception("can't find valid subscription plan."); DocumentDBHelper docDBHelpler = new DocumentDBHelper(companyId, companySubscription.CosmosDBConnectionString); EquipmentModels equipmentModel = new EquipmentModels(); return Ok(docDBHelpler.GetAlarmMessageByEquipmentId(equipmentModel.getEquipmentById(equipmentId).EquipmentId, top, hours, order, companyId)); } catch (Exception ex) { StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Global._appLogger.Error(logAPI + logMessage); return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Roles : external /// </summary> /// <param name="top">default 10</param> /// <param name="hours">default 168</param> /// <param name="order">value = asc or desc, default desc</param> [HttpGet] [Route("Equipment/{equipmentId}/Message")] [SwaggerResponse(HttpStatusCode.OK)] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetMessageByEquipmentId(int equipmentId, [FromUri]int top = 10, [FromUri]int hours = 168, [FromUri]string order = "desc") { try { int companyId = Global.GetCompanyIdFromToken(); if (!General.IsEquipmentUnderCompany(equipmentId, companyId)) return Unauthorized(); CompanyModel companyModel = new CompanyModel(); CompanyModel.Format_Detail company = companyModel.GetById(companyId); var companySubscription = companyModel.GetValidSubscriptionPlanByCompanyId(companyId); if (companySubscription == null) throw new Exception("can't find valid subscription plan."); DocumentDBHelper docDBHelpler = new DocumentDBHelper(companyId, companySubscription.CosmosDBConnectionString); EquipmentModels equipmentModel = new EquipmentModels(); return Ok(docDBHelpler.GetMessageByEquipmentId(equipmentModel.getEquipmentById(equipmentId).EquipmentId, top, hours, order, companyId)); } catch (Exception ex) { StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Global._appLogger.Error(logAPI + logMessage); return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Roles : external /// </summary> /// <param name="top">default 10</param> /// <param name="hours">default 168</param> /// <param name="order">value = asc or desc, default desc</param> [HttpGet] [Route("AlarmMessage")] [SwaggerResponse(HttpStatusCode.OK)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAlarmMessageByCompanyId([FromUri]int top = 10, [FromUri]int hours = 168, [FromUri]string order = "desc") { try { int companyId = Global.GetCompanyIdFromToken(); CompanyModel companyModel = new CompanyModel(); CompanyModel.Format_Detail company = companyModel.GetById(companyId); var companySubscription = companyModel.GetValidSubscriptionPlanByCompanyId(companyId); if (companySubscription == null) throw new Exception("can't find valid subscription plan."); DocumentDBHelper docDBHelpler = new DocumentDBHelper(companyId, companySubscription.CosmosDBConnectionString); return Ok(docDBHelpler.GetAlarmMessageByCompanyId(companyId, top, hours, order)); } catch (Exception ex) { StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Global._appLogger.Error(logAPI + logMessage); return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Roles : external /// </summary> /// <param name="top">default 10</param> /// <param name="hours">default 168</param> /// <param name="order">value = asc or desc, default desc</param> [HttpGet] [Route("Message")] [SwaggerResponse(HttpStatusCode.OK)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetMessageByCompanyId([FromUri]int top = 10, [FromUri]int hours = 168, [FromUri]string order = "desc") { try { int companyId = Global.GetCompanyIdFromToken(); CompanyModel companyModel = new CompanyModel(); CompanyModel.Format_Detail company = companyModel.GetById(companyId); var companySubscription = companyModel.GetValidSubscriptionPlanByCompanyId(companyId); if (companySubscription == null) throw new Exception("can't find valid subscription plan."); DocumentDBHelper docDBHelpler = new DocumentDBHelper(companyId, companySubscription.CosmosDBConnectionString); return Ok(docDBHelpler.GetMessageByCompanyId(companyId, top, hours, order)); } catch (Exception ex) { StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Global._appLogger.Error(logAPI + logMessage); return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Client_Id : External - OK /// </summary> [HttpGet] [Route("IoTDevice")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<IoTDeviceModel.Format_DetailForExternal>))] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetAllIoTDeviceByCompanyId() { try { IoTDeviceModel model = new IoTDeviceModel(); return Content(HttpStatusCode.OK, model.External_GetAllByCompanyId(UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } /// <summary> /// Client_Id : External - OK /// </summary> [HttpGet] [Route("IoTDevice/{iotDeviceId}")] [SwaggerResponse(HttpStatusCode.OK, Type = typeof(IoTDeviceModel.Format_DetailForExternal))] [SwaggerResponse(HttpStatusCode.Unauthorized)] [SwaggerResponse(HttpStatusCode.InternalServerError)] public IHttpActionResult GetIoTDeviceById(int iotDeviceId) { try { IoTDeviceModel model = new IoTDeviceModel(); return Content(HttpStatusCode.OK, model.External_GetById(iotDeviceId, UserToken.CompanyId)); } catch (CDSException cdsEx) { return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId)); } catch (Exception ex) { return Content(HttpStatusCode.InternalServerError, ex); } } } }
using System; using System.Collections.Generic; using System.Text; namespace MusicStore { public class Album : ObjectModel { public string title { get; set; } public Artist artist { get; set; } public int ArtistId { get; set; } public override string ToString() { return $"{ArtistId},{title},{artist}"; } } }
namespace Labs.WPF.TvShowOrganizer.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class RemoveFields : DbMigration { public override void Up() { DropColumn("dbo.Servers", "UpdateUri"); DropColumn("dbo.Servers", "LastUpdate"); } public override void Down() { AddColumn("dbo.Servers", "LastUpdate", c => c.Double(nullable: false)); AddColumn("dbo.Servers", "UpdateUri", c => c.String(nullable: false, maxLength: 50)); } } }
using System; using System.Collections.Generic; using ReadyGamerOne.Utility; using UnityEngine; namespace ReadyGamerOne.Script { public class TriggerContainer3D:MonoBehaviour { private LayerMask targetLayer=0; private List<Collider> contains = new List<Collider>(); private Func<Collider, bool> IsOk; public void Init(LayerMask targetLayerMask, Func<Collider, bool> condition) { this.targetLayer = targetLayerMask; this.IsOk = condition; } /// <summary> /// 外部回去触发器内部东西 /// </summary> public List<Collider> Content => contains; private void OnTriggerEnter(Collider other) { //判断层级 if (1 == targetLayer.value.GetNumAtBinary(other.gameObject.layer)) { if (!contains.Contains(other)) { if (IsOk(other)) { Debug.Log("进入:" + other.name+other.GetInstanceID()); contains.Add(other); } } } } private void OnTriggerExit(Collider other) { if (contains.Contains(other)) { Debug.Log("移除:"+other.name); contains.Remove(other); } } } }
/* * Copyright 2017 University of Zurich * * 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. */ using JetBrains.ReSharper.Psi.CSharp.Tree; using KaVE.RS.Commons.Analysis.CompletionTarget; using NUnit.Framework; namespace KaVE.RS.Commons.Tests_Integration.Analysis.CompletionTargetTestSuite { internal class Annotations : BaseTest { [Test] public void InAnnotation_Class() { CompleteInNamespace( @" [Asd$] class C {} "); AssertCompletionMarker<IAttribute>(CompletionCase.Undefined); } [Test] public void InAnnotation_Method() { CompleteInClass( @" [Asd$] void M() {} "); AssertCompletionMarker<IAttribute>(CompletionCase.Undefined); } [Test] public void InAnnotation_Parameter() { CompleteInClass( @" void M([Asd$] int i) {} "); AssertCompletionMarker<IAttribute>(CompletionCase.Undefined); } [Test] public void Annotation_InEmptyClass() { CompleteInClass( @" [TestCa$] "); AssertCompletionMarker<IAttribute>(CompletionCase.Undefined); } } }
using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Text; using Web.Data; using Web.Helpers; using Web.Identity; using Web.Models; using Web.ViewModels.Checkout; namespace Web.Services { public static class CheckOutServices { public static ApplicationUser GetPurchaser(ApplicationDbContext context) { var purchaser = new ApplicationUser(); return purchaser; } public static void GetRegistrationDropDownLists(ref OrderViewModel viewModel) { viewModel.ProvModel = RegisterLists.ProvList(); viewModel.CountryModel = RegisterLists.CountryList(); viewModel.CreditCardType = RegisterLists.CreditCardTypeList(); viewModel.ExpiryYearList = RegisterLists.ExpiryYearList(); viewModel.ExpiryMonthList = RegisterLists.ExpiryMonthList(); } public static ApplicationUser AddRegistrantAsUser(OrderViewModel viewModel, ApplicationDbContext context) { var user = new ApplicationUser { FirstName = viewModel.FirstName, LastName = viewModel.LastName, Address1 = viewModel.Address1, //Address2 = viewModel.Address2, City = viewModel.City, CountryCode = viewModel.CountryCode, PostalCode = viewModel.PostalCode, Email = viewModel.Email, UserName = viewModel.Email, Phone = viewModel.Phone, //Gender = viewModel.Gender }; return user; } public static OperationResult<bool> ProcessPaymentOrPromo(ref OrderViewModel viewModel) { var operationResult = new OperationResult<bool>(); if (viewModel.Amt == 0) { viewModel.ConfirmationCode = "PROMO"; viewModel.Ppref = "PROMO"; viewModel.CorrelationId = "PROMO"; viewModel.Tax1Amount = 0; operationResult.Result = true; operationResult.Message = "Promo Accepted"; } else { //process Paypal Payment var amtBeforeTaxes = viewModel.Cart.CalculateOrderTotal(); viewModel.Tax1Amount = amtBeforeTaxes*viewModel.Tax1Rate/100; var nvpapiCaller = new NvpApiCaller(); viewModel.CurrencyCode = "CAD"; viewModel.PaymentType = "Sale"; viewModel.ExpDate = viewModel.ExpiryMonthCreditCard + viewModel.ExpiryYearCreditCard.Substring(2, 2); string retMsg = ""; var decoder = new NvpCodec(); //Submit Payment to PayPal nvpapiCaller.DirectPayment(viewModel, ref decoder, ref retMsg); var processorReturnCode = decoder["RESULT"].ToLower(); if (processorReturnCode == "0") { //Get confirmation code from PayPal viewModel.ConfirmationCode = decoder["PNREF"]; viewModel.Ppref = decoder["PPREF"]; viewModel.CorrelationId = decoder["CORRELATIONID"]; retMsg = "ErrorCode=" + processorReturnCode + "&" + "Desc=" + decoder["RESPMSG"]; operationResult.Result = true; operationResult.Message = "Payment Accepted by PayPal"; } } return operationResult; } public static Order AddOrder(OrderViewModel vm, ApplicationDbContext context) { var order = new Order { ConfirmationCode = vm.ConfirmationCode, Ppref = vm.Ppref, Correlationid = vm.CorrelationId, PaymentType = vm.PaymentOption, UserName = vm.UserName, FirstName = vm.FirstName, LastName = vm.LastName, City = vm.City, Country = vm.CountryCode, PostalCode = vm.PostalCode, OrderDate = DateTime.UtcNow, Total = vm.Amt, Phone = vm.Phone, Email = vm.Email, Tax1Amount = vm.Tax1Amount, Tax1Name = vm.Tax1Name, }; context.Orders.Add(order); try { context.SaveChanges(); //This gets the orderId that we use to for Order details table } catch (DbEntityValidationException e) { foreach (var error in e.EntityValidationErrors) { Console.WriteLine(@"Entity of Type ""{0}"" in state ""{1}"" has the following errors:", error.Entry.Entity.GetType().Name, error.Entry.State); foreach (var ve in error.ValidationErrors) { Console.WriteLine(@"-Property: '{0}', Error: '{1}", ve.PropertyName, ve.ErrorMessage); } } } return order; } public static string BuildHtmlForInvoice(Order transaction, IEnumerable<OrderDetail> orderDetails) { var body = new StringBuilder(); body.Append("<h2>" + @Resources.Resources.form_invoice + " #" + transaction.OrderId + " - " + @Resources.Resources.Layout_AppName + "</h2>"); body.Append("<h3>" + transaction.OrderDate.ToLongDateString() + "</h3>"); body.Append("<h4>" + @Resources.Resources.form_received_from + ": " + transaction.FirstName + " " + transaction.LastName + "</h4>"); body.Append("<table>"); foreach (var item in orderDetails) { body.Append("<tr><td style='padding: 5px 15px 0 15px;'>" + item.Course.Title + "</td><td>$" + item.UnitPrice + "</td>"); } body.Append("<tr><td style='padding: 5px 15px 0 20px;'>" + transaction.Tax1Name + "</td><td><span style='text-decoration: underline;'>$" + transaction.Tax1Amount + "</span></td></tr>"); body.Append("<tr><td></td><td><b>$" + transaction.Total + "</b></td></tr>"); body.Append("</table>"); body.Append(@Resources.Resources.form_reference_code + ":<b>" + transaction.ConfirmationCode + "</b>"); return body.ToString(); } public static void PopulateViewModelWithRegisteredUserData(ref OrderViewModel viewModel, ApplicationUser currentUser) { // ReSharper disable once PossibleNullReferenceException viewModel.FirstName = currentUser.FirstName; viewModel.LastName = currentUser.LastName; //viewModel.Gender = currentUser.Gender; viewModel.Address1 = currentUser.Address1; viewModel.City = currentUser.City; viewModel.ProvCode = currentUser.ProvCode; viewModel.CountryCode = currentUser.CountryCode; viewModel.PostalCode = currentUser.PostalCode; //viewModel.Phone = currentUser.Phone; viewModel.ProvModel = RegisterLists.ProvList(); viewModel.CountryModel = RegisterLists.CountryList(); viewModel.Email = currentUser.Email; viewModel.UserName = currentUser.UserName; viewModel.CcAddress1 = currentUser.Address1; //viewModel.CcAddress2 = currentUser.Address2; viewModel.CcCity = currentUser.City; viewModel.CcPostalCode = currentUser.PostalCode; viewModel.FirstNameCreditCard = currentUser.FirstName; viewModel.LastNameCreditCard = currentUser.LastName; viewModel.Password = "123456"; viewModel.ConfirmPassword = "123456"; } } }
using SudokuSolver.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SudokuSolver.Models { public abstract class SudokuBlock : Block<int> { } }
namespace KISSMp3MoverBefore { using KISSMp3MoverBefore.Factories; public class Mp3MoverProgram { public static void Main() { var mp3Mover = Mp3Mover.Instance; mp3Mover.DirectoryPath = @"C:\MyMusic\"; mp3Mover.SelectStrategy = new FileSelectStrategyFactory().Get("ArtistDashSong"); mp3Mover.RenameStrategy = new FileRenameStrategyFactory().Get("RemoveArtist"); mp3Mover.MoveStrategy = new FileMoveStrategyFactory().Get("Normal"); mp3Mover.Start(); } } }
using System.Reflection; using System.IO; namespace Roylance.Common { public static class StringExtensions { public static string ReadResource(this string resourceLocation, Assembly assembly) { resourceLocation.CheckIfNull(nameof(resourceLocation)); assembly.CheckIfNull(nameof(assembly)); using (var d1Stream = assembly.GetManifestResourceStream(resourceLocation)) { if (d1Stream == null) { return string.Empty; } using (var stringReader = new StreamReader(d1Stream)) { return stringReader.ReadToEnd(); } } } } }
using System; using MXDbhelper.Common; using System.Collections.Generic; namespace MXQHLibrary { [TableView("Sys_Login")] public class Login { /// <summary> /// Session /// </summary> [ColumnProperty(Key.True)] public string LoginKey { get; set; } /// <summary> /// 用户账号 /// </summary> [ColumnProperty(Sort.ASC, 0)] public string UserNo { get; set; } /// <summary> /// 登录时间 /// </summary> public DateTime LoginTime { get; set; } /// <summary> /// 登录电脑ip /// </summary> public string LoginIp { get; set; } /// <summary> /// 具有的角色列表 /// </summary> [ColumnProperty(Custom.True)] public virtual Dictionary<string, string> UserRole { get; set; } /// <summary> /// 具有的功能列表 /// </summary> [ColumnProperty(Custom.True)] public virtual Dictionary<string, UserFun> UserFun { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BalloonScript : MonoBehaviour { public GameObject post; public GameScript gameScript; public GameObject hero; public Text tutorialText; private LineRenderer line; private RaycastHit2D hit; private GameObject lastHit; GameObject hitObject; private Animator heroAnim; private GameObject currentlyAttachedTo; void Start () { lastHit = null; line = GetComponent<LineRenderer>(); line.material = new Material(Shader.Find("Sprites/Default")); line.startColor = Color.gray; line.endColor = Color.white; // Set some positions currentlyAttachedTo = post; Vector3[] positions = new Vector3[2]; positions[0] = currentlyAttachedTo.transform.position; positions[1] = this.gameObject.transform.position; line.numPositions = positions.Length; line.SetPositions(positions); heroAnim = hero.GetComponent<Animator>(); } void Update() { Vector3[] positions = new Vector3[2]; positions[0] = new Vector3(currentlyAttachedTo.transform.position.x + 0.2f , currentlyAttachedTo.transform.position.y); positions[1] = this.gameObject.transform.position; //when I move it left, it looks awk line.numPositions = positions.Length; line.SetPositions(positions); AnimationCurve curve = new AnimationCurve(); curve.AddKey(0.01f, 0.2f); curve.AddKey(0.2f, 0.01f); curve.AddKey(0.31f, 0.3f); line.widthCurve = curve; line.widthMultiplier = 0.1f; /* hit = Physics2D.Raycast(positions[0], positions[1] - positions[0]); if (hit.collider != null) { hitObject = hit.collider.gameObject; if (hitObject != lastHit) { if (hitObject.tag == "Enemy") { gameScript.TakeHealOrDamage(-10); } else { } lastHit = hitObject; } } else { } */ } public void StartGrabTutorial() { tutorialText.gameObject.SetActive(true); } public void TriggerJumpDown() { hero.GetComponent<HeroScript>().EndShooting(); this.GetComponent<RectTransform>().anchoredPosition = new Vector3(-7.81f, 5.47f, 0); //transform.localPosition = Vector3.zero; heroAnim.SetBool("jump", false); heroAnim.SetBool("unmasked", false); heroAnim.SetBool("comesDown", true); } public void TriggerUnmask() { heroAnim.SetBool("unmasked", true); } public void ChangeAttached(GameObject attached) { tutorialText.gameObject.SetActive(false); this.currentlyAttachedTo = attached; //move hero if (!heroAnim.GetBool("jump")) { heroAnim.SetBool("jump", true); hero.GetComponent<HeroScript>().StartShooting(); } } public void heroHealed() { if (!heroAnim.GetBool("revives")) { heroAnim.SetBool("revives", true); } } }
using Learn.IService; using Learn.Model; using Learn.Utility.ApiResult; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using SqlSugar; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Learn.WebApi.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class NoteInfoController : ControllerBase { private readonly INoteService _iNoteService; public readonly IWebHostEnvironment _webHostEnvironment; public NoteInfoController(INoteService iNoteService, IWebHostEnvironment webHostEnvironment) { this._iNoteService = iNoteService; _webHostEnvironment = webHostEnvironment; } /// <summary> /// 创建笔记 /// </summary> /// <param name="title"></param> /// <param name="content"></param> /// <param name="tag"></param> /// <returns></returns> [HttpPost("Create")] public async Task<ApiResult> Create(string title,string content,string tag) { NoteInfo note = new NoteInfo { Title = title, Content = content, Time = DateTime.Now, Tag = tag, LikeNumber = 0, WriterID = Convert.ToInt32(this.User.FindFirst("Id").Value) }; bool b = await _iNoteService.CreateAsync(note); if (!b) return ApiResultHelper.Error("添加失败"); return ApiResultHelper.Success(note); } /// <summary> /// 用户删除自己的笔记 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete("Detele")] public async Task<ActionResult<ApiResult>> Delete(int id) { bool b = await _iNoteService.DeleteAsync(id); if (!b) return ApiResultHelper.Error("删除失败"); return ApiResultHelper.Success(b); } /// <summary> /// 用户编辑自己的笔记 /// </summary> /// <param name="id"></param> /// <param name="title"></param> /// <param name="content"></param> /// <param name="tag"></param> /// <returns></returns> [HttpPut("Edit")] public async Task<ActionResult<ApiResult>> Edit(int id, string title, string content, string tag) { var note = await _iNoteService.FindAsync(id); if (note == null) return ApiResultHelper.Error("没有找到该数据"); note.Title = title; note.Content = content; note.Tag = tag; bool b = await _iNoteService.EditAsync(note); if (!b) return ApiResultHelper.Error("修改失败"); return ApiResultHelper.Success(note); } /// <summary> /// 查找所有笔记 /// </summary> /// <param name="page"></param> /// <param name="size"></param> /// <returns></returns> [HttpGet("NotePageAll")] public async Task<ApiResult> GetNotePageAll(int page, int size) { RefAsync<int> total = 0; var note = await _iNoteService.QueryAsync(page, size, total); if (note == null) return ApiResultHelper.Error("没有找到数据"); return ApiResultHelper.Success(note, total); } /// <summary> /// 根据标签查找所有笔记 /// </summary> /// <param name="page"></param> /// <param name="size"></param> /// <param name="tag"></param> /// <returns></returns> [HttpGet("NotePageTag")] public async Task<ApiResult> GetNotePageTag(int page, int size,string tag) { RefAsync<int> total = 0; var note = await _iNoteService.QueryAsync(c=>c.Tag==tag, page, size, total); if(note ==null) return ApiResultHelper.Error("没有找到数据"); return ApiResultHelper.Success(note, total); } /// <summary> /// 查找自己所写的笔记 /// </summary> /// <param name="page"></param> /// <param name="size"></param> /// <returns></returns> [HttpGet("NotePage")] public async Task<ApiResult> GetNotePage(int page, int size) { RefAsync<int> total = 0; int id = Convert.ToInt32(this.User.FindFirst("Id").Value); var note = await _iNoteService.QueryAsync(c=>c.WriterID==id,page, size, total); if (note == null) return ApiResultHelper.Error("没有找到数据"); return ApiResultHelper.Success(note, total); } [HttpGet("NoteID")] public async Task<ApiResult> GetNoteID(int id) { var note = await _iNoteService.QueryAsync(c => c.ID == id); if (note == null) return ApiResultHelper.Error("没有找到数据"); return ApiResultHelper.Success(note); } /// <summary> /// 点赞笔记 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpPut("Like")] public async Task<ActionResult<ApiResult>> Like(int id) { var note = await _iNoteService.FindAsync(id); if (note == null) return ApiResultHelper.Error("没有找到该数据"); note.LikeNumber = ++note.LikeNumber; bool b = await _iNoteService.EditAsync(note); if (!b) return ApiResultHelper.Error("点赞失败"); return ApiResultHelper.Success(note); } [HttpPost("UpLoadImg")] public async Task<ApiResult> UpLoadImg([FromForm(Name = "imgFile")]IFormFile file) { string webRootPath = _webHostEnvironment.WebRootPath; // wwwroot 文件夹 string uploadPath = Path.Combine("uploads", DateTime.Now.ToString("yyyyMMdd")); string dirPath = Path.Combine(webRootPath, uploadPath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } string fileExt = Path.GetExtension(file.FileName).Trim('.'); //文件扩展名,不含“.” string newFileName = Guid.NewGuid().ToString().Replace("-", "") + "." + fileExt; //随机生成新的文件名 var fileFolder = Path.Combine(dirPath, newFileName); using (var stream = new FileStream(fileFolder, FileMode.Create)) { await file.CopyToAsync(stream); } string url = $@"/{uploadPath}/{newFileName}"; return ApiResultHelper.Success("http://localhost:5000"+url); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public partial class Usuario { public int Codigo; public string Nome; public string Senha; public Usuario(int codigo, string nome, string senha) { this.Codigo = codigo; this.Nome = nome; this.Senha = senha; } }
using Sistema.Arquitetura.Library.Core; using Sistema.Arquitetura.Library.Core.Interface; using Sistema.Arquitetura.Library.Core.Util.Security; using Idealize.VO; using System.Collections.Generic; namespace Idealize.DAO { /// <summary> /// Classe de Acesso a Dados da Tabela aluno /// </summary> public class TipoQuestaoDAO : NativeDAO<TipoQuestao> { /// <summary> /// Inicializa uma instância da classe /// </summary> /// <param name="connection">Recebendo como parametro a conexao com banco de dados</param> /// <param name="objectSecurity">Objeto de segurança</param> /// <returns>Objeto inserido</returns> public TipoQuestaoDAO(System.Data.IDbConnection connection, ObjectSecurity objectSecurity) : base(connection, objectSecurity) { } #region Métodos de Persistência Básicos /// <summary> /// Realiza o insert do objeto por stored Procedure /// </summary> /// <param name="pObject">Objeto com os valores a ser inserido</param> /// <returns>Objeto Inserido</returns> public TipoQuestao InsertByStoredProcedure(TipoQuestao pObject) { string sql = "dbo.I_sp_TipoQuestao"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("descricao", pObject.descricao); return this.ExecuteReturnT(statement); } /// <summary> /// Realiza o update do objeto por stored Procedure /// </summary> /// <param name="pObject">Objeto com os valores a ser atualizado</param> /// <returns>Objeto Atualizado</returns> public TipoQuestao UpdateByStoredProcedure(TipoQuestao pObject) { string sql = "dbo.U_sp_TipoQuestao"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("idTipoQuestao", pObject.idTipoQuestao); statement.AddParameter("Descricao", pObject.descricao); return this.ExecuteReturnT(statement); } /// <summary> /// Realiza a deleção do objeto por stored Procedure /// </summary> /// <param name="idObject">PK da tabela</param> /// <returns>Quantidade de Registros deletados</returns> public int DeleteByStoredProcedure(TipoQuestao pObject, bool flExclusaoLogica, int userSystem) { string sql = "dbo.D_sp_TipoQuestao"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("idTipoQuestao", pObject.idTipoQuestao); return this.ExecuteNonQuery(statement); } /// <summary> /// Retorna registro pela PK /// </summary> /// <param name="idObject">PK da tabela</param> /// <returns>Registro da PK</returns> public TipoQuestao SelectByPK(TipoQuestao pObject) { string sql = "dbo.S_sp_TipoQuestao"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("idTipoQuestao", pObject.idTipoQuestao); return this.ExecuteReturnT(statement); } #endregion #region Métodos Personalizados #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication8 { public class MallardDuck : Duck { public MallardDuck() { QuackBehavior quackBehavior = new NormalQuack(); FlyBehavior flyBehavior = new FlyWithWings(); } public override void Display() { Console.WriteLine("I'm a real Mallard duck"); } } public class ToyDuck : Duck { public ToyDuck() { QuackBehavior quackBehavior = new Squeak(); FlyBehavior flyBehavior = new FlyNoWay(); } public override void Display() { Console.WriteLine("I'm a toy duck!"); } } }
using UnityEngine; using System.Collections; namespace Ph.Bouncer { public class LevelCompleteMenu : MonoBehaviour { public void OnLevelComplete() { NGUITools.SetActiveChildren(gameObject, true); } void OnEnable() { Messenger.AddListener(Events.LevelComplete, OnLevelComplete); } void OnDisable() { Messenger.RemoveListener(Events.LevelComplete, OnLevelComplete); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Tethering : MonoBehaviour { //private bool onglass = false; private List<Tetherable> under = new List<Tetherable>(); private Tetherable tethered = null; private List<Slot> slots = new List<Slot>(); private float tmp = 0f; void Update() { if(!InInput.controller.isOnGlass()) tmp = Time.time; if(Time.time - tmp > 0.1f && GameManager.Manager.thresholdLC1(0.7f) > 0 && under.Count > 0 && tethered == null) { tethered = under[under.Count - 1].Tether(gameObject.transform); } if(GameManager.Manager.thresholdLC1(0.4f) < 0 && tethered != null) { tethered.Untether(); tethered = null; } if(tethered != null) { var availableSlots = slots.FindAll(sl => !sl.IsOccupied || sl.Sloted.Contains(tethered)); // if sl.Unique, IsOccupied == true iff the slot is actually occupied, else IsOccupied is always false if(availableSlots.Count > 0) tethered.ActiveSlot = availableSlots[0]; else tethered.ActiveSlot = null; } } void OnTriggerEnter2D(Collider2D other) { Tetherable teth = other.gameObject.GetComponent<Tetherable>(); if(teth != null) under.Add(teth); Slot sl = other.gameObject.GetComponent<Slot>(); if(sl != null) slots.Add(sl); } void OnTriggerExit2D(Collider2D other) { Tetherable teth = other.gameObject.GetComponent<Tetherable>(); if(teth != null) under.Remove(teth); Slot sl = other.gameObject.GetComponent<Slot>(); if(sl != null) slots.Remove(sl); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameManager : Singleton<GameManager> { public TowerBtn ClickedBtn { get; set; } private int currency; private int wave = 0; public int Currency { get { return currency; } set { this.currency = value; this.currencyText.text = value.ToString() + "<color=lime>$</color>"; } } [SerializeField] private Text currencyText; [SerializeField] private GameObject waveBtn; List<Monster> activeMonsters = new List<Monster>(); public ObjectPool Pool { get; set; } public bool WaveActive { get { return activeMonsters.Count > 0; } } private void Awake() { Pool = GetComponent<ObjectPool>(); } // Use this for initialization void Start() { Currency = 50; } // Update is called once per frame void Update() { HandleEscape(); } public void PickTower(TowerBtn towerBtn) { if (Currency >= towerBtn.Price && !WaveActive) { this.ClickedBtn = towerBtn; //Hover.Instance.Activate (towerBtn.Sprite); } } public void BuyTower() { if (Currency >= ClickedBtn.Price) { Currency = Currency - ClickedBtn.Price; //Hover.Instance.Deactivate (); } } private void HandleEscape() { if (Input.GetKeyDown(KeyCode.Escape)) { Hover.Instance.Deactivate(); } } // functia asta se apeleaza cand apesi pe butonu' next wave public void StartWave() { wave++; StartCoroutine(SpawnWave()); waveBtn.SetActive(false); } // tipu' inamicului private IEnumerator SpawnWave() { LevelManager.Instance.GeneratePath(); for (int i = 0; i < wave; i++) { int monsterIndex = Random.Range(0, 3); string type = string.Empty; switch (monsterIndex) { case 0: type = "Jerry"; break; case 1: type = "BirdPerson"; break; case 2: type = "MrNeedful"; break; default: break; } //Pool.GetObject(type); Monster monster = Pool.GetObject(type).GetComponent<Monster>(); monster.Spawn(); activeMonsters.Add(monster); yield return new WaitForSeconds(2.5f); } } public void RemoveMonster(Monster monster) { activeMonsters.Remove(monster); if (!WaveActive) { waveBtn.SetActive(true); } } }
using Moq; using System; using Toppler.Api; using Toppler.Redis; using Xunit; namespace Toppler.Tests.Unit.Api { public class RankingTest { [Fact] public void Ctor_WhenNullProvider_ShouldThrowException() { Assert.Throws<ArgumentNullException>(() => { ITopplerContext context = new TopplerContext("", 0, null); var api = new Ranking(null, context); }); } [Fact] public void Ctor_WhenNullContext_ShouldThrowException() { Assert.Throws<ArgumentNullException>(() => { var provider = new Mock<IRedisConnection>(); var api = new Ranking(provider.Object, null); }); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Forms; namespace callback { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { callmeback app = new callmeback(); app.ShowDialog(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using online_knjizara.EF; using online_knjizara.EntityModels; using online_knjizara.Helpers; using online_knjizara.ViewModels; namespace online_knjizara.Controllers { [Autorizacija(zaposlenik: true, citaockorisnik: false)] public class KorisnikController : Controller { private OnlineKnjizaraDbContext _context; public KorisnikController(OnlineKnjizaraDbContext _db) { _context = _db; } public IActionResult Index(string option,string search) { List<KorisnikPrikazVM> model = _context.Korisnik .Select( x => new KorisnikPrikazVM { ID = x.ID, Ime = x.Ime, Prezime = x.Prezime, Adresa = x.Adresa, Email = x.Email, Grad = x.Grad.Naziv + " [" + x.Grad.Drzava.Naziv + "]", Telefon = x.Telefon, DatumRodjenja = x.DatumRodjenja, KorisnickoIme = _context.CitaocKorisnik.Where(y=>y.Korisnik_ID==x.ID).Select(a=>a.KorisnickiNalog.KorisnickoIme).FirstOrDefault() }).ToList(); if (option == "ImePrezime") { return View(model.Where(x => search == null || (x.Ime + " " + x.Prezime).ToLower().Contains(search.ToLower()) || (x.Prezime + " " + x.Ime).ToLower().Contains(search.ToLower())).ToList()); } else if(option=="Adresa") { return View(model.Where(x =>search == null ||(x.Adresa.ToLower().Contains(search.ToLower())) ).ToList()); } else if (option == "Email") { return View(model.Where(x => search == null || (x.Email.ToLower().Contains(search.ToLower()))).ToList()); } else if (option == "KorisnickoIme") { return View(model.Where(x => search == null || (x.KorisnickoIme.ToLower().Contains(search.ToLower()))).ToList()); } else if(option=="Sve") { return View(model); } return View(model); } public IActionResult Dodaj() { KorisnikUrediVM model = new KorisnikUrediVM { Grad = _context.Grad.OrderBy(x => x.Naziv).Select(a => new SelectListItem { Value = a.ID.ToString(), Text = a.Naziv + " [" + a.Drzava.Naziv + "]" }).ToList() }; return View(model); } public IActionResult Snimi(KorisnikUrediVM vm) { var citaoc = _context.CitaocKorisnik.Where(x=>x.Korisnik_ID==vm.ID); if (!ModelState.IsValid) { vm.Grad = _context.Grad.OrderBy(x => x.Naziv).Select(a => new SelectListItem { Value = a.ID.ToString(), Text = a.Naziv + " [" + a.Drzava.Naziv + "]" }).ToList(); return View("Dodaj", vm); } Korisnik korisnik; if (vm.ID == 0) { korisnik = new Korisnik(); _context.Add(korisnik); } else { korisnik = _context.Korisnik.Find(vm.ID); } korisnik.ID = vm.ID; korisnik.Ime = vm.Ime; korisnik.Prezime = vm.Prezime; korisnik.Adresa = vm.Adresa; korisnik.Email = vm.Email; korisnik.Telefon = vm.Telefon; korisnik.DatumRodjenja = vm.DatumRodjenja; korisnik.Grad_ID = vm.Grad_ID; _context.SaveChanges(); return RedirectToAction("Index"); } public IActionResult Uredi(int id) { Korisnik korisnik = _context.Korisnik.Find(id); if (korisnik == null) { return RedirectToAction(nameof(Index)); } KorisnikUrediVM model = new KorisnikUrediVM { ID = korisnik.ID, Ime = korisnik.Ime, Prezime = korisnik.Prezime, Adresa = korisnik.Adresa, Email = korisnik.Email, Telefon= korisnik.Telefon, Grad = _context.Grad.OrderBy(x => x.Naziv).Select(o => new SelectListItem(o.Naziv + " [" + o.Drzava.Naziv + "]", o.ID.ToString())).ToList(), Grad_ID = korisnik.Grad_ID, DatumRodjenja=korisnik.DatumRodjenja, KorisnickoIme = _context.CitaocKorisnik.Where(y => y.Korisnik_ID == id).Select(a => a.KorisnickiNalog.KorisnickoIme).FirstOrDefault() }; return View("Dodaj", model); } public IActionResult Obrisi(int id) { var korisnik = _context.Korisnik.Find(id); var citaockorisnik = _context.CitaocKorisnik.Where(x => x.Korisnik_ID == korisnik.ID); foreach (var item in _context.Zaposlenici) { if (item.KorisnickiNalog_ID == citaockorisnik.Select(y => y.KorisnickiNalog_ID).FirstOrDefault()) { _context.Zaposlenici.Remove(item); } } foreach (var item in _context.KorisnickiNalozi) { if(item.KorisnickiNalog_ID==citaockorisnik.Select(y=>y.KorisnickiNalog_ID).FirstOrDefault()) { _context.KorisnickiNalozi.Remove(item); } } _context.CitaocKorisnik.Remove(citaockorisnik.Single()); _context.Korisnik.Remove(korisnik); _context.SaveChanges(); return RedirectToAction("Index"); } } }
using System.Drawing; namespace Calcifer.UI.Controls { public class Bar: UIElement { public int Value { get; set; } public int MaxValue { get; set; } public Bar(UIElement parent) : base(parent) { FrontColor = Color.GreenYellow; BackColor = Color.Silver; } protected override void Render(IRenderer renderer) { renderer.SetProperty("Value", Value); renderer.SetProperty("MaxValue", MaxValue); base.Render(renderer); } } }
using Football.Models; using System; using System.Collections.Generic; using System.Linq; namespace Football { public class Football { static void Main(string[] args) { List<Team> teams = new List<Team>(); string input; while ((input = Console.ReadLine()) != "END") { try { string[] comand = input.Split(";", StringSplitOptions.RemoveEmptyEntries); if (comand[0] == "Team") { Team team = new Team(comand[1]); teams.Add(team); } else if (comand[0] == "Add") { if (teams.FirstOrDefault(x => x.Name == comand[1]) == null) { throw new InvalidOperationException(string.Format("Team {0} does not exist.", comand[1])); } else { int[] playerTokens = comand.Skip(3).Select(int.Parse).ToArray(); Player player = new Player(comand[2], playerTokens[0], playerTokens[1], playerTokens[2], playerTokens[3], playerTokens[4]); teams.First(x => x.Name == comand[1]).AddPlayer(player); } } else if (comand[0] == "Remove") { teams.First(x => x.Name == comand[1]).RemovePlayer(comand[2]); } else if (comand[0] == "Rating") { if (teams.FirstOrDefault(x => x.Name == comand[1]) == null) { throw new InvalidOperationException(string.Format("Team {0} does not exist.", comand[1])); } else { teams.First(x => x.Name == comand[1]).CalculateRating(); } } } catch (Exception ae) { Console.WriteLine(ae.Message); } } } } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using TQVaultAE.Domain.Contracts.Services; using TQVaultAE.GUI.Helpers; using TQVaultAE.Presentation; using System.Collections.ObjectModel; using TQVaultAE.Domain.Entities; using TQVaultAE.GUI.Components; using System.Linq; using System.IO; using System.Diagnostics; namespace TQVaultAE.GUI { public partial class BagButtonSettings : VaultForm { // DI private readonly ITranslationService TranslationService; private readonly IIconService iconService; private readonly ILogger<BagButtonSettings> Log; // Drag & Drop stuff private bool IsDragging = false; private Point DragPosition; // Form object model crossing simplification public readonly List<FlowLayoutPanel> PicsPanelList; public readonly List<GroupBox> GroupBoxList; // Remove duplicate List<RecordId> alreadyAddedPics = new(); // From Database private ReadOnlyCollection<IconInfo> Pictures; private BagButtonIconInfo _DefaultBagButtonIconInfo = new() { DisplayMode = BagButtonDisplayMode.Default }; #region CurrentBagButton private BagButtonBase _CurrentBagButton; private bool IsLoaded; internal BagButtonBase CurrentBagButton { set { _CurrentBagButton = value; ApplySelectedBagPath(); } } #endregion #if DEBUG // For Design Mode public BagButtonSettings() => InitializeComponent(); #endif public BagButtonSettings(MainForm instance , ITranslationService translationService , IIconService iconService , ILogger<BagButtonSettings> log ) : base(instance.ServiceProvider) { this.Owner = instance; this.TranslationService = translationService; this.iconService = iconService; this.Log = log; this.InitializeComponent(); this.MinimizeBox = false; this.NormalizeBox = false; this.MaximizeBox = true; // Map [Esc] and [Enter] this.CancelButton = this.cancelButton; this.AcceptButton = this.applyButton; #region Translations this.Text = Resources.BagButtonSettingsTitle; // Selected button this.scalingLabelSelectedButton.Text = Resources.BagButtonSettingsSelectedButton; // Button properties this.groupBoxEdit.Text = Resources.BagButtonSettingsButtonProperties; this.scalingRadioButtonDefaultIcon.Text = Resources.BagButtonSettingsUseDefault; this.scalingRadioButtonCustomIcon.Text = Resources.BagButtonSettingsCustomIcon; this.scalingCheckBoxNumber.Text = Resources.BagButtonSettingsNumber; this.scalingCheckBoxLabel.Text = Resources.BagButtonSettingsLabel; // Selected pictures this.groupBoxSelectedPictures.Text = Resources.BagButtonSettingsSelectedPictures; this.radioButtonPictureSimple.Text = Resources.BagButtonSettingsModeSimple; this.radioButtonPictureDetailed.Text = Resources.BagButtonSettingsModeDetailed; this.groupBoxOffBitmap.Text = Resources.BagButtonSettingsOffBitmap; this.groupBoxOnBitmap.Text = Resources.BagButtonSettingsOnBitmap; this.groupBoxOverBitmap.Text = Resources.BagButtonSettingsOverBitmap; this.groupBoxSimpleImage.Text = Resources.BagButtonSettingsImageBitmap; // Available pictures this.groupBoxAvailablePictures.Text = Resources.BagButtonSettingsAvailablePictures; this.scalingLabelDragDropNotice.Text = Resources.BagButtonSettingsDragDropNotice; // Tabs this.tabPageSkills.Text = TranslationService.TranslateXTag("tagWindowName02"); this.tabPageRelics.Text = TranslationService.TranslateXTag("tagTutorialTip18Title"); this.tabPageArtifacts.Text = TranslationService.TranslateXTag("xtagTutorialTip05Title"); this.tabPageJewellery.Text = Resources.GlobalJewellery; this.tabPageScrolls.Text = TranslationService.TranslateXTag("xtagTutorialTip06Title"); this.tabPagePotions.Text = TranslationService.TranslateXTag("tagTutorialTip14Title"); this.tabPageButtons.Text = Resources.GlobalButtons; this.tabPageMisc.Text = Resources.GlobalMiscellaneous; this.tabPageHelmets.Text = TranslationService.TranslateXTag("tagItemHelmet"); this.tabPageArmbands.Text = TranslationService.TranslateXTag("tagItemArmband"); this.tabPageShields.Text = TranslationService.TranslateXTag("tagItemBuckler"); this.tabPageGreaves.Text = TranslationService.TranslateXTag("tagItemGreaves"); // Exit this.applyButton.Text = TranslationService.TranslateXTag("tagMenuButton07"); this.cancelButton.Text = TranslationService.TranslateXTag("tagMenuButton06"); #endregion #region Custom font & Scaling this.Font = FontService.GetFont(9F, FontStyle.Regular, GraphicsUnit.Point); var title = FontService.GetFont(12F, FontStyle.Regular, GraphicsUnit.Point); this.scalingLabelSelectedButton.Font = title; this.groupBoxEdit.Font = title; this.groupBoxSelectedPictures.Font = title; this.groupBoxAvailablePictures.Font = title; this.cancelButton.Font = title; this.applyButton.Font = title; var text = FontService.GetFontLight(11.25F, FontStyle.Regular, GraphicsUnit.Point); this.scalingLabelSelectedButtonValue.Font = text; this.groupBoxEdit.ProcessAllControls(ctr => ctr.Font = text); this.groupBoxSelectedPictures.ProcessAllControls(ctr => ctr.Font = text); this.groupBoxAvailablePictures.ProcessAllControls(ctr => ctr.Font = text); ScaleControl(this.UIService, this.cancelButton); ScaleControl(this.UIService, this.applyButton); #endregion #if DEBUG this.scalingTextBoxDebug.Visible = true; #endif this.PicsPanelList = new() { this.flowLayoutPanelPicsArtifacts, this.flowLayoutPanelPicsButtons, this.flowLayoutPanelPicsJewellery, this.flowLayoutPanelPicsMisc, this.flowLayoutPanelPicsPotions, this.flowLayoutPanelPicsRelics, this.flowLayoutPanelPicsScrolls, this.flowLayoutPanelPicsSkills, }; this.GroupBoxList = new() { groupBoxOnBitmap, groupBoxOffBitmap, groupBoxOverBitmap, groupBoxSimpleImage }; } private void ApplySelectedBagPath() { var vaultPanel = _CurrentBagButton.Parent as VaultPanel; this.scalingLabelSelectedButtonValue.Text = string.Format("{0} - {1} - ({2})" , vaultPanel.Player.PlayerName , _CurrentBagButton.ButtonNumber + 1 , _CurrentBagButton.Sack?.BagButtonIconInfo?.Label ); } private void BagButtonSettings_Load(object sender, EventArgs e) { this.Pictures = this.iconService.GetIconDatabase();// Singleton ApplyIconInfo(); if (!IsLoaded) { TogglePicturePickup(); this.PicsPanelList.ForEach(p => p.SuspendLayout()); this.SuspendLayout(); foreach (var pic in this.Pictures) AddPicture(pic); this.PicsPanelList.ForEach(p => p.ResumeLayout(false)); this.PicsPanelList.ForEach(p => p.PerformLayout()); DisplayPictures(); this.ResumeLayout(false); this.PerformLayout(); IsLoaded = true; } } /// <summary> /// Adjuste form display at first load /// </summary> private void ApplyIconInfo() { ResetImagePicker(); var info = _CurrentBagButton.Sack.BagButtonIconInfo; if (info is null) info = _DefaultBagButtonIconInfo; this.scalingTextBoxLabel.Text = info.Label; if (info.DisplayMode.HasFlag(BagButtonDisplayMode.CustomIcon)) this.scalingRadioButtonCustomIcon.Checked = true; if (info.DisplayMode.HasFlag(BagButtonDisplayMode.Label)) this.scalingCheckBoxLabel.Checked = true; if (info.DisplayMode.HasFlag(BagButtonDisplayMode.Number)) this.scalingCheckBoxNumber.Checked = true; if (info.DisplayMode == BagButtonDisplayMode.Default) this.scalingRadioButtonDefaultIcon.Checked = true; // Adjust Simple pickup or Detailed => Goes Detailed if non Default, user can change pickup view afterward if (!this.scalingRadioButtonDefaultIcon.Checked) { // Apply previously saved icons var prevOn = this.Pictures.Where(p => p.Own(info.On)).FirstOrDefault(); var prevOff = this.Pictures.Where(p => p.Own(info.Off)).FirstOrDefault(); var prevOver = this.Pictures.Where(p => p.Own(info.Over)).FirstOrDefault(); if (prevOn is not null) { this.pictureBoxOn.Image = prevOn.OnBitmap; this.pictureBoxOn.Tag = prevOn; } if (prevOff is not null) { this.pictureBoxOff.Image = this.pictureBoxSimple.Image = prevOff.OffBitmap; this.pictureBoxOff.Tag = this.pictureBoxSimple.Tag = prevOff; } if (prevOver is not null) { this.pictureBoxOver.Image = prevOver.OffBitmap; this.pictureBoxOver.Tag = prevOver; } return; } } private void ResetImagePicker() { // Reset image picker this.pictureBoxOn.Image = this.pictureBoxOff.Image = this.pictureBoxSimple.Image = this.pictureBoxOver.Image = null; this.pictureBoxOn.Tag = this.pictureBoxOff.Tag = this.pictureBoxSimple.Tag = this.pictureBoxOver.Tag = null; } void TogglePicturePickup() { if (this.radioButtonPictureSimple.Checked) { groupBoxOnBitmap.Visible = false; groupBoxOffBitmap.Visible = false; groupBoxOverBitmap.Visible = false; groupBoxSimpleImage.Visible = true; } else { groupBoxOnBitmap.Visible = true; groupBoxOffBitmap.Visible = true; groupBoxOverBitmap.Visible = true; groupBoxSimpleImage.Visible = false; } } private void DisplayPictures() { this.PicsPanelList.ForEach(p => p.SuspendLayout()); this.PicsPanelList.ForEach(p => p.ProcessAllControls(pb => DisplayPicture(pb))); this.PicsPanelList.ForEach(p => p.ResumeLayout(false)); this.PicsPanelList.ForEach(p => p.PerformLayout()); } private void DisplayPicture(Control picturebox) { var pb = picturebox as PictureBox; var info = pb.Tag as IconInfo; var resourceid = pb.Image.Tag as RecordId; if (this.radioButtonPictureSimple.Checked) { pb.Visible = (resourceid == info.Off); // Display Off pics only for Simple mode return; } pb.Visible = true;// Display all } private void AddPicture(IconInfo info) { if (info.Off is not null) AddPicture(info, info.OffBitmap, info.Off); if (info.On is not null) AddPicture(info, info.OnBitmap, info.On); if (info.Over is not null) AddPicture(info, info.OverBitmap, info.Over); } private void AddPicture(IconInfo info, Bitmap bmp, RecordId resourceId) { if (alreadyAddedPics.Contains(resourceId)) return;// Because an instance of IconInfo may contain resourceId multiple time if (bmp is not null) { var picOff = new PictureBox() { SizeMode = PictureBoxSizeMode.Zoom, // "Zoom" ensure aspect ratio on resize Size = new Size(32, 32), // force image size for picking. Source Bmp may vary Image = bmp, Tag = info, BorderStyle = BorderStyle.FixedSingle, }; bmp.Tag = resourceId; // Magnifier picOff.MouseEnter += PicOff_MouseEnter; picOff.MouseLeave += PicOff_MouseLeave; // Drag & Drop events picOff.MouseDown += PicOff_MouseDown; picOff.MouseMove += PicOff_MouseMove; picOff.MouseUp += PicOff_MouseUp; // Allocate per category switch (info.Category) { case IconCategory.Misc: this.flowLayoutPanelPicsMisc.Controls.Add(picOff); break; case IconCategory.Artifacts: this.flowLayoutPanelPicsArtifacts.Controls.Add(picOff); break; case IconCategory.Relics: this.flowLayoutPanelPicsRelics.Controls.Add(picOff); break; case IconCategory.Jewellery: this.flowLayoutPanelPicsJewellery.Controls.Add(picOff); break; case IconCategory.Potions: this.flowLayoutPanelPicsPotions.Controls.Add(picOff); break; case IconCategory.Scrolls: this.flowLayoutPanelPicsScrolls.Controls.Add(picOff); break; case IconCategory.Skills: this.flowLayoutPanelPicsSkills.Controls.Add(picOff); break; case IconCategory.Buttons: this.flowLayoutPanelPicsButtons.Controls.Add(picOff); break; case IconCategory.Helmets: this.flowLayoutPanelPicsHelmets.Controls.Add(picOff); break; case IconCategory.Shields: this.flowLayoutPanelPicsShields.Controls.Add(picOff); break; case IconCategory.Armbands: this.flowLayoutPanelPicsArmbands.Controls.Add(picOff); break; case IconCategory.Greaves: this.flowLayoutPanelPicsGreaves.Controls.Add(picOff); break; } alreadyAddedPics.Add(resourceId); } } private void CherryPickIconSimpleMode(IconInfo info, Image bmp) { pictureBoxSimple.Image = pictureBoxOff.Image = bmp;// Which is Off pictureBoxSimple.Image.Tag = pictureBoxOff.Image.Tag = info.Off;// Which is Off pictureBoxSimple.Tag = pictureBoxOver.Tag = pictureBoxOff.Tag = pictureBoxOn.Tag = info; pictureBoxOn.Image = info.OnBitmap; if (pictureBoxOn.Image is not null)// May happen on rare exception (TEX Filename rule not consitent) pictureBoxOn.Image.Tag = info.On; // Apply only if different if (info.IsOverSameAsOthers) { pictureBoxOver.Image = null; } else { pictureBoxOver.Image = info.OverBitmap; if (pictureBoxOver.Image is not null) pictureBoxOver.Image.Tag = info.Over; } } private void PicOff_MouseEnter(object sender, EventArgs e) { if (IsDragging) return; // No magnifier from icon placeholders for default icon if (this.scalingRadioButtonDefaultIcon.Checked && (sender == this.pictureBoxOff || sender == this.pictureBoxOn || sender == this.pictureBoxOver || sender == this.pictureBoxSimple) ) return; var picB = sender as PictureBox; if (picB.Image is null) return; var picFilePath = picB.Image.Tag as RecordId; var picName = Path.GetFileNameWithoutExtension(picFilePath.Raw); picName = picName[0] + new string(picName.ToLower().Skip(1).ToArray());// Titlecase var info = picB.Tag as IconInfo; // Find original size Size? orig = null; if (info.On == picFilePath) orig = info?.OnBitmap?.Size; else if (info.Off == picFilePath) orig = info?.OffBitmap?.Size; else if (info.Over == picFilePath) orig = info?.OverBitmap?.Size; // Compute Position of Magnifier relative to picB var loc = this.PointToClient(picB.PointToScreen(Point.Empty)); this.iconMagnifier.Location = new Point(loc.X, loc.Y + 32);// Locate below icon this.iconMagnifier.pictureBox.Image = picB.Image; this.iconMagnifier.scalingLabelFilename.Text = picName; this.iconMagnifier.scalingLabelSize.Text = orig is not null ? string.Format("{0} x {1}", orig?.Width, orig?.Height) : string.Empty; this.iconMagnifier.Visible = true; } private void PicOff_MouseLeave(object sender, EventArgs e) { if (IsDragging) return; this.iconMagnifier.Visible = false; } #region Drag & Drop private void PicOff_MouseDown(object sender, MouseEventArgs e) { var picB = sender as PictureBox; var info = picB.Tag as IconInfo; var bmp = info.OffBitmap; // Auto assign on Right Click if (e.Button == MouseButtons.Right) { CherryPickIconSimpleMode(info, bmp); this.scalingRadioButtonCustomIcon.Checked = true; UpdateTextBoxDebug(bmp); return; } IsDragging = true; pictureBoxDrag.Location = this.PointToClient(Cursor.Position); pictureBoxDrag.Image = picB.Image; pictureBoxDrag.Tag = info; pictureBoxDrag.Visible = true; } private void PicOff_MouseMove(object sender, MouseEventArgs e) { if (IsDragging) { DragPosition = this.PointToClient(Cursor.Position); pictureBoxDrag.Location = new Point(DragPosition.X - 5, DragPosition.Y - 5);// Slight delta } } private void PicOff_MouseUp(object sender, MouseEventArgs e) { PictureBox picB = sender as PictureBox; Image bmp = null; IconInfo info = null; IsDragging = false; pictureBoxDrag.Visible = false; info = pictureBoxDrag.Tag as IconInfo; bmp = pictureBoxDrag.Image; var found = flowLayoutPanelPicturePickup.GetChildAtPoint( flowLayoutPanelPicturePickup.PointToClient(Cursor.Position) , GetChildAtPointSkip.Invisible | GetChildAtPointSkip.Transparent ); if (this.radioButtonPictureDetailed.Checked) { if (found == this.groupBoxOnBitmap) { pictureBoxOn.Image = bmp; pictureBoxOn.Tag = info; pictureBoxOn.Image.Tag = info.On; } if (found == this.groupBoxOffBitmap) { pictureBoxOff.Image = bmp; pictureBoxOff.Tag = info; pictureBoxOff.Image.Tag = info.Off; } if (found == this.groupBoxOverBitmap) { pictureBoxOver.Image = bmp; pictureBoxOver.Tag = info; pictureBoxOver.Image.Tag = info.Over; } } if (this.radioButtonPictureSimple.Checked) { if (found == this.groupBoxSimpleImage) { CherryPickIconSimpleMode(info, bmp); } } if (found is not null) { this.scalingRadioButtonCustomIcon.Checked = true; UpdateTextBoxDebug(bmp); } } #endregion [Conditional("DEBUG")] private void UpdateTextBoxDebug(Image bmp) { this.scalingTextBoxDebug.Text = bmp.Tag.ToString() + $" - ({bmp.Size.Width}x{bmp.Size.Height})"; } private void radioButtonPictureSimple_CheckedChanged(object sender, EventArgs e) { TogglePicturePickup(); DisplayPictures(); } private void radioButtonPictureDetailed_CheckedChanged(object sender, EventArgs e) { TogglePicturePickup(); DisplayPictures(); } private void applyButton_Click(object sender, EventArgs e) { var dispmode = GetDisplayMode(); // Validation if (this.pictureBoxOff.Image is null || this.pictureBoxOn.Image is null || (dispmode.HasFlag(BagButtonDisplayMode.Label) && string.IsNullOrWhiteSpace(this.scalingTextBoxLabel.Text))) { MessageBox.Show( Resources.BagButtonSettingsValidationMessage, Resources.BagButtonSettingsValidationCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, PlayerPanel.RightToLeftOptions); this.DialogResult = DialogResult.None; return; } this._CurrentBagButton.Sack.IsModified = true; if (dispmode == BagButtonDisplayMode.Default) { // Reset to default settings this._CurrentBagButton.OnBitmap = Resources.inventorybagup01; this._CurrentBagButton.OffBitmap = Resources.inventorybagdown01; this._CurrentBagButton.OverBitmap = Resources.inventorybagover01; this._CurrentBagButton.Sack.BagButtonIconInfo = null; } else { // New settings var save = new BagButtonIconInfo() { DisplayMode = dispmode, Label = this.scalingTextBoxLabel.Text.Trim(), Off = this.pictureBoxOff.Image.Tag as RecordId, On = this.pictureBoxOn.Image.Tag as RecordId, Over = this.pictureBoxOver?.Image?.Tag as RecordId, }; this._CurrentBagButton.Sack.BagButtonIconInfo = save; this._CurrentBagButton.ApplyIconInfo(this._CurrentBagButton.Sack); } this.DialogResult = DialogResult.OK; this.Close(); } private BagButtonDisplayMode GetDisplayMode() { var val = BagButtonDisplayMode.Default; if (this.scalingRadioButtonDefaultIcon.Checked) return val; if (this.scalingRadioButtonCustomIcon.Checked) val |= BagButtonDisplayMode.CustomIcon; if (this.scalingCheckBoxLabel.Checked) val |= BagButtonDisplayMode.Label; if (this.scalingCheckBoxNumber.Checked) val |= BagButtonDisplayMode.Number; return val; } private void cancelButton_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } private void checkBoxLabel_CheckedChanged(object sender, EventArgs e) { this.scalingTextBoxLabel.Enabled = this.scalingCheckBoxLabel.Checked; if (!this.scalingTextBoxLabel.Enabled) this.scalingTextBoxLabel.Text = string.Empty; } private void scalingRadioButtonDefaultIcon_CheckedChanged(object sender, EventArgs e) { if (this.scalingRadioButtonDefaultIcon.Checked) { this.scalingCheckBoxLabel.Checked = this.scalingCheckBoxNumber.Checked = false; this.pictureBoxOn.Image = Resources.inventorybagup01; this.pictureBoxOff.Image = this.pictureBoxSimple.Image = Resources.inventorybagdown01; this.pictureBoxOver.Image = Resources.inventorybagover01; } } } }
using Newtonsoft.Json; using QDot.Infraestructure.Models; using QDot.Infraestructure.Repository.Interface; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Options; using QDot.Infraestructure.Configuration; namespace QDot.Infraestructure.Repository { public class DeveloperRepository : IRepository<Developer> { private readonly InfraestructureSettings _infraestructureSettings; public DeveloperRepository(IOptions<InfraestructureSettings> optionsAccessor) { _infraestructureSettings = optionsAccessor.Value; } #region Operations /// <summary> /// Get all developers /// </summary> /// <returns>Developers with skills</returns> public async Task<IEnumerable<Developer>> GetAllAsync() { var jsonText = await _GetJsonDevelopersAsync(); //Json.NET does not have a real async method var allDevelopers = JsonConvert.DeserializeObject<List<Developer>>(jsonText); return allDevelopers; } #endregion #region Helpers /// <summary> /// Read developers json file /// </summary> /// <returns>Json file with developer data</returns> private async Task<string> _GetJsonDevelopersAsync() { //TODO: Remove static dependency on File when IO abstractions is nuget available for dotnet core for testability //https://github.com/joaope/System.IO.Abstractions.Core using (var reader = File.OpenText(_infraestructureSettings.DeveloperPath)) { return await reader.ReadToEndAsync(); } } #endregion } }
using Hybrid.Domain.Entities; using System; namespace AspNetCoreSample.Models.Defaut { public class Default : Entity<Guid> { public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace SocketAsyncLib { public class SocketAsyncServer { private IPAddress _ipAddress; private int _port; private TcpListener _tcpListener; // tcp 연결 쉽게 해주는 helper class private readonly List<TcpClient> _clients; public EventHandler<ConnectedEventArgs> RaiseClientConnectedEvent; public EventHandler<TextReceivedEventArgs> RaiseTextReceivedEvent; public EventHandler<DisconnectedEventArgs> RaiseClientDisconnectedEvent; public bool _keepRunning { get; set; } public SocketAsyncServer() { _clients = new List<TcpClient>(); } protected virtual void OnRaiseClientConnectedEvent(ConnectedEventArgs e) { RaiseClientConnectedEvent?.Invoke(this, e); } protected virtual void OnRaiseTextReceivedEvent(TextReceivedEventArgs e) { RaiseTextReceivedEvent?.Invoke(this, e); } protected virtual void OnRaiseClientDisconnectedEvent(DisconnectedEventArgs e) { RaiseClientDisconnectedEvent?.Invoke(this, e); } public async void StartListeningForIncomingConnection(IPAddress ipAddress = null, int port = 50001) { SetConnectionVariables(ipAddress, port); _tcpListener = new TcpListener(_ipAddress, _port); try { _tcpListener.Start(); _keepRunning = true; while (_keepRunning) { var returnedByAccept = await _tcpListener.AcceptTcpClientAsync(); _clients.Add(returnedByAccept); Console.WriteLine($"Client({_clients.Count}) connected successfully: {returnedByAccept}"); TakeCareOfTcpClient(returnedByAccept); var args = new ConnectedEventArgs(returnedByAccept.Client.RemoteEndPoint.ToString()); OnRaiseClientConnectedEvent(args); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } private async void TakeCareOfTcpClient(TcpClient client) { NetworkStream stream = null; StreamReader reader = null; var clientEndPoint = client.Client.RemoteEndPoint.ToString(); try { stream = client.GetStream(); reader = new StreamReader(stream); var buffer = new char[64]; while (_keepRunning) { Console.WriteLine("***Ready to read***"); var length = await reader.ReadAsync(buffer, 0, buffer.Length); Console.WriteLine($"Return: {length}"); if (length == 0) { OnRaiseClientDisconnectedEvent(new DisconnectedEventArgs(clientEndPoint)); RemoveClient(client); Console.WriteLine("Socket is disconnected"); break; } string receivedMessage = new string(buffer, 0, length); Console.WriteLine($"***Received: {receivedMessage}"); OnRaiseTextReceivedEvent(new TextReceivedEventArgs(clientEndPoint, receivedMessage)); Array.Clear(buffer, 0, buffer.Length); } } catch (Exception ex) { RemoveClient(client); Console.WriteLine(ex.ToString()); } //finally //{ // if (reader != null) // { // reader.Close(); // reader.Dispose(); // } // if (stream != null) // { // stream.Close(); // stream.Dispose(); // } //} } private void RemoveClient(TcpClient client) { if (_clients.Contains(client)) { _clients.Remove(client); Console.WriteLine($"Client removed, Count: {_clients.Count()}"); } } private void SetConnectionVariables(IPAddress ipAddress, int port) { if (ipAddress == null) _ipAddress = IPAddress.Any; else _ipAddress = ipAddress; if (port <= 0 || port > 65535) _port = 50001; else _port = port; Console.WriteLine($"IP Address: {_ipAddress} - Port: {_port}"); } public async void SendToAll(string message) { if (string.IsNullOrWhiteSpace(message)) { return; } try { var bufferMessage = Encoding.ASCII.GetBytes(message); _clients.ForEach(c => c.GetStream().WriteAsync(bufferMessage, 0, bufferMessage.Length)); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public void StopServer() { try { _tcpListener?.Stop(); _clients.ForEach(c => c.Close()); _clients.Clear(); } catch (Exception ex) { Console.WriteLine(ex); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; using WindowsCuotasApp.Clases; namespace WindowsCuotasApp { public partial class FormCancelarDeuda : MetroFramework.Forms.MetroForm { GestorDGV gestorDGV; GestorAfiliados ga; private ArrayList listaMesesID = new ArrayList(); int dni = 0; public FormCancelarDeuda() { InitializeComponent(); gestorDGV = new GestorDGV(); ga = new GestorAfiliados(); } private void FormCancelarDeuda_Load(object sender, EventArgs e) { } private void soloNumeros(object sender, KeyPressEventArgs e) { if (!(char.IsNumber(e.KeyChar)) && (e.KeyChar != (char)Keys.Back)) { MessageBox.Show("Solo números", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.Handled = true; return; } } private void txtDni_KeyPress(object sender, KeyPressEventArgs e) { soloNumeros(sender,e); } private void SelecccionDeMesesAPagar() { int c = 0; foreach (DataGridViewRow row in dataGridView1.Rows) { bool check = Convert.ToBoolean(row.Cells[2].Value) ; if (check) { listaMesesID.Clear(); listaMesesID.Add(Convert.ToInt32(row.Cells[0].Value)); c++; } } if(listaMesesID.Count>0) { btnContinuar.Enabled = true; btnCancelar.Enabled = true; dni = Convert.ToInt32( txtDni.Text); } label2.Text = c.ToString(); if (label2.Text.Equals("0")) { btnContinuar.Enabled = false; btnCancelar.Enabled = false; } } private void button1_Click_1(object sender, EventArgs e) { try { if (!string.IsNullOrEmpty(txtDni.Text)) { int dni = Convert.ToInt32(txtDni.Text); gestorDGV.cargarDataGrid(dataGridView1, "SP_FILTRO_AFIL_SEDE " + dni); gestorDGV.efectosDGV(dataGridView1); DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn(); col.ReadOnly = false; dataGridView1.Columns.Add(col); foreach (DataGridViewColumn column in dataGridView1.Columns) { column.SortMode = DataGridViewColumnSortMode.NotSortable; } dataGridView1.Columns[0].ReadOnly = true; dataGridView1.Columns[1].ReadOnly = true; } } catch (Exception) { MetroFramework.MetroMessageBox.Show(this, "Error en la consulta posibles causas: " + "\n" + " No existe dni del afiliado " + "\n" + " El afiliado paga por otro medio " + "\n" + " Posible error en la conexión. ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); dataGridView1.DataSource = null; } } private void btnCargarDatos_Click(object sender, EventArgs e) => SelecccionDeMesesAPagar(); private void btnConfirmarPago_Click(object sender, EventArgs e) { dni = Convert.ToInt32(txtDni.Text); try { if (MetroFramework.MetroMessageBox.Show(this, "Desea registrar el pago del afiliado, dni nro: " + dni + "?", "Confirmación de pago", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { if (dni > 0) { foreach (Object objMes in listaMesesID) { int m = (Int32)objMes; ga.TransaccionCancelarDeuda(m,dni); } this.Dispose(); } } } catch (Exception) { } } private void habilitarControles(bool x) { txtDni.Enabled = x; btnCargarDatos.Enabled = x; dataGridView1.Enabled = x; btnContinuar.Enabled = x; btnConfirmarPago.Enabled = !x; button1.Enabled = x; } private void btnContinuar_Click(object sender, EventArgs e) { if (listaMesesID.Count > 0) { if (MetroFramework.MetroMessageBox.Show(this, "Desea continuar con la cancelación de la deuda de el afiliado, dni nro: " + dni + "?", "Cancelación deuda", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { habilitarControles(false); } } } private void btnCancelar_Click(object sender, EventArgs e) { if (MetroFramework.MetroMessageBox.Show(this, "Desea cancelar y volver a iniciar?", "Cancelar operación", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { this.Dispose(); FormCancelarDeuda n = new FormCancelarDeuda(); n.ShowDialog(); } } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { DataGridViewCheckBoxCell cell = this.dataGridView1.CurrentCell as DataGridViewCheckBoxCell; if (cell != null && !cell.ReadOnly) { cell.Value = cell.Value == null || !((bool)cell.Value); SelecccionDeMesesAPagar(); } } } }
using Microsoft.Xna.Framework; using Terraria; using Terraria.ModLoader; namespace Malum.Tiles { public class AzuriteOre : ModTile { public override void SetDefaults() { Main.tileSolid[Type] = true; Main.tileMergeDirt[Type] = true; drop = mod.ItemType("AzuriteOre"); AddMapEntry(new Color(0, 125, 150)); minPick = 35; } } }
#r "Newtonsoft.Json" using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Primitives; using Newtonsoft.Json; using System; using System.IO; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Net.Http; using Newtonsoft.Json.Linq; using System.Text; using System.Xml.Linq; public static async Task<IActionResult> Run(HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string serviceUrl = req.Query["url"]; if (string.IsNullOrEmpty(serviceUrl)){ return new BadRequestObjectResult(String.Format("No ArcGIS Online route layer url.")); } if (!serviceUrl.Contains("FeatureServer")){ return new BadRequestObjectResult(String.Format("The url {0} is not to an ArcGIS feature service.",serviceUrl)); } serviceUrl = serviceUrl.Substring(0,serviceUrl.LastIndexOf("FeatureServer"))+"FeatureServer"; string serviceInfoUrl = serviceUrl+"/info/itemInfo?f=pjson"; string serviceQueryUrl = serviceUrl+"?f=pjson"; string where = req.Query["where"]; where = where ?? "1=1"; string pointQueryUrl = serviceUrl+"/0/query?where="+where+"&outSR=4326&outFields=*&f=pjson"; string routeQueryUrl = serviceUrl+"/2/query?where="+where+"&outSR=4326&outFields=*&f=pjson"; HttpClient client = new HttpClient(); // get the name of the route var result = await client.GetAsync(serviceInfoUrl); string resultContent = await result.Content.ReadAsStringAsync(); var details = JObject.Parse(resultContent); string title = (string)details["title"]; //String uri = serviceQueryUrl; result = await client.GetAsync(serviceQueryUrl); resultContent = await result.Content.ReadAsStringAsync(); details = JObject.Parse(resultContent); JArray layers = (JArray)details["layers"]; if(layers.Count != 4){ return new BadRequestObjectResult(String.Format("{0} is not an ArcGIS route feature service.",title)); } string capabilities = (string)details["capabilities"]; if (!capabilities.Contains("Query")){ return new BadRequestObjectResult(String.Format("{0} does not allow Querying.",title)); } JObject pointLayer = (JObject)layers[0]; if((string)pointLayer["geometryType"] != "esriGeometryPoint"){ return new BadRequestObjectResult(String.Format("Layer {1} of {0} is not a point layer.",title,(string)pointLayer["name"])); } JObject routeLayer = (JObject)layers[2]; if((string)routeLayer["geometryType"] != "esriGeometryPolyline"){ return new BadRequestObjectResult(String.Format("Layer {1} of {0} is not a polyline.",title,(string)routeLayer["name"])); } // get the points result = await client.GetAsync(pointQueryUrl); resultContent = await result.Content.ReadAsStringAsync(); details = JObject.Parse(resultContent); JArray points = (JArray)details["features"]; // get the route result = await client.GetAsync(routeQueryUrl); resultContent = await result.Content.ReadAsStringAsync(); details = JObject.Parse(resultContent); JArray lines = (JArray)details["features"]; //string routeName = title; //XElement g = new XElement("gpx"); XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; XNamespace gpx1 = "http://www.topografix.com/GPX/1/1/"; XNamespace gpx2 = "http://www.topografix.com/GPX/1/1/gpx.xsd"; XElement g = new XElement(gpx1+"gpx", new XAttribute("creator","http://www.cagegis.com/"), new XAttribute("version","1.1"), new XAttribute(XNamespace.Xmlns+"xsi",xsi.NamespaceName), new XAttribute(xsi+"schemaLocation",gpx1.NamespaceName + " " + gpx2.NamespaceName)); g.Add(new XElement("metadata", new XElement("name", title) )); XDocument d = new XDocument(new XDeclaration("1.0", "utf-8", "true"),g); //d.Add(g); foreach (JObject f in points.Children<JObject>()){ string wptName = (string)f["attributes"]["Name"]; if(string.IsNullOrEmpty(wptName)||string.IsNullOrWhiteSpace(wptName)||wptName=="null"){ wptName = title + " Wpt " + (int)f["attributes"]["Sequence"]; } XElement w = new XElement("wpt", new XAttribute("lat",(double)f["geometry"]["y"]), new XAttribute("lon",(double)f["geometry"]["x"]), new XElement("name",wptName), new XElement("desc",(string)f["attributes"]["DisplayText"]) ); g.Add(w); //routeGeom = (JObject)f["geometry"]; } foreach (JObject f in lines.Children<JObject>()){ XElement t = new XElement("trk", new XElement("name",title), new XElement("desc",(string)f["attributes"]["RouteName"]) ); double totalMinutes = (double)f["attributes"]["TotalMinutes"]; double meters = (double)f["attributes"]["TotalMeters"]; int miles = Convert.ToInt32(meters/1609); int kilometers = Convert.ToInt32(meters/1000); int hours = (int)(totalMinutes/60); int minutes = Convert.ToInt32(totalMinutes-(hours*60)); string costs =string.Format("Route length: {0} mi ({1} km); {2} hrs, {3} min.",miles,kilometers,hours,minutes); t.Add(new XElement("cmt",costs)); g.Add(t); JArray routeGeom = (JArray)f["geometry"]["paths"]; foreach (JArray path in routeGeom.Children<JArray>()){ XElement s = new XElement("trkseg"); foreach (JArray point in path.Children<JArray>()){ s.Add(new XElement("trkpt", new XAttribute("lat",point[1].ToString()), new XAttribute("lon",point[0].ToString()) )); } t.Add(s); } } byte[] dataBytes = Encoding.ASCII.GetBytes(d.ToString()); client = null; FileResult file = new FileContentResult(dataBytes,"application/octet-stream"); file.FileDownloadName = title+".gpx"; return (ActionResult)file; }
namespace angserver.Models { public class TestModel { public string Data { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using DAL; using BUS; using DevExpress.Utils.Win; using DevExpress.XtraEditors; using DevExpress.XtraBars; using GUI.Properties; using ControlLocalizer; namespace GUI { public partial class f_themdoituong : Form { KetNoiDBDataContext db = new KetNoiDBDataContext(); t_doituong dt = new t_doituong(); public f_themdoituong() { InitializeComponent(); // This line of code is generated by Data Source Configuration Wizard txtnhom.Properties.DataSource = new DAL.KetNoiDBDataContext().nhomdoituongs; // This line of code is generated by Data Source Configuration Wizard txtmanv.Properties.DataSource = new DAL.KetNoiDBDataContext().accounts; txtmadv.Properties.DataSource = new DAL.KetNoiDBDataContext().donvis; } private void f_themdoituong_Load(object sender, EventArgs e) { LanguageHelper.Translate(this); LanguageHelper.Translate(barManager1); this.Text = LanguageHelper.TranslateMsgString("." + Name + "_title", "Thêm Đối Tượng").ToString(); changeFont.Translate(this); changeFont.Translate(barManager1); if (Biencucbo.hdmanhanhdt == 1) { var lst2 = (from a in db.doituongs where a.id == Biencucbo.madtnhanh select a).ToList(); if (lst2.Count() == 0) { txtid.Text = Biencucbo.madtnhanh; txtten.Text = Biencucbo.tennhanhdt; Biencucbo.hddt = 0; } else { Biencucbo.hddt = 1; Biencucbo.ma = Biencucbo.madtnhanh; } } if (Biencucbo.hddt == 1) { txtid.Enabled = false; var Lst = (from dt in db.doituongs where dt.id == Biencucbo.ma select dt).ToList(); txtid.DataBindings.Clear(); txtten.DataBindings.Clear(); txtnhom.DataBindings.Clear(); txtloai.DataBindings.Clear(); txtdc.DataBindings.Clear(); txtmsthue.DataBindings.Clear(); txtdt.DataBindings.Clear(); txtdd.DataBindings.Clear(); txtemail.DataBindings.Clear(); txtfax.DataBindings.Clear(); txttk.DataBindings.Clear(); txtnh.DataBindings.Clear(); txtmanv.DataBindings.Clear(); txtmadv.DataBindings.Clear(); txtid.DataBindings.Add("text", Lst, "id"); txtid.Text.Trim(); txtmanv.DataBindings.Add("text", Lst, "manv".Trim()); txtmadv.DataBindings.Add("text", Lst, "madv".Trim()); txtten.DataBindings.Add("text", Lst, "ten".Trim()); txtnhom.DataBindings.Add("text", Lst, "nhom".Trim()); txtloai.DataBindings.Add("text", Lst, "loai".Trim()); txtdc.DataBindings.Add("text", Lst, "diachi".Trim()); txtmsthue.DataBindings.Add("text", Lst, "msthue".Trim()); txtdt.DataBindings.Add("text", Lst, "dienthoai".Trim()); txtdd.DataBindings.Add("text", Lst, "dd".Trim()); txtemail.DataBindings.Add("text", Lst, "email".Trim()); txtfax.DataBindings.Add("text", Lst, "fax".Trim()); txttk.DataBindings.Add("text", Lst, "taikhoan".Trim()); txtnh.DataBindings.Add("text", Lst, "nganhang".Trim()); } } private void txtnhom_Popup(object sender, EventArgs e) { IPopupControl popupControl = sender as IPopupControl; SimpleButton button = new SimpleButton() { Image = Resources.icons8_Add_File_16, Text = "Thêm mới", BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder }; button.Click += new EventHandler(button_Click); button.Location = new Point(5, popupControl.PopupWindow.Height - button.Height - 5); popupControl.PopupWindow.Controls.Add(button); button.BringToFront(); } public void button_Click(object sender, EventArgs e) { f_themnhomdoituong frm = new f_themnhomdoituong(); frm.ShowDialog(); txtnhom.Properties.DataSource = new KetNoiDBDataContext().nhomdoituongs; } private void btnhuy_ItemClick(object sender, ItemClickEventArgs e) { this.Close(); } private void luu_ItemClick(object sender, ItemClickEventArgs e) { if (txtid.Text == "" || txtten.Text == "" || txtnhom.Text == "") { Lotus.MsgBox.ShowWarningDialog("Thông tin chưa đầy đủ - Vui lòng kiểm tra lại!"); } else { if (Biencucbo.hddt == 0) { //khong cho trung ID va Ten var Lst = (from dt in db.doituongs where dt.id == txtid.Text || dt.ten == txtten.Text select dt).ToList(); if (Lst.Count == 1) { Lotus.MsgBox.ShowErrorDialog("Đối tượng này đã tồn tại, Vui Lòng Kiểm tra Lại"); } else { if(txtmanv.Text !="") { var lst2 = from a in db.doituongs where a.manv == txtmanv.Text select a; if( lst2.Count() !=0) { Lotus.MsgBox.ShowErrorDialog("Mã nhân viên không được phép trùng, Vui Lòng Kiểm tra Lại"); return; } } if (txtmadv.Text != "") { var lst2 = from a in db.doituongs where a.madv == txtmadv.Text select a; if (lst2.Count() != 0) { Lotus.MsgBox.ShowErrorDialog("Mã đơn vị không được phép trùng, Vui Lòng Kiểm tra Lại"); return; } } dt.moi(txtid.Text.Trim(), txtten.Text, txtnhom.Text, txtloai.Text, txtdc.Text, txtmsthue.Text, txtdt.Text, txtemail.Text, txtfax.Text, txtdd.Text, txttk.Text, txtnh.Text,txtmanv.Text, txtmadv.Text); this.Close(); } } else { var Lst = (from l in db.doituongs where l.ten == txtten.Text && l.id != txtid.Text select l).ToList(); if (Lst.Count == 1) { Lotus.MsgBox.ShowErrorDialog("Đối tượng này đã tồn tại, Vui Lòng Kiểm tra Lại"); } else { dt.sua(txtid.Text, txtten.Text, txtnhom.Text, txtloai.Text, txtdc.Text, txtmsthue.Text, txtdt.Text, txtemail.Text, txtfax.Text, txtdd.Text, txttk.Text, txtnh.Text,txtmanv.Text, txtmadv.Text); this.Close(); } } } } } }
using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Core.Globalization; namespace DoE.Quota.Web.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim(GlobalConstants.CLAIM_NAME, string.IsNullOrEmpty(this.C_Name) ? " " : this.C_Name)); userIdentity.AddClaim(new Claim(GlobalConstants.CLAIM_FIRSTNAME, string.IsNullOrEmpty(this.C_FirstName) ? " " : this.C_FirstName)); userIdentity.AddClaim(new Claim(GlobalConstants.CLAIM_SURNAME, string.IsNullOrEmpty(this.C_Surname) ? " " : this.C_Surname)); userIdentity.AddClaim(new Claim(GlobalConstants.CLAIM_SUBID, string.IsNullOrEmpty(this.C_SubId) ? " " : this.C_SubId)); userIdentity.AddClaim(new Claim(GlobalConstants.CLAIM_ENTITY, string.IsNullOrEmpty(this.C_Entity) ? " " : this.C_Entity)); return userIdentity; } public string C_Name { get; set; } public string C_FirstName { get; set; } public string C_Surname { get; set; } public string C_SubId { get; set; } public string C_Entity { get; set; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WF.SDK.Models.Internal { [Serializable] public class ContactItem { public Guid Id; public string Title; public string FirstName; public string LastName; public string CompanyName; public string Email; public string Fax; public string MobilePhone; public string Phone; public string Type; public Guid? OwnerId; public ContactItem() { } } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Yandex.Dialogs.Models { [JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class Session { public string SessionId { get; set; } public int MessageId { get; set; } public string UserId { get; set; } public User User { get; set; } public Application Application { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WUIClient.Gizmos; using WUIShared.Objects; namespace WUIClient.Tools { public class MoveTool : Tool { private MoveGizmo gizmo; private GameObject selected; public MoveTool() { gizmo = new MoveGizmo(); } protected override void OnSelect() { } protected override void OnUpdate() { if(WMouse.LeftMouseClick()) { GameObject obj = WMouse.GetGameObjectUnderneathMouse(Game1.instance.world, false); if (obj != null) { selected = obj; if (gizmo.Parent == null) Game1.gizmoWorld.AddChild(gizmo); gizmo.transform.Position = obj.transform.Position + obj.transform.Size / 2; } } if (WMouse.RightMouseClick()) { selected = null; gizmo.Remove(); } if(selected != null) { selected.transform.Position = gizmo.transform.Position - selected.transform.Size/2; } } protected override void OnDeselect() { selected = null; gizmo.Remove(); } } }
using System; using System.ComponentModel; using System.Reactive.Linq; using System.Windows.Input; using Acr.UserDialogs; using Humanizer; using Plugin.HttpTransferTasks; using Xamarin.Forms; namespace Sample { public class HttpTaskViewModel : ViewModel { readonly IHttpTask task; IDisposable taskSub; public HttpTaskViewModel(IHttpTask task) { this.task = task; this.Cancel = new Command(task.Cancel); this.MoreInfo = new Command(() => { if (task.Status == TaskStatus.Error) UserDialogs.Instance.Alert(task.Exception.ToString(), "Error"); }); this.taskSub = Observable .Create<IHttpTask>(ob => { var handler = new PropertyChangedEventHandler((sender, args) => ob.OnNext(this.task)); this.task.PropertyChanged += handler; return () => this.task.PropertyChanged -= handler; }) .Sample(TimeSpan.FromSeconds(1)) .Subscribe(x => Device.BeginInvokeOnMainThread(() => this.OnPropertyChanged(String.Empty))); } public string Identifier => this.task.Identifier; public bool IsUpload => this.task.IsUpload; public TaskStatus Status => this.task.Status; public string Uri => this.task.Configuration.Uri; public decimal PercentComplete => this.task.PercentComplete; public string TransferSpeed => Math.Round(this.task.BytesPerSecond.Bytes().Kilobytes, 2) + " Kb/s"; public string EstimateMinsRemaining => Math.Round(this.task.EstimatedCompletionTime.TotalMinutes, 1) + " min(s)"; public ICommand Cancel { get; } public ICommand MoreInfo { get; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Dominio { public class ResumoFinanceiro { public string NM_RAZAO_SOCIAL { get; set; } public string NU_CNPJ_FILIAL { get; set; } public string TP_RECEITA { get; set; } public List<dynamic> ANOS_RECEITA { get; set; } = new List<dynamic>(); public string Data { get { var dados = new ArrayList(); foreach (var item in ANOS_RECEITA) { dados.Add(new { ano = item.Key, Value = item.Value != null ? Convert.ToDecimal(item.Value) : 0 }); } return JsonConvert.SerializeObject(dados.ToArray()); } } } }
using Enrollment.XPlatform.Flow.Settings.Screen; using Enrollment.XPlatform.ViewModels.SearchPage; using System; using Xamarin.Forms; namespace Enrollment.XPlatform.Views.Factories { public class SearchPageFactory : ISearchPageFactory { private readonly Func<SearchPageViewModelBase, SearchPageViewCS> _getPage; private readonly Func<ScreenSettingsBase, SearchPageViewModelBase> _getViewModel; public SearchPageFactory( Func<SearchPageViewModelBase, SearchPageViewCS> getPage, Func<ScreenSettingsBase, SearchPageViewModelBase> getViewModel) { _getPage = getPage; _getViewModel = getViewModel; } public Page CreatePage(ScreenSettingsBase screenSettings) => _getPage ( _getViewModel(screenSettings) ); } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.MosaTypeSystem; using System.Collections.Generic; using System.Diagnostics; namespace Mosa.Compiler.Framework.Stages { /// <summary> /// Inline Stage /// </summary> public class InlineStage : BaseMethodCompilerStage { private readonly Counter InlineCount = new Counter("InlineStage.MethodsWithInlinedCallSites"); private readonly Counter InlinedCallSitesCount = new Counter("InlineStage.InlinedCallSites"); private Dictionary<MosaMethod, KeyValuePair<MethodData, InlineMethodData>> cache; protected override void Initialize() { Register(InlineCount); Register(InlinedCallSitesCount); } protected override void Finish() { if (cache.Count != 0) { cache = null; } } protected override void Run() { var trace = CreateTraceLog("Inlined"); if (cache == null || cache.Count != 0) { cache = new Dictionary<MosaMethod, KeyValuePair<MethodData, InlineMethodData>>(); } int callSiteCount = 0; // find all call sites var callSites = new List<InstructionNode>(); foreach (var block in BasicBlocks) { for (var node = block.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmptyOrNop) continue; if (node.Instruction != IRInstruction.CallStatic) continue; callSites.Add(node); } } foreach (var callSiteNode in callSites) { var invokedMethod = callSiteNode.Operand1.Method; // don't inline self if (invokedMethod == Method) continue; Debug.Assert(callSiteNode.Operand1.IsSymbol); (MethodData Callee, InlineMethodData InlineMethodData) result = GetCalleeData(invokedMethod); //Debug.WriteLine($"{MethodScheduler.GetTimestamp()} - Inline: {(inlineMethodData.IsInlined ? "Inlined" : "NOT Inlined")} [{MethodData.Version}] {Method} -> [{inlineMethodData.Version}] {callee.Method}"); //DEBUGREMOVE if (!result.InlineMethodData.IsInlined) continue; Inline(callSiteNode, result.InlineMethodData.BasicBlocks); callSiteCount++; trace?.Log($" -> Inlined: [{result.Callee.Version}] {result.Callee.Method}"); //Debug.WriteLine($" -> Inlined: [{callee.Version}] {callee.Method}");//DEBUGREMOVE } InlineCount.Set(1); InlinedCallSitesCount.Set(callSiteCount); } private (MethodData, InlineMethodData) GetCalleeData(MosaMethod invokedMethod) { if (cache.TryGetValue(invokedMethod, out KeyValuePair<MethodData, InlineMethodData> found)) { return (found.Key, found.Value); } else { var callee = MethodCompiler.Compiler.GetMethodData(invokedMethod); var inlineMethodData = callee.GetInlineMethodDataForUseBy(Method); cache.Add(invokedMethod, new KeyValuePair<MethodData, InlineMethodData>(callee, inlineMethodData)); return (callee, inlineMethodData); } } protected void Inline(InstructionNode callSiteNode, BasicBlocks blocks) { var mapBlocks = new Dictionary<BasicBlock, BasicBlock>(blocks.Count); var map = new Dictionary<Operand, Operand>(); var nextBlock = Split(callSiteNode); // create basic blocks foreach (var block in blocks) { var newBlock = CreateNewBlock(); mapBlocks.Add(block, newBlock); } // copy instructions foreach (var block in blocks) { var newBlock = mapBlocks[block]; for (var node = block.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmpty) continue; if (node.Instruction == IRInstruction.Prologue) continue; if (node.Instruction == IRInstruction.Epilogue) { newBlock.BeforeLast.Insert(new InstructionNode(IRInstruction.Jmp, nextBlock)); continue; } if (node.Instruction == IRInstruction.SetReturn32 || node.Instruction == IRInstruction.SetReturn64 || node.Instruction == IRInstruction.SetReturnObject || node.Instruction == IRInstruction.SetReturnR4 || node.Instruction == IRInstruction.SetReturnR8 || node.Instruction == IRInstruction.SetReturnCompound) { if (callSiteNode.Result != null) { var newOperand = Map(node.Operand1, map, callSiteNode); BaseInstruction moveInstruction = null; if (node.Instruction == IRInstruction.SetReturn32) moveInstruction = IRInstruction.Move32; else if (node.Instruction == IRInstruction.SetReturn64) moveInstruction = IRInstruction.Move64; else if (node.Instruction == IRInstruction.SetReturnObject) moveInstruction = IRInstruction.MoveObject; else if (node.Instruction == IRInstruction.SetReturnR4) moveInstruction = IRInstruction.MoveR4; else if (node.Instruction == IRInstruction.SetReturnR8) moveInstruction = IRInstruction.MoveR8; else if (node.Instruction == IRInstruction.SetReturnCompound) moveInstruction = IRInstruction.MoveCompound; Debug.Assert(moveInstruction != null); var moveNode = new InstructionNode(moveInstruction, callSiteNode.Result, newOperand); newBlock.BeforeLast.Insert(moveNode); } continue; } var newNode = new InstructionNode(node.Instruction, node.OperandCount, node.ResultCount) { ConditionCode = node.ConditionCode, InvokeMethod = node.InvokeMethod, MosaField = node.MosaField, MosaType = node.MosaType, Label = callSiteNode.Label, }; if (node.BranchTargets != null) { // copy targets foreach (var target in node.BranchTargets) { newNode.AddBranchTarget(mapBlocks[target]); } } // copy results for (int i = 0; i < node.ResultCount; i++) { var op = node.GetResult(i); var newOp = Map(op, map, callSiteNode); newNode.SetResult(i, newOp); } // copy operands for (int i = 0; i < node.OperandCount; i++) { var op = node.GetOperand(i); var newOp = Map(op, map, callSiteNode); newNode.SetOperand(i, newOp); } // copy other if (node.MosaType != null) newNode.MosaType = node.MosaType; if (node.MosaField != null) newNode.MosaField = node.MosaField; UpdateParameterInstructions(newNode); newBlock.BeforeLast.Insert(newNode); } } var prologue = mapBlocks[blocks.PrologueBlock]; var callSiteOperands = callSiteNode.GetOperands(); if (callSiteOperands.Count > 1) { var context = new Context(prologue); for (int i = 1; i < callSiteOperands.Count; i++) { var operand = callSiteOperands[i]; if (!operand.IsVirtualRegister || operand.Low == null) continue; context.AppendInstruction(IRInstruction.GetLow32, operand.Low, operand); context.AppendInstruction(IRInstruction.GetHigh32, operand.High, operand); } } callSiteNode.SetInstruction(IRInstruction.Jmp, prologue); } private static void UpdateParameterInstructions(InstructionNode newNode) { var instruction = newNode.Instruction; if (instruction == IRInstruction.LoadParamR4) { newNode.Instruction = IRInstruction.MoveR4; } else if (instruction == IRInstruction.LoadParamR8) { newNode.Instruction = IRInstruction.MoveR8; } else if (instruction == IRInstruction.LoadParam32 || instruction == IRInstruction.LoadParamSignExtend8x32 || instruction == IRInstruction.LoadParamSignExtend16x32 || instruction == IRInstruction.LoadParamZeroExtend8x32 || instruction == IRInstruction.LoadParamZeroExtend16x32) { newNode.Instruction = IRInstruction.Move32; } else if (instruction == IRInstruction.LoadParamObject) { newNode.Instruction = IRInstruction.MoveObject; } else if (instruction == IRInstruction.LoadParam64 || instruction == IRInstruction.LoadParamSignExtend8x64 || instruction == IRInstruction.LoadParamSignExtend16x64 || instruction == IRInstruction.LoadParamSignExtend32x64 || instruction == IRInstruction.LoadParamZeroExtend8x64 || instruction == IRInstruction.LoadParamZeroExtend16x64 || instruction == IRInstruction.LoadParamZeroExtend32x64) { newNode.Instruction = IRInstruction.Move64; } else if (instruction == IRInstruction.StoreParam8 || instruction == IRInstruction.StoreParam16 || instruction == IRInstruction.StoreParam32) { newNode.SetInstruction(IRInstruction.Move32, newNode.Operand1, newNode.Operand2); } else if (instruction == IRInstruction.StoreParamObject) { newNode.SetInstruction(IRInstruction.MoveObject, newNode.Operand1, newNode.Operand2); } else if (instruction == IRInstruction.StoreParam64) { newNode.SetInstruction(IRInstruction.Move64, newNode.Operand1, newNode.Operand2); } else if (instruction == IRInstruction.StoreParamR4) { newNode.SetInstruction(IRInstruction.MoveR4, newNode.Operand1, newNode.Operand2); } else if (instruction == IRInstruction.StoreParamR8) { newNode.SetInstruction(IRInstruction.MoveR8, newNode.Operand1, newNode.Operand2); } else if (instruction == IRInstruction.StoreParamCompound) { newNode.Instruction = IRInstruction.MoveCompound; } else if (instruction == IRInstruction.LoadParamCompound) { newNode.Instruction = IRInstruction.MoveCompound; } } private Operand Map(Operand operand, Dictionary<Operand, Operand> map, InstructionNode callSiteNode) { if (operand == null) return null; if (map.TryGetValue(operand, out Operand mappedOperand)) { return mappedOperand; } if (operand.IsSymbol) { if (operand.IsString) { // FUTURE: explore operand re-use mappedOperand = Operand.CreateStringSymbol(operand.Name, operand.StringData, operand.Type.TypeSystem); } else if (operand.Method != null) { // FUTURE: explore operand re-use mappedOperand = Operand.CreateSymbolFromMethod(operand.Method, operand.Type.TypeSystem); } else if (operand.Name != null) { // FUTURE: explore operand re-use mappedOperand = Operand.CreateSymbol(operand.Type, operand.Name); } } else if (operand.IsParameter) { mappedOperand = callSiteNode.GetOperand(operand.Index + 1); } else if (operand.IsStackLocal) { mappedOperand = MethodCompiler.AddStackLocal(operand.Type, operand.IsPinned); } else if (operand.IsVirtualRegister) { mappedOperand = AllocateVirtualRegister(operand); } else if (operand.IsStaticField) { // FUTURE: explore operand re-use mappedOperand = Operand.CreateStaticField(operand.Field, TypeSystem); } else if (operand.IsCPURegister) { mappedOperand = operand; } else if (operand.IsConstant) { mappedOperand = operand; } Debug.Assert(mappedOperand != null); if (operand.HasLongParent) { MethodCompiler.SplitLongOperand(mappedOperand); if (operand.IsLow) { mappedOperand = mappedOperand.Low; } else if (operand.IsHigh) { mappedOperand = mappedOperand.High; } } map.Add(operand, mappedOperand); return mappedOperand; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Terminal.Interactive; namespace PiconTest { public class DictionaryAppController : IAppController { private readonly IList<Command> _commands; public DictionaryAppController(IList<Command> commands) { _commands = commands; } public Task<object> ExecuteAsync(string code, CancellationToken cancellationToken) { var action = (from c in _commands let match = c.Regex.Match(code) where match.Success select c.GetAction(match)).FirstOrDefault(); if (action == null) { Console.WriteLine("Didn't undestand. Sorry."); return Task.FromResult<object>(null); } return action(); } public Task<List<CompletionData>> GetCompletions(string code, int location) { return Task.FromResult(new List<CompletionData>()); } public Task Reset() { return Task.CompletedTask; } } }
using System; using System.Collections.Generic; using System.Text; namespace dynamic_configuration_parser { public class InvalidKeyException : Exception { } }
using SearchEng.Common.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; namespace SearchEng.Common.AW { /// <summary> /// Data annotations attributes for ProductSubcategory. /// This class won't update by generator. Delete this file to get updated fields. /// </summary> public class ProductSubcategory : IModifiedDate,Irowguid ,INotifyPropertyChanged { public ProductSubcategory() { Products = new HashSet<Product>(); } public Int32 ProductSubcategoryID { get; set; } public Int32 ProductCategoryID { get; set; } public String Name { get; set; } public System.Guid rowguid { get; set; } public DateTime ModifiedDate { get; set; } public bool IsDirty { get; set; } public virtual HashSet<Product> Products { get; set; } public event PropertyChangedEventHandler PropertyChanged; } }
using System; using HW2; namespace BettingPlatformEmulatorTest { class Tets { static void Main(string[] args) { BettingPlatformEmulator bettingPlatform = new BettingPlatformEmulator(); bettingPlatform.Start(); } } }
using System; using System.IO; using System.Linq; using System.Net; using System.Windows.Forms; using Newtonsoft.Json.Linq; namespace KGViewer { public partial class MainForm : Form { //Карточки событий на форме private Card[] Cards; //Текущая страница на форма, максимальная на форме и страница для запроса private int Page, MaxPage, PageAPI; //Ответ на запрос в десериализованном виде private ResponseString resp; //Форма для выбора категорий событий private CategoriesForm cf; //Подстрока категорий для запроса public string categories; public MainForm() { InitializeComponent(); InitializeCards(); InitializeStandarts(); } public void InitializeStandarts() { Page = 1; PageAPI = 0; MaxPage = 0; categories = "&categories="; CheckPageSet(); } /// <summary> /// Инициализация карточек событий /// </summary> private void InitializeCards() { Cards = new Card[9]; for (int i = 0; i < 9; i++) Cards[i] = new Card(); int count = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { CardsLayout.Controls.Add(Cards[count].Table, j, i); count++; } } } private void MainForm_Load(object sender, EventArgs e) { LoadCards(); } /// <summary> /// Подтягивание и загрузка событий на форму /// </summary> private void LoadCards() { int count = 9 * (Page - 1), pos = 0; if (MaxPage == 0) MaxPage = Methods.GetEventsPage(1, categories).Count / 9 + 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (count / 20 + 1 != PageAPI) { PageAPI = count / 20 + 1; resp = Methods.GetEventsPage(PageAPI, categories); } if (count % 20 < resp.Results.Count) LoadEvent(resp.Results[count % 20], pos); else LoadEvent(null, pos); pos++; count++; } } } /// <summary> /// Подтягивание полных данных о событии и запись его в i-ую карточку на форме /// </summary> /// <param name="ev">Информация о событии</param> /// <param name="i">Номер карточки на форме</param> private void LoadEvent(EventShort ev, int i) { //Если нет события - не показываем карточку if (ev == null) { Cards[i].NameLabel.Text = ""; Cards[i].Image.Image = null; Cards[i].DateLabel.Text = ""; Cards[i].Table.Visible = false; return; } else if (!Cards[i].Table.Visible) Cards[i].Table.Visible = true; //Подтягиваем полную информацию о событии (ибо дата только в полной информации) WebRequest request = WebRequest.Create("https://kudago.com/public-api/v1.3/events/" + ev.Id + "/"); WebResponse response = request.GetResponse(); using (StreamReader stream = new StreamReader(response.GetResponseStream())) { string line = stream.ReadLine(); if (line != null) { JObject search = JObject.Parse(line); Card c = Cards[i]; c.Title = Methods.FirstToUpper(search["title"].ToString()); c.StartDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) .AddSeconds(search["dates"].Children()["start"].ToList()[0].ToObject<int>()).ToLocalTime(); c.Description = Methods.CutTags(search["description"].ToString()); c.Body = Methods.CutTags(search["body_text"].ToString()); c.Images = search["images"].Children()["image"].Select(x => x.ToString()).ToList(); c.Age = search["age_restriction"].ToString(); c.Price = search["price"].ToString(); c.NameLabel.Text = c.Title; c.Image.Load(c.Images[0]); c.DateLabel.Text = c.StartDate.ToString(); Hint.SetToolTip(c.NameLabel, c.NameLabel.Text); } } } private void NextButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; Page++; LoadCards(); CheckPageSet(); Cursor = Cursors.Arrow; } private void PrevButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; Page--; LoadCards(); CheckPageSet(); Cursor = Cursors.Arrow; } private void CategoryLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { //Если форма еще не была создана - создаем if (cf == null) { cf = new CategoriesForm(); cf.Owner = this; } cf.Show(); } private void UpdateButton_Click(object sender, EventArgs e) { Update(); } /// <summary> /// Функция для обновления результатов на форме /// </summary> public void Update() { Cursor = Cursors.WaitCursor; LoadCards(); Cursor = Cursors.Arrow; } /// <summary> /// Проверка всего, что связано с номером страницы /// </summary> private void CheckPageSet() { PageLabel.Text = Page.ToString(); if (Page == 1) PrevButton.Enabled = false; else PrevButton.Enabled = true; if (Page == MaxPage) NextButton.Enabled = false; else NextButton.Enabled = true; Text = "KudaGo - страница " + Page; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using YoctoScheduler.Core.Database; using System.Data.SqlClient; namespace YoctoScheduler.UnitTest.Daatabase { [TestClass] public class LiveExecutionStatus_Test { [TestMethod] public void LiveExecutionStatus_Insert_NotNull() { LiveExecutionStatus les = new LiveExecutionStatus() { Inserted = DateTime.Now, LastUpdate = DateTime.Now, ScheduleID = Guid.NewGuid(), ServerID = 1, TaskID = 1 }; using (SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING)) { conn.Open(); using (var trans = conn.BeginTransaction()) { LiveExecutionStatus.Insert(conn,trans,les); trans.Commit(); } } } [TestMethod] public void LiveExecutionStatus_Insert_Null() { LiveExecutionStatus les = new LiveExecutionStatus() { Inserted = DateTime.Now, LastUpdate = DateTime.Now, ScheduleID = null, ServerID = 1, TaskID = 1 }; using (SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING)) { conn.Open(); using (var trans = conn.BeginTransaction()) { LiveExecutionStatus.Insert(conn, trans, les); trans.Commit(); } } } } }
using ArkeOS.Hardware.Architecture; using ArkeOS.Utilities.Extensions; using System; using System.Reflection; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace ArkeOS.Hosts.UWP { public partial class Debugger : Page { private SystemHost host; private DispatcherTimer refreshTimer; public Debugger() { this.InitializeComponent(); this.BreakButton.IsEnabled = false; this.ContinueButton.IsEnabled = false; this.StepButton.IsEnabled = false; this.RefreshButton.IsEnabled = true; } protected override void OnNavigatedTo(NavigationEventArgs e) { this.host = (SystemHost)e.Parameter; this.refreshTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) }; this.refreshTimer.Tick += (s, ee) => this.RefreshDebug(); this.host.Processor.BreakHandler = async () => await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.BreakButton.IsEnabled = false; this.ContinueButton.IsEnabled = true; this.StepButton.IsEnabled = true; this.refreshTimer.Stop(); this.RefreshDebug(); }); var running = this.host.Processor.IsRunning; this.BreakButton.IsEnabled = running; this.ContinueButton.IsEnabled = !running; this.StepButton.IsEnabled = !running; if (running) this.refreshTimer.Start(); this.RefreshDebug(); } private void Shutdown() { this.refreshTimer.Stop(); this.BreakButton.IsEnabled = false; this.ContinueButton.IsEnabled = false; this.StepButton.IsEnabled = false; this.RefreshButton.IsEnabled = false; } private void BreakButton_Click(object sender, RoutedEventArgs e) { this.refreshTimer.Stop(); this.host.Processor.Break(); this.BreakButton.IsEnabled = false; this.ContinueButton.IsEnabled = true; this.StepButton.IsEnabled = true; this.RefreshDebug(); } private void ContinueButton_Click(object sender, RoutedEventArgs e) { this.refreshTimer.Start(); this.Apply(); this.host.Processor.Continue(); this.BreakButton.IsEnabled = true; this.ContinueButton.IsEnabled = false; this.StepButton.IsEnabled = false; } private void StepButton_Click(object sender, RoutedEventArgs e) { this.Apply(); this.host.Processor.Step(); this.RefreshDebug(); } private void Apply() { var displayBase = (this.HexRadioButton.IsChecked ?? false) ? 16 : ((this.DecRadioButton.IsChecked ?? false) ? 10 : 2); foreach (var r in Enum.GetNames(typeof(Register))) { var textbox = (TextBox)this.GetType().GetField(r + "TextBox", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this); this.host.Processor.WriteRegister((Register)Enum.Parse(typeof(Register), r), Convert.ToUInt64(textbox.Text.Substring(2).Replace("_", ""), displayBase)); } } private void RefreshDebug() { var displayBase = (this.HexRadioButton.IsChecked ?? false) ? 16 : ((this.DecRadioButton.IsChecked ?? false) ? 10 : 2); foreach (var r in Enum.GetNames(typeof(Register))) { var textbox = (TextBox)this.GetType().GetField(r + "TextBox", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this); if (textbox == null) return; textbox.Text = this.host.Processor.ReadRegister((Register)Enum.Parse(typeof(Register), r)).ToString(displayBase); } this.CurrentInstructionLabel.Text = this.host.Processor.CurrentInstruction.ToString(displayBase); } private void FormatRadioButton_Checked(object sender, RoutedEventArgs e) => this.RefreshDebug(); private void RefreshButton_Click(object sender, RoutedEventArgs e) => this.RefreshDebug(); } }
using System.Collections; public class DungeonNameGenerator { /* FIXME_VAR_TYPE name_set = { }; FIXME_VAR_TYPE chain_cache = { }; void generate_name(type) { FIXME_VAR_TYPE chain; if(chain = markov_chain(type)) { return markov_name(chain); } return ''; } void name_list(type, n_of) { FIXME_VAR_TYPE list = []; for(FIXME_VAR_TYPE i = 0; i < n_of; i++) { list.push(generate_name(type)); } return list; } void markov_chain(type) { FIXME_VAR_TYPE chain; if(chain = chain_cache[type]) { return chain; } else { FIXME_VAR_TYPE list; if(list = name_set[type]) { FIXME_VAR_TYPE chain; if(chain = construct_chain(list)) { chain_cache[type] = chain; return chain; } } } return false; } void construct_chain(list) { FIXME_VAR_TYPE chain = { }; for(FIXME_VAR_TYPE i = 0; i < list.length; i++) { FIXME_VAR_TYPE names = list[i].split(/\s +/); chain = incr_chain(chain, 'parts', names.length); for(FIXME_VAR_TYPE j = 0; j < names.length; j++) { FIXME_VAR_TYPE name = names[j]; chain = incr_chain(chain, 'name_len', name.length); FIXME_VAR_TYPE c = name.substr(0, 1); chain = incr_chain(chain, 'initial', c); FIXME_VAR_TYPE string= name.substr(1); FIXME_VAR_TYPE last_c = c; while(string.length > 0) { FIXME_VAR_TYPE c = string.substr(0, 1); chain = incr_chain(chain, last_c, c); string = string.substr(1); last_c = c; } } } return scale_chain(chain); } void incr_chain(chain, key, token) { if(chain[key]) { if(chain[key][token]) { chain[key][token]++; } else { chain[key][token] = 1; } } else { chain[key] = { }; chain[key][token] = 1; } return chain; } void scale_chain(chain) { FIXME_VAR_TYPE table_len = { }; foreach(FIXME_VAR_TYPE key in chain) { table_len[key] = 0; for(FIXME_VAR_TYPE token in chain[key]) { FIXME_VAR_TYPE count = chain[key][token]; FIXME_VAR_TYPE weighted = Math.floor(Math.pow(count, 1.3f)); chain[key][token] = weighted; table_len[key] += weighted; } } chain['table_len'] = table_len; return chain; } void markov_name(chain) { FIXME_VAR_TYPE parts = select_link(chain, 'parts'); FIXME_VAR_TYPE names = []; for(FIXME_VAR_TYPE i = 0; i < parts; i++) { FIXME_VAR_TYPE name_len = select_link(chain, 'name_len'); FIXME_VAR_TYPE c = select_link(chain, 'initial'); FIXME_VAR_TYPE name = c; FIXME_VAR_TYPE last_c = c; while(name.length < name_len) { c = select_link(chain, last_c); name += c; last_c = c; } names.push(name); } return names.join(' '); } void select_link(chain, key) { FIXME_VAR_TYPE len = chain['table_len'][key]; FIXME_VAR_TYPE idx = Math.floor(Math.random() * len); for(FIXME_VAR_TYPE token in chain[key]) { t += chain[key][token]; if(idx < t) { return token; } } return '-'; } */ }
using UnityEngine; using UnityEngine.Audio; public abstract class AudioEvent : ScriptableObject { public AudioMixerGroup audioMixerGroup; public bool loop; public AudioClip[] clips; public abstract void Play(AudioSource sourceGiven = null); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using POLIMIGameCollective; public class WindSound : MonoBehaviour { // Use this for initialization void Start () { SfxManager.Instance.Play ("wind"); } // Update is called once per frame void Update () { } }
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_CacheBehaviour : LuaObject { [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_animation(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.animation); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_audio(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.audio); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_camera(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.camera); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_collider(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.collider); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_collider2D(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.collider2D); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_constantForce(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.constantForce); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_guiText(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.guiText); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_guiTexture(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.guiTexture); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_hingeJoint(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.hingeJoint); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_light(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.light); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_particleSystem(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.particleSystem); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_renderer(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.renderer); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_rigidbody(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.rigidbody); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_rigidbody2D(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif CacheBehaviour self=(CacheBehaviour)checkSelf(l); pushValue(l,true); pushValue(l,self.rigidbody2D); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"CacheBehaviour"); addMember(l,"animation",get_animation,null,true); addMember(l,"audio",get_audio,null,true); addMember(l,"camera",get_camera,null,true); addMember(l,"collider",get_collider,null,true); addMember(l,"collider2D",get_collider2D,null,true); addMember(l,"constantForce",get_constantForce,null,true); addMember(l,"guiText",get_guiText,null,true); addMember(l,"guiTexture",get_guiTexture,null,true); addMember(l,"hingeJoint",get_hingeJoint,null,true); addMember(l,"light",get_light,null,true); addMember(l,"particleSystem",get_particleSystem,null,true); addMember(l,"renderer",get_renderer,null,true); addMember(l,"rigidbody",get_rigidbody,null,true); addMember(l,"rigidbody2D",get_rigidbody2D,null,true); createTypeMetatable(l,null, typeof(CacheBehaviour),typeof(UnityEngine.MonoBehaviour)); } }
using System; using Person; namespace Client { class Program { static void Main() { Male male = new Male(); male.MaleInfo(); Female female = new Female(); female.FemaleInfo(); Hermaphrodite hermaphrodite = new Hermaphrodite(); hermaphrodite.HermaphroditeInfo(); } } }
using Moq; using System; using Xunit; namespace Rinsen.IdentityProvider.ExternalApplications { public class ExternalApplicationServiceTests { [Theory] [InlineData(null)] [InlineData("")] public void WhenNoHostIsProvided_GetFailedValidationResultAndNullToken(string data) { var externalApplicationService = new ExternalApplicationService(null, null, null, StubLogger.CreateLogger<ExternalApplicationService>()); var result = externalApplicationService.GetTokenForValidHostAsync("", data, Guid.Empty, Guid.Empty, false).Result; Assert.True(result.Failed); Assert.False(result.Succeeded); Assert.Null(result.Token); } [Fact] public void WhenHostIsNotFound_GetFailedValidationResultAndNullToken() { var externalApplicationStorageMock = new Mock<IExternalApplicationStorage>(); var externalApplicationService = new ExternalApplicationService(externalApplicationStorageMock.Object, null, null, StubLogger.CreateLogger<ExternalApplicationService>()); var result = externalApplicationService.GetTokenForValidHostAsync("AppName", "www.rinsen.se", Guid.Empty, Guid.Empty, false).Result; Assert.True(result.Failed); Assert.False(result.Succeeded); Assert.Null(result.Token); externalApplicationStorageMock.Verify(m => m.GetFromApplicationNameAndHostAsync(It.Is<string>(host => host == "AppName"), It.Is<string>(host => host == "www.rinsen.se")), Times.Once); } [Fact] public void WhenHostIsFound_GetSucceededValidationResultAndToken() { var identity = Guid.NewGuid(); var externalApplicationId = Guid.NewGuid(); var externalApplicationStorageMock = new Mock<IExternalApplicationStorage>(); externalApplicationStorageMock.Setup(m => m.GetFromApplicationNameAndHostAsync(It.Is<string>(host => host == "AppName"), It.Is<string>(host => host == "www.rinsen.se"))) .ReturnsAsync(new ExternalApplication { ExternalApplicationId = externalApplicationId }); var tokenStorageMock = new Mock<ITokenStorage>(); var externalApplicationService = new ExternalApplicationService(externalApplicationStorageMock.Object, null, tokenStorageMock.Object, StubLogger.CreateLogger<ExternalApplicationService>()); var result = externalApplicationService.GetTokenForValidHostAsync("AppName", "www.rinsen.se", Guid.Empty, Guid.Empty, false).Result; tokenStorageMock.Verify(mock => mock.CreateAsync(It.Is<Token>(token => token.TokenId == result.Token && token.ExternalApplicationId == externalApplicationId && token.IdentityId == Guid.Empty)), Times.Once); Assert.True(result.Token.Length >= 40); Assert.False(result.Failed); Assert.True(result.Succeeded); } } }
using System.Collections.Generic; using System.Linq; using Common; using Common.Input; using Common.Utils; using Glass.Graphics; using OpenTK; namespace Glass { class SimulationEngine { private KeyHandler _keyHandler; private Player _player; private Vector3 _mirrorCenter = new Vector3(0, 10, 0); private GraphicsSystem _graphics; private List<SimpleModel> _models; private List<SimpleModel> _reflectiveModels; float angle1 = 0; float angle2 = 0; float angle3 = 0; Vector3 defaultVec1 = new Vector3(0, 10, 30); Vector3 defaultVec2 = new Vector3(15, 10, -25.98f); Vector3 defaultVec3 = new Vector3(-15, 10, -25.98f); public SimulationEngine(int width, int height) { _player = new Player(); _player.Position = new Vector3(0, 0.5f, 0); _player.Target = new Vector3(100, 0.5f, 0); _graphics = new GraphicsSystem(width, height, _player, _mirrorCenter); _keyHandler = new KeyHandler(); _keyHandler.KeyPress += OnKeyPress; InitObjects(); } private void InitObjects() { int waferSize = 100; float axisWidth = 0.15f; var verticesPlane = new[] { new Vector3(waferSize, 0, -waferSize), new Vector3(-waferSize, 0, waferSize), new Vector3(-waferSize, 0, -waferSize), new Vector3(waferSize, 0, -waferSize), new Vector3(waferSize, 0, waferSize), new Vector3(-waferSize, 0, waferSize), }; var verticesOx = new[] { new Vector3(waferSize, 0.2f, -axisWidth), new Vector3(-waferSize, 0.2f, axisWidth), new Vector3(-waferSize, 0.2f, -axisWidth), new Vector3(waferSize, 0.2f, -axisWidth), new Vector3(waferSize, 0.2f, axisWidth), new Vector3(-waferSize, 0.2f, axisWidth), }; const float ozLift = 0.25f; var verticesOZ = new[] { new Vector3(axisWidth, ozLift, -waferSize), new Vector3(-axisWidth, ozLift, waferSize), new Vector3(-axisWidth, ozLift, -waferSize), new Vector3(axisWidth, ozLift, -waferSize), new Vector3(axisWidth, ozLift, waferSize), new Vector3(-axisWidth, ozLift, waferSize), }; var colorsCombined = new[] { new Vector3(0, 0, 0.4f), new Vector3(0, 0, 0.4f), new Vector3(0, 0, 0.4f), new Vector3(0, 0, 0.4f), new Vector3(0, 0, 0.4f), new Vector3(0, 0, 0.4f), // 0x new Vector3(0, 0.7f, 0.0f), new Vector3(0, 0.1f, 0.0f), new Vector3(0, 0.1f, 0.0f), new Vector3(0, 0.7f, 0.0f), new Vector3(0, 0.7f, 0.0f), new Vector3(0, 0.1f, 0.0f), // 0z new Vector3(0.7f, 0.0f, 0.0f), new Vector3(0.1f, 0.0f, 0.0f), new Vector3(0.7f, 0.0f, 0.0f), new Vector3(0.7f, 0.0f, 0.0f), new Vector3(0.1f, 0.0f, 0.0f), new Vector3(0.1f, 0.0f, 0.0f), }; var verticesCombined = new List<Vector3>(); verticesCombined.AddRange(verticesPlane); verticesCombined.AddRange(verticesOx); verticesCombined.AddRange(verticesOZ); var wafer = new SimpleModel() { Vertices = verticesCombined.ToArray(), Colors = colorsCombined, Normals = Enumerable.Repeat(Vector3.UnitY, verticesCombined.Count).ToArray() }; var cubeNormals = new[] { Enumerable.Repeat(Vector3.UnitX, 6), Enumerable.Repeat(-Vector3.UnitX, 6), Enumerable.Repeat(Vector3.UnitY, 6), Enumerable.Repeat(-Vector3.UnitY, 6), Enumerable.Repeat(Vector3.UnitZ, 6), Enumerable.Repeat(-Vector3.UnitZ, 6) } .SelectMany(a => a.ToArray()) .ToArray(); var nonReflectiveCube = new SimpleModel(); var nonReflectiveCube2 = new SimpleModel(); var nonReflectiveCube3 = new SimpleModel(); nonReflectiveCube.Vertices = GeometryHelper.GetVerticesForOrdinaryCube(1); nonReflectiveCube2.Vertices = GeometryHelper.GetVerticesForOrdinaryCube(1); nonReflectiveCube3.Vertices = GeometryHelper.GetVerticesForOrdinaryCube(1); nonReflectiveCube.Vertices.TranslateAll(defaultVec1); nonReflectiveCube2.Vertices.TranslateAll(defaultVec2); nonReflectiveCube3.Vertices.TranslateAll(defaultVec3); nonReflectiveCube.Normals = cubeNormals; nonReflectiveCube2.Normals = cubeNormals; nonReflectiveCube3.Normals = cubeNormals; nonReflectiveCube.Colors = Enumerable.Repeat(Vector3.UnitX, 36).ToArray(); nonReflectiveCube2.Colors = Enumerable.Repeat(Vector3.UnitY, 36).ToArray(); nonReflectiveCube3.Colors = Enumerable.Repeat(Vector3.UnitZ, 36).ToArray(); _models = new List<SimpleModel>() { nonReflectiveCube, nonReflectiveCube2, nonReflectiveCube3, /*, wafer*/ }; //var sphere = new SimpleModel(@"Assets\simpleSphere.obj", null); //sphere.Vertices.TranslateAll(new Vector3(0, 2, 0)); //_reflectiveModels = new List<SimpleModel>() { sphere }; var reflectiveCube = new SimpleModel(); reflectiveCube.Vertices = GeometryHelper.GetVerticesForOrdinaryCube(8); reflectiveCube.Vertices.TranslateAll(_mirrorCenter); reflectiveCube.Colors = new[] { Enumerable.Repeat(Vector3.UnitX, 6), Enumerable.Repeat(Vector3.UnitX* 0.5f, 6), Enumerable.Repeat(Vector3.UnitY, 6), Enumerable.Repeat(Vector3.UnitY* 0.5f, 6), Enumerable.Repeat(Vector3.UnitZ, 6), Enumerable.Repeat(Vector3.UnitZ * 0.5f, 6) } .SelectMany(a => a.ToArray()) .ToArray(); reflectiveCube.Normals = cubeNormals; _reflectiveModels = new List<SimpleModel>() { reflectiveCube }; } private void OnKeyPress(InputSignal signal) { _player.Handle(signal); } internal void Tick(long timeSlice, Vector2 dxdy) { _keyHandler.CheckKeys(); _player.HandleMouseMove(dxdy); UpdatePositions(); FullRender(); } private void UpdatePositions() { const float speed = MathHelper.TwoPi / 270.0f; angle1 += speed; angle2 += speed; angle3 += speed; _models[0].Vertices = GeometryHelper.GetVerticesForOrdinaryCube(1); var rot = Matrix4.CreateRotationY(angle1); _models[0].Vertices.TranslateAll(Vector3.TransformVector(defaultVec1, rot)); _models[1].Vertices = GeometryHelper.GetVerticesForOrdinaryCube(1); rot = Matrix4.CreateRotationY(angle2); _models[1].Vertices.TranslateAll(Vector3.TransformVector(defaultVec2, rot)); _models[2].Vertices = GeometryHelper.GetVerticesForOrdinaryCube(1); rot = Matrix4.CreateRotationY(angle3); _models[2].Vertices.TranslateAll(Vector3.TransformVector(defaultVec3, rot)); } private void FullRender() { _graphics.Render(_models, _reflectiveModels); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using SistemaToners.Entidades; using SistemaToners.Conexion; namespace SistemaToners.Areas { public partial class ListaAreas : Form { public ListaAreas() { InitializeComponent(); Conexiones nuevaConexion = new Conexiones(); List<AreayPuesto> ListaPuestos = nuevaConexion.ListaPuesto(); foreach (var Puesto in ListaPuestos) { ListArea.Items.Add(Puesto.Area_puesto.Nombre_area.ToString()); } } private void AgreArea_Click(object sender, EventArgs e) { AgregArea nagregar = new AgregArea(); nagregar.Show(); } private void Cancelar_Click(object sender, EventArgs e) { this.Close(); } private void Buscar_Click(object sender, EventArgs e) { } } }