text
stringlengths
13
6.01M
using System.Collections.Generic; using System.Reflection; using AutoMapper; using L7.Business; using L7.Persistance; using L7.Persistance.Repositories; using L7.Domain; using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace L7 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { var assemblies = new List<Assembly> { typeof(BusinessLayer).Assembly }; services.AddDbContext<ShopContext>(o => o.UseSqlServer(Configuration.GetConnectionString("Shop"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddAutoMapper(assemblies) .AddMediatR(assemblies); services.AddScoped<IShopingCartRepository, ShoppingCartRepository>(); services.AddScoped<IProductRepository, ProductRepository>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } } }
using Microsoft.AspNetCore.Identity; using SoccerFieldServer.Core.Enums; using System; using System.ComponentModel.DataAnnotations.Schema; namespace SoccerFieldServer.Core.Entities { public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } public bool IsEnabled { get; set; } [Column(TypeName = "date")] public DateTime DateOfBirth { get; set; } public string Address { get; set; } public string BankAcount { get; set; } public string Sex { get; set; } public string Note { get; set; } } }
using OpenQA.Selenium; namespace Applitools.Framework.PageObjectModels { public class BasePageClass { private readonly IWebDriver _driver; public PageModelContext page; public BasePageClass(IWebDriver driver) { _driver = driver; page = new PageModelContext(_driver); } #region Methods public bool IsAt(string title) { if (_driver.Title.Contains(title)) return true; return false; } #endregion Methods } }
using Apache.Ignite.Core; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IgniteDemo { class Server { private static object ignite; static void Main(string[] args) { Ignition.ClientMode = true; //// Start Ignite in client mode. IIgnite ignite = Ignition.Start(); //// Create cache on all the existing and future server nodes. //// Note that since the local node is a client, it will not //// be caching any data. var cache = ignite.GetOrCreateCache<object, object>("cacheName"); ICompute compute = ignite.GetCompute(); // Execute computation on the server nodes (default behavior). //compute.Broadcast(new MyComputeAction()); } } }
using Microsoft.EntityFrameworkCore; using SGDE.Domain.Entities; using SGDE.Domain.Repositories; using System; using System.Collections.Generic; using System.Linq; namespace SGDE.DataEFCoreMySQL.Repositories { public class WorkBudgetDataRepository : IWorkBudgetDataRepository, IDisposable { private readonly EFContextMySQL _context; public WorkBudgetDataRepository(EFContextMySQL context) { _context = context; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _context.Dispose(); } } private bool WorkBudgetDataExists(int id) { return GetById(id) != null; } public List<WorkBudgetData> GetAll(int workId) { if (workId != 0) { return _context.WorkBudgetData .Include(x => x.Work) .Include(x => x.WorkBudgets) .Where(x => x.WorkId == workId) .OrderBy(x => x.AddedDate) .ToList(); } return _context.WorkBudgetData .Include(x => x.Work) .Include(x => x.WorkBudgets) .OrderBy(x => x.AddedDate) .ToList(); } public WorkBudgetData GetById(int id) { return _context.WorkBudgetData .Include(x => x.Work) .Include(x => x.WorkBudgets) .FirstOrDefault(x => x.Id == id); } public WorkBudgetData GetByWorkIdAndReference(int workId, string reference) { return _context.WorkBudgetData .FirstOrDefault(x => x.WorkId == workId && x.Reference == reference); } public WorkBudgetData Add(WorkBudgetData newWorkBudgetData) { _context.WorkBudgetData.Add(newWorkBudgetData); _context.SaveChanges(); return newWorkBudgetData; } public bool Update(WorkBudgetData workBudgetData) { if (!WorkBudgetDataExists(workBudgetData.Id)) return false; _context.WorkBudgetData.Update(workBudgetData); _context.SaveChanges(); return true; } public bool Delete(int id) { if (!WorkBudgetDataExists(id)) return false; var toRemove = _context.WorkBudgetData.Find(id); _context.WorkBudgetData.Remove(toRemove); _context.SaveChanges(); return true; } } }
using Roaring.DataStores; using System; using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; namespace Roaring { public unsafe class MappedRoaringBitmap : RoaringBitmap, IDisposable { private readonly MemoryMappedViewAccessor _view; private bool _isDisposed = false; private MappedRoaringBitmap(MemoryMappedViewAccessor view, byte* ptr, Dictionary<uint, int> indices, KeyedList<RoaringContainer> containers) : base(new MappedArrayStore(ptr, indices), new MappedBitmapStore(ptr, indices), containers, false) { _view = view; } internal MappedRoaringBitmap Create(FileStream stream, Dictionary<uint, int> indices, KeyedList<RoaringContainer> containers) { var map = MemoryMappedFile.CreateFromFile(stream, "Roaring-" + Guid.NewGuid().ToString(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, false); var view = map.CreateViewAccessor(); byte* ptr = null; view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr); return new MappedRoaringBitmap(view, ptr, indices, containers); } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) _view.Dispose(); _view?.SafeMemoryMappedViewHandle.ReleasePointer(); _isDisposed = true; } } ~MappedRoaringBitmap() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using UnityEditor; using UnityEngine; namespace EnhancedEditor.Editor { /// <summary> /// Special <see cref="DecoratorDrawer"/> for fields with the attribute <see cref="HorizontalLineAttribute"/>. /// </summary> [CustomPropertyDrawer(typeof(HorizontalLineAttribute), false)] public class HorizontalLineDecoratorDrawer : DecoratorDrawer { #region Decorator Content public override float GetHeight() { HorizontalLineAttribute _attribute = attribute as HorizontalLineAttribute; return _attribute.Height + EditorGUIUtility.standardVerticalSpacing; } public override void OnGUI(Rect _position) { HorizontalLineAttribute _attribute = attribute as HorizontalLineAttribute; _position.height -= EditorGUIUtility.standardVerticalSpacing; EnhancedEditorGUI.HorizontalLine(_position, _attribute.Color, _attribute.Margins); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using DominosPizza.Models; using System.Data.Entity.ModelConfiguration; namespace DominosPizza.Models { public class TaskRow { public int TaskRowId { get; set; } public int Quantity { get; set; } public int TaskId { get; set; } public Task Task { get; set; } public int ProductId { get; set; } public Product Product { get; set; } } public class TaskRowMap:EntityTypeConfiguration<TaskRow> { public TaskRowMap() { HasRequired(x => x.Task); HasRequired(x => x.Product); } } }
using System; using NUnit.Framework; namespace FileSearch.Test { [TestFixture] public class SpeedTests { [Test] public void IsFasterUsingSampledFile() { } public void DoSearch() { } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlackJackDudekGueguen.Model { class Hand { public ObservableCollection<Card> Cards { get; set; } public int Bet { get; set; } public int SideBet { get; set; } public int Score { get; set; } public Hand() { this.Cards = new ObservableCollection<Card>(); this.Bet = 0; this.Score = 0; } } }
using Opbot.Services; using System; using System.Collections.Generic; using System.Linq; using System.Net.FtpClient; using System.Text; using System.Threading.Tasks; using Xunit; namespace Opbot.Tests { public class FtpTests { //public const string FtpHost = "ftp://betclick.upload.llnw.net"; public const string FtpHost = "betclick.upload.llnw.net"; public const string FtpUser = "betclick-ht-mlemaitre"; public const string FtpPwd = "Dnj8wtSfpDm!"; [Fact] public void ListDetails() { //var ftp = new FtpService(new Options() { Host = FtpHost, User = FtpUser, Password = FtpPwd }, null); //var all = ftp.ListDirectoryAsync("/media/retention/frfr/betclic/sport/emails/2015/02/04").Result; } [Fact] public void ListDetailsByClient() { var client = new FtpClient(); client.Credentials = new System.Net.NetworkCredential(FtpUser, FtpPwd); client.Host = FtpHost; client.Connect(); var items = client.GetListing("/media/retention/frfr/sitepoker", FtpListOption.AllFiles | FtpListOption.Recursive); client.Disconnect(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using _2013_TCO_Algorithm_Round_1A___Division_I__Level_One; namespace TopCoderTest { [TestClass] public class UnitTest1 { [TestMethod] public void TestHouseBuilding() { HouseBuilding target = new HouseBuilding(); string[] input = { "10", "31" }; //string[] input = {"5781252", "2471255", "0000291", "1212489"}; int actual = target.GetMinimum(input); Assert.AreEqual(2, actual); string[] input1 = { "5781252", "2471255", "0000291", "1212489" }; actual = target.GetMinimum(input1); Assert.AreEqual (53, actual); string[] input2 = {"54454","61551"}; actual = target.GetMinimum(input2); Assert.AreEqual(7, actual); } } }
namespace WebApplication1.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Firebird.ADD")] public partial class Address { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Address() { AddressLocators = new HashSet<AddressLocator>(); } [Key(), Column("ID")] public Guid Id { get; set; } [Required] [StringLength(64)] [Column("L1")] public string Line1 { get; set; } [StringLength(64)] [Column("L2")] public string Line2 { get; set; } [StringLength(64)] [Column("L3")] public string Line3 { get; set; } [Required] [StringLength(64)] [Column("LOC")] public string Locality { get; set; } [Required] [StringLength(64)] [Column("PC")] public string PostalCode { get; set; } [Required] [StringLength(64)] [Column("PRO")] public string Province { get; set; } [Required] [StringLength(64)] [Column("CTRY")] public string Country { get; set; } [StringLength(512)] [Column("FA")] public string FullAddress { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<AddressLocator> AddressLocators { get; set; } } }
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.UI.Xaml.Controls; namespace Caliburn.Light.WinUI { /// <summary> /// SuspensionManager captures global session state to simplify process lifetime management /// for an application. Note that session state will be automatically cleared under a variety /// of conditions and should only be used to store information that would be convenient to /// carry across sessions, but that should be discarded when an application crashes or is /// upgraded. /// </summary> public interface ISuspensionManager { /// <summary> /// Provides access to global session state for the current session. This state is /// serialized by <see cref="SaveAsync"/> and restored by /// <see cref="RestoreAsync"/>, so values must be serializable and should be as compact as possible. /// </summary> IDictionary<string, object> SessionState { get; } /// <summary> /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to /// and restored from <see cref="SessionState"/>. Frames should be registered once /// immediately after creation if they will participate in session state management. Upon /// registration if state has already been restored for the specified key /// the navigation history will immediately be restored. Subsequent invocations of /// <see cref="RestoreAsync"/> will also restore navigation history. /// </summary> /// <param name="frame">An instance whose navigation history should be managed by /// <see cref="ISuspensionManager"/></param> /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to /// store navigation-related information.</param> /// <param name="sessionBaseKey">An optional key that identifies the type of session. /// This can be used to distinguish between multiple application launch scenarios.</param> void RegisterFrame(Frame frame, string sessionStateKey, string sessionBaseKey = null); /// <summary> /// Restores previously saved <see cref="SessionState"/>. Any <see cref="Frame"/> instances /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its /// state. /// </summary> /// <returns>An asynchronous task that reflects when session state has been read. The /// content of <see cref="SessionState"/> should not be relied upon until this task /// completes.</returns> Task RestoreAsync(); /// <summary> /// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances /// registered with <see cref="RegisterFrame"/> will also preserve their current /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity /// to save its state. /// </summary> /// <returns>An asynchronous task that reflects when session state has been saved.</returns> Task SaveAsync(); /// <summary> /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/> /// from <see cref="SessionState"/>. Any navigation state previously captured will be /// removed. /// </summary> /// <param name="frame">An instance whose navigation history should no longer be /// managed.</param> void UnregisterFrame(Frame frame); } }
//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Text; using System.Threading; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using NopSolutions.NopCommerce.BusinessLogic; using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement; using NopSolutions.NopCommerce.BusinessLogic.Directory; using NopSolutions.NopCommerce.BusinessLogic.Localization; using NopSolutions.NopCommerce.BusinessLogic.Products; using NopSolutions.NopCommerce.BusinessLogic.Tax; using NopSolutions.NopCommerce.Common.Utils; namespace NopSolutions.NopCommerce.Web.Modules { public partial class ProductPriceControl : BaseNopUserControl { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindData(); } } private void BindData() { ProductVariant productVariant = ProductManager.GetProductVariantByID(this.ProductVariantID); if (productVariant != null) { decimal oldPriceBase = TaxManager.GetPrice(productVariant, productVariant.OldPrice); decimal finalPriceWithoutDiscountBase = TaxManager.GetPrice(productVariant, PriceHelper.GetFinalPrice(productVariant, false)); decimal finalPriceWithDiscountBase = TaxManager.GetPrice(productVariant, PriceHelper.GetFinalPrice(productVariant, true)); decimal oldPrice = CurrencyManager.ConvertCurrency(oldPriceBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency); decimal finalPriceWithoutDiscount = CurrencyManager.ConvertCurrency(finalPriceWithoutDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency); decimal finalPriceWithDiscount = CurrencyManager.ConvertCurrency(finalPriceWithDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency); if (finalPriceWithoutDiscountBase != oldPriceBase && oldPriceBase > decimal.Zero) { lblOldPrice.Text = PriceHelper.FormatPrice(oldPrice); lblPriceValue.Text = PriceHelper.FormatPrice(finalPriceWithoutDiscount); phOldPrice.Visible = true; } else { lblPriceValue.Text = PriceHelper.FormatPrice(finalPriceWithoutDiscount); phOldPrice.Visible = false; } if (finalPriceWithoutDiscountBase != finalPriceWithDiscountBase) { lblFinalPriceWithDiscount.Text = PriceHelper.FormatPrice(finalPriceWithDiscount); phDiscount.Visible = true; } else { phDiscount.Visible = false; } if (phDiscount.Visible) { lblPriceValue.CssClass = string.Empty; } else { lblPriceValue.CssClass = "productPrice"; } if (phDiscount.Visible || phOldPrice.Visible) { lblPrice.Text = GetLocaleResourceString("Products.FinalPriceWithoutDiscount"); } } else this.Visible = false; } public int ProductVariantID { get { object obj2 = this.ViewState["ProductVariantID"]; if (obj2 != null) return (int)obj2; else return 0; } set { this.ViewState["ProductVariantID"] = value; } } } }
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace prjCapelo.Models { [Table("Professor")] class Professor { public Professor() { Disciplina = new Disciplina(); Pessoa = new Pessoa(); } [Key] public int Matricula { get; set; } public int DataIngresso { get; set; } public string Senha { get; set; } public Disciplina Disciplina { get; set; } public Pessoa Pessoa { get; set; } } }
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Kers.Models.Repositories; using Kers.Models.Entities.KERScore; using Kers.Models.Entities.KERSmain; using Kers.Models.Abstract; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore; using System.Diagnostics; using Kers.Models.Entities; using Kers.Models.Contexts; using Newtonsoft.Json; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using System.Text.RegularExpressions; using Microsoft.Extensions.Caching.Distributed; using Kers.Models.Data; using Kers.Models.ViewModels; using Kers.Models.Entities.SoilData; namespace Kers.Controllers.Soil { [Route("api/[controller]")] public class SoilSampleController : BaseController { KERScoreContext _coreContext; SoilDataContext _context; public SoilSampleController( KERSmainContext mainContext, IKersUserRepository userRepo, SoilDataContext _context, KERScoreContext _coreContext ):base(mainContext, _coreContext, userRepo){ this._context = _context; this._coreContext = _coreContext; } [HttpGet("forms")] public IActionResult GetFormTypes(){ var forms = this._context.TypeForm.OrderBy(r => r.Code).ToList(); return new OkObjectResult(forms); } [HttpGet("attributetypes/{formTypeId}")] public IActionResult AttributeTypes(int formTypeId){ var types = this._context.SampleAttributeType.Where(t => t.TypeFormId == formTypeId).OrderBy(r => r.Order).ToList(); return new OkObjectResult(types); } [HttpGet("attributes/{attributeTypeId}")] public IActionResult Attributes(int attributeTypeId){ var types = this._context.SampleAttribute.Where(t => t.SampleAttributeTypeId == attributeTypeId).OrderBy(r => r.Name).ToList(); return new OkObjectResult(types); } [HttpGet("billingtypes")] public IActionResult BillingTypes(){ var types = this._context.BillingType.OrderBy(r => r.Id).ToList(); return new OkObjectResult(types); } [HttpGet("optionaltests")] public IActionResult OptionalTests(){ var types = this._context.OptionalTest.OrderBy(r => r.Id).ToList(); return new OkObjectResult(types); } [HttpGet("lastsamplenum/{CountyCodeId?}")] public IActionResult LastSampleNum(int CountyCodeId = 0){ if(CountyCodeId == 0) CountyCodeId = this.CurrentCountyCode().Id; var NumRecord = this._context.CountyAutoCoSamNum.Where( c => c.CountyCodeId == CountyCodeId).FirstOrDefault(); if( NumRecord != null ) return new OkObjectResult( NumRecord.LastSampleNumber ); // Last Sample Code Number not found in the database int LastNumber = FindLastCountyNum(CountyCodeId); // Create Record CountyAutoCoSamNum numberRecord = new CountyAutoCoSamNum(); numberRecord.CountyCodeId = CountyCodeId; numberRecord.AutoSampleNumber = true; numberRecord.LastSampleNumber = LastNumber; this._context.CountyAutoCoSamNum.Add(numberRecord); this._context.SaveChanges(); return new OkObjectResult(LastNumber); } private int FindLastCountyNum(int CountyCodeId){ var countyNumbers = this._context.SoilReportBundle.Where( b => b.PlanningUnitId == CountyCodeId).OrderByDescending( b => b.SampleLabelCreated).Take(40).Select( b => b.CoSamnum).ToList(); int currentNumber = 0; foreach ( string countyCodes in countyNumbers){ var parts = countyCodes.Split("-"); var NumPart = parts[0]; int i = 0; bool result = int.TryParse(NumPart, out i); if( i > currentNumber ) currentNumber = i; } return currentNumber; } private CountyCode CurrentCountyCode(){ var PlanningUnitId = _coreContext.ReportingProfile.Where( p => p.LinkBlueId == CurrentUserLinkBlueId()).Select( p => p.PlanningUnitId).FirstOrDefault(); return _context.CountyCodes.Where( c => c.PlanningUnitId == PlanningUnitId ).FirstOrDefault(); } protected string CurrentUserLinkBlueId(){ return User.FindFirst(ClaimTypes.NameIdentifier).Value; } [HttpPost("addsample")] [Authorize] public IActionResult AddSample( [FromBody] SoilReportBundle sample){ if(sample != null){ foreach( SampleInfoBundle smpl in sample.SampleInfoBundles){ var cleanedConnections = new List<SampleAttributeSampleInfoBundle>(); foreach( SampleAttributeSampleInfoBundle attr in smpl.SampleAttributeSampleInfoBundles ){ if( attr.SampleAttributeId != 0 ){ cleanedConnections.Add(attr); } } smpl.SampleAttributeSampleInfoBundles = cleanedConnections; smpl.PurposeId = 1; sample.TypeFormId = smpl.TypeFormId; } var contCode = this.CurrentCountyCode(); sample.PlanningUnit = contCode; sample.UniqueCode = Guid.NewGuid().ToString(); var cntId = sample.CoSamnum; var now = DateTime.Now; sample.SampleLabelCreated = new DateTime( sample.SampleLabelCreated.Year, sample.SampleLabelCreated.Month, sample.SampleLabelCreated.Day, now.Hour, now.Minute, now.Second) ; int i = 0; if( int.TryParse(cntId, out i) ){ var NumRecord = this._context.CountyAutoCoSamNum.Where( c => c.CountyCodeId == contCode.Id).FirstOrDefault(); NumRecord.LastSampleNumber = i; } if( sample.FarmerAddress != null ){ sample.FarmerAddressId = sample.FarmerAddress.Id; sample.FarmerForReport = CreateFarmerForReport(sample.FarmerAddressId??0); sample.FarmerAddress = null; } var status = _context.SoilReportStatus.Where( s => s.Name == "Entered").FirstOrDefault(); sample.LastStatus = new SoilReportStatusChange(); sample.LastStatus.SoilReportStatus = status; sample.LastStatus.Created = DateTime.Now; sample.CoSamnum = sample.CoSamnum.PadLeft(5, '0'); sample.TypeForm = this._context.TypeForm.Find(sample.TypeFormId); _context.Add(sample); _context.SaveChanges(); this.Log( sample ,"SoilReportBundle", "Soil Sample Info added.", "SoilReportBundle"); return new OkObjectResult(sample); }else{ this.Log( sample ,"SoilReportBundle", "Error in adding Soil Sample Info attempt.", "SoilReportBundle", "Error"); return new StatusCodeResult(500); } } [HttpPut("updatesample/{id}")] [Authorize] public IActionResult UpdateSample( int id, [FromBody] SoilReportBundle sample){ var smpl = _context.SoilReportBundle.Where( t => t.Id == id) .Include( s => s.FarmerForReport) .Include( b => b.SampleInfoBundles).ThenInclude( i => i.SampleAttributeSampleInfoBundles) .Include( b => b.OptionalTestSoilReportBundles) .Include( b => b.LastStatus).ThenInclude( s => s.SoilReportStatus) .Include( b => b.Reports) .FirstOrDefault(); if(sample != null && smpl != null ){ foreach( var bndl in smpl.SampleInfoBundles){ _context.RemoveRange(bndl.SampleAttributeSampleInfoBundles); _context.SaveChanges(); } _context.RemoveRange(smpl.SampleInfoBundles); _context.SaveChanges(); var isItAnAltCrop = false; foreach( SampleInfoBundle smplBundle in sample.SampleInfoBundles){ var cleanedConnections = new List<SampleAttributeSampleInfoBundle>(); foreach( SampleAttributeSampleInfoBundle attr in smplBundle.SampleAttributeSampleInfoBundles ){ if( attr.SampleAttributeId != 0 ){ cleanedConnections.Add(attr); } } smplBundle.SampleAttributeSampleInfoBundles = cleanedConnections; if( smplBundle.PurposeId == 2 ) isItAnAltCrop = true; smpl.TypeFormId = smplBundle.TypeFormId; } if(isItAnAltCrop){ var status = _context.SoilReportStatus.Where( s => s.Name == "AltCrop").FirstOrDefault(); if( smpl.LastStatus == null ){ smpl.LastStatus = new SoilReportStatusChange(); } smpl.LastStatus.SoilReportStatus = status; }else{ var now = DateTime.Now; smpl.SampleLabelCreated = new DateTime( sample.SampleLabelCreated.Year, sample.SampleLabelCreated.Month, sample.SampleLabelCreated.Day, now.Hour, now.Minute, now.Second); } smpl.SampleInfoBundles = sample.SampleInfoBundles; smpl.OptionalTestSoilReportBundles = sample.OptionalTestSoilReportBundles; smpl.OwnerID = sample.OwnerID; smpl.Acres = sample.Acres; smpl.OptionalInfo = sample.OptionalInfo; smpl.PrivateNote = sample.PrivateNote; if(sample.FarmerAddress != null ){ smpl.FarmerAddressId = sample.FarmerAddress.Id; } var numFarmersForReport = _context.SoilReportBundle.Where( r => r.FarmerForReportId == smpl.FarmerForReportId).Count(); if(numFarmersForReport > 1){ smpl.FarmerForReport = CreateFarmerForReport(smpl.FarmerAddressId??0); }else{ UpdateFarmerForReport(smpl.FarmerForReport, smpl.FarmerAddressId??0); } smpl.SampleInfoBundles = sample.SampleInfoBundles; smpl.BillingTypeId = sample.BillingTypeId; smpl.CoSamnum = sample.CoSamnum.PadLeft(5, '0'); _context.SaveChanges(); smpl.TypeForm = this._context.TypeForm.Find(smpl.TypeFormId); this.Log( sample ,"SoilReportBundle", "Soil Sample Info updated.", "SoilReportBundle"); return new OkObjectResult(smpl); }else{ this.Log( sample ,"SoilReportBundle", "Not Found SoilSample in an update attempt.", "SoilReportBundle", "Error"); return new StatusCodeResult(500); } } private FarmerForReport CreateFarmerForReport( int FarmerId ){ var newFarmer = new FarmerForReport(); UpdateFarmerForReport(newFarmer, FarmerId); return newFarmer; } private void UpdateFarmerForReport( FarmerForReport newFarmer, int FarmerId){ var Frmr = this._context.FarmerAddress.Find(FarmerId); newFarmer.First = Frmr.First; newFarmer.FarmerID = Frmr.FarmerID; newFarmer.Mi = Frmr.Mi; newFarmer.Last = Frmr.Last; newFarmer.Title = Frmr.Title; newFarmer.Modifier = Frmr.Modifier; newFarmer.Company = Frmr.Company; newFarmer.Address = Frmr.Address; newFarmer.City = Frmr.City; newFarmer.St = Frmr.St; newFarmer.Status = Frmr.Status; newFarmer.WorkNumber = Frmr.WorkNumber; newFarmer.DuplicateHouseHold = Frmr.DuplicateHouseHold; newFarmer.HomeNumber = Frmr.HomeNumber; newFarmer.Fax = Frmr.Fax; newFarmer.FarmerID = Frmr.FarmerID; newFarmer.Zip = Frmr.Zip; newFarmer.EmailAddress = Frmr.EmailAddress; } [HttpPost("reportsdata")] public IActionResult ReportsData([FromBody] UniqueIds unigueIds) { var samples = this._context.SoilReportBundle .Where( b => unigueIds.ids.Contains(b.UniqueCode) && b.Reports.Count() > 0) .Include( b => b.Reports) .Include( b => b.FarmerForReport) .OrderBy( b => b.CoSamnum) .ToList(); List<List<string>> data = new List<List<string>>(); data.Add( this.ReportHeader()); foreach( var sample in samples){ foreach( var report in sample.Reports){ data.Add( ReportToStringList(report, sample)); } } return new OkObjectResult(data); } private List<string> ReportHeader(){ var header = new List<string>{ "Date", "County #", "Owner #", "Owner Name", "Crop", "Form Type", "Lab pH", "Lab P", "Lab K", "Lab Ca", "Lab Mg", "Lab Zn", "Rec N", "Rec P2O5", "Rec K2O", "Rec LIME", "Rec Zn" }; return header; } private List<string> ReportToStringList(SoilReport report, SoilReportBundle bundle ){ var row = new List<string> { bundle.SampleLabelCreated.ToString(), bundle.CoSamnum.TrimStart('0'), bundle.OwnerID, bundle.FarmerForReport.First + " " + bundle.FarmerForReport.Last, report.CropInfo1, report.TypeForm }; var tests = this._context.TestResults.Where( r => r.PrimeIndex == report.Prime_Index).ToList(); var LabPh = tests.Where( t => t.TestName == "Soil pH").FirstOrDefault(); row.Add( LabPh == null ? "" : LabPh.Result); var LabP = tests.Where( t => t.TestName == "Phosphorus").FirstOrDefault(); row.Add( LabP == null ? "" : LabP.Result); var LabK = tests.Where( t => t.TestName == "Potassium").FirstOrDefault(); row.Add( LabK == null ? "" : LabK.Result); var LabCa = tests.Where( t => t.TestName == "Calcium").FirstOrDefault(); row.Add( LabCa == null ? "" : LabCa.Result); var LabMg = tests.Where( t => t.TestName == "Magnesium").FirstOrDefault(); row.Add( LabMg == null ? "" : LabMg.Result); var LabZn = tests.Where( t => t.TestName == "Zinc").FirstOrDefault(); row.Add( LabMg == null ? "" : LabZn.Result); var RecN = tests.Where( t => t.TestName == "Nitrogen").FirstOrDefault(); row.Add( RecN == null ? "" : RecN.Recommmendation); var RecP = tests.Where( t => t.TestName == "Phosphorus").FirstOrDefault(); row.Add( RecP == null ? "" : RecP.Recommmendation); var RecK = tests.Where( t => t.TestName == "Potassium").FirstOrDefault(); row.Add( RecK == null ? "" : RecK.Recommmendation); row.Add( report.LimeComment); var RecZn = tests.Where( t => t.TestName == "Zinc").FirstOrDefault(); row.Add( RecZn == null ? "" : RecZn.Recommmendation); return row; } [HttpPost("checksamnum")] public IActionResult CheckSampleNumber([FromBody] CoSamNumCheck SampleNumber) { var exists = false; var sNum = SampleNumber.CoSamNum.PadLeft(5, '0'); var dateToCompare = DateTime.Now.AddDays(-200); CountyCode CountyCode = this.CurrentCountyCode(); exists = _context.SoilReportBundle .Where( b => b.PlanningUnit == CountyCode && b.CoSamnum == sNum && b.SampleLabelCreated > dateToCompare ).Any(); return new OkObjectResult(exists); } } public class UniqueIds{ public List<string> ids; } public class CoSamNumCheck{ public string CoSamNum; } }
/* * This files demos the below concept: * - string interpolation */ namespace CSBasic { /// <summary> /// This is a StringInterpolation class used for the demo. /// This is xml style documention and a good practice to use. /// </summary> public class StringInterpolation { public string SayHello(string name) { // String interpolation is done by $ System.Console.WriteLine($"Hello {name} !!"); return ($"Hello {name} !!"); ; } } }
using System; using System.Threading.Tasks; using CDSShareLib.Helper; using Microsoft.AspNet.SignalR; using Microsoft.Owin; using MsgHubService.Controllers; using Owin; [assembly: OwinStartup(typeof(MsgHubService.Startup))] namespace MsgHubService { public class Startup { public static LogHelper _appLogger = null; public static Int64 _allowStartIP = 0, _allowEndIP = (Int64) 255*255*255*255; public static IHubContext _hubContext = GlobalHost.ConnectionManager.GetHubContext<RTMessageHub>(); public static String _adminWebURI, _superAdminWebURI; public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888 // Initial SignalR app.MapSignalR(); // Initial CDS Configuration String logStorageConnectionString = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("SystemStorageConnectionString"); String logStorageContainer = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("MsgHubServiceLogStorageContainerApp"); LogLevel logLevel = (LogLevel)Enum.Parse(typeof(LogLevel), AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("MsgHubServiceLogLevel")); _appLogger = new LogHelper(logStorageConnectionString, logStorageContainer, logLevel); _appLogger.Info("Initial Program Start..."); _adminWebURI = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("AdminWebURI"); if (_adminWebURI != null && _adminWebURI.Contains("//")) _adminWebURI = _adminWebURI.Substring(_adminWebURI.IndexOf("//") + 2); _superAdminWebURI = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("SuperAdminWebURI"); if (_superAdminWebURI != null && _superAdminWebURI.Contains("//")) _superAdminWebURI = _superAdminWebURI.Substring(_superAdminWebURI.IndexOf("//") + 2); try { String msgHubAllowIPStart = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("MessageHubAllowIPStart"); String[] allowStartIP = msgHubAllowIPStart.Split('.'); _allowStartIP = Int64.Parse(allowStartIP[0]) * Int64.Parse(allowStartIP[1]) * Int64.Parse(allowStartIP[2]) * Int64.Parse(allowStartIP[3]); String msgHubAllowIPend = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("MessageHubAllowIpEnd"); String[] allowEndIP = msgHubAllowIPend.Split('.'); _allowEndIP = Int64.Parse(allowEndIP[0]) * Int64.Parse(allowEndIP[1]) * Int64.Parse(allowEndIP[2]) * Int64.Parse(allowEndIP[3]); _appLogger.Info(string.Format("Allow IP: {0} ~ {1}", msgHubAllowIPStart, msgHubAllowIPend)); } catch (Exception) { } } } }
using System; using System.Diagnostics; using System.Net; namespace WebsitePerformance.BLL.WebsiteAccess { public class LinkResponseTime { string link; HttpWebRequest request; Stopwatch Watch; public LinkResponseTime(string link) { this.link = link; request = (HttpWebRequest)WebRequest.Create(link); Watch = new Stopwatch(); } public float Measure() { try { Watch.Start(); using (WebResponse response = request.GetResponse()) { } Watch.Stop(); TimeSpan ts = Watch.Elapsed; return (float)ts.Seconds + (float)(ts.Milliseconds / 1000.0f); } catch (Exception) { throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CONSULS_SYSTEM.Models { public class Config { public string skin { get; set; } } }
using CallCenter.Common.Entities; namespace CallCenter.Client.SqlStorage.Entities { public class Operator : IOperator, ISerializable { public virtual int Id { get; set; } public virtual string Number { get; set; } public virtual string Name { get; set; } public virtual ICallCenter CallCenter { get; set; } public virtual string Password { get; set; } } }
using BackHackaton.BDD.ClassesEfCore; using BackHackaton.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BackHackaton { public static class SelectData { public static List<Tournament> SelectAllTournaments() { List<Tournament> tournaments = new List<Tournament>(); TournamentContext context = new TournamentContext(); foreach (Tournament tournament in context.Tournament) { tournaments.Add(tournament); } return tournaments; } public static List<Knight> SelectAllKnights() { List<Knight> knights = new List<Knight>(); TournamentContext context = new TournamentContext(); foreach (Knight tournament in context.Knight) { knights.Add(tournament); } return knights; } internal static List<Knight> SelectAliveKnights() { List<Knight> knights = new List<Knight>(); TournamentContext context = new TournamentContext(); // var CougarsAnimalsCount = context.Animals.Where((a) => a.Specie.SpecieName == "Cougars blancs") foreach (Knight tournament in context.Knight.Where((knight) => knight.Alive == true)) { knights.Add(tournament); } return knights; } internal static List<Knight> SelectKnightsHaveAMount() { List<Knight> knights = new List<Knight>(); TournamentContext context = new TournamentContext(); // var CougarsAnimalsCount = context.Animals.Where((a) => a.Specie.SpecieName == "Cougars blancs") foreach (Knight tournament in context.Knight.Where((knight) => knight.Mount == true)) { knights.Add(tournament); } return knights; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TxHumor.Cache.Service { public class srv_MemcacheCacheManager { /// <summary> /// 获取多个 /// </summary> /// <param name="keys"></param> /// <returns></returns> public static IDictionary<string, object> Get(params string[] keys) { return new Dictionary<string, object>(0); } /// <summary> /// 添加 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expireMin"></param> public static void Add(string key, object value, int expireMin) { return; } } }
using Enrollment.Common.Configuration.ExpansionDescriptors; using Enrollment.Common.Configuration.ExpressionDescriptors; using Enrollment.Data.Entities; using Enrollment.Domain.Entities; using Enrollment.Forms.Configuration; using Enrollment.Forms.Configuration.Bindings; using Enrollment.Forms.Configuration.DataForm; using System.Collections.Generic; using System.Linq; namespace Enrollment.XPlatform.Tests { internal static class ReadOnlyDescriptors { internal static DataFormSettingsDescriptor ResidencyForm = new() { Title = "Residency", RequestDetails = new FormRequestDetailsDescriptor { GetUrl = "/Residency/GetSingle", ModelType = typeof(UserModel).AssemblyQualifiedName, DataType = typeof(User).AssemblyQualifiedName, Filter = new FilterLambdaOperatorDescriptor { FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "f" }, MemberFullName = "UserId" }, Right = new ConstantOperatorDescriptor { Type = typeof(int).FullName, ConstantValue = 1 } }, SourceElementType = typeof(UserModel).AssemblyQualifiedName, ParameterName = "f" }, SelectExpandDefinition = new SelectExpandDefinitionDescriptor { Selects = new List<string>(), ExpandedItems = new List<SelectExpandItemDescriptor> { new SelectExpandItemDescriptor { MemberName = "Residency" } } } }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "UserId", Type = "System.Int32", Title = "User ID", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "HiddenTemplate" } }, new FormControlSettingsDescriptor { Field = "CitizenshipStatus", Type = "System.String", Title = "Citizenship Status", StringFormat = "{0}", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select Citizenship Status:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "citizenshipstatus", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } }, }, new FormControlSettingsDescriptor { Field = "ResidentState", Type = "System.String", Title = "Resident State", StringFormat = "{0}", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select Citizenship Status:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "states" }, Right = new ConstantOperatorDescriptor { ConstantValue = "citizenshipstatus", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "HasValidDriversLicense", Type = "System.Boolean", Title = "Has Valid Drivers License", StringFormat = "{0}", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "SwitchTemplate" } }, new MultiSelectFormControlSettingsDescriptor { KeyFields = new List<string> { "State" }, Field = "StatesLivedIn", Title ="States Lived In", Type = typeof(ICollection<StateLivedInModel>).AssemblyQualifiedName, MultiSelectTemplate = new MultiSelectTemplateDescriptor { TemplateName = "MultiSelectTemplate", PlaceholderText = "(States Lived In)", LoadingIndicatorText = "Loading ...", ModelType = typeof(StateLivedInModel).AssemblyQualifiedName, TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "d" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Ascending, SelectorParameterName = "d" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["State"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUps>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<StateLivedInModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<StateLivedInModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<StateLivedIn>).AssemblyQualifiedName } } } }, ModelType = typeof(ResidencyModel).AssemblyQualifiedName }; internal static DataFormSettingsDescriptor AcademicForm = new() { Title = "Academic", RequestDetails = new FormRequestDetailsDescriptor { GetUrl = "/Academic/GetSingle", ModelType = typeof(UserModel).AssemblyQualifiedName, DataType = typeof(User).AssemblyQualifiedName, Filter = new FilterLambdaOperatorDescriptor { FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "f" }, MemberFullName = "UserId" }, Right = new ConstantOperatorDescriptor { Type = typeof(int).FullName, ConstantValue = 1 } }, SourceElementType = typeof(UserModel).AssemblyQualifiedName, ParameterName = "f" }, SelectExpandDefinition = new SelectExpandDefinitionDescriptor { Selects = new List<string>(), ExpandedItems = new List<SelectExpandItemDescriptor> { new SelectExpandItemDescriptor { MemberName = "Academic" } } } }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "UserId", Type = "System.Int32", Title = "User ID", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "HiddenTemplate" } }, new FormControlSettingsDescriptor { Field = "LastHighSchoolLocation", Type = "System.String", Title = "Last High School Location", Placeholder = "Last High School Location (required)", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select Last High School Location:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "highSchoolLocation", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "NcHighSchoolName", Type = "System.String", Title = "NC High School Name", Placeholder = "NC High School Name (required)", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select NC High School Name:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "ncHighSchools", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "FromDate", Type = "System.DateTime", Title = "From Date", Placeholder = "", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "DateTemplate" } }, new FormControlSettingsDescriptor { Field = "ToDate", Type = "System.DateTime", Title = "To Date", Placeholder = "", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "DateTemplate" } }, new FormControlSettingsDescriptor { Field = "GraduationStatus", Type = "System.String", Title = "Graduation Status", Placeholder = "Graduation Status(required)", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select Graduation Status:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "graduationStatus", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "EarnedCreditAtCmc", Type = "System.Boolean", Title = "Earned Credit At CMC", Placeholder = "", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "SwitchTemplate" } }, new FormGroupArraySettingsDescriptor { Field = "Institutions", Placeholder = "(Institutions)", FormGroupTemplate = new FormGroupTemplateDescriptor { TemplateName = "FormGroupArrayTemplate" }, FormsCollectionDisplayTemplate = new FormsCollectionDisplayTemplateDescriptor { TemplateName = "TextDetailTemplate", Bindings = new List<ItemBindingDescriptor> { new TextItemBindingDescriptor { Name = "Text", Property = "InstitutionName", StringFormat = "{0}", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new TextItemBindingDescriptor { Name = "Detail", Property = "InstitutionState", StringFormat = "{0}", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } } }.ToDictionary(b => b.Name) }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "InstitutionId", Type = "System.Int32", Title = "ID", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "HiddenTemplate" } }, new FormControlSettingsDescriptor { Field = "InstitutionState", Type = "System.String", Title = "Institution State", Placeholder = "Institution State", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select Institution State:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "states", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "InstitutionName", Type = "System.String", Title = "Institution Name", Placeholder = "Institution Name", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select Highest Degree Earned:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "northCarolinaInstitutions", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "StartYear", Type = "System.String", Title = "StartYear", Placeholder = "StartYear (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "EndYear", Type = "System.String", Title = "EndYear", Placeholder = "EndYear (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "HighestDegreeEarned", Type = "System.String", Title = "Highest Degree Earned", Placeholder = "Highest Degree Earned", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select Highest Degree Earned:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "degreeEarned", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, }, ModelType = typeof(InstitutionModel).AssemblyQualifiedName, Type = typeof(ICollection<InstitutionModel>).AssemblyQualifiedName, KeyFields = new List<string> { "InstitutionId" } } } }; internal static DataFormSettingsDescriptor PersonalFrom = new() { Title = "Personal", RequestDetails = new FormRequestDetailsDescriptor { GetUrl = "/Personal/GetSingle", ModelType = typeof(UserModel).AssemblyQualifiedName, DataType = typeof(User).AssemblyQualifiedName, Filter = new FilterLambdaOperatorDescriptor { FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "f" }, MemberFullName = "UserId" }, Right = new ConstantOperatorDescriptor { Type = typeof(int).FullName, ConstantValue = 1 } }, SourceElementType = typeof(UserModel).AssemblyQualifiedName, ParameterName = "f" }, SelectExpandDefinition = new SelectExpandDefinitionDescriptor { Selects = new List<string>(), ExpandedItems = new List<SelectExpandItemDescriptor> { new SelectExpandItemDescriptor { MemberName = "Personal" } } } }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormGroupSettingsDescriptor { Field = "Personal", Title = "Personal", ModelType = typeof(PersonalModel).AssemblyQualifiedName, FormGroupTemplate = new FormGroupTemplateDescriptor { TemplateName = "InlineFormGroupTemplate", }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormGroupBoxSettingsDescriptor { GroupHeader = "Name", FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "FirstName", Type = "System.String", Title = "First Name", Placeholder = "First Name (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "MiddleName", Type = "System.String", Title = "Middle Name", Placeholder = "Middle Name (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "LastName", Type = "System.String", Title = "Last Name", Placeholder = "Last Name (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "PrimaryEmail", Type = "System.String", Title = "Primary Email", Placeholder = "Primary Email (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "Suffix", Type = "System.String", Title = "Suffix", Placeholder = "Suffix", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, } }, new FormGroupBoxSettingsDescriptor { GroupHeader = "Address", FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "Address1", Type = "System.String", Title = "Address1", Placeholder = "Address1 (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "Address2", Type = "System.String", Title = "Address2", Placeholder = "Address2", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "City", Type = "System.String", Title = "City", Placeholder = "City (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "County", Type = "System.String", Title = "County", Placeholder = "County (required)", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select County:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "counties", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "State", Type = "System.String", Title = "State", Placeholder = "State (required)", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select State:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "states", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "ZipCode", Type = "System.String", Title = "Zip Code", Placeholder = "Zip Code (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, } }, new FormGroupBoxSettingsDescriptor { GroupHeader = "Phone Numbers", FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "CellPhone", Type = "System.String", Title = "Cell Phone", Placeholder = "Cell Phone (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "OtherPhone", Type = "System.String", Title = "Other Phone", Placeholder = "Other Phone (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } } } } } } }, FormType = FormType.Detail, ModelType = typeof(UserModel).AssemblyQualifiedName }; internal static DataFormSettingsDescriptor PersonalFromWithDefaultGroupForSomeFields = new() { Title = "PersonalRoot", RequestDetails = new FormRequestDetailsDescriptor { GetUrl = "/Personal/GetSingle", ModelType = typeof(UserModel).AssemblyQualifiedName, DataType = typeof(User).AssemblyQualifiedName, Filter = new FilterLambdaOperatorDescriptor { FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "f" }, MemberFullName = "UserId" }, Right = new ConstantOperatorDescriptor { Type = typeof(int).FullName, ConstantValue = 1 } }, SourceElementType = typeof(UserModel).AssemblyQualifiedName, ParameterName = "f" }, SelectExpandDefinition = new SelectExpandDefinitionDescriptor { Selects = new List<string>(), ExpandedItems = new List<SelectExpandItemDescriptor> { new SelectExpandItemDescriptor { MemberName = "Personal" } } } }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormGroupSettingsDescriptor { Field = "Personal", Title = "Personal", ModelType = typeof(PersonalModel).AssemblyQualifiedName, FormGroupTemplate = new FormGroupTemplateDescriptor { TemplateName = "InlineFormGroupTemplate", }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormGroupBoxSettingsDescriptor { GroupHeader = "Address", FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "Address1", Type = "System.String", Title = "Address1", Placeholder = "Address1 (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "Address2", Type = "System.String", Title = "Address2", Placeholder = "Address2", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "City", Type = "System.String", Title = "City", Placeholder = "City (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "County", Type = "System.String", Title = "County", Placeholder = "County (required)", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select County:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "counties", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "State", Type = "System.String", Title = "State", Placeholder = "State (required)", DropDownTemplate = new DropDownTemplateDescriptor { TemplateName = "PickerTemplate", TitleText = "Select State:", LoadingIndicatorText = "Loading ...", TextField = "Text", ValueField = "Value", TextAndValueSelector = new SelectorLambdaOperatorDescriptor { Selector = new SelectOperatorDescriptor { SourceOperand = new OrderByOperatorDescriptor { SourceOperand = new WhereOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "$it" }, FilterBody = new EqualsBinaryOperatorDescriptor { Left = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "ListName" }, Right = new ConstantOperatorDescriptor { ConstantValue = "states", Type = typeof(string).AssemblyQualifiedName } }, FilterParameterName = "l" }, SelectorBody = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "l" }, MemberFullName = "Text" }, SortDirection = LogicBuilder.Expressions.Utils.Strutures.ListSortDirection.Descending, SelectorParameterName = "l" }, SelectorBody = new MemberInitOperatorDescriptor { MemberBindings = new Dictionary<string, OperatorDescriptorBase> { ["Value"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Value" }, ["Text"] = new MemberSelectorOperatorDescriptor { SourceOperand = new ParameterOperatorDescriptor { ParameterName = "s" }, MemberFullName = "Text" } }, NewType = typeof(LookUpsModel).AssemblyQualifiedName }, SelectorParameterName = "s" }, SourceElementType = typeof(IQueryable<LookUpsModel>).AssemblyQualifiedName, ParameterName = "$it", BodyType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName }, RequestDetails = new RequestDetailsDescriptor { DataSourceUrl = "api/Dropdown/GetObjectDropdown", ModelType = typeof(LookUpsModel).AssemblyQualifiedName, DataType = typeof(LookUps).AssemblyQualifiedName, ModelReturnType = typeof(IEnumerable<LookUpsModel>).AssemblyQualifiedName, DataReturnType = typeof(IEnumerable<LookUps>).AssemblyQualifiedName } } }, new FormControlSettingsDescriptor { Field = "ZipCode", Type = "System.String", Title = "Zip Code", Placeholder = "Zip Code (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, } }, new FormGroupBoxSettingsDescriptor { GroupHeader = "Phone Numbers", FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "CellPhone", Type = "System.String", Title = "Cell Phone", Placeholder = "Cell Phone (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "OtherPhone", Type = "System.String", Title = "Other Phone", Placeholder = "Other Phone (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } } } } } }, new FormGroupSettingsDescriptor { Field = "Personal", Title = "Personal", ModelType = typeof(PersonalModel).AssemblyQualifiedName, FormGroupTemplate = new FormGroupTemplateDescriptor { TemplateName = "InlineFormGroupTemplate", }, FieldSettings = new List<FormItemSettingsDescriptor> { new FormControlSettingsDescriptor { Field = "FirstName", Type = "System.String", Title = "First Name", Placeholder = "First Name (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "MiddleName", Type = "System.String", Title = "Middle Name", Placeholder = "Middle Name (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "LastName", Type = "System.String", Title = "Last Name", Placeholder = "Last Name (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "PrimaryEmail", Type = "System.String", Title = "Primary Email", Placeholder = "Primary Email (required)", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, new FormControlSettingsDescriptor { Field = "Suffix", Type = "System.String", Title = "Suffix", Placeholder = "Suffix", TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" } }, } }, }, FormType = FormType.Detail, ModelType = typeof(UserModel).AssemblyQualifiedName }; } }
using System.Collections.Generic; namespace MVC_Entity.Models { public class Adress { public Adress() { } public int AdressID { get; set; } public string Street { get; set; } public string City { get; set; } public string Zip { get; set; } public IList<Person> Persons { get; set; } } }
using Mathml.Operations; using System; using System.Collections.Generic; using System.Xml.Linq; namespace Mathml { /// <summary> /// Helper for parsing operations from a predetermined XML file. /// </summary> public class XmlParser { private const string INPUT_FILE = "Data/math.xml"; private const string DESCRIPTION_NAME = "Description"; private const char DESCRIPTION_DIVIDER = ';'; private const string VALUE1_NAME = "Value1"; private const string VALUE2_NAME = "Value2"; private const short USERNAME = 0; private const short OPERATION_NAME = 1; private const short MISCELLANEOUS = 2; private enum OperationName { Add, Subtract, Multiply, Divide } private const char ADDITION_SYMBOL = '+'; private const char SUBTRACTION_SYMBOL = '-'; private const char MULTIPLACATION_SYMBOL = '*'; private const char DIVISION_SYMBOL = '/'; /// <summary> /// Parses operations from a predertmined XML file. Operations with bad values will be skipped. /// </summary> /// <returns>The successfully parsed operations</returns> public static List<Operation> RetrieveOperations() { XDocument doc = XDocument.Load(INPUT_FILE); List<Operation> parsedOperations = new List<Operation>(); foreach (XElement xmlOperation in doc.Root.Elements()) { Operation parsedOperation = ParseXmlOperation(xmlOperation); if (parsedOperation != null) { parsedOperations.Add(parsedOperation); } } return parsedOperations; } private static Operation ParseXmlOperation(XElement xmlOperation) { // Description XElement descriptionElement = xmlOperation.Element(DESCRIPTION_NAME); string[] parsedDescription = descriptionElement.Value.Split(DESCRIPTION_DIVIDER); // Values XElement value1Element = xmlOperation.Element(VALUE1_NAME); XElement value2Element = xmlOperation.Element(VALUE2_NAME); bool value1WasConverted = int.TryParse(value1Element.Value, out int value1); bool value2WasConverted = int.TryParse(value2Element.Value, out int value2); // Operation type bool operationTypeWasParsed = Enum.TryParse(xmlOperation.Name.LocalName, out OperationName kindOfOperation); Operation parsedOperation; // If either value isn't an integer, then skip it: if (!value1WasConverted || !value2WasConverted) { return null; } // If the operation wasn't recognized, then skip it: if (!operationTypeWasParsed) { return null; } switch (kindOfOperation) { case OperationName.Add: parsedOperation = new Addition(); AssignOperationValues(parsedOperation, parsedDescription, value1, value2); parsedOperation.OperationSymbol = ADDITION_SYMBOL; return parsedOperation; case OperationName.Subtract: parsedOperation = new Subtraction(); AssignOperationValues(parsedOperation, parsedDescription, value1, value2); parsedOperation.OperationSymbol = SUBTRACTION_SYMBOL; return parsedOperation; case OperationName.Multiply: parsedOperation = new Multiplication(); AssignOperationValues(parsedOperation, parsedDescription, value1, value2); parsedOperation.OperationSymbol = MULTIPLACATION_SYMBOL; return parsedOperation; case OperationName.Divide: parsedOperation = new Division(); AssignOperationValues(parsedOperation, parsedDescription, value1, value2); parsedOperation.OperationSymbol = DIVISION_SYMBOL; return parsedOperation; default: return null; } } private static void AssignOperationValues(Operation operation, string[] parsedDescription, int value1, int value2) { operation.Username = parsedDescription[USERNAME]; operation.OperationName = parsedDescription[OPERATION_NAME]; operation.MiscellaneousInfo = parsedDescription[MISCELLANEOUS]; operation.Value1 = value1; operation.Value2 = value2; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MyPage.Data; using MyPage.Data.DAL; using MyPage.Models; using MyPage.Models.Infra; namespace MyPage.Controllers { [Authorize] public class UsuarioController : Controller { private readonly UserManager<Usuario> _userManager; public UsuarioController(UserManager<Usuario> userManager, Contexto contexto) { _userManager = userManager; } public async Task<IActionResult> Index() { return View(await _userManager.Users.ToListAsync()); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(RegistrarNovoUsuarioViewModel model) { if (ModelState.IsValid) { var user = new Usuario { Nome = model.Nome, Sobrenome = model.Sobrenome, Apelido = model.Apelido, TpAcesso = model.TpAcesso, UserName = model.UserName, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { //_logger.LogInformation("Usuário criou uma nova conta com senha."); //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //await _signInManager.SignInAsync(user, isPersistent: false); //_logger.LogInformation("Usuário acesso com a conta criada."); return RedirectToAction(nameof(Index)); } AddErrors(result); } return View(model); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public async Task<IActionResult> Edit(string id) { return await GetUserViewById(id); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(string id, Usuario usuario) { if (id != usuario.Id) { return NotFound(); } if (ModelState.IsValid) { try { await _userManager.UpdateAsync(usuario); //await usuarioDAL.SetUsuario(usuario); TempData["Mensagem"] = $"O Usuario '{usuario.NomeCompleto} foi alterado com sucesso!'"; } catch (DbUpdateConcurrencyException) { return NotFound(); } return RedirectToAction(nameof(Index)); } return View(usuario); } public async Task<IActionResult> Details(string id) { return await GetUserViewById(id); } public async Task<IActionResult> Delete(string id) { return await GetUserViewById(id); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> ConfirmDelete(string id) { Usuario usuario = await _userManager.FindByIdAsync(id); await _userManager.DeleteAsync(usuario); TempData["Mensagem"] = $"O Usuario {usuario.NomeCompleto} foi removido com sucesso!"; return RedirectToAction(nameof(Index)); } public async Task<IActionResult> GetUserViewById(string id) { if (id == null) { return NotFound(); } var usuario = await _userManager.FindByIdAsync(id); //var usuario = await usuarioDAL.GetUsuarioById(id); if (usuario == null) { return NotFound(); } return View(usuario); } } }
using System; using System.Collections.Generic; using System.Text; //Write a program that reads two numbers N and K and generates all the variations of K elements from the set [1..N]. Example: // N = 3, K = 2 -> {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3} class Program { static void Main() { Console.Write("Enter N: "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter K: "); int k = int.Parse(Console.ReadLine()); int[] num = new int[k]; Generate(num, n, k-1); } private static void Generate(int[] num, int n, int index) { if (index == -1) // bottom of recursion { foreach (var item in num) { Console.Write(item+" "); } Console.WriteLine(); } else { for (int i = 1; i <= n; i++) { num[index] = i; Generate(num, n, index - 1); //recursion } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ResourceManager : MonoBehaviour { public static ResourceManager instance = null; public List<GameObject> resourcePrefabs = new List<GameObject>(); public GameObject procedualWeaponPrefab = null; public GameObject weaponDropPrefab = null; public GameObject currencyPrefab; public string currencyName = "Coins"; public string fuelName = "fuel"; public string specialCurrencyName = "special"; // Start is called before the first frame update void Start() { init(); } // Update is called once per frame void Update() { } void init() { instance = this; } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game.Mono; [Attribute38("PowerHistoryInfo")] public class PowerHistoryInfo : MonoClass { public PowerHistoryInfo(IntPtr address) : this(address, "PowerHistoryInfo") { } public PowerHistoryInfo(IntPtr address, string className) : base(address, className) { } public int GetEffectIndex() { return base.method_11<int>("GetEffectIndex", Array.Empty<object>()); } public bool ShouldShowInHistory() { return base.method_11<bool>("ShouldShowInHistory", Array.Empty<object>()); } public int mEffectIndex { get { return base.method_2<int>("mEffectIndex"); } } public bool mShowInHistory { get { return base.method_2<bool>("mShowInHistory"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SSL { public partial class Menu : Form { public List<Player> listPlayer; //autoscale public float newWidth; public float newHeight; public float originalWidth = 1280; public float originalHeight = 720; public Point btnJoueurOldLocation; public Point btnJouerOldLocation; public Point btnScoreOldLocation; public Menu() { InitializeComponent(); //autoscale btnJoueurOldLocation = btnJoueur.Location; btnJouerOldLocation = btnJouer.Location; btnScoreOldLocation = btnScore.Location; } private void btnQuitter_Click(object sender, EventArgs e) { //Demande une confirmation avant de quitter l'application complètement DialogResult result = MessageBox.Show("Êtes-vous sûr de vouloir quitter l'application ?", "Quitter ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == System.Windows.Forms.DialogResult.Yes) { //Environment.Exit(0); System.Windows.Forms.Application.ExitThread(); } } private void btnJoueur_Click(object sender, EventArgs e) { Joueur frmJoueur = new Joueur(this); frmJoueur.Show(); this.Hide(); } private void btnJouer_Click(object sender, EventArgs e) { Jouer frmJouer = new Jouer(this); frmJouer.Show(); this.Hide(); } private void btnScore_Click(object sender, EventArgs e) { Score frmScore = new Score(this); frmScore.Show(); this.Hide(); } private void Menu_Load(object sender, EventArgs e) { newWidth = this.Width; newHeight = this.Height; ResizeControls(); } private void ResizeControls() { float scaleFactorWidth = originalWidth / newWidth; float scaleFactorHeight = originalHeight / newHeight; Control.ControlCollection controlCollection = this.Controls; foreach (Control item in controlCollection) { //Point oldLocation = item.Location; //if (item.GetType() == typeof(Button)){} item.Size = new Size(Convert.ToInt32(item.Size.Width / scaleFactorWidth), Convert.ToInt32(item.Size.Height / scaleFactorHeight)); item.Font = new Font(item.Font.FontFamily, item.Font.Size / scaleFactorHeight); } btnQuitter.Left = Convert.ToInt32(newWidth - btnQuitter.Width - 25); picBoxLogo.Location = new Point((this.Width - picBoxLogo.Width) / 2, Convert.ToInt32(50 / scaleFactorHeight)); btnJoueur.Location = new Point(Convert.ToInt32(btnJoueurOldLocation.X / scaleFactorHeight), Convert.ToInt32(btnJoueurOldLocation.Y / scaleFactorHeight)); btnJouer.Location = new Point(Convert.ToInt32(btnJouerOldLocation.X / scaleFactorHeight), Convert.ToInt32(btnJouerOldLocation.Y / scaleFactorHeight)); btnScore.Location = new Point(Convert.ToInt32(btnScoreOldLocation.X / scaleFactorHeight), Convert.ToInt32(btnScoreOldLocation.Y / scaleFactorHeight)); } } }
using EliteK9.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace EliteK9.Controllers { public class NotificationsController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); /// <summary> /// lists all notifications with buttons to create and delete /// </summary> /// <returns></returns> public ActionResult Notifications() { return View(NotificationDB.GetNotifications(db)); } /// <summary> /// creates a notification /// </summary> /// <returns></returns> public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Notifications notifications) { if (ModelState.IsValid) { NotificationDB.AddNotification(db, notifications); return RedirectToAction("Notifications"); } return View(notifications); } /// <summary> /// Deletes the selected Notification from the notifications page /// </summary> /// <returns></returns> public ActionResult Delete() { return View(); } [HttpPost] public ActionResult Delete(int id) { Notifications Notification = NotificationDB.FindNotification(db, id); if (Notification != null) { NotificationDB.DeleteNotification(db, Notification); return RedirectToAction("Notifications"); } return View(); } } }
using UnityEngine; using System.Collections; public class log : MonoBehaviour { /* * - removed JointPosition script from Ball object * - created room * * * */ }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using OxyPlot; using OxyPlot.Series; namespace Ekonometria { public sealed partial class Result : Page { Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; public Result() { this.InitializeComponent(); } private int Find_Last_Empty() { int i = 1; while (true) { if (localSettings.Values["x" + i] == null) return i; i++; } } private int Count_Sum_x() { int last = Find_Last_Empty(); int sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["x" + i].ToString(); sum += Convert.ToInt16(val); } return sum; } private int Count_Sum_y() { int last = Find_Last_Empty(); int sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["y" + i].ToString(); sum += Convert.ToInt32(val); } return sum; } private double Count_Average_x() { int last = Find_Last_Empty(); double sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["x" + i].ToString(); sum += Convert.ToDouble(val); } if ((last - 1) == 0) { return 0; } return (sum / (last-1)); } private double Count_Average_y() { int last = Find_Last_Empty(); double sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["y" + i].ToString(); sum += Convert.ToDouble(val); } if ((last - 1) == 0) { return 0; } return (sum / (last - 1)); } private double Count_Beta() { int last = Find_Last_Empty(); double sum = 0; double sumM = 0; double avex = Count_Average_x(); double avey = Count_Average_y(); for (int i = 1; i < last; i++) { string valx = localSettings.Values["x" + i].ToString(); string valy = localSettings.Values["y" + i].ToString(); sumM += ((Convert.ToDouble(valx) - avex) * (Convert.ToDouble(valx) - avex)); } for (int i = 1; i < last; i++) { string valx = localSettings.Values["x" + i].ToString(); string valy = localSettings.Values["y" + i].ToString(); sum += ((Convert.ToDouble(valx) - avex) * (Convert.ToDouble(valy) - avey)); } return sum/sumM; } private double Count_Alpha() { double avey = Count_Average_y(); double avex = Count_Average_x(); double Beta = Count_Beta(); return avey - Beta * avex; } protected override void OnNavigatedTo(NavigationEventArgs e) { SumX.Text = Count_Sum_x().ToString(); SumY.Text = Count_Sum_y().ToString(); if (Count_Average_x().ToString().Length > 4) { AveX.Text = Count_Average_x().ToString().Substring(0, 4); } else { AveX.Text = Count_Average_x().ToString(); } if (Count_Average_y().ToString().Length > 4) { AveY.Text = Count_Average_y().ToString().Substring(0, 4); } else { AveY.Text = Count_Average_y().ToString(); } if (Count_Beta().ToString().Length > 4) { Beta.Text = Count_Beta().ToString().Substring(0, 4); } else { Beta.Text = Count_Beta().ToString(); } if (Count_Alpha().ToString().Length > 4) { Alph.Text = Count_Alpha().ToString().Substring(0, 4); } else { Alph.Text = Count_Alpha().ToString(); } } private void ButtonBack_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(MainPage)); } } public class MainViewModel { Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; private int Find_Last_Empty() { int i = 1; while (true) { if (localSettings.Values["x" + i] == null) return i; i++; } } private int Count_Sum_x() { int last = Find_Last_Empty(); int sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["x" + i].ToString(); sum += Convert.ToInt16(val); } return sum; } private int Count_Sum_y() { int last = Find_Last_Empty(); int sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["y" + i].ToString(); sum += Convert.ToInt32(val); } return sum; } private double Count_Average_x() { int last = Find_Last_Empty(); int sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["x" + i].ToString(); sum += Convert.ToInt32(val); } if ((last - 1) == 0) { return 0; } return sum / (last-1); } private double Count_Average_y() { int last = Find_Last_Empty(); int sum = 0; for (int i = 1; i < last; i++) { string val = localSettings.Values["y" + i].ToString(); sum += Convert.ToInt32(val); } if ((last - 1) == 0) { return 0; } return sum / (last - 1); } private double Count_Beta() { int last = Find_Last_Empty(); double sum = 0; double sumM = 0; double avex = Count_Average_x(); double avey = Count_Average_y(); for (int i = 1; i < last; i++) { string valx = localSettings.Values["x" + i].ToString(); string valy = localSettings.Values["y" + i].ToString(); sumM += ((Convert.ToDouble(valx) - avex) * (Convert.ToDouble(valx) - avex)); } for (int i = 1; i < last; i++) { string valx = localSettings.Values["x" + i].ToString(); string valy = localSettings.Values["y" + i].ToString(); sum += ((Convert.ToDouble(valx) - avex) * (Convert.ToDouble(valy) - avey)); } return sum / sumM; } private double Count_Alpha() { double avey = Count_Average_y(); double avex = Count_Average_x(); double Beta = Count_Beta(); return avey - Beta * avex; } private int minimal(){ int min = 99999; int i = 1; while (localSettings.Values["x" + i] != null) { string val = localSettings.Values["x" + i].ToString(); if (Convert.ToInt32(val) < min) { min = Convert.ToInt32(val); } i++; } return min; } private int maximum() { int max = 0; int i = 1; while (localSettings.Values["x" + i] != null) { string val = localSettings.Values["x" + i].ToString(); if (Convert.ToInt32(val) > max) { max = Convert.ToInt32(val); } i++; } return max; } private double function(double x) { double a = Count_Alpha(); double b = Count_Beta(); return b * x + a; } public MainViewModel() { if (localSettings.Values["x1"] == null) { this.MyModel = new PlotModel { }; } else { int min = minimal(); int max = maximum(); this.MyModel = new PlotModel { }; var lineSeries = new LineSeries(); int i = 1; while (localSettings.Values["x" + i] != null) { string valx = localSettings.Values["x" + i].ToString(); string valy = localSettings.Values["y" + i].ToString(); lineSeries.Points.Add(new DataPoint(Convert.ToDouble(valx), Convert.ToDouble(valy))); i++; } lineSeries.Color = OxyPlot.OxyColors.Transparent; lineSeries.MarkerFill = OxyPlot.OxyColors.SteelBlue; lineSeries.MarkerType = OxyPlot.MarkerType.Circle; string a = null; string b = null; if (Count_Beta().ToString().Length > 4) { b = Count_Beta().ToString().Substring(0, 4); } else { b = Count_Beta().ToString(); } if (Count_Alpha().ToString().Length > 4) { a = Count_Alpha().ToString().Substring(0, 4); } else { a = Count_Alpha().ToString(); } if(Convert.ToDouble(a)>0){ this.MyModel.Series.Add(new FunctionSeries(function, min - 2, max + 2, 0.1, "f(x)=" + b + "x+" + a)); } else{ this.MyModel.Series.Add(new FunctionSeries(function, min - 2, max + 2, 0.1, "f(x)=" + b + "x" + a)); } this.MyModel.Series.Add(lineSeries); } } public PlotModel MyModel { get; private 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; namespace topic2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (graphics == null) graphics = this.CreateGraphics(); output(); drawCayleyTree(10, 200, 310, 100, -Math.PI / 2); } private Graphics graphics; double th1; double th2; double per1; double per2; double k; void drawCayleyTree(int n, double x0, double y0, double leng, double th) { if (n == 0) return; double x1 = x0 + leng * Math.Cos(th); double x2 = x0 + leng * k * Math.Cos(th); double y1 = y0 + leng * Math.Sin(th); double y2 = y0 + leng * k * Math.Sin(th); drawLine(x0, y0, x1, y1); drawCayleyTree(n - 1, x1, y1, per1 * leng, th + th1); drawCayleyTree(n - 1, x2, y2, per2 * leng, th - th2); } void drawLine(double x0, double y0, double x1, double y1) { try { graphics.DrawLine(Pens.Blue, (int)x0, (int)y0, (int)x1, (int)y1); } catch (Exception e) { Console.WriteLine("input error: " + e.Message); } } void output() { try { string a = textBox1.Text; string b = textBox2.Text; string c = textBox3.Text; string d = textBox4.Text; string e = textBox5.Text; double A = double.Parse(a); double B = double.Parse(b); double C = double.Parse(c); double D = double.Parse(d); double E = double.Parse(e); k = E; th1 = A * Math.PI / 180; th2 = B * Math.PI / 180; per1 = C; per2 = D; } catch (Exception e) { Console.WriteLine("input error: " + e.Message); } } } }
public static bool IsPowerOfThree(int n) { if (n == 1) { return true; } double num = n; bool isPower = false; while (num >= 1) { num = num / 3; if (num == 1 && num == (int) num) { return true; } } return isPower; } public static bool IsPowerOfThree(int n) { if (n == 1) { return true; } else if (n == 0 || n % 3 > 0) { return false; } else { return IsPowerOfThree(n / 3); } } class Solution { public: bool isPowerOfThree(int n) { return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0); } };
using System; namespace Athena.Import.Extractors { [Serializable] public class ExtractorException : Exception { public string Text { get; } public ExtractorException(string message, string text) : base(message) { Text = text; } } }
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace KekManager.Database.Migrations { public partial class AddedSubjectKekPek : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Kek", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: false), Description = table.Column<string>(nullable: true), Level = table.Column<int>(nullable: false), Type = table.Column<int>(nullable: false), LearningProgramId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Kek", x => x.Id); table.ForeignKey( name: "FK_Kek_LearningProgram_LearningProgramId", column: x => x.LearningProgramId, principalTable: "LearningProgram", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Subject", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), SupervisorId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Subject", x => x.Id); table.ForeignKey( name: "FK_Subject_ResearchFellow_SupervisorId", column: x => x.SupervisorId, principalTable: "ResearchFellow", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Pek", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: false), Description = table.Column<string>(nullable: true), Level = table.Column<int>(nullable: false), Type = table.Column<int>(nullable: false), SubjectId = table.Column<int>(nullable: false), KekId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Pek", x => x.Id); table.ForeignKey( name: "FK_Pek_Kek_KekId", column: x => x.KekId, principalTable: "Kek", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Pek_Subject_SubjectId", column: x => x.SubjectId, principalTable: "Subject", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "SubjectKekJoinModel", columns: table => new { SubjectId = table.Column<int>(nullable: false), KekId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_SubjectKekJoinModel", x => new { x.KekId, x.SubjectId }); table.ForeignKey( name: "FK_SubjectKekJoinModel_Kek_KekId", column: x => x.KekId, principalTable: "Kek", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_SubjectKekJoinModel_Subject_SubjectId", column: x => x.SubjectId, principalTable: "Subject", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "Subject", columns: new[] { "Id", "Name", "SupervisorId" }, values: new object[,] { { 1, "Teleinformatyka", 3 }, { 2, "Algorytmy i Struktury Danych", 1 }, { 3, "Projektowanie Systemów Informatycznych II", null }, { 4, "Analiza Matematyczna I", null } }); migrationBuilder.CreateIndex( name: "IX_Kek_LearningProgramId", table: "Kek", column: "LearningProgramId"); migrationBuilder.CreateIndex( name: "IX_Pek_KekId", table: "Pek", column: "KekId"); migrationBuilder.CreateIndex( name: "IX_Pek_SubjectId", table: "Pek", column: "SubjectId"); migrationBuilder.CreateIndex( name: "IX_Subject_SupervisorId", table: "Subject", column: "SupervisorId"); migrationBuilder.CreateIndex( name: "IX_SubjectKekJoinModel_SubjectId", table: "SubjectKekJoinModel", column: "SubjectId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Pek"); migrationBuilder.DropTable( name: "SubjectKekJoinModel"); migrationBuilder.DropTable( name: "Kek"); migrationBuilder.DropTable( name: "Subject"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TopPanelAnimator : MonoBehaviour { Animator anim; InstantiateTower instTower; void Awake () { anim = GetComponent<Animator>(); instTower = GameObject.FindGameObjectWithTag("GameController").GetComponent<InstantiateTower>(); //reference script } public void TopPanelDown() { anim.SetBool("TopPanelOn", true); } public void TopPanelUp() { anim.SetBool("TopPanelOn", false); instTower.colorReset(instTower.spawnPoints); //set all spawnPoints in main state } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; //using Practice3; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace WinForm { class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main(string[] args) { using (var db = new OrderContext()) { var order = new Order(1, "aaa"); db.Orders.Add(order); db.SaveChanges(); } //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); } } }
using UnityEngine; [CreateAssetMenu] public class LobbyPlayersReadyRuntimeSet : RuntimeSet<bool> { public void Ready(int index) { Items[index] = true; } public void NotReady(int index) { Items[index] = false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public int maxHealth; public int currentHealth; public static bool sane; public StatsScreen statScreen; bool isDead; Player() { maxHealth = 100; sane = true; } void Start() { currentHealth = maxHealth; isDead = false; } void Update() { if (Input.GetMouseButtonDown(1)) { sane = false; Debug.Log(sane); } if (Input.GetMouseButtonDown(2)) { sane = true; Debug.Log(sane); } } public void TakeDamage(int damage) { currentHealth -= damage; if (currentHealth <= 0) { Die(); } //sanityCheck(); } void Die() { Debug.Log("Dead"); Destroy(this.gameObject); isDead = true; //statScreen.Stats(); } public bool sanityCheck() { while (currentHealth <= 25) { sane = false; } return sane; } public static bool getSanity() { return sane; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Pitstop { public class LUD_DetectionZoneRepairing : MonoBehaviour { public GameObject builderNative1; public GameObject builderNative2; private bool isPlayerInside = false; [Header("Bridge Reparation")] private bool isBridgeRepaired = false; public GameObject dialogueWhenBridgeIsRepaired; [SerializeField] float timeBeforeCommentingReparation = 1f; [Header("If Only One Builder Is Here")] [SerializeField] float timeBeforeSayingThatABuilderMissed = 1f; public DialogueTrigger dialogueWhenOnlyOneBuilderIsHere; private float timer = 0f; // Update is called once per frame private void Update() { if (isPlayerInside && builderNative1.GetComponent<LUD_NonDialogueReactions>().isArrivedToEast && builderNative2.GetComponent<LUD_NonDialogueReactions>().isArrivedToEast && !isBridgeRepaired) { isBridgeRepaired = true; FindObjectOfType<OpenTheGate>().BridgeReparation(); StartCoroutine(WaitBeforeCommentingReparations()); } else if (isPlayerInside && (builderNative1.GetComponent<LUD_NonDialogueReactions>().isArrivedToEast || builderNative2.GetComponent<LUD_NonDialogueReactions>().isArrivedToEast) && !isBridgeRepaired) { //StartCoroutine(WaitBeforeSayingThatYouNeedSomeoneElse()); if (timer>= timeBeforeSayingThatABuilderMissed) { dialogueWhenOnlyOneBuilderIsHere.TriggerDialogueDirectly(); } else { timer += Time.deltaTime; } } } IEnumerator WaitBeforeCommentingReparations() { yield return new WaitForSeconds(timeBeforeCommentingReparation); dialogueWhenBridgeIsRepaired.GetComponent<DialogueTrigger>().TriggerDialogueDirectly(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { isPlayerInside = true; } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { isPlayerInside = false; } } } }
namespace Core { using System; using Microsoft.ApplicationInsights.AspNetCore; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.SnapshotCollector; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; public class SnapshotCollectorTelemetryProcessorFactory : ITelemetryProcessorFactory { private readonly IServiceProvider _serviceProvider; public SnapshotCollectorTelemetryProcessorFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public ITelemetryProcessor Create(ITelemetryProcessor nextProcessor) { var options = _serviceProvider.GetService<IOptions<SnapshotCollectorConfiguration>>(); return options != null ? new SnapshotCollectorTelemetryProcessor(nextProcessor, options.Value) : new SnapshotCollectorTelemetryProcessor(nextProcessor); } } }
using System.Windows.Forms; using System; namespace QuanLyTiemGiatLa.Danhmuc { public partial class frmCTBangGia : Form { public OnSaved onsaved; private TrangThai TrangThai; public frmCTBangGia() { InitializeComponent(); bndsrcDSMatHang.DataSource = Business.MatHangBO.SelectAll(); bndsrcDSKieuGiatLa.DataSource = Business.KieuGiatLaBO.SelectAll(); this.Load += new System.EventHandler(frmCTBangGia_Load); } private void frmCTBangGia_Load(object sender, System.EventArgs e) { TrangThai = this.BangGia == null ? TrangThai.Them : TrangThai.Sua; txtDonGia.Text = TrangThai == TrangThai.Them ? "" : (this.BangGia as Entity.BangGiaEntity).DonGia.ToString(); if (TrangThai == TrangThai.Them) { cboKieuGiatLa.SelectedIndex = -1; cboMatHang.SelectedIndex = -1; } } public Entity.BangGiaEntity BangGia { set { bndsrcBaogia.DataSource = value; } get { return bndsrcBaogia.DataSource as Entity.BangGiaEntity; } } private Boolean CheckForm() { txtDonGia.Text = txtDonGia.Text.Trim(); if (String.IsNullOrEmpty(txtDonGia.Text)) { txtDonGia.Focus(); MessageBox.Show("Đơn giá trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (cboMatHang.SelectedIndex == -1) { cboMatHang.Focus(); MessageBox.Show("Bạn chưa chọn đồ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (cboKieuGiatLa.SelectedIndex == -1) { cboKieuGiatLa.Focus(); MessageBox.Show("Bạn chưa chọn kiểu giặt", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (nudSoSanPham.Value < 1) { nudSoSanPham.Focus(); MessageBox.Show("Số sản phẩm phải > 1", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } return true; } private void btnGhi_Click(object sender, EventArgs e) { if (!this.CheckForm()) return; Entity.BangGiaEntity bg = new Entity.BangGiaEntity() { DonGia = Int64.Parse(txtDonGia.Text), MaHang = Int32.Parse(cboMatHang.SelectedValue.ToString()), MaKieuGiat = Int32.Parse(cboKieuGiatLa.SelectedValue.ToString()), SoSanPham = Convert.ToByte(nudSoSanPham.Value) }; if (TrangThai == TrangThai.Them) { Int32 count = Business.BangGiaBO.CheckExist(0, bg.MaHang, bg.MaKieuGiat); if (count > 0) { MessageBox.Show("Đã tồn tại dữ liệu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { Int32 kq = Business.BangGiaBO.Insert(bg); onsaved(); this.Close(); } } else { bg.IDGia = (bndsrcBaogia.DataSource as Entity.BangGiaEntity).IDGia; Int32 count = Business.BangGiaBO.CheckExist(bg.IDGia, bg.MaHang, bg.MaKieuGiat); if (count > 0) { MessageBox.Show("Đã tồn tại dữ liệu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { Int32 kq = Business.BangGiaBO.Update(bg); onsaved(); this.Close(); } } } private void btnThoat_Click(object sender, EventArgs e) { this.Close(); } private void cboMatHang_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) cboKieuGiatLa.Focus(); } private void cboKieuGiatLa_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) txtDonGia.Focus(); } private void txtDonGia_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) btnGhi_Click(sender, e); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Hotel.Web.Areas.ModulRecepcija.ViewModels { public class TipUslugeDodajVM { public int Id { set; get; } [Required(ErrorMessage ="Naziv je obavezan")] public string Naziv { set; get; } [Required(ErrorMessage ="Cijena je obavezna")] [Range(1,10000,ErrorMessage ="Cijena mora biti veca od 0")] public float Cijena { get; set; } } }
using Android.Hardware; using Android.Runtime; using GSL_Track.Models; namespace GSL_Track.Managers { public delegate void AccelerometerDataChangedHandler(); public class AccelerometerManager : Java.Lang.Object, ISensorEventListener { static readonly object _syncLock = new object(); public SensorManager SensorManager { get; set; } public AccelerometerDataModel CurrentSensorData { get; private set; } public static event AccelerometerDataChangedHandler AccelerometerDataChanged; #region Singletone private static AccelerometerManager instance; private AccelerometerManager() { } public static AccelerometerManager Instance { get { if (instance == null) { instance = new AccelerometerManager(); } return instance; } } #endregion #region Public Methods public void StartAccelerometerTracking() { //currentInterval = -1; SensorManager.RegisterListener(this, SensorManager.GetDefaultSensor(SensorType.LinearAcceleration), SensorDelay.Normal); } public void StopAccelerometerTracking() { if (SensorManager != null) SensorManager.UnregisterListener(this); } #endregion #region ISensorEventListener Implementation public void OnAccuracyChanged(Sensor sensor, [GeneratedEnum] SensorStatus accuracy) { // throw new NotImplementedException(); } public void OnSensorChanged(SensorEvent e) { lock (_syncLock) { var model = VMManager.ToAccelerometerDataModel(e); CurrentSensorData = model; AccelerometerDataChanged?.Invoke(); } // throw new NotImplementedException(); } #endregion //int currentInterval = -1; //List<AccelerometerDataModel> packetData = new List<AccelerometerDataModel>(); } }
using System.Collections.Generic; namespace StreetFinder { public interface IStreetSearchRepository { void CreateStreetRepository(); bool ExistStreetRepository(); void DeleteStreetRepository(); IEnumerable<Street> SearchForStreets(string zipCode, string streetName); void InsertStreet(Street street); void InsertStreets(string zipCode, ISet<string> streets); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace ADO.Net_StoredProcedure { class Program { static void Main(string[] args) { /* CREATE PROCEDURE [dbo].[Procedure] @p1 int, @p2 varchar(5) AS insert into Table1 values(@p1, @p2) */ try { string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Experiment;Integrated Security=True;"; using (SqlConnection connection = new SqlConnection(connectionString)) { string procedureName = "Procedure"; using (SqlCommand cmd = new SqlCommand(procedureName, connection)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; SqlParameter parameter; parameter = new SqlParameter("@p1", 6); cmd.Parameters.Add(parameter); parameter = new SqlParameter() { ParameterName = "@p2", Value = "f", DbType = System.Data.DbType.AnsiString }; cmd.Parameters.Add(parameter); connection.Open(); cmd.ExecuteNonQuery(); connection.Close(); } string procedureName2 = "_Proc"; using (SqlCommand cmd = new SqlCommand(procedureName2, connection)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; //Input Argument cmd.Parameters.Add(new SqlParameter { ParameterName = "@Param", DbType = System.Data.DbType.Int32, Value = 5, }); //Ref Argument SqlParameter _refParam = new SqlParameter { ParameterName = "@RefParam", DbType = System.Data.DbType.Int32, Direction = System.Data.ParameterDirection.Output }; cmd.Parameters.Add(_refParam); //Return Code Argument SqlParameter _returnCode = new SqlParameter { Direction = System.Data.ParameterDirection.ReturnValue }; cmd.Parameters.Add(_returnCode); connection.Open(); object scalarResult = cmd.ExecuteScalar(); int? resultSet = null; if (scalarResult != null && scalarResult != DBNull.Value) resultSet = (int)scalarResult; int refParam = (int)_refParam.Value; int returnCode = (int)_returnCode.Value; connection.Close(); } } } catch (Exception e) { } finally { } } } }
using System; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace DBFirstPlannerAPI.Models { public partial class TestDBContext : DbContext { public TestDBContext() { } public TestDBContext(DbContextOptions<TestDBContext> options) : base(options) { } public virtual DbSet<SessionAttendees> SessionAttendees { get; set; } public virtual DbSet<SessionTypes> SessionTypes { get; set; } public virtual DbSet<Sessions> Sessions { get; set; } public virtual DbSet<UserDetails> UserDetails { get; set; } public virtual DbSet<Users> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=<YourStrong@Passw0rd>;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<SessionAttendees>(entity => { entity.HasKey(e => new { e.UserId, e.SessionId }) .HasName("PK__Session___6F2524F2FE3C588E"); entity.ToTable("Session_Attendees"); entity.Property(e => e.UserId).HasColumnName("user_id"); entity.Property(e => e.SessionId).HasColumnName("session_id"); entity.HasOne(d => d.Session) .WithMany(p => p.SessionAttendees) .HasForeignKey(d => d.SessionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__Session_A__sessi__32E0915F"); entity.HasOne(d => d.User) .WithMany(p => p.SessionAttendees) .HasForeignKey(d => d.UserId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__Session_A__user___31EC6D26"); }); modelBuilder.Entity<SessionTypes>(entity => { entity.ToTable("Session_Types"); entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.SessionType) .IsRequired() .HasColumnName("session_type") .HasMaxLength(32) .IsUnicode(false); }); modelBuilder.Entity<Sessions>(entity => { entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.DateHeld) .HasColumnName("date_held") .HasColumnType("datetime"); entity.Property(e => e.Description) .HasColumnName("description") .HasMaxLength(512) .IsUnicode(false); entity.Property(e => e.Organizer).HasColumnName("organizer"); entity.Property(e => e.SessionTypeId).HasColumnName("session_type_id"); entity.Property(e => e.Title) .IsRequired() .HasColumnName("title") .HasMaxLength(64) .IsUnicode(false); entity.HasOne(d => d.OrganizerNavigation) .WithMany(p => p.Sessions) .HasForeignKey(d => d.Organizer) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__Sessions__organi__2E1BDC42"); entity.HasOne(d => d.SessionType) .WithMany(p => p.Sessions) .HasForeignKey(d => d.SessionTypeId) .HasConstraintName("FK__Sessions__sessio__2F10007B"); }); modelBuilder.Entity<UserDetails>(entity => { entity.HasKey(e => e.UserId) .HasName("PK__User_Det__B9BE370F705D696A"); entity.ToTable("User_Details"); entity.Property(e => e.UserId) .HasColumnName("user_id") .ValueGeneratedNever(); entity.Property(e => e.DateOfBirth) .HasColumnName("date_of_birth") .HasColumnType("datetime"); entity.Property(e => e.FirstName) .IsRequired() .HasColumnName("first_name") .HasMaxLength(32) .IsUnicode(false); entity.Property(e => e.LastName) .IsRequired() .HasColumnName("last_name") .HasMaxLength(32) .IsUnicode(false); entity.Property(e => e.Phone) .HasColumnName("phone") .HasMaxLength(16) .IsUnicode(false); entity.HasOne(d => d.User) .WithOne(p => p.UserDetails) .HasForeignKey<UserDetails>(d => d.UserId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__User_Deta__user___29572725"); }); modelBuilder.Entity<Users>(entity => { entity.HasIndex(e => e.Email) .HasName("unique_email") .IsUnique(); entity.HasIndex(e => e.Username) .HasName("unique_username") .IsUnique(); entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.Email) .IsRequired() .HasColumnName("email") .HasMaxLength(64) .IsUnicode(false); entity.Property(e => e.PasswordHash) .IsRequired() .HasColumnName("password_hash") .HasMaxLength(64) .IsUnicode(false); entity.Property(e => e.PasswordSat) .IsRequired() .HasColumnName("password_sat") .HasMaxLength(32) .IsUnicode(false); entity.Property(e => e.Username) .IsRequired() .HasColumnName("username") .HasMaxLength(32) .IsUnicode(false); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawners : MonoBehaviour { public List<GameObject> entities = new List<GameObject>(); [SerializeField] private GameObject player; //0 = hostile bird, 1 = coins, 2 = shield private float timer = 0; private float spawntime = 75; // Update is called once per frame void Update () { if (player.GetComponent<Player_Movement>().GetScore() >= 30) spawntime = 45.5f; Spawn(); } void Spawn() { timer++; if (timer >= spawntime) { //spawns birds Instantiate(entities[0], new Vector3(10, Random.Range(-3.5f, 5), 0), Quaternion.identity); if (player.GetComponent<Player_Movement>().GetScore() >= 60) Instantiate(entities[0], new Vector3(10, Random.Range(-3.5f, 5), 0), Quaternion.identity); if (player.GetComponent<Player_Movement>().GetScore() >= 130) Instantiate(entities[0], new Vector3(10, Random.Range(-3.5f, 5), 0), Quaternion.identity); //spawns coins if (Random.Range(0,2) == 1)Instantiate(entities[1], new Vector3(10, Random.Range(-3.5f, 5), 0), Quaternion.identity); //spawns shields if (Random.Range(0, 10) == 1) Instantiate(entities[2], new Vector3(10, Random.Range(-3.5f, 5), 0), Quaternion.identity); timer = 0; } } }
using CheckMySymptoms.Flow.ScreenSettings.Views; using System; using System.Collections.Generic; using System.Text; namespace CheckMySymptoms.Flow.Cache { public class ScreenData { public ScreenSettingsBase ScreenSettings { get; set; } } }
using Microsoft.AspNetCore.Identity; namespace TC.Identidade.Extensions { public class IdentityMensagensPortugues : IdentityErrorDescriber { public override IdentityError DefaultError() { return new IdentityError { Code = nameof(DefaultError), Description = $"Ocorreu um erro desconhecido" }; } public override IdentityError PasswordMismatch() { return new IdentityError { Code = nameof(DefaultError), Description = "Senha incorreta" }; } public override IdentityError InvalidToken() { return new IdentityError { Code = nameof(DefaultError), Description = "Token inválido" }; } public override IdentityError LoginAlreadyAssociated() { return new IdentityError { Code = nameof(DefaultError), Description = "Já existe um usuário com este login" }; } public override IdentityError InvalidEmail(string email) { return new IdentityError { Code = nameof(DefaultError), Description = $"O email '{email}' é inválido" }; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class Villager : MonoBehaviour { static List<Villager> allVillagers = new List<Villager>(); static System.Random randomNumber = new System.Random(); public static Villager RandomVillager() { return allVillagers[randomNumber.Next(0, allVillagers.Count)]; } public static IEnumerable<Villager> IdleVillagers(int count = 1) { return allVillagers.OrderBy((v) => randomNumber.Next()).Take(count); } private bool alive = true; public bool IsLiving() { return alive; } public void Kill() { alive = false; Destroy(this.gameObject); } // Use this for initialization void Start () { allVillagers.Add(this); } // Update is called once per frame void Update () { } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_AudioDistortionFilter : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { AudioDistortionFilter o = new AudioDistortionFilter(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_distortionLevel(IntPtr l) { int result; try { AudioDistortionFilter audioDistortionFilter = (AudioDistortionFilter)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, audioDistortionFilter.get_distortionLevel()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_distortionLevel(IntPtr l) { int result; try { AudioDistortionFilter audioDistortionFilter = (AudioDistortionFilter)LuaObject.checkSelf(l); float distortionLevel; LuaObject.checkType(l, 2, out distortionLevel); audioDistortionFilter.set_distortionLevel(distortionLevel); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.AudioDistortionFilter"); LuaObject.addMember(l, "distortionLevel", new LuaCSFunction(Lua_UnityEngine_AudioDistortionFilter.get_distortionLevel), new LuaCSFunction(Lua_UnityEngine_AudioDistortionFilter.set_distortionLevel), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_AudioDistortionFilter.constructor), typeof(AudioDistortionFilter), typeof(Behaviour)); } }
namespace samsung.sedac.alligatormanagerproject.Api.Entities { public class Departamentos { public int Id { get; set; } public string Name { get; set; } } }
namespace BusinessLogic.Interface.DataAccess { public interface IDataAccess { /// <summary> /// Methid that saves data to database /// </summary> void SaveDataToDatabase(); } }
using LuaInterface; using SLua; using System; public class Lua_BMSymbol : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { BMSymbol o = new BMSymbol(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int MarkAsChanged(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); bMSymbol.MarkAsChanged(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Validate(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); UIAtlas atlas; LuaObject.checkType<UIAtlas>(l, 2, out atlas); bool b = bMSymbol.Validate(atlas); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_sequence(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.sequence); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_sequence(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); string sequence; LuaObject.checkType(l, 2, out sequence); bMSymbol.sequence = sequence; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_spriteName(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.spriteName); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_spriteName(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); string spriteName; LuaObject.checkType(l, 2, out spriteName); bMSymbol.spriteName = spriteName; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_length(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.length); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_offsetX(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.offsetX); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_offsetY(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.offsetY); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_width(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.width); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_height(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.height); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_advance(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.advance); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_uvRect(IntPtr l) { int result; try { BMSymbol bMSymbol = (BMSymbol)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, bMSymbol.uvRect); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "BMSymbol"); LuaObject.addMember(l, new LuaCSFunction(Lua_BMSymbol.MarkAsChanged)); LuaObject.addMember(l, new LuaCSFunction(Lua_BMSymbol.Validate)); LuaObject.addMember(l, "sequence", new LuaCSFunction(Lua_BMSymbol.get_sequence), new LuaCSFunction(Lua_BMSymbol.set_sequence), true); LuaObject.addMember(l, "spriteName", new LuaCSFunction(Lua_BMSymbol.get_spriteName), new LuaCSFunction(Lua_BMSymbol.set_spriteName), true); LuaObject.addMember(l, "length", new LuaCSFunction(Lua_BMSymbol.get_length), null, true); LuaObject.addMember(l, "offsetX", new LuaCSFunction(Lua_BMSymbol.get_offsetX), null, true); LuaObject.addMember(l, "offsetY", new LuaCSFunction(Lua_BMSymbol.get_offsetY), null, true); LuaObject.addMember(l, "width", new LuaCSFunction(Lua_BMSymbol.get_width), null, true); LuaObject.addMember(l, "height", new LuaCSFunction(Lua_BMSymbol.get_height), null, true); LuaObject.addMember(l, "advance", new LuaCSFunction(Lua_BMSymbol.get_advance), null, true); LuaObject.addMember(l, "uvRect", new LuaCSFunction(Lua_BMSymbol.get_uvRect), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_BMSymbol.constructor), typeof(BMSymbol)); } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("CheckBox")] public class CheckBox : PegUIElement { public CheckBox(IntPtr address) : this(address, "CheckBox") { } public CheckBox(IntPtr address, string className) : base(address, className) { } public int GetButtonID() { return base.method_11<int>("GetButtonID", Array.Empty<object>()); } public bool IsChecked() { return base.method_11<bool>("IsChecked", Array.Empty<object>()); } public void OnOut(PegUIElement.InteractionState oldState) { object[] objArray1 = new object[] { oldState }; base.method_8("OnOut", objArray1); } public void OnOver(PegUIElement.InteractionState oldState) { object[] objArray1 = new object[] { oldState }; base.method_8("OnOver", objArray1); } public void OnPress() { base.method_8("OnPress", Array.Empty<object>()); } public void OnRelease() { base.method_8("OnRelease", Array.Empty<object>()); } public void SetButtonID(int id) { object[] objArray1 = new object[] { id }; base.method_8("SetButtonID", objArray1); } public void SetButtonText(string s) { object[] objArray1 = new object[] { s }; base.method_8("SetButtonText", objArray1); } public void SetChecked(bool isChecked) { object[] objArray1 = new object[] { isChecked }; base.method_8("SetChecked", objArray1); } public void SetState(PegUIElement.InteractionState state) { object[] objArray1 = new object[] { state }; base.method_8("SetState", objArray1); } public bool ToggleChecked() { return base.method_11<bool>("ToggleChecked", Array.Empty<object>()); } public int m_buttonID { get { return base.method_2<int>("m_buttonID"); } } public GameObject m_check { get { return base.method_3<GameObject>("m_check"); } } public bool m_checked { get { return base.method_2<bool>("m_checked"); } } public string m_checkOffSound { get { return base.method_4("m_checkOffSound"); } } public string m_checkOnSound { get { return base.method_4("m_checkOnSound"); } } public TextMesh m_text { get { return base.method_3<TextMesh>("m_text"); } } public UberText m_uberText { get { return base.method_3<UberText>("m_uberText"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Uxnet.Web.Module.ForBootstrap { public partial class DropdownMenuItem : System.Web.UI.UserControl { protected Uxnet.Web.Module.SiteAction.SiteMenuItem _dataItem; protected void Page_Load(object sender, EventArgs e) { } public Uxnet.Web.Module.SiteAction.SiteMenuItem DataItem { get { return _dataItem; } set { _dataItem = value; } } public override void DataBind() { if (_dataItem != null) { base.DataBind(); } else { this.Visible = false; } } public virtual void BindData(Uxnet.Web.Module.SiteAction.SiteMenuItem item) { _dataItem = item; this.DataBind(); } protected internal int _level; [Bindable(true)] public int StaticLevel { get; set; } } }
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Threading; using Micro.Net.Abstractions; using Micro.Net.Abstractions.Hosting; using Micro.Net.Core.Configuration; using Micro.Net.Core.Pipeline; using Micro.Net.Dispatch; using Micro.Net.Exceptions; using Micro.Net.Handling; using Micro.Net.Receive; using Micro.Net.Storage.FileSystem; using Newtonsoft.Json; using JsonSerializer = Micro.Net.Serializing.JsonSerializer; using Micro.Net.Transport.Http; using Micro.Net.Transport.Feather; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; namespace Micro.Net { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { MicroHostConfiguration hostConfig = hostContext.Configuration.GetSection("Host").Get<MicroHostConfiguration>(); Assembly assembly = Assembly.LoadFrom(hostConfig.Assembly); IEnumerable<Type> types = assembly.GetExportedTypes().Where(t => t.IsAssignableTo(typeof(IMicroserviceConfigurable))); IMicroserviceConfigurable cfgbl = default; if (!types.Any()) { throw new MicroHostException("No configurable types found!", 1401); } if (string.IsNullOrWhiteSpace(hostConfig.ConfigClass)) { if (types.Count() > 1) { throw new MicroHostException("More than one configurable type found, but none were specified! Designate a configurable type as 'Host:ConfigClass'.", 1402); } else { cfgbl = (IMicroserviceConfigurable)Activator.CreateInstance(types.Single()); } } else { types = types.Where(t => t.Name.Equals(hostConfig.ConfigClass) || t.FullName.Equals(hostConfig.ConfigClass) || t.AssemblyQualifiedName.Equals(hostConfig.ConfigClass)); if (types.Count() > 1) { throw new MicroHostException("Multiple configurable types found matching designated configurable! Use FullName or AssemblyQualifiedName instead.", 1403); } else if (!types.Any()) { throw new MicroHostException($"No configurable types found with name '{hostConfig.ConfigClass}'!", 1404); } else { cfgbl = (IMicroserviceConfigurable)Activator.CreateInstance(types.Single()); } } services.UseMicroNet(mcfg => cfgbl.Configure(mcfg, hostContext.Configuration)); if (services.All(s => s.ServiceType != typeof(ILoggerFactory))) { services.AddLogging(conf => { conf.AddConsole(); }); } }); } }
using System.Threading.Tasks; using Acme.Core.Models; namespace Acme.Core.Repositories { public interface IMerchantRepository { Task<Merchant> GetByIdAsync(string id); } }
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 RestaurantApp.Core; using RestaurantApp.Core.Interfaces; using RestaurantApp.Infrastructure; namespace RestaurantApp.Web.Controllers { public class CartDetailsController : Controller { private ICartDetailRepository _repo; public int pageSize = 10; public CartDetailsController(ICartDetailRepository repo) { _repo = repo; } // GET: CartDetails public ActionResult Index() { return View(); } // GET: CartDetails/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } CartDetail cartDetail = _repo.GetById(Convert.ToInt32(id)); if (cartDetail == null) { return HttpNotFound(); } return View(cartDetail); } // GET: CartDetails/Create public ActionResult Create() { return View(); } // POST: CartDetails/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,CartId,FoodId,Amount,CreatedAt,UpdatedAt")] CartDetail cartDetail) { if (ModelState.IsValid) { cartDetail.CreatedAt = cartDetail.UpdatedAt = DateTime.Now; _repo.Update(cartDetail); return RedirectToAction("Index"); } return View(cartDetail); } // GET: CartDetails/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } CartDetail cartDetail = _repo.GetById(Convert.ToInt32(id)); if (cartDetail == null) { return HttpNotFound(); } return View(cartDetail); } // POST: CartDetails/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,CartId,FoodId,Amount,CreatedAt,UpdatedAt")] CartDetail cartDetail) { if (ModelState.IsValid) { cartDetail.UpdatedAt = DateTime.Now; _repo.Update(cartDetail); return RedirectToAction("Index"); } return View(cartDetail); } public JsonResult Remove(int id) { bool result = _repo.Remove(id); return Json(result, JsonRequestBehavior.AllowGet); } protected override void Dispose(bool disposing) { if (disposing) { } base.Dispose(disposing); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using HardwareInventoryManager.Controllers; using HardwareInventoryManager.Models; using HardwareInventoryManager.Helpers.Import; using Moq; using HardwareInventoryManager.Repository; using System.Linq.Expressions; namespace HardwareInventoryManager.Tests.Services { [TestClass] public class ImportServiceTests { [TestMethod] public void Upload_CSVWithData_Processed() { // ARRANGE var service = new ImportService("david"); string csvString = @"Model,Serial Number,Purchase Date,Warranty Period,Obsolescense Date,Price Paid,Category,Location Description 12345,LLLLLLLL1,10/03/2015,3 years,10/03/2018,100,Desktop,Room 101 456798,MMMMM1,10/03/2014,1 years,10/03/2017,200,Laptop,Room 102 "; // ACT string[] lines = service.ProcessCsvLines(csvString); // ASSERT Assert.AreEqual(3, lines.Length); } [TestMethod] public void ProcessCsvHeader_CSVHeaderSupplied_Processed() { // ARRANGE var service = new ImportService("david"); string header = "Model,Serial Number,Purchase Date,Warranty Period,Obsolescense Date,Price Paid,Category,Location Description"; // ACT string[] headerArray = service.ProcessCsvHeader(header); // ASSERT Assert.AreEqual(8, headerArray.Length); Assert.AreEqual("Model", headerArray[0]); Assert.AreEqual("SerialNumber", headerArray[1]); } [TestMethod] public void ProcessLineToAsset_HeaderAndLineSupplied_Processes() { // ARRANGE Mock<IRepository<Lookup>> m = new Mock<IRepository<Lookup>>(); m.Setup(x => x.Single(It.IsAny<Expression<Func<Lookup, bool>>>())).Returns( new Lookup { Description = "3 Years", Type = new LookupType { Description = "WarrantyPeriod" } } ); var service = new ImportService("david"); string[] header = { "Model", "SerialNumber", "PurchaseDate", "WarrantyPeriod", "ObsolescenseDate", "PricePaid", "Category", "LocationDescription" }; string line = "12345,LLLLLLLL1,10/03/2015,3 years,10/03/2018,100,Desktop,Room 101"; service.LookupRepository = m.Object; // ACT ConvertedAsset convertedAsset = service.ProcessLineToAsset(header, line, 3, 1); Asset asset = convertedAsset.Asset; // ASSERT Assert.IsNotNull(asset); Assert.AreEqual("12345", asset.Model); Assert.AreEqual("LLLLLLLL1", asset.SerialNumber); Assert.AreEqual("10/03/2015", asset.PurchaseDate.Value.ToString("dd/MM/yyyy")); Assert.AreEqual("3 Years", asset.WarrantyPeriod.Description); } [TestMethod] public void ProcessLineToAsset_InvalidPurchaseDate_ErrorSupplied() { // ARRANGE Mock<IRepository<Lookup>> m = new Mock<IRepository<Lookup>>(); m.Setup(x => x.Single(It.IsAny<Expression<Func<Lookup, bool>>>())).Returns( new Lookup { Description = "3 Years", Type = new LookupType { Description = "WarrantyPeriod" } } ); var service = new ImportService("david"); string[] header = { "Model", "SerialNumber", "PurchaseDate", "WarrantyPeriod", "ObsolescenceDate", "PricePaid", "Category", "LocationDescription" }; string line = "12345,LLLLLLLL1,30/30/2015,3 years,july july aug,money,Desktop,Room 101"; service.LookupRepository = m.Object; // ACT ConvertedAsset convertedAsset = service.ProcessLineToAsset(header, line, 3, 1); Asset asset = convertedAsset.Asset; // ASSERT Assert.IsNotNull(asset); Assert.AreEqual("12345", asset.Model); Assert.AreEqual("LLLLLLLL1", asset.SerialNumber); Assert.AreEqual("3 Years", asset.WarrantyPeriod.Description); Assert.AreEqual(3, convertedAsset.Errors.Count); Assert.AreEqual( string.Format(HIResources.Strings.ImportError_PurchaseDate, 1, "30/30/2015"), convertedAsset.Errors[0]); Assert.AreEqual( string.Format(HIResources.Strings.ImportError_ObsolescenseDate, 1, "july july aug"), convertedAsset.Errors[1]); Assert.AreEqual(string.Format(HIResources.Strings.ImportError_PricePaid, 1, "money"), convertedAsset.Errors[2]); } [TestMethod] public void RemoveBlankLines_BlankLines_Cleared() { // ARRANGE string[] linesWithBlanks = { ",,,,,,,", "12345,LLLLLLLL1,30/30/2015,3 years,july july aug,money,Desktop,Room 101", ",,,,,,,", "", "654321,LLLLLLLL1,30/30/2015,3 years,july july aug,money,Desktop,Room 101", ",,,,,,," }; var service = new ImportService("user"); // ACT string[] trimmedLines = service.RemoveBlankLines(linesWithBlanks); // ASSERT Assert.AreEqual(2, trimmedLines.Length); Assert.IsTrue(trimmedLines[0].StartsWith("12345")); Assert.IsTrue(trimmedLines[1].StartsWith("654321")); } } }
using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using System.Web; using System.Collections.Generic; using System; using System.Net.Mail; using WebApp; using Contratos; using Mocks; namespace AnBem.WebApplication.Controllers { //[Authorize] public class DocentesController : BaseController { private static IServicioWeb servicio = new MockService(); // GET: /Docentes/ [HttpGet] public async Task<ActionResult> Index() { return View(servicio.ObtenerDocentes(null, 0,0,"").Lista); } // GET: /Docentes/Create [HttpGet] public ActionResult Form(int id = 0, bool readOnly = false, bool delete = false) { var usuario = new Docente(); ViewBag.Title = "Nueva Docente"; if (id != 0) { usuario = servicio.ObtenerDocentePorId(usuarioLogueado, id); if (delete) ViewBag.Title = "Eliminar Docente"; else ViewBag.Title = "Editar Docente"; } if (usuario == null) return RedirectToAction("Index"); ViewBag.ReadOnly = readOnly; ViewBag.Delete = delete; return View(usuario); } // POST: /Docentes/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Form(Docente usuario, bool readOnly = false, bool delete = false) { if (delete) { var resultado = servicio.EliminarDocente(usuario.Id, usuario, usuarioLogueado); if (resultado.EsValido) return RedirectToAction("Index"); TempData["Error"] = resultado; } if (ModelState.IsValid) { Resultado resultado = new Resultado(); if (usuario.Id == 0) resultado = servicio.AltaDocente(usuario, usuarioLogueado); else resultado = servicio.EditarDocente(usuario.Id, usuario, usuarioLogueado); if (resultado.EsValido) return RedirectToAction("Index"); TempData["Error"] = resultado; } ViewBag.ReadOnly = readOnly; ViewBag.Delete = delete; return View(usuario); } } }
using UnityEngine; using Minigame4; using System.Collections; using System.Collections.Generic; public class MiniGame4_Manager : MiniGameSingleton<MiniGame4_Manager> { #region variables /// <summary> /// Лэйбл для отображения оставшегося времени /// </summary> public UILabel labelTime; /// <summary> /// Трансформ, содержащий все иконки /// </summary> public Transform containerIcons; /// <summary> /// Время до окончания игры /// </summary> private float _time = 0f; /// <summary> /// Список всех иконок /// </summary> private List<Icon> listIcons; /// <summary> /// Список всех теней иконок /// </summary> private List<IconShadow> listIconsShadow; /// <summary> /// Выбранная на данный момент иконка /// </summary> private Icon _currentIcon; /// <summary> /// Выбранная на данный момент тень /// </summary> private IconShadow _currentShadow; /// <summary> /// true - на данный момент работает корутина /// </summary> private bool _isCoroutine = false; #endregion void Awake() { // Для синглтона if (_instance == null) _instance = this; else Destroy(this.gameObject); } void Update() { if (_isPlay) CheckTime(); } public void CloseMenu() { if (!_isCoroutine) Hide(); } /// <summary> /// Инициализация /// </summary> protected override void Init() { _currentIcon = null; if (listIcons == null) MiniGameHelper.FindChildObjects<Icon>(containerIcons, ref listIcons); foreach (Icon icon in listIcons) if (icon != null) icon.Reset(); if (listIconsShadow == null) MiniGameHelper.FindChildObjects<IconShadow>(containerIcons, ref listIconsShadow); foreach (IconShadow shadow in listIconsShadow) if (shadow != null) shadow.Reset(); MiniGameHelper.ListRandomSortTransformPositions<IconShadow>(ref listIconsShadow, 10); } /// <summary> /// Инициализация новой игры /// </summary> /// <param name="time">Время для прохождения</param> public void NewGame(float time) { Init(); Show(); _time = time; _isPlay = true; } public void ClickToggleIcon(Icon icon) { if (!isPlay || icon == null) return; if (_currentIcon != null && _currentIcon != icon) _currentIcon.SetPair(null); _currentIcon = (icon.value) ? icon : null; if (_currentShadow != null) CheckSelectedPair(); } public void ClickToggleIconShadow(IconShadow shadow) { if (!isPlay || shadow == null) return; if (_currentShadow != null && _currentShadow != shadow) _currentShadow.SetPair(null); _currentShadow = (shadow.value) ? shadow : null; if (_currentIcon != null) CheckSelectedPair(); } private void CheckSelectedPair() { if (!isPlay || _currentIcon == null || _currentShadow == null) return; _currentIcon.SetPair(_currentShadow); _currentShadow.SetPair(_currentIcon); _currentIcon = null; _currentShadow = null; CheckWin(); } public void CheckWin() { if (!isPlay || listIcons == null || listIconsShadow == null) return; foreach (Icon icon in listIcons) if (icon.selectPair == null) return; foreach (IconShadow shadow in listIconsShadow) if (shadow.selectPair == null) return; foreach (IconShadow shadow in listIconsShadow) shadow.ShowCorrectPair(); Win(); } protected override void Win() { _isPlay = false; StartCoroutine(WinCoroutine(3f)); } protected IEnumerator WinCoroutine(float delay) { _isCoroutine = true; yield return new WaitForSeconds(delay); base.Win(); _isCoroutine = false; } /// <summary> /// Проверка оставшегося времени до конца игры /// </summary> private void CheckTime() { if (_isPlay) { _time -= Time.deltaTime; if (labelTime != null) labelTime.text = (((int)_time / 60)).ToString("00") + ":" + ((int)_time % 60).ToString("00"); if (_time <= 0) { Debug.Log("Time is out!"); Win(); } } } protected override MiniGameResult GetResult() { int i = 0; foreach (Icon icon in listIcons) if (icon.selectPair != icon.correctPair) i++; return (i == 0) ? MiniGameResult.Gold : (i == 1 || i == 2) ? MiniGameResult.Silver : MiniGameResult.Bronze; } }
using CleanArchitecture.Core.Entities; using CleanArchitecture.Core.Interfaces.Repositories; namespace CleanArchitecture.InfraStructure.Persistence.Repositories { public class ProductRepository : IProductRepository { public void Add(Product product) { throw new System.NotImplementedException(); } public Product GetByID(int id) { throw new System.NotImplementedException(); } public void Remove(Product product) { throw new System.NotImplementedException(); } } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_WindZoneMode : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.WindZoneMode"); LuaObject.addMember(l, 0, "Directional"); LuaObject.addMember(l, 1, "Spherical"); LuaDLL.lua_pop(l, 1); } }
using UnityEngine; using System.Collections; using System.Net.NetworkInformation; using System.ComponentModel.Design.Serialization; public class Obstacle : MonoBehaviour { //Movement speed public float upDownSpeed = 0; public float moveSpeed = 0; //Switch movement diection every x seconds public float switchTime = 2; public float deleteTime = 0; float randomNumber = 0; private Rigidbody2D[] obstacleRigidbodies; void Start () { randomNumber = Random.Range (0.8f, 1.1f); InvokeRepeating ("Switch", 0, switchTime * randomNumber * 1.2f); Invoke ("DestroyThis", deleteTime); obstacleRigidbodies = GetComponentsInChildren <Rigidbody2D> (); // GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveSpeed, upDownSpeed); } void Update () { } void Switch () { upDownSpeed *= -1 * randomNumber; // GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveSpeed, upDownSpeed); foreach (var item in obstacleRigidbodies) { item.velocity = new Vector2 (moveSpeed, upDownSpeed); } } void DestroyThis () { Destroy (gameObject); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DietFood.Models.Enums { public enum MealName { Завтрак, Обед, Ужин, Доп_1, Доп_2 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculator { class Result { // field for doubleResult private double doubleResult; // determines computation depending on operation public void setResult(double x, double y, string op) { if (op == "+") { doubleResult = x + y; } else if (op == "-") { doubleResult = x - y; } else if (op == "*") { doubleResult = x * y; } else if (op == "/") { // check if two numbers are divisable if (y != 0) doubleResult = x / y; else Console.Write($"ERROR: {x} and {y} is not divisable! "); } else if (op == "%") { // check if two numbers are divisable if (y != 0) doubleResult = x % y; else Console.Write($"ERROR: {x} and {y} is not divisable! "); } else if (op.ToUpper() == "QUIT") { System.Environment.Exit(0); } else { // in the case that the user enters something else other than the recommended inputs Console.Write("Wrong input! Please try again."); } } // getter for doubleResult public double getResult() { return doubleResult; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; namespace TableTopCrucible.Core.WPF.Helper { public static class KeyboardHelper { public static bool IsKeyPressed(ModifierKeys key) => ((Keyboard.Modifiers & key) == key); } }
using System; using System.Collections.Generic; namespace OpenGov.Models { public class Meeting { public int Id { get; set; } public Source Source { get; set; } public string BoardId { get; set; } public string BoardName { get; set; } public string MeetingId { get; set; } public string AgendaItemId { get; set; } public DateTime Date { get; set; } public string Title { get; set; } public Uri Url { get; set; } public Uri DocumentsUrl { get; set; } public IList<Match> Matches { get; set; } public IList<Document> Documents { get; set; } } }
using System.Runtime.Serialization; namespace RedLine.Models { [DataContract(Name = "RemoteFile", Namespace = "v1/Models")] public struct RemoteFile { [DataMember(Name = "FileName")] public string FileName { get; set; } [DataMember(Name = "SourcePath")] public string SourcePath { get; set; } [DataMember(Name = "Body")] public byte[] Body { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; namespace TheLivingRoom { class PlaybackEngine { // Get instance of Singleton public static PlaybackEngine GetInstance() { if (_instance != null) { return _instance; } _instance = new PlaybackEngine(); return _instance; } private static PlaybackEngine _instance; // Private constructor private PlaybackEngine() { // Initialize members Parameters = new List<PlaybackParameter>(); SystemVolumeLimit = 1.0; CreateDefaultParameters(); } private void CreateDefaultParameters() { PlaybackParameter distanceVolume = new PlaybackParameter("Distance"); Parameters.Add(distanceVolume); PlaybackParameter handTouch = new PlaybackParameter("Touching Hands"); Parameters.Add(handTouch); } // Interface public void PlaySound(Sound sound) { // Seek to beginning of sound sound.ResetToBeginning(); // Calculate current volume according to parameters and system volume limit double vol = CalculatePlaybackVolume(); Debug.WriteLine("Adjusted volume level: " + vol); sound.AdjustVolume(vol); // Play Sound sound.Play(); } public void PlaySoundPreview(Sound sound) { // Play Sound at full volume sound.ResetToBeginning(); sound.AdjustVolume(SystemVolumeLimit); sound.PlayPreview(); } public void StopPlayback() { // TODO: implement } public bool AdjustParameter(PlaybackParameter parameter, int newValue) { return parameter.AdjustLevel(newValue); } public bool ToggleParameter(PlaybackParameter parameter) { return parameter.Toggle(); } public bool SetVolumeLimit(double newVolume) { if (newVolume >= 0.0 && newVolume <= 1.0) { SystemVolumeLimit = newVolume; return true; } return false; } private double CalculatePlaybackVolume() { if (SystemVolumeLimit == 0.0) { return SystemVolumeLimit; } // Assume default, no parameter volume level is 2/ volume limit double playbackVolume = SystemVolumeLimit * 0.5; // Set maximum volume adjustment factor per parameter such that // if all paramaters were set to 50 system would play at full limit // and if all parameters were set to -50 volume would be half limit. double maxAdjustFactorPerParameter = (SystemVolumeLimit * .5) / NumberParametersOn(); FetchLatestParameterValues(); // Adjust playbackVolume according to parameters foreach (PlaybackParameter param in Parameters) { if (param.IsOn) { playbackVolume += maxAdjustFactorPerParameter * param.Level * param.Multiplier; Debug.WriteLine("Adding: " + maxAdjustFactorPerParameter + " * " + param.Level + " * " + param.Multiplier); } } if (playbackVolume < 0 || playbackVolume > 1) { Debug.WriteLine("Something messed up"); } else { Debug.WriteLine("New volume is " + playbackVolume); } return playbackVolume; } private int NumberParametersOn() { int count = 0; foreach (PlaybackParameter param in Parameters) { if (param.IsOn) { ++count; } } return count; } private static double GetDistanceMultiplier(double distance) { double multiplier = (ZeroedDistance - distance) / ZeroedDistance; if (multiplier <= -1) { // Boundary of calculation return -1; } return multiplier; } private void FetchLatestParameterValues() { // _parameters[0] is distance string distance = Client.GetInstance().HttpGetAsync("/api/kinect/distance"); if (distance != null) { double distanceCast = Convert.ToDouble(distance); Parameters[0].AdjustLevel(GetDistanceMultiplier(distanceCast)); Debug.WriteLine("Distance multiplyer: " + GetDistanceMultiplier(distanceCast)); } // _parameters[1] is hand touch string handContact = Client.GetInstance().HttpGetAsync("/api/kinect/contact"); if (handContact != null) { bool handContactCast = Convert.ToBoolean((string)handContact); Parameters[1].AdjustLevel(handContactCast ? 1 : 0); Debug.WriteLine("Hand Multiplyer: " + (handContactCast ? 1 : 0)); } } // Members public List<PlaybackParameter> Parameters { get; private set; } public double SystemVolumeLimit { get; private set; } // upper limit of playback volume private const double ZeroedDistance = 2.0; // Feet of 'normal separation' apart } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("CardTypeBanner")] public class CardTypeBanner : MonoBehaviour { public CardTypeBanner(IntPtr address) : this(address, "CardTypeBanner") { } public CardTypeBanner(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public static CardTypeBanner Get() { return MonoClass.smethod_15<CardTypeBanner>(TritonHs.MainAssemblyPath, "", "CardTypeBanner", "Get", Array.Empty<object>()); } public CardDef GetCardDef() { return base.method_14<CardDef>("GetCardDef", Array.Empty<object>()); } public void Hide() { base.method_9("Hide", new Class272.Enum20[0], Array.Empty<object>()); } public void Hide(Actor actor) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class }; object[] objArray1 = new object[] { actor }; base.method_9("Hide", enumArray1, objArray1); } public void HideImpl() { base.method_8("HideImpl", Array.Empty<object>()); } public bool IsShown() { return base.method_11<bool>("IsShown", Array.Empty<object>()); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void Show(Actor a) { object[] objArray1 = new object[] { a }; base.method_8("Show", objArray1); } public void ShowImpl() { base.method_8("ShowImpl", Array.Empty<object>()); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public void UpdatePosition() { base.method_8("UpdatePosition", Array.Empty<object>()); } public Actor m_actor { get { return base.method_3<Actor>("m_actor"); } } public GameObject m_minionBanner { get { return base.method_3<GameObject>("m_minionBanner"); } } public GameObject m_root { get { return base.method_3<GameObject>("m_root"); } } public GameObject m_spellBanner { get { return base.method_3<GameObject>("m_spellBanner"); } } public UberText m_text { get { return base.method_3<UberText>("m_text"); } } public GameObject m_weaponBanner { get { return base.method_3<GameObject>("m_weaponBanner"); } } public Color MINION_COLOR { get { return base.method_2<Color>("MINION_COLOR"); } } public Color SPELL_COLOR { get { return base.method_2<Color>("SPELL_COLOR"); } } public Color WEAPON_COLOR { get { return base.method_2<Color>("WEAPON_COLOR"); } } } }
using System; using OCP.AppFramework.Http; namespace OCP.Authentication.TwoFactorAuth { /** * @since 13.0.0 */ public interface IProvidesCustomCSP { /** * @return ContentSecurityPolicy * * @since 13.0.0 */ ContentSecurityPolicy getCSP(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RespawnPoint : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D hitInfo) { if (hitInfo.gameObject.CompareTag("Player")) { PlayerMovement player = hitInfo.GetComponent<PlayerMovement>(); Vector3 pos = this.transform.position; pos.y += 9; player.setRespawnPoint(pos); } } }
using System; namespace ETravel.Coffee.Service.Dtos { public class Order { public virtual Guid? Id { get; set; } public virtual string Vendor { get; set; } public virtual string ExpiresAt { get; set; } public virtual long? Interval { get; set; } public virtual string Owner { get; set; } } }
namespace ConsoleAppGeneratePDFFile.MailService { public static class Supplier { public const string USERNAME_CREDENTIAL = "daviddemabou@gmail.com"; public const string PASSWORD_CREDENTIAL = "Moundou237"; public const string SMTP_CREDENTIAL = "smtp.gmail.com"; public const string MAILPATTERN = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$"; } }
using Newtonsoft.Json.Linq; using Ninject; using System.ServiceModel.Web; using System.Web.Script.Serialization; namespace JKMWCFService { /// <summary> /// Class Name : Estimate /// Author : Pratik Soni /// Creation Date : 10 Jan 2018 /// Purpose : Gets the list of all Estimate. /// Revision : /// </summary> /// <returns></returns> public class Estimate : IEstimate { //BLL.ContactDetails class object to private readonly JKMServices.BLL.Interface.IEstimateDetails bllEstimateDetails; private readonly StandardKernel kernel; //Constructor public Estimate() { log4net.Config.XmlConfigurator.Configure(); StandardKernelLoader standardKernelLoader = new StandardKernelLoader(); kernel = Utility.General.StandardKernel(); kernel = standardKernelLoader.LoadStandardKernel(); bllEstimateDetails = kernel.Get<JKMServices.BLL.Interface.IEstimateDetails>(); } /// <summary> /// Method Name : GetEstimateData /// Author : Pratik Soni /// Creation Date : 10 Jan 2018 /// Purpose : Gets the estimate data for the customer id. /// Revision : /// </summary> /// <param name="userId"></param> /// <returns></returns> public string GetEstimateData(string customerId) { string serviceResponse; serviceResponse = bllEstimateDetails.GetEstimateData(customerId).Replace("\"", "'"); WebOperationContext customContext; customContext = Utility.General.SetCustomHttpStatusCode(JObject.Parse(serviceResponse)); return serviceResponse; } /// <summary> /// Method Name : GetEstimatePDF /// Author : Pratik Soni /// Creation Date : 10 Jan 2018 /// Purpose : Gets the estimate PDF file for the estimateID in the request body. /// Revision : /// </summary> /// <param name="estimateId"></param> /// <returns></returns> public string GetEstimatePDF(string moveId) { string serviceResponse; serviceResponse = bllEstimateDetails.GetEstimatePDF(moveId).Replace("\"", "'"); WebOperationContext customContext; customContext = Utility.General.SetCustomHttpStatusCode(JObject.Parse(serviceResponse)); return serviceResponse; } /// <summary> /// Method Name : PutEstimateData /// Author : Pratik Soni /// Creation Date : 12 Jan 2018 /// Purpose : Updates estimate data for the moveId. Mostly used to set estimate as booked. /// Revision : /// </summary> /// <param name="moveId"></param> /// <returns></returns> public string PutEstimateData(string moveId, EstimateDetail estimateDetail) { JavaScriptSerializer js = new JavaScriptSerializer(); string requestBody = js.Serialize(estimateDetail); string serviceResponse = bllEstimateDetails.PutEstimateData(moveId, requestBody).Replace("\"", "'"); WebOperationContext customContext; customContext = Utility.General.SetCustomHttpStatusCode(JObject.Parse(serviceResponse)); return serviceResponse; } } }
/* DotNetMQ - A Complete Message Broker For .NET Copyright (C) 2011 Halil ibrahim KALKAN This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.IO; using System.Text; namespace MDS.Serialization { /// <summary> /// This class is the default serializer of MDS. /// The serialized object must be deserialized by MDSDefaultDeserializer. /// Only needed serializers designed for MDS. /// </summary> public class MDSDefaultSerializer : IMDSSerializer { #region Private fields /// <summary> /// The stream that is used to write serialized items. /// </summary> private readonly Stream _stream; #endregion #region Public methods /// <summary> /// Creates a new MDSDefaultSerializer object. /// </summary> /// <param name="stream">The stream that is used to write serialized items</param> public MDSDefaultSerializer(Stream stream) { _stream = stream; } /// <summary> /// Serializes a byte. /// </summary> /// <param name="b">byte to serialize</param> public void WriteByte(byte b) { _stream.WriteByte(b); } /// <summary> /// Writes a byte array to serialization stream. /// Byte array may be null or empty. /// </summary> /// <param name="bytes">byte array to write</param> public void WriteByteArray(byte[] bytes) { if (bytes == null) { WriteInt32(-1); } else { WriteInt32(bytes.Length); if (bytes.Length > 0) { _stream.Write(bytes, 0, bytes.Length); } } } /// <summary> /// Serializes a integer. /// </summary> /// <param name="number">integer to serialize</param> public void WriteInt32(int number) { _stream.WriteByte((byte)((number >> 24) & 0xFF)); _stream.WriteByte((byte)((number >> 16) & 0xFF)); _stream.WriteByte((byte)((number >> 8) & 0xFF)); _stream.WriteByte((byte)(number & 0xFF)); } /// <summary> /// Serializes an unsigned integer. /// </summary> /// <param name="number">unsigned integer to serialize</param> public void WriteUInt32(uint number) { WriteInt32((int) number); } /// <summary> /// Serializes a long. /// </summary> /// <param name="number">long to serialize</param> public void WriteInt64(long number) { _stream.WriteByte((byte)((number >> 56) & 0xFF)); _stream.WriteByte((byte)((number >> 48) & 0xFF)); _stream.WriteByte((byte)((number >> 40) & 0xFF)); _stream.WriteByte((byte)((number >> 32) & 0xFF)); _stream.WriteByte((byte)((number >> 24) & 0xFF)); _stream.WriteByte((byte)((number >> 16) & 0xFF)); _stream.WriteByte((byte)((number >> 8) & 0xFF)); _stream.WriteByte((byte)(number & 0xFF)); } /// <summary> /// Serializes a boolean. /// </summary> /// <param name="b">boolean to serialize</param> public void WriteBoolean(bool b) { _stream.WriteByte((byte) (b ? 1 : 0)); } /// <summary> /// Serializes a DateTime object. /// </summary> /// <param name="dateTime">DateTime to serialize</param> public void WriteDateTime(DateTime dateTime) { WriteInt64(dateTime.Ticks); } /// <summary> /// Serializes a char according to UTF8. /// Char may be null or empty. /// Note: A better way may be found. /// </summary> /// <param name="c">char to serialize</param> public void WriteCharUTF8(char c) { WriteByteArray(Encoding.UTF8.GetBytes(c.ToString())); } /// <summary> /// Serializes a string according to UTF8. /// String may be null or empty. /// </summary> /// <param name="text">string to serialize</param> public void WriteStringUTF8(string text) { switch (text) { case null: WriteInt32(-1); break; case "": WriteInt32(0); break; default: WriteByteArray(Encoding.UTF8.GetBytes(text)); break; } } /// <summary> /// Serializes an object that implements IMDSSerializable interface. /// Object may be null. /// </summary> /// <param name="serializableObject">object to serialize</param> public void WriteObject(IMDSSerializable serializableObject) { if (serializableObject == null) { _stream.WriteByte(0); return; } _stream.WriteByte(1); serializableObject.Serialize(this); } /// <summary> /// Serializes an array that all items implements IMDSSerializable interface. /// Object array may be null or empty. /// </summary> /// <param name="serializableObjects">objects to serialize</param> public void WriteObjectArray(IMDSSerializable[] serializableObjects) { if (serializableObjects == null) { WriteInt32(-1); } else { WriteInt32(serializableObjects.Length); for (var i = 0; i < serializableObjects.Length; i++) { WriteObject(serializableObjects[i]); } } } #endregion } }
using UnityEngine; using UnityEditor; using Object = UnityEngine.Object; /**************************************** * * 2020 Alan Mattano * SOARING STARS Lab * * ***************************************/ public class Copy_Path : MonoBehaviour { [MenuItem("Assets/Copy Full Path Location", false, 19)] private static void CopyPathToClipboard() { Object obj = Selection.activeObject; if (obj != null) { if (AssetDatabase.Contains(obj)) { string path = AssetDatabase.GetAssetPath(obj); path = path.TrimStart('A', 's', 's', 'e', 't'); path = Application.dataPath + path; path = path.Replace('/', '\\'); GUIUtility.systemCopyBuffer = path; Debug.Log("The full path was copy to the clipboard:\n" + path); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using POG.Forum; namespace FoxTester { public partial class FoxTester : Form { POG.Forum.VBulletin_3_8_7 _forum; Int32 _nextPost = 1; public FoxTester() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); _forum = new POG.Forum.VBulletin_3_8_7((x) => Invoke(x)); _forum.NewPostsAvailable += new EventHandler<POG.Forum.NewPostsAvailableEventArgs>(_forum_NewPostEvent); _forum.PropertyChanged += new PropertyChangedEventHandler(_forum_PropertyChanged); _forum.StatusUpdate += new EventHandler<POG.Forum.NewStatusEventArgs>(_forum_StatusUpdate); _forum.FinishedReadingThread += new EventHandler(_forum_FinishedReadingThread); } void _forum_FinishedReadingThread(object sender, EventArgs e) { } void _forum_StatusUpdate(object sender, POG.Forum.NewStatusEventArgs e) { txtStatus.Text = e.Status; } void _forum_PropertyChanged(object sender, PropertyChangedEventArgs e) { Console.WriteLine("Property Changed: " + e.PropertyName); if (e.PropertyName == "ThreadURL") { lbPosts.Items.Clear(); } } void _forum_PMReadEvent(object sender, POG.Forum.PMReadEventArgs e) { throw new NotImplementedException(); } void _forum_NewPostEvent(object sender, POG.Forum.NewPostsAvailableEventArgs e) { Post[] posts = _forum.GetPosts(_nextPost, e.NewestPostNumber); foreach (Post post in posts) { lbPosts.Items.Add(post.PostNumber.ToString() + " " + post.Poster); } _nextPost = e.NewestPostNumber + 1; } void _forum_NewPMEvent(object sender, POG.Forum.NewPMEventArgs e) { throw new NotImplementedException(); } private void button1_Click(object sender, EventArgs e) { _forum.ThreadURL = textBox1.Text; } private void button2_Click(object sender, EventArgs e) { _forum.RefreshNow(); } private void button3_Click(object sender, EventArgs e) { _forum.Start(); } private void button4_Click(object sender, EventArgs e) { _forum.Stop(); } private void textBox1_TextChanged(object sender, EventArgs e) { _forum.ThreadURL = textBox1.Text; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Mentors.Models { public class Person { public int Id { get; set; } [Required(ErrorMessage = "Не указано имя")] public string Name { get; set; } [Required(ErrorMessage = "Не указано фамилию")] public string Surname { get; set; } public int Age { get; set; } public string Country { get; set; } public string City { get; set; } public string StudyPlace { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Vk { get; set; } public string Facebook { get; set; } public string LinkedIn { get; set; } } }
using System.Runtime.InteropServices; namespace RedLine.Models.RunPE { [StructLayout(LayoutKind.Explicit, Size = 64)] public struct IMAGE_DOS_HEADER { [FieldOffset(0)] public ushort e_magic; [FieldOffset(60)] public uint e_lfanew; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Lab_4 { public partial class Form1 : Form { private Brush[] color = new Brush[3]; //This will store 3 colors: White, Black, and Red private bool [,] takenSpot = new bool[8, 8]; //Store location of queens on a 8x8 array private int queens; //Keep track of number of Queens public Form1() { InitializeComponent(); } //Check if move is valid: If it is, update the 2D bool array private bool validMove(int x, int y) { //Invalidate the row for (int i = 0; i < 8; i++) { if (takenSpot[i, y]) { return false; } } //Invalidate the column for (int j = 0; j < 8; j++) { if (takenSpot[x, j]) { return false; } } //Go through the diagonals and make them false (4 possible diagonal directions) int diag_1 = x; int diag_2 = x; int diag_3 = x; int diag_4 = x; //Invalidate diagonal spaces from right to left (going down) for (int k = y; ((diag_1 >= 0) && (k >= 0)) && ((diag_1 < 8) && (k < 8)); k--) { if (takenSpot[diag_1, k]) { return false; } diag_1--; } //Invalidate diagonal spaces from left to right (going down) for (int m = y; ((diag_2 >= 0) && (m >= 0)) && ((diag_2 < 8) && (m < 8)); m--) { if (takenSpot[diag_2, m]) { return false; } diag_2++; } //Invalidate diagonal spaces from right to left (going up) for (int n = y; ((diag_3 >= 0) && (n >= 0)) && ((diag_3 < 8) && (n < 8)); n++) { if (takenSpot[diag_3, n]) { return false; } diag_3--; } //Invalidate diagonal spaces from left to right (going up) for (int num10 = y; ((diag_4 >= 0) && (num10 >= 0)) && ((diag_4 < 8) && (num10 < 8)); num10++) { if (takenSpot[diag_4, num10]) { return false; } diag_4++; } //If no conditions are met to be FALSE, the space remains valid (TRUE) return true; } private void Form1_Paint(object sender, PaintEventArgs e) { Graphics graphics = e.Graphics; //Create brush colors in the color array this.color[0] = Brushes.White; this.color[1] = Brushes.Black; this.color[2] = Brushes.Red; //Use this value to determine what brush to use int color_value; //Create the board for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { //If hints box is checked and the box is false, color the square RED if (this.hintBox.Checked && !validMove(i, j)) { color_value = 2; } //If the sume of rows and column are even, color the square BLACK else if (((i + j) % 2) == 0) { color_value = 0; } // else color the square WHITE else { color_value = 1; } //Color the board graphics.FillRectangle(color[color_value], 100 + (i * 50), 100 + (j * 50), 50, 50); graphics.DrawRectangle(Pens.Black, 100 + (i * 50), 100 + (j * 50), 50, 50); //Add the Queens if (takenSpot[i, j]) { //Upper left most point in the square float x_corner = 100 + i * 50; float y_corner = 100 + j * 50; //Font for Queen Font drawFont = new Font("Arial", 30f, FontStyle.Bold); //Draw rectangle as a blueprint for where to place the Q RectangleF guide_box = new RectangleF(x_corner, y_corner, 50f, 50f); //Need StringFormat parameter to place string in center of box StringFormat centerLoc = new StringFormat(); centerLoc.Alignment = StringAlignment.Center; //Horizontal middle centerLoc.LineAlignment = StringAlignment.Center; //Vertical Middle //Use Drawstring that uses RectangleF for centered Queen, alternating color to show queen graphics.DrawString("Q", drawFont, color[(color_value + 1) % 2], guide_box, centerLoc); } //This is the message on the top of the display this.topMessage.Text = "You have " + queens + " queens on the board."; } } } //Checkbox for the Hints private void hintBox_CheckedChanged(object sender, EventArgs e) { this.Invalidate(); } //Clears the board private void cleanBoard_Click(object sender, EventArgs e) { takenSpot = new bool[8, 8]; queens = 0; this.Invalidate(); } private void Form1_MouseClick(object sender, MouseEventArgs e) { int x = e.X; int y = e.Y; //If a click is within the grid, check it if (((x >= 100) && (y >= 100)) && ((x <= 500) && (y <= 500))) { //Eliminate the offset (grid starts at 100,100) x = x - 100; y = y - 100; //Each box is 50 x 50,so by divding by 50, we get the row and column number x = x / 50; y = y / 50; //If a user left-clicks on a valid space, add a queen if (e.Button == MouseButtons.Left) { //Check if space is valid if (validMove(x, y)) { takenSpot[x, y] = true; ++queens; //If there are Eight Queens, show popoup if (queens == 8) { MessageBox.Show("Congratulations! You did it!"); } this.Invalidate(); } //Else play an error sound else { SystemSounds.Beep.Play(); } } //If a user right-clicks on a queen, remove it else if ((e.Button == MouseButtons.Right) && takenSpot[x, y]) { --queens; takenSpot[x, y] = false; this.Invalidate(); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class LoadingScreenMenu : Menu<LoadingScreenMenu> { public Image loadingIcon; public static void Show(int scene) { Open(); Instance.StartCoroutine(Instance.LoadScene(scene)); } public static void Hide() { Close(); } public override void OnBackPressed() { } IEnumerator LoadScene(int scene) { float currentVelocity = 0; float smoothTime = 0.2f; loadingIcon.fillAmount = 0; AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(scene); while (!asyncLoad.isDone || loadingIcon.fillAmount <= 0.99f) { loadingIcon.fillAmount = Mathf.SmoothDamp(loadingIcon.fillAmount,asyncLoad.progress,ref currentVelocity, smoothTime); yield return null; } GameMenu.Show(); } }
/* SLTrace * ObjectPathTracer.cs * * Copyright (c) 2010, Ewen Cheslack-Postava * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of SLTrace nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using OpenMetaverse; using OpenMetaverse.Packets; using OpenMetaverse.Rendering; namespace SLTrace { /** Records events concerning object locations - addition and removal from * interest set, position and velocity updates, size updates, etc. */ class ObjectPathTracer : ITracer { public ObjectPathTracer(string args_string) { mTraceFilename = "object_paths.json"; string[] split_args = Arguments.Split(args_string); Dictionary<string, string> arg_map = Arguments.Parse(split_args); if (arg_map.ContainsKey("o")) mTraceFilename = arg_map["o"]; if (arg_map.ContainsKey("out")) mTraceFilename = arg_map["out"]; } public void StartTrace(TraceSession parent) { mParent = parent; // For initial startup info mParent.Client.Network.OnSimConnected += new NetworkManager.SimConnectedCallback(this.SimConnectedHandler); string renderer_name = "OpenMetaverse.Rendering.Meshmerizer.dll"; string renderer_path = System.IO.Path.Combine(parent.Config.BinaryPath, renderer_name); mRenderer = OpenMetaverse.Rendering.RenderingLoader.LoadRenderer(renderer_path); mObjectsByLocalID = new Dictionary<uint, Primitive>(); mObjectsByID = new Dictionary<UUID, Primitive>(); mObjectParents = new Dictionary<UUID, uint>(); mParent.Client.Objects.OnObjectDataBlockUpdate += new ObjectManager.ObjectDataBlockUpdateCallback(this.ObjectDataBlockUpdateHandler); mParent.Client.Objects.OnNewAvatar += new ObjectManager.NewAvatarCallback(this.NewAvatarHandler); mParent.Client.Objects.OnNewPrim += new ObjectManager.NewPrimCallback(this.NewPrimHandler); mParent.Client.Objects.OnNewAttachment += new ObjectManager.NewAttachmentCallback(this.NewAttachmentHandler); // Note: We only do OnObjectTerseUpdate because OnObjectUpdate // is redundant and less informative. mParent.Client.Objects.OnObjectTerseUpdate += new ObjectManager.ObjectUpdatedTerseCallback(this.ObjectUpdatedTerseHandler); mParent.Client.Objects.OnObjectKilled += new ObjectManager.KillObjectCallback(this.ObjectKilledHandler); mParent.Client.Objects.OnObjectProperties += new ObjectManager.ObjectPropertiesCallback(this.ObjectPropertiesHandler); mParent.Client.Self.Movement.Camera.Far = 512.0f; // We output JSON, one giant list of events System.IO.TextWriter streamWriter = new System.IO.StreamWriter(mTraceFilename); mJSON = new JSON(streamWriter); mJSON.BeginArray(); mStartTime = DateTime.Now; } public void StopTrace() { mJSON.EndArray(); mJSON.Finish(); } private void ComputeBounds(Primitive prim) { SimpleMesh mesh = mRenderer.GenerateSimpleMesh(prim, DetailLevel.High); if (mesh.Vertices.Count == 0) return; Vector3 vert_min = mesh.Vertices[0].Position; Vector3 vert_max = mesh.Vertices[0].Position; foreach(Vertex v in mesh.Vertices) { vert_min = Vector3.Min(vert_min, v.Position); vert_max = Vector3.Max(vert_max, v.Position); } lock(mJSON) { mJSON.BeginObject(); JSONStringField("event", "size"); JSONUUIDField("id", prim.ID); JSONTimeSpanField("time", SinceStart); JSONVector3Field("min", vert_min); JSONVector3Field("max", vert_max); JSONVector3Field("scale", prim.Scale); mJSON.EndObject(); } } private void CheckMembershipWithLocation(Simulator sim, String primtype, Primitive prim) { CheckMembership(sim, primtype, prim, true); } private void CheckMembership(Simulator sim, String primtype, Primitive prim) { CheckMembership(sim, primtype, prim, false); } private void CheckMembership(Simulator sim, String primtype, Primitive prim, bool with_loc) { if (prim.ID == UUID.Zero) return; lock(this) { if (mObjectsByLocalID.ContainsKey(prim.LocalID)) { if (mObjectsByLocalID[prim.LocalID] != prim) { Console.WriteLine("Object addition for existing local id: " + prim.LocalID.ToString()); return; } } bool is_update = false; if (mObjectsByID.ContainsKey(prim.ID)) { if (mObjectsByID[prim.ID] != prim) Console.WriteLine("Conflicting global ID for different prim instances: {0}.", prim.ID.ToString()); is_update = true; } mObjectsByLocalID[prim.LocalID] = prim; mObjectsByID[prim.ID] = prim; Primitive parentPrim = null; bool known_parent = mObjectsByLocalID.ContainsKey(prim.ParentID); if (known_parent) parentPrim = mObjectsByLocalID[prim.ParentID]; // Either this is brand new, or its an update and we should only // store the object if an important feature has changed. Currently // the only important feature we track is ParentID. if (!is_update || mObjectParents[prim.ID] != prim.ParentID) StoreNewObject(primtype, prim, prim.ParentID, parentPrim); mObjectParents[prim.ID] = prim.ParentID; if (is_update) // Everything else should only happen for brand new objects return; RequestObjectProperties(sim, prim); if (!known_parent && prim.ParentID != 0) RequestObjectProperties(sim, prim.ParentID); ComputeBounds(prim); if (with_loc) StoreLocationUpdate(prim); } } private void RemoveMembership(uint localid) { UUID fullid = UUID.Zero; lock(this) { if (mObjectsByLocalID.ContainsKey(localid)) { Primitive prim = mObjectsByLocalID[localid]; mObjectsByLocalID.Remove(localid); mObjectsByID.Remove(prim.ID); mObjectParents.Remove(prim.ID); fullid = prim.ID; } } if (fullid == UUID.Zero) return; lock(mJSON) { mJSON.BeginObject(); JSONStringField("event", "kill"); JSONTimeSpanField("time", SinceStart); JSONUUIDField("id", fullid); mJSON.EndObject(); } } // Note: Because we need to use this both for new prims/avatars and for // ObjectUpdates, and ObjectUpdates don't update the primitive until *after* // the callback, we need to pass the information in explicitly. private void StoreLocationUpdate(Primitive prim, Vector3 pos, Vector3 vel, Quaternion rot, Vector3 angvel) { lock(mJSON) { mJSON.BeginObject(); JSONStringField("event", "loc"); JSONUUIDField("id", prim.ID); JSONTimeSpanField("time", SinceStart); JSONVector3Field("pos", pos); JSONVector3Field("vel", vel); JSONQuaternionField("rot", rot); JSONVector3Field("angvel", angvel); mJSON.EndObject(); } } private void StoreLocationUpdate(Primitive prim) { StoreLocationUpdate(prim, prim.Position, prim.Velocity, prim.Rotation, prim.AngularVelocity); } private void StoreLocationUpdate(Primitive prim, ObjectUpdate update) { StoreLocationUpdate(prim, update.Position, update.Velocity, update.Rotation, update.AngularVelocity); } private void RequestObjectProperties(Simulator sim, Primitive prim) { mParent.Client.Objects.SelectObject(sim, prim.LocalID); } private void RequestObjectProperties(Simulator sim, uint primid) { mParent.Client.Objects.SelectObject(sim, primid); } private void ObjectDataBlockUpdateHandler(Simulator simulator, Primitive prim, Primitive.ConstructionData constructionData, ObjectUpdatePacket.ObjectDataBlock block, ObjectUpdate update, NameValue[] nameValues) { // Note: We can't do membership or really much useful here since the // primitive doesn't have its information filled in quite yet. Instead, // we're forced to use the OnNew* events, which get called *after* all // the data has been filled in. //Console.WriteLine("Object: " + update.LocalID.ToString() + " - " + update.Position.ToString() + " " + update.Velocity.ToString()); } private void StoreNewObject(String type, Primitive obj, uint parentLocal, Primitive parent) { lock(mJSON) { mJSON.BeginObject(); JSONStringField("event", "add"); JSONTimeSpanField("time", SinceStart); JSONStringField("type", type); JSONUInt32Field("local", obj.LocalID); JSONUUIDField("id", obj.ID); if (parentLocal != 0) JSONUInt32Field("parent_local", parentLocal); if (parent != null) JSONUUIDField("parent", parent.ID); mJSON.EndObject(); } // Selecting avatars doesn't work for getting object properties, but the // same properties are available immediately here. Avatar avtr = obj as Avatar; if (avtr != null) StoreObjectProperties(avtr.ID, avtr.Name, "(Avatar: N/A)"); } private void StoreObjectProperties(UUID id, string name, String description) { lock(mJSON) { mJSON.BeginObject(); JSONStringField("event", "properties"); JSONUUIDField("id", id); JSONStringField("name", name); JSONStringField("description", description); mJSON.EndObject(); } } private void SimConnectedHandler(Simulator sim) { lock(mJSON) { mJSON.BeginObject(); JSONStringField("event", "started"); mJSON.Field("time", new JSONString( mStartTime.ToString() )); JSONStringField("sim", sim.Name); mJSON.EndObject(); } } private void NewAvatarHandler(Simulator simulator, Avatar avatar, ulong regionHandle, ushort timeDilation) { CheckMembershipWithLocation(simulator, "avatar", avatar); } private void NewPrimHandler(Simulator simulator, Primitive prim, ulong regionHandle, ushort timeDilation) { CheckMembershipWithLocation(simulator, "prim", prim); } private void NewAttachmentHandler(Simulator simulator, Primitive prim, ulong regionHandle, ushort timeDilation) { CheckMembershipWithLocation(simulator, "attachment", prim); } private void ObjectUpdatedTerseHandler(Simulator simulator, Primitive prim, ObjectUpdate update, ulong regionHandle, ushort timeDilation) { CheckMembership(simulator, "terse", prim); StoreLocationUpdate(prim, update); } private void ObjectKilledHandler(Simulator simulator, uint objectID) { RemoveMembership(objectID); } private void ObjectPropertiesHandler(Simulator simulator, Primitive.ObjectProperties properties) { StoreObjectProperties(properties.ObjectID, properties.Name, properties.Description); } // JSON Encoding helpers private void JSONStringField(String name, String val) { mJSON.Field(name, new JSONString(val)); } private void JSONUInt32Field(String name, uint val) { mJSON.Field(name, new JSONInt((long)val)); } private void JSONUUIDField(String name, UUID val) { mJSON.Field(name, new JSONString( val.ToString() )); } private void JSONVector3Field(String name, Vector3 vec) { mJSON.ObjectField(name); mJSON.Field("x", new JSONString(vec.X.ToString())); mJSON.Field("y", new JSONString(vec.Y.ToString())); mJSON.Field("z", new JSONString(vec.Z.ToString())); mJSON.EndObject(); } private void JSONQuaternionField(String name, Quaternion vec) { mJSON.ObjectField(name); mJSON.Field("w", new JSONString(vec.W.ToString())); mJSON.Field("x", new JSONString(vec.X.ToString())); mJSON.Field("y", new JSONString(vec.Y.ToString())); mJSON.Field("z", new JSONString(vec.Z.ToString())); mJSON.EndObject(); } private void JSONTimeSpanField(String name, TimeSpan val) { mJSON.Field(name, new JSONString( val.TotalMilliseconds.ToString() + "ms" )); } // Time helpers private TimeSpan SinceStart { get { return DateTime.Now - mStartTime; } } private IEnumerable<Primitive> RootObjects { get { return mObjectsByLocalID.Values.Where(obj => obj.ParentID == 0); } } private string mTraceFilename; private TraceSession mParent; IRendering mRenderer; private DateTime mStartTime; private Dictionary<uint, Primitive> mObjectsByLocalID; // All tracked // objects, by LocalID private Dictionary<UUID, Primitive> mObjectsByID; // All tracked objects, by // global UUID private Dictionary<UUID, uint> mObjectParents; // LocalID of parents of all // tracked objects private JSON mJSON; // Stores JSON formatted output event stream } // class RawPacketTracer } // namespace SLTrace
using System; using System.Collections.Generic; using System.Text; namespace State { public class ApagadoState : State { // Referencia a la clase de contexto private Vehiculo v; // Constructor que inyecta la dependencia en la clase actual public ApagadoState(Vehiculo v) { this.v = v; } public void Acelerar() { // Acelerar con el vehiculo apagado no sirve de mucho 🙂 Console.WriteLine("ERROR: El vehiculo esta apagado. Efectue el contacto para iniciar"); } public void Frenar() { // Frenar con el vehiculo parado tampoco sirve de mucho... Console.WriteLine("ERROR: El vehiculo esta apagado. Efectue el contacto para iniciar"); } public void Contacto() { // Comprobamos que el vehiculo disponga de combustible if (v.CombustibleActual > 0) { // El vehiculo arranca -> Cambio de estado //estado = PARADO; v.Estado = new ParadoState(v); Console.WriteLine("El vehiculo se encuentra ahora PARADO"); v.VelocidadActual = 0; } else { // El vehiculo no arranca -> Sin combustible //estado = SIN COMBUSTIBLE v.Estado = new SinCombustibleState(v); Console.WriteLine("El vehiculo se encuentra sin combustible"); } } } }
using System; using System.Collections.Generic; using System.Text; namespace ClassLibrary1.Mynamespace2 { class student { //如果在同一个project里面有不同的namespace,那么这个class student可以随意调用Mynamespace下的add方法。 } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2009 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; using System.Collections.Generic; using System.Web; using System.Web.Caching; using Framework.Db; using Framework.Entity; using Framework.Metadata; using Framework.Utils; namespace Framework.Remote { /// <summary> /// Base entity class for Silverlight applications. /// </summary> public class CxSlEntity : CxBaseEntity { /// <summary> /// Initializes new instance entity class for the given entity usage metadata. /// </summary> /// <param name="metadata">metadata that describes this entity</param> public CxSlEntity(CxEntityUsageMetadata metadata) : base(metadata) { } //---------------------------------------------------------------------------- public const string BLOB_PRESENT_IN_DB = "BLOB_PRESENT_IN_DB"; public const string REMOVE_BLOB_FROM_DB = "REMOVE_BLOB_FROM_DB"; //---------------------------------------------------------------------------- /// <summary> /// Inserts entity (and all "owned" child) entities to the database. /// </summary> /// <param name="connection">connection an INSERT should work in context of</param> public override void Insert(CxDbConnection connection) { AssignBlobsFromCache(); base.Insert(connection); } //---------------------------------------------------------------------------- /// <summary> /// Updates entity (and all "owned" child entities) in the database. /// </summary> /// <param name="connection">connection an UPDATE should work in context of</param> public override void Update(CxDbConnection connection) { AssignBlobsFromCache(); base.Update(connection); } //---------------------------------------------------------------------------- /// <summary> /// Sets binary data from cache nt fields with type equals 'file' /// </summary> protected virtual void AssignBlobsFromCache() { foreach (Metadata.CxAttributeMetadata atrMetadata in Metadata.Attributes) { if (IsBlobToRestoreFromCache(atrMetadata)) { string cacheId = this[atrMetadata.Id].ToString(); Cache cache = HttpContext.Current.Cache; if (cache[cacheId] == null) throw new ExException("Cached binary data is expired."); this[atrMetadata.Id] = ((CxUploadHandler)cache[cacheId]).GetData(); cache.Remove(cacheId); this[GetBlobStateAttributeId(atrMetadata.Id)] = BLOB_PRESENT_IN_DB; } if (IsBlobToRemoveAttribute(atrMetadata)) { this[atrMetadata.Id] = null; this[GetBlobStateAttributeId(atrMetadata.Id)] = REMOVE_BLOB_FROM_DB; } } } //---------------------------------------------------------------------------- /// <summary> /// Returns list of atrtribytes with type 'file'. /// </summary> /// <param name="attributes">List of all attribytes.</param> /// <returns></returns> protected virtual IList<Metadata.CxAttributeMetadata> FilterBlobAttributes(IEnumerable<Metadata.CxAttributeMetadata> attributes) { List<Metadata.CxAttributeMetadata> updatedAttrs = new List<Metadata.CxAttributeMetadata>(); foreach (Metadata.CxAttributeMetadata atrMetadata in attributes) { if (!IsBlobAttribute(atrMetadata)) { updatedAttrs.Add(atrMetadata); continue; } if (IsMustBeStoredBlob(atrMetadata)) { updatedAttrs.Add(atrMetadata); continue; } if(IsBlobToRemoveAttribute(atrMetadata)) { updatedAttrs.Add(atrMetadata); continue; } } return updatedAttrs; } //---------------------------------------------------------------------------- /// <summary> /// Composes SQL INSERT statement to for entity. /// </summary> /// <param name="dbObjectName">database table or view name</param> /// <param name="attributes">list of available attributes</param> /// <returns>insert SQL statement</returns> protected override string ComposeInsert(string dbObjectName, IList<Metadata.CxAttributeMetadata> attributes) { return base.ComposeInsert(dbObjectName, FilterBlobAttributes(attributes)); } //---------------------------------------------------------------------------- /// <summary> /// Returns true if 'Type' property of given attribute equals 'file'. /// </summary> /// <param name="attrMetadata"></param> /// <returns></returns> private bool IsBlobAttribute(Metadata.CxAttributeMetadata attrMetadata) { return (string.Compare(attrMetadata.Type, "file") == 0) || (string.Compare(attrMetadata.Type, "image") == 0); } //---------------------------------------------------------------------------- /// <summary> /// Returns true if value of given CxAttributeMetadata means 'this blob must be stored to DB'. /// </summary> private bool IsMustBeStoredBlob(Metadata.CxAttributeMetadata attrMetadata) { if (IsBlobAttribute(attrMetadata) && this[attrMetadata.Id] is byte[] && ((byte[])this[attrMetadata.Id]).Length > 0) { return true; } return false; } //---------------------------------------------------------------------------- /// <summary> /// Returns true if value of given CxAttributeMetadata means 'this blob must be removed'. /// </summary> protected bool IsBlobToRemoveAttribute(Metadata.CxAttributeMetadata attrMetadata) { if (IsBlobAttribute(attrMetadata) && this[GetBlobStateAttributeId(attrMetadata.Id)] != null && this[GetBlobStateAttributeId(attrMetadata.Id)].Equals(REMOVE_BLOB_FROM_DB)) { return true; } return false; } //---------------------------------------------------------------------------- /// <summary> /// Returns true if value of given CxAttributeMetadata means 'need to get binary data from Cache'. /// </summary> protected bool IsBlobToRestoreFromCache(Metadata.CxAttributeMetadata attrMetadata) { if (IsBlobAttribute(attrMetadata) && this[attrMetadata.Id] is Guid) { return true; } return false; } //---------------------------------------------------------------------------- /// <summary> /// Returns true if value of given CxAttributeMetadata /// means 'exclude this field from Insert and Update statements'. /// </summary> private bool IsNothingToDoBlob(Metadata.CxAttributeMetadata attrMetadata) { if (IsBlobAttribute(attrMetadata) && ((this[GetBlobStateAttributeId(attrMetadata.Id)] == null) || this[GetBlobStateAttributeId(attrMetadata.Id)].Equals(BLOB_PRESENT_IN_DB))) { return true; } return false; } //---------------------------------------------------------------------------- /// <summary> /// Returns blob state attribute Id. /// </summary> /// <param name="blobAttributeId">Id of attribute that contains blob.</param> /// <returns></returns> public static string GetBlobStateAttributeId(string blobAttributeId) { return string.Concat(blobAttributeId, "STATE"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using TwinkleStar.Data; using TwinkleStar.Service; namespace TwinkleStar.Demo.Core { public abstract class DemoServiceBase { ///// <summary> ///// 获取或设置 工作单元对象,用于处理同步业务的事务操作 ///// </summary> //[Import] //protected IUnitOfWork UnitOfWork { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Nector.Core.Tests { public class UtilityTest { [Fact] public void ShouldReturnSameByteArray() { //Arrange byte[] input=new byte[3]{0,1,2}; //Act byte[] result = input.ToByteArray(); //Aseert Assert.Equal(input, result); } [Fact] public void ShouldReturnByteArrayListFromCollection() { //Arrange List<byte[]> expectedList = new List<byte[]>(); List<object> inputList = new List<object>(); int firstItemInInputList = 2; long secondItemInInputList = 3; string thirdItemInInputList= "sampleValue"; expectedList.Add(BitConverter.GetBytes(firstItemInInputList)); expectedList.Add(BitConverter.GetBytes(secondItemInInputList)); expectedList.Add(Encoding.UTF8.GetBytes(thirdItemInInputList)); inputList.Add(firstItemInInputList); inputList.Add(secondItemInInputList); inputList.Add(thirdItemInInputList); //Act List<byte[]> result = inputList.ToByteArrayListFromCollection<object>(); //Aseert Assert.Equal<List<byte[]>>(expectedList, result); } } }
using Enrollment.Domain; using Enrollment.Spa.Flow.ScreenSettings.Views; namespace Enrollment.Spa.Flow.Requests { public class GridRequest : RequestBase { public EntityModelBase? Entity { get; set; } public override ViewType ViewType { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Benchmark.Benchmarks { using BenchmarkDotNet.Attributes; /* * Method | SizeOfInput | Mean | Error | StdDev | Allocated | --------------------- |------------ |------------:|-----------:|----------:|----------:| ContainsDirect | 0 | 8.0891 ns | 3.0855 ns | 0.1743 ns | 0 B | ContainsViaInterface | 0 | 8.6354 ns | 2.8752 ns | 0.1625 ns | 0 B | CopyToDirect | 0 | 3.6926 ns | 3.1324 ns | 0.1770 ns | 0 B | CopyToViaInterface | 0 | 4.7780 ns | 2.8098 ns | 0.1588 ns | 0 B | CountDirect | 0 | 0.0000 ns | 0.0000 ns | 0.0000 ns | 0 B | CountViaInterface | 0 | 1.6710 ns | 1.1001 ns | 0.0622 ns | 0 B | ContainsDirect | 1 | 8.0362 ns | 6.9193 ns | 0.3910 ns | 0 B | ContainsViaInterface | 1 | 8.9115 ns | 0.8119 ns | 0.0459 ns | 0 B | CopyToDirect | 1 | 5.7880 ns | 2.9302 ns | 0.1656 ns | 0 B | CopyToViaInterface | 1 | 6.8646 ns | 2.5265 ns | 0.1427 ns | 0 B | CountDirect | 1 | 0.0000 ns | 0.0000 ns | 0.0000 ns | 0 B | CountViaInterface | 1 | 1.6377 ns | 1.9788 ns | 0.1118 ns | 0 B | ContainsDirect | 100 | 11.2285 ns | 2.7729 ns | 0.1567 ns | 0 B | ContainsViaInterface | 100 | 11.9377 ns | 7.1724 ns | 0.4053 ns | 0 B | CopyToDirect | 100 | 213.8980 ns | 34.1613 ns | 1.9302 ns | 0 B | CopyToViaInterface | 100 | 215.3195 ns | 70.9116 ns | 4.0066 ns | 0 B | CountDirect | 100 | 0.0253 ns | 0.3934 ns | 0.0222 ns | 0 B | CountViaInterface | 100 | 1.7035 ns | 0.7346 ns | 0.0415 ns | 0 B | */ public class HashSetBenchmark { [Params(0, 1, 100)] public int SizeOfInput; // HashSet is ICollection, not IList, and has a struct enumerator private HashSet<int> directCollection; private ICollection<int> collectionViaInterface; private int[] destination; [GlobalSetup] public void Setup() { this.collectionViaInterface = new HashSet<int>(Enumerable.Range(0, this.SizeOfInput)); this.directCollection = new HashSet<int>(Enumerable.Range(0, this.SizeOfInput)); this.destination = new int[this.SizeOfInput]; } [Benchmark] public bool ContainsDirect() { return this.directCollection.Contains(5); } [Benchmark] public void CopyToDirect() { this.directCollection.CopyTo(this.destination, 0); } [Benchmark] public int CountDirect() { return this.directCollection.Count; } [Benchmark] public bool ContainsViaInterface() { return this.collectionViaInterface.Contains(5); } [Benchmark] public void CopyToViaInterface() { this.collectionViaInterface.CopyTo(this.destination, 0); } [Benchmark] public int CountViaInterface() { return this.collectionViaInterface.Count; } } }
using System.Collections; using System.Collections.Generic; using QuantumTek.MenuSystem; using UnityEngine; public class VictoryScript : MonoBehaviour { // Components public Window victoryWindow; public AudioSource audioSource; // ------ // Events // ------ void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Player")) { PlayerController.isInputEnabled = false; ChiefController.isActive = false; AudioSource[] allAudioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[]; foreach (AudioSource audioS in allAudioSources) { audioS.Stop(); } audioSource.Play(); victoryWindow.Open(); } } }
using BLL; using Entidades; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProyectoFinal.UI.Consultas { public partial class BusquedaProducto : Form { private List<Productos> listado; public int id { get; set; } public BusquedaProducto() { InitializeComponent(); listado = new List<Productos>(); id = 0; Buscar(); } private void Buscarbutton_Click(object sender, EventArgs e) { Buscar(); } private void Buscar() { RepositorioBase<Productos> db = new RepositorioBase<Productos>(); if (CriteriotextBox.Text.Trim().Length > 0) { try { switch (FiltrocomboBox.SelectedIndex) { case 0://Todo listado = db.GetList(U => true); break; case 1://ID int id = int.Parse(CriteriotextBox.Text); listado = db.GetList(U => U.IdUsuario == id); break; case 2://Descripcion listado = db.GetList(U => U.Descripcion == CriteriotextBox.Text); break; case 3:// Usuario listado = db.GetList(U => U.IdUsuario == int.Parse(CriteriotextBox.Text)); break; } if (FechacheckBox.Checked) { listado = listado.Where(U => U.FechaCreacion >= DesdedateTimePicker.Value.Date && U.FechaCreacion <= HastadateTimePicker.Value.Date).ToList(); } } catch (Exception) { } } else { listado = db.GetList(p => true); } //listado = listado.Where(E => E.FechaIngreso >= DesdedateTimePicker.Value.Date && E.FechaIngreso <= HastadateTimePicker.Value.Date ).ToList(); //ConsultadataGridView.DataSource = null; ConsultadataGridView.DataSource = listado; } private void ConsultadataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { id = ConsultadataGridView.CurrentRow.Index; this.Close(); } private void ConsultadataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { id = ConsultadataGridView.CurrentRow.Index; this.Hide(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SEGU_ENTI.Entidades; namespace SEGU_ENTI.Interfaz { public interface IEN_SEGU_SIST { List<clsSEGU_SIST> fn_CARG_MENU(string CO_USUA, int ID_OPCI); } }