text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Projet2Cpi { [Serializable] public class Tache : CalendarObj { /// <summary> /// Cette classe représente les tâches /// ///L'attribut PRIVE _etat représente un entier qui peut prendre les valeurs 0, 1 ou 2. le 0 signifie que la tâche /// non réalisée, le 1 que la tâche est en cours de réalisD:\brouillons-programmes\C#\WpfApp1\WpfApp1\DataTypes\Tache.csation et le 2 que la tâche est réalisée. ///L'attribut PUBLIC etat représente un string prenant 3 valeurs possibles : "realise", "en cours" et ///"non realise", ce sont des setters et getters pour _priorité ("realise" equivaut à 2, "en cours" equivaut à 1 et ///"non realise" equivaut à 0) /// /// Pour l'attribut PRIVE _priorite, et l'attribut PUBLIC priorite, suivre la même logique que _etat et etat. Sauf /// que dans ce cas 0 equivaut à "elevee", 1 equivaut à "moyenne" et 2 equivaut à "faible" /// /// </summary> private int _id;//Identification de la tâche public int id { get { return _id; } set { _id = value; } } private string _title; public string title { get { return _title; } set { _title = value; } } private string _details;//Designation de la tâche public string Details { get { return _details; } set { _details = value; } } private string _etat;//attribut _etat, voir documentation ci dessus public string etat { get { return _etat; } set { _etat = value; } } private string _priorite;//attribut _priorie, voir ci dessus également, même logique que pour _etat public string priorite { get { return _priorite; } set { _priorite = value; } } private DateTime _dateDebut; public DateTime dateDebut { get { return _dateDebut; } set { _dateDebut = value; } } private DateTime _dateFin; public DateTime dateFin { get { return _dateFin; } set { _dateFin = value; } } private List<String> fichiers = new List<string>(); public List<String> Fichiers { set { this.fichiers = value; } get { return this.fichiers; } } // Activité private String activitee; public String Activitee { set { this.activitee = value; } get { return activitee; } } private List<Notif> alarms; public List<Notif> Alarms { set { this.alarms = value; } get { return this.alarms; } } public Tache() { } } }
using System; using System.Windows; namespace CaveDwellersTest.Extensions { public static class PointExtensions { public static bool IsEqualTo(this Point thisPoint, Point point) { var x1 = (int)Math.Round(thisPoint.X, 0, MidpointRounding.AwayFromZero); var x2 = (int)Math.Round(point.X, 0, MidpointRounding.AwayFromZero); var y1 = (int)Math.Round(thisPoint.Y, 0, MidpointRounding.AwayFromZero); var y2 = (int)Math.Round(point.Y, 0, MidpointRounding.AwayFromZero); return x1 == x2 && y1 == y2; } } }
 using StructureMap; using StructureMap.Graph; namespace ConsoleApplication1.DependencyResolution { public class DefaultRegistry : Registry { public DefaultRegistry() { this.Scan(scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); }); } } }
using MixErp.Data; 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 MixErp.Stok { public partial class frmStokDurum : Form { MixErpDbEntities db = new MixErpDbEntities(); public frmStokDurum() { InitializeComponent(); } private void frmStokDurum_Load(object sender, EventArgs e) { Listele(); } private void Listele() { Liste.Rows.Clear(); int i = 0; var srg = (from s in db.tblStokDurums where s.tblUrunler.UrunKodu.Contains(txtBul.Text) // contains: içermek select s).ToList(); // sorgu sonucunu liste haline getirip srg nesnesinin içine atar. foreach (var k in srg) { Liste.Rows.Add(); // her döngüye girdiğinde bir satır oluşturur. Liste.Rows[i].Cells[0].Value = k.Id; Liste.Rows[i].Cells[1].Value = k.StokKodu; Liste.Rows[i].Cells[2].Value = k.UrunId; Liste.Rows[i].Cells[3].Value = k.tblUrunler.UrunAciklama; Liste.Rows[i].Cells[4].Value = k.Depo; Liste.Rows[i].Cells[5].Value = k.Raf; Liste.Rows[i].Cells[6].Value = k.Ambar; Liste.Rows[i].Cells[7].Value = k.OBFiyat; Liste.Rows[i].Cells[8].Value = k.Barkod; i++; } // kullanıcı yeni bir satır eklemesin Liste.AllowUserToAddRows = false; } private void btnBul_Click(object sender, EventArgs e) { Listele(); } private void btnKapat_Click(object sender, EventArgs e) { Close(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; public class MeteorsSpawn : MonoBehaviour { public ARReferencePointManager arReferencePointManager; private Vector3 center; public float sphereRadius; public GameObject meteorPrefab; private bool canSpawnmeteors; void Start() { center = transform.position; canSpawnmeteors = true; StartCoroutine(SpawnMeteors()); } Vector3 RandomPointOnSphere() { float x = Random.Range(-1f, 1f); float y = Random.Range(0.5f, 1f); float z = Random.Range(-1f, 1f); Vector3 pos = center + new Vector3(x, y, z).normalized * sphereRadius; return pos; } public IEnumerator SpawnMeteors() { while (canSpawnmeteors) { Pose pose; pose.position = RandomPointOnSphere(); pose.rotation = Quaternion.identity; ARReferencePoint meteorReferencePoint = arReferencePointManager.AddReferencePoint(pose); GameObject meteor = Instantiate(meteorPrefab, pose.position, Quaternion.identity); meteor.transform.SetParent(meteorReferencePoint.gameObject.transform); meteor.transform.localPosition = new Vector3(0, 0, 0); meteor.transform.LookAt(center); yield return new WaitForSeconds(3f); } } }
namespace WebApi.Responses { public class WebApiResultInfo { public int? PageIndex { get; set; } public int? PageSize { get; set; } public int? Count { get; set; } public int? TotalCount { get; set; } public WebApiResultInfo(int? pageIndex = null, int? pageSize = null, int? count = null, int? totalCount = null) { this.PageIndex = pageIndex; this.PageSize = pageSize; this.Count = count; this.TotalCount = totalCount; } } }
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 Проверка { public struct Searchmobs { public PictureBox picture; public Label label; public string name; public string land; public string category; public Searchmobs(string name1, string land1, string Category) { name = name1; land = land1; label = new Label(); picture = new PictureBox(); category = Category; } } public partial class Mobs : Form { /// <summary> /// Все мобы /// </summary> public static List<Searchmobs> mob_list = new List<Searchmobs>(); /// <summary> /// Мобы, у которых лайк стоит /// </summary> public static List<Searchmobs> Mob_like = new List<Searchmobs>(); public static List<Searchmobs> Mob_dislike = new List<Searchmobs>(); /// <summary> /// Формируем список всех мобов /// </summary> public static void FillMobsList() { mob_list.Add(new Searchmobs("Ифрит", "Ад", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Зомби-наездник", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Крипер", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Утопленник", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Древний страж", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Чешуйница Края", "Верхний мир, Ад, Край", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Вызыватель", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Гаст", "Ад", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Страж", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Хоглин", "Ад", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Кадавр", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Лавовый куб", "Ад", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Фантом", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Жестокий пинглин", "Ад", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Разбойник", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Разоритель", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Шалкер", "Край", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Чешуйница", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Скелет", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Cкелет-наездник", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Слизень", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Зимогор", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Досаждатель", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Поборник", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Ведьма", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Скелет-иссушитель", "Ад", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Зоглин", "Ад", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Зомби", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Зомби-житель", "Верхний мир", "Враждебные_мобы")); mob_list.Add(new Searchmobs("Летучая мышь", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Кошка", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Курица", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Треска", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Корова", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Лошадь", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Лиса", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Грибная корова", "Верхний мир", "Дружелюбные_мобы")); mob_list.Add(new Searchmobs("Оцелот", "Верхний мир", "Дружелюбные_мобы")); for (int i = 0; i < mob_list.Count; i++) { mob_list[i].picture.Click += new EventHandler(OpenMob); } } string groupName; /// <summary> /// Открыть форму с мобами /// </summary> /// <param name="_groupName">Враждебные мобы</param> public Mobs(string _groupName) { InitializeComponent(); groupName = _groupName; int x = 10; int y = 80; for (int i = 0; i < mob_list.Count; i++) { if (mob_list[i].category != groupName) continue; mob_list[i].picture.BackColor = Color.Transparent; mob_list[i].picture.Tag = mob_list[i].name; mob_list[i].picture.Location = new Point(x, y); mob_list[i].picture.Size = new Size(300, 300); mob_list[i].picture.SizeMode = PictureBoxSizeMode.Zoom; try { mob_list[i].picture.Load("../../Враждебные_мобы/" + mob_list[i].name + ".gif"); } catch (Exception) { mob_list[i].picture.Load("../../Враждебные_мобы/" + mob_list[i].name + ".png"); } Controls.Add(mob_list[i].picture); mob_list[i].label.AutoSize = true; mob_list[i].label.BackColor = Color.Transparent; mob_list[i].label.ForeColor = Color.Red; mob_list[i].label.Font = new Font("Microsoft Sans Serif", 15F); mob_list[i].label.Location = new Point(x + 100, y + 300); mob_list[i].label.Size = new Size(300, 29); mob_list[i].label.TabIndex = 31; mob_list[i].label.Text = mob_list[i].name; Controls.Add(mob_list[i].label); x = x + 300; if (x + 300 > Width) { x = 10; y = y + 350; } } } public static void OpenMob(object sender, EventArgs e) { PictureBox picture = (PictureBox)sender; MobForm form = new MobForm(picture.Tag.ToString()); form.Show(); } private void button1_Click(object sender, EventArgs e) { int x = 10; int y = 80; for (int i = 0; i < mob_list.Count; i++) { if (mob_list[i].category != groupName) continue; mob_list[i].picture.Visible = true; mob_list[i].label.Visible = true; if (textBox1.Text != "" && !mob_list[i].name.Contains(textBox1.Text)) { mob_list[i].picture.Visible = false; mob_list[i].label.Visible = false; } if (comboBox1.Text != "" && !mob_list[i].land.Contains(comboBox1.Text)) //mobs[i].land != comboBox1.Text) { mob_list[i].picture.Visible = false; mob_list[i].label.Visible = false; } if (mob_list[i].picture.Visible) { mob_list[i].picture.Location = new Point(x, y); mob_list[i].label.Location = new Point(x + 100, y + 300); x = x + 300; if (x + 300 > Width) { x = 10; y = y + 350; } } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthPack : MonoBehaviour { public AudioSource healSound; public int healthHealed = 100; // Start is called before the first frame update void Start() { } // Update is called once per frame private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { if (!GetComponent<BatteryShop>() || (GetComponent<BatteryShop>() && GetComponent<BatteryShop>().CanPickup())) { collision.gameObject.GetComponent<Health>().HealDamage(healthHealed); AudioSource.PlayClipAtPoint(healSound.clip, transform.position); if(!GetComponent<BatteryShop>() || (GetComponent<BatteryShop>() && !GetComponent<BatteryShop>().zMode)) Destroy(gameObject); } } } }
namespace ANSI { public enum Attributes { Bold = 1, Faint = 2, Italic = 3, Underline = 4, SlowBlink = 5, RapidBlink = 6, Reverse = 7, Conceal = 8, Strikethrough = 9, NoBoldNoFaint = 22, NoItalic = 23, NoUnderline = 24, NoBlink = 25, NoInverse = 27, NoConceal = 2, NoStrikethrough = 29, ColorBlack = 30, ColorRed = 31, ColorGreen = 32, ColorYellow = 33, ColorBlue = 34, ColorMagenta = 35, ColorCyan = 36, ColorWhite = 37, ColorBrightBlack = 90, ColorBrightRed = 91, ColorBrightGreen = 92, ColorBrightYellow = 93, ColorBrightBlue = 94, ColorBrightMagenta = 95, ColorBrightCyan = 96, ColorBrightWhite = 97 } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using WebAPITest.Context; using WebAPITest.Services; namespace WebAPITest { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddEntityFrameworkSqlServer() .AddDbContext<StudentContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStr"))); services.AddTransient<IStudentServices, StudentServices>(); services.AddTransient<ICourseServices, CourseServices>(); services.AddTransient<INavBarService, NavBarService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //app.UseMvc(routes => //{ // routes.MapRoute("default", "{controller=student}/{action=default}/{id?}"); //}); app.UseCors(b => b.WithOrigins("*","http://localhost:4200", "http://localhost:4200/*", "https://localhost:44361/*", "https://localhost:44361/api/student/students").AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod()); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); StudentContext.SeedData(app.ApplicationServices); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; namespace WebChapter.AspNetCore.MvcDemo.Security { public class EmployeeRequirementHandler : AuthorizationHandler<EmployeeRequirement> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EmployeeRequirement requirement) { if (!context.User.Identity.IsAuthenticated) { context.Fail(); return Task.CompletedTask; } if (context.User.Claims.FirstOrDefault(c => c.Type == "IsEmployee") == null) { context.Fail(); return Task.CompletedTask; } context.Succeed(requirement); return Task.CompletedTask; } } }
using Microsoft.Owin.Security; namespace ServerApi.OwinMiddleware.Authentication { public class SkautIsAuthenticationOptions : AuthenticationOptions { public SkautIsAuthenticationOptions() : base("SkautISAuth") { } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; /* Don't change anything here. * Do not add any other imports. You need to write * this program using only these libraries */ namespace ProgramNamespace { class DiscountProduct { public string ProductName { get; set; } public decimal MinPrice { get; set; } public decimal MaxPrice { get; set; } } class BuyersData { public string CustomerName; public string StoreLocation; public int DayOfMonth; public string ProductName; public decimal Price; public string PaymentType; public static List<BuyersData> GetConvertedData(IEnumerable<string> lines) { List<BuyersData> Data = new List<BuyersData>(); foreach(string line in lines) { string[] values = line.Split(','); BuyersData buyerValues = new BuyersData(); buyerValues.CustomerName = values[0].Trim(); buyerValues.StoreLocation = values[1].Trim(); buyerValues.DayOfMonth = Convert.ToInt16(values[2].Trim()); buyerValues.ProductName = values[3].Trim(); buyerValues.Price = Convert.ToDecimal(values[4].Replace("Rs", "").Trim()); buyerValues.PaymentType = values[5].Trim(); Data.Add(buyerValues); } return Data; } } public class Program { public static List<String> processData(IEnumerable<string> lines) { List<String> retVal = new List<String>(); List<DiscountProduct> discountProducts = new List<DiscountProduct>(); List<BuyersData> ConvertedData = BuyersData.GetConvertedData(lines); IEnumerable<string> DistinctProducts = ConvertedData.Select(x => x.ProductName).Distinct(); var q1 = from b in ConvertedData select b; var q2 = (from b in ConvertedData select b).ToArray(); foreach(string product in DistinctProducts) { var minPrice = ConvertedData.Where(x => x.ProductName == product).Min(p => p.Price); var maxPrice = ConvertedData.Where(x => x.ProductName == product).Max(p => p.Price); if(minPrice != maxPrice) { DiscountProduct discountProduct = new DiscountProduct(); discountProduct.ProductName = product; discountProduct.MinPrice = minPrice; discountProduct.MaxPrice = maxPrice; discountProducts.Add(discountProduct); } } foreach(DiscountProduct discountProduct in discountProducts) { var customerName = ConvertedData.FirstOrDefault(x => x.Price == discountProduct.MinPrice && x.ProductName == discountProduct.ProductName) .CustomerName; var sometimesBroughtOnHigherPrice = false; foreach(DiscountProduct innerLoop in discountProducts) { sometimesBroughtOnHigherPrice = ConvertedData.Any(x => x.CustomerName == customerName && x.ProductName == innerLoop.ProductName && x.Price == innerLoop.MaxPrice); if(sometimesBroughtOnHigherPrice) break; } if(!sometimesBroughtOnHigherPrice) retVal.Add(customerName); } return retVal; } static void Main(string[] args) { try { String line; var inputLines = new List<String>(); while((line = Console.ReadLine()) != null) { line = line.Trim(); if (line != "") inputLines.Add(line); else break; } var retVal = processData(inputLines); foreach(var res in retVal) Console.WriteLine(res); } catch (IOException ex) { Console.WriteLine(ex.Message); } } } }
using UBaseline.Shared.GlobalScriptsComposition; using UBaseline.Shared.Node; using UBaseline.Shared.Property; using UBaseline.Shared.Title; namespace Uintra.Core.Login { public class LoginPageModel: NodeModel, ITitleContainer, IGlobalScriptsComposition { public PropertyModel<string> Title { get; set; } public GlobalScriptsCompositionModel GlobalScripts { get; set; } } }
namespace DataLayer { using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; public class HumanResourceManager { public DataTable GetAbsenceTable(int group_id, DateTime start_date, DateTime end_date, string group_txt) { SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@group_id", group_id), new SqlParameter("@unit_code", group_txt), new SqlParameter("@start_date", start_date), new SqlParameter("@end_date", end_date) }; return clsConnectionString.returnConnection.executeSelectQuery("usp_hrm_absence_dashboard", CommandType.StoredProcedure, parameterArray); } public DataTable GetAbsenceTableExportData(int group_id, DateTime start_date, DateTime end_date, string group_txt) { SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@group_id", group_id), new SqlParameter("@unit_code", group_txt), new SqlParameter("@start_date", start_date), new SqlParameter("@end_date", end_date) }; return clsConnectionString.returnConnection.executeSelectQuery("usp_hrm_absence_dashboard_export", CommandType.StoredProcedure, parameterArray); } public DataTable ReadGroupList(string unitCode, string divCode, string username) { SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@unit_code", unitCode), new SqlParameter("@div_code", divCode), new SqlParameter("@user_name", username) }; return clsConnectionString.returnConnection.executeSelectQuery("usp_hrm_group_user_ddl", CommandType.StoredProcedure, parameterArray); } public DataTable SearchSsaQuery(string desc) { SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@description", desc.Trim()) }; return clsConnectionString.returnConnection.executeSelectQuery("usp_prg_ssa_query", CommandType.StoredProcedure, parameterArray); } public DataTable SearchSsaSuppliers() => clsConnectionString.returnConnection.executeSelectQuery("usp_prg_ssa_supplier_list", CommandType.StoredProcedure); public DataTable GetLatestHrPositionPeriod() => clsConnectionString.returnConnection.executeSelectQuery("usp_hrm_position_period_get", CommandType.StoredProcedure); public bool UpdateSsaSupplier(List<int> encExpIdList, string supplierName) { bool flag = false; using (SqlConnection connection = new SqlConnection(clsConnectionString.returnConnection.StrConnectionString)) { connection.Open(); using (SqlTransaction transaction = connection.BeginTransaction()) { try { foreach (int num in encExpIdList) { SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@prg_enc_exp_id", num), new SqlParameter("@supplier_name", supplierName) }; clsConnectionString.returnConnection.executeQuery("usp_prg_ssa_supplier_update", parameterArray, CommandType.StoredProcedure, connection, transaction); } transaction.Commit(); flag = true; } catch (Exception) { transaction.Rollback(); throw; } return flag; } } } } }
using Sentry.PlatformAbstractions; using Runtime = Sentry.PlatformAbstractions.Runtime; namespace Sentry.Tests.PlatformAbstractions; public class RuntimeExtensionsTests { [Theory] [InlineData(".NET Framework", true)] [InlineData(".NET Framework Foo", true)] [InlineData(".NET", false)] [InlineData(".NET Foo", false)] [InlineData(".NET Core", false)] [InlineData(".NET Core Foo", false)] [InlineData("Mono", false)] [InlineData("Mono Foo", false)] public void IsNetFx(string name, bool shouldMatch) { var runtime = new Runtime(name); var result = runtime.IsNetFx(); Assert.Equal(shouldMatch, result); } [Theory] [InlineData(".NET Framework", false)] [InlineData(".NET Framework Foo", false)] [InlineData(".NET", true)] [InlineData(".NET Foo", true)] [InlineData(".NET Core", true)] [InlineData(".NET Core Foo", true)] [InlineData("Mono", false)] [InlineData("Mono Foo", false)] public void IsNetCore(string name, bool shouldMatch) { var runtime = new Runtime(name); var result = runtime.IsNetCore(); Assert.Equal(shouldMatch, result); } [Theory] [InlineData(".NET Framework", false)] [InlineData(".NET Framework Foo", false)] [InlineData(".NET", false)] [InlineData(".NET Foo", false)] [InlineData(".NET Core", false)] [InlineData(".NET Core Foo", false)] [InlineData("Mono", true)] [InlineData("Mono Foo", true)] public void IsMono(string name, bool shouldMatch) { var runtime = new Runtime(name); var result = runtime.IsMono(); Assert.Equal(shouldMatch, result); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class kill : MonoBehaviour { // Start is called before the first frame update void Start() { } private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.name == "blue2") { Destroy(this.gameObject); } } void Update() { } }
namespace Shiftgram.Core.Enums { public enum DbAnswerCode { Ok, Bad } }
using System; using System.ComponentModel; using System.Globalization; using DelftTools.Utils; using TypeConverter = System.ComponentModel.TypeConverter; namespace DelftTools.Functions.Tuples { public class PairTypeConverter<T1, T2>: TypeConverter where T2 : IComparable<T2> where T1 : IComparable<T1> { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return (sourceType == typeof(string)); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if(destinationType == typeof(string)) { return true; } return false; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if(destinationType == typeof(string)) { return value.ToString(); } throw new InvalidOperationException(String.Format("Can't convert from Pair<{0}, {1}> to type: {2}", typeof(T1), typeof(T2), destinationType)); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var item = (string)value; var pair = new Pair<T1, T2>(); item = item.Replace("(", "").Replace(")",""); var items = item.Split(','); pair.First = (T1)Convert.ChangeType(items[0], typeof (T1)); pair.Second = (T2)Convert.ChangeType(items[1], typeof(T2)); return pair; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; using FluentAssertions; using Microsoft.Azure.Batch.SoftwareEntitlement.Common; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.IdentityModel.Tokens; using Xunit; namespace Microsoft.Azure.Batch.SoftwareEntitlement.Tests { public class TokenEnforcementTests { // A valid software entitlement to use for testing private readonly NodeEntitlements _validEntitlements; // Generator used to create a token private readonly TokenGenerator _generator; // Verifier used to check the token private readonly TokenVerifier _verifier; // Current time - captured as a member so it doesn't change during a test private readonly DateTimeOffset _now = DateTimeOffset.Now; // A application identifiers for testing private readonly string _contosoFinanceApp = "contosofinance"; private readonly string _contosoITApp = "contosoit"; private readonly string _contosoHRApp = "contosohr"; // IP addresses to use private readonly IPAddress _otherAddress = IPAddress.Parse("203.0.113.42"); private readonly IPAddress _approvedAddress = IPAddress.Parse("203.0.113.45"); // Name for the approved entitlement private readonly string _entitlementIdentifer = "mystery-identifier"; // Audience to which tokens should be addressed private readonly string _audience = "https://account.region.batch.azure.test"; // Issuer by which tokens should be created private readonly string _issuer = "https://account.region.batch.azure.test"; // Logger that does nothing private readonly ILogger _nullLogger = NullLogger.Instance; // Key to use for signing private readonly SymmetricSecurityKey _signingKey; // Key to use for encryption private readonly SymmetricSecurityKey _encryptingKey; // Credentials used for encryption private readonly EncryptingCredentials _encryptingCredentials; // Credentials used for signing private readonly SigningCredentials _signingCredentials; public TokenEnforcementTests() { // Hard coded key for unit testing only; actual operation will use a cert const string plainTextSigningKey = "This is my shared, not so secret, secret that needs to be very long!"; _signingKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(plainTextSigningKey)); _signingCredentials = new SigningCredentials( _signingKey, SecurityAlgorithms.HmacSha256Signature); // Hard coded key for unit testing only; actual operation will use a cert const string plainTextEncryptionKey = "This is another, not so secret, secret that needs to be very long!"; _encryptingKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(plainTextEncryptionKey)); _encryptingCredentials = new EncryptingCredentials( _encryptingKey, "dir", SecurityAlgorithms.Aes256CbcHmacSha512); _validEntitlements = CreateEntitlements(); _verifier = new TokenVerifier(_signingKey, _encryptingKey); _generator = new TokenGenerator(_nullLogger, _signingCredentials, _encryptingCredentials); } private NodeEntitlements CreateEntitlements(EntitlementCreationOptions creationOptions = EntitlementCreationOptions.None) { var result = new NodeEntitlements() .FromInstant(_now) .UntilInstant(_now + TimeSpan.FromDays(7)) .WithAudience(_audience) .WithIssuer(_issuer); if (!creationOptions.HasFlag(EntitlementCreationOptions.OmitIpAddress)) { result = result.AddIpAddress(_approvedAddress); } if (!creationOptions.HasFlag(EntitlementCreationOptions.OmitIdentifier)) { result = result.WithIdentifier(_entitlementIdentifer); } if (!creationOptions.HasFlag(EntitlementCreationOptions.OmitApplication)) { result = result.AddApplication(_contosoFinanceApp); } if (!creationOptions.HasFlag(EntitlementCreationOptions.OmitMachineId)) { result = result.WithVirtualMachineId("virtual-machine-identifier"); } return result; } /// <summary> /// Options used to control the creation of an <see cref="NodeEntitlements"/> instance /// for testing. /// </summary> [Flags] private enum EntitlementCreationOptions { None = 0, OmitIpAddress = 1, OmitIdentifier = 2, OmitApplication = 4, OmitMachineId = 8 } public class ConfigurationCheck : TokenEnforcementTests { // Base case check that our valid entitlement actually works to create a token // If this test fails, first check to see if our test data is still valid [Fact] public void GivenValidEntitlement_ReturnsSuccess() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); } } public class TokenTimeSpan : TokenEnforcementTests { private readonly TimeSpan _oneWeek = TimeSpan.FromDays(7); private readonly TimeSpan _oneDay = TimeSpan.FromDays(1); [Fact] public void GivenValidEntitlement_HasExpectedNotBefore() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.NotBefore.Should().BeCloseTo(_validEntitlements.NotBefore, precision: 1000); } [Fact] public void GivenValidEntitlement_HasExpectedNotAfter() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.NotAfter.Should().BeCloseTo(_validEntitlements.NotAfter, precision: 1000); } [Fact] public void WhenEntitlementHasExpired_ReturnsExpectedError() { var entitlement = _validEntitlements .FromInstant(_now - _oneWeek) .UntilInstant(_now - _oneDay); var token = _generator.Generate(entitlement); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("expired")); } [Fact] public void WhenEntitlementHasNotYetStarted_ReturnsExpectedError() { var entitlement = _validEntitlements .FromInstant(_now + _oneDay) .UntilInstant(_now + _oneWeek); var token = _generator.Generate(entitlement); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("will not be valid")); } } public class VirtualMachineIdentifier : TokenEnforcementTests { [Fact] public void WhenIdentifierIncluded_IsReturnedByVerifier() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.VirtualMachineId.Should().Be(_validEntitlements.VirtualMachineId); } [Fact] public void WhenIdentifierOmitted_EntitlementHasNoVirtualMachineIdentifier() { var entitlements = CreateEntitlements(EntitlementCreationOptions.OmitMachineId); var token = _generator.Generate(entitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.VirtualMachineId.Should().BeNullOrEmpty(); } } public class Applications : TokenEnforcementTests { [Fact] public void WhenEntitlementContainsOnlyTheRequestedApplication_ReturnsExpectedApplication() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.Applications.Should().Contain(_contosoFinanceApp); } [Fact] public void WhenEntitlementContainsOnlyADifferentApplication_ReturnsError() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoITApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains(_contosoITApp)); } [Fact] public void WhenEntitlementContainsMultipleApplicationsButNotTheRequestedApplication_ReturnsError() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoITApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().NotBeEmpty(); } [Fact] public void WhenEntitlementContainsMultipleApplicationsIncludingTheRequestedApplication_ReturnsExpectedApplication() { var entitlement = _validEntitlements.AddApplication(_contosoHRApp) .AddApplication(_contosoITApp); var token = _generator.Generate(entitlement); var result = _verifier.Verify(token, _audience, _issuer, _contosoHRApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.Applications.Should().Contain(_contosoHRApp); } [Fact] public void WhenEntitlementContainsNoApplications_ReturnsError() { var entitlements = CreateEntitlements(EntitlementCreationOptions.OmitApplication); var token = _generator.Generate(entitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoITApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains(_contosoITApp)); } } public class IpAddressProperty : TokenEnforcementTests { [Fact] public void WhenEntitlementContainsIp_ReturnsIpAddress() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.IpAddresses.Should().Contain(_approvedAddress); } [Fact] public void WhenEntitlementContainsOtherIp_ReturnsError() { var entitlements = CreateEntitlements(EntitlementCreationOptions.OmitIpAddress) .AddIpAddress(_otherAddress); var token = _generator.Generate(entitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().NotBeEmpty(); } [Fact] public void WhenEntitlementHasNoIp_ReturnsError() { var entitlements = CreateEntitlements(EntitlementCreationOptions.OmitIpAddress); var token = _generator.Generate(entitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains(_approvedAddress.ToString())); } } public class IdentifierProperty : TokenEnforcementTests { [Fact] public void WhenValidEntitlementSpecifiesIdentifier_ReturnsIdentifier() { var token = _generator.Generate(_validEntitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.Identifier.Should().Be(_entitlementIdentifer); } [Fact] public void WhenIdentifierOmitted_ReturnsError() { var entitlements = CreateEntitlements(EntitlementCreationOptions.OmitIdentifier); var token = _generator.Generate(entitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("identifier")); } } public class AudienceProperty : TokenEnforcementTests { [Fact] public void WhenAudienceOfTokenDiffers_ReturnsError() { var entitlements = CreateEntitlements() .WithAudience("http://not.the.audience.you.expected"); var token = _generator.Generate(entitlements); var result = _verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("audience")); } } /// <summary> /// Tests to check that enforcement works end to end with no signing key /// </summary> public class WithoutSigning : TokenEnforcementTests { // Generator with no signing key used to create a token private readonly TokenGenerator _generatorWithNoSigningKey; // Verifier with no signing key used to check the token private readonly TokenVerifier _verifierWithNoSigningKey; public WithoutSigning() { _verifierWithNoSigningKey = new TokenVerifier(encryptingKey: _encryptingKey); _generatorWithNoSigningKey = new TokenGenerator(_nullLogger, null, _encryptingCredentials); } [Fact] public void WhenEntitlementContainsOnlyTheRequestedApplication_ReturnsExpectedApplication() { var token = _generatorWithNoSigningKey.Generate(_validEntitlements); var result = _verifierWithNoSigningKey.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.Applications.Should().Contain(_contosoFinanceApp); } } /// <summary> /// Tests to check that enforcement works end to end with no encryption key /// </summary> public class WithoutEncryption : TokenEnforcementTests { // Generator with no signing key used to create a token private readonly TokenGenerator _generatorWithNoEncryptionKey; // Verifier with no signing key used to check the token private readonly TokenVerifier _verifierWithNoEncryptionKey; public WithoutEncryption() { _verifierWithNoEncryptionKey = new TokenVerifier(signingKey: _signingKey); _generatorWithNoEncryptionKey = new TokenGenerator(_nullLogger, _signingCredentials, encryptingCredentials: null); } [Fact] public void WhenEntitlementContainsOnlyTheRequestedApplication_ReturnsExpectedApplication() { var token = _generatorWithNoEncryptionKey.Generate(_validEntitlements); var result = _verifierWithNoEncryptionKey.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); result.HasValue.Should().BeTrue(); result.Value.Applications.Should().Contain(_contosoFinanceApp); } } public class WithCertificates : TokenEnforcementTests { [Theory(Skip = "Specify a certificate thumbprint in TestCaseKeys() to enable this test.")] [MemberData(nameof(TestCaseKeys))] public void WhenSignedByCertificate_ReturnsExpectedResult(SecurityKey key) { // Arrange var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha512Signature); var verifier = new TokenVerifier(signingKey: key); var generator = new TokenGenerator(_nullLogger, signingCredentials, encryptingCredentials: null); // Act var token = generator.Generate(_validEntitlements); var result = verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); // Assert result.Errors.Should().BeEmpty(); result.Value.Applications.Should().Contain(_contosoFinanceApp); } [Theory(Skip = "Specify a certificate thumbprint in TestCaseKeys() to enable this test.")] [MemberData(nameof(TestCaseKeys))] public void WhenEncryptedByCertificate_ReturnsExpectedResult(SecurityKey key) { // Arrange var encryptingCredentials = new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512); var verifier = new TokenVerifier(encryptingKey: key); var generator = new TokenGenerator(_nullLogger, signingCredentials: null, encryptingCredentials: encryptingCredentials); // Act var token = generator.Generate(_validEntitlements); var result = verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress); // Assert result.Errors.Should().BeEmpty(); result.Value.Applications.Should().Contain(_contosoFinanceApp); } public static IEnumerable<object[]> TestCaseKeys() { // To use this test, change the next line by entering a thumbprint that exists on the test machine var thumbprint = new CertificateThumbprint("<thumbprint-goes-here>"); var store = new CertificateStore(); var cert = store.FindByThumbprint("test", thumbprint); if (!cert.HasValue) { throw new InvalidOperationException(cert.Errors.First()); } var parameters = cert.Value.GetRSAPrivateKey().ExportParameters(includePrivateParameters: true); var key = new RsaSecurityKey(parameters); yield return new object[] { key }; } } } }
using System; using System.Threading; using System.Threading.Tasks; using Etherama.Common; using Etherama.Common.Extensions; using Etherama.CoreLogic.Services.Blockchain.Ethereum; using Etherama.DAL; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NLog; namespace Etherama.WebApplication.Services.HostedServices { public abstract class BaseHostedService : IHostedService, IDisposable { protected AppConfig AppConfig { get; } protected ILogger Logger { get; } protected ApplicationDbContext DbContext { get; } protected IEthereumReader EthereumObserver { get; } protected IEthereumWriter EthereumWriter { get; } protected abstract TimeSpan Period { get; } private Task _task; private readonly CancellationTokenSource _cts = new CancellationTokenSource(); protected BaseHostedService(IServiceProvider services) { Logger = services.GetLoggerFor(this.GetType()); AppConfig = services.GetRequiredService<AppConfig>(); DbContext = services.GetRequiredService<ApplicationDbContext>(); EthereumObserver = services.GetRequiredService<IEthereumReader>(); EthereumWriter = services.GetRequiredService<IEthereumWriter>(); } public void Dispose() { } public Task StartAsync(CancellationToken cancellationToken) { _task = ExecuteAsync(_cts.Token); return _task.IsCompleted ? _task : Task.CompletedTask; } public async Task StopAsync(CancellationToken cancellationToken) { if (_task == null) { return; } try { _cts.Cancel(); } finally { await Task.WhenAny(_task, Task.Delay(Timeout.Infinite, cancellationToken)); } } private async Task ExecuteAsync(CancellationToken cancellationToken) { await OnInit(); while (!cancellationToken.IsCancellationRequested) { try { await DoWork(); } catch (Exception e) { Logger.Error(e, "Hosted service failure"); } await Task.Delay(Period, cancellationToken); } } protected virtual Task OnInit() => Task.CompletedTask; protected abstract Task DoWork(); } }
using Entities.DbEntities; using Repositories.Interfaces; using System.Web; namespace Repositories.Repositories { public class CrossOutListRepository : ICrossOutListRepository { public ApplicationDbContext DbContext { get { if (HttpContext.Current.Items["ApplicationDbContext"] == null) { var context = new ApplicationDbContext(); HttpContext.Current.Items["ApplicationDbContext"] = context; return context; } else { return (ApplicationDbContext)HttpContext.Current.Items["ApplicationDbContext"]; } } } public void Update(ApplicationUser user) { } } }
using System; using System.ComponentModel.DataAnnotations; namespace gregs_list_again.Models { public class Job { public string Id { get; set; } [Required] public string JobTitle { get; set; } [Required] public string Company { get; set; } [Required] public int Salary { get; set; } public string Description { get; set; } public Job(string jobTitle, string company, int salary, string description) { Id = Guid.NewGuid().ToString(); JobTitle = jobTitle; Company = company; Salary = salary; Description = description; } } }
using System; namespace Microsoft.UnifiedPlatform.Service.Common.AppExceptions { [Serializable] public class IncompleteConfigurationException: Exception { public IncompleteConfigurationException(string clusterName, string appName, string missingConfiguration, Exception innerException) : base($"For app {appName} in cluster {clusterName}, the following configuration is missing: {missingConfiguration}", innerException) { } } }
using System; using UnityEngine; namespace Grandma.PF { [Serializable] public struct Shot { [Tooltip("The number of projectiles launched in this shot")] public int NumberOfProjectiles; } [Serializable] public struct Burst { //The number of shots in the burst public int Count => Shots.Length; [Tooltip("The shots in the current burst")] public Shot[] Shots; [Tooltip("The time between shots for the current burst. Measured in seconds")] public float Time; } /// <summary> /// Parameters to define the rate of fire for a PF /// </summary> //The fields here are private, to allow this class to do some //pre-processing before being sent off to the PF [Serializable] public class FiringData { //N < reloadingData.N, otherwise the burst data will never be triggered [SerializeField] public Burst BurstData; } }
using System; using System.Linq; using StackExchange.Redis; using System.Threading.Tasks; using Microsoft.UnifiedRedisPlatform.Core.Logging; using Microsoft.UnifiedRedisPlatform.Core.Pipeline; using Microsoft.UnifiedRedisPlatform.Core.RedisExecutionMiddlewares; namespace Microsoft.UnifiedRedisPlatform.Core.Database { public partial class UnifiedRedisDatabase : IDatabase { private readonly IDatabase _baseDatabase; private readonly UnifiedConnectionMultiplexer _unifiedMux; private readonly UnifiedConfigurationOptions _configurations; private readonly BaseMiddleware _executionManager; private readonly RedisExecutionContext _context; private readonly ILogger _logger; public UnifiedRedisDatabase(IDatabase rootDatabase, UnifiedConnectionMultiplexer mux, UnifiedConfigurationOptions configurations, ILogger logger) : this(rootDatabase, mux, configurations, logger, null) { } public UnifiedRedisDatabase(IDatabase rootDatabase, UnifiedConnectionMultiplexer mux, UnifiedConfigurationOptions configurations, ILogger logger, RedisExecutionContext context) { _baseDatabase = rootDatabase; _unifiedMux = mux; _configurations = configurations; _logger = logger; IPipeline executionPipeline = new PipelineManager(); if (_configurations.OperationsRetryProtocol != null && _configurations.OperationsRetryProtocol.HardTimeoutEnabled) executionPipeline = executionPipeline.With(new HardTimeoutMiddleware(_configurations, _logger)); if (_configurations.DiagnosticSettings.Enabled) executionPipeline = executionPipeline.With(new DiagnosticMiddleware(_configurations, _logger)); executionPipeline.With(new ResilliencyMiddleware(_configurations, _logger)); _executionManager = executionPipeline.Create(); _context = context; } public int Database => _baseDatabase.Database; public IConnectionMultiplexer Multiplexer { get => _unifiedMux; } private RedisKey CreateAppKey(RedisKey rootKey) { var appKey = $"{_configurations.KeyPrefix}:{rootKey}"; return appKey; } private RedisKey[] CreateAppKeys(RedisKey[] rootKeys) { return rootKeys.Select(key => CreateAppKey(key)).ToArray(); } public void EnableHardTimeout() { _configurations.OperationsRetryProtocol.HardTimeoutEnabled = true; } public void DisableHardTimeout() { _configurations.OperationsRetryProtocol.HardTimeoutEnabled = false; } public TimeSpan Ping(CommandFlags flags = CommandFlags.None) => _baseDatabase.Ping(flags); public Task<TimeSpan> PingAsync(CommandFlags flags = CommandFlags.None) => _baseDatabase.PingAsync(flags); protected Task<T> ExecuteAsync<T>(Func<Task<T>> action) { return _executionManager.ExecuteAsync<T>(action, _context); } protected T Execute<T>(Func<T> action) { return _executionManager.Execute<T>(action, _context); } } }
using Microsoft.EntityFrameworkCore; namespace Backend.Models { public class MagacinContext : DbContext { public DbSet<Magacin> Magacini { get; set; } public DbSet<Raf> Rafovi { get; set; } public DbSet<Mesto> Mesta { get; set; } public MagacinContext(DbContextOptions options) : base(options) { } } }
using Sentry.Tests.Helpers.Reflection; namespace Sentry.Tests.Reflection; public class AssemblyExtensionsTests { [Fact] public void GetNameAndVersion_NoInformationalAttribute_ReturnsAssemblyNameData() { var asmName = new AssemblyName { Name = Guid.NewGuid().ToString(), Version = new Version(1, 2, 3, 4) }; var actual = AssemblyCreationHelper.CreateAssembly(asmName).GetNameAndVersion(); Assert.Equal(asmName.Name, actual.Name); Assert.Equal(asmName.Version.ToString(), actual.Version); } [Fact] public void GetNameAndVersion_WithInformationalAttribute_ReturnsAssemblyInformationalVersion() { const string expectedVersion = "1.0.0-preview2"; var asmName = new AssemblyName { Name = Guid.NewGuid().ToString(), Version = new Version(1, 2, 3, 4) }; var actual = AssemblyCreationHelper.CreateWithInformationalVersion(expectedVersion, asmName) .GetNameAndVersion(); Assert.Equal(asmName.Name, actual.Name); Assert.Equal(expectedVersion, actual.Version); } }
 namespace com.Sconit.Web.Controllers.ISS { using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using com.Sconit.Utility; using Telerik.Web.Mvc; using com.Sconit.Web.Models; using com.Sconit.Web.Models.SearchModels.ISS; using com.Sconit.Web.Controllers.ACC; using com.Sconit.Entity.ISS; using com.Sconit.Service; public class IssueLevelController : WebAppBaseController { /// <summary> /// /// </summary> private static string selectCountStatement = "select count(*) from IssueLevel as il"; /// <summary> /// /// </summary> private static string selectStatement = "select il from IssueLevel as il"; /// <summary> /// /// </summary> private static string codeDuiplicateVerifyStatement = @"select count(*) from IssueLevel as il where il.Code = ?"; /// <summary> /// /// </summary> //public IGenericMgr genericMgr { get; set; } // // GET: /IssueLevel/ [SconitAuthorize(Permissions = "Url_IssueLevel_View")] public ActionResult Index() { return View(); } [GridAction] [SconitAuthorize(Permissions = "Url_IssueLevel_View")] public ActionResult List(GridCommand command, IssueLevelSearchModel searchModel) { TempData["IssueLevelSearchModel"] = searchModel; ViewBag.PageSize = base.ProcessPageSize(command.PageSize); return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_IssueLevel_View")] public ActionResult _AjaxList(GridCommand command, IssueLevelSearchModel searchModel) { SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel); return PartialView(GetAjaxPageData<IssueLevel>(searchStatementModel, command)); } [SconitAuthorize(Permissions = "Url_IssueLevel_Edit")] public ActionResult New() { return View(); } [HttpPost] [SconitAuthorize(Permissions = "Url_IssueLevel_Edit")] public ActionResult New(IssueLevel issueLevel) { if (ModelState.IsValid) { //判断用户名不能重复 if (this.genericMgr.FindAll<long>(codeDuiplicateVerifyStatement, new object[] { issueLevel.Code })[0] > 0) { base.SaveErrorMessage(Resources.ISS.IssueLevel.Errors_Existing_IssueLevel, issueLevel.Code); } else { genericMgr.CreateWithTrim(issueLevel); SaveSuccessMessage(Resources.ISS.IssueLevel.IssueLevel_Added); return RedirectToAction("Edit/" + issueLevel.Code); } } return View(issueLevel); } [HttpGet] [SconitAuthorize(Permissions = "Url_IssueLevel_Edit")] public ActionResult Edit(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { IssueLevel issueLevel = this.genericMgr.FindById<IssueLevel>(id); return View(issueLevel); } } /// <summary> /// Delete action /// </summary> /// <param name="id">IssueLevel id for delete</param> /// <returns>return to List action</returns> [SconitAuthorize(Permissions = "Url_IssueLevel_Delete")] public ActionResult Delete(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { this.genericMgr.DeleteById<IssueLevel>(id); SaveSuccessMessage(Resources.ISS.IssueLevel.IssueLevel_Deleted); return RedirectToAction("List"); } } [HttpPost] [SconitAuthorize(Permissions = "Url_IssueLevel_Edit")] public ActionResult Edit(IssueLevel issueLevel) { if (ModelState.IsValid) { genericMgr.UpdateWithTrim(issueLevel); SaveSuccessMessage(Resources.ISS.IssueLevel.IssueLevel_Updated); } return View(issueLevel); } private SearchStatementModel PrepareSearchStatement(GridCommand command, IssueLevelSearchModel searchModel) { string whereStatement = string.Empty; IList<object> param = new List<object>(); HqlStatementHelper.AddLikeStatement("Code", searchModel.Code, HqlStatementHelper.LikeMatchMode.Start, "il", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("Description", searchModel.Description, HqlStatementHelper.LikeMatchMode.Start, "il", ref whereStatement, param); HqlStatementHelper.AddEqStatement("IsActive", searchModel.IsActive, "il", ref whereStatement, param); string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectCountStatement; searchStatementModel.SelectStatement = selectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.master2.model { public class CSharpMethod : IComparable { private string name; private double relevance = 0; public double Relevance { get { return relevance; } set { relevance = value; } } public string Name { get { return name; } set { name = value; } } private ArrayList incomingCalls = new ArrayList(); public ArrayList IncomingCalls { get { return incomingCalls; } set { incomingCalls = value; } } private ArrayList outgoingCalls = new ArrayList(); public ArrayList OutgoingCalls { get { return outgoingCalls; } set { outgoingCalls = value; } } public override bool Equals(System.Object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. CSharpMethod p = obj as CSharpMethod; if ((System.Object)p == null) { return false; } // Return true if the fields match: return (Name == p.Name); } public override int GetHashCode() { return 1; } // Implement IComparable CompareTo to provide default sort order. int IComparable.CompareTo(object obj) { CSharpMethod c1 = this; CSharpMethod c2 = (CSharpMethod)obj; if (c1.Relevance < c2.Relevance) return 1; if (c1.Relevance > c2.Relevance) return -1; else return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Domain.ValueObject { public class StoreSetting { } }
using System; using System.Configuration; using System.Web; using CIPMSBC; /// <summary> /// Summary description for AppRouteManager /// </summary> public class AppRouteManager { // 2014-07-28 The first routing rule is for PJL - if the user is in EligiblePJLottery (used PJ special code, failed at community due to DS public static string GetNextRouteBasedOnStatus(StatusInfo status, string option) { var url = "Step2_3.aspx"; bool isOn = ConfigurationManager.AppSettings["PJLottery"] == "On"; if (status == StatusInfo.EligiblePJLottery && isOn) { var specialCode = SessionSpecialCode.GetPJLotterySpecialCode(); if (specialCode != "") { var campYearId = Convert.ToInt32(HttpContext.Current.Application["CampYearID"]); if (SpecialCodeManager.IsValidCode(campYearId, (int)FederationEnum.PJL, specialCode)) { url = "../PJL/Step2_2_route_info.aspx?prev=" + option; } } } else if (status == StatusInfo.EligiblePJLottery && !isOn) { HttpContext.Current.Session["STATUS"] = (int)StatusInfo.SystemInEligible; } return url; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02.HumanBeing { class Student : Human { public int Grade { get; set; } public Student(string name, string lastName, int grade) { this.Name = name; this.LastName = lastName; this.Grade = grade; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Query.DTO; namespace EBS.Query { public interface IStocktakingPlanQuery { IEnumerable<StocktakingPlanDto> GetPageList(Pager page, SearchStocktakingPlan condition); IEnumerable<StocktakingSummaryDto> GetSummaryData(Pager page, SearchStocktakingPlanSummary condition); IEnumerable<StocktakingPlanItemDto> GetDetails(Pager page, int planId, int? from, int? to, bool showDifference,string productCodeOrBarCode); Dictionary<int, string> GetStocktakingPlanStatus(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NStandard.Windows.Native.Service { public enum ServiceStartType { /// <summary> /// A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services. /// </summary> SERVICE_AUTO_START = 0x00000002, /// <summary> /// A device driver started by the system loader. This value is valid only for driver services. /// </summary> SERVICE_BOOT_START = 0x00000000, /// <summary> /// A service started by the service control manager when a process calls the StartService function. For more information, see Starting Services on Demand. /// </summary> SERVICE_DEMAND_START = 0x00000003, /// <summary> /// A service that cannot be started. Attempts to start the service result in the error code ERROR_SERVICE_DISABLED. /// </summary> SERVICE_DISABLED = 0x00000004, /// <summary> /// A device driver started by the IoInitSystem function. This value is valid only for driver services. /// </summary> SERVICE_SYSTEM_START = 0x00000001, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual { /// <summary> /// Representa el objeto response de RequerimientoBien /// </summary> /// <remarks> /// Creación : GMD 20150609 <br /> /// Modificación : <br /> /// </remarks> public class RequerimientoBienResponse { /// <summary> /// Codigo Requerimiento Bien /// </summary> public Guid CodigoRequerimientoBien { get; set; } /// <summary> /// Codigo Requerimiento /// </summary> public Guid CodigoRequerimiento { get; set; } /// <summary> /// Codigo de Bien /// </summary> public Guid CodigoBien { get; set; } /// <summary> /// Estado de Registro /// </summary> public char EstadoRegistro { get; set; } } }
using System.Collections.Generic; namespace AudioText.Models.ViewModels { public class FilterListItemViewModel { public List<Filter> FilterList { get; private set; } public FilterListItemViewModel(List<Filter> list) { FilterList = list; } } }
using RC.Infra; using RC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace RC.Controllers { public class HomeController : RCController { // // GET: /Home/ private RCContext db = new RCContext(); public ActionResult Index() { var lista = db.Incidentes.AsQueryable(); return View(lista); } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Estacionamento.Map; namespace Infra.Mapeamentos { public class MappingSolicitacoesVagas : EntityTypeConfiguration<SolicitacoesVagasMap> { public MappingSolicitacoesVagas() { // Primary Key this.HasKey(t => t.IdSolicitacao); // Properties this.Property(t => t.IdUser) .IsRequired() .HasMaxLength(128); this.Property(t => t.UserCancel) .IsRequired() .HasMaxLength(128); this.Property(t => t.IdUser) .IsRequired(); // Table & Column Mappings this.ToTable("SolicitacoesMap"); // Relationships HasOptional(s => s.PessoaMap) .WithRequired(s => s.SolicitacaoVaga); HasRequired(x => x.AspNetUserCadastro) .WithMany(x => x.SolicitacoesVagasCadastro) .HasForeignKey(x => x.IdUser); HasRequired(x => x.AspNetUserCancel) .WithMany(x => x.SolicitacoesVagasCancel) .HasForeignKey(x => x.UserCancel); } } }
using IWorkFlow.DataBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("B_YYYD_Comparison", "ID")] public class B_YYYD_Comparison : QueryInfo { [DataField("ID", "B_YYYD_Comparison")] public int ID { get { return this._ID; } set { this._ID = value; } } int _ID; [DataField("qydm", "B_YYYD_Comparison")] public string qydm { get { return this._qydm; } set { this._qydm = value; } } string _qydm; [DataField("sjly", "B_YYYD_Comparison")] public string sjly { get { return this._sjly; } set { this._sjly = value; } } string _sjly; [DataField("dybm", "B_YYYD_Comparison")] public string dybm { get { return this._dybm; } set { this._dybm = value; } } string _dybm; } }
using System; using System.Text; namespace NStandard { public static partial class ConvertEx { /// <summary> /// Returns an object of the specified type and whose value is equivalent to the specified object. /// (Enhance: Support Nullable types.) /// </summary> /// <param name="value">An object that implements the System.IConvertible interface.</param> /// <param name="conversionType">The type of object to return.</param> public static object ChangeType(object value, Type conversionType) { if (conversionType.IsNullable()) { if (value is null) return null; else return Convert.ChangeType(value, conversionType.GetGenericArguments()[0]); } else { if (value is null) return conversionType.CreateDefault(); else return Convert.ChangeType(value, conversionType); } } public static string ToBase58String(byte[] bytes) => Base58Converter.ToBase58String(bytes); public static byte[] FromBase58String(string str) => Base58Converter.FromBase58String(str); //TODO: Functions are being designed. //public static string ToBase32String(byte[] bytes) => Base32Converter.ToBase32String(bytes); //public static byte[] FromBase32String(string str) => Base32Converter.FromBase32String(str); } }
namespace gView.Framework.system { public delegate void TimeEventAddedEventHandler(ITimeStatistics sender, ITimeEvent timeEvent); public delegate void TimeEventsRemovedEventHandler(ITimeStatistics sender); }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Security.Cryptography; using Windows.Storage; using Windows.Storage.Provider; using Windows.Storage.Streams; using GUI.Helpers; using GUI.Models; namespace GUI.ViewModels { public class IrpViewModel : BindableBase { public IrpViewModel(Irp irp = null) => _model = irp ?? new Irp(); private Irp _model; public Irp Model { get => _model; } private bool _isLoading = false; public bool IsLoading { get => _isLoading; set => Set(ref _isLoading, value); } public DateTime TimeStamp { get => DateTime.FromFileTime((long)Model.header.TimeStamp); } public string TimeStampString { get => TimeStamp.ToString("yyyy/MM/dd HH:mm:ss.fffffff"); } public uint ProcessId { get => Model.header.ProcessId; } public uint ThreadId { get => Model.header.ThreadId; } public string IrqLevel { get => Model.IrqlAsString(); } public string Type { get => Model.TypeAsString(); } public uint IoctlCode { get => Model.header.IoctlCode; } public uint Status { get => Model.header.Status; } public uint InputBufferLength { get => Model.header.InputBufferLength; } public uint OutputBufferLength { get => Model.header.OutputBufferLength; } public string DriverName { get => Model.header.DriverName; } public string DeviceName { get => Model.header.DeviceName; } public string ProcessName { get => Model.header.ProcessName; } public byte[] InputBuffer { get => Model.body.InputBuffer; } public byte[] OutputBuffer { get => Model.body.OutputBuffer; } public string IoctlCodeString { get => Model.header.Type == (uint)IrpMajorType.IRP_MJ_DEVICE_CONTROL || Model.header.Type == (uint)IrpMajorType.IRP_MJ_INTERNAL_DEVICE_CONTROL ? $"0x{IoctlCode.ToString("x8")}" : "N/A"; } public string IoctlCodeDetailString { get => Utils.PrintParsedIoctlCode(this.IoctlCode); } public string StatusString { get => $"0x{Status.ToString("x8")}"; } public string StatusFullString { get => Utils.FormatMessage(Status); } private string ShowStringMax(string s, int nb) { if (s == null || s.Length == 0) return ""; int len = Math.Min(s.Length, nb); var t = s.Substring(0, len); if (len == nb) t += "[...]"; return t; } public string InputBufferString { get => InputBuffer != null ? ShowStringMax(BitConverter.ToString(InputBuffer), 10 * 3): ""; } public string OutputBufferString { get => OutputBuffer != null ? ShowStringMax(BitConverter.ToString(OutputBuffer), 10 * 3): ""; } /// <summary> /// Export the IRP as a standalone script whose type is given as parameter. /// </summary> /// <param name="_type">File type of the script</param> /// <returns>True on success, Exception() upon failure</returns> public async Task<bool> ExportAs(string _type) { if (Model.header.Type != (uint)IrpMajorType.IRP_MJ_DEVICE_CONTROL) throw new Exception("Only IRP_MJ_DEVICE_CONTROL IRP can be replayed..."); List<string> ValidTypes = new List<string>() { "Raw", "Powershell", "Python", "C" }; if (!ValidTypes.Contains(_type)) { throw new Exception("Invalid export type provided"); } string template_filepath = null; if (_type != "Raw") { template_filepath = Package.Current.InstalledLocation.Path + $"\\ScriptTemplates\\{_type:s}Template.txt"; if (!File.Exists(template_filepath)) { throw new Exception($"SaveAs{_type}Script(): missing template"); } } return await GenerateBodyScript(_type, template_filepath); } /// <summary> /// Generate the script body /// </summary> /// <param name="TypeStr"></param> /// <param name="template_file"></param> /// <returns></returns> private async Task<bool> GenerateBodyScript(string TypeStr, string template_file) { IBuffer output; if (TypeStr == "Raw") { output = CryptographicBuffer.CreateFromByteArray(this.InputBuffer); } else { var DriverName = this.DriverName; var DeviceName = this.DeviceName.Replace(@"\Device", @"\\."); if (TypeStr == "C") { DeviceName = DeviceName.Replace(@"\", @"\\"); DriverName = DriverName.Replace(@"\", @"\\"); } var IrpDataInStr = ""; foreach (byte c in this.Model.body.InputBuffer) IrpDataInStr += $"{c:X2}"; var fmt = File.ReadAllText(template_file); output = CryptographicBuffer.ConvertStringToBinary( String.Format( fmt, this.IoctlCode, DeviceName, DriverName, $"\"{IrpDataInStr}\"", this.OutputBufferLength ), BinaryStringEncoding.Utf8 ); } // // write it to disk // var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.SuggestedFileName = $"Irp-{this.IoctlCodeString}-Session-{DateTime.Now.ToString("yyyyMMddTHH:mm:ssZ")}"; switch (TypeStr) { case "Powershell": savePicker.FileTypeChoices.Add("PowerShell", new List<string>() { ".ps1" }); break; case "Python": savePicker.FileTypeChoices.Add("Python", new List<string>() { ".py" }); break; case "C": savePicker.FileTypeChoices.Add("C++", new List<string>() { ".cpp" }); break; case "Raw": savePicker.FileTypeChoices.Add("Raw", new List<string>() { ".bin" }); break; } StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); await FileIO.WriteBufferAsync(file, output); FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == FileUpdateStatus.Complete) return true; } throw new Exception($"Couldn't save IRP as a {TypeStr} script..."); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CM_App_Creator { public partial class Eventlog : Page { protected void Page_Load(object sender, EventArgs e) { string fileNEWS = Server.MapPath(@"Eventlog.log"); try { string[] AllLines = System.IO.File.ReadAllLines(fileNEWS); int sortField = 0; int sortField2 = 1; int appcounter = 0; // Demonstrates how to return query from a method. // The query is executed here. DataTable dt = new DataTable(); dt.Columns.Add("Time"); dt.Columns.Add("Creator"); dt.Columns.Add("Action"); foreach (string[] str in RunQueryReturnFields(AllLines, sortField, sortField2)) { if (str[2].Contains("Successfully saved application")) { ++appcounter; str[2] = "<b>" + str[2] + "</b>"; } else if (str[2].Contains("ERROR")) { str[2] = "<b><font color='red'>" + str[2] + "</b></font><br>"; } dt.Rows.Add(str); } foreach (string str in RunQuery(AllLines, sortField, sortField2)) { //dt.Rows.Add(str, str, str); //if (str.Contains("Successfully saved application")) //{ // ++appcounter; // txtfileNews.InnerHtml += "<b>" + str + "</b><br>"; //} //else if (str.Contains("ERROR")) //{ // txtfileNews.InnerHtml += "<b><font color='red'>" + str + "</b></font><br>"; //} //else //{ // txtfileNews.InnerHtml += str + "<br>"; //} } GridView1.DataSource = dt; GridView1.DataBind(); nrofappscreated.InnerText = "Number of applications created: " + appcounter.ToString(); } catch (Exception ex) { // Let the user know what went wrong. alertError.Visible = true; contentdiv.Visible = false; spanError.InnerHtml = String.Format("An error occured when attempting to access file {1}.<br>Error message: {0}", ex.Message, fileNEWS); Console.WriteLine("The file could not be read:"); Console.WriteLine(ex.Message); } } // Returns the query variable, not query results! static IEnumerable<string[]> RunQueryReturnFields(IEnumerable<string> source, int num, int num2) { // Split the string and sort on field[num] var scoreQuery = from line in source let fields = line.Split(';') orderby fields[num] descending, fields[num2] select fields; return scoreQuery; } // Returns the query variable, not query results! static IEnumerable<string> RunQuery(IEnumerable<string> source, int num, int num2) { // Split the string and sort on field[num] var scoreQuery = from line in source let fields = line.Split(';') orderby fields[num] descending, fields[num2] select line; return scoreQuery; } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //if (e.Row.Cells[2].Text == "Successfully saved application") //{ // e.Row.Attributes.Add("style", "font-weight: bold;"); // = "highlightRow"; // ...so highlight it //} } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } } }
using Enviosbase.Data; using Enviosbase.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enviosbase.Business { public class MunicipioBusiness { public int Create(MunicipioModel item) { return new MunicipioDataMapper().Create(item); } public void Update(MunicipioModel item) { MunicipioDataMapper MunicipioDM = new MunicipioDataMapper(); MunicipioDM.Update(item); } public List<MunicipioModel> GetAll() { return new MunicipioDataMapper().GetAll(); } public MunicipioModel GetById(int Id) { return new MunicipioDataMapper().GetById(Id); } public List<MunicipioModel> GetByDepartamento(int IdDepto) { return new MunicipioDataMapper().GetByDepartamento(IdDepto); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Diagnostics; namespace Editor { [DescriptionAttribute("Mesh Component"), CategoryAttribute("Components")] public class MeshComponent : Component { // Reflects the enum types in MeshComponent.h public static string[] FilterNames = { "Cube", "Plane", "Sphere", "Cylinder", "Torus", "Cone" }; #region accessors [TypeConverter(typeof(FilterNameConverter))] [CategoryAttribute("Filter")] public string Filter { get { return FilterNames[(uint)GetField("Filter").value]; } set { string v = value; for (uint i = 0; i < FilterNames.Length; ++i) { if (v == FilterNames[i]) { GetField("Filter").value = i; break; } } } } #endregion accessors public override void OnModify(string propertyName, object newVal) { Filter = (string)newVal; } public MeshComponent() { base.DisplayName = "Mesh"; base.Name = "MeshComponent"; base.Description = "Mesh Component"; } } // https://msdn.microsoft.com/en-us/library/aa302326.aspx internal class FilterNameConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(MeshComponent.FilterNames); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } } }
using Xamarin.Forms; namespace RRExpress.AppCommon.UserControls { /// <summary> /// 控件与MVVM设计原则: /// MVVM 是给使用控件的人用的,不是给写控件的人用的 /// 如果控件里使用了 MVVM 会造成 BindingContext 错乱 /// </summary> public partial class Stepper : ContentView { #region Min /// <summary> /// 最小值 /// </summary> public static readonly BindableProperty MinProperty = BindableProperty.Create("Min", typeof(double), typeof(Stepper), double.MinValue); /// <summary> /// 最小值 /// </summary> public double Min { get { return (double)this.GetValue(MinProperty); } set { this.SetValue(MinProperty, value); } } #endregion #region max /// <summary> /// 最大值 /// </summary> public static readonly BindableProperty MaxProperty = BindableProperty.Create("Max", typeof(double), typeof(Stepper), double.MaxValue); /// <summary> /// 最大值 /// </summary> public double Max { get { return (double)this.GetValue(MaxProperty); } set { this.SetValue(MaxProperty, value); } } #endregion #region Step /// <summary> /// 步长 /// </summary> public static readonly BindableProperty StepProperty = BindableProperty.Create("Step", typeof(double), typeof(Stepper), 1d ); /// <summary> /// 步长 /// </summary> public double Step { get { return (double)this.GetValue(StepProperty); } set { if (value < 1) value = 1; this.SetValue(StepProperty, value); } } #endregion; #region value /// <summary> /// 当前值 /// </summary> public static readonly BindableProperty ValueProperty = BindableProperty.Create("Value", typeof(double), typeof(Stepper), 0d, BindingMode.TwoWay, propertyChanged: ValueChanged); /// <summary> /// 当前值 /// </summary> public double Value { get { return (double)this.GetValue(ValueProperty); } set { if (value < this.Min) value = this.Min; if (value > this.Max) value = this.Max; this.SetValue(ValueProperty, value); } } private static void ValueChanged(BindableObject bindable, object oldValue, object newValue) { var stepper = (Stepper)bindable; stepper.Update(); } #endregion #region format /// <summary> /// 格式 /// </summary> public static readonly BindableProperty FormatProperty = BindableProperty.Create("Format", typeof(string), typeof(Stepper), "0", propertyChanged: FmtChanged); /// <summary> /// 格式 /// </summary> public string Format { get { return (string)this.GetValue(FormatProperty); } set { this.SetValue(FormatProperty, value); } } private static void FmtChanged(BindableObject bindable, object oldValue, object newValue) { var stepper = (Stepper)bindable; stepper.lbl.Text = stepper.Value.ToString(stepper.Format ?? ""); } #endregion public Stepper() { InitializeComponent(); } private void Update() { this.lbl.Text = this.Value.ToString(this.Format ?? ""); this.btnReduce.IsEnabled = this.Value > this.Min; this.btnIncrease.IsEnabled = this.Value < this.Max; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Runtime.InteropServices; namespace identity { public class Text { public Game1 game; Texture2D textbox, z; Vector2 textpos = new Vector2(0, 720); public static int textinitiate; public static int textpause; public static int event1; float timer; string words; int keypress; public static int textkey; private KeyboardState newState; SpriteFont Font; public Text(Game1 game) { this.game = game; textbox = game.Content.Load<Texture2D>("images/Text Box"); z = game.Content.Load<Texture2D>("images/Z"); Font = game.Content.Load<SpriteFont>(@"font"); } public void Update(GameTime Gametime) { KeyboardState keyboardState = Keyboard.GetState(); newState = keyboardState; if (textinitiate >= 1) { if (textpos.Y >= 600) { textpos.Y -= 10; } if (newState.IsKeyDown(Keys.Z)) { keypress += 1; } if (keypress == 1) { textkey += 1; } if (newState.IsKeyUp(Keys.Z)) { keypress = 0; } } if (textinitiate == 0) { words = ""; if (textpos.Y <= 720) { textpos.Y += 10; } textkey = 0; } if (textinitiate == 1) words = "Better check my email."; if (textinitiate == 2) { if (textkey == 0) words = "Kurt: What is this?"; if (textkey == 1) words = "Kurt: I didn't order a bomb."; if (textkey == 2) words = "Kurt: Who is doing this?"; if (textkey == 3) words = "Kurt: Was my iden..."; if (textkey == 4) { words = "Cop: Stop! You are under arrest."; } if (textkey >= 4 && textkey <= 6) { if (Chapter1.coppos1.Y >= 300) { Chapter1.coppos1.Y -= 5; Chapter1.coppos1.X -= 2; Chapter1.coppos2.Y -= 5; Chapter1.coppos3.Y -= 5; Chapter1.coppos3.X += 3; } } if (textkey == 5) { words = "Kurt: What did I do."; } if (textkey == 6) { words = "Cop: You're coming with us"; } if (textkey >= 7) { Chapter1.coppos1.Y += 5; Chapter1.coppos1.X += 2; Chapter1.coppos2.Y += 5; Chapter1.coppos3.Y += 5; Chapter1.coppos3.X -= 3; textpause = 1; Gameplay.KurtPos.X -= 1; Gameplay.KurtPos.Y += 5; if (Chapter1.coppos1.Y >= 750) { game.level1 = 2; Gameplay.KurtPos = new Vector2(1000, 1000); textinitiate = 0; textkey = 1; } } } if (textinitiate == 3) { if (textkey == 1) words = "Kurt: Why am I in here?"; if (textkey == 2) words = "Cop: You are in here because you commited fraud, burglary, hacking, and identity theft."; if (textkey == 3) words = "Kurt: I didn't do any of that. I must have been framed. My idenity must have been stolen."; if (textkey == 4) words = "Cop: Yea right. You will be rotting in here for the next 20 years."; if (textkey == 5) { words = "Nooooo........"; event1 = 1; } } if (textinitiate == 4) { if (textkey == 0) words = "You got a lantern! Might come in handy later."; } if (textinitiate == 5) { words = "Hmmm... What does this do?"; if (textkey == 1) textinitiate = 0; } if (textinitiate == 6) { words = "I have to get my identity back."; if (textkey == 1) textinitiate = 0; } if (textinitiate == 7) words = ""; if (textinitiate == 8) words = ""; if (textinitiate == 9) words = ""; if (textinitiate == 10) words = ""; if (textinitiate == 11) words = ""; if (textinitiate == 12) words = ""; if (textinitiate == 13) words = ""; if (textinitiate == 14) words = ""; if (textinitiate == 15) words = ""; if (textinitiate == 16) words = ""; if (textinitiate == 17) words = ""; } public void Draw(SpriteBatch spritebatch) { spritebatch.Begin(); spritebatch.Draw(textbox, textpos, null, Color.White * 0.5f, 0, Vector2.Zero, game.scale, SpriteEffects.None, 0); if (keypress == 0) { spritebatch.Draw(z, new Vector2(textpos.X + 1000, textpos.Y + 75), null, Color.White * 0.5f, 0, Vector2.Zero, 1, SpriteEffects.None, 0); } spritebatch.DrawString(Font, words, new Vector2(150, textpos.Y + 50), Color.White); spritebatch.End(); } } }
using Manager.Interface; using Repository.Interface; using System; using System.Collections.Generic; using System.Text; using TestApp4.Models; namespace Manager.Implementation { public class UserRoleManager : IUserRoleManager { private IUserRoleRepository userroleRepository; public UserRoleManager(IUserRoleRepository userroleRepository) { this.userroleRepository = userroleRepository; } public object ActiveOrDeactive(long userId) { throw new NotImplementedException(); } public object Create(string userName) { try { var ob = new UserRole() { RoleName = userName , UpdatedOn = DateTime.Now, CreatedOn = DateTime.Now, IsActive = true }; this.userroleRepository.Add(ob); this.userroleRepository.SaveChanges(); var result = new { success = true, successMessage = "User Added sccessfully !" }; return result; } catch (Exception ex) { var result = new { success = true, errorMessage = ex.Message }; return result; } } public object GetAllUserRole() { try { var data = this.userroleRepository.GetAll(); var result = new { success = true , data = data }; return result; } catch (Exception ex) { var result = new { success = false , errorMessage = ex.Message }; return result; } } public object Update(long userId, string fristName, string lastName) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace CODE.Framework.Wpf.Theme.Universe.Controls { /// <summary>Simple rendering mechanism to render a standard Newsroom loading animation (circular)</summary> public class CircularProgressAnimation : Grid { /// <summary>Constructor</summary> public CircularProgressAnimation() { ClipToBounds = false; IsVisibleChanged += (o, args) => { if ((bool)args.NewValue && IsActive) StartAnimation(); else StopAnimation(); }; } /// <summary>Defines the number of actual dots in the animation</summary> public int DotCount { get { return (int)GetValue(DotCountProperty); } set { SetValue(DotCountProperty, value); } } /// <summary>Defines the number of actual dots in the animation</summary> public static readonly DependencyProperty DotCountProperty = DependencyProperty.Register("DotCount", typeof(int), typeof(CircularProgressAnimation), new UIPropertyMetadata(6, TriggerVisualRefresh)); /// <summary>Defines the diameter of each dot within the animation</summary> public double DotDiameter { get { return (double)GetValue(DotDiameterProperty); } set { SetValue(DotDiameterProperty, value); } } /// <summary>Defines the diameter of each dot within the animation</summary> public static readonly DependencyProperty DotDiameterProperty = DependencyProperty.Register("DotDiameter", typeof(double), typeof(CircularProgressAnimation), new UIPropertyMetadata(6d, TriggerVisualRefresh)); /// <summary>Brush used to draw each dot</summary> public Brush DotBrush { get { return (Brush)GetValue(DotBrushProperty); } set { SetValue(DotBrushProperty, value); } } /// <summary>Brush used to draw each dot</summary> public static readonly DependencyProperty DotBrushProperty = DependencyProperty.Register("DotBrush", typeof(Brush), typeof(CircularProgressAnimation), new UIPropertyMetadata(Brushes.Black, TriggerVisualRefresh)); /// <summary>Determines the spacing of the individual dots (1 = neutral)</summary> public double DotSpaceFactor { get { return (double)GetValue(DotSpaceFactorProperty); } set { SetValue(DotSpaceFactorProperty, value); } } /// <summary>Determines the spacing of the individual dots (1 = neutral)</summary> public static readonly DependencyProperty DotSpaceFactorProperty = DependencyProperty.Register("DotSpaceFactor", typeof(double), typeof(CircularProgressAnimation), new UIPropertyMetadata(1d, TriggerVisualRefresh)); /// <summary>Sets the speed of the animation (factor 1 = neutral speed, lower factors are faster, larger factors slower, as it increases the time the animation has to perform)(</summary> public double DotAnimationSpeedFactor { get { return (double)GetValue(DotAnimationSpeedFactorProperty); } set { SetValue(DotAnimationSpeedFactorProperty, value); } } /// <summary>Sets the speed of the animation (factor 1 = neutral speed, lower factors are faster, larger factors slower, as it increases the time the animation has to perform)(</summary> public static readonly DependencyProperty DotAnimationSpeedFactorProperty = DependencyProperty.Register("DotAnimationSpeedFactor", typeof(double), typeof(CircularProgressAnimation), new UIPropertyMetadata(1d, TriggerVisualRefresh)); /// <summary>Indicates whether the progress animation is active</summary> /// <value>True if active</value> /// <remarks>For the progress animation to be displayed, the IsActive must be true, and the control must have its visibility set to visible.</remarks> public bool IsActive { get { return (bool)GetValue(IsActiveProperty); } set { SetValue(IsActiveProperty, value); } } /// <summary>Indicates whether the progress animation is active</summary> /// <value>True if active</value> /// <remarks>For the progress animation to be displayed, the IsActive must be true, and the control must have its visibility set to visible.</remarks> public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register("IsActive", typeof(bool), typeof(CircularProgressAnimation), new UIPropertyMetadata(false, (s, e) => { var progress = s as CircularProgressAnimation; if (progress != null && (bool)e.NewValue && progress.Visibility == Visibility.Visible) progress.StartAnimation(); else if (progress != null) progress.StopAnimation(); })); /// <summary> /// Defines the delay (in milliseconds) before the progress animation appears when activated /// </summary> public int StartDelay { get { return (int)GetValue(StartDelayProperty); } set { SetValue(StartDelayProperty, value); } } /// <summary> /// Defines the delay (in milliseconds) before the progress animation appears when activated /// </summary> public static readonly DependencyProperty StartDelayProperty = DependencyProperty.Register("StartDelay", typeof(int), typeof(CircularProgressAnimation), new PropertyMetadata(0)); /// <summary>Triggers a re-creation of all the child elements that make up the animation</summary> /// <param name="o">Dependency Object</param> /// <param name="e">Event arguments</param> private static void TriggerVisualRefresh(DependencyObject o, DependencyPropertyChangedEventArgs e) { var o2 = o as CircularProgressAnimation; if (o2 == null || !o2.IsActive) return; o2.CreateVisuals(o2.DotCount); o2.StartAnimation(); } /// <summary>Creates the actual visual elements that make up the animation</summary> /// <param name="circleCount">Number of circles to use in the animation</param> private void CreateVisuals(int circleCount) { Children.Clear(); _storyboards.Clear(); for (var counter = 0; counter < circleCount; counter++) { var grid = new Grid { RenderTransformOrigin = new Point(.5, .5), RenderTransform = new RotateTransform() }; var ellipse = new Ellipse { Height = DotDiameter, Width = DotDiameter, Fill = DotBrush, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center }; grid.Children.Add(ellipse); Children.Add(grid); var a1 = new DoubleAnimationUsingKeyFrames { RepeatBehavior = RepeatBehavior.Forever, BeginTime = TimeSpan.FromMilliseconds((DotSpaceFactor * 175 * counter) + StartDelay) }; Storyboard.SetTargetProperty(a1, new PropertyPath("(UIElement.RenderTransform).(RotateTransform.Angle)")); Storyboard.SetTarget(a1, grid); var storyboard = new Storyboard(); storyboard.Children.Add(a1); a1.KeyFrames.Add(new EasingDoubleKeyFrame(0d, KeyTime.FromTimeSpan(new TimeSpan(0)))); a1.KeyFrames.Add(new EasingDoubleKeyFrame(180d, KeyTime.FromTimeSpan(new TimeSpan((long)(12500000 * DotAnimationSpeedFactor))))); a1.KeyFrames.Add(new EasingDoubleKeyFrame(360d, KeyTime.FromTimeSpan(new TimeSpan((long)(16500000 * DotAnimationSpeedFactor))))); var a2 = new DoubleAnimationUsingKeyFrames { RepeatBehavior = new RepeatBehavior(1), BeginTime = TimeSpan.FromMilliseconds((DotSpaceFactor * 175 * counter) + StartDelay) }; Storyboard.SetTargetProperty(a2, new PropertyPath("(UIElement.Opacity)")); Storyboard.SetTarget(a2, ellipse); storyboard.Children.Add(a2); a2.KeyFrames.Add(new EasingDoubleKeyFrame(1d, KeyTime.FromTimeSpan(new TimeSpan(0)))); _storyboards.Add(storyboard); } } /// <summary> /// Starts the animation. /// </summary> public void StartAnimation() { if (_animationInStartMode) return; // Preventing accidental recursive calls _animationInStartMode = true; CreateVisuals(DotCount); foreach (var sb in _storyboards) sb.Begin(); if (!IsActive) IsActive = true; _animationInStartMode = false; } /// <summary>Internal field used to prevent recursive calls</summary> private bool _animationInStartMode; /// <summary> /// Stops the animation. /// </summary> public void StopAnimation() { foreach (var sb in _storyboards) sb.Stop(); } private readonly List<Storyboard> _storyboards = new List<Storyboard>(); } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using Android.App; using Android.Content; using MvvmCross.Platform; using MvvmCross.Platform.Core; using MvvmCross.Platform.Droid.Platform; using MvvmCross.Plugins.PictureChooser; using ResidentAppCross.Droid.Views.AwesomeSiniExtensions; using ResidentAppCross.Services; using Square.OkHttp; namespace ResidentAppCross.Droid.Views.Sections { public class AndroidDialogService : IDialogService { private Application _droidApp; private IMvxPictureChooserTask _pictureChooserTask; public Activity CurrentTopActivity => Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity; public IMvxPictureChooserTask PictureChooserTask { get { return _pictureChooserTask ?? (_pictureChooserTask = Mvx.Resolve<IMvxPictureChooserTask>()); } set { _pictureChooserTask = value; } } public IMvxMainThreadDispatcher Dispatcher => Mvx.Resolve<IMvxMainThreadDispatcher>(); public AndroidDialogService(Application droidApp) { _droidApp = droidApp; } public Task<T> OpenSearchableTableSelectionDialog<T>(IList<T> items, string title, Func<T, string> itemTitleSelector, Func<T, string> itemSubtitleSelector = null, object arg = null) { return Task.Factory.StartNew(() => { T result = default(T); ManualResetEvent waitForCompleteEvent = new ManualResetEvent(false); Dispatcher.RequestMainThreadAction(() => { var frag = new SearchDialog<T>() { Items = items, TitleSelector = itemTitleSelector, }; frag.OnItemSelected += obj => { result = obj; waitForCompleteEvent.Set(); }; frag.Show(CurrentTopActivity.FragmentManager, "Search Dialog"); }); waitForCompleteEvent.WaitOne(); return result; }); } public Task<DateTime?> OpenDateTimeDialog(string title) { return Task.Factory.StartNew(() => { DateTime? result = null; ManualResetEvent waitForCompleteEvent = new ManualResetEvent(false); Dispatcher.RequestMainThreadAction(() => { var frag = new DateTimePickerDialog() { }; frag.DateTimeSelected += obj => { result = obj; waitForCompleteEvent.Set(); frag.Dismiss(); }; frag.Show(CurrentTopActivity.FragmentManager, "Date Time Picker"); }); waitForCompleteEvent.WaitOne(); return result; }); } public Task<DateTime?> OpenDateDialog(string title) { throw new NotImplementedException(); } public static int ImageDialogResult = 288823; public Task<byte[]> OpenImageDialog() { return Task.Factory.StartNew(() => { byte[] result = null; ManualResetEvent waitForCompleteEvent = new ManualResetEvent(false); Dispatcher.RequestMainThreadAction(() => { var frag = new NotificationDialog { TitleText = "Select Photo Source", Mode = NotificationDialogMode.Select }; frag.SetActions(new[] { new NotificationDialogItem() { Action = async () => { result = await OpenImageTakeDialog(); waitForCompleteEvent.Set(); }, Title = "Take Photo", ShouldDismiss = true }, new NotificationDialogItem() { Action = async () => { result = await OpenImagePickDialog(); waitForCompleteEvent.Set(); }, Title = "Select Photo", ShouldDismiss = true }, new NotificationDialogItem() { Action = ()=> { }, Title = "Cancel", ShouldDismiss = true }, }); frag.Show(CurrentTopActivity.FragmentManager, "Image Pick Dialog"); }); waitForCompleteEvent.WaitOne(); return result; }); } public async Task<byte[]> OpenImagePickDialog() { var stream = await PictureChooserTask.ChoosePictureFromLibrary(1024, 62); if (stream == null) return null; byte[] buffer = new byte[stream.Length]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } public async Task<byte[]> OpenImageTakeDialog() { var stream = await PictureChooserTask.TakePicture(1024, 62); if (stream == null) return null; byte[] buffer = new byte[stream.Length]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } public void OpenNotification(string title, string subtitle, string ok, Action action = null) { if(action != null) throw new Exception("Handler is not currently supported on droid"); var frag = new NotificationDialog() { }; frag.Mode = NotificationDialogMode.Notify; frag.TitleText = title; frag.SubTitleText = subtitle; frag.SetActions(new NotificationDialogItem[] { new NotificationDialogItem() { Action = () => { }, Title = ok, ShouldDismiss = true } }); frag.Show(CurrentTopActivity.FragmentManager, "Notification Dialog"); } public void OpenImageFullScreen(object imageObject) { var data = imageObject as byte[]; var frag = new PhotoViewerDialog() {CurrentData = data}; frag.Show(CurrentTopActivity.FragmentManager, "Photo Viewer"); } public void OpenImageFullScreenFromUrl(string url) { var frag = new PhotoViewerDialog() { CurrentUrl = url }; frag.Show(CurrentTopActivity.FragmentManager, "Photo Viewer"); } public void OpenUrl(string url) { Intent browserIntent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(url)); CurrentTopActivity.StartActivity(browserIntent); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Thingy.WebServerLite.Api; namespace Thingy.WebServerLite { public class ControllerProvider : IControllerProvider { private readonly IController[] controllers; public ControllerProvider(IController[] controllers) { this.controllers = controllers.OrderByDescending(c => c.Priority).ToArray(); } public IController GetControllerForRequest(IWebServerRequest request) { return controllers.FirstOrDefault(c => c.CanHandle(request)); } public IController GetNextControllerForRequest(IWebServerRequest request, Priorities prreviousPiority) { return controllers.FirstOrDefault(c => c.Priority > prreviousPiority && c.CanHandle(request)); } } }
using System; using System.Collections.Generic; namespace POSServices.PosMsgModels { public partial class IntegrationParameter { public string Erpdatabase { get; set; } public string BackendPosdatabase { get; set; } public int Recid { get; set; } } }
using System; namespace Net01_1.Model { class TextMaterial:BaseTrainingMaterial, ICloneable { public string Text { get { return _text; } set { if (value != null && value.Length > 1000) { throw new ArgumentException("Text should contain less then 1000 simbols"); } _text = value; } } private string _text; public override string ToString() { return Description; } public object Clone() { var text = new TextMaterial { Text = Text, Description = Description, Id = Id }; return text; } } }
namespace Brambillator.Historiarum.Repositories.EntityFramework { public static class EFHistoriarumUnitOfWorkInitializer { public static void Initialize(EFHistoriarumUnitOfWork context) { context.Database.EnsureCreated(); } } }
namespace Alabo.UI.Design.AutoReports.Dtos { /// <summary> /// CountReportTable /// </summary> public class CountReportTable { /// <summary> /// 表格名称 /// </summary> public string Name { get; set; } /// <summary> /// 日期格式 /// 格式:2019-6-26 /// </summary> public string Date { get; set; } /// <summary> /// 数量 /// </summary> public long Count { get; set; } /// <summary> /// 比例 /// </summary> public string Rate { get; set; } /// <summary> /// 表格 /// </summary> public CountReportItem AutoReportChart { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; public class LCode149 { public int MaxPoints(int[][] points) { if (points == null) return 0; if (points.Length == 0) return 0; if (points[0].Length == 0) return 0; Dictionary<float, int> counts = new Dictionary<float, int>(); int diffY0Cnt = 0; int maxCount = 0; int surplus = 0; for (int i = 0; i < points.Length; i++) { float kj = 0; diffY0Cnt = 0; counts.Clear(); surplus = 0; for (int j = 0; j < points.Length; j++) { if (j == i) continue; float diffX = points[i][0] - points[j][0]; float diffY = points[i][1] - points[j][1]; if (points[i][0] - points[j][0] == 0 && points[i][1] - points[j][1] == 0) { surplus++; } else { if (diffY == 0) { diffY0Cnt++; } else { kj = diffX / diffY; if (!counts.ContainsKey(kj)) { counts.Add(kj, 1); } else { counts[kj]++; } } } } foreach (var count in counts) { int surplusedVal = count.Value + surplus; if (surplusedVal > maxCount) { maxCount = surplusedVal; } } if (diffY0Cnt + surplus > maxCount) { maxCount = diffY0Cnt + surplus; } } return maxCount+1; } private void Test() { int[][] points = new int[][] { new int[]{ 0,0}, new int[]{ 94911151,94911150}, new int[]{ 94911152,94911151}, }; Console.WriteLine(MaxPoints(points)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebAppAdvocacia.Models; namespace WebAppAdvocacia.Controllers { public class TribunalApiController : ApiController { public Tribunal Get() { Tribunal T = new Tribunal() { TribunalID = 150, Descricao = "Qualquer Coisa", Endereco = "Rua A"}; return (T); } } }
using CRMSecurityProvider.Configuration; using CRMSecurityProvider.Repository; using CRMSecurityProvider.Repository.Factory; namespace AlphaSolutions.SitecoreCms.ExtendedCRMProvider.Repository.Factory { public class UserRepositoryFactory : RepositoryFactory, IUserRepositoryFactory { public UserRepositoryBase GetRepository(ConfigurationSettings settings) { return base.Resolve<UserRepositoryBase>(settings); } } }
using System; namespace SourceCode { public interface Ipower { int GetPower(); } public class PowerSupply : Ipower { public int GetPower() => 100; } public class Deskfan { private Ipower _PowGet; public Deskfan(Ipower PowGet) { _PowGet = PowGet; } public string Work() { int power = _PowGet.GetPower(); if (power <= 0) { return "don't work."; } else if (power < 100) { return "work slow."; } else if (power < 200) { return "work hight."; } else { return "boom!!!"; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using PROnline.Models.WorkStations; using PROnline.Models.Teams; using PROnline.Models; using PROnline.Src; namespace PROnline.Controllers.WorkStations { public class WorkStationController : Controller { private PROnlineContext db = new PROnlineContext(); // // GET: /WorkStation/ public ActionResult Index() { ViewBag.list = Utils.PageIt(this, db.WorkStation.Where(t => t.isDeleted == false) .OrderBy(t => t.CreateDate)).ToList(); return View(); } public JsonResult NameCheck() { String name = Request.Params["WorkStationName"]; int count = db.WorkStation.Where(r => r.WorkStationName == name).Count(); return Json(count == 0, JsonRequestBehavior.AllowGet); } // // GET: /WorkStation/Details/5 public ActionResult Details(Guid id) { WorkStation result = db.WorkStation.Find(id); return View(result); } // // GET: /WorkStation/Create public ActionResult Create() { return View(); } // // POST: /WorkStation/Create [HttpPost] public ActionResult Create(WorkStation workstation) { if (ModelState.IsValid) { WorkStation temp = new WorkStation(); temp.WorkStationID = Guid.NewGuid(); temp.WorkStationName = workstation.WorkStationName; temp.WorkStationerName = workstation.WorkStationerName; temp.Telephone = workstation.Telephone; temp.CreateDate = DateTime.Now; temp.CreatorID = Utils.CurrentUser(this).Id; temp.isDeleted = false; db.WorkStation.Add(temp); db.SaveChanges(); return RedirectToAction("Index"); } return View(); } // // GET: /WorkStation/Edit/5 public ActionResult Edit(Guid id) { WorkStation result = db.WorkStation.Find(id); return View(result); } // // POST: /WorkStation/Edit/5 [HttpPost] public ActionResult Edit(WorkStation workstation) { String wName = Request.Form.Get("WorkStationName"); Guid wid = Guid.Parse(Request.Form.Get("WorkStationID")); int count = db.WorkStation.Where(r => r.WorkStationName == wName).ToList().Count(); if (count != 0) { if (count == 1) { Guid temp = db.WorkStation.Where(r => r.WorkStationName == wName).Single().WorkStationID; if (temp.CompareTo(wid) != 0) { ModelState.AddModelError("Error", "工作站名不能重复"); return View(workstation); } } else if (count > 1) { ModelState.AddModelError("Error", "工作站名不能重复"); return View(workstation); } } if (ModelState.IsValid) { Guid id = Guid.Parse(Request.Form.Get("WorkStationID")); WorkStation temp = db.WorkStation.Find(id); temp.WorkStationName = workstation.WorkStationName; temp.WorkStationerName = workstation.WorkStationerName; temp.Telephone = workstation.Telephone; temp.ModifierID = Utils.CurrentUser(this).Id; temp.ModifyDate = DateTime.Now; db.Entry(temp).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(); } // // GET: /WorkStation/Delete/5 public ActionResult Delete(Guid id) { WorkStation result = db.WorkStation.Find(id); return View(result); } // // POST: /WorkStation/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(Guid id) { WorkStation temp = db.WorkStation.Find(id); temp.isDeleted = true; var list = db.Team.Where(r => r.WorkStationID == id).ToList(); if (list.Count != 0) { foreach(Team item in list) { item.WorkStationID = null; item.WorkStation = null; db.Entry(item).State = EntityState.Modified; } } db.WorkStation.Remove(temp); db.SaveChanges(); return RedirectToAction("Index"); } [HttpPost] public JsonResult Tips() { Guid id = Guid.Parse(Request.Params.Get("wID")); WorkStation w = db.WorkStation.Find(id); String wName = w.WorkStationName; String werName = w.WorkStationerName; String wTel = w.Telephone; String result = wName + werName + wTel; return Json(w, JsonRequestBehavior.AllowGet); } } }
using Inventory.Data; using Inventory.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Inventory.Services { public class DishIngredientService : IDishIngredientService { private IDataServiceFactory DataServiceFactory { get; } public DishIngredientService(IDataServiceFactory dataServiceFactory) { DataServiceFactory = dataServiceFactory; } public async Task<DishIngredientModel> GetDishIngredientAsync(int id) { using (var dataService = DataServiceFactory.CreateDataService()) { var entity = await dataService.GetDishIngredientAsync(id); return await CreateModelAsync(entity, true); } } public async Task<DishIngredientModel> GetDishIngredientAsync(Guid dishIngredientGuid) { using (var dataService = DataServiceFactory.CreateDataService()) { var entity = await dataService.GetDishIngredientAsync(dishIngredientGuid); return await CreateModelAsync(entity, true); } } public async Task<IList<DishIngredientModel>> GetDishIngredientsAsync(Guid dishGuid) { var models = new List<DishIngredientModel>(); using (var dataService = DataServiceFactory.CreateDataService()) { var entities = await dataService.GetDishIngredientsAsync(dishGuid); foreach (var entity in entities) { var model = await CreateModelAsync(entity, false); models.Add(model); } } return models; } private async Task<DishIngredientModel> CreateModelAsync(DishIngredient source, bool includeAllFields) { var model = new DishIngredientModel() { Id = source.Id, RowGuid = source.RowGuid, DishGuid = source.DishGuid, Name = source.Name, RowPosition = source.RowPosition, Price = source.Price, Thumbnail = source.Thumbnail, ThumbnailSource = await BitmapTools.LoadBitmapAsync(source.Thumbnail) }; if (includeAllFields) { model.Picture = source.Picture; model.PictureSource = await BitmapTools.LoadBitmapAsync(source.Picture); } return model; } } }
using Chloe.NBAClient.Contracts; using System.Threading.Tasks; using Chloe.ViewModels; using Chloe.ViewComponents.PlayersComponent.Contracts; namespace Chloe.ViewComponents.PlayersComponent { public class PlayersComponent : IPlayersComponent { public PlayersComponent(INBAClient client) { this.client = client; this.ComponentType = ComponentType.Players; this.ViewName = "Players"; } public Task InvokeAsync() { return Task.Run(async () => { var result = await client.GetAllPlayersAsync(); this.Title = result.Resource; }); } public string Title { get; set; } public ComponentType ComponentType { get; set; } public string ViewName { get; set; } protected readonly INBAClient client; public string ViewLocation { get { return string.Format("Components/_{0}", this.ViewName); } } } }
using FastNet.Framework.Dapper; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; namespace SkywalkingDemo.Repository { public class TestRepository : SqlServerRepository { public TestRepository(string connString) : base(connString) { } } }
using System; using System.Collections.Generic; namespace TagProLeague.Models { public class Team : Document { public DateTime? EstablishedOn { get; set; } public DateTime? LastActiveOn { get; set; } public string LogoUrl { get; set; } public string FullName { get; set; } public string Founder { get; set; } public List<string> Leagues { get; set; } public List<string> Players { get; set; } public List<string> Series { get; set; } public List<string> Maps { get; set; } public List<string> Awards { get; set; } public List<string> Games { get; set; } public string TotalStatline { get; set; } } }
using System.Collections.Generic; namespace Algorithms.LeetCode { // Check different approaches // 1. O(n^3) time and O(1) space // 2. O(n^2) time and O(n) space // 3. O(n^2) time and O(1) space // 4. O(n) time and O(n) space public class SubarraySumEqualsK { // Approach #4: hashtable public int SubarraySum(int[] nums, int k) { var dict = new Dictionary<int, int>(); dict.Add(0, 1); var cnt = 0; var sum = 0; for (int i = 0; i < nums.Length; ++i) { sum += nums[i]; if (dict.ContainsKey(sum - k)) cnt += dict[sum - k]; if (dict.ContainsKey(sum)) dict[sum] = dict[sum] + 1; else dict.Add(sum, 1); } return cnt; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using TestProject_Aarif.CustomAttributes; namespace TestProject_Aarif.Models { public class EmployeeModel { [Required] public string FirstName { get; set; } public string LastName { get; set; } [PositiveNumber] public double AnnualSalary { get; set; } [Range(0, 12)] public int Rate { get; set; } public string Period { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class TelaBehavior : MonoBehaviour { [Header("Identificação")] public int index; [Header("Animações")] private Animator anim; [Header("Animações")] public UnityEvent StartFI; public UnityEvent StartFO; public UnityEvent EndFI; public UnityEvent EndFO; // Use this for initialization void Start () { //GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.width, Screen.height); transform.position = new Vector2(Screen.width / 2, Screen.height / 2); transform.SetSiblingIndex(index: 4-index); anim = GetComponent<Animator>(); if (index > 0) PlayFadeOut(); } // Update is called once per frame void Update () { } public void PlayFadeIn() { anim.SetBool("Show", true); transform.SetAsLastSibling(); } public void PlayFadeOut() { anim.SetBool("Show", false); } public void StartFadeIn() { StartFI.Invoke(); } public void StartFadeOut() { StartFO.Invoke(); } public void EndFadeIn() { EndFI.Invoke(); } public void EndFadeOut() { EndFO.Invoke(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Happiness.Models; using System.Data.Entity; namespace Happiness.Controllers { public class EmployeeSearchController : Controller { // // GET: /EmployeeSearch/ public ActionResult Index() { return View(); } #region UserProfileIndex UsersContext db = new UsersContext(); public ActionResult Edit(long id = 0) { ReportingAuthorityAllocation ReportingAuthorityAllocation = db.ReportingAuthorityAllocation.Find(id); // division.PhotoPath = "~/Upload/" + division.PhotoPath; if (ReportingAuthorityAllocation == null) { return HttpNotFound(); } return View(ReportingAuthorityAllocation); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(long id) { UserProfile division = db.UserProfiles.Find(id); db.UserProfiles.Remove(division); db.SaveChanges(); return RedirectToAction("Index"); } [HttpPost] public JsonResult DeleteAJAX(int divsID) { try { //UserProfile child = (from t in db.UserProfiles where t.Report_MasterID == divsID select t).FirstOrDefault(); //db.ReportingAuthorityAllocationChild.Remove(child); //db.SaveChanges(); UserProfile division = db.UserProfiles.Find(divsID); db.UserProfiles.Remove(division); db.SaveChanges(); return Json("Record deleted successfully!"); } catch (Exception ex) { return Json(ex.Message); } } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } private int SortString(string s1, string s2, string sortDirection) { return sortDirection == "asc" ? s1.CompareTo(s2) : s2.CompareTo(s1); } private int SortInteger(string s1, string s2, string sortDirection) { long i1 = long.Parse(s1); long i2 = long.Parse(s2); return sortDirection == "asc" ? i1.CompareTo(i2) : i2.CompareTo(i1); } private int SortDateTime(string s1, string s2, string sortDirection) { DateTime d1 = DateTime.Parse(s1); DateTime d2 = DateTime.Parse(s2); return sortDirection == "asc" ? d1.CompareTo(d2) : d2.CompareTo(d1); } public static List<ReportingAuthorityAllocation> GetAllTransactions() { using (var context = new UsersContext()) { return (from pd in context.ReportingAuthorityAllocation join od in context.ReportingAuthority on pd.Report_id equals od.id select new { id = pd.id, Report_id = pd.Report_id, Reporting_auth_name = od.Reporting_auth_name // StudentName = od.StudentName }).AsEnumerable().Select(x => new ReportingAuthorityAllocation { id = x.id, Report_id = x.Report_id, Reporting_auth_name = x.Reporting_auth_name // StudentName = x.StudentName }).ToList(); } } private List<UserProfile> FilterData(ref int recordFiltered, int start, int length, string search, int sortColumn, string sortDirection) { List<UserProfile> list = new List<UserProfile>(); if (search == null) { list = db.UserProfiles.ToList(); } else { // simulate search foreach (UserProfile dataItem in db.UserProfiles.ToList()) { if (dataItem.EmployeeCode.ToUpper().Contains(search.ToUpper()) || dataItem.EmployeeName.ToUpper().Contains(search.ToUpper()) || dataItem.Emp_Mob.ToString().Contains(search.ToUpper()) || dataItem.Emp_Email.ToString().Contains(search.ToUpper())) { list.Add(dataItem); } } } // simulate sort if (sortColumn == 0) {// sort Name list.Sort((x, y) => SortString(x.EmployeeCode, y.EmployeeCode, sortDirection)); } if (sortColumn == 1) {// sort Name list.Sort((x, y) => SortString(x.EmployeeName, y.EmployeeName, sortDirection)); } if (sortColumn == 3) {// sort Name list.Sort((x, y) => SortString(x.Emp_Email, y.Emp_Email, sortDirection)); } //else if (sortColumn == 1) //{// sort Name // list.Sort((x, y) => SortInteger(x.StudentRegno, y.StudentRegno, sortDirection)); //} //else if (sortColumn == 2) //{// sort Age // list.Sort((x, y) => SortInteger(x.StudentAppNo, y.StudentAppNo, sortDirection)); //} //else if (sortColumn == 3) //{ // list.Sort((x, y) => SortInteger(x.RechargeCardNo, y.RechargeCardNo, sortDirection)); // // sort DoB // // list.Sort((x, y) => SortDateTime(x.DoB, y.DoB, sortDirection)); //} recordFiltered = list.Count; // get just one page of data list = list.GetRange(start, Math.Min(length, list.Count - start)); return list; } public class DataTableData { public int draw { get; set; } public int recordsTotal { get; set; } public int recordsFiltered { get; set; } public List<UserProfile> data { get; set; } } public ActionResult GettAllData(int draw, int start, int length) { string search = Request.QueryString["search[value]"]; int sortColumn = -1; string sortDirection = "asc"; if (length == -1) { // length = TOTAL_ROWS; } // note: we only sort one column at a time if (Request.QueryString["order[0][column]"] != null) { sortColumn = int.Parse(Request.QueryString["order[0][column]"]); } if (Request.QueryString["order[0][dir]"] != null) { sortDirection = Request.QueryString["order[0][dir]"]; } DataTableData dataTableData = new DataTableData(); dataTableData.draw = draw; // dataTableData.recordsTotal = TOTAL_ROWS; int recordsFiltered = 0; dataTableData.data = FilterData(ref recordsFiltered, start, length, search, sortColumn, sortDirection); dataTableData.recordsFiltered = recordsFiltered; return Json(dataTableData, JsonRequestBehavior.AllowGet); } public JsonResult Employees() { return Json(db.UserProfiles.ToList(), JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult CardActivateOrDeactivate(int StudID) { try { UserProfile userpro = db.UserProfiles.Find(StudID); if (userpro.Emp_isActive == true) { userpro.Emp_isActive = false; } else { userpro.Emp_isActive = true; } db.Entry(userpro).State = EntityState.Modified; db.SaveChanges(); } catch (Exception ex) { } UserProfile studM = db.UserProfiles.Find(StudID); bool cardStatus = studM.Emp_isActive; return Json(studM.Emp_isActive, JsonRequestBehavior.AllowGet); } #endregion } }
using BenefitDeduction.Employees.FamilyMembers; using System.Collections.Generic; namespace BenefitDeduction.Employees { public interface IEmployeeRepository { List <IEmployee> GetEmployees(); IEmployee GetEmployeeById(int employeeId); List<IFamilyMember> GetFamilyMembers(IEmployee employee); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Models { public class InvoiceLine { public InvoiceLine() { Description = ""; ItemId = ""; PriceLevel = ""; SerialNumber = ""; TaxCode = ""; TransCode = ""; } public double Cost { get; set; } public string Description { get; set; } public double FinalPrice { get; set; } public string ItemId { get; set; } public int LineOrder { get; set; } public int OnHand { get; set; } public int ParentRecordId { get; set; } public double Points { get; set; } public double Price { get; set; } public string PriceLevel { get; set; } public int Qty { get; set; } public int RecordId { get; set; } public string SerialNumber { get; set; } public string TaxCode { get; set; } public double Discount { get; set; } public string TransCode { get; set; } public void CalculateDiscount() { if (Qty == 0 || TransCode == "O") return; var price = Price*Qty; Discount = (FinalPrice - price)/Qty; } } }
/******************************************* * * This class should only control Modules that involves Player Air Controls * NO CALCULATIONS SHOULD BE DONE HERE * *******************************************/ using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Player.Controllers { [System.Serializable] public class WallJumpController : PlayerControllerManager.Controller { [SerializeField] [MinValue(0f)] private float m_movementRestrictionDuration; [SerializeField] private float m_minimumWallHeight; private IWallJump m_wallJump; private bool m_hasWallJumped; private float m_movementRestrictionTimer; public bool hasWallJumped => m_hasWallJumped; public bool isRestricting => m_movementRestrictionTimer > 0; public float minimumWallHeight => m_minimumWallHeight; public override void Initialize() { m_wallJump = m_player.GetComponentInChildren<IWallJump>(); m_movementRestrictionTimer = 0; } public void HandleWallJump() { if (m_input.isJumpPressed) { m_hasWallJumped = m_wallJump.Jump(true); if (m_hasWallJumped) { //m_player.animation.DoWallJump(); m_movementRestrictionTimer = m_movementRestrictionDuration; } } else { m_hasWallJumped = false; } } public void UpdateTimer(float deltaTime) { if (m_movementRestrictionTimer > 0) { m_movementRestrictionTimer -= deltaTime; } } public void DisableRestriction() { m_movementRestrictionTimer = 0; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; using Newtonsoft.Json; using PluginDevelopment.Helper; using PluginDevelopment.Helper.Dapper.NET; using PluginDevelopment.Model; namespace PluginDevelopment.DAL { public class MenuOperation { private static readonly DbBase Dbbase = new DbBase("DefaultConnectionString"); /// <summary> /// 获取树形文档列表 /// </summary> /// <returns></returns> public static string GetMenuDocument() { var sqlStr = "select a.id,a.name,a.parentid,a.url,a.icon from menu a group by a.sort"; IList<Menu> menuList; using (var conDbconnection = Dbbase.DbConnecttion) { menuList = conDbconnection.Query<Menu>(sqlStr).ToList(); } //获取集合中父ID为空的记录 var parentMenus = menuList.Where(x => string.IsNullOrEmpty(x.ParentId)).ToList(); //循环遍历父ID为空的集合 foreach (var menu in parentMenus) { //递归获取父ID为空的子节点 FeatchMenuChildren(menuList, menu); } return JsonConvert.SerializeObject(parentMenus); } /// <summary> /// 获取子节点 /// </summary> /// <param name="menus">查询得到的菜单集合</param> /// <param name="menu">父节点为空的集合</param> public static void FeatchMenuChildren(IList<Menu> menus, Menu menu) { menu.Children = new Collection<Menu>(menus.Where(x => x.ParentId.Equals(menu.Id)).ToList()); if (!menu.Children.Any()) return; foreach (var childMenu in menu.Children) { FeatchMenuChildren(menus, childMenu); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Graph : MonoBehaviour { [SerializeField] private Sprite circleSprite; List<int> valueList = new List<int>(); private RectTransform graphContainer; public float time; public float timeToPlaceNewPoint; private bool showGraph = false; public string nameToTrack; public void ToggleGraph() { if (showGraph == false) { showGraph = true; } else { showGraph = false; } } private void Awake() { graphContainer = transform.Find("graphContainer").GetComponent<RectTransform>(); ShowGraph(valueList); } //private void CreateDotConnection(Vector2 dotPositionA, Vector2 dotPositionB) //{ // GameObject gameObject = new GameObject("dotConnection", typeof(Image)); // gameObject.transform.SetParent(graphContainer, false); // gameObject.GetComponent<Image>().color = new Color(1, 1, 1, 0.5f); // RectTransform rectTransform = gameObject.GetComponent<RectTransform>(); // Vector2 dir = (dotPositionB - dotPositionA).normalized; // float distance = Vector2.Distance(dotPositionA, dotPositionB); // rectTransform.anchorMin = new Vector2(0, 0); // rectTransform.anchorMax = new Vector2(0, 0); // rectTransform.sizeDelta = new Vector2(distance, 3f); // rectTransform.anchoredPosition = dotPositionA + dir * distance * 0.5f; // rectTransform.localEulerAngles = new Vector3(0, 0, UtilsClass.GetAngleFromVectorFloat(dir)); //} private void CreateCircle(Vector2 anchoredPosition) { GameObject gameObject = new GameObject("circle", typeof(Image)); gameObject.transform.SetParent(graphContainer, false); gameObject.GetComponent<Image>().sprite = circleSprite; RectTransform rectTransform = gameObject.GetComponent<RectTransform>(); rectTransform.anchoredPosition = anchoredPosition; rectTransform.sizeDelta = new Vector2(11, 11); rectTransform.anchorMin = new Vector2(0, 0); rectTransform.anchorMax = new Vector2(0, 0); } private void ShowGraph(List<int> valueList) { float graphHeight = graphContainer.sizeDelta.y; float graphWidth = graphContainer.sizeDelta.x; float yMaximum = 100f; float xMaximum = 10f; float xSize = 800f; for (int i = 0; i < valueList.Count; i++) { foreach (var gameObj in FindObjectsOfType(typeof(GameObject)) as GameObject[]) { if (gameObj.name == "circle") { Destroy(gameObj); } } } for (int i = 0; i < valueList.Count; i++) { float xPosition = i * xSize / valueList.Count - 1; float yPosition = (valueList[i] / yMaximum) * graphHeight; CreateCircle(new Vector2(xPosition, yPosition)); } } void Update() { time += Time.deltaTime; if(time > timeToPlaceNewPoint) { int currentNumOfFish = 0; foreach (var gameObj in FindObjectsOfType(typeof(GameObject)) as GameObject[]) { if (gameObj.name == nameToTrack) { currentNumOfFish++; } } valueList.Add(currentNumOfFish); ShowGraph(valueList); time = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using tableModel; using colModel; using SQLToCSharpNamespace; namespace CreateMethod { public class FunctionAdd { public string CreateAddFunction(string dbName, TableModel tableModel) { string result = ""; //return result string sqlField = ""; //sqlStr part assign string sqlPara = ""; //sqlStr part where string paramaters = ""; //SqlParameter[] parameters init int count = 0; string assign = ""; //SqlParameter[] parameters assign if (tableModel != null && tableModel.models.Count > 0) { foreach (ColModel model in tableModel.models) { //if the column is identity, not need add this column if (model.isIdentity == 0) { sqlField += "[" + model.name + "],"; sqlPara += "@" + model.name.Replace(' ', '_') + ","; paramaters += @" new SqlParameter(""@" + model.name.Replace(' ', '_') + @""", SqlDbType." + SQLToCSharp.SqlTypeToSqlDBType(model.type).ToString() + @"," + model.len + @"),"; assign += @" if( model." + model.name.Replace(' ', '_') + @"==null) parameters[" + count + @"].Value = DBNull.Value; else parameters[" + count + @"].Value = model." + model.name.Replace(' ', '_') + @";"; count++; } } sqlField = sqlField.Substring(0, sqlField.Length - 1); sqlPara = sqlPara.Substring(0, sqlPara.Length - 1); paramaters = paramaters.Substring(0, paramaters.Length - 1); if (tableModel != null) { result = @" public bool Add(" + dbName + @"Model." + tableModel.className + @" model) { StringBuilder sqlStr = new StringBuilder(); sqlStr.Append(""insert into " + tableModel.tableName + @"(""); sqlStr.Append(""" + sqlField + @")""); sqlStr.Append("" values(""); sqlStr.Append(""" + sqlPara + @")""); SqlParameter[] parameters = {" + paramaters + @" }; " + assign + @" int result = SQLHelper.ExecuteSql(sqlStr.ToString(),parameters); if(result==1){ return true; } else{ return false; } }"; } } return result; } } }
using System; namespace Divar.Core.Commands.Advertisements.Commands { public class CreateCommand { public Guid Id { get; set; } public Guid OwnerId { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Playables; using RVP; public class _cutsceneManager : MonoBehaviour { // Start is called before the first frame update [SerializeField] Animator[] cars; [SerializeField] GameObject carsounds; [SerializeField] Animator blackBars; [SerializeField] GameObject nextCutscene; private int whichTake = 0; void Start() { Invoke("StartCutscene", 1f); } void StartCutscene() { this.GetComponent<PlayableDirector>().Play(); } public void PlayTake() { if(whichTake == 0) { cars[0].Play("cutscene1"); } else if(whichTake == 1) { cars[0].Play("cutscene2"); cars[1].Play("cutscene2"); } else if(whichTake == 2) { cars[0].Play("cutscene3"); cars[1].Play("cutscene3"); cars[2].Play("cutscene3"); } else if(whichTake == 3) { cars[0].Play("cutscene4"); cars[1].Play("cutscene4"); cars[2].Play("cutscene4"); } else if(whichTake == 4) { cars[2].gameObject.SetActive(false); cars[0].enabled = false; cars[0].transform.position = new Vector3(139.4808f, 4.53f, 1420.09f); cars[0].transform.eulerAngles = Vector3.zero; cars[0].GetComponent<Rigidbody>().isKinematic = false; cars[0].GetComponent<speedometer>().enabled = true; cars[0].gameObject.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * 2000); cars[1].enabled = false; cars[1].transform.position = new Vector3(139.4808f, 4.53f, 1350.286f); cars[1].transform.eulerAngles = Vector3.zero; cars[1].gameObject.GetComponent<RVP.FollowAI>().enabled = true; cars[1].gameObject.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * 2000); blackBars.Play("HideIt"); carsounds.SetActive(false); } whichTake++; } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Report_ClassLibrary; using System.Collections; using System.IO; using ClosedXML.Excel; using System.Text; using DocumentFormat.OpenXml.Spreadsheet; public partial class ChequeStatus : System.Web.UI.Page { Dictionary<string, bool> UserList = new Dictionary<string, bool>(); static List<VanDetails> vanList = new List<VanDetails>(); static List<SaleArea> salArea = new List<SaleArea>(); List<User> LoginUser = new List<User>(); ReportDocument rdoc = new ReportDocument(); bool validateFilter = false; string connStrng = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; DataTable _dt = new DataTable(); protected void Page_Load(object sender, EventArgs e) { if (Session["AllCashReportLogin"] != null) { UserList = (Dictionary<string, bool>)Session["AllCashReportLogin"]; if (UserList.First().Value.ToString() == "0") { Response.Redirect("~/index.aspx"); } } if (Session["AllCashReportLogin"] == null) { Response.Redirect("~/index.aspx"); } if (!IsPostBack) { InitPage(); } var requestTarget = this.Request["__EVENTTARGET"]; var requestArgs = this.Request["__EVENTARGUMENT"]; if (requestTarget == "save") { SaveData(); } if (chkShowAll.Checked) { grdChequeStatus.AllowPaging = false; } else { grdChequeStatus.AllowPaging = true; } //if (ViewState["ChequeStatusReport"] != null) //{ // grdChequeStatus.DataSource = (DataTable)ViewState["ChequeStatusReport"]; // grdChequeStatus.DataBind(); //} } private void InitPage() { Dictionary<string, string> companyList = new Dictionary<string, string>(); try { using (SqlConnection cn = new SqlConnection(connStrng)) { cn.Open(); SqlCommand cmd = new SqlCommand("proc_ChequeStatusReport_GetCompany", cn); cmd.CommandType = System.Data.CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); companyList.Add("-1", "---All---"); while (reader.Read()) { companyList.Add(reader["RowNum"].ToString(), reader["Company"].ToString()); } cn.Close(); } ddlCompany.Items.Clear(); ddlCompany.DataSource = companyList; ddlCompany.DataTextField = "Value"; ddlCompany.DataValueField = "Key"; ddlCompany.DataBind(); Dictionary<string, string> statusList = new Dictionary<string, string>(); statusList.Add("All", "---All---"); statusList.Add("Y", "---Received---"); statusList.Add("N", "---Not Receive---"); ddlStatus.Items.Clear(); ddlStatus.DataSource = statusList; ddlStatus.DataTextField = "Value"; ddlStatus.DataValueField = "Key"; ddlStatus.DataBind(); Dictionary<string, string> statementList = new Dictionary<string, string>(); statementList.Add("All", "---All---"); statementList.Add("Y", "มีข้อมูล Statement"); statementList.Add("N", "ไม่มีข้อมูล Statement"); ddlStatement.Items.Clear(); ddlStatement.DataSource = statementList; ddlStatement.DataTextField = "Value"; ddlStatement.DataValueField = "Key"; ddlStatement.DataBind(); } catch (Exception ex) { Helper.WriteLog(ex.Message); throw; } } private void BindGridView() { try { if (chkShowAll.Checked) { grdChequeStatus.AllowPaging = false; } else { grdChequeStatus.AllowPaging = true; } DataTable _dt = GetDataFromDB(); grdChequeStatus.DataSource = _dt; grdChequeStatus.DataBind(); ViewState["ChequeStatusReport"] = _dt; } catch (Exception ex) { Helper.WriteLog(ex.Message); throw ex; } } protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e) { } private string GridViewSortDirection { get { return ViewState["SortDirection"] as string ?? "ASC"; } set { ViewState["SortDirection"] = value; } } private string GridViewSortExpression { get { return ViewState["SortExpression"] as string ?? string.Empty; } set { ViewState["SortExpression"] = value; } } private string GetSortDirection() { switch (GridViewSortDirection) { case "ASC": GridViewSortDirection = "DESC"; break; case "DESC": GridViewSortDirection = "ASC"; break; } return GridViewSortDirection; } protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging) { if (dataTable != null) { DataView dataView = new DataView(dataTable); if (GridViewSortExpression != string.Empty) { if (isPageIndexChanging) { dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection); } else { dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GetSortDirection()); } } return dataView; } else { return new DataView(); } } public DataTable ReturnDataTable(string lvCommand, String lvConnectionString) { // This will return a System.Data.SQLClient.DataTable based on the command received // Will return null if an error occurs string dateFrom = ""; string cardCode = ""; string dateTo = ""; string statmentDateFrom = ""; string statmentDateTo = ""; string receiveDateFrom = ""; string receiveDateTo = ""; string chequeNoFrom = ""; decimal checksum = 0; string checkdateFrom = ""; string checkdateTo = ""; string chequeNoTo = ""; string docNoFrom = ""; string docNoTo = ""; List<string> _dateFrom = new List<string>(); List<string> _dateTo = new List<string>(); List<string> _statmentDateFrom = new List<string>(); List<string> _statmentDateTo = new List<string>(); List<string> _receiveDateFrom = new List<string>(); List<string> _receiveDateTo = new List<string>(); List<string> _checkdateFrom = new List<string>(); List<string> _checkdateTo = new List<string>(); string company = ddlCompany.SelectedItem.Text == "---All---" ? "" : ddlCompany.SelectedItem.Text; string status = ddlStatus.SelectedValue == "All" ? "" : ddlStatus.SelectedValue; _dateFrom = txtStartDate.Text.Split('/').ToList(); dateFrom = string.Join("/", _dateFrom[1], _dateFrom[0], _dateFrom[2]); _dateTo = txtEndDate.Text.Split('/').ToList(); dateTo = string.Join("/", _dateTo[1], _dateTo[0], _dateTo[2]); if (txtSStatmentDate.Text != "") { _statmentDateFrom = txtSStatmentDate.Text.Split('/').ToList(); statmentDateFrom = string.Join("/", _statmentDateFrom[1], _statmentDateFrom[0], _statmentDateFrom[2]); } else { _statmentDateFrom = DateTime.Now.AddYears(-10).ToString("dd/MM/yyyy").Split('/').ToList(); statmentDateFrom = string.Join("/", _statmentDateFrom[1], _statmentDateFrom[0], _statmentDateFrom[2]); } if (txtEStatmentDate.Text != "") { _statmentDateTo = txtEStatmentDate.Text.Split('/').ToList(); statmentDateTo = string.Join("/", _statmentDateTo[1], _statmentDateTo[0], _statmentDateTo[2]); } else { _statmentDateTo = DateTime.Now.AddYears(1).ToString("dd/MM/yyyy").Split('/').ToList(); statmentDateTo = string.Join("/", _statmentDateTo[1], _statmentDateTo[0], _statmentDateTo[2]); } if (txtSReceiveDate.Text != "") { _receiveDateFrom = txtSReceiveDate.Text.Split('/').ToList(); receiveDateFrom = string.Join("/", _receiveDateFrom[1], _receiveDateFrom[0], _receiveDateFrom[2]); } if (txtEReceiveDate.Text != "") { _receiveDateTo = txtEReceiveDate.Text.Split('/').ToList(); receiveDateTo = string.Join("/", _receiveDateTo[1], _receiveDateTo[0], _receiveDateTo[2]); } if (txtCheckDateFrom.Text != "") { _checkdateFrom = txtCheckDateFrom.Text.Split('/').ToList(); checkdateFrom = string.Join("/", _checkdateFrom[1], _checkdateFrom[0], _checkdateFrom[2]); } else { _checkdateFrom = DateTime.Now.AddYears(-10).ToString("dd/MM/yyyy").Split('/').ToList(); checkdateFrom = string.Join("/", _checkdateFrom[1], _checkdateFrom[0], _checkdateFrom[2]); } if (txtCheckDateTo.Text != "") { _checkdateTo = txtCheckDateTo.Text.Split('/').ToList(); checkdateTo = string.Join("/", _checkdateTo[1], _checkdateTo[0], _checkdateTo[2]); } else { _checkdateTo = DateTime.Now.AddYears(1).ToString("dd/MM/yyyy").Split('/').ToList(); checkdateTo = string.Join("/", _checkdateTo[1], _checkdateTo[0], _checkdateTo[2]); } if (txtDocNo.Text != "") { docNoFrom = txtDocNo.Text; } if (txtDocNoTo.Text != "") { docNoTo = txtDocNoTo.Text; } if (txtCheque.Text != "") { chequeNoFrom = txtCheque.Text; } if (txtChequeTo.Text != "") { chequeNoTo = txtChequeTo.Text; } if (txtSearchCheckSum.Text != "") { checksum = Convert.ToDecimal(txtSearchCheckSum.Text); } if (txtCardCode.Text != "") { cardCode = txtCardCode.Text; } DataTable dtReturn = new DataTable("dtTemp"); using (SqlConnection cn = new SqlConnection(lvConnectionString)) { cn.Open(); using (SqlCommand cmd = new SqlCommand("proc_ChequeStatusReport_GetData", cn)) { // if (excelFlag) //{ // cmd = new SqlCommand("proc_ChequeStatusReport_GenExcel", cn); //} //else //{ // cmd = new SqlCommand("proc_ChequeStatusReport_GetData", cn); //} cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@Company", company)); cmd.Parameters.Add(new SqlParameter("@Startdate", dateFrom)); cmd.Parameters.Add(new SqlParameter("@EndDate", dateTo)); cmd.Parameters.Add(new SqlParameter("@Status", status)); cmd.Parameters.Add(new SqlParameter("@StmStartdate", statmentDateFrom)); cmd.Parameters.Add(new SqlParameter("@StmEndDate", statmentDateTo)); cmd.Parameters.Add(new SqlParameter("@RStartdate", receiveDateFrom)); cmd.Parameters.Add(new SqlParameter("@REndDate", receiveDateTo)); cmd.Parameters.Add(new SqlParameter("@docNoF", docNoFrom)); cmd.Parameters.Add(new SqlParameter("@docNoT", docNoTo)); cmd.Parameters.Add(new SqlParameter("@chequeNoF", chequeNoFrom)); cmd.Parameters.Add(new SqlParameter("@chequeNoT", chequeNoTo)); cmd.Parameters.Add(new SqlParameter("@checksum", checksum.ToString())); cmd.Parameters.Add(new SqlParameter("@CheckDateFrom", checkdateFrom)); cmd.Parameters.Add(new SqlParameter("@CheckDateTo", checkdateTo)); cmd.Parameters.Add(new SqlParameter("@CardCode", cardCode)); cmd.CommandTimeout = 0; try { //DataSet dsTemp = ReturnDataSet(cmd); //dtReturn = dsTemp.Tables[0]; SqlDataReader reader = cmd.ExecuteReader(); dtReturn.Load(reader); cn.Close(); //DataTable _dt = new DataTable("SdtTemp"); //_dt = dtReturn.Clone(); //_dt.Clear(); //DataRow[] filteredRows = null; //if (!string.IsNullOrEmpty(chequeNoFrom) && !string.IsNullOrEmpty(chequeNoTo)) //{ // filteredRows = dtReturn.Select(string.Format("{0} >= '{1}' AND {0} <= '{2}'", "ChequeNoSAP", chequeNoFrom, chequeNoTo)); // if (filteredRows != null) // { // AddDataTableRow(_dt, ref filteredRows); // } //} //else if (!string.IsNullOrEmpty(chequeNoFrom)) //{ // filteredRows = dtReturn.Select(string.Format("{0} LIKE '{1}%'", "ChequeNoSAP", chequeNoFrom)); // if (filteredRows != null) // { // AddDataTableRow(_dt, ref filteredRows); // } //} //else if (!string.IsNullOrEmpty(chequeNoTo)) //{ // filteredRows = dtReturn.Select(string.Format("{0} LIKE '{1}%'", "ChequeNoSAP", chequeNoTo)); // if (filteredRows != null) // { // AddDataTableRow(_dt, ref filteredRows); // } //} //if (_dt != null && _dt.Rows.Count > 0) //{ // dtReturn = _dt; //} //dtReturn = ReturnDataTable(cmd); } catch (Exception ex) { cn.Close(); dtReturn = null; throw ex; } } } return dtReturn; } public void AddDataTableRow(DataTable _dt, ref DataRow[] filteredRows) { foreach (var row in filteredRows) { List<object> data = new List<object>(); for (int i = 0; i < row.ItemArray.Count(); i++) { data.Add(row[i]); } _dt.Rows.Add(data.ToArray()); } } public DataSet ReturnDataSet(SqlCommand lvSQLCommand) { DataSet dsTemp = new DataSet("dsTemp"); SqlDataAdapter daTemp = new SqlDataAdapter(lvSQLCommand); try { daTemp.Fill(dsTemp); } catch (Exception ex) { throw ex; } return dsTemp; } public DataTable ReturnDataTable(SqlCommand lvSQLCommand) { DataTable dataTable = new DataTable("dtTemp"); try { SqlDataReader reader = lvSQLCommand.ExecuteReader(); dataTable.Load(reader); } catch (Exception ex) { throw ex; } return dataTable; } private DataTable GetDataFromDB(bool excelFlag = false) { DataTable _dt = new DataTable(); try { if (chkShowAll.Checked) { grdChequeStatus.AllowPaging = false; } else { grdChequeStatus.AllowPaging = true; } _dt = ReturnDataTable("", connStrng); DataView dv = new DataView(_dt); string _sqlWhere = ""; string statmentStatus = ddlStatement.SelectedValue; if (statmentStatus == "Y") { _sqlWhere = excelFlag ? "Statement IS NOT NULL" : "StatementDate IS NOT NULL"; dv.RowFilter = _sqlWhere; } else if (statmentStatus == "N") { _sqlWhere = excelFlag ? "Statement IS NULL" : "StatementDate IS NULL"; dv.RowFilter = _sqlWhere; } DataTable _newDataTable = new DataTable(); _newDataTable = dv.ToTable(); //ViewState["ChequeDataForExcel"] = _newDataTable; return _newDataTable; } catch (Exception ex) { Helper.WriteLog(ex.Message); throw ex; } } protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e) { } protected void btnReport_Click(object sender, EventArgs e) { InitialSAPData(); BindGridView(); if (grdChequeStatus.DataSource != null && grdChequeStatus.Rows.Count > 0) { //linkSave.Visible = true; linkExportReport.Visible = true; } } private void InitialSAPData() { try { using (SqlConnection cn = new SqlConnection(connStrng)) { cn.Open(); SqlCommand cmd = null; cmd = new SqlCommand("proc_ChequeStatusReport_InitailData", cn); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandTimeout = 0; cmd.ExecuteNonQuery(); cn.Close(); } } catch (Exception ex) { Helper.WriteLog(ex.Message); throw ex; } } protected void grdChequeStatus_RowCommand(object sender, GridViewCommandEventArgs e) { } protected void grdChequeStatus_Sorting(object sender, GridViewSortEventArgs e) { GridViewSortExpression = e.SortExpression; int pageIndex = grdChequeStatus.PageIndex; grdChequeStatus.DataSource = SortDataTable((DataTable)ViewState["ChequeStatusReport"], false); grdChequeStatus.DataBind(); for (int i = 1; i < grdChequeStatus.Columns.Count - 1; i++) { string ht = ((LinkButton)grdChequeStatus.HeaderRow.Cells[i].Controls[0]).Text; if (ht == e.SortExpression) { TableCell tableCell = grdChequeStatus.HeaderRow.Cells[i]; Image img = new Image(); img.ImageUrl = (GridViewSortDirection == "ASC") ? "~/Images/asc.gif" : "~/Images/desc.gif"; tableCell.Controls.Add(img); } } grdChequeStatus.PageIndex = pageIndex; } protected void grdChequeStatus_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { int colIndex = 1; foreach (TableCell tc in e.Row.Cells) { if (tc.HasControls() && colIndex > 1) { // search for the header link LinkButton lnk = (LinkButton)tc.Controls[0]; string sortDir = ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; string sortBy = ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : "---"; if (lnk != null && sortBy == lnk.CommandArgument) { string sortArrow = sortDir == "ASC" ? " &#9650;" : " &#9660;"; lnk.Text += sortArrow; } } colIndex++; } } } protected void grdChequeStatus_PageIndexChanging(object sender, GridViewPageEventArgs e) { grdChequeStatus.PageIndex = e.NewPageIndex; BindGridView(); } //protected void linkSave_Click(object sender, EventArgs e) private void SaveData() { //string confirmValue = Request.Form["confirm_value"]; //if (confirmValue == "Yes") //{ //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true); try { using (SqlConnection dataConnection = new SqlConnection(connStrng)) { using (SqlCommand dataCommand = dataConnection.CreateCommand()) { dataConnection.Open(); foreach (GridViewRow row in grdChequeStatus.Rows) { string chequeStatus = ""; CheckBox _chkChequeStatus = (row.FindControl("chkChequeStatus") as CheckBox); string u_chequestatus = (row.FindControl("lblU_chequestatus") as Label).Text; if (_chkChequeStatus != null && _chkChequeStatus is CheckBox) { chequeStatus = _chkChequeStatus.Checked == true ? "Y" : "N"; //(u_chequestatus == "Not Receive" ? "N" : ""); } string chequeNo = ""; TextBox _txtChequeNo = (row.FindControl("txtChequeNo") as TextBox); string _chequeNoSAP = (row.FindControl("lblChequeNoSAP") as Label).Text; if (_txtChequeNo != null && _txtChequeNo is TextBox) { chequeNo = _txtChequeNo.Text; //_chequeNoSAP == _txtChequeNo.Text ? "" : _txtChequeNo.Text; } List<string> _statementDate = new List<string>(); List<string> _receiveDate = new List<string>(); string receiveDate = ""; TextBox _txtReceiveDate = (row.FindControl("txtReceiveDate") as TextBox); if (_txtReceiveDate != null && _txtReceiveDate is TextBox) { if (_txtReceiveDate.Text != "") { _receiveDate = _txtReceiveDate.Text.Split('/').ToList(); receiveDate = string.Join("", _receiveDate[2], _receiveDate[1], _receiveDate[0]); } } string statementDate = ""; TextBox _txtStatementDate = (row.FindControl("txtStatementDate") as TextBox); if (_txtStatementDate != null && _txtStatementDate is TextBox) { if (_txtStatementDate.Text != "") { _statementDate = _txtStatementDate.Text.Split('/').ToList(); statementDate = string.Join("", _statementDate[2], _statementDate[1], _statementDate[0]); } } string docNo = (row.FindControl("lblDocNo") as Label).Text; string company = (row.FindControl("lblCompany") as Label).Text; string query = ""; query += "IF NOT EXISTS(SELECT 1 FROM [dbo].[tbl_JEEntry] WHERE [DocNo] = '" + docNo + "' AND Company = '" + company + "') "; query += "BEGIN "; query += " INSERT INTO [dbo].[tbl_JEEntry] "; query += " ([DocNo] "; query += " ,[Status] "; query += " ,[ChequeNo] "; query += " ,[StatusDate] "; query += " ,[ChequeModifyDate] "; query += " ,[Company] "; query += " ,StatementDate "; query += " ,ReceiveDate) "; query += " VALUES "; query += " ('" + docNo + "' "; query += " , IIF('" + chequeStatus + "' = '', NULL, '" + chequeStatus + "') "; query += " , '" + chequeNo + "' "; if (!string.IsNullOrEmpty(chequeStatus)) { query += " , case when EXISTS(SELECT 1 FROM [dbo].tbl_JEEntry_Temp WHERE [DocNo] = '" + docNo + "' AND Company = '" + company + "' AND ISNULL(Status, 'N') = '" + chequeStatus + "') THEN NULL ELSE GETDATE() END"; } else { if (!string.IsNullOrEmpty(statementDate) || !string.IsNullOrEmpty(receiveDate)) { query += " , GETDATE() "; } else { query += " , NULL "; } } if (!string.IsNullOrEmpty(chequeNo)) { query += " , case when EXISTS(SELECT 1 FROM [dbo].tbl_JEEntry_Temp WHERE [DocNo] = '" + docNo + "' AND Company = '" + company + "' AND ChequeNo = '" + chequeNo + "') THEN NULL ELSE GETDATE() END"; } else { query += " , NULL "; } query += " , '" + company + "' "; if (string.IsNullOrEmpty(statementDate)) { query += " , NULL "; } else { query += " , '" + statementDate + "' "; } if (string.IsNullOrEmpty(receiveDate)) { query += " , NULL )"; } else { query += " , '" + receiveDate + "') "; } query += "END "; query += "ELSE "; query += " BEGIN "; query += " IF EXISTS(SELECT 1 FROM [dbo].[tbl_JEEntry] WHERE [DocNo] = '" + docNo + "' AND Company = '" + company + "') "; query += " BEGIN "; query += " UPDATE [dbo].[tbl_JEEntry] "; query += " SET [ChequeNo] = IIF('" + chequeNo + "' = '', NULL, '" + chequeNo + "') "; query += " ,[ChequeModifyDate] = GETDATE() "; query += " ,[Status] = IIF('" + chequeStatus + "' = '', NULL, '" + chequeStatus + "') "; query += " ,[StatusDate] = GETDATE() "; if (string.IsNullOrEmpty(statementDate)) { query += " ,[StatementDate] = NULL"; } else { query += " ,[StatementDate] = '" + statementDate + "' "; } if (string.IsNullOrEmpty(receiveDate)) { query += " ,[ReceiveDate] = NULL"; } else { query += " ,[ReceiveDate] = '" + receiveDate + "' "; } query += " WHERE [DocNo] = '" + docNo + "' AND Company = '" + company + "' "; query += " END "; query += "END "; dataCommand.CommandType = CommandType.Text; dataCommand.CommandTimeout = 0; dataCommand.CommandText = query; dataCommand.ExecuteNonQuery(); } dataConnection.Close(); } } BindGridView(); ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "showValidateMsg()", true); } catch (SqlException sqlEx) { Helper.WriteLog(sqlEx.Message); throw sqlEx; } //} } protected void linkExportReport_Click(object sender, EventArgs e) { try { using (SqlConnection cn = new SqlConnection(connStrng)) { cn.Open(); SqlCommand cmd = null; cmd = new SqlCommand("proc_ChequeStatusReport_GenExcel_R2", cn); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandTimeout = 0; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "ChequeExcel"); DataTable _dt = ds.Tables["ChequeExcel"]; using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(_dt, "ChequeExcel"); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=ChequeStatusReport.xlsx"); using (MemoryStream MyMemoryStream = new MemoryStream()) { wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.Close(); //Response.End(); } } cn.Close(); } } catch (Exception ex) { Helper.WriteLog(ex.Message); throw ex; } //try //{ // DataTable _dt = GetDataFromDB(true); // if (_dt != null && _dt.Rows.Count > 0) // { // using (XLWorkbook wb = new XLWorkbook()) // { // wb.Worksheets.Add(_dt, "ChequeExcel"); // Response.Clear(); // Response.Buffer = true; // Response.Charset = ""; // Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // Response.AddHeader("content-disposition", "attachment;filename=ChequeStatusReport.xlsx"); // using (MemoryStream MyMemoryStream = new MemoryStream()) // { // wb.SaveAs(MyMemoryStream); // MyMemoryStream.WriteTo(Response.OutputStream); // Response.Flush(); // Response.End(); // } // } // //using (XLWorkbook wb = new XLWorkbook()) // //{ // // wb.Worksheets.Add(_dt, "ChequeStatus"); // // Response.Clear(); // // Response.Buffer = true; // // Response.Charset = ""; // // Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // // Response.AddHeader("content-disposition", "attachment;filename=ChequeStatusReport.xlsx"); // // using (MemoryStream MyMemoryStream = new MemoryStream()) // // { // // wb.SaveAs(MyMemoryStream); // // MyMemoryStream.WriteTo(Response.OutputStream); // // Response.Flush(); // // Response.Close(); // // } // //} // } //} //catch (Exception ex) //{ // throw ex; //} } protected void grdChequeStatus_RowDataBound(object sender, GridViewRowEventArgs e) { try { //e.Row.Attributes.Add("style", "cursor:help;"); if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Alternate) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.BackColor = System.Drawing.Color.FromName("#C2D69B"); } } else { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.BackColor = System.Drawing.Color.FromName("white"); } } if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)"); e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)"); CheckBox chk = (CheckBox)e.Row.FindControl("chkChequeStatus"); HiddenField lblSatatus = (HiddenField)e.Row.FindControl("hfChequeStatus"); if (lblSatatus.Value.ToString() == "Y") { chk.Checked = true; e.Row.BackColor = System.Drawing.Color.FromName("aqua"); } else { chk.Checked = false; } } } catch (Exception ex) { throw ex; } } }
using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace HealthVault.Sample.Xamarin.Core.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MedicationEditPage : ContentPage { public MedicationEditPage() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace Challan.Models { public class ChallanPrinciple { public ChallanPrinciple() { AcceptorDetailses = new List<AcceptorDetails>(); ApplicantDetailses = new List<ApplicantDetails>(); HolderDetailses = new List<HolderDetails>(); Currencies = new List<Currency>(); Districts = new List<District>(); } //[DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public string ReasonForDeposit { get; set; } public DateTime ChallanDate { get; set; } //navigation public List<AcceptorDetails> AcceptorDetailses { get; set; } public List<ApplicantDetails> ApplicantDetailses { get; set; } public List<HolderDetails> HolderDetailses { get; set; } public List<Currency> Currencies { get; set; } public List<District> Districts { get; set; } } }
using System; namespace Multiple_Subtraction_Quiz { class Program { static void Main(string[] args) { string [] answers = new string[5]; Random rand = new Random(); int timeStart = DateTime.Now.Second; Console.WriteLine("You are presented with five math problems"); int correctAnswer = 0; for (int i = 0; i < answers.Length; i++) { int a = rand.Next(0, 10); int b = rand.Next(0, 10); int temp = 0; if (a<b) { temp = a; a = b; b = temp; } int answer = a - b; Console.Write("{0} - {1} = ", a, b); int c = int.Parse(Console.ReadLine()); if (c == answer) { answers[i] = a + " - " + b + " = " + c + " - Correct!"; Console.WriteLine("Correct!"); correctAnswer++; } else { Console.Write("Wrong, answer should be {0} - {1} = {2}", a, b, answer); answers[i] = a + " - " + b + " = " + c + " - Wrong!"; Console.WriteLine(); } } int timeStop = (int)(DateTime.Now.Second) - timeStart; Console.WriteLine("Test time is {0} seconds",timeStop); Console.WriteLine("Correct count is " + correctAnswer); for (int i = 0; i < answers.Length; i++) { Console.WriteLine(answers[i]); } } } }
using UnityEngine; [RequireComponent(typeof(Animator))] public class GameUi : MonoBehaviour { private static int blackScreenAnimParam { get; } = Animator.StringToHash("BlackScreen"); private static int notifyAbilityAnimParam { get; } = Animator.StringToHash("NotifyAbility"); [SerializeField] protected UnlockedNotificationUi _notificationUi; [SerializeField] protected Animator _animator; [SerializeField] protected CharacterBrain _character; private void Reset() { if (!_animator) _animator = GetComponent<Animator>(); } private void Awake() { _character.onAbilityUnlocked.AddListener(NotifyNewAbility); } private void NotifyNewAbility(KeyCode keyCode) { _notificationUi.ShowText(keyCode); _animator.SetTrigger(notifyAbilityAnimParam); } public void EndLevel() => _animator.SetBool(blackScreenAnimParam, true); public void StartLevel() => _animator.SetBool(blackScreenAnimParam, false); }
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; namespace School3D { public partial class 帮助 : Form { public 帮助() { InitializeComponent(); } private void toolStripMenuItem1_Click(object sender, EventArgs e) { } private void toolStripComboBox1_Click(object sender, EventArgs e) { } private void 帮助_Load(object sender, EventArgs e) { } private void 标签功能ToolStripMenuItem_Click(object sender, EventArgs e) { StringBuilder str = new StringBuilder(); richTextBox1.Text = ""; str.AppendLine("欢迎来到数字校园地图管理程序:书签功能介绍!"); str.AppendLine("书签管理模块包含为当前视图添加书签,缩放至书签,删除某一书签和清空所有书签功能"); str.AppendLine("操作说明:书签功能在本程序中作用为定位你想要保存的位置,点击书签即可立刻转到你建立标签时候的3d地图的位置"); richTextBox1.Text += str; } private void 基础功能介绍ToolStripMenuItem_Click(object sender, EventArgs e) { StringBuilder str = new StringBuilder(); richTextBox1.Text = ""; str.AppendLine("欢迎来到数字校园地图管理程序:基础功能介绍!"); str.AppendLine("基础功能包括:1 打开地图 2 导航 3 漫游 4 缩放 5 放大至图层 6 测量模式 7 信息概览 "); str.AppendLine("操作说明:打开地图即为打开3D图像.导航,缩放和漫游即为对导入的3D地图进行全方位无死角查看.放大至图层即为立刻跳转到你所选图层.测量模式即为得到你在地图上所选两点之间的距离.信息概览模式中可查看点击任意一点的属性"); richTextBox1.Text+=str; } private void 鹰眼模式ToolStripMenuItem_Click(object sender, EventArgs e) { StringBuilder str = new StringBuilder(); richTextBox1.Text = ""; str.AppendLine("欢迎来到数字校园地图管理程序:鹰眼模式介绍"); str.AppendLine("鹰眼模式是二维地图中显示三维地图的对应位置,当三维地图显示区域变化时,二维地图上显示的位置也会相应变化。也可以在二维地图画矩形来控制三维地图的显示区域"); richTextBox1.Text += str; } private void 查询共功能ToolStripMenuItem_Click(object sender, EventArgs e) { StringBuilder str = new StringBuilder(); richTextBox1.Text = ""; str.AppendLine("欢迎来到数字校园地图管理程序:查询模式介绍"); str.AppendLine("查询模块功能包括输入内容查询建筑物、得到查询结果、放大至查询结果等"); str.AppendLine("操作说明:本程序的查询功能主要是查询3d图片中的模型的name属性,得到结果和位置,用户可以直接查询想要得到的地物的name属性,点击“放大查询结果”即可得到具体位置"); richTextBox1.Text += str; } private void 关于ToolStripMenuItem_Click(object sender, EventArgs e) { StringBuilder str = new StringBuilder(); richTextBox1.Text = ""; str.AppendLine("copyright: shuyuan ou 、 yangfan 、 chengkun gan , 三只小咸鱼"); str.AppendLine("程序成型时间较短,还有诸多不足之处,望谅解,以后会慢慢完善!"); richTextBox1.Text += str; } } }
using System; namespace Problem_Circle_Area { class Program { static void Main(string[] args) { const double PI = 3.14159265358979; double r = double.Parse(Console.ReadLine()); double area = PI * r * r; double peremiter = 2 * r * PI; Console.WriteLine($"Area is {area}"); Console.WriteLine($"Perimeter is {peremiter}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task2_Optimized_Banking_System { public class task2_Optimized_Banking_System { public static void Main() { var bankAccounts = new List<BankAccount>(); var input = Console.ReadLine(); while (input != "end") { var line = input.Split(new char[] { '|', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); var newAccount = new BankAccount() { Name = line[1], Bank = line[0], Balance = decimal.Parse(line[2]) }; bankAccounts.Add(newAccount); input = Console.ReadLine(); } var ordered = bankAccounts .OrderByDescending(x => x.Balance) .ThenBy(y => y.Bank).ToList(); foreach (var item in ordered) { Console.WriteLine($"{item.Name} -> {item.Balance} ({item.Bank})"); } } public class BankAccount { public string Name { get; set; } public string Bank { get; set; } public decimal Balance { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace Integer.Web.ViewModels { public class ItemViewModel { public string Id { get; set; } public string Nome { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Thingy.GraphicsPlus { public class EllipseElement : BaseElement { public override void Draw(Graphics graphics) { graphics.FillEllipse(StandardSolidBrush, StandardRectangleF); } } public class CircleElementStrategy : ElementStrategyBase<EllipseElement> { } public class EllipseElementStrategy : ElementStrategyBase<EllipseElement> { } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using WebApplication4.Controllers; using WebApplication4.Models; using System.Linq; using System.Web.Mvc; using System.Collections.Generic; namespace WebApplication4.Tests.Controllers { [TestClass] public class BubleTsControllerTest { [TestMethod] public void TestIndex() { var db = new bubleteaEntities(); var controller = new BubleTsController(); var result = controller.Index(); var view = result as ViewResult; Assert.IsNotNull(view); var model = view.Model as List<BubleT>; Assert.IsNotNull(model); Assert.AreEqual(db.BubleTs.Count(), model.Count); } [TestMethod] public void TestEditG() { var controller = new BubleTsController(); var result0 = controller.Edit(0); Assert.IsInstanceOfType(result0, typeof(HttpNotFoundResult)); var db = new bubleteaEntities(); var item = db.BubleTs.First(); var result1 = controller.Edit(item.ID) as ViewResult; Assert.IsNotNull(result1); var model = result1.Model as BubleT; Assert.AreEqual(item.ID, model.ID); } [TestMethod] public void testCreateP() { var db = new bubleteaEntities(); var model = new BubleT { Name = "tra sua vl", Price = 25000, Topping = "Trang chau trang" }; var controller = new BubleTsController(); var result = controller.Create(model); var redirect = result as RedirectToRouteResult; Assert.IsNotNull(redirect); Assert.AreEqual("Index", redirect.RouteValues["action"]); var item = db.BubleTs.Find(model.ID); Assert.IsNotNull(item); Assert.AreEqual(model.Name, item.Name); Assert.AreEqual(model.Price, item.Price); Assert.AreEqual(model.Topping, item.Topping); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityEditor; public class AnimalsGameManager : MonoBehaviour { [SerializeField] private GameObject objectframeprefab; [SerializeField] private Transform framespanel; [SerializeField] private Text QuestionText; [SerializeField] private Transform questionpanel; private GameObject[] objectstrings; [SerializeField] private Sprite[] lettersprite = new Sprite[25]; [SerializeField] private Transform soundbutton; [SerializeField] private GameObject gameoverpanel; [SerializeField] private Text gameoverpointtext; [SerializeField] private Text gamepointtext; [SerializeField] private Sprite[] gameoverbackrounds = new Sprite[4]; [SerializeField] private GameObject[] boomeffect = new GameObject[5]; [SerializeField] private Text secondtext; [SerializeField] AudioSource audiosource; public AudioClip[] enletternumbersounds = new AudioClip[25]; public AudioClip[] trletternumbersounds = new AudioClip[25]; public AudioClip[] deletternumbersounds = new AudioClip[25]; public AudioClip[] frletternumbersounds = new AudioClip[25]; public AudioClip[] badresultsounds = new AudioClip[4]; public AudioClip[] middleresultsounds = new AudioClip[3]; public AudioClip[] otherresultsounds = new AudioClip[10]; public AudioClip buttonssound; public AudioClip createbaloonsound; public AudioClip timesupsound; public AudioClip trueanswersound; public AudioClip wronganswersound; public AudioClip catsound; public AudioClip dogsound; public AudioClip birdsound; public AudioClip sheepsound; public AudioClip chickensound; public AudioClip ducksound; public AudioClip cowsound; public AudioClip elephantsound; public AudioClip horsesound; int stringnumber = 3; int randomletters; string questsprite; string buttonpoint; bool buttonclick; string trueanswer; int lasthealth; int finishsituation; bool notfinished = true; int randomeffect; int lastseconds; bool seconds = true; int casenumber; int questionnumber; int levelnumber; Health health; PointManager pointManager; List<UnityEngine.Sprite> firstanswerlist = new List<UnityEngine.Sprite>(); List<UnityEngine.Sprite> answerlist = new List<UnityEngine.Sprite>(); private void Awake() { audiosource = GetComponent<AudioSource>(); objectstrings = new GameObject[stringnumber]; lasthealth = 4; gameoverpanel.GetComponent<RectTransform>().localScale = Vector2.zero; foreach (var item in boomeffect) { item.GetComponent<RectTransform>().localScale = Vector2.zero; } soundbutton.GetComponent<RectTransform>().localScale = Vector2.zero; questionpanel.GetComponent<RectTransform>().localScale = Vector2.zero; objectframeprefab.GetComponent<RectTransform>().localScale = Vector2.zero; health = Object.FindObjectOfType<Health>(); pointManager = Object.FindObjectOfType<PointManager>(); health.healthcontrol(lasthealth); } void Start() { buttonclick = false; lastseconds = 30; levelnumber = 0; secondtext.text = lastseconds.ToString(); for (int i = 0; i < 25; i++) { firstanswerlist.Add(lettersprite[i]); } createobjects(); } public void createobjects() { foreach (var item in boomeffect) { item.GetComponent<RectTransform>().localScale = Vector2.zero; } objectstrings = new GameObject[stringnumber]; for (int i = 0; i < stringnumber; i++) { GameObject frame = Instantiate(objectframeprefab, framespanel); frame.transform.GetComponent<Button>().onClick.AddListener(() => TouchedButton()); objectstrings[i] = frame; } lettersandnumberstexts(); StartCoroutine(Dofaderoutine()); Invoke("questionpanelopen", 1f); } void TouchedButton() { if (buttonclick) { buttonpoint = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.transform.GetChild(1).GetComponent<Image>().sprite.name; resultcontrol(); } } public void ButonSound() { audiosource.PlayOneShot(buttonssound); } void resultcontrol() { if (buttonpoint == trueanswer) { if (buttonpoint=="0cat") { audiosource.PlayOneShot(catsound); } else if(buttonpoint=="1dog") { audiosource.PlayOneShot(dogsound); } else if (buttonpoint=="2bird") { audiosource.PlayOneShot(birdsound); } else if (buttonpoint=="8sheep") { audiosource.PlayOneShot(sheepsound); } else if (buttonpoint=="10chicken") { audiosource.PlayOneShot(chickensound); } else if (buttonpoint=="11duck") { audiosource.PlayOneShot(ducksound); } else if (buttonpoint=="13cow") { audiosource.PlayOneShot(cowsound); } else if (buttonpoint== "21elephant") { audiosource.PlayOneShot(elephantsound); } else if (buttonpoint=="24horse") { audiosource.PlayOneShot(horsesound); } else { audiosource.PlayOneShot(trueanswersound); } pointManager.pointincreasing(); buttonclick = false; firstanswerlist.RemoveAt(questionnumber); if (firstanswerlist.Count < 6) { firstanswerlist.Clear(); for (int i = 0; i < 25; i++) { firstanswerlist.Add(lettersprite[i]); } } answerlist.Clear(); StartCoroutine(DestroyRoutine()); StopAllCoroutines(); RemoveAllFrame(); levelnumber++; if (stringnumber < 20) { if (levelnumber<4|| levelnumber==8 || levelnumber==12 || levelnumber==16 || levelnumber==20 || levelnumber==24 || levelnumber==28 || levelnumber==32 || levelnumber==36|| levelnumber==40) { stringnumber++; } } if (notfinished) { createobjects(); } } else { audiosource.PlayOneShot(wronganswersound); lasthealth--; health.healthcontrol(lasthealth); if (lasthealth == 1) { GameFinished(); } } } void GameFinished() { buttonclick = false; notfinished = false; seconds = false; QuestionText.text = " "; StopAllCoroutines(); RemoveAllFrame(); soundbutton.GetComponent<RectTransform>().localScale = Vector2.zero; questionpanel.GetComponent<RectTransform>().localScale = Vector2.zero; gameoverpointtext.text = gamepointtext.text; finishsituation = int.Parse(gameoverpointtext.text); if (finishsituation < 16) { audiosource.PlayOneShot(badresultsounds[(Random.Range(0, badresultsounds.Length))]); gameoverpanel.GetComponent<Image>().sprite = gameoverbackrounds[0]; } else if (finishsituation >= 16 && finishsituation < 31) { audiosource.PlayOneShot(middleresultsounds[(Random.Range(0, middleresultsounds.Length))]); gameoverpanel.GetComponent<Image>().sprite = gameoverbackrounds[1]; } else if (finishsituation >= 31 && finishsituation < 51) { audiosource.PlayOneShot(otherresultsounds[(Random.Range(0, otherresultsounds.Length))]); gameoverpanel.GetComponent<Image>().sprite = gameoverbackrounds[2]; } else if (finishsituation >= 51) { audiosource.PlayOneShot(otherresultsounds[(Random.Range(0, otherresultsounds.Length))]); gameoverpanel.GetComponent<Image>().sprite = gameoverbackrounds[3]; } randomeffect = Random.Range(0, boomeffect.Length); boomeffect[randomeffect].GetComponent<RectTransform>().DOScale(1, 0.5f).SetEase(Ease.OutBack); gameoverpanel.GetComponent<RectTransform>().DOScale(1, 0.5f).SetEase(Ease.OutBack); } void RemoveAllFrame() { foreach (var item in objectstrings) { item.GetComponent<DestroyObject>().destroyobjects(); } } IEnumerator Dofaderoutine() { foreach (var frame in objectstrings) { frame.GetComponent<RectTransform>().DOScale(1, 0.5f).SetEase(Ease.OutBack); audiosource.PlayOneShot(createbaloonsound); yield return new WaitForSeconds(0.2f); } } IEnumerator DestroyRoutine() { questionpanel.GetComponent<RectTransform>().DOScale(0, 0.3f).SetEase(Ease.InOutSine); soundbutton.GetComponent<RectTransform>().DOScale(0, 0.3f).SetEase(Ease.InOutSine); yield return new WaitForSeconds(0.05f); } IEnumerator TimerRoutine() { while (seconds) { yield return new WaitForSeconds(1f); if (lastseconds < 10) { secondtext.text = "0" + lastseconds.ToString(); } else { secondtext.text = lastseconds.ToString(); } lastseconds--; if (lastseconds < 0) { audiosource.PlayOneShot(timesupsound); GameFinished(); } } } void lettersandnumberstexts() { foreach (var frame in objectstrings) { randomletters = Random.Range(0, firstanswerlist.Count); answerlist.Add(firstanswerlist[randomletters]); frame.transform.GetChild(1).GetComponent<Image>().sprite = firstanswerlist[randomletters]; } } void questionpanelopen() { quest(); buttonclick = true; questionpanel.GetComponent<RectTransform>().DOScale(1, 0.3f).SetEase(Ease.OutBack); soundbutton.GetComponent<RectTransform>().DOScale(1, 0.3f).SetEase(Ease.OutBack); StartCoroutine(TimerRoutine()); } void quest() { questsprite = answerlist[Random.Range(0, answerlist.Count)].name; for (int i = 0; i < firstanswerlist.Count; i++) { if (questsprite == firstanswerlist[i].name) { questionnumber = i; } } trueanswer = questsprite; if (seconds) { FindQuestText(); } QuestionText.text = questsprite; } void FindQuestText() { switch (questsprite) { case "0cat": casenumber = 0; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Cat"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Kedi"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Katze"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "chat"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "1dog": casenumber = 1; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Dog"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Köpek"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Hund"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "chien"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "2bird": casenumber = 2; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Bird"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Kuş"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Vogel"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Oiseau"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "3bear": casenumber = 3; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Bear"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Ayı"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Bär"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Ours"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "4lion": casenumber = 4; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Lion"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Aslan"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Löwe"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Lion"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "5tortoise": casenumber = 5; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Tortoise"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Kaplumbağa"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Schildkröte"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "tortue"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "6fish": casenumber = 6; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Fish"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Balık"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Fisch"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "poisson"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "7rabbit": casenumber = 7; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Rabbit"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Tavşan"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Hase"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Lapin"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "8sheep": casenumber = 8; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "sheep"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Koyun"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Schaf"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Mouton"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "9camel": casenumber = 9; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Camel"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Deve"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Kamel"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Chameau"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "10chicken": casenumber = 10; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "chicken"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Tavuk"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Hähnchen"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Poulet"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "11duck": casenumber = 11; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Duck"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Ördek"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Ente"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Canard"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "12butterfly": casenumber = 12; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Butterfly"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Kelebek"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Schmetterling"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Papillon"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "13cow": casenumber = 13; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Cow"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "İnek"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Kuh"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Vache"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "14mouse": casenumber = 14; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Mouse"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Fare"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Maus"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Souris"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "15zebra": casenumber = 15; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Zebra"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Zebra"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Zebra"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Zèbre"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "16bee": casenumber = 16; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Bee"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Arı"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Biene"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Abeille"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "17stork": casenumber = 17; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Stork"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Leylek"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Storch"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Cigogne"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "18deer": casenumber = 18; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Deer"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Geyik"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Hirsch"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Cerf"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "19kangaroo": casenumber = 19; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Kangaroo"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Kanguru"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Känguru"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Kangourou"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "20ostrich": casenumber = 20; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Ostrich"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Devekuşu"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Strauß"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Autruche"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "21elephant": casenumber = 21; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Elephant"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Fil"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Elefant"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "l'éléphant"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "22giraffe": casenumber = 22; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Giraffe"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Zürafa"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Giraffe"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "girafe"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "23monkey": casenumber = 23; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Monkey"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "Maymun"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Affe"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Singe"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; case "24horse": casenumber = 24; switch (PlayerPrefs.GetInt("languageselect")) { case 0: questsprite = "Horse"; audiosource.PlayOneShot(enletternumbersounds[casenumber]); break; case 1: questsprite = "At"; audiosource.PlayOneShot(trletternumbersounds[casenumber]); break; case 2: questsprite = "Pferd"; audiosource.PlayOneShot(deletternumbersounds[casenumber]); break; case 3: questsprite = "Cheval"; audiosource.PlayOneShot(frletternumbersounds[casenumber]); break; } break; } } public void LearnObjectSound() { if (PlayerPrefs.GetInt("languageselect") == 0) { audiosource.PlayOneShot(enletternumbersounds[casenumber]); } else if (PlayerPrefs.GetInt("languageselect") == 1) { audiosource.PlayOneShot(trletternumbersounds[casenumber]); } else if (PlayerPrefs.GetInt("languageselect") == 2) { audiosource.PlayOneShot(deletternumbersounds[casenumber]); } else if (PlayerPrefs.GetInt("languageselect") == 3) { audiosource.PlayOneShot(frletternumbersounds[casenumber]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Extensions; using Småstad.Models; using System.IO; using Microsoft.AspNetCore.Authorization; namespace Småstad.Models { public class EFSmastadRepo : ISmastadRepo { private ApplicationDbContext context; private IHttpContextAccessor contextAcc; public EFSmastadRepo (ApplicationDbContext ctx, IHttpContextAccessor cont) { context = ctx; contextAcc = cont; } public IQueryable<Department> Department => context.Departments; public IQueryable<Employee> Employee => context.Employees; public IQueryable<Errand> Errand => context.Errands; public IQueryable<ErrandStatus> ErrandStatus => context.ErrandStatuses; public IQueryable<Picture> Picture => context.Pictures; public IQueryable<Sample> Sample => context.Samples; public IQueryable<Sequence> Sequence => context.Sequences; /// <summary> /// Saves a new errand to the database, or updates a current one, depending on if the errand /// already has an "ErrandId". /// </summary> /// <param name="errand"> Errand to be saved or updated. </param> public void SaveErrand(Errand errand) { if(errand.ErrandId == 0) { errand.RefNumber = "2018-45-" + GetCurrentRefNum(); errand.StatusId = "S_A"; context.Errands.Add(errand); UpdateSequence(); } else { Errand dbEntry = context.Errands.FirstOrDefault(s => s.ErrandId == errand.ErrandId); if(dbEntry != null) { context.Errands.Update(dbEntry = errand); } } context.SaveChanges(); } /// <summary> /// Saves a picture. /// </summary> /// <param name="pictures"></param> public void SavePic(List<Picture> pictures) { context.Pictures.Add(pictures.FirstOrDefault()); context.SaveChanges(); } /// <summary> /// Saves a sample. /// </summary> /// <param name="samples"></param> public void SaveSamp(List<Sample> samples) { context.Samples.Add(samples.FirstOrDefault()); context.SaveChanges(); } ///<summary> Matches and returns an errand on its property "ErrandId". </summary> ///<param name="id"> string of id to be matched. </param> public Task<Errand> GetErrandTask(int id) { return Task.Run(() => { var errand = context.Errands.Where(ed => ed.ErrandId == id); return errand.First(); }); } /// <summary> /// Matches and returns an errand on its property "ErrandId". /// </summary> /// <param name="id"></param> /// <returns></returns> public Errand GetErrand(int id) { var errand = context.Errands.Where(ed => ed.ErrandId == id); return errand.FirstOrDefault(); } /// <summary> /// Returns the CurrentValue of the Sequence as a string. /// </summary> /// <returns></returns> public string GetCurrentRefNum() { Sequence current = context.Sequences.FirstOrDefault(); return current.CurrentValue.ToString(); } /// <summary> /// Get all the pictures connected to an errand ID. /// </summary> /// <param name="id"> id of the current errand. </param> /// <returns> list of pictures </returns> public List<Picture> GetPictures(int id) { return context.Pictures.Where(p => p.ErrandId == id).ToList(); } /// <summary> /// Get all the samples connected to an errand ID. /// </summary> /// <param name="id"> id of the current errand. </param> /// <returns> list of samples </returns> public List<Sample> GetSamples(int id) { return context.Samples.Where(p => p.ErrandId == id).ToList(); } /// <summary> /// Gets the department Id of the current user /// </summary> /// <param name="name"> Name of the current user </param> /// <returns> DepartmentId </returns> public string getDepartment(string name) { Employee employee = context.Employees.Where(n => n.EmployeeId == name).FirstOrDefault(); return employee.DepartmentId; } /// <summary> /// Gets the current users name. /// </summary> /// <returns> Name of the user. </returns> public string getCurrentUser() { return contextAcc.HttpContext.User.Identity.Name; } /// <summary> /// Returns the rank of the current user. /// </summary> /// <param name="name"> username to refer to </param> /// <returns> Rank of user </returns> public string getUserRank(string name) { Employee user = context.Employees.Where(p => p.EmployeeId == name).FirstOrDefault(); return user.RoleTitle; } /// <summary> /// Returns a list to be used in the viewcomponent for dropdown lists. /// </summary> /// <param name="type"> type of list to be created. </param> /// <returns> list of string </returns> public Task<List<string>> getList(string type) { return Task.Run(() => { if (type == "ErrandStatus") { List<string> list = context.ErrandStatuses.Select(n => n.StatusName).ToList(); return list; } else if (type == "Investigator") { string department = getDepartment(getCurrentUser()); return context.Employees.Where(x => x.DepartmentId == department).Select(n => n.EmployeeName).ToList(); } else if (type == "Department") { List<string> list = context.Departments.Select(n => n.DepartmentName).ToList(); return list; } else { List<string> list = new List<string> { "Inget att visa." }; return list; } }); } /// <summary> /// Selects all relevant information to be displayed as errand on the coordinator start page. /// </summary> /// <returns> List of DisplayErrand </returns> public List<DisplayErrand> DisplayAllErrands() { var errandList = from err in Errand join stat in ErrandStatus on err.StatusId equals stat.StatusId join dep in Department on err.DepartmentId equals dep.DepartmentId into departmentErrand from deptE in departmentErrand.DefaultIfEmpty() join em in Employee on err.EmployeeId equals em.EmployeeId into employeErrand from emptE in employeErrand.DefaultIfEmpty() orderby err.RefNumber descending select new DisplayErrand { DateOfObservation = err.DateOfObservation, ErrandId = err.ErrandId, RefNumber = err.RefNumber, TypeOfCrime = err.TypeOfCrime, StatusName = stat.StatusName, DepartmentName = (err.DepartmentId == null ? "Ej tillsatt" : deptE.DepartmentName), EmployeeName = (err.EmployeeId == null ? "Ej tillsatt" : emptE.EmployeeName) }; return errandList.ToList(); } /// <summary> /// Displays the correct errands according to the managers department. /// </summary> /// <returns> List of DisplayErrand </returns> public List<DisplayErrand> DisplayDepartmentErrands() { string department = getDepartment(getCurrentUser()); var errandList = from err in Errand join stat in ErrandStatus on err.StatusId equals stat.StatusId join dep in Department on err.DepartmentId equals dep.DepartmentId where dep.DepartmentId == department // FIlter out departments join em in Employee on err.EmployeeId equals em.EmployeeId into employeErrand from emptE in employeErrand.DefaultIfEmpty() orderby err.RefNumber descending select new DisplayErrand { DateOfObservation = err.DateOfObservation, ErrandId = err.ErrandId, RefNumber = err.RefNumber, TypeOfCrime = err.TypeOfCrime, StatusName = stat.StatusName, DepartmentName = dep.DepartmentName, EmployeeName = (err.EmployeeId == null ? "Ej tillsatt" : emptE.EmployeeName) }; return errandList.ToList(); } /// <summary> /// Displays the correct errand according to which employee that is logged in. /// </summary> /// <returns> List of DisplayErrand </returns> public List<DisplayErrand> DisplayEmployeeErrands() { string employee = getCurrentUser(); var errandList = from err in Errand join stat in ErrandStatus on err.StatusId equals stat.StatusId join dep in Department on err.DepartmentId equals dep.DepartmentId join em in Employee on err.EmployeeId equals em.EmployeeId where em.EmployeeId == employee // filter out employees orderby err.RefNumber descending select new DisplayErrand { DateOfObservation = err.DateOfObservation, ErrandId = err.ErrandId, RefNumber = err.RefNumber, TypeOfCrime = err.TypeOfCrime, StatusName = stat.StatusName, DepartmentName = dep.DepartmentName, EmployeeName = em.EmployeeName }; return errandList.ToList(); } /// <summary> /// Updates the CurrentValue of the Sequence with +1. /// </summary> public void UpdateSequence() { Sequence current = context.Sequences.FirstOrDefault(); current.CurrentValue++; context.SaveChanges(); } /// <summary> /// Searches the table Errands for an errand with the input id, if it exists it gets deleted. /// </summary> /// <param name="id"> id to match with ErrandId. </param> /// <returns> True if correctly deleted, else false. </returns> public bool DeleteErrand(int id) { Errand dbEntry = context.Errands.FirstOrDefault(s => s.ErrandId == id); if (dbEntry != null) { context.Errands.Remove(dbEntry); context.SaveChanges(); return true; } else { return false; } } } }
namespace Fingo.Auth.Domain.CustomData.ConfigurationClasses.User { public class NumberUserConfiguration : UserConfiguration { public int Value { get; set; } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace StickFigure.Input { public class InputDeviceExtended<TS> where TS : struct { private readonly Queue<InputStateExtended<TS>> _recordedStates = new Queue<InputStateExtended<TS>>(); public Queue<InputStateExtended<TS>> RecordedStates { get { return _recordedStates; } } private readonly Stack<InputStateExtended<TS>> _statesForReuse = new Stack<InputStateExtended<TS>>(); protected void EnqueueNewState(GameTime time, TS state) { if (!state.Equals(_currentState)) { _currentState = state; _recordedStates.Enqueue(CreateState(time, state)); } } private TS _currentState; public TS CurrentState { get { return _currentState; } } protected void DequeueOldStates(GameTime currentTime) { InputStateExtended<TS> state = null; if (_recordedStates.Count > 0) { state = _recordedStates.Peek(); } if (state != null && state.StateTime < currentTime.TotalRealTime().Subtract(new TimeSpan(0, 0, 0, 0, InputDeviceConstants.ClickCountTimeMS))) { _statesForReuse.Push(_recordedStates.Dequeue()); DequeueOldStates(currentTime); } } private InputStateExtended<TS> CreateState(GameTime time, TS state) { if (_statesForReuse.Count > 0) { //Reuses the object to fight of the GC InputStateExtended<TS> stateExt = _statesForReuse.Pop(); stateExt.StateTime = time.TotalRealTime(); stateExt.State = state; return stateExt; } return new InputStateExtended<TS>(time, state); } /// <summary> /// Deletes all the states in the queue and adds them to the reuse stack. /// Used when a Click event or similar succeededs to stop another click event to occur immediately after. /// </summary> private void FlushAllStates() { while (_recordedStates.Count > 0) { _statesForReuse.Push(_recordedStates.Dequeue()); } } public void Reset() { FlushAllStates(); } public virtual bool NothingPressed { get { return true; } } } }
using Dapper; using MGV.Entities; using MGV.Shared; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Data; namespace MGV.Data.Repositories { public class FileRepository : IRepository<File> { #region Private Fields private IDbConnection _connectionString { get { return _transaction.Connection; } } private readonly ILogger _logger; private readonly IDbTransaction _transaction; private bool _isDisposed = false; #endregion Private Fields #region Public Constructors public FileRepository(IDbTransaction transaction, ILogger logger) { _logger = logger; _transaction = transaction; } #endregion Public Constructors #region Public Methods public void Create(File item) { var sql = "INSERT INTO Files(Name, AsBytes, FileType, Extension)" + "Values(@Name, @AsBytes, @fileType, @Extension)"; var result = _connectionString.Execute(sql, new { item.FileName, item.AsBytes, item.FileType, item.Extension }, _transaction); if (result <= 0) { _logger.LogError($"File not created: {item.FileName}, {item.Extension}, {item.FileType}"); } } public void Delete(int id) { var sql = "Delete From Files Where Files.FileId = @id"; var result = _connectionString.Execute(sql, new { id }, _transaction); if (result <= 0) { _logger.LogError($"File not removed: {id}"); } } public void Dispose() { if (!_isDisposed) { GC.SuppressFinalize(this); _isDisposed = true; } } public File Get(int id) { File result; var sql = "Select * From Files Where Files.FileId = @id"; result = _connectionString.QueryFirst<File>(sql, new { id }); if (result == null) { _logger.LogError($"File not find: {id}"); } return result; } public File Get(string name) { File result = default(File); var sql = "Select * From Files Where Files.Name = @name"; try { result = _connectionString.QueryFirst<File>(sql, new { name }); } catch (Exception e) { _logger.LogError(e, e.Message); } return result; } public IEnumerable<File> GetAll() { var sql = "Select * From Files"; IEnumerable<File> result = _connectionString.Query<File>(sql); if (result == null) { _logger.LogError($"Files not find"); } return result; } public void Update(File item) { var sql = "Update Files" + "Set Name = @Name, AsBytes = @AsBytes, FileType = @FileType, Extension = @Extention)" + "Where Id = @Id"; var result = _connectionString.Execute(sql, new { item.FileName, item.AsBytes, item.FileType, item.Extension, item.FileId }, _transaction); if (result <= 0) { _logger.LogError($"File not updated: {item.FileId}, {item.FileName}, {item.Extension}, {item.FileType}"); } } #endregion Public Methods } }
using DataModel.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CamcoManufacturing.View { /// <summary> /// Interaction logic for View_TurretHolders.xaml /// </summary> public partial class View_TurretHolders : Window { BaseDataContext db = new BaseDataContext(); int TurretTypeId = 0; int SeqaunceNumber = 0; public View_TurretHolders() { InitializeComponent(); } public View_TurretHolders(int TurretType,int sequance) { InitializeComponent(); TurretTypeId = TurretType; SeqaunceNumber = sequance; FillWrapPanel(TurretTypeId); } private void FillWrapPanel(int TurretType) { WrapPanelTurretHolders.Children.Clear(); var result = db.tTurretHolders.Where(p => p.TurretTypeId == TurretType).ToList(); foreach (var item in result) { Button button = new Button(); button.Content = item.TurretHolderName + Environment.NewLine + item.TurretHolderQRN; button.Width = 150; button.Height = 60; if (item.TurretHolderImage != null) { ImageBrush brush; BitmapImage bi; using (var ms = new MemoryStream(item.TurretHolderImage)) { brush = new ImageBrush(); bi = new BitmapImage(); bi.BeginInit(); bi.CreateOptions = BitmapCreateOptions.None; bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = ms; bi.EndInit(); } brush.ImageSource = bi; button.Background = brush; } button.Click += new RoutedEventHandler(buttonSelectedItem_Click); WrapPanelTurretHolders.Children.Add(button); } void buttonSelectedItem_Click(object sender, RoutedEventArgs e) { Button btn = (Button)sender; string abc = btn.Content.ToString(); string[] multiArray = abc.Split(new Char[] { '\r', '\n' }); string Name = multiArray[0].ToString(); var resultDetail = db.tTurretHolders.Where(p => p.TurretHolderName == Name).FirstOrDefault(); if (resultDetail != null) { foreach (Window item in Application.Current.Windows) { if (item.Name == "CreateSetUpSheet") { if (SeqaunceNumber == 3) { ((SetUpSheet)item).textBoxTurrentHolder.Text = resultDetail.TurretHolderName; ((SetUpSheet)item).textBoxQRN3.Text = resultDetail.TurretHolderQRN; } } } if (!HelperClass.IsWindowOpen(typeof(SetUpSheet))) { this.Close(); SetUpSheet obj = new SetUpSheet(); obj.ShowDialog(); } else { this.Close(); HelperClass.activateWindow(typeof(SetUpSheet)); } } } } } }
namespace WebShop.Data.Repository.Contract { public interface IUnitOfWork { ICategoryRepo Category { get; } IProductRepo Product { get; } IOrderRepo Order { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32; using MaterialDesignThemes.Wpf; namespace Projet2Cpi { /// <summary> /// Logique d'interaction pour FormulaireAddTache.xaml /// </summary> public partial class FormulaireAddTache : UserControl { public WindowFormulaires windowParent; private int cpt_files = 0; private List<String> files = new List<string>(); private Dictionary<Chip, Notif> NotificationDict = new Dictionary<Chip, Notif>(); //Define a class of activity public FormulaireAddTache() { InitializeComponent(); LoadActivities(); } private void ButtonCancel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { windowParent.Close(); } private Chip CreateAlarmChip(String title) { Chip c = new Chip() { Content = title, IsDeletable = true, Margin = new Thickness(4), }; c.DeleteClick += new RoutedEventHandler(Chip_DeleteClick); return c; } private void Chip_DeleteClick(object sender, RoutedEventArgs e) { alarmeChipsField.Children.Remove((Chip)sender); NotificationDict.Remove((Chip)sender); if (NotificationDict.Count < 3) AddAlarme.IsEnabled = true; } private void AddAlarmeEvent(object sender, MouseButtonEventArgs e) { if (DatePickeralarm.SelectedDate == null || TimePickeralarm.SelectedTime == null || ComboBoxAlarmType.SelectedIndex == -1) { MessageBox.Show("Veuillez remplir tous les champs"); return; } DateTime d = DatePickeralarm.SelectedDate.Value; DateTime t = TimePickeralarm.SelectedTime.Value; Notif n = new Notif() { time = new DateTime(d.Year, d.Month, d.Day, t.Hour, t.Minute, 0), Type = ComboBoxAlarmType.SelectedIndex == 0 ? "email" : "sms", }; Chip c = CreateAlarmChip($"{d.Year}-{d.Month}-{d.Date}-{t.Hour}:{t.Minute}"); bool b = false; foreach (Notif notif in NotificationDict.Values) { if (notif.time == n.time && notif.Type == n.Type) { b = true; break; } } if (!b) { NotificationDict[c] = n; alarmeChipsField.Children.Add(c); if (NotificationDict.Count == 3) AddAlarme.IsEnabled = false; } else { MessageBox.Show("Alarme Dupliquée"); } } private void AddTask(object sender, MouseButtonEventArgs e) { if (TextBoxTitle.Text == "") { TextBoxTitle.Focus(); } else if (PickerDate.SelectedDate == null || PickerHeureDebut.SelectedTime == null || PickerHeureFin.SelectedTime == null) { MessageBox.Show("Veuillez choisir la date exacte"); } else if ((ComboBoxPriorité.SelectedIndex != 0) && (ComboBoxPriorité.SelectedIndex != 1) && (ComboBoxPriorité.SelectedIndex != 2)) { MessageBox.Show("Veuillez choisir la priorité"); } else if (((string)((ComboBoxItem)ComboBoxActivities.SelectedItem).DataContext) == "Activité scolaire" && DataSupervisor.ds.user.JoursFeries.Keys.Contains(PickerDate.SelectedDate.Value)) { MessageBox.Show("Le jour choisit est ferie"); } else { Tache t = new Tache(); DateTime? selectedDay = PickerDate.SelectedDate; DateTime dateDebut = new DateTime(selectedDay.Value.Year, selectedDay.Value.Month, selectedDay.Value.Day, PickerHeureDebut.SelectedTime.Value.Hour, PickerHeureDebut.SelectedTime.Value.Minute, PickerHeureDebut.SelectedTime.Value.Second); DateTime dateFin = new DateTime(selectedDay.Value.Year, selectedDay.Value.Month, selectedDay.Value.Day, PickerHeureFin.SelectedTime.Value.Hour, PickerHeureFin.SelectedTime.Value.Minute, PickerHeureFin.SelectedTime.Value.Second); t.dateDebut = dateDebut; t.dateFin = dateFin; foreach (String s in this.files) t.Fichiers.Add(s); t.title = TextBoxTitle.Text; t.Details = TextBoxDescription.Text; switch (ComboBoxPriorité.SelectedIndex) { case 0: t.priorite = "Urgente"; break; case 1: t.priorite = "Normale"; break; case 2: t.priorite = "Basse"; break; default: return; } t.Activitee = (string)((ComboBoxItem)ComboBoxActivities.SelectedItem).DataContext; t.Alarms = new List<Notif>(); foreach (KeyValuePair<Chip, Notif> n in NotificationDict) { t.Alarms.Add(n.Value); } DataSupervisor.ds.AddTache(t); windowParent.Close(); } } // Files : private void Importfile_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { OpenFileDialog file = new OpenFileDialog(); file.Filter = "Pdf Files (*.pdf)|*.pdf|Excel Files (*.xls)|*.xls|Word Files (*.docx)|*.docx|All files (*.*)|*.*"; file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); file.Multiselect = true; //On peut selectionner multiple fichiers if (file.ShowDialog() == true) { //Si l'utilisatuer selectionne aucun fichier if (file.FileNames.Length == 0) { cpt_files = 0; //un compteur qui compte le nombre des fichiers selectionnés files.Clear(); AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; } //si il selectionne un ficher else if (file.FileNames.Length == 1) { AddfilesCard.Visibility = Visibility.Hidden; FilesChipsCard.Visibility = Visibility.Visible; cpt_files = 1; //un compteur qui compte le nombre des fichiers selectionnés File1.Visibility = Visibility.Visible; File1.Content = file.SafeFileNames[0]; files.Add(file.FileNames[0]); } // si il selectionne deux fichiers else if (file.FileNames.Length == 2) { AddfilesCard.Visibility = Visibility.Hidden; FilesChipsCard.Visibility = Visibility.Visible; cpt_files = 2; //un compteur qui compte le nombre des fichiers selectionnés File1.Visibility = Visibility.Visible; File2.Visibility = Visibility.Visible; files.Clear(); foreach (string filename in file.SafeFileNames) files.Add(filename); File1.Content = files[0]; File1.ToolTip = files[0]; File2.Content = files[1]; File2.ToolTip = files[1]; } // si il selectionne trois fichiers else if (file.FileNames.Length == 3) { AddfilesCard.Visibility = Visibility.Hidden; FilesChipsCard.Visibility = Visibility.Visible; cpt_files = 3; //un compteur qui compte le nombre des fichiers selectionnés File1.Visibility = Visibility.Visible; File2.Visibility = Visibility.Visible; File3.Visibility = Visibility.Visible; files.Clear(); foreach (string filename in file.SafeFileNames) files.Add(filename); File1.Content = files[0]; File1.ToolTip = files[0]; File2.Content = files[1]; File2.ToolTip = files[1]; File3.Content = files[2]; File3.ToolTip = files[2]; } // s'il selectionne plus de trois fichiers else if (file.FileNames.Length > 3) { MessageBox.Show("Veuillez choisir trois fichiers seulement"); cpt_files = 0; //un compteur qui compte le nombre des fichiers selectionnés } } } //Si l'utilisateur veut supprimer qlqs fichiers private void File1_DeleteClick(object sender, RoutedEventArgs e) { File1.Visibility = Visibility.Hidden; Thickness margin = File2.Margin; margin.Left = -100; File2.Margin = margin; cpt_files -= 1; if (cpt_files == 0) { AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; margin.Left += 105; File3.Margin = margin; margin = File2.Margin; margin.Left += 105; File2.Margin = margin; } } private void File2_DeleteClick(object sender, RoutedEventArgs e) { File2.Visibility = Visibility.Hidden; Thickness margin = File3.Margin; margin.Left = -100; File3.Margin = margin; cpt_files -= 1; if (cpt_files == 0) { AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; margin.Left += 105; File3.Margin = margin; margin = File2.Margin; margin.Left += 105; File2.Margin = margin; } } private void File3_DeleteClick(object sender, RoutedEventArgs e) { File3.Visibility = Visibility.Hidden; cpt_files -= 1; Thickness margin = File3.Margin; if (cpt_files == 0) { AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; margin.Left += 105; File3.Margin = margin; margin = File2.Margin; margin.Left += 105; File2.Margin = margin; } } private static ComboBoxItem CreateActivityComboBox(string name, string color) { ComboBoxItem cbi = new ComboBoxItem() { Height = 30, DataContext = name }; WrapPanel sp = new WrapPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center }; MaterialDesignThemes.Wpf.PackIcon icon = new PackIcon() { Kind = PackIconKind.CheckboxBlankCircle, Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)), Width = 15 }; TextBlock tb = new TextBlock() { Text = name, HorizontalAlignment = HorizontalAlignment.Left, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(5, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, FontSize = 11 }; sp.Children.Add(icon); sp.Children.Add(tb); cbi.Content = sp; return cbi; } private void LoadActivities() { foreach (KeyValuePair<string, string> kv in DataSupervisor.ds.user.Activities) { ComboBoxActivities.Items.Add(CreateActivityComboBox(kv.Key, kv.Value)); } } } }
using ReactiveUI; namespace OrangeApple.WPF.ViewModels { public abstract class ComparisonItemViewModel : ReactiveObject { public abstract string ResultsViewText { get; } public override string ToString() { return ResultsViewText; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using Photon.Realtime; using UnityEngine.UI; public class LeaderboardListing : MonoBehaviour { [SerializeField] private TMP_Text rankText = null; [SerializeField] private TMP_Text nameText = null; public Player _player = null; public RoomInfo _RoomInfo { get; set; } private RawImage listingBackground; [SerializeField] private Color fullBackgroundColor = new Color(); [SerializeField] private Color fullTextColor = new Color(); void Start() { listingBackground = GetComponent<RawImage>(); } public void SetPlayerInfo(Player player) { _player = player; nameText.text = player.NickName; listingBackground.color = fullBackgroundColor; nameText.color = fullTextColor; rankText.color = fullTextColor; } }
using UnityEngine; using System.Collections; public class Spawn : MonoBehaviour { //a shared spawner used by enemies and powerups public float lowerFireRange;//Ranges define random intervals for firerate public float higherFireRange; public float nextFire = 0f;//controls first instance of instantiated object public GameObject spawn; void Update () { //randomly shoot the specified gameobjects from spawners float fireRate = Random.Range(lowerFireRange, higherFireRange); if (Time.time > nextFire) { nextFire = Time.time + fireRate; Vector3 position = transform.position; Instantiate(spawn, position, transform.rotation); } } }
namespace DesignPatterns.State.SystemPermissionExample { public class SystemUser { } }