text
stringlengths
13
6.01M
using MetroFramework; using MetroFramework.Forms; using PDV.CONTROLER.Funcoes; using PDV.DAO.Entidades; using PDV.UTIL; using PDV.VIEW.Forms.Cadastro; using PDV.VIEW.Forms.Util; using System; using System.Data; using System.Windows.Forms; namespace PDV.VIEW.Forms.Consultas { public partial class FCO_Categorias : DevExpress.XtraEditors.XtraForm { private string NOME_TELA = "CONSULTA DE CATEGORIAS"; public FCO_Categorias() { InitializeComponent(); AtualizarCategorias("", ""); } private void AtualizarCategorias(string Codigo, string Descricao) { gridControl1.DataSource = FuncoesCategoria.GetCategorias(Codigo, Descricao); FormatarGrid(); } private void FormatarGrid() { Grids.FormatGrid(ref gridView1); } private void ovBTN_Novo_Click(object sender, EventArgs e) { FCA_Categoria t = new FCA_Categoria(new Categoria()); t.ShowDialog(this); AtualizarCategorias("", ""); DesabilitarBotoes(); } private void ovBTN_Editar_Click(object sender, EventArgs e) { Editar(); } private void ovBTN_Excluir_Click(object sender, EventArgs e) { if (MessageBox.Show(this, "Deseja remover a Categoria selecionada?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { var id = Grids.GetValorDec(gridView1, "idcategoria"); try { if (!FuncoesCategoria.Remover(id)) throw new Exception("Não foi possível remover a Categoria."); } catch (Exception Ex) { MessageBox.Show(this, Ex.Message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } AtualizarCategorias("", ""); } DesabilitarBotoes(); } private void gridControl1_Click(object sender, EventArgs e) { btnEditar.Enabled = true; btnRemover.Enabled = true; } private void gridControl1_DoubleClick(object sender, EventArgs e) { Editar(); } private void imprimriMetroButton_Click(object sender, EventArgs e) { gridControl1.ShowPrintPreview(); DesabilitarBotoes(); } private void atualizarMetroButton_Click(object sender, EventArgs e) { AtualizarCategorias("", ""); } private void Editar() { try { var id = Grids.GetValorDec(gridView1, "idcategoria"); FCA_Categoria t = new FCA_Categoria(FuncoesCategoria.GetCategoria(id)); t.ShowDialog(this); AtualizarCategorias("", ""); } catch (NullReferenceException) { } finally { DesabilitarBotoes(); } } private void DesabilitarBotoes() { btnEditar.Enabled = btnRemover.Enabled = false; } } }
using System; using MenuSample.Scenes.Core; namespace MenuSample.Scenes { /// <summary> /// Un exemple de menu d'options /// </summary> public class OptionsMenuScene : AbstractMenuScene { private readonly MenuItem _languageMenuItem; private readonly MenuItem _resolutionMenuItem; private readonly MenuItem _fullscreenMenuItem; private readonly MenuItem _volumeMenuItem; //private readonly MenuItem _scoreMenuItem; private enum Mode { Arcade, Extreme, Cooperatif, } //private static Mode _currentmod = Language.Francais; //private static readonly string[] Resolutions = { "480x800", "800x600", "1024x768", "1280x1024", "1680x1050" }; /// <summary> /// Constructor. /// </summary> public OptionsMenuScene(SceneManager sceneMgr) : base(sceneMgr, "A delete") { // Création des options du menu _languageMenuItem = new MenuItem(string.Empty); _resolutionMenuItem = new MenuItem(string.Empty); _fullscreenMenuItem = new MenuItem(string.Empty); _volumeMenuItem = new MenuItem(string.Empty); //SetMenuItemText(); var back = new MenuItem("Retour"); // Gestion des évènements back.Selected += OnCancel; // Ajout des options au menu MenuItems.Add(_languageMenuItem); MenuItems.Add(_resolutionMenuItem); MenuItems.Add(_fullscreenMenuItem); MenuItems.Add(_volumeMenuItem); MenuItems.Add(back); } /// <summary> /// Mise à jour des valeurs du menu /// </summary> /* private void SetMenuItemText() { _languageMenuItem.Text = "Langue: " + _currentLanguage; _resolutionMenuItem.Text = "Resolution: " + Resolutions[_currentResolution]; _fullscreenMenuItem.Text = "Plein ecran: " + (_fullscreen ? "oui" : "non"); _volumeMenuItem.Text = "Volume: " + _volume; } private void LanguageMenuItemSelected(object sender, EventArgs e) { _currentLanguage++; if (_currentLanguage > Language.Nihongo) _currentLanguage = 0; SetMenuItemText(); } private void ResolutionMenuItemSelected(object sender, EventArgs e) { _currentResolution = (_currentResolution + 1) % Resolutions.Length; SetMenuItemText(); } private void FullscreenMenuItemSelected(object sender, EventArgs e) { _fullscreen = !_fullscreen; SetMenuItemText(); } private void VolumeMenuItemSelected(object sender, EventArgs e) { _volume++; SetMenuItemText(); } */ } }
using System.Collections; using UnityEngine; /// <summary> /// Scene 2 Checking phase (Save the animals) /// </summary> public class CheckingPhaseActivity2 : CheckingPhaseManager { protected CandSManager candSManager; private AudioContext2 audioContext; private System.Random rnd; /// <summary> /// Index of the current animal that has to go on the ark /// </summary> private int targetAnimalIndex; /// <summary> /// Setup the attributes and starts the Checking phase /// </summary> protected override void CheckingPhase() { audioContext = (AudioContext2)sceneManager.AudioContext; candSManager = (CandSManager)sceneManager; rnd = new System.Random(); StartCoroutine(IntroductionAndSaveAnimals()); } /// <summary> /// Check whether to do another iteration of the checking phase or end it /// if there are no more animals to save. /// </summary> internal void PickedAnimal() { if (SceneObjects.Count == 0) End(); else TriggerAnimalIteration(); } /// <summary> /// Wrap a single checking phase iteration in a coroutine /// </summary> private void TriggerAnimalIteration() { StartCoroutine(SaveAnimalsIteration()); } /// <summary> /// Makes the Virtual Assistant introduce the checking phase and start the /// first iteration of the activity. /// </summary> /// <returns></returns> private IEnumerator IntroductionAndSaveAnimals() { yield return candSManager.IntroduceCheckingPhase(); GameObject.Find("Ark").GetComponent<ArkLogic>().AnimalList = SceneObjects; yield return SaveAnimalsIteration(); } /// <summary> /// Choose target animal and play the corresponding audio /// </summary> /// <returns></returns> private IEnumerator SaveAnimalsIteration() { targetAnimalIndex = rnd.Next(0, SceneObjects.Count); yield return TartgetNextAnimal(); } /// <summary> /// Set the target animal in ArkLogic script and choose the audio /// </summary> /// <remarks> Audio choice is between one regarding comparative/superlative and the one /// where there is only one animal left. /// </remarks> /// <returns></returns> private IEnumerator TartgetNextAnimal() { string targetAnimal = SceneObjects[targetAnimalIndex]; GameObject.Find("Ark").GetComponent<ArkLogic>().SetTargetAnimal(targetAnimal); //If there are more than one animal use the comparatives and superlatives audios if (SceneObjects.Count > 1) yield return ChooseComparativeOrSuperlative(targetAnimal); else yield return TargetLastAnimal(); } /// <summary> /// Choose the audio to play between the comparative and the superlative one. /// </summary> /// <remarks>The method heavily relies on the animal position in the SceneObjects list</remarks> /// <param name="targetAnimal">The target animal</param> /// <returns></returns> private IEnumerator ChooseComparativeOrSuperlative(string targetAnimal) { //If the animal is the first or the last in the list, the superlative audio can be used bool canUseSuperlative = (targetAnimalIndex == 0) || (targetAnimalIndex == SceneObjects.Count - 1); if (canUseSuperlative) { //Decide to use the superlative audio or not bool useSuperlative = (rnd.Next(0, 2)) == 0; if (useSuperlative) { //Use the superlative audio if (targetAnimalIndex == 0) yield return TargetNextSuperlative(targetAnimal, Superlatives.Smallest); else yield return TargetNextSuperlative(targetAnimal, Superlatives.Biggest); } else //Use the comparative audio yield return TargetNextComparative(targetAnimal); } else //Otherwise use the comparative audio yield return TargetNextComparative(targetAnimal); } private IEnumerator TargetNextComparative(string targetAnimal) { yield return candSManager.IntroduceTasktWithComparatives(targetAnimal); } private IEnumerator TargetNextSuperlative(string targetAnimal, Superlatives superlative) { yield return candSManager.IntroduceTaskWithSuperlatives(targetAnimal, superlative.Value); } private IEnumerator TargetLastAnimal() { yield return candSManager.IntroduceLastAnimal(); } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; /* * * Function Template When Usint TaskCenter * * <Return Type> Function Name (OrderedDictionary Parameters) * { * Dictionary should contain the parameter object as the key and the parameter type as the value * Should already know what type each parameter is when writing the function. May just use list of objects and convert in function * * <Return Type> * } * */ namespace GITRepoManager { public class TaskCenter { private static List<TaskFunction> TaskList_Function { get; set; } private static List<TaskAction> TaskList_Action { get; set; } public static List<object> Responses { get; set; } public TaskCenter() { TaskList_Function = new List<TaskFunction>(); TaskList_Action = new List<TaskAction>(); Responses = new List<object>(); } public void Add_Function(Func<OrderedDictionary, object> function, OrderedDictionary Parameters) { TaskFunction temp = new TaskFunction(function, Parameters); TaskList_Function.Add(temp); } public void Add_Action(Action<OrderedDictionary> action, OrderedDictionary Parameters) { TaskAction temp = new TaskAction(action, Parameters); TaskList_Action.Add(temp); } public void Run_Functions() { foreach(TaskFunction TaskFunc in TaskList_Function) { try { TaskFunc.func.Invoke(TaskFunc.Parameters); } catch { } } } public void Run_Actions() { foreach(TaskAction TaskAct in TaskList_Action) { try { TaskAct.action.Invoke(TaskAct.Parameters); } catch { } } } public void Clear_Lists() { TaskList_Action.Clear(); TaskList_Function.Clear(); Responses.Clear(); } } public class TaskFunction { public Func<OrderedDictionary, object> func { get; set; } public OrderedDictionary Parameters { get; set; } public TaskFunction(Func<OrderedDictionary, object> _Function = null, OrderedDictionary _Parameters = null) { func = _Function; Parameters = _Parameters; } } public class TaskAction { public Action<OrderedDictionary> action { get; set; } public OrderedDictionary Parameters { get; set; } public TaskAction(Action<OrderedDictionary> _Action = null, OrderedDictionary _Parameters = null) { action = _Action; Parameters = _Parameters; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BooksApi.Models; using BooksApi.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.OpenApi.Models; namespace BooksApi { 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.Configure<BookstoreDatabaseSettings>( Configuration.GetSection(nameof(BookstoreDatabaseSettings))); services.AddSingleton<IBookstoreDatabaseSettings>(sp => sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value); services.AddSingleton<BookService>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Books API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme.", Type = SecuritySchemeType.Http, //We set the scheme type to http since we're using bearer authentication Scheme = "bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement{ { new OpenApiSecurityScheme{ Reference = new OpenApiReference{ Id = "Bearer", //The name of the previously defined security scheme. Type = ReferenceType.SecurityScheme } },new List<string>() } }); }); services.AddControllers(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Report API V1"); c.RoutePrefix = String.Empty; }); app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireCors("CorsPolicy"); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Investiments : MonoBehaviour { public static Investiments instance; public List<InvestmentCard> cards = new List<InvestmentCard>(); [SerializeField] Transform cardsParent; private void Awake() { instance = this; } public float GetTotalValueInvested() { float f = 0; foreach (var inv in cards) { f += inv._Value; } return f; } public float GetTotalInvested() { float f = 0; foreach (var inv in cards) { f += inv.invAmount; } return f; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Model.DataEntity; using eIVOGo.Helper; using eIVOGo.Models; using Model.Security.MembershipManagement; using Business.Helper; using System.Text; using Model.Locale; using System.Web.Script.Serialization; using System.IO; using System.IO.Compression; using Utility; using System.Threading; using System.Data.SqlClient; using System.Data; using ClosedXML.Excel; using System.Data.Linq; using eIVOGo.Models.ViewModel; using Model.Models.ViewModel; using ModelExtension.Helper; using Model.Helper; using System.Threading.Tasks; using eIVOGo.Helper.Security.Authorization; using Uxnet.Com.Helper; namespace eIVOGo.Controllers { public class InvoiceQueryController : SampleController<InvoiceItem> { protected UserProfileMember _userProfile; protected ModelSourceInquiry<InvoiceItem> createModelInquiry() { _userProfile = HttpContext.GetUser(); var inquireConsumption = new InquireInvoiceConsumption { ControllerName = "InquireInvoice", ActionName = "ByConsumption", CurrentController = this }; //inquireConsumption.Append(new InquireInvoiceConsumptionExtensionToPrint { CurrentController = this }); return (ModelSourceInquiry<InvoiceItem>)(new InquireEffectiveInvoice { CurrentController = this }) .Append(new InquireInvoiceByRole(_userProfile) { CurrentController = this }) .Append(inquireConsumption) .Append(new InquireInvoiceSeller { ControllerName = "InquireInvoice", ActionName = "BySeller", /*QueryRequired = true, AlertMessage = "請選擇公司名稱!!",*/ CurrentController = this }) .Append(new InquireInvoiceBuyer { ControllerName = "InquireInvoice", ActionName = "ByBuyer", CurrentController = this }) .Append(new InquireInvoiceBuyerByName { ControllerName = "InquireInvoice", ActionName = "ByBuyerName", CurrentController = this }) .Append(new InquireInvoiceDate { ControllerName = "InquireInvoice", ActionName = "ByInvoiceDate", CurrentController = this }) .Append(new InquireInvoiceAttachment { ControllerName = "InquireInvoice", ActionName = "ByAttachment", CurrentController = this }) .Append(new InquireInvoiceNo { CurrentController = this }) .Append(new InquireInvoiceAgent { ControllerName = "InquireInvoice", ActionName = "ByAgent", CurrentController = this }) .Append(new InquireWinningInvoice { CurrentController = this }); } [RoleAuthorize(RoleID = new Naming.RoleID[] { Naming.RoleID.ROLE_SYS })] public ActionResult InvoiceReport(InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = false; ViewBag.QueryAction = "Inquire"; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); return View(models.Inquiry); } [RoleAuthorize(RoleID = new Naming.RoleID[] { Naming.RoleID.ROLE_SYS })] public ActionResult MonthlyReport(MonthlyReportQueryViewModel viewModel) { //ViewBag.HasQuery = false; ViewBag.QueryAction = "Inquire"; ViewBag.ViewModel = viewModel; return View(models.Inquiry); } [RoleAuthorize(RoleID = new Naming.RoleID[] { Naming.RoleID.ROLE_SYS })] public ActionResult InquireMonthlyReport(MonthlyReportQueryViewModel viewModel) { ViewBag.ViewModel = viewModel; if (!viewModel.DateFrom.HasValue) { ModelState.AddModelError("InvoiceDateFrom", "請輸入查詢起日"); } if (!viewModel.DateTo.HasValue) { ModelState.AddModelError("InvoiceDateFrom", "請輸入查詢迄日"); } if(!viewModel.AgentID.HasValue && !viewModel.SellerID.HasValue) { ModelState.AddModelError("AgentID", "請選擇代理人"); ModelState.AddModelError("SellerID", "請輸入開立人統編"); } if (!ModelState.IsValid) { return View("~/Views/Shared/ReportInputError.cshtml"); } viewModel.Message = "發票月報表"; ProcessRequest processItem = new ProcessRequest { Sender = HttpContext.GetUser()?.UID, SubmitDate = DateTime.Now, ProcessStart = DateTime.Now, ResponsePath = System.IO.Path.Combine(Logger.LogDailyPath, Guid.NewGuid().ToString() + ".xlsx"), ViewModel = viewModel.JsonStringify(), }; models.GetTable<ProcessRequest>().InsertOnSubmit(processItem); models.SubmitChanges(); viewModel.TaskID = processItem.TaskID; viewModel.Push($"{DateTime.Now.Ticks}.json"); return View("~/Views/Shared/Module/PromptCheckDownload.cshtml", new AttachmentViewModel { TaskID = processItem.TaskID, FileName = processItem.ResponsePath, FileDownloadName = "月報表資料明細.xlsx", }); } [RoleAuthorize(RoleID = new Naming.RoleID[] { Naming.RoleID.ROLE_SYS, Naming.RoleID.ROLE_SELLER })] public ActionResult InvoiceMediaReport(TaxMediaQueryViewModel viewModel) { ViewBag.ViewModel = viewModel; if(!viewModel.BusinessBorder.HasValue) { viewModel.BusinessBorder = CategoryDefinition.CategoryEnum.發票開立營業人; } ViewBag.QueryAction = "InquireInvoiceMedia"; return View("~/Views/InvoiceQuery/InvoiceMediaReport.cshtml"); } public ActionResult InquireInvoiceMedia(TaxMediaQueryViewModel viewModel) { ViewBag.ViewModel = viewModel; if (viewModel.BusinessBorder == CategoryDefinition.CategoryEnum.發票開立營業人) { viewModel.TaxNo = viewModel.TaxNo.GetEfficientString(); if (viewModel.TaxNo == null || viewModel.TaxNo.Length != 9) { ModelState.AddModelError("TaxNo", "請輸入9位數稅籍編號!!"); } } if (!viewModel.Year.HasValue) { ModelState.AddModelError("Year", "請選擇年度!!"); } if (!viewModel.PeriodNo.HasValue) { ModelState.AddModelError("PeriodNo", "請選擇期別!!"); } if (!viewModel.SellerID.HasValue) { ModelState.AddModelError("SellerID", "請選擇發票開立人!!"); } if (!ModelState.IsValid) { ViewBag.ModelState = ModelState; return View("~/Views/InvoiceQuery/InvoiceMediaReport.cshtml"); } if (viewModel.BusinessBorder == CategoryDefinition.CategoryEnum.境外電商) { ProcessRequest processItem = new ProcessRequest { Sender = HttpContext.GetUser()?.UID, SubmitDate = DateTime.Now, ProcessStart = DateTime.Now, ResponsePath = System.IO.Path.Combine(Logger.LogDailyPath, Guid.NewGuid().ToString() + ".csv"), }; models.GetTable<ProcessRequest>().InsertOnSubmit(processItem); models.SubmitChanges(); saveAsCsv(processItem.TaskID, processItem.ResponsePath, viewModel); return View("~/Views/InvoiceQuery/InvoiceMediaReport.cshtml", new AttachmentViewModel { TaskID = processItem.TaskID, FileName = processItem.ResponsePath, FileDownloadName = $"{DateTime.Today:yyyy-MM-dd}.csv", }); //return View("~/Views/InvoiceQuery/InvoiceMediaReportCBM.cshtml"); } DateTime startDate = new DateTime(viewModel.Year.Value, viewModel.PeriodNo.Value * 2 - 1, 1); DataLoadOptions ops = new DataLoadOptions(); ops.LoadWith<InvoiceItem>(i => i.InvoiceBuyer); ops.LoadWith<InvoiceItem>(i => i.InvoiceCancellation); ops.LoadWith<InvoiceItem>(i => i.InvoiceAmountType); ops.LoadWith<InvoiceItem>(i => i.InvoiceSeller); models.GetDataContext().LoadOptions = ops; var items = models.GetTable<InvoiceItem>().Where(i => i.SellerID == viewModel.SellerID && i.InvoiceDate >= startDate && i.InvoiceDate < startDate.AddMonths(2)) .OrderBy(i => i.InvoiceID); var allowance = models.GetTable<InvoiceAllowance>() .Where(a => a.InvoiceAllowanceCancellation == null) .Where(a => a.InvoiceAllowanceSeller.SellerID == viewModel.SellerID) .Where(a => a.AllowanceDate >= startDate && a.AllowanceDate < startDate.AddMonths(2)); ViewBag.AllowanceItems = allowance; if (items.Count() > 0 || allowance.Count() > 0) { ViewBag.FileName = String.Format("{0:d4}{1:d2}({2}).txt", viewModel.Year, viewModel.PeriodNo, items.First().Organization.ReceiptNo); var orgItem = models.GetTable<Organization>().Where(o => o.CompanyID == viewModel.SellerID).First(); if (orgItem.OrganizationExtension == null) orgItem.OrganizationExtension = new OrganizationExtension { }; if (orgItem.OrganizationExtension.TaxNo != viewModel.TaxNo) { orgItem.OrganizationExtension.TaxNo = viewModel.TaxNo; models.SubmitChanges(); } } else { ViewBag.Message = "資料不存在!!"; return View("InvoiceMediaReport"); } return View("~/Views/InvoiceQuery/InquireInvoiceMedia.cshtml", items); } static void saveAsCsv(int taskID, String resultFile, TaxMediaQueryViewModel viewModel) { Task.Run(() => { try { String tmp = $"{resultFile}.tmp"; Exception exception = null; using (StreamWriter writer = new StreamWriter(tmp,false,Encoding.UTF8)) { using (ModelSource<InvoiceItem> db = new ModelSource<InvoiceItem>()) { try { DateTime dateFrom = new DateTime(viewModel.Year.Value, viewModel.PeriodNo.Value * 2 - 1, 1); writer.WriteLine("格式代號,資料所屬期別(年月),幣別,銷售總計金額,匯率,換算後銷售總計金額,銷售額,銷項稅額,交易筆數,統一發票字軌,發票起號,發票迄號,發票開立年月"); for (int idx = 0; idx < 2; idx++) { var invoiceItems = db.DataContext.GetInvoiceReport(viewModel.SellerID, dateFrom, dateFrom.AddMonths(1)); var allowanceItems = db.DataContext.GetAllowanceReport(viewModel.SellerID, dateFrom, dateFrom.AddMonths(1)); foreach (var g in invoiceItems) { decimal? exchangeRate; if (g.CurrencyID == 0) { exchangeRate = 1; } else { exchangeRate = db.GetTable<InvoicePeriodExchangeRate>() .Where(v => v.PeriodID == g.PeriodID && v.CurrencyID == g.CurrencyID) .FirstOrDefault()?.ExchangeRate; } decimal? twTotalAmt = g.TotalAmount * exchangeRate; decimal? twAmtNoTax = null; if (twTotalAmt.HasValue) { twTotalAmt = Math.Round(twTotalAmt.Value); twAmtNoTax = Math.Round(twTotalAmt.Value / 1.05M); } writer.WriteLine($"35,{dateFrom.Year - 1911}{dateFrom.Month:00},{(g.CurrencyID == 0 ? "NTD" : g.AbbrevName)},{g.TotalAmount},{exchangeRate:.#####},{twTotalAmt},{twAmtNoTax},{twTotalAmt - twAmtNoTax},{g.RecordCount},{g.TrackCode},{g.StartNo:00000000},{g.EndNo:00000000},"); } foreach (var g in allowanceItems) { decimal? exchangeRate; if (g.CurrencyID == 0) { exchangeRate = 1; } else { exchangeRate = db.GetTable<InvoicePeriodExchangeRate>() .Where(v => v.PeriodID == g.PeriodID && v.CurrencyID == g.CurrencyID) .FirstOrDefault()?.ExchangeRate; } decimal? twTotalAmt = g.TotalAmount * exchangeRate; decimal? twTaxAmt = g.TotalTaxAmount * exchangeRate; if (twTotalAmt.HasValue) { twTotalAmt = Math.Round(twTotalAmt.Value); } if (twTaxAmt.HasValue) { twTaxAmt = Math.Round(twTaxAmt.Value); } writer.WriteLine($"33,{dateFrom.Year - 1911}{dateFrom.Month:00},{(g.CurrencyID == 0 ? "NTD" : g.AbbrevName)},{g.TotalAmount},{exchangeRate:.#####},,,,{g.RecordCount},{g.TrackCode},{g.StartNo:00000000},{g.EndNo:00000000},{g.Year - 1911:000}{g.Month:00}"); } dateFrom = dateFrom.AddMonths(1); } } catch (Exception ex) { Logger.Error(ex); exception = ex; } ProcessRequest taskItem = db.GetTable<ProcessRequest>() .Where(t => t.TaskID == taskID).FirstOrDefault(); if (taskItem != null) { if (exception != null) { taskItem.ExceptionLog = new ExceptionLog { DataContent = exception.Message }; } taskItem.ProcessComplete = DateTime.Now; db.SubmitChanges(); } } } if (exception == null) { System.IO.File.Move(tmp, resultFile); } } catch (Exception ex) { Logger.Error(ex); } }); } public ActionResult Inquire(InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = true; ViewBag.PrintAction = "PrintResult"; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); return View("InquiryResult",models.Inquiry); } [RoleAuthorize(RoleID = new Naming.RoleID[] { Naming.RoleID.ROLE_SYS })] public ActionResult InvoiceAttachment(InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = false; ViewBag.QueryAction = "InquireAttachment"; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); return View("InvoiceReport", models.Inquiry); } public ActionResult InquireAttachment(InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = true; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); return View("AttachmentResult", models.Inquiry); } public ActionResult AttachmentGridPage(int index, int size, InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = true; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); if (index > 0) index--; else index = 0; return View(models.Items.OrderByDescending(d => d.InvoiceID) .Skip(index * size).Take(size)); } public ActionResult GridPage(int index,int size, InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = true; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); if (index > 0) index--; else index = 0; return View(models.Items.OrderByDescending(d => d.InvoiceID) .Skip(index * size).Take(size)); } public ActionResult DownloadCSV(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); Response.ContentEncoding = Encoding.GetEncoding(950); return View(models.Items); } public ActionResult CreateXlsx(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); _userProfile["modelSource"] = models; Server.Transfer("~/MvcHelper/CreateInvoiceReport.aspx"); return new EmptyResult(); } public ActionResult AssignDownload(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); String resultFile = Path.Combine(Logger.LogDailyPath, Guid.NewGuid().ToString() + ".xlsx"); _userProfile["assignDownload"] = resultFile; ThreadPool.QueueUserWorkItem(stateInfo => { try { SqlCommand sqlCmd = (SqlCommand)models.GetCommand(models.Items); using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd)) { using (DataSet ds = new DataSet()) { adapter.Fill(ds); using(XLWorkbook xls = new XLWorkbook()) { xls.Worksheets.Add(ds); xls.SaveAs(resultFile); } } } models.Dispose(); } catch(Exception ex) { Logger.Error(ex); } }); return Content("下載資料請求已送出!!"); } public ActionResult PrintResult(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); ((ModelSource<InvoiceItem>)models).ResultModel = Naming.DataResultMode.Print; return View(models.Inquiry); } public ActionResult DownloadInvoiceAttachment(DocumentQueryViewModel viewModel) { ViewBag.ViewModel = viewModel; if (viewModel.KeyID != null) { viewModel.DocID = viewModel.DecryptKeyValue(); } var items = models.GetTable<InvoiceItem>().Where(i => i.InvoiceID == viewModel.DocID); if (items.Any()) { return zipAttachment(items); } else { Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Cache-control", "max-age=1"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", HttpUtility.UrlEncode("DataNotFound.txt"))); Response.Output.WriteLine("file not found!!"); Response.End(); return new EmptyResult(); } } public ActionResult DownloadAttachment() { String jsonData = Request["data"]; if (!String.IsNullOrEmpty(jsonData)) { JavaScriptSerializer serializer = new JavaScriptSerializer(); int[] invoiceID = serializer.Deserialize<int[]>(jsonData); using (ModelSource<InvoiceItem> models = new ModelSource<InvoiceItem>()) { return zipAttachment(models.EntityList.Where(i => invoiceID.Contains(i.InvoiceID))); } } return Content(jsonData); } public ActionResult DownloadAll(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); return zipAttachment(models.Items); } private ActionResult zipAttachment(IEnumerable<InvoiceItem> items) { String temp = Server.MapPath("~/temp"); if (!Directory.Exists(temp)) { Directory.CreateDirectory(temp); } String outFile = Path.Combine(temp, Guid.NewGuid().ToString() + ".zip"); using (var zipOut = System.IO.File.Create(outFile)) { using (ZipArchive zip = new ZipArchive(zipOut, ZipArchiveMode.Create)) { foreach (var item in items) { if (item.CDS_Document.Attachment.Count > 0) { for (int i = 0; i < item.CDS_Document.Attachment.Count; i++) { var attach = item.CDS_Document.Attachment[i]; if (System.IO.File.Exists(attach.StoredPath)) { ZipArchiveEntry entry = zip.CreateEntry(i == 0 ? item.TrackCode + item.No + ".pdf" : item.TrackCode + item.No + "-" + i + ".pdf"); using (Stream outStream = entry.Open()) { using (var inStream = System.IO.File.Open(attach.StoredPath, FileMode.Open)) { inStream.CopyTo(outStream); } } } } } } } } var result = new FilePathResult(outFile, "application/octet-stream"); result.FileDownloadName = "發票附件.zip"; return result; } public ActionResult InvoiceSummary(InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = false; ViewBag.QueryAction = "InquireSummary"; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); return View("~/Views/InvoiceQuery/InvoiceReport.cshtml", models.Inquiry); } public static readonly int[] AvailableMemberCategory = new int[] { (int)CategoryDefinition.CategoryEnum.發票開立營業人, (int)CategoryDefinition.CategoryEnum.GoogleTaiwan, (int)CategoryDefinition.CategoryEnum.營業人發票自動配號, (int)CategoryDefinition.CategoryEnum.經銷商, (int)CategoryDefinition.CategoryEnum.境外電商, }; public ActionResult InquireSummary(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; if (!viewModel.InvoiceDateFrom.HasValue) { ModelState.AddModelError("InvoiceDateFrom", "請輸入查詢起日"); } if (!viewModel.InvoiceDateTo.HasValue) { ModelState.AddModelError("InvoiceDateTo", "請輸入查詢迄日"); } if(!ModelState.IsValid) { return View("~/Views/Shared/ReportInputError.cshtml"); } var profile = HttpContext.GetUser(); models.Inquiry = createModelInquiry(); models.BuildQuery(); var orgaCate = models.GetTable<OrganizationCategory>().Where(c => AvailableMemberCategory.Contains(c.CategoryID)); IQueryable<Organization> sellerItems = models.GetTable<Organization>() .Where(o => orgaCate.Any(c => c.CompanyID == o.CompanyID)); sellerItems = models.GetDataContext().FilterOrganizationByRole(profile, sellerItems); if (viewModel.SellerID.HasValue) { sellerItems = sellerItems.Where(o => o.CompanyID == viewModel.SellerID); } if (viewModel.AgentID.HasValue) { sellerItems = sellerItems .Join(models.GetTable<InvoiceIssuerAgent>() .Where(a => a.AgentID == viewModel.AgentID), o => o.CompanyID, a => a.IssuerID, (o, a) => o); } viewModel.ResultView = "~/Views/InvoiceQuery/Module/InvoiceSummaryResult.cshtml"; return PageResult(viewModel, sellerItems); } public ActionResult CreateMonthlyReportXlsx(InquireInvoiceViewModel viewModel) { ViewResult result = (ViewResult)InquireSummary(viewModel); IQueryable<Organization> items = result.Model as IQueryable<Organization>; if (items == null) { return result; } ProcessRequest processItem = new ProcessRequest { Sender = HttpContext.GetUser()?.UID, SubmitDate = DateTime.Now, ProcessStart = DateTime.Now, ResponsePath = System.IO.Path.Combine(Logger.LogDailyPath, Guid.NewGuid().ToString() + ".xlsx"), }; models.GetTable<ProcessRequest>().InsertOnSubmit(processItem); models.SubmitChanges(); _dbInstance = false; SqlCommand sqlCmd = (SqlCommand)models.GetCommand(items); SaveAsExcel(processItem, viewModel, items); return View("~/Views/Shared/Module/PromptCheckDownload.cshtml", new AttachmentViewModel { TaskID = processItem.TaskID, FileName = processItem.ResponsePath, FileDownloadName = "開立發票月報表.xlsx", }); } private void SaveAsExcel(ProcessRequest taskItem, InquireInvoiceViewModel viewModel, IQueryable<Organization> items) { Task.Run(() => { Exception exception = null; try { using (DataSet ds = new DataSet()) { IQueryable<InvoiceItem> dataItems = models.Items; DataTable table = new DataTable(); table.Columns.Add(new DataColumn("開立發票營業人", typeof(String))); table.Columns.Add(new DataColumn("統編", typeof(String))); table.Columns.Add(new DataColumn("上線日期", typeof(String))); table.Columns.Add(new DataColumn("發票筆數", typeof(int))); table.Columns.Add(new DataColumn("註記停用日期", typeof(String))); table.TableName = $"發票資料統計({viewModel.InvoiceDateFrom:yyyy-MM-dd}~{viewModel.InvoiceDateTo:yyyy-MM-dd})"; ds.Tables.Add(table); //var invoiceItems = items.GroupJoin(models.Items, // o => o.CompanyID, i => i.SellerID, (o, i) => new { Seller = o, Items = i }); foreach (var item in items.OrderBy(o => o.ReceiptNo)) { DataRow r = table.NewRow(); r[0] = item.CompanyName; r[1] = item.ReceiptNo; r[2] = $"{item.OrganizationExtension?.GoLiveDate:yyyy/MM/dd}"; r[3] = dataItems.Count(i => i.SellerID == item.CompanyID); r[4] = $"{item.OrganizationExtension?.ExpirationDate:yyyy/MM/dd}"; table.Rows.Add(r); } foreach (var yy in dataItems.GroupBy(i => i.InvoiceDate.Value.Year)) { foreach (var mm in yy.GroupBy(i => i.InvoiceDate.Value.Month)) { table = new DataTable(); table.Columns.Add(new DataColumn("日期", typeof(String))); table.Columns.Add(new DataColumn("未作廢總筆數", typeof(int))); table.Columns.Add(new DataColumn("未作廢總金額", typeof(decimal))); table.Columns.Add(new DataColumn("已作廢總筆數", typeof(int))); table.Columns.Add(new DataColumn("已作廢總金額", typeof(decimal))); table.TableName = $"月報表({yy.Key}-{ mm.Key})"; ds.Tables.Add(table); IEnumerable<InvoiceItem> v0, v1; DataRow r; foreach (var item in mm.GroupBy(i => i.InvoiceDate.Value.Day).OrderBy(g => g.Key)) { r = table.NewRow(); r[0] = item.Key.ToString(); v0 = item.Where(i => i.InvoiceCancellation == null); v1 = item.Where(i => i.InvoiceCancellation != null); r[1] = v0.Count(); r[2] = v0.Sum(i => i.InvoiceAmountType.TotalAmount); r[3] = v1.Count(); r[4] = v1.Sum(i => i.InvoiceAmountType.TotalAmount); table.Rows.Add(r); } v0 = mm.Where(i => i.InvoiceCancellation == null); v1 = mm.Where(i => i.InvoiceCancellation != null); r = table.NewRow(); r[0] = "總計"; r[1] = v0.Count(); r[2] = v0.Sum(i => i.InvoiceAmountType.TotalAmount); r[3] = v1.Count(); r[4] = v1.Sum(i => i.InvoiceAmountType.TotalAmount); table.Rows.Add(r); } } using (var xls = ds.ConvertToExcel()) { xls.SaveAs(taskItem.ResponsePath); } } } catch (Exception ex) { exception = ex; Logger.Error(ex); } if (exception != null) { taskItem.ExceptionLog = new ExceptionLog { DataContent = exception.Message }; } taskItem.ProcessComplete = DateTime.Now; models.SubmitChanges(); models.Dispose(); }); } public ActionResult InvoiceSummaryGridPage(int index, int size, InquireInvoiceViewModel viewModel) { //ViewBag.HasQuery = true; ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); if (index > 0) index--; else index = 0; ViewBag.PageIndex = index; ViewBag.PageSize = size; return View(models.Items); } public ActionResult CreateInvoiceSummaryXlsx(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); _userProfile["modelSource"] = models; Server.Transfer("~/MvcHelper/CreateInvoiceSummaryReport.aspx"); return new EmptyResult(); } public ActionResult PrintInvoiceSummary(InquireInvoiceViewModel viewModel) { ViewBag.ViewModel = viewModel; models.Inquiry = createModelInquiry(); models.BuildQuery(); ((ModelSource<InvoiceItem>)models).ResultModel = Naming.DataResultMode.Print; return View(models.Inquiry); } public ActionResult DataQueryIndex(DataQueryViewModel viewModel) { ViewBag.ViewModel = viewModel; return View("~/Views/InvoiceQuery/DataQueryIndex.cshtml"); } public ActionResult InquireData(DataQueryViewModel viewModel) { ViewBag.ViewModel = viewModel; viewModel.CommandText = viewModel.CommandText.GetEfficientString(); if (viewModel.CommandText == null) { ModelState.AddModelError("CommandText", "請輸入查詢指令!!"); } if (!ModelState.IsValid) { ViewBag.ModelState = ModelState; return View("~/Views/Shared/ReportInputError.cshtml"); } return View("~/Views/InvoiceQuery/DataAction/ExecuteDataQuery.cshtml"); } } }
using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Web; namespace GetLabourManager.Configuration { public class AllocationContainersConfiguration:EntityTypeConfiguration<AllocationContainers> { public AllocationContainersConfiguration() { Property(x => x.ContainerId).IsRequired(); Property(x => x.ContainerNumber).IsOptional().HasMaxLength(25); Property(x => x.AllocationId).IsRequired(); HasRequired(x => x.GangAllocated).WithMany(x => x.Containers) .HasForeignKey(x => x.AllocationId).WillCascadeOnDelete(false); } } }
using System; using NUnit.Framework; namespace TestsPayroll.Social { [TestFixture()] public class SocialEmployerPaymentTest { [Test()] public void Employer_Insurance_Payment_For_2_000_CZK_Base_Is_X_CZK() { } [Test()] public void Employer_Insurance_Payment_For_10_000_CZK_Base_Is_X_CZK() { } [Test()] public void Employer_Insurance_Payment_For_0_CZK_Base_Is_0_CZK() { } [Test()] public void Employer_Insurance_Payment_For_Obligatory_Base_Is_X_CZK() { } [Test()] public void Employer_Insurance_Payment_For_Annual_Max_Base_Is_X_CZK() { } } }
using System; using System.ComponentModel.DataAnnotations; namespace IMDB.Api.Models.ViewModel { public class ContentRating : BaseModel { [Required(ErrorMessage = "Title is required")] public string Title { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hotel.Web.Areas.ModulRecepcija.ViewModels { public class RezervisanaUslugaIndexVM { public List<Row> usluge { get; set; } public class Row { public int Id { set; get; } public int UslugeHotelaId { get; set; } public string UslugeHotela { get; set; } public int CheckINId { get; set; } public string CheckIN { get; set; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using BPiaoBao.AppServices.DataContracts.DomesticTicket.DataObject; using BPiaoBao.Common.Enums; using BPiaoBao.DomesticTicket.Domain.Models; namespace BPiaoBao.DomesticTicket.Domain.Services { public class GetFlightBasicData { string strConnectionString = string.Empty; public GetFlightBasicData() { strConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["FlightQuery"].ConnectionString; } #region 测试数据 /// <summary> /// 返回datatable /// </summary> /// <param name="safeSql"></param> /// <returns></returns> public DataTable GetDataSet(string safeSql) { DataSet ds = new DataSet(); try { SqlCommand cmd = new SqlCommand(safeSql, new SqlConnection(strConnectionString)); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetDataSet]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetDataSet]", e); } if (ds.Tables.Count > 0) { return ds.Tables[0]; } else { return null; } } public int ExecuteSQL(string safeSql) { int result = -1; try { using (SqlConnection connection = new SqlConnection(strConnectionString)) { using (SqlCommand cmd = new SqlCommand(safeSql, connection)) { cmd.CommandTimeout = 120; if (connection.State == ConnectionState.Closed) { connection.Open(); } result = cmd.ExecuteNonQuery(); } if (connection.State == ConnectionState.Open) { connection.Close(); } } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[ExecuteSQL]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[ExecuteSQL]", e); } return result; } public object ExecuteScalar(string safeSql) { object result = -1; try { using (SqlConnection connection = new SqlConnection(strConnectionString)) { using (SqlCommand cmd = new SqlCommand(safeSql, connection)) { cmd.CommandTimeout = 120; if (connection.State == ConnectionState.Closed) { connection.Open(); } result = cmd.ExecuteScalar(); } if (connection.State == ConnectionState.Open) { connection.Close(); } } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[ExecuteScalar]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[ExecuteScalar]", e); } return result; } public int ExecuteSQLList(List<string> safeSql) { int result = -1; try { using (SqlConnection connection = new SqlConnection(strConnectionString)) { SqlCommand cmd = new SqlCommand(); cmd.Connection = connection; cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 120; if (connection.State == ConnectionState.Closed) { connection.Open(); } foreach (string sql in safeSql) { cmd.CommandText = sql; result = cmd.ExecuteNonQuery(); } connection.Close(); } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[ExecuteSQLList]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[ExecuteSQLList]", e); } return result; } public List<CabinRow> GetCabinSeatListPolicy(string sqlWhere) { string sql = "select CarrierCode,SeatList from dbo.CabinSeat"; if (!string.IsNullOrEmpty(sqlWhere)) { sql += " where " + sqlWhere; } List<CabinRow> reList = new List<CabinRow>(); try { using (SqlConnection conn = new SqlConnection(strConnectionString)) { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); string strCarrayCode = string.Empty; while (rdr.Read()) { CabinRow cabinRow = new CabinRow(); strCarrayCode = rdr["CarrierCode"] != null ? rdr["CarrierCode"].ToString() : ""; string strSeat = rdr["SeatList"] != null ? rdr["SeatList"].ToString() : ""; string[] strArray = strSeat.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (strArray.Length > 0) { List<Seat> listSpace = new List<Seat>(); foreach (string item in strArray) { if (item.Split('-').Length == 2) { reList.Add(new CabinRow() { CarrayCode = strCarrayCode, Seat = item.Split('-')[0], Rebate = decimal.Parse(item.Split('-')[1]) }); } } } } rdr.Close(); } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetCabinSeatListPolicy]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetCabinSeatListPolicy]", e); } return reList; } public List<CabinSeat> GetCabinSeatList(string sqlWhere) { string sql = "select * from dbo.CabinSeat"; if (!string.IsNullOrEmpty(sqlWhere)) { sql += " where " + sqlWhere; } List<CabinSeat> reList = new List<CabinSeat>(); try { using (SqlConnection conn = new SqlConnection(strConnectionString)) { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (rdr.Read()) { CabinSeat cabinSeat = new CabinSeat(); cabinSeat._id = rdr["_id"] != null ? rdr["_id"].ToString() : ""; cabinSeat.CarrierCode = rdr["CarrierCode"] != null ? rdr["CarrierCode"].ToString() : ""; cabinSeat.Airline = new Airline() { FromCode = rdr["FromCode"] != null ? rdr["FromCode"].ToString() : "", ToCode = rdr["ToCode"] != null ? rdr["ToCode"].ToString() : "", Mileage = int.Parse(rdr["Mileage"] != null ? rdr["Mileage"].ToString() : "0"), SeatPrice = decimal.Parse(rdr["SeatPrice"] != null ? rdr["SeatPrice"].ToString() : "0") }; cabinSeat.Fuel = new Fuel() { AdultFuelFee = decimal.Parse(rdr["AdultFuelFee"] != null ? rdr["AdultFuelFee"].ToString() : "0"), ChildFuelFee = decimal.Parse(rdr["ChildFuelFee"] != null ? rdr["ChildFuelFee"].ToString() : "0") }; string strSeat = rdr["SeatList"] != null ? rdr["SeatList"].ToString() : ""; string[] strArray = strSeat.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (strArray.Length > 0) { List<Seat> listSpace = new List<Seat>(); foreach (string item in strArray) { if (item.Split('-').Length == 2) { listSpace.Add(new Seat() { Code = item.Split('-')[0], Rebate = decimal.Parse(item.Split('-')[1]) }); } } cabinSeat.SeatList = listSpace; } else { cabinSeat.SeatList = new List<Seat>(); } reList.Add(cabinSeat); } rdr.Close(); } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetCabinSeatList]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetCabinSeatList]", e); } return reList; } public bool UpdateCarrier(string Code, string YDOffice, string CPOffice, string PrintNo) { string sql = string.Format("update dbo.AirCarrier set YDOffice='{0}',CPOffice='{1}',PrintNo='{2}' where Code='{3}' ", YDOffice, CPOffice, PrintNo, Code ); int execCount = ExecuteSQL(sql); return (execCount > 0 ? true : false); } public List<AirCarrier> GetAirCarrier(string sqlWhere) { List<AirCarrier> listAirCarrier = new List<AirCarrier>(); string sql = "select * from dbo.AirCarrier"; if (!string.IsNullOrEmpty(sqlWhere)) { sql += " where " + sqlWhere; } using (SqlConnection conn = new SqlConnection(strConnectionString)) { try { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (rdr.Read()) { AirCarrier ac = new AirCarrier(); //ac._id = rdr["_id"] != null ? rdr["_id"].ToString() : ""; ac.AirName = rdr["AirName"] != null ? rdr["AirName"].ToString() : ""; ac.Code = rdr["Code"] != null ? rdr["Code"].ToString() : ""; ac.SettleCode = rdr["SettleCode"] != null ? rdr["SettleCode"].ToString() : ""; ac.ShortName = rdr["ShortName"] != null ? rdr["ShortName"].ToString() : ""; ac.YDOffice = rdr["YDOffice"] != null ? rdr["YDOffice"].ToString() : ""; ac.CPOffice = rdr["CPOffice"] != null ? rdr["CPOffice"].ToString() : ""; ac.ShortName = rdr["PrintNo"] != null ? rdr["PrintNo"].ToString() : ""; listAirCarrier.Add(ac); } rdr.Close(); } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetAirCarrier]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetAirCarrier]", e); } } return listAirCarrier; } public bool ExistAirplainType(string code) { int count = -1; string sql = string.Format("select count(*) from dbo.AirplainType where Code='{0}'", code); int.TryParse(ExecuteScalar(sql).ToString(), out count); return count > 0 ? true : false; } public List<AirplainType> GetAirplainType() { List<AirplainType> listAirplainType = new List<AirplainType>(); string sql = "select * from dbo.AirplainType"; using (SqlConnection conn = new SqlConnection(strConnectionString)) { try { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (rdr.Read()) { AirplainType atype = new AirplainType(); //atype._id = rdr["_id"] != null ? rdr["_id"].ToString() : ""; atype.Code = rdr["Code"] != null ? rdr["Code"].ToString() : ""; atype.TaxFee = decimal.Parse(rdr["TaxFee"] != null ? rdr["TaxFee"].ToString() : "0"); listAirplainType.Add(atype); } rdr.Close(); } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetAirplainType]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetAirplainType]", e); } } return listAirplainType; } public List<CityCode> GetCityCode() { string sql = "select * from dbo.CityCode"; List<CityCode> listCityCode = new List<CityCode>(); using (SqlConnection conn = new SqlConnection(strConnectionString)) { try { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (rdr.Read()) { CityCode cityCode = new CityCode(); //cityCode._id = rdr["_id"] != null ? rdr["_id"].ToString() : ""; cityCode.Code = rdr["Code"] != null ? rdr["Code"].ToString() : ""; cityCode.Name = rdr["Name"] != null ? rdr["Name"].ToString() : ""; cityCode.SimplePinyin = rdr["SimplePinyin"] != null ? rdr["SimplePinyin"].ToString() : ""; cityCode.WholePinyin = rdr["WholePinyin"] != null ? rdr["WholePinyin"].ToString() : ""; cityCode.Terminal = rdr["Terminal"] != null ? rdr["Terminal"].ToString() : ""; listCityCode.Add(cityCode); } rdr.Close(); } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetCityCode]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetCityCode]", e); } } return listCityCode; } public List<BaseCabin> GetBaseCabin(string sqlWhere) { string sql = "select * from dbo.BaseCabin"; if (!string.IsNullOrEmpty(sqlWhere)) { sql += " where " + sqlWhere; } List<BaseCabin> reList = new List<BaseCabin>(); try { using (SqlConnection conn = new SqlConnection(strConnectionString)) { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (rdr.Read()) { BaseCabin baseCabin = new BaseCabin(); //baseCabin._id = rdr["_id"] != null ? rdr["_id"].ToString() : ""; baseCabin.CarrierCode = rdr["CarrierCode"] != null ? rdr["CarrierCode"].ToString() : ""; baseCabin.Code = rdr["Code"] != null ? rdr["Code"].ToString() : ""; decimal _Rebate = 0m; decimal.TryParse((rdr["Rebate"] != null ? rdr["Rebate"].ToString() : "0"), out _Rebate); baseCabin.Rebate = _Rebate; reList.Add(baseCabin); } rdr.Close(); } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetBaseCabin]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetBaseCabin]", e); } return reList; } public List<PolicyCache> GetPolicyCache(string sqlWhere) { List<PolicyCache> reList = new List<PolicyCache>(); string sql = "select * from PolicyCache "; if (!string.IsNullOrEmpty(sqlWhere)) { sql += " where " + sqlWhere; } try { using (SqlConnection conn = new SqlConnection(strConnectionString)) { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (rdr.Read()) { PolicyCache pc = new PolicyCache(); pc._id = rdr["_id"] != DBNull.Value ? rdr["_id"].ToString() : ""; pc.PolicyId = rdr["PolicyId"] != DBNull.Value ? rdr["PolicyId"].ToString() : ""; pc.CarrierCode = rdr["CarrierCode"] != DBNull.Value ? rdr["CarrierCode"].ToString() : ""; pc.CabinSeatCode = (rdr["CabinSeatCode"] != DBNull.Value ? rdr["CabinSeatCode"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); pc.FromCityCode = rdr["FromCityCode"] != DBNull.Value ? rdr["FromCityCode"].ToString() : ""; pc.MidCityCode = rdr["MidCityCode"] != DBNull.Value ? rdr["MidCityCode"].ToString() : ""; pc.ToCityCode = rdr["ToCityCode"] != DBNull.Value ? rdr["ToCityCode"].ToString() : ""; pc.SuitableFlightNo = (rdr["SuitableFlightNo"] != DBNull.Value ? rdr["SuitableFlightNo"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); pc.ExceptedFlightNo = (rdr["ExceptedFlightNo"] != DBNull.Value ? rdr["ExceptedFlightNo"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); string[] strSuitableWeek = (rdr["SuitableWeek"] != DBNull.Value ? rdr["SuitableWeek"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); List<DayOfWeek> daylist = new List<DayOfWeek>(); foreach (string item in strSuitableWeek) { switch (item) { case "1": daylist.Add(DayOfWeek.Monday); break; case "2": daylist.Add(DayOfWeek.Tuesday); break; case "3": daylist.Add(DayOfWeek.Wednesday); break; case "4": daylist.Add(DayOfWeek.Thursday); break; case "5": daylist.Add(DayOfWeek.Friday); break; case "6": daylist.Add(DayOfWeek.Saturday); break; case "0": daylist.Add(DayOfWeek.Sunday); break; default: break; } } pc.SuitableWeek = daylist.ToArray(); DateTime CheckinTime_FromTime = System.DateTime.Now; DateTime CheckinTime_EndTime = System.DateTime.Now; DateTime IssueTime_FromTime = System.DateTime.Now; DateTime IssueTime_EndTime = System.DateTime.Now; DateTime ServiceTime_WeekendTime_FromTime = System.DateTime.Now; DateTime ServiceTime_WeekendTime_EndTime = System.DateTime.Now; DateTime ServiceTime_WeekTime_FromTime = System.DateTime.Now; DateTime ServiceTime_WeekTime_EndTime = System.DateTime.Now; DateTime TFGTime_WeekendTime_FromTime = System.DateTime.Now; DateTime TFGTime_WeekendTime_EndTime = System.DateTime.Now; DateTime TFGTime_WeekTime_FromTime = System.DateTime.Now; DateTime TFGTime_WeekTime_EndTime = System.DateTime.Now; if (rdr["CheckinTime_FromTime"] != DBNull.Value) { CheckinTime_FromTime = DateTime.Parse(rdr["CheckinTime_FromTime"].ToString()); } if (rdr["CheckinTime_EndTime"] != DBNull.Value) { CheckinTime_EndTime = DateTime.Parse(rdr["CheckinTime_EndTime"].ToString()); } if (rdr["IssueTime_FromTime"] != DBNull.Value) { IssueTime_FromTime = DateTime.Parse(rdr["IssueTime_FromTime"].ToString()); } if (rdr["IssueTime_EndTime"] != DBNull.Value) { IssueTime_EndTime = DateTime.Parse(rdr["IssueTime_EndTime"].ToString()); } pc.CheckinTime = new TimePeriod() { FromTime = CheckinTime_FromTime, EndTime = CheckinTime_EndTime }; pc.IssueTime = new TimePeriod() { FromTime = IssueTime_FromTime, EndTime = IssueTime_EndTime }; if (rdr["ServiceTime_WeekendTime_FromTime"] != DBNull.Value) { ServiceTime_WeekendTime_FromTime = DateTime.Parse(rdr["ServiceTime_WeekendTime_FromTime"].ToString()); } if (rdr["ServiceTime_WeekendTime_EndTime"] != DBNull.Value) { ServiceTime_WeekendTime_EndTime = DateTime.Parse(rdr["ServiceTime_WeekendTime_EndTime"].ToString()); } if (rdr["ServiceTime_WeekTime_FromTime"] != DBNull.Value) { ServiceTime_WeekTime_FromTime = DateTime.Parse(rdr["ServiceTime_WeekTime_FromTime"].ToString()); } if (rdr["ServiceTime_WeekTime_EndTime"] != DBNull.Value) { ServiceTime_WeekTime_EndTime = DateTime.Parse(rdr["ServiceTime_WeekTime_EndTime"].ToString()); } pc.ServiceTime = new WorkTime() { WeekTime = new TimePeriod() { FromTime = ServiceTime_WeekTime_FromTime, EndTime = ServiceTime_WeekTime_EndTime }, WeekendTime = new TimePeriod() { FromTime = ServiceTime_WeekendTime_FromTime, EndTime = ServiceTime_WeekendTime_EndTime } }; if (rdr["TFGTime_WeekendTime_FromTime"] != DBNull.Value) { TFGTime_WeekendTime_FromTime = DateTime.Parse(rdr["TFGTime_WeekendTime_FromTime"].ToString()); } if (rdr["TFGTime_WeekendTime_EndTime"] != DBNull.Value) { TFGTime_WeekendTime_EndTime = DateTime.Parse(rdr["TFGTime_WeekendTime_EndTime"].ToString()); } if (rdr["TFGTime_WeekTime_FromTime"] != DBNull.Value) { TFGTime_WeekTime_FromTime = DateTime.Parse(rdr["TFGTime_WeekTime_FromTime"].ToString()); } if (rdr["TFGTime_WeekTime_EndTime"] != DBNull.Value) { TFGTime_WeekTime_EndTime = DateTime.Parse(rdr["TFGTime_WeekTime_EndTime"].ToString()); } pc.TFGTime = new WorkTime() { WeekTime = new TimePeriod() { FromTime = TFGTime_WeekTime_FromTime, EndTime = TFGTime_WeekTime_EndTime }, WeekendTime = new TimePeriod() { FromTime = TFGTime_WeekendTime_FromTime, EndTime = TFGTime_WeekendTime_EndTime } }; pc.Remark = rdr["Remark"] != DBNull.Value ? rdr["Remark"].ToString() : ""; string strTravelType = rdr["TravelType"] != DBNull.Value ? rdr["TravelType"].ToString() : "1"; pc.TravelType = strTravelType == "1" ? TravelType.Oneway : (strTravelType == "2" ? TravelType.Twoway : TravelType.Connway); string strPolicyType = rdr["PolicyType"] != DBNull.Value ? rdr["PolicyType"].ToString() : "B2B"; pc.PolicyType = (strPolicyType == "B2B") ? PolicyType.B2B : PolicyType.BSP; decimal _point = 0m; decimal.TryParse((rdr["Point"] != DBNull.Value ? rdr["Point"].ToString() : "0"), out _point); pc.Point = _point; pc.OldPoint = _point; pc.PlatformCode = rdr["PlatformCode"] != DBNull.Value ? rdr["PlatformCode"].ToString() : ""; pc.CacheDate = rdr["CacheDate"] != DBNull.Value ? DateTime.Parse(rdr["CacheDate"].ToString()) : System.DateTime.Now; pc.CacheExpiresDate = rdr["CacheExpiresDate"] != DBNull.Value ? DateTime.Parse(rdr["CacheExpiresDate"].ToString()) : System.DateTime.Now.AddMonths(1); pc.PolicySourceType = EnumPolicySourceType.Interface; reList.Add(pc); } rdr.Close(); } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetPolicyCache]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetPolicyCache]", e); } return reList; } public bool AddPolicyCache(List<PolicyCache> PolicyList) { bool Issucess = false; StringBuilder sbAdd = new StringBuilder(); try { foreach (PolicyCache Pc in PolicyList) { sbAdd.Append("INSERT INTO [dbo].[PolicyCache]([_id],[PolicyId],[PlatformCode],[CarrierCode],[CabinSeatCode],[FromCityCode],[MidCityCode],[ToCityCode],[SuitableFlightNo],[ExceptedFlightNo],[SuitableWeek],[CheckinTime_FromTime],[CheckinTime_EndTime],[IssueTime_FromTime],[IssueTime_EndTime],[ServiceTime_WeekendTime_FromTime],[ServiceTime_WeekendTime_EndTime],[ServiceTime_WeekTime_FromTime],[ServiceTime_WeekTime_EndTime],[TFGTime_WeekendTime_FromTime],[TFGTime_WeekendTime_EndTime],[TFGTime_WeekTime_FromTime],[TFGTime_WeekTime_EndTime],[Remark],[TravelType],[PolicyType],[Point],[CacheDate])VALUES("); sbAdd.AppendFormat("'{0}',", Pc._id.ToString()); sbAdd.AppendFormat("'{0}',", Pc.PolicyId.ToString()); sbAdd.AppendFormat("'{0}',", Pc.PlatformCode.ToString()); sbAdd.AppendFormat("'{0}',", Pc.CarrierCode.ToString()); sbAdd.AppendFormat("'{0}',", string.Join("/", Pc.CabinSeatCode)); sbAdd.AppendFormat("'{0}',", Pc.FromCityCode); sbAdd.AppendFormat("'{0}',", Pc.MidCityCode); sbAdd.AppendFormat("'{0}',", Pc.ToCityCode); sbAdd.AppendFormat("'{0}',", string.Join("/", Pc.SuitableFlightNo)); sbAdd.AppendFormat("'{0}',", string.Join("/", Pc.ExceptedFlightNo)); string strSuitableWeek = ""; if (Pc.SuitableWeek != null && Pc.SuitableWeek.Length > 0) { List<string> ll = new List<string>(); for (int i = 0; i < Pc.SuitableWeek.Length; i++) { ll.Add(((int)Pc.SuitableWeek[i]).ToString()); } strSuitableWeek = string.Join("/", ll.ToArray()); } sbAdd.AppendFormat("'{0}',", strSuitableWeek); sbAdd.AppendFormat("'{0}',", Pc.CheckinTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.CheckinTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.IssueTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.IssueTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.ServiceTime.WeekendTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.ServiceTime.WeekendTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.ServiceTime.WeekTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.ServiceTime.WeekTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.TFGTime.WeekendTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.TFGTime.WeekendTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.TFGTime.WeekTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.TFGTime.WeekTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.AppendFormat("'{0}',", Pc.Remark); sbAdd.AppendFormat("'{0}',", ((int)Pc.TravelType).ToString()); sbAdd.AppendFormat("'{0}',", Pc.PolicyType.ToString()); sbAdd.AppendFormat("{0},", Pc.Point); sbAdd.AppendFormat("'{0}'", Pc.CacheDate.ToString("yyyy-MM-dd HH:mm:ss")); sbAdd.Append(") \r\n"); } PnrAnalysis.LogText.LogWrite(sbAdd.ToString(), "AddPolicyCache"); Issucess = true; } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[AddPolicyCache]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[AddPolicyCache]", e); } return Issucess; } /// <summary> /// 获取折扣 /// </summary> /// <returns></returns> public decimal GetZK(string fromcode, string tocode, string carrayCode, string seat, decimal seatPrice) { decimal zk = 0m; try { string sqlWhere = string.Format("CarrierCode='{0}' and FromCode='{1}' and ToCode='{2}' and SeatList like '%Y-100%'", carrayCode, fromcode, tocode); List<CabinSeat> list = GetCabinSeatList(sqlWhere); if (list != null && list.Count > 0) { Seat m_seat = list[0].SeatList.Where(p1 => p1.Code.ToUpper() == seat.ToUpper()).FirstOrDefault(); if (m_seat != null) { zk = m_seat.Rebate; } } if (zk == 0) { string sql = string.Format("select FareFee from dbo.Bd_Air_Fares where FromCityCode='{0}' and ToCityCode='{1}' and (CarryCode=''or CarryCode='{2}')", fromcode, tocode, carrayCode); object objFare = ExecuteScalar(sql); decimal YFare = 0m; if (objFare != null && decimal.TryParse(objFare.ToString(), out YFare) && YFare > 0) { zk = GetZk(seatPrice, YFare); } } } catch (SqlException ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetZK]", ex); } catch (Exception e) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "航班数据库查询[GetZK]", e); } return zk; } /// <summary> /// 计算折扣 /// </summary> /// <param name="SeatPrice"></param> /// <param name="YSeatPrice"></param> /// <returns></returns> public decimal GetZk(decimal SeatPrice, decimal YSeatPrice) { decimal _zk = 0m; if (YSeatPrice != 0) { _zk = Math.Round((SeatPrice / YSeatPrice) + 0.0000001M, 4) * 100; } return _zk; } #endregion #region 缓存接口政策 private DataTable GetTable(List<PolicyCache> policyList, int patchNo, int cacheDay) { DataTable dt = new DataTable(); if (policyList != null && policyList.Count > 0) { PolicyCache policy = policyList[0]; List<DataColumn> listCol = new List<DataColumn>(); listCol.Add(new DataColumn("_id", typeof(string))); listCol.Add(new DataColumn("PolicyId", typeof(string))); listCol.Add(new DataColumn("PlatformCode", typeof(string))); listCol.Add(new DataColumn("CarrierCode", typeof(string))); listCol.Add(new DataColumn("CabinSeatCode", typeof(string))); listCol.Add(new DataColumn("FromCityCode", typeof(string))); listCol.Add(new DataColumn("MidCityCode", typeof(string))); listCol.Add(new DataColumn("ToCityCode", typeof(string))); listCol.Add(new DataColumn("SuitableFlightNo", typeof(string))); listCol.Add(new DataColumn("ExceptedFlightNo", typeof(string))); listCol.Add(new DataColumn("SuitableWeek", typeof(string))); listCol.Add(new DataColumn("CheckinTime_FromTime", typeof(DateTime))); listCol.Add(new DataColumn("CheckinTime_EndTime", typeof(DateTime))); listCol.Add(new DataColumn("IssueTime_FromTime", typeof(DateTime))); listCol.Add(new DataColumn("IssueTime_EndTime", typeof(DateTime))); listCol.Add(new DataColumn("ServiceTime_WeekendTime_FromTime", typeof(DateTime))); listCol.Add(new DataColumn("ServiceTime_WeekendTime_EndTime", typeof(DateTime))); listCol.Add(new DataColumn("ServiceTime_WeekTime_FromTime", typeof(DateTime))); listCol.Add(new DataColumn("ServiceTime_WeekTime_EndTime", typeof(DateTime))); listCol.Add(new DataColumn("TFGTime_WeekendTime_FromTime", typeof(DateTime))); listCol.Add(new DataColumn("TFGTime_WeekendTime_EndTime", typeof(DateTime))); listCol.Add(new DataColumn("TFGTime_WeekTime_FromTime", typeof(DateTime))); listCol.Add(new DataColumn("TFGTime_WeekTime_EndTime", typeof(DateTime))); listCol.Add(new DataColumn("Remark", typeof(string))); listCol.Add(new DataColumn("TravelType", typeof(string))); listCol.Add(new DataColumn("PolicyType", typeof(string))); listCol.Add(new DataColumn("Point", typeof(decimal))); listCol.Add(new DataColumn("CacheDate", typeof(DateTime))); listCol.Add(new DataColumn("CacheExpiresDate", typeof(DateTime))); listCol.Add(new DataColumn("PatchNo", typeof(int))); dt.Columns.AddRange(listCol.ToArray()); dt.TableName = policy.GetType().Name; DataRow dr = null; foreach (PolicyCache item in policyList) { dr = dt.NewRow(); //赋值 dr["_id"] = item._id; dr["PolicyId"] = item.PolicyId; dr["PlatformCode"] = item.PlatformCode; dr["CarrierCode"] = item.CarrierCode; dr["CabinSeatCode"] = string.Join("/", item.CabinSeatCode); dr["FromCityCode"] = item.FromCityCode; dr["MidCityCode"] = item.MidCityCode; dr["ToCityCode"] = item.ToCityCode; dr["SuitableFlightNo"] = string.Join("/", item.SuitableFlightNo); dr["ExceptedFlightNo"] = string.Join("/", item.ExceptedFlightNo); string strSuitableWeek = ""; if (item.SuitableWeek != null && item.SuitableWeek.Length > 0) { List<string> ll = new List<string>(); for (int i = 0; i < item.SuitableWeek.Length; i++) { ll.Add(((int)item.SuitableWeek[i]).ToString()); } strSuitableWeek = string.Join("/", ll.ToArray()); } dr["SuitableWeek"] = strSuitableWeek; dr["CheckinTime_FromTime"] = item.CheckinTime.FromTime; dr["CheckinTime_EndTime"] = item.CheckinTime.EndTime; dr["IssueTime_FromTime"] = item.IssueTime.FromTime; dr["IssueTime_EndTime"] = item.IssueTime.EndTime; dr["ServiceTime_WeekendTime_FromTime"] = item.ServiceTime.WeekendTime.FromTime; dr["ServiceTime_WeekendTime_EndTime"] = item.ServiceTime.WeekendTime.EndTime; dr["ServiceTime_WeekTime_FromTime"] = item.ServiceTime.WeekTime.FromTime; dr["ServiceTime_WeekTime_EndTime"] = item.ServiceTime.WeekTime.EndTime; dr["TFGTime_WeekendTime_FromTime"] = item.TFGTime.WeekendTime.FromTime; dr["TFGTime_WeekendTime_EndTime"] = item.TFGTime.WeekendTime.EndTime; dr["TFGTime_WeekTime_FromTime"] = item.TFGTime.WeekTime.FromTime; dr["TFGTime_WeekTime_EndTime"] = item.TFGTime.WeekTime.EndTime; dr["Remark"] = item.Remark; dr["TravelType"] = (int)item.TravelType; dr["PolicyType"] = item.PolicyType; dr["Point"] = item.Point; dr["CacheDate"] = item.CacheDate; dr["CacheExpiresDate"] = System.DateTime.Now.AddDays(cacheDay); dr["PatchNo"] = patchNo; dt.Rows.Add(dr); } } return dt; } public void TableValuedToDB(List<PolicyCache> policyList, int patchNo, int cacheDay) { patchNo = 0; DataTable dt = GetTable(policyList, patchNo, cacheDay); SqlConnection sqlConn = new SqlConnection(strConnectionString); StringBuilder sbSQL = new StringBuilder(); sbSQL.Append("INSERT INTO [dbo].[PolicyCache]([_id],[PolicyId],[PlatformCode],[CarrierCode],[CabinSeatCode],[FromCityCode],[MidCityCode],[ToCityCode],[SuitableFlightNo],[ExceptedFlightNo],[SuitableWeek],[CheckinTime_FromTime],[CheckinTime_EndTime],[IssueTime_FromTime],[IssueTime_EndTime],[ServiceTime_WeekendTime_FromTime],[ServiceTime_WeekendTime_EndTime],[ServiceTime_WeekTime_FromTime],[ServiceTime_WeekTime_EndTime],[TFGTime_WeekendTime_FromTime],[TFGTime_WeekendTime_EndTime],[TFGTime_WeekTime_FromTime],[TFGTime_WeekTime_EndTime],[Remark],[TravelType],[PolicyType],[Point],[CacheDate],[CacheExpiresDate],[PatchNo]) "); sbSQL.Append(" select t.[_id],t.[PolicyId],t.[PlatformCode],t.[CarrierCode],t.[CabinSeatCode],t.[FromCityCode],t.[MidCityCode],t.[ToCityCode],t.[SuitableFlightNo],t.[ExceptedFlightNo],t.[SuitableWeek],t.[CheckinTime_FromTime],t.[CheckinTime_EndTime],t.[IssueTime_FromTime],t.[IssueTime_EndTime],t.[ServiceTime_WeekendTime_FromTime],t.[ServiceTime_WeekendTime_EndTime],t.[ServiceTime_WeekTime_FromTime],t.[ServiceTime_WeekTime_EndTime],t.[TFGTime_WeekendTime_FromTime],t.[TFGTime_WeekendTime_EndTime],t.[TFGTime_WeekTime_FromTime],t.[TFGTime_WeekTime_EndTime],t.[Remark],t.[TravelType],t.[PolicyType],t.[Point],t.[CacheDate],t.[CacheExpiresDate],t.[PatchNo] from @Tvp AS t"); SqlCommand cmd = new SqlCommand(sbSQL.ToString(), sqlConn); SqlParameter catParam = cmd.Parameters.AddWithValue("@Tvp", dt); catParam.SqlDbType = SqlDbType.Structured; //表值参数的名字叫BulkUdt catParam.TypeName = "dbo.BulkUdt"; try { if (dt != null && dt.Rows.Count != 0) { sqlConn.Open(); cmd.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } finally { if (sqlConn.State == ConnectionState.Open) { sqlConn.Close(); } } } /// <summary> /// 删除重复的政策或者过期的政策 /// </summary> public void ExecRepeatSQL() { try { //去掉重复或者过期的政策的 StringBuilder sbSql = new StringBuilder(); sbSql.Append("delete dbo.PolicyCache where CacheExpiresDate is not null and CacheExpiresDate <getdate()"); //删除过期的 int exec = ExecuteSQL(sbSql.ToString()); //删除重复的 sbSql.Append(" delete from dbo.PolicyCache where PolicyId in( "); sbSql.Append(" select PolicyId from dbo.PolicyCache group by PolicyId having COUNT(PolicyId)>1 "); sbSql.Append(" ) and _id not in(select MAX(_id) from dbo.PolicyCache group by PolicyId having COUNT(PolicyId)>1) "); //sbSql.Append(" or (CacheExpiresDate is not null and CacheExpiresDate <getdate())"); exec = ExecuteSQL(sbSql.ToString()); if (exec < 0) { exec = ExecuteSQL(sbSql.ToString()); } } catch (Exception ex) { JoveZhao.Framework.Logger.WriteLog(JoveZhao.Framework.LogType.ERROR, "删除重复的政策或者过期的政策[ExecRepeatSQL]", ex); } } #endregion } }
using UnityEngine; using System.Collections; public class PlayerAnimationStateManager : StateMachineBehaviour { #region Influence Target Information U2DController controller; [SerializeField] private string targetName = "Dummy"; [SerializeField] private GameObject fire; [SerializeField] private GameObject aCol1; [SerializeField] private GameObject aCol2; [SerializeField] private GameObject aCol3; [SerializeField] private string stateName; #endregion #region For Initialize Script Condition private bool init = true; void Initialize() { init = false; controller = GameObject.Find(targetName).GetComponent<U2DController>(); } #endregion // OnStateEnter is called before OnStateEnter is called on any state inside this state machine override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //新しいステートに移り変わった時に実行 #region Initialize if (init) { Initialize(); } #endregion #region Reset Combo Conditions if (stateInfo.IsName("SwordCombo03")) { canCreateFire = true; } else { canCreateFire = false; } if (stateInfo.IsName("SwordCombo01") || stateInfo.IsName("SwordCombo02") || stateInfo.IsName("SwordCombo03")) { canCreatCol = true; canCreateBullet = false; } else if (stateInfo.IsName("GunCombo01") || stateInfo.IsName("GunCombo02") || stateInfo.IsName("GunCombo03")) { canCreatCol = false; canCreateBullet = true; } #endregion #region About Player Object Shouting bool isShout = false; int number = -1; if (stateInfo.IsName("SwordCombo01") || stateInfo.IsName("GunCombo01")) { isShout = true; number = 0; } else if (stateInfo.IsName("SwordCombo02") || stateInfo.IsName("GunCombo02")) { isShout = true; number = 1; } else if (stateInfo.IsName("SwordCombo03")) { isShout = true; number = 2; } else if (stateInfo.IsName("GunCombo03")) { isShout = true; number = 5; } if (isShout && number != -1) { controller.Shout(number); } #endregion } #region variables of Spawn Attack Collider and Effects private bool canCreateFire = false; private bool canCreatCol = false; private bool canCreateBullet = false; #endregion // OnStateUpdate is called before OnStateUpdate is called on any state inside this state machine override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //最初と最後のフレームを除く、各フレーム単位で実行 if (stateInfo.IsName(stateName)) { controller.EndAttack(); } else if (canCreatCol) { GameObject obj = null; if (stateInfo.IsName("SwordCombo01") && 0.3f <= stateInfo.normalizedTime && stateInfo.normalizedTime <= 0.5f) { canCreatCol = false; obj = Instantiate(aCol1); } else if (stateInfo.IsName("SwordCombo02") && 0.2f <= stateInfo.normalizedTime && stateInfo.normalizedTime <= 0.5f) { canCreatCol = false; obj = Instantiate(aCol2); } else if (stateInfo.IsName("SwordCombo03") && 0.2f <= stateInfo.normalizedTime && stateInfo.normalizedTime <= 0.5f) { canCreatCol = false; obj = Instantiate(aCol3); } if (canCreatCol == false && obj != null) { GameObject target = GameObject.Find(targetName); U2DController u2dc = target.GetComponent<U2DController>(); int direction = u2dc.GetDirection(); AColManager acm = obj.GetComponent<AColManager>(); acm.SetInfo(target.transform.position, direction); } } else if (canCreateFire) { if (stateInfo.IsName("SwordCombo03") && 0.6f <= stateInfo.normalizedTime) { canCreateFire = false; GameObject target = GameObject.Find(targetName); U2DController u2dc = target.GetComponent<U2DController>(); float direction = (float)u2dc.GetDirection(); GameObject obj = Instantiate(fire); FireMoving fm = obj.GetComponent<FireMoving>(); fm.SetInfo(target.transform.position, direction); } } else if (canCreateBullet) { if ((stateInfo.IsName("GunCombo01") && 0.3f <= stateInfo.normalizedTime && stateInfo.normalizedTime <= 0.5f) || (stateInfo.IsName("GunCombo02") && 0.3f <= stateInfo.normalizedTime && stateInfo.normalizedTime <= 0.5f) || (stateInfo.IsName("GunCombo03") && 0.3f <= stateInfo.normalizedTime && stateInfo.normalizedTime <= 0.5f)) { int type = stateInfo.IsName("GunCombo01") ? 0 : (stateInfo.IsName("GunCombo02") ? 1 : 2); int numBullet = 3; for (int i = 0; i < numBullet; i++) { controller.StartCoroutine(controller.CreateBullet(type, i, 0.1f * i)); } canCreateBullet = false; if (stateInfo.IsName("GunCombo03")) { for (int i = 0; i < numBullet; i++) { controller.StartCoroutine(controller.CreateMissile(i)); } } } } } // OnStateExit is called before OnStateExit is called on any state inside this state machine override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //ステートが次のステートに移り変わる直前に実行 if (stateInfo.IsName("SwordCombo01") || stateInfo.IsName("GunCombo01") || stateInfo.IsName("SwordCombo02") || stateInfo.IsName("GunCombo02") || stateInfo.IsName("SwordCombo03") || stateInfo.IsName("GunCombo03")) { controller.ChainBreak(); } } // OnStateMove is called before OnStateMove is called on any state inside this state machine //override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //MonoBehaviour.OnAnimatorMoveの直後に実行される //} // OnStateIK is called before OnStateIK is called on any state inside this state machine //override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //MonoBehaviour.OnAnimatorIKの直後に実行される //} // OnStateMachineEnter is called when entering a statemachine via its Entry Node //override public void OnStateMachineEnter(Animator animator, int stateMachinePathHash){ // //スクリプトが貼り付けられたステートマシンに遷移してきた時に実行 //} // OnStateMachineExit is called when exiting a statemachine via its Exit Node //override public void OnStateMachineExit(Animator animator, int stateMachinePathHash) { // //スクリプトが貼り付けられたステートマシンから出て行く時に実行 //} }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallController : MonoBehaviour { public float startForce; private Rigidbody2D myRigidBody; public GameObject paddle1; public GameObject paddle2; public GameManager theGM; // Use this for initialization void Start () { myRigidBody = GetComponent<Rigidbody2D>(); myRigidBody.velocity = new Vector2(startForce, startForce); } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D other) { if(other.tag == "GoalZone") { if(transform.position.x < 0) { transform.position = paddle2.transform.position + new Vector3(-1f, 0, 0); myRigidBody.velocity = new Vector2(-startForce, -startForce); theGM.UpdateScore(2); } else { transform.position = paddle1.transform.position + new Vector3(1f, 0, 0); myRigidBody.velocity = new Vector2(startForce, startForce); theGM.UpdateScore(1); } } } }
namespace DeliverySystem.Dtos.User { public class UserRegisterDto { public string Username { get; set; } public string Password { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; using System.Data; using System.Data.SQLite; using System.Transactions; namespace csharp_scraper.Controllers { public class Store : Data { public static void Data(DateTime timeStamp, string symbol, string companyName, string lastPrice, string change, string percentChange) { var sql = new SQLiteCommand("INSERT INTO stocks(timeStamp, symbol, companyName, lastPrice, change, percentChange) VALUES(?,?,?,?,?,?)", connect()); try { Console.WriteLine("Saving data..."); sql.Parameters.AddWithValue("timeStamp", timeStamp); sql.Parameters.AddWithValue("symbol", symbol); sql.Parameters.AddWithValue("companyName", companyName); sql.Parameters.AddWithValue("lastPrice", lastPrice); sql.Parameters.AddWithValue("change", change); sql.Parameters.AddWithValue("percentChange", percentChange); sql.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } }
using Project.BLL.RepositoryPattern.RepositoryConcrete; using Project.MODEL.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Project.MVCUI.Controllers { public class BookController : Controller { BookRepository brep = new BookRepository(); AuthorRepository arep = new AuthorRepository(); // GET: Book public ActionResult ListBooks() { return View(brep.SelectAll()); } public ActionResult AddBook() { return View(Tuple.Create(arep.SelectAll(), new Book())); } [HttpPost] public ActionResult AddBook([Bind(Prefix = "Item2")] Book item) { brep.Add(item); return RedirectToAction("ListBooks"); } public ActionResult DeleteBook(int id) { brep.Delete(brep.GetByID(id)); return RedirectToAction("ListBooks"); } public ActionResult UpdateBook(int id) { return View(Tuple.Create(arep.SelectAll(), brep.GetByID(id))); } [HttpPost] public ActionResult UpdateBook([Bind(Prefix = "Item2")] Book item) { brep.Update(item); return RedirectToAction("ListBooks"); } } }
using System; namespace Matrizes { class Program { static void Main(string[] args) { string[] vect = Console.ReadLine().Split(' '); int M = int.Parse(vect[0]); int N = int.Parse(vect[1]); int[,] Matriz = new int[M, N]; for (int i = 0; i < M; i++) { string[] vect2 = Console.ReadLine().Split(' '); for (int j = 0; j < N; j++) { Matriz[i, j] = int.Parse(vect2[j]); } } Console.Write("Digite um Numero Pertencente a Matriz: "); int Valor = int.Parse(Console.ReadLine()); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (Matriz[i, j] == Valor) { Console.WriteLine($"Posicion {i},{j}:"); if (j > 0) { Console.WriteLine("Left: " + Matriz[i, (j - 1)]); } if (i >= 0) { Console.WriteLine("Right: " + Matriz[i, (j + 1)]); } if (j < N - 1) { Console.WriteLine("Up: " + Matriz[(i + 1), j]); } if (i < M - 1) { Console.WriteLine("Down: " + Matriz[(i - 1), j]); } } } } } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game; using Triton.Game.Mono; [Attribute38("SoundManager")] public class SoundManager : MonoBehaviour { public SoundManager(IntPtr address) : this(address, "SoundManager") { } public SoundManager(IntPtr address, string className) : base(address, className) { } public void AnimateBeginningDuckState(DuckState state) { object[] objArray1 = new object[] { state }; base.method_8("AnimateBeginningDuckState", objArray1); } public void AnimateRestoringDuckState(DuckState state) { object[] objArray1 = new object[] { state }; base.method_8("AnimateRestoringDuckState", objArray1); } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void ChangeDuckState(DuckState state, DuckMode mode) { object[] objArray1 = new object[] { state, mode }; base.method_8("ChangeDuckState", objArray1); } public void CleanInactiveSources() { base.method_8("CleanInactiveSources", Array.Empty<object>()); } public SoundPlaybackLimitClipDef FindClipDefInPlaybackDef(string clipName, SoundPlaybackLimitDef def) { object[] objArray1 = new object[] { clipName, def }; return base.method_14<SoundPlaybackLimitClipDef>("FindClipDefInPlaybackDef", objArray1); } public SoundDuckingDef FindDuckingDefForCategory(SoundCategory cat) { object[] objArray1 = new object[] { cat }; return base.method_14<SoundDuckingDef>("FindDuckingDefForCategory", objArray1); } public void GarbageCollectBundles() { base.method_8("GarbageCollectBundles", Array.Empty<object>()); } public static SoundManager Get() { return MonoClass.smethod_15<SoundManager>(TritonHs.MainAssemblyPath, "", "SoundManager", "Get", Array.Empty<object>()); } public SoundConfig GetConfig() { return base.method_14<SoundConfig>("GetConfig", Array.Empty<object>()); } public List<MusicTrack> GetCurrentAmbienceTracks() { Class267<MusicTrack> class2 = base.method_14<Class267<MusicTrack>>("GetCurrentAmbienceTracks", Array.Empty<object>()); if (class2 != null) { return class2.method_25(); } return null; } public List<MusicTrack> GetCurrentMusicTracks() { Class267<MusicTrack> class2 = base.method_14<Class267<MusicTrack>>("GetCurrentMusicTracks", Array.Empty<object>()); if (class2 != null) { return class2.method_25(); } return null; } public float GetDuckingVolume(SoundCategory cat) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.ValueType }; object[] objArray1 = new object[] { cat }; return base.method_10<float>("GetDuckingVolume", enumArray1, objArray1); } public uint GetNextDuckStateTweenId() { return base.method_11<uint>("GetNextDuckStateTweenId", Array.Empty<object>()); } public int GetNextSourceId() { return base.method_11<int>("GetNextSourceId", Array.Empty<object>()); } public GameObject GetPlaceholderSound() { return base.method_14<GameObject>("GetPlaceholderSound", Array.Empty<object>()); } public void ImmediatelyKillMusicAndAmbience() { base.method_8("ImmediatelyKillMusicAndAmbience", Array.Empty<object>()); } public void InitializeOptions() { base.method_8("InitializeOptions", Array.Empty<object>()); } public bool IsInitialized() { return base.method_11<bool>("IsInitialized", Array.Empty<object>()); } public bool Load(string soundName) { object[] objArray1 = new object[] { soundName }; return base.method_11<bool>("Load", objArray1); } public void LoadAndPlay(string soundName) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String }; object[] objArray1 = new object[] { soundName }; base.method_9("LoadAndPlay", enumArray1, objArray1); } public void LoadAndPlay(string soundName, float volume) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.R4 }; object[] objArray1 = new object[] { soundName, volume }; base.method_9("LoadAndPlay", enumArray1, objArray1); } public void LoadAndPlay(string soundName, GameObject parent) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.Class }; object[] objArray1 = new object[] { soundName, parent }; base.method_9("LoadAndPlay", enumArray1, objArray1); } public void LoadAndPlay(string soundName, GameObject parent, float volume) { object[] objArray1 = new object[] { soundName, parent, volume }; base.method_9("LoadAndPlay", new Class272.Enum20[] { Class272.Enum20.String }, objArray1); } public void NukeAmbienceAndStopPlayingCurrentTrack() { base.method_8("NukeAmbienceAndStopPlayingCurrentTrack", Array.Empty<object>()); } public void NukeMusicAndAmbiencePlaylists() { base.method_8("NukeMusicAndAmbiencePlaylists", Array.Empty<object>()); } public void NukeMusicAndStopPlayingCurrentTrack() { base.method_8("NukeMusicAndStopPlayingCurrentTrack", Array.Empty<object>()); } public void NukePlaylistsAndStopPlayingCurrentTracks() { base.method_8("NukePlaylistsAndStopPlayingCurrentTracks", Array.Empty<object>()); } public void OnAmbienceLoaded(string name, GameObject go, object callbackData) { object[] objArray1 = new object[] { name, go, callbackData }; base.method_8("OnAmbienceLoaded", objArray1); } public void OnAppFocusChanged(bool focus, object userData) { object[] objArray1 = new object[] { focus, userData }; base.method_8("OnAppFocusChanged", objArray1); } public void OnBackgroundSoundOptionChanged(Triton.Game.Mapping.Option option, object prevValue, bool existed, object userData) { object[] objArray1 = new object[] { option, prevValue, existed, userData }; base.method_8("OnBackgroundSoundOptionChanged", objArray1); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void OnDuckStateBeginningComplete(DuckState state) { object[] objArray1 = new object[] { state }; base.method_8("OnDuckStateBeginningComplete", objArray1); } public void OnDuckStateRestoringComplete(DuckState state) { object[] objArray1 = new object[] { state }; base.method_8("OnDuckStateRestoringComplete", objArray1); } public void OnEnabledOptionChanged(Triton.Game.Mapping.Option option, object prevValue, bool existed, object userData) { object[] objArray1 = new object[] { option, prevValue, existed, userData }; base.method_8("OnEnabledOptionChanged", objArray1); } public void OnLoadAndPlaySoundLoaded(string name, GameObject go, object callbackData) { object[] objArray1 = new object[] { name, go, callbackData }; base.method_8("OnLoadAndPlaySoundLoaded", objArray1); } public void OnLoadSoundLoaded(string name, GameObject go, object callbackData) { object[] objArray1 = new object[] { name, go, callbackData }; base.method_8("OnLoadSoundLoaded", objArray1); } public void OnMasterEnabledOptionChanged(Triton.Game.Mapping.Option option, object prevValue, bool existed, object userData) { object[] objArray1 = new object[] { option, prevValue, existed, userData }; base.method_8("OnMasterEnabledOptionChanged", objArray1); } public void OnMasterVolumeOptionChanged(Triton.Game.Mapping.Option option, object prevValue, bool existed, object userData) { object[] objArray1 = new object[] { option, prevValue, existed, userData }; base.method_8("OnMasterVolumeOptionChanged", objArray1); } public void OnMusicLoaded(string name, GameObject go, object callbackData) { object[] objArray1 = new object[] { name, go, callbackData }; base.method_8("OnMusicLoaded", objArray1); } public void OnSceneLoaded(SceneMgr.Mode mode, Scene scene, object userData) { object[] objArray1 = new object[] { mode, scene, userData }; base.method_8("OnSceneLoaded", objArray1); } public void OnVolumeOptionChanged(Triton.Game.Mapping.Option option, object prevValue, bool existed, object userData) { object[] objArray1 = new object[] { option, prevValue, existed, userData }; base.method_8("OnVolumeOptionChanged", objArray1); } public bool PlayNextAmbience() { return base.method_11<bool>("PlayNextAmbience", Array.Empty<object>()); } public bool PlayNextMusic() { return base.method_11<bool>("PlayNextMusic", Array.Empty<object>()); } public void PrintAllCategorySources() { base.method_8("PrintAllCategorySources", Array.Empty<object>()); } public DuckState RegisterDuckState(object trigger, SoundDuckedCategoryDef duckedCatDef) { object[] objArray1 = new object[] { trigger, duckedCatDef }; return base.method_14<DuckState>("RegisterDuckState", objArray1); } public void SetConfig(SoundConfig config) { object[] objArray1 = new object[] { config }; base.method_8("SetConfig", objArray1); } public void Start() { base.method_8("Start", Array.Empty<object>()); } public bool StartDucking(SoundDucker ducker) { object[] objArray1 = new object[] { ducker }; return base.method_11<bool>("StartDucking", objArray1); } public void StopCurrentAmbienceTrack() { base.method_8("StopCurrentAmbienceTrack", Array.Empty<object>()); } public void StopCurrentMusicTrack() { base.method_8("StopCurrentMusicTrack", Array.Empty<object>()); } public void StopDucking(SoundDucker ducker) { object[] objArray1 = new object[] { ducker }; base.method_8("StopDucking", objArray1); } public void UnloadSoundBundle(string name) { object[] objArray1 = new object[] { name }; base.method_8("UnloadSoundBundle", objArray1); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public void UpdateAllCategoryVolumes() { base.method_8("UpdateAllCategoryVolumes", Array.Empty<object>()); } public void UpdateAllMutes() { base.method_8("UpdateAllMutes", Array.Empty<object>()); } public void UpdateAppMute() { base.method_8("UpdateAppMute", Array.Empty<object>()); } public void UpdateCategoryMute(SoundCategory cat) { object[] objArray1 = new object[] { cat }; base.method_8("UpdateCategoryMute", objArray1); } public void UpdateCategoryVolume(SoundCategory cat) { object[] objArray1 = new object[] { cat }; base.method_8("UpdateCategoryVolume", objArray1); } public void UpdateDuckStates() { base.method_8("UpdateDuckStates", Array.Empty<object>()); } public void UpdateGeneratedSources() { base.method_8("UpdateGeneratedSources", Array.Empty<object>()); } public void UpdateMusicAndAmbience() { base.method_8("UpdateMusicAndAmbience", Array.Empty<object>()); } public void UpdateMusicAndSources() { base.method_8("UpdateMusicAndSources", Array.Empty<object>()); } public void UpdateSourceBundles() { base.method_8("UpdateSourceBundles", Array.Empty<object>()); } public void UpdateSourceExtensionMappings() { base.method_8("UpdateSourceExtensionMappings", Array.Empty<object>()); } public void UpdateSources() { base.method_8("UpdateSources", Array.Empty<object>()); } public void UpdateSourcesByCategory() { base.method_8("UpdateSourcesByCategory", Array.Empty<object>()); } public void UpdateSourcesByClipName() { base.method_8("UpdateSourcesByClipName", Array.Empty<object>()); } public bool m_ambienceIsAboutToPlay { get { return base.method_2<bool>("m_ambienceIsAboutToPlay"); } } public int m_ambienceTrackIndex { get { return base.method_2<int>("m_ambienceTrackIndex"); } } public List<MusicTrack> m_ambienceTracks { get { Class267<MusicTrack> class2 = base.method_3<Class267<MusicTrack>>("m_ambienceTracks"); if (class2 != null) { return class2.method_25(); } return null; } } public SoundConfig m_config { get { return base.method_3<SoundConfig>("m_config"); } } public List<ExtensionMapping> m_extensionMappings { get { Class267<ExtensionMapping> class2 = base.method_3<Class267<ExtensionMapping>>("m_extensionMappings"); if (class2 != null) { return class2.method_25(); } return null; } } public uint m_frame { get { return base.method_2<uint>("m_frame"); } } public bool m_musicIsAboutToPlay { get { return base.method_2<bool>("m_musicIsAboutToPlay"); } } public int m_musicTrackIndex { get { return base.method_2<int>("m_musicTrackIndex"); } } public List<MusicTrack> m_musicTracks { get { Class267<MusicTrack> class2 = base.method_3<Class267<MusicTrack>>("m_musicTracks"); if (class2 != null) { return class2.method_25(); } return null; } } public bool m_mute { get { return base.method_2<bool>("m_mute"); } } public uint m_nextDuckStateTweenId { get { return base.method_2<uint>("m_nextDuckStateTweenId"); } } public int m_nextSourceId { get { return base.method_2<int>("m_nextSourceId"); } } [Attribute38("SoundManager.BundleInfo")] public class BundleInfo : MonoClass { public BundleInfo(IntPtr address) : this(address, "BundleInfo") { } public BundleInfo(IntPtr address, string className) : base(address, className) { } public bool CanGarbageCollect() { return base.method_11<bool>("CanGarbageCollect", Array.Empty<object>()); } public void EnableGarbageCollect(bool enable) { object[] objArray1 = new object[] { enable }; base.method_8("EnableGarbageCollect", objArray1); } public string GetName() { return base.method_13("GetName", Array.Empty<object>()); } public int GetRefCount() { return base.method_11<int>("GetRefCount", Array.Empty<object>()); } public bool IsGarbageCollectEnabled() { return base.method_11<bool>("IsGarbageCollectEnabled", Array.Empty<object>()); } public void SetName(string name) { object[] objArray1 = new object[] { name }; base.method_8("SetName", objArray1); } public bool m_garbageCollect { get { return base.method_2<bool>("m_garbageCollect"); } } public string m_name { get { return base.method_4("m_name"); } } } public enum DuckMode { IDLE, BEGINNING, HOLD, RESTORING } [Attribute38("SoundManager.DuckState")] public class DuckState : MonoClass { public DuckState(IntPtr address) : this(address, "DuckState") { } public DuckState(IntPtr address, string className) : base(address, className) { } public SoundDuckedCategoryDef GetDuckedDef() { return base.method_14<SoundDuckedCategoryDef>("GetDuckedDef", Array.Empty<object>()); } public SoundManager.DuckMode GetMode() { return base.method_11<SoundManager.DuckMode>("GetMode", Array.Empty<object>()); } public object GetTrigger() { return base.method_14<object>("GetTrigger", Array.Empty<object>()); } public SoundCategory GetTriggerCategory() { return base.method_11<SoundCategory>("GetTriggerCategory", Array.Empty<object>()); } public string GetTweenName() { return base.method_13("GetTweenName", Array.Empty<object>()); } public float GetVolume() { return base.method_11<float>("GetVolume", Array.Empty<object>()); } public bool IsTrigger(object trigger) { object[] objArray1 = new object[] { trigger }; return base.method_11<bool>("IsTrigger", objArray1); } public bool IsTriggerAlive() { return base.method_11<bool>("IsTriggerAlive", Array.Empty<object>()); } public void SetDuckedDef(SoundDuckedCategoryDef def) { object[] objArray1 = new object[] { def }; base.method_8("SetDuckedDef", objArray1); } public void SetMode(SoundManager.DuckMode mode) { object[] objArray1 = new object[] { mode }; base.method_8("SetMode", objArray1); } public void SetTrigger(object trigger) { object[] objArray1 = new object[] { trigger }; base.method_8("SetTrigger", objArray1); } public void SetTweenName(string name) { object[] objArray1 = new object[] { name }; base.method_8("SetTweenName", objArray1); } public void SetVolume(float volume) { object[] objArray1 = new object[] { volume }; base.method_8("SetVolume", objArray1); } public SoundDuckedCategoryDef m_duckedDef { get { return base.method_3<SoundDuckedCategoryDef>("m_duckedDef"); } } public SoundManager.DuckMode m_mode { get { return base.method_2<SoundManager.DuckMode>("m_mode"); } } public object m_trigger { get { return base.method_3<object>("m_trigger"); } } public SoundCategory m_triggerCategory { get { return base.method_2<SoundCategory>("m_triggerCategory"); } } public string m_tweenName { get { return base.method_4("m_tweenName"); } } public float m_volume { get { return base.method_2<float>("m_volume"); } } } [Attribute38("SoundManager.ExtensionMapping")] public class ExtensionMapping : MonoClass { public ExtensionMapping(IntPtr address) : this(address, "ExtensionMapping") { } public ExtensionMapping(IntPtr address, string className) : base(address, className) { } public SoundManager.SourceExtension Extension { get { return base.method_3<SoundManager.SourceExtension>("Extension"); } } } [Attribute38("SoundManager.SoundLoadContext")] public class SoundLoadContext : MonoClass { public SoundLoadContext(IntPtr address) : this(address, "SoundLoadContext") { } public SoundLoadContext(IntPtr address, string className) : base(address, className) { } public bool m_haveCallback { get { return base.method_2<bool>("m_haveCallback"); } } public GameObject m_parent { get { return base.method_3<GameObject>("m_parent"); } } public SceneMgr.Mode m_sceneMode { get { return base.method_2<SceneMgr.Mode>("m_sceneMode"); } } public object m_userData { get { return base.method_3<object>("m_userData"); } } public float m_volume { get { return base.method_2<float>("m_volume"); } } } [Attribute38("SoundManager.SourceExtension")] public class SourceExtension : MonoClass { public SourceExtension(IntPtr address) : this(address, "SourceExtension") { } public SourceExtension(IntPtr address, string className) : base(address, className) { } public string m_bundleName { get { return base.method_4("m_bundleName"); } } public float m_codePitch { get { return base.method_2<float>("m_codePitch"); } } public float m_codeVolume { get { return base.method_2<float>("m_codeVolume"); } } public float m_defPitch { get { return base.method_2<float>("m_defPitch"); } } public float m_defVolume { get { return base.method_2<float>("m_defVolume"); } } public bool m_ducking { get { return base.method_2<bool>("m_ducking"); } } public int m_id { get { return base.method_2<int>("m_id"); } } public bool m_paused { get { return base.method_2<bool>("m_paused"); } } public float m_sourcePitch { get { return base.method_2<float>("m_sourcePitch"); } } public float m_sourceVolume { get { return base.method_2<float>("m_sourceVolume"); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 自动闪烁 /// </summary> [RequireComponent(typeof(SpriteRenderer))] public class ItemShining : MonoBehaviour { private SpriteRenderer sr; public float interval = 0.5f; private float timer; private void Start() { sr = GetComponent<SpriteRenderer>(); timer = interval; } private void Update() { timer -= Time.deltaTime; if (timer <= 0) { sr.enabled = !sr.enabled; timer = interval; } } }
using System; using System.Collections.Generic; using System.Linq; namespace PuddingWolfLoader.Framework.Container { class ViewContainer { private static Dictionary<Type, object> _views = new Dictionary<Type, object>(); public static object GetViewInstance<T>() { var type = typeof(T); return GetViewInstance(type); } public static object GetViewInstance(Type type) { if (_views.ContainsKey(type)) { if (_views[type] is null) { RegisterViewInstance(type); } return _views[type]; } else { RegisterViewInstance(type); } return _views[type]; } public static void RegisterViewInstance(Type type) { if (_views.ContainsKey(type)) return; _views.Add(type, Activator.CreateInstance(type) ?? new object()); } public static object GetViewInstance(int id) { Type type; if (id >= _views.Count) { //数组越界 type = _views.ToList().First().Key; } else { type = _views.ToList()[id].Key; } return GetViewInstance(type); } } }
//创建数据库,使用测试数据初始化数据库 //该文件中的代码 首先检查是否有用户数据在数据库中,如果没有的话,就可以假定数据库是新建的,然后使用测试数据进行填充 //代码中使用数组存放测试数据而不是使用List<T>集合是为了优化性能 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NaturalDisasterDatabaseWebsite.Models; namespace NaturalDisasterDatabaseWebsite.Data { public static class DBInitializer { public static void Initialize(NaturalDisasterDatabaseWebsiteContext context) { //EnsureCreated方法自动创建数据库 context.Database.EnsureCreated(); // 查找用户 if (context.users.Any()) { return; // DB 已有测试(基本)数据 } var users = new UsersViewModel[] { new UsersViewModel{username="admin",password="123456",sex="女",email="2108123704@qq.com",status="管理员",img="head-default.png",telephone="18877524840",workplace="广西师范大学",occupation="Web前端",address="广西师范大学雁山校区"}, new UsersViewModel{username="haha",password="185662",sex="男",email="2108123704@qq.com",status="普通用户",img="head-default.png",telephone="18877524840",workplace="广西师范大学",occupation="运维工程师",address="广西师范大学雁山校区"} }; foreach (UsersViewModel u in users) { context.users.Add(u); } context.SaveChanges(); var essays = new Science_essayViewModel[] { new Science_essayViewModel{ID=1,title="习近平总书记关于防灾减灾救灾重要论述摘录",author="灾协",source="云南防震减灾网",fb_time=DateTime.Parse("2019-07-26 19:53:00"),wz_content="要坚持抗震救灾工作和经济社会发展两手抓、两不误,大力弘扬伟大抗震救灾精神,大力发挥各级党组织领导核心和战斗堡垒作用、广大党员先锋模范作用,引导灾区群众广泛开展自力更生、生产自救活动,在中央和四川省大力支持下,积极发展生产、建设家园,用自己的双手创造幸福美好的生活",wz_style="科普",state="已发布",userID=1}, new Science_essayViewModel {ID=2,title="古人如何应对洪涝灾害",author="灾协",source="中国水运报",fb_time=DateTime.Parse("2019-11-29 14:53:00"),wz_content="今年入夏以来,从南到北各地水灾多发,抗洪救灾成为舆论热点。事实上,洪涝灾害自古以来就是人类最常面对的自然灾害。因此,人类历史也是一部与洪涝灾害斗争的历史。那么,我国古代在条件有限的情况下是如何应对洪涝灾害呢?",wz_style="科普",state="待审核",userID=2} }; foreach (Science_essayViewModel s in essays) { context.Science_essay.Add(s); } context.SaveChanges(); var fMsgs = new Forum_msgViewModel[] { new Forum_msgViewModel{ID=1,comment="习大大的胸怀是真的非常宽广!赞赞赞~~~",comment_time=DateTime.Parse("2020-1-6 14:24:00"),userID=2,essayID=1}, new Forum_msgViewModel{ID=1,comment="古人头脑真睿智啊~赞赞赞~",comment_time=DateTime.Parse("2019-12-28 10:43:00"),userID=5,essayID=2}, }; foreach (Forum_msgViewModel e in fMsgs) { context.Forum_msg.Add(e); } context.SaveChanges(); } } }
using UnityEngine; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Debug = UnityEngine.Debug; namespace CoreEditor.Drawing { public static class ReduceColor { public class ReduceColorParams { public string InputFile; public int NumberOfColors; public override string ToString() { return string.Format(@" --force --ext {0} --speed 1 {1} ""{2}""", System.IO.Path.GetExtension(InputFile), NumberOfColors, InputFile ); } } public static string Path { get { switch ( Application.platform ) { case RuntimePlatform.OSXEditor: return Directory.GetCurrentDirectory() + @"/ExternalTools/Mac/pngquant"; case RuntimePlatform.WindowsEditor: return Directory.GetCurrentDirectory() + @"\ExternalTools\Windows\pngquant.exe"; default: throw new System.PlatformNotSupportedException(); } } } public static bool IsInstalled { get { return File.Exists( Path ); } } public static bool RunCommand( ReduceColorParams paramObj ) { return RunCommand( paramObj.ToString() ); } public static bool RunCommand( string command ) { if ( IsInstalled == false ) { Debug.LogError( "Cannot find " + Path ); return false; } var proc = new Process(); proc.StartInfo.FileName = Path; proc.StartInfo.Arguments = command; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.EnvironmentVariables["PATH"] = System.Environment.GetEnvironmentVariable("PATH"); proc.Start(); var output = new List<string>(); string line; while ( ( line = proc.StandardOutput.ReadLine() ) != null ) { output.Add( line ); } var error = new List<string>(); while ( ( line = proc.StandardError.ReadLine() ) != null ) { error.Add( line ); } proc.WaitForExit(); if ( error.Count > 0 ) Debug.LogWarning( string.Join( "\n", error.ToArray() ) ); return proc.ExitCode == 0; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpaceShip : MonoBehaviour { public bool started = false; public SpriteRenderer old; public GameObject stick; public GameObject stars; public logic gamelogic; public float waittime1 = 3f; public float waittime2 = 2f; public float waittime3 = 5f; public Vector3 moverate; public void Begin() { started = true; } void FixedUpdate() { if (started) { waittime1 -= Time.fixedDeltaTime; if (waittime1 <= 0) { waittime2 -= Time.fixedDeltaTime; stars.SetActive(true); if (waittime2 <= 0) { old.enabled = false; stick.SetActive(true); transform.position = transform.position + moverate; waittime3 -= Time.fixedDeltaTime; if (waittime3 <= 0) { gamelogic.Win(); } } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class ItemsManager : MonoBehaviour { public static ItemsManager itemsManagerInstance; [HideInInspector] public GameObject itemsHolder; public Transform baseItemPrefab; public List<Item> items; private Dictionary<string, Item> itemDictionary = new Dictionary<string, Item>(); private void Awake() { //Nos aseguramos de que solo haya 1 GameManager if (itemsManagerInstance == null) { itemsManagerInstance = this; } else if (itemsManagerInstance != this) { Destroy(gameObject); } ClearItems(); } public void SetupItems() { itemsHolder = GameObject.Find("ItemsHolder"); if (itemsHolder != null) { foreach (Transform child in itemsHolder.transform) { Destroy(child.gameObject); } } else { itemsHolder = new GameObject("ItemsHolder"); } LoadItems(); } private void LoadItems() { string lvlName = "Level" + GameManager.instance.level; Item[] currentLevelItems = Resources.LoadAll<Item>(lvlName + "/Items"); foreach (Item item in currentLevelItems) { Item currentItem = Instantiate(item); items.Add(currentItem); //añadimos los items del nivel a la lista que contiene los items de los niveles anteriores itemDictionary.Add(item.itemName, item); } } public Item GetItemByName(string itemName) { return itemDictionary[itemName]; } public Item GetItemByRarity(int minRarity, int maxRarity) { int rarity = GetRarity(minRarity, maxRarity); List<Item> availableItems = new List<Item>(); foreach (Item item in items) { if (item.rarity == rarity && item.amount > 0) { availableItems.Add(item); } } if (availableItems.Count != 0) { int r = Random.Range(0, availableItems.Count); availableItems[r].amount--; return availableItems[r]; } else { return null; } } private int GetRarity(int minRarity, int maxRarity) { float minRandom = 0; float maxRandom = 1f; switch (minRarity) { case 1: maxRandom = 1f; break; case 2: maxRandom = 0.549f; break; case 3: maxRandom = 0.249f; break; case 4: maxRandom = 0.099f; break; case 5: maxRandom = 0.029f; break; } switch (maxRarity) { case 1: minRandom = 0.55f; break; case 2: minRandom = 0.25f; break; case 3: minRandom = 0.1f; break; case 4: minRandom = 0.03f; break; case 5: minRandom = 0; break; } int rarity = 1; if (minRarity != maxRarity) //si son diferentes, calculamos la rareza resultante { float random = Random.Range(minRandom, maxRandom); if (random < 0.03f) //0.03 - 3% rarity = 5; else if (random < 0.1f) //0.07 - 7% rarity = 4; else if (random < 0.25f) //0.15 - 15% rarity = 3; else if (random < 0.55f) //0.3 - 30% rarity = 2; else if (random >= 0.55f) //0.45 - 45% rarity = 1; Debug.Log("Rarity: " + rarity); } else { rarity = minRarity; } return rarity; } public void ClearItems() { items.Clear(); itemDictionary.Clear(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace YuME.GM { public class GMCommandCandidate { public bool InCandiateState { get; set; } private List<string> _autoCompleteList; private int _autoCompleteIndex; public GMCommandCandidate() { _autoCompleteList = new List<string>(); _autoCompleteIndex = 0; } public void Init(string baseCommand) { _autoCompleteList.Clear(); var e = GMCommandRepository.commands.GetEnumerator(); while (e.MoveNext()) { var k = e.Current.Key; if (k.IndexOf(baseCommand) == 0) { _autoCompleteList.Add(k); } } _autoCompleteIndex = 0; } public bool HasCandidate() { return _autoCompleteList.Count != 0; } public string GetNextCandidate() { string s = _autoCompleteList[_autoCompleteIndex]; _autoCompleteIndex = (_autoCompleteIndex + 1) % _autoCompleteList.Count; return s; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.Entities { public class ConfigurationSetting { public bool IsSecure { get; set; } public string Key { get; set; } public string Value { get; set; } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Interactions; using System; using System.Collections.Generic; namespace HOTELpinSight.Pages { public class HotelSearchPage : BasePage { public HotelSearchPage(IWebDriver driver) : base(driver) { } [FindsBy(How = How.Id, Using = "ucPWP_ctl08_55218_lnkGoToBackOffice")] private IWebElement _backOfficeButton; [FindsBy(How = How.Id, Using = "autoSuggest")] private IWebElement _search; //Not sure about the identifiers //Datepickers [FindsBy(How = How.LinkText, Using = "Check-in")] private IWebElement _checkInDatePicker; [FindsBy(How = How.LinkText, Using = "Pick a year from the dropdown")] private IWebElement _checkInDatePickerYear; [FindsBy(How = How.LinkText, Using = "Pick a month from the dropdown")] private IWebElement _checkInDatePickerMonth; [FindsBy(How = How.LinkText, Using = "Go to the previous month")] private IWebElement _checkInDatePickerNavBack; [FindsBy(How = How.LinkText, Using = "Go to the next month")] private IWebElement _checkInDatePickerNavNext; [FindsBy(How = How.LinkText, Using = "Check-out")] private IWebElement _checkOutDatePicker; [FindsBy(How = How.Id, Using = "search")] private IWebElement _searchButton; public void Search(string value) { _search.SendKeys(value); } public void SelectCheckIn() { Actions selectCheckIn = new Actions(_driver); selectCheckIn.MoveToElement(_checkInDatePicker); _checkInDatePicker.Click(); if(_checkInDatePickerYear.Text != "2018") new SelectElement(_checkInDatePickerYear).SelectByValue("2018"); new SelectElement(_checkInDatePickerMonth).SelectByValue("May"); IList<IWebElement> rows = _checkInDatePicker.FindElements(By.TagName("tr")); IList<IWebElement> columns = _checkInDatePicker.FindElements(By.TagName("td")); foreach(IWebElement cell in columns) { if (cell.ToString().Equals("6")) { cell.FindElement(By.LinkText("6")).Click(); break; } } selectCheckIn.Perform(); } /* public void SelectCheckOut() { Actions selectCheckOut = new Actions(_driver); selectCheckOut.MoveToElement(_checkOutDatePicker); _checkOutDatePicker.Click(); if (_checkOutDatePicker.Text != "2018") new SelectElement(_checkOutDatePickerYear).SelectByValue("2018"); new SelectElement() } */ public void ClickSearchHotel() { _searchButton.Click(); } public void EnsurePageIsLoaded() { WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(30)); wait.Until(ExpectedConditions.ElementToBeClickable(_backOfficeButton)); } public SearchingPage Login() { _searchButton.Click(); return new SearchingPage(_driver); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; namespace LotteryWebService { public class TicketInfo { public int TicketCount{get;set;} public String TicketNo { get; set; } public int PriceAmount { get; set; } public int TicketPrice { get; set; } public DateTime CloseDate { get; set; } public int Status { get; set; } public string Error { get; set; } } }
using ServerKinect.Clustering; using ServerKinect.DataSource; using ServerKinect.Shape; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.OpenNI { public class OpenNIClusterDataSource : DataSourceProcessor<ClusterCollection, IntPtr>, IClusterDataSource { private IntSize size; private IClusterFactory clusterFactory; private IDepthPointFilter<IntPtr> filter; public OpenNIClusterDataSource(IDepthPointerDataSource dataSource, ClusterDataSourceSettings settings) : this(dataSource, new KMeansClusterFactory(settings, dataSource.Size), new PointerDepthPointFilter(dataSource.Size, settings.MinimumDepthThreshold, settings.MaximumDepthThreshold, settings.LowerBorder)) { } public OpenNIClusterDataSource(IDepthPointerDataSource dataSource, IClusterFactory clusterFactory, IDepthPointFilter<IntPtr> filter) : base(dataSource) { this.size = dataSource.Size; this.CurrentValue = new ClusterCollection(); this.clusterFactory = clusterFactory; this.filter = filter; } public int Width { get { return this.size.Width; } } public int Height { get { return this.size.Height; } } public IntSize Size { get { return this.size; } } protected override ClusterCollection Process(IntPtr sourceData) { return this.clusterFactory.Create(this.FindPointsWithinDepthRange(sourceData)); } protected virtual unsafe IList<Point> FindPointsWithinDepthRange(IntPtr dataPointer) { return this.filter.Filter(dataPointer); } } }
using ApplicationApp.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApiSite.Controllers { [Authorize] public class ProdutoAPIController : Controller { public readonly InterfaceProductApp _InterfaceProductApp; public readonly InterfaceCompraUsuarioApp _InterfaceCompraUsuarioApp; public ProdutoAPIController(InterfaceProductApp InterfaceProductApp, InterfaceCompraUsuarioApp InterfaceCompraUsuarioApp) { _InterfaceProductApp = InterfaceProductApp; _InterfaceCompraUsuarioApp = InterfaceCompraUsuarioApp; } [HttpGet("/api/ListaProdutos")] public async Task<JsonResult> ListaProdutos(string descricao) { return Json(await _InterfaceProductApp.ListarProdutosComEstoque(descricao)); } } }
using ServerKinect.Shape; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.HandTracking { public class Palm { private Point location; private double distanceToContour; public Palm(Point location, double distanceToContour) { this.location = location; this.distanceToContour = distanceToContour; } public Point Location { get { return this.location; } } public double DistanceToContour { get { return this.distanceToContour; } } } }
namespace OC.Files.ObjectStore { public class S3Signature { } }
using Microsoft.Extensions.DependencyInjection; using Promact.Oauth.Server.Models.ApplicationClasses; using Promact.Oauth.Server.Repository.ProjectsRepository; using Promact.Oauth.Server.Data_Repository; using Xunit; using System; using Promact.Oauth.Server.Models; using System.Collections.Generic; using System.Threading.Tasks; using Promact.Oauth.Server.Constants; using Promact.Oauth.Server.Repository; using Promact.Oauth.Server.Data; using Microsoft.AspNetCore.Identity; namespace Promact.Oauth.Server.Tests { public class ProjectTests : BaseProvider { #region Private Variables private readonly IProjectRepository _projectRepository; private readonly IDataRepository<Project, PromactOauthDbContext> _dataRepository; private readonly IDataRepository<ProjectUser, PromactOauthDbContext> _dataRepositoryProjectUser; private readonly IStringConstant _stringConstant; private readonly IUserRepository _userRepository; private readonly UserManager<ApplicationUser> _userManager; ApplicationUser user = new ApplicationUser(); Project project = new Project(); ProjectUser projectUser = new ProjectUser(); #endregion #region Constructor public ProjectTests() : base() { _projectRepository = serviceProvider.GetService<IProjectRepository>(); _dataRepository = serviceProvider.GetService<IDataRepository<Project, PromactOauthDbContext>>(); _dataRepositoryProjectUser = serviceProvider.GetService<IDataRepository<ProjectUser, PromactOauthDbContext>>(); _stringConstant = serviceProvider.GetService<IStringConstant>(); _userRepository = serviceProvider.GetService<IUserRepository>(); _userManager = serviceProvider.GetService<UserManager<ApplicationUser>>(); Initialize(); } #endregion #region Test Case /// <summary> /// This test case to add a new project /// </summary> [Fact, Trait("Category", "Required")] public async Task AddProjectAsync() { var id = await GetProjectMockData(); var project = _dataRepository.FirstOrDefault(x => x.Id == id); Assert.NotNull(project); } /// <summary> /// This test case for the add user and project in userproject table /// </summary> [Fact, Trait("Category", "Required")] public async Task AddUserProject() { await GetProjectUserMockData(); var ProjectUser = _dataRepositoryProjectUser.Fetch(x => x.ProjectId == 1); Assert.NotNull(ProjectUser); } /// <summary> /// This test case for gets project By Id /// </summary> [Fact, Trait("Category", "Required")] public async Task GetProjectById() { var id = await GetProjectMockData(); await GetProjectUserMockData(); ProjectAc project = await _projectRepository.GetProjectByIdAsync(id); Assert.NotNull(project); } /// <summary> /// This test case for gets project By Id without team leader /// </summary> [Fact, Trait("Category", "Required")] public async Task GetProjectByProjectId() { string userId = await MockOfUserAc(); ProjectAc projectac = new ProjectAc(); projectac.Name = _stringConstant.Name; projectac.IsActive = _stringConstant.IsActive; projectac.CreatedBy = _stringConstant.CreatedBy; projectac.TeamLeader = new UserAc { FirstName = _stringConstant.FirstName }; projectac.TeamLeaderId = userId; var id = await _projectRepository.AddProjectAsync(projectac, _stringConstant.CreatedBy); await GetProjectUserMockData(); ProjectAc project = await _projectRepository.GetProjectByIdAsync(id); Assert.NotNull(project); } /// <summary> /// This test case used to check exception condition /// </summary> /// <returns></returns> [Fact, Trait("Category", "Required")] public async Task GetProjectByIdExcption() { var id = await GetProjectMockData(); await GetProjectUserMockData(); Assert.Throws<AggregateException>(() => _projectRepository.GetProjectByIdAsync(2).Result); } /// <summary> /// This test case edit project /// </summary> [Fact, Trait("Category", "Required")] public async Task EditProject() { List<UserAc> userlist = GetUserListMockData(); var id = await GetProjectMockData(); await GetProjectUserMockData(); ProjectAc projectacSecound = new ProjectAc() { Id = id, Name = _stringConstant.EditName, IsActive = _stringConstant.IsActive, TeamLeader = new UserAc { FirstName = _stringConstant.FirstName }, TeamLeaderId = _stringConstant.TeamLeaderId, CreatedBy = _stringConstant.CreatedBy, CreatedDate = DateTime.UtcNow, ApplicationUsers = userlist }; await _projectRepository.EditProjectAsync(id, projectacSecound, _stringConstant.CreatedBy); var project = _dataRepository.Fetch(x => x.Id == 1); _dataRepositoryProjectUser.Fetch(x => x.ProjectId == 1); Assert.NotNull(project); } /// <summary> /// TThis test case used to check exception condition /// </summary> [Fact, Trait("Category", "Required")] public async Task EditProjectExcption() { List<UserAc> userlist = GetUserListMockData(); var id = await GetProjectMockData(); await GetProjectUserMockData(); ProjectAc projectacSecound = new ProjectAc() { Id = id, Name = _stringConstant.EditName, IsActive = _stringConstant.IsActive, TeamLeader = new UserAc { FirstName = _stringConstant.FirstName }, TeamLeaderId = _stringConstant.TeamLeaderId, CreatedBy = _stringConstant.CreatedBy, CreatedDate = DateTime.Now, ApplicationUsers = userlist }; Assert.Throws<AggregateException>(() => _projectRepository.EditProjectAsync(2, projectacSecound, _stringConstant.CreatedBy).Result); } /// <summary> /// This test case for the check duplicate project /// </summary> [Fact, Trait("Category", "Required")] public async Task CheckDuplicateNegative() { ProjectAc projectAc = MockOfProjectAc(); await _projectRepository.AddProjectAsync(projectAc, _stringConstant.CreatedBy); var project = await _projectRepository.CheckDuplicateProjectAsync(projectAc); Assert.Null(project.Name); } /// <summary> /// This test case for the check duplicate where project name and slack channel name both are already in database. /// </summary> [Fact, Trait("Category", "Required")] public async Task CheckDuplicateProject() { List<UserAc> userlist = GetUserListMockData(); await GetProjectMockData(); ProjectAc projectacSecound = new ProjectAc() { Id = 5, Name = _stringConstant.Name, IsActive = true, TeamLeader = new UserAc { FirstName = _stringConstant.FirstName }, TeamLeaderId = _stringConstant.TeamLeaderId, CreatedBy = _stringConstant.CreatedBy, CreatedDate = DateTime.UtcNow, ApplicationUsers = userlist }; var project = await _projectRepository.CheckDuplicateProjectAsync(projectacSecound); Assert.Null(project.Name); } /// <summary> /// This test case for the check duplicate where project name and slack channel name both not in database. /// </summary> [Fact, Trait("Category", "Required")] public async Task TestCheckDuplicateNegative() { List<UserAc> userlist = GetUserListMockData(); await GetProjectMockData(); ProjectAc projectacSecound = new ProjectAc() { Id = 5, Name = _stringConstant.LastName, IsActive = true, TeamLeader = new UserAc { FirstName = _stringConstant.FirstName }, TeamLeaderId = _stringConstant.TeamLeaderId, CreatedBy = _stringConstant.CreatedBy, CreatedDate = DateTime.UtcNow, ApplicationUsers = userlist }; var project = await _projectRepository.CheckDuplicateProjectAsync(projectacSecound); Assert.NotNull(project.Name); } /// <summary> /// This test case for the get all projects /// </summary> [Fact, Trait("Category", "Required")] public async Task GetAllProject() { var id = await MockOfUserAc(); ProjectAc projectAc = MockOfProjectAc(); projectAc.TeamLeaderId = id; projectAc.CreatedBy = id; var projectId = await _projectRepository.AddProjectAsync(projectAc, id); IEnumerable<ProjectAc> projects = await _projectRepository.GetAllProjectsAsync(); Assert.NotNull(projects); } /// <summary> /// This test case for the get all projects without Team leader /// </summary> [Fact, Trait("Category", "Required")] public async Task GetAllProjects() { var id = await MockOfUserAc(); ProjectAc projectAc = MockOfProjectAc(); projectAc.TeamLeaderId = ""; projectAc.CreatedBy = id; var projectId = await _projectRepository.AddProjectAsync(projectAc, id); IEnumerable<ProjectAc> projects = await _projectRepository.GetAllProjectsAsync(); Assert.NotNull(projects); } /// <summary> /// Fetch the project of the given Team leader /// </summary> /// <returns></returns> [Fact, Trait("Category", "A")] public async Task GetAllProjectForUserAsync() { var userId = await MockOfUserAc(); ProjectAc projectAc = MockOfProjectAc(); projectAc.TeamLeaderId = userId; await _projectRepository.AddProjectAsync(projectAc, _stringConstant.CreatedBy); var project = await _projectRepository.GetAllProjectForUserAsync(userId); Assert.NotNull(projectAc); } /// <summary> /// Fetch the project of the given user /// </summary> /// <returns></returns> [Fact, Trait("Category", "A")] public async Task GetAllProjectForUserAsyncForUser() { await GetProjectUserMockData(); var project = await _projectRepository.GetAllProjectForUserAsync(_stringConstant.UserId); Assert.NotNull(project); } /// <summary> /// Test case to check GetProjectsWithUsers /// </summary> [Fact, Trait("Category", "Required")] public async void TestGetProjectsWithUsers() { string id = await CreateMockAndUserAsync(); ProjectAc project = new ProjectAc() { Name = _stringConstant.Name, IsActive = _stringConstant.IsActive, TeamLeaderId = id, CreatedBy = _stringConstant.CreatedBy, }; await _projectRepository.AddProjectAsync(project, _stringConstant.CreatedBy); var projectUsers = await _projectRepository.GetProjectsWithUsersAsync(); Assert.NotNull(projectUsers); } /// <summary> /// Test case to check GetProjectDetails /// </summary> [Fact, Trait("Category", "Required")] public async void TestGetProjectDetails() { string id = await CreateMockAndUserAsync(); ProjectAc project = new ProjectAc() { Name = _stringConstant.Name, IsActive = _stringConstant.IsActive, TeamLeaderId = id, CreatedBy = _stringConstant.CreatedBy, }; var projectId = await _projectRepository.AddProjectAsync(project, _stringConstant.CreatedBy); var projectDetails = await _projectRepository.GetProjectDetailsAsync(projectId); Assert.Equal(projectDetails.Name, _stringConstant.Name); } /// <summary> /// Test cases to check the functionality of GetListOfProjectsEnrollmentOfUserByUserIdAsync /// </summary> /// <returns></returns> [Fact, Trait("Category", "Required")] public async Task GetListOfProjectsEnrollmentOfUserByUserIdAsync() { var userId = await AddUser(); await AddProjectAndProjectUserAsync(); var result = await _projectRepository.GetListOfProjectsEnrollmentOfUserByUserIdAsync(userId); Assert.Equal(result.Count, 1); } /// <summary> /// Test cases to check the functionality of GetListOfProjectsEnrollmentOfUserByUserIdAsync /// </summary> /// <returns></returns> [Fact, Trait("Category", "Required")] public async Task GetListOfTeamMemberByProjectIdAsync() { await AddUser(); var projectId = await AddProjectAndProjectUserAsync(); var result = await _projectRepository.GetListOfTeamMemberByProjectIdAsync(projectId); Assert.Equal(result.Count, 1); } #endregion #region private methods private void Initialize() { user.Email = _stringConstant.EmailForTest; user.UserName = _stringConstant.EmailForTest; project.CreatedBy = _stringConstant.UserId; project.CreatedDateTime = DateTime.UtcNow; project.IsActive = true; project.Name = _stringConstant.Name; project.TeamLeaderId = _stringConstant.UserId; projectUser.CreatedBy = _stringConstant.CreatedBy; projectUser.CreatedDateTime = DateTime.UtcNow; } /// <summary> /// mock data of project /// </summary> /// <returns></returns> private async Task<int> GetProjectMockData() { ProjectAc projectac = new ProjectAc(); projectac.Name = _stringConstant.Name; projectac.IsActive = _stringConstant.IsActive; projectac.CreatedBy = _stringConstant.CreatedBy; return await _projectRepository.AddProjectAsync(projectac, _stringConstant.CreatedBy); } /// <summary> /// mock data of projectuser. /// </summary> /// <returns></returns> private async Task GetProjectUserMockData() { ProjectUser projectUser = new ProjectUser() { ProjectId = 1, Project = new Project { Name = _stringConstant.Name }, UserId = _stringConstant.UserId, User = new ApplicationUser { FirstName = _stringConstant.FirstName } }; await _projectRepository.AddUserProjectAsync(projectUser); } /// <summary> /// mock of users data. /// </summary> /// <returns></returns> private List<UserAc> GetUserListMockData() { List<UserAc> userlist = new List<UserAc>(); UserAc user = new UserAc() { FirstName = _stringConstant.FirstName }; UserAc userSecound = new UserAc() { Id = _stringConstant.UserIdSecond, FirstName = _stringConstant.FirstNameSecond }; UserAc userThird = new UserAc() { Id = _stringConstant.UserIdThird, FirstName = _stringConstant.FirstNameThird }; userlist.Add(user); userlist.Add(userSecound); userlist.Add(userThird); return userlist; } /// <summary> /// mock of project ac /// </summary> /// <returns></returns> private ProjectAc MockOfProjectAc() { ProjectAc projectAc = new ProjectAc(); projectAc.Name = _stringConstant.Name; projectAc.IsActive = _stringConstant.IsActive; projectAc.TeamLeader = new UserAc { FirstName = _stringConstant.FirstName }; projectAc.TeamLeaderId = _stringConstant.TeamLeaderId; projectAc.CreatedBy = _stringConstant.CreatedBy; return projectAc; } /// <summary> /// Creates mock user /// </summary> /// <returns>id of user created</returns> private async Task<string> MockOfUserAc() { UserAc user = new UserAc() { Email = _stringConstant.RawEmailIdForTest, JoiningDate = DateTime.UtcNow, IsActive = true, RoleName = _stringConstant.Employee }; return await _userRepository.AddUserAsync(user, _stringConstant.RawFirstNameForTest); } /// <summary> /// Method to add project /// </summary> /// <returns>projectId</returns> private async Task<int> AddProjectAndProjectUserAsync() { _dataRepository.Add(project); await _dataRepository.SaveChangesAsync(); projectUser.ProjectId = project.Id; projectUser.UserId = user.Id; _dataRepositoryProjectUser.Add(projectUser); await _dataRepositoryProjectUser.SaveChangesAsync(); return project.Id; } /// <summary> /// Method to add user /// </summary> /// <returns>userId</returns> private async Task<string> AddUser() { await _userManager.CreateAsync(user); return user.Id; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace KDTree2 { public class Color { public float R { get; set; } public float G { get; set; } public float B { get; set; } } }
using DapperExtensions; using KRF.Core.DTO.Sales; using KRF.Core.Entities.Employee; using KRF.Core.Entities.Sales; using KRF.Core.Entities.ValueList; using KRF.Core.FunctionalContracts; using System; using System.Collections.Generic; using System.Linq; using System.Transactions; namespace KRF.Persistence.FunctionalContractImplementation { public class LeadManagement : ILeadManagement { /// <summary> /// Create an Lead /// </summary> /// <param name="lead">Lead details</param> /// <param name="customerAddress"></param> /// <returns>Newly created Lead identifier</returns> public int Create(Lead lead, IList<CustomerAddress> customerAddress) { using (var transactionScope = new TransactionScope()) { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); var id = conn.Insert(lead); lead.ID = id; foreach (var address in customerAddress) { conn.Insert<CustomerAddress>(customerAddress); // TODO this looks weird; check it out } transactionScope.Complete(); return id; } } } /// <summary> /// Edit an Lead based on updated Lead details. /// </summary> /// <param name="lead">Updated Lead details.</param> /// <returns>Updated Lead details.</returns> public Lead Edit(Lead lead, IList<CustomerAddress> customerAddress) { using (var transactionScope = new TransactionScope()) { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); conn.Update(lead); foreach (var address in customerAddress) { conn.Insert<CustomerAddress>(customerAddress); // TODO this looks weird } transactionScope.Complete(); return lead; } } } /// <summary> /// Create Job Address /// </summary> /// <param name="customerAddress"></param> /// <returns></returns> public int CreateJobAddress(IList<CustomerAddress> customerAddress) { var id = 0; if (customerAddress.Any()) { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); id = conn.Insert(customerAddress[0]); } } return id; } /// <summary> /// Edit Job Address /// </summary> /// <param name="customerAddress"></param> /// <returns></returns> public bool EditJobAddress(IList<CustomerAddress> customerAddress) { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); var isEdited = conn.Update(customerAddress[0]); return isEdited; } } /// <summary> /// Delete Job Address /// </summary> /// <param name="jobAddId"></param> /// <returns></returns> public bool DeleteJobAddress(int jobAddId) { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); var isDeleted = false; try { var predicateGroupEst = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroupEst.Predicates.Add(Predicates.Field<Estimate>(s => s.JobAddressID, Operator.Eq, jobAddId)); IList<Estimate> estimates = conn.GetList<Estimate>(predicateGroupEst).ToList(); var predicateGroupJob = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroupJob.Predicates.Add(Predicates.Field<Core.Entities.Customer.Job>(s => s.JobAddressID, Operator.Eq, jobAddId)); IList<Core.Entities.Customer.Job> jobs = conn.GetList<Core.Entities.Customer.Job>(predicateGroupJob).ToList(); if (!estimates.Any() && !jobs.Any()) { var predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<CustomerAddress>(s => s.ID, Operator.Eq, jobAddId)); isDeleted = conn.Delete<CustomerAddress>(predicateGroup); } } catch (Exception ex) { Console.WriteLine(ex); isDeleted = false; } return isDeleted; } } /// <summary> /// Delete an Lead. /// </summary> /// <param name="id"> Lead unique identifier</param> /// <returns>True - if successful deletion; False - If failure.</returns> public bool Delete(int id) { try { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); var predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<Lead>(s => s.ID, Operator.Eq, id)); var isDeleted = conn.Delete<Lead>(predicateGroup); return isDeleted; } } catch (Exception ex) { Console.WriteLine(ex); return false; } } /// <summary> /// Get all Lead created in the system. /// </summary> /// <param name="predicate"></param> /// <param name="isActive">If true - returns only active Leads else return all</param> /// <returns>List of Leads.</returns> public LeadDTO GetLeads(Func<Lead, bool> predicate, bool isActive = true) { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); IList<Lead> leads = conn.GetList<Lead>().Where(predicate).ToList(); var predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<City>(s => s.Active, Operator.Eq, true)); IList<City> cities = conn.GetList<City>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<State>(s => s.Active, Operator.Eq, true)); IList<State> states = conn.GetList<State>(predicateGroup).ToList(); IList<Country> countries = conn.GetList<Country>().ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<Status>(s => s.Active, Operator.Eq, true)); IList<Status> status = conn.GetList<Status>(predicateGroup).ToList(); status = status.Where(k => k.ID != 4).ToList(); IList<ContactMethod> contactMethod = conn.GetList<ContactMethod>().ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<HearAboutUs>(s => s.Active, Operator.Eq, true)); IList<HearAboutUs> hearAboutUs = conn.GetList<HearAboutUs>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<PropertyRelationship>(s => s.Active, Operator.Eq, true)); IList<PropertyRelationship> propertyRelationship = conn.GetList<PropertyRelationship>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<ProjectStartTimeline>(s => s.Active, Operator.Eq, true)); IList<ProjectStartTimeline> projectStartTimeline = conn.GetList<ProjectStartTimeline>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<ProjectType>(s => s.Active, Operator.Eq, true)); IList<ProjectType> projectType = conn.GetList<ProjectType>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<RoofAge>(s => s.Active, Operator.Eq, true)); IList<RoofAge> roofAge = conn.GetList<RoofAge>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<NumberOfStories>(s => s.Active, Operator.Eq, true)); IList<NumberOfStories> numberOfStories = conn.GetList<NumberOfStories>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<RoofType>(s => s.Active, Operator.Eq, true)); IList<RoofType> roofType = conn.GetList<RoofType>(predicateGroup).ToList(); IList<Employee> employees = conn.GetList<Employee>().ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<ExistingRoof>(s => s.Active, Operator.Eq, true)); IList<ExistingRoof> existingRoof = conn.GetList<ExistingRoof>(predicateGroup).ToList(); return new LeadDTO { Leads = leads, Cities = cities.OrderBy(p => p.ID).ToList(), States = states.OrderBy(p => p.Description).ToList(), Countries = countries.OrderBy(p => p.Description).ToList(), Statuses = status.OrderBy(p => p.Description).ToList(), ContactMethod = contactMethod.Where(p => p.Active).OrderBy(p => p.Description).ToList(), HearAboutUsList = hearAboutUs.Where(p => p.Active).OrderBy(p => p.Description).ToList(), PropertyRelationship = propertyRelationship.Where(p => p.Active).OrderBy(p => p.Description).ToList(), ProjectStartTimelines = projectStartTimeline.OrderBy(p => p.Description).ToList(), ProjectTypes = projectType.OrderBy(p => p.Description).ToList(), RoofAgeList = roofAge.OrderBy(p => p.ID).ToList(), BuildingStoriesList = numberOfStories.OrderBy(p => p.Description).ToList(), RoofTypes = roofType.OrderBy(p => p.Description).ToList(), Employees = employees.OrderBy(p => p.FirstName).ToList(), ExistingRoofs = existingRoof.OrderBy(p => p.Description).ToList() }; } } /// <summary> /// Get Lead details based on id. /// </summary> /// <param name="id">Lead unique identifier</param> /// <returns>Lead details.</returns> public LeadDTO GetLead(int id) { var dbConnection = new DataAccessFactory(); using (var conn = dbConnection.CreateConnection()) { conn.Open(); var predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<Lead>(s => s.ID, Operator.Eq, id)); var lead = conn.Get<Lead>(id); IList<Lead> leads = new List<Lead>(); leads.Add(lead); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<City>(s => s.Active, Operator.Eq, true)); IList<City> cities = conn.GetList<City>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<State>(s => s.Active, Operator.Eq, true)); IList<State> states = conn.GetList<State>(predicateGroup).ToList(); predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; predicateGroup.Predicates.Add(Predicates.Field<CustomerAddress>(s => s.LeadID, Operator.Eq, id)); IList<CustomerAddress> customerAddress = conn.GetList<CustomerAddress>(predicateGroup).ToList(); return new LeadDTO { Leads = leads, Cities = cities.OrderBy(p => p.ID).ToList(), States = states.OrderBy(p => p.Description).ToList(), CustomerAddress = customerAddress }; } } /// <summary> /// Search and filter Lead based on search text. /// </summary> /// <param name="searchText">Search text which need to be mapped with any of Lead related fields.</param> /// <returns> Lead list.</returns> public IList<Lead> SearchLead(string searchText) { return null; } /// <summary> /// Set Lead to active / Inactive /// </summary> /// <param name="leadId"> Lead unique identifier</param> /// <param name="isActive">True - active; False - Inactive.</param> /// <returns>True - if successful deletion; False - If failure.</returns> public bool SetActive(int leadId, bool isActive) { return false; } private CustomerAddress CustomerAddress(int leadId, Lead lead) { var caddress = new CustomerAddress { LeadID = leadId, Address1 = lead.JobAddress1??"", Address2 = lead.JobAddress2??"", City = lead.JobCity, State = lead.JobState, ZipCode = lead.JobZipCode??"", }; return caddress; } } }
using Godot; using System; public class Bullet : Area2D { [Export] public int damage = 1; [Export] public int speed = 10; [Export] public float lifeTime = 20; private Vector2 moveDir; private Vector2 iVelocity; private RayCast2D rayCast; public override void _Ready() { rayCast = (RayCast2D)GetNode("RayCast2D"); } public override void _Process(float delta) { if (lifeTime < 0) kill(); if (rayCast.IsColliding()) { var collider = rayCast.GetCollider(); if (collider is Enemy) { ((Enemy)collider).damage(damage); } else if (collider is Station) { ((Station)collider).Kill(); } kill(); } lifeTime--; LookAt(GlobalPosition + moveDir); this.GlobalPosition += moveDir * speed + (iVelocity * delta); } public void setTarget(Vector2 dir, Vector2 currentVelocity) { moveDir = dir; iVelocity = currentVelocity; } protected void move() { } protected void kill() { QueueFree(); } }
using System.Threading.Tasks; using DataLayer.Entities; using DataLayer.RequestFeatures; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Services.Logger; using Services.Report; namespace PurchaseAppNew.Controllers { [Route("api/[controller]")] public class ReportsController : Controller { private readonly IReportManager _reportManager; private readonly ILoggerManager _logger; private readonly UserManager<User> _userManager; public ReportsController(IReportManager reportManager, ILoggerManager logger, UserManager<User> userManager) { _reportManager = reportManager; _logger = logger; _userManager = userManager; } [HttpGet, Authorize] public async Task<IActionResult> Get([FromQuery] PurchaseParameters purchaseParameters) { var userId = _userManager.FindByNameAsync(User.Identity.Name).Result.Id; var purchasesbyCategory = await _reportManager.GetPurchasesByCategory(userId, purchaseParameters); return Ok(purchasesbyCategory); } [HttpGet("max"), Authorize] public async Task<IActionResult> GetMaximum([FromQuery] PurchaseParameters purchaseParameters) { var userId = _userManager.FindByNameAsync(User.Identity.Name).Result.Id; var maximumPurchases = await _reportManager.GetMaximumPurchase(userId, purchaseParameters); return Ok(maximumPurchases); } [HttpGet("min"), Authorize] public async Task<IActionResult> GetMinimum([FromQuery] PurchaseParameters purchaseParameters) { var userId = _userManager.FindByNameAsync(User.Identity.Name).Result.Id; var minimumPurchases = await _reportManager.GetMinimumPurchase(userId, purchaseParameters); return Ok(minimumPurchases); } } }
using DAL; using MetaDados; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BAL { public static class ClienteBAL { /// <summary> /// Ligação para a função InsertClient do banco de dados /// </summary> /// <param name="cli"></param> /// <returns>Response</returns> public static Response InsertClient(Cliente cli) { //-----Tratamento de dados-----// cli.data_nascimento = Checker.StringCleaner(cli.data_nascimento); cli.cpf = Checker.StringCleaner(cli.cpf); cli.telefone_1 = Checker.StringCleaner(cli.telefone_1); cli.telefone_2 = Checker.StringCleaner(cli.telefone_2); cli.cep = Checker.StringCleaner(cli.cep); Response resp = ClienteDB.InsertClient(cli); return resp; } /// <summary> /// Ligação para a função SelectListClient do banco de dados /// </summary> /// <param name="id_cliente"></param> /// <returns>Response</returns> public static List<Cliente> SelectListClient(int id_cliente) { List<Cliente> list_client = new List<Cliente>(); Response resp = ClienteDB.SelectListClient(out list_client, id_cliente); return list_client; } /// <summary> /// Ligação para a função DeleteClient do banco de dados /// </summary> /// <param name="id_cliente"></param> /// <returns>Response</returns> public static Response DeleteClient(int id_cliente) { Response resp = ClienteDB.DeleteClient(id_cliente); return resp; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace MvcPL.Models.ViewModels { public class UsersListViewModel { public UserModel user { get; set; } public string Role { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Configuration; using System.Data.SqlClient; using System.IO; namespace solution1 { class vider_bdd { string connectionString = ConfigurationManager.ConnectionStrings["connectString1"].ConnectionString; public void parcour_fichier (TextBox parcour) { OpenFileDialog openFile = new OpenFileDialog(); openFile.DefaultExt = "csv"; openFile.Filter = "Fichier CSV (*.csv)|*.csv"; openFile.ShowDialog(); if (openFile.FileNames.Length > 0) { foreach (string filename in openFile.FileNames) { parcour.Text = filename; //listBoxAdd.Items.Add(filename); } } } public void vider_bdd_tapbe(ComboBox comboBox_table, TextBox textBox_journal_bdd) { if (comboBox_table.Text.ToString().Substring(7).Trim() == "Catégorie Bien") { string requete_sup = "delete from CategorieBien"; if (MaConnexion.ExecuteUpdate(connectionString, requete_sup) != -1) { textBox_journal_bdd.Text = "la table Catégorie bien est vidé "; } else { textBox_journal_bdd.Text = "la table Catégorie bien n'a pas put etre vidé !! "; } } if (comboBox_table.Text.ToString().Substring(7).Trim() == "Bien") { string requete_sup = "delete from Bien"; if (MaConnexion.ExecuteUpdate(connectionString, requete_sup) != -1) { textBox_journal_bdd.Text = "la table bien est vidé "; } else { textBox_journal_bdd.Text = "la table bien n'a pas put etre vidé !! "; } } if (comboBox_table.Text.ToString().Substring(7).Trim() == "Site") { string requete_sup = "delete from Site"; if (MaConnexion.ExecuteUpdate(connectionString, requete_sup) != -1) { textBox_journal_bdd.Text = "la table Site est vidé "; } else { textBox_journal_bdd.Text = "la table Site n'a pas put etre vidé !! "; } } if (comboBox_table.Text.ToString().Substring(7).Trim() == "Emplacement") { string requete_sup = "delete from Emplacement"; if (MaConnexion.ExecuteUpdate(connectionString, requete_sup) != -1) { textBox_journal_bdd.Text = "la table Catégorie bien est vidé "; } else { textBox_journal_bdd.Text = "la table Catégorie bien n'a pas put etre vidé !! "; } } if (comboBox_table.Text.ToString().Substring(7).Trim() == "Se Trouve Bien") { string requete_sup = "delete from SeTrouveB"; if (MaConnexion.ExecuteUpdate(connectionString, requete_sup) != -1) { textBox_journal_bdd.Text = "la table se trouve bien est vidé "; } else { textBox_journal_bdd.Text = "la table Se Trouve Bien n'a pas put etre vidé !! "; } } } public void vider_toute_bdd(TextBox textBox_journal_bdd) { string requate_sup_total = "delete from Bien delete from CategorieBien delete from Emplacement delete from Site delete from SeTrouveB"; if (MaConnexion.ExecuteUpdate(connectionString, requate_sup_total) != 1) { textBox_journal_bdd.Text = "la base de donnée est vidé complaintement "; } else { textBox_journal_bdd.Text = "interoption de l'instruction la base n'a pas put etre vidé "; } } } }
using UnityEngine; using System.Collections; namespace Ph.Bouncer { public class CreditsButton : MonoBehaviour { void OnPress(bool isDown) { if(!isDown) { LevelLoadHelper.LoadCreditsScreen(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace nmct.ba.cashlessproject.model.ASP.NET { public class Organisation { public int ID { get; set; } [Required(ErrorMessage = "U bent verplicht een loginnaam in te geven.")] [RegularExpression(@"^[a-zA-Z''-'\s]{1,50}$", ErrorMessage = "De loginnaam mag geen speciale tekens bevatten.")] [StringLength(20, MinimumLength = 3, ErrorMessage = "De loginnaam moet minstens 3 en maximaal 20 karakters bevatten.")] public String Login { get; set; } /* * Regex credits: http://forums.asp.net/t/918584.aspx?REGEX+password+must+contain+letters+a+zA+Z+and+at+least+one+digit+0+9 */ [Required(ErrorMessage = "U bent verplicht een wachtwoord in te geven.")] [RegularExpression(@"^[A-Za-z]+\d+.*$", ErrorMessage = "Het wachtwoord moet beginnen met een letter en minstens 1 cijfer bevatten.")] [StringLength(20, MinimumLength = 3, ErrorMessage = "Het wachtwoord moet minstens 3 en maximaal 20 karakters bevatten.")] public String Password { get; set; } [Required(ErrorMessage = "U bent verplicht een databasenaam in te geven.")] [RegularExpression(@"^[a-zA-Z''-'\s]{1,50}$", ErrorMessage = "De databasenaam mag geen speciale tekens bevatten.")] [StringLength(20, MinimumLength = 3, ErrorMessage = "De de databasenaam moet minstens 3 en maximaal 20 karakters bevatten.")] public String DbName { get; set; } [Required(ErrorMessage = "U bent verplicht een loginnaam in te geven.")] [RegularExpression(@"^[a-zA-Z''-'\s]{1,50}$", ErrorMessage = "De loginnaam mag geen speciale tekens bevatten.")] [StringLength(20, MinimumLength = 3, ErrorMessage = "De loginnaam moet minstens 3 en maximaal 20 karakters bevatten.")] public String DbLogin { get; set; } [Required(ErrorMessage = "U bent verplicht een wachtwoord in te geven.")] [RegularExpression(@"^[A-Za-z]+\d+.*$", ErrorMessage = "Het wachtwoord moet beginnen met een letter en minstens 1 cijfer bevatten.")] [StringLength(20, MinimumLength = 3, ErrorMessage = "Het wachtwoord moet minstens 3 en maximaal 20 karakters bevatten.")] public String DbPassword { get; set; } [Required(ErrorMessage = "U bent verplicht een organisatienaam in te geven.")] public String OrganisationName { get; set; } [Required(ErrorMessage = "U bent verplicht een adres in te geven.")] public String Address { get; set; } [Required(ErrorMessage = "U bent verplicht een e-mailadres in te geven.")] [EmailAddress(ErrorMessage = "Het ingegeven e-mailadres is niet correct.")] public String Email { get; set; } [Required(ErrorMessage = "U bent verplicht een telefoonnummer in te geven.")] [Phone(ErrorMessage = "Het ingegeven telefoonnummer is niet correct.")] public String Phone { get; set; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; namespace Dnn.PersonaBar.Pages.Components.Exceptions { public class PageNotFoundException : Exception { } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using FPS.Service.Interface; using FPS.Service.Models; using static FPS.Service.Infrastructure.StructureMapConfigurator; namespace FPS.Api.Controllers { public class ResidentController : CoreController { private readonly IResidentService _residentService; public ResidentController() { _residentService = GetInstance<IResidentService>(); } [ActionName("GetList")] [HttpGet] public HttpResponseMessage GetResidentList() { return GenerateResponse(_residentService.GetResident(null)); } [ActionName("GetList")] [HttpPost] public HttpResponseMessage GetResidentList(ResidentFilterServiceModel residentFilter) { return GenerateResponse(_residentService.GetResident(residentFilter)); } [ActionName("GetById")] [HttpGet] public HttpResponseMessage GetResidentById(int id) { return GenerateResponse(_residentService.GetResident(id)); } [ActionName("Create")] [HttpPost] public HttpResponseMessage CreateResident(ResidentServiceModel resident) { return GenerateResponse(_residentService.CreateResident(resident)); } [ActionName("Update")] [HttpPost] public HttpResponseMessage UpdateResident(ResidentServiceModel resident) { return GenerateResponse(_residentService.UpdateResident(resident)); } [ActionName("Delete")] [HttpPost] public HttpResponseMessage DeleteResident(int id) { return GenerateResponse(_residentService.DeleteResident(id)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoreComponents.Items { public sealed class EqualityFuncComparer<T> : IEqualityComparer<T> { readonly Func<T, T, bool> myFunc; public EqualityFuncComparer(Func<T, T, bool> func) { myFunc = func; } public bool Equals(T x, T y) { return myFunc(x, y); } public int GetHashCode(T obj) { return obj.GetHashCode(); } } }
using StoreKit; namespace Liddup.iOS.Services { internal class DeezerApiiOS { } }
using System; using System.Collections.Generic; using System.Text; using AgentStoryComponents.core; namespace AgentStoryComponents { public class Users { private utils ute = new utils(); private string _connectionString = null; public Users(string asConnectionString) { this._connectionString = asConnectionString; } public List<User> UserList { get { //count number of users int numUsers = this.NumberUsers; List<User> userList = new List<User>(numUsers); string sql = ""; sql += "select * from users order by dateAdded DESC"; OleDbHelper dbHelper = ute.getDBcmd(this._connectionString); dbHelper.cmd.CommandText = sql; dbHelper.reader = dbHelper.cmd.ExecuteReader(); if (dbHelper.reader.HasRows) { while (dbHelper.reader.Read()) { int userID = Convert.ToInt32( dbHelper.reader["ID"] ); User u = new User(this._connectionString, userID); userList.Add(u); } } dbHelper.cleanup(); return userList; } } /// <summary> /// return number of users in users table. /// </summary> public int NumberUsers { get { string sql = ""; int count = -1; sql += "select count(id) from users"; OleDbHelper dbHelper = ute.getDBcmd(this._connectionString); dbHelper.cmd.CommandText = sql; dbHelper.reader = dbHelper.cmd.ExecuteReader(); if (dbHelper.reader.HasRows) { dbHelper.reader.Read(); count = Convert.ToInt32( dbHelper.reader[0] ); } else { count = 0; } dbHelper.cleanup(); return count; } } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; using RSCTest; namespace RSC.Test { [TestFixture] public class CheckStringTest { public CheckString checkString; [SetUp] public void Init() { checkString = new CheckString(); } [Test] public void IsPalindrome_ReturnFalse() { checkString = new CheckString(); var result = checkString.IsPalindrome("1234"); Assert.IsFalse(result); } [TestCase(123)] [TestCase(2342134)] [TestCase("qwer")] public void IsPalindrome_ReturnFalse(string value) { var result = checkString.IsPalindrome(value); Assert.IsFalse(result); } } }
/****************************************************** * ROMVault3 is written by Gordon J. * * Contact gordon@romvault.com * * Copyright 2010 * ******************************************************/ using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.Globalization; using System.Windows.Forms; using Compress; using FileHeaderReader; using ROMVault.Utils; using RVCore; using RVCore.FindFix; using RVCore.ReadDat; using RVCore.RvDB; using RVCore.Scanner; using RVCore.Utils; using RVIO; namespace ROMVault { public partial class FrmMain : Form { private static readonly Color CBlue = Color.FromArgb(214, 214, 255); private static readonly Color CGreyBlue = Color.FromArgb(214, 224, 255); private static readonly Color CRed = Color.FromArgb(255, 214, 214); private static readonly Color CBrightRed = Color.FromArgb(255, 0, 0); private static readonly Color CGreen = Color.FromArgb(214, 255, 214); private static readonly Color CGrey = Color.FromArgb(214, 214, 214); private static readonly Color CCyan = Color.FromArgb(214, 255, 255); private static readonly Color CCyanGrey = Color.FromArgb(214, 225, 225); private static readonly Color CMagenta = Color.FromArgb(255, 214, 255); private static readonly Color CBrown = Color.FromArgb(140, 80, 80); private static readonly Color CPurple = Color.FromArgb(214, 140, 214); private static readonly Color CYellow = Color.FromArgb(255, 255, 214); private static readonly Color COrange = Color.FromArgb(255, 214, 140); private static readonly Color CWhite = Color.FromArgb(255, 255, 255); private static int[] _gameGridColumnXPositions; private readonly Color[] _displayColor; private readonly Color[] _fontColor; private readonly ContextMenu _mnuContext; private readonly ContextMenu _mnuContextToSort; private readonly MenuItem _mnuOpen; private readonly MenuItem _mnuToSortScan; private readonly MenuItem _mnuToSortOpen; private readonly MenuItem _mnuToSortDelete; private readonly MenuItem _mnuToSortSetPrimary; private readonly MenuItem _mnuToSortSetCache; private RvFile _clickedTree; private bool _updatingGameGrid; private int _gameGridSortColumnIndex; private SortOrder _gameGridSortOrder = SortOrder.Descending; private FrmKey _fk; private float _scaleFactorX = 1; private float _scaleFactorY = 1; private Label _labelGameName; private TextBox _textGameName; private Label _labelGameDescription; private TextBox _textGameDescription; private Label _labelGameManufacturer; private TextBox _textGameManufacturer; private Label _labelGameCloneOf; private TextBox _textGameCloneOf; private Label _labelGameRomOf; private TextBox _textGameRomOf; private Label _labelGameYear; private TextBox _textGameYear; private Label _labelGameTotalRoms; private TextBox _textGameTotalRoms; //Trurip Extra Data private Label _labelTruripPublisher; private TextBox _textTruripPublisher; private Label _labelTruripDeveloper; private TextBox _textTruripDeveloper; private Label _labelTruripTitleId; private TextBox _textTruripTitleId; private Label _labelTruripSource; private TextBox _textTruripSource; private Label _labelTruripCloneOf; private TextBox _textTruripCloneOf; private Label _labelTruripRelatedTo; private TextBox _textTruripRelatedTo; private Label _labelTruripYear; private TextBox _textTruripYear; private Label _labelTruripPlayers; private TextBox _textTruripPlayers; private Label _labelTruripGenre; private TextBox _textTruripGenre; private Label _labelTruripSubGenre; private TextBox _textTruripSubGenre; private Label _labelTruripRatings; private TextBox _textTruripRatings; private Label _labelTruripScore; private TextBox _textTruripScore; public FrmMain() { InitializeComponent(); AddGameGrid(); Text = $@"RomVault ({Program.StrVersion}) {Application.StartupPath}"; _displayColor = new Color[(int)RepStatus.EndValue]; _fontColor = new Color[(int)RepStatus.EndValue]; // RepStatus.UnSet _displayColor[(int)RepStatus.UnScanned] = CBlue; _displayColor[(int)RepStatus.DirCorrect] = CGreen; _displayColor[(int)RepStatus.DirMissing] = CRed; _displayColor[(int)RepStatus.DirCorrupt] = CBrightRed; //BrightRed _displayColor[(int)RepStatus.Missing] = CRed; _displayColor[(int)RepStatus.Correct] = CGreen; _displayColor[(int)RepStatus.NotCollected] = CGrey; _displayColor[(int)RepStatus.UnNeeded] = CCyanGrey; _displayColor[(int)RepStatus.Unknown] = CCyan; _displayColor[(int)RepStatus.InToSort] = CMagenta; _displayColor[(int)RepStatus.Corrupt] = CBrightRed; //BrightRed _displayColor[(int)RepStatus.Ignore] = CGreyBlue; _displayColor[(int)RepStatus.CanBeFixed] = CYellow; _displayColor[(int)RepStatus.MoveToSort] = CPurple; _displayColor[(int)RepStatus.Delete] = CBrown; _displayColor[(int)RepStatus.NeededForFix] = COrange; _displayColor[(int)RepStatus.Rename] = COrange; _displayColor[(int)RepStatus.CorruptCanBeFixed] = CYellow; _displayColor[(int)RepStatus.MoveToCorrupt] = CPurple; //Missing _displayColor[(int)RepStatus.Deleted] = CWhite; for (int i = 0; i < (int)RepStatus.EndValue; i++) { _fontColor[i] = Contrasty(_displayColor[i]); } _gameGridColumnXPositions = new int[(int)RepStatus.EndValue]; DirTree.Setup(ref DB.DirTree); splitContainer3_Panel1_Resize(new object(), new EventArgs()); splitContainer4_Panel1_Resize(new object(), new EventArgs()); _mnuContext = new ContextMenu(); MenuItem mnuScan = new MenuItem { Text = @"Scan", Tag = null }; MenuItem mnuFile = new MenuItem { Text = @"Set Dir Settings", Tag = null }; _mnuOpen = new MenuItem { Text = @"Open", Tag = null }; MenuItem mnuMakeDat = new MenuItem { Text = @"Make Dat with CHDs as disk", Tag = null }; MenuItem mnuMakeDat2 = new MenuItem { Text = @"Make Dat with CHDs as rom", Tag = null }; _mnuContext.MenuItems.Add(mnuScan); _mnuContext.MenuItems.Add(_mnuOpen); _mnuContext.MenuItems.Add(mnuFile); _mnuContext.MenuItems.Add(mnuMakeDat); _mnuContext.MenuItems.Add(mnuMakeDat2); mnuScan.Click += MnuToSortScan; _mnuOpen.Click += MnuOpenClick; mnuFile.Click += MnuFileClick; mnuMakeDat.Click += MnuMakeDatClick; mnuMakeDat2.Click += MnuMakeDat2Click; _mnuContextToSort = new ContextMenu(); _mnuToSortScan = new MenuItem { Text = @"Scan", Tag = null }; _mnuToSortOpen = new MenuItem { Text = @"Open", Tag = null }; _mnuToSortDelete = new MenuItem { Text = @"Remove", Tag = null }; _mnuToSortSetPrimary = new MenuItem { Text = @"Set To Primary ToSort", Tag = null }; _mnuToSortSetCache = new MenuItem { Text = @"Set To Cache ToSort", Tag = null }; _mnuContextToSort.MenuItems.Add(_mnuToSortScan); _mnuContextToSort.MenuItems.Add(_mnuToSortOpen); _mnuContextToSort.MenuItems.Add(_mnuToSortDelete); _mnuContextToSort.MenuItems.Add(_mnuToSortSetPrimary); if (Settings.rvSettings.UseFileSelection) _mnuContextToSort.MenuItems.Add(_mnuToSortSetCache); _mnuToSortScan.Click += MnuToSortScan; _mnuToSortOpen.Click += MnuToSortOpen; _mnuToSortDelete.Click += MnuToSortDelete; _mnuToSortSetPrimary.Click += MnuToSortSetPrimary; _mnuToSortSetCache.Click += MnuToSortSetCache; chkBoxShowCorrect.Checked = Settings.rvSettings.chkBoxShowCorrect; chkBoxShowMissing.Checked = Settings.rvSettings.chkBoxShowMissing; chkBoxShowFixed.Checked = Settings.rvSettings.chkBoxShowFixed; chkBoxShowMerged.Checked = Settings.rvSettings.chkBoxShowMerged; TabArtworkInitialize(); } public sealed override string Text { get => base.Text; set => base.Text = value; } protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { base.ScaleControl(factor, specified); splitToolBarMain.SplitterDistance = (int)(splitToolBarMain.SplitterDistance * factor.Width); splitDatInfoGameInfo.SplitterDistance = (int)(splitDatInfoGameInfo.SplitterDistance * factor.Width); splitDatInfoGameInfo.Panel1MinSize = (int)(splitDatInfoGameInfo.Panel1MinSize * factor.Width); splitDatInfoTree.SplitterDistance = (int)(splitDatInfoTree.SplitterDistance * factor.Height); splitGameInfoLists.SplitterDistance = (int)(splitGameInfoLists.SplitterDistance * factor.Height); _scaleFactorX *= factor.Width; _scaleFactorY *= factor.Height; } private void AddTextBox(int line, string name, int x, int x1, out Label lBox, out TextBox tBox) { int y = 14 + line * 16; lBox = new Label { Location = SPoint(x, y + 1), Size = SSize(x1 - x - 2, 13), Text = name + @" :", TextAlign = ContentAlignment.TopRight }; tBox = new TextBox { AutoSize=false, Location = SPoint(x1, y), Size = SSize(20, 17), BorderStyle = BorderStyle.FixedSingle, ReadOnly = true, TabStop = false }; gbSetInfo.Controls.Add(lBox); gbSetInfo.Controls.Add(tBox); } private void AddGameGrid() { AddTextBox(0, "Name", 6, 84, out _labelGameName, out _textGameName); AddTextBox(1, "Description", 6, 84, out _labelGameDescription, out _textGameDescription); AddTextBox(2, "Manufacturer", 6, 84, out _labelGameManufacturer, out _textGameManufacturer); AddTextBox(3, "Clone of", 6, 84, out _labelGameCloneOf, out _textGameCloneOf); AddTextBox(3, "Year", 206, 284, out _labelGameYear, out _textGameYear); AddTextBox(4, "Rom of", 6, 84, out _labelGameRomOf, out _textGameRomOf); AddTextBox(4, "Total ROMs", 206, 284, out _labelGameTotalRoms, out _textGameTotalRoms); //Trurip AddTextBox(2, "Publisher", 6, 84, out _labelTruripPublisher, out _textTruripPublisher); AddTextBox(2, "Title Id", 406, 484, out _labelTruripTitleId, out _textTruripTitleId); AddTextBox(3, "Developer", 6, 84, out _labelTruripDeveloper, out _textTruripDeveloper); AddTextBox(3, "Source", 406, 484, out _labelTruripSource, out _textTruripSource); AddTextBox(4, "Clone of", 6, 84, out _labelTruripCloneOf, out _textTruripCloneOf); AddTextBox(5, "Related to", 6, 84, out _labelTruripRelatedTo, out _textTruripRelatedTo); AddTextBox(6, "Year", 6, 84, out _labelTruripYear, out _textTruripYear); AddTextBox(6, "Genre", 206, 284, out _labelTruripGenre, out _textTruripGenre); AddTextBox(6, "Ratings", 406, 484, out _labelTruripRatings, out _textTruripRatings); AddTextBox(7, "Players", 6, 84, out _labelTruripPlayers, out _textTruripPlayers); AddTextBox(7, "SubGenre", 206, 284, out _labelTruripSubGenre, out _textTruripSubGenre); AddTextBox(7, "Score", 406, 484, out _labelTruripScore, out _textTruripScore); gbSetInfo_Resize(null, new EventArgs()); UpdateRomGrid(new RvFile(FileType.Dir)); } private Point SPoint(int x, int y) { return new Point((int)(x * _scaleFactorX), (int)(y * _scaleFactorY)); } private Size SSize(int x, int y) { return new Size((int)(x * _scaleFactorX), (int)(y * _scaleFactorY)); } private void DirTreeRvChecked(object sender, MouseEventArgs e) { RepairStatus.ReportStatusReset(DB.DirTree); DatSetSelected(DirTree.Selected); } private void DirTreeRvSelected(object sender, MouseEventArgs e) { RvFile cf = (RvFile)sender; if (cf != DirTree.GetSelected()) { DatSetSelected(cf); } if (e.Button != MouseButtons.Right) { return; } _clickedTree = (RvFile)sender; Point controLocation = ControlLoc(DirTree); if (cf.IsInToSort) { bool selected = (_clickedTree.Tree.Checked != RvTreeRow.TreeSelect.Locked); _mnuToSortOpen.Enabled = Directory.Exists(_clickedTree.FullName); _mnuToSortDelete.Enabled = !(_clickedTree.FileStatusIs(FileStatus.PrimaryToSort) | _clickedTree.FileStatusIs(FileStatus.CacheToSort)); _mnuToSortSetCache.Enabled = selected; _mnuToSortSetPrimary.Enabled = selected; _mnuContextToSort.Show(this, new Point(controLocation.X + e.X - 32, controLocation.Y + e.Y - 10)); } else { _mnuOpen.Enabled = Directory.Exists(_clickedTree.FullName); _mnuContext.Show(this, new Point(controLocation.X + e.X - 32, controLocation.Y + e.Y - 10)); } } private Point ControlLoc(Control c) { Point ret = new Point(c.Left, c.Top); if (c.Parent == this) return ret; Point pNext = ControlLoc(c.Parent); ret.X += pNext.X; ret.Y += pNext.Y; return ret; } private void MnuFileClick(object sender, EventArgs e) { using (FrmSetDirSettings sd = new FrmSetDirSettings()) { string tDir = _clickedTree.TreeFullName; sd.SetLocation(tDir); sd.SetDisplayType(true); sd.ShowDialog(this); if (sd.ChangesMade) UpdateDats(); } } private void MnuOpenClick(object sender, EventArgs e) { string tDir = _clickedTree.FullName; if (Directory.Exists(tDir)) Process.Start(tDir); } private void MnuMakeDatClick(object sender, EventArgs e) { SaveFileDialog browse = new SaveFileDialog { Filter = "DAT file|*.dat", Title = "Save an Dat File", FileName = _clickedTree.Name }; if (browse.ShowDialog() != DialogResult.OK) { return; } if (browse.FileName == "") { return; } DatMaker.MakeDatFromDir(_clickedTree, browse.FileName); } private void MnuMakeDat2Click(object sender, EventArgs e) { SaveFileDialog browse = new SaveFileDialog { Filter = "DAT file|*.dat", Title = "Save an Dat File", FileName = _clickedTree.Name }; if (browse.ShowDialog() != DialogResult.OK) { return; } if (browse.FileName == "") { return; } DatMaker.MakeDatFromDir(_clickedTree, browse.FileName, false); } private void AddToSortToolStripMenuItem_Click(object sender, EventArgs e) { FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); DialogResult result = folderBrowserDialog1.ShowDialog(); if (result != DialogResult.OK) return; RvFile ts = new RvFile(FileType.Dir) { Name = folderBrowserDialog1.SelectedPath, Tree = new RvTreeRow { Checked = RvTreeRow.TreeSelect.Locked }, DatStatus = DatStatus.InDatCollect }; DB.DirTree.ChildAdd(ts, DB.DirTree.ChildCount); RepairStatus.ReportStatusReset(DB.DirTree); DirTree.Setup(ref DB.DirTree); DatSetSelected(ts); DB.Write(); } private void MnuToSortScan(object sender, EventArgs e) { ScanRoms(Settings.rvSettings.ScanLevel, _clickedTree); } private void MnuToSortOpen(object sender, EventArgs e) { string tDir = _clickedTree.FullName; if (Directory.Exists(tDir)) Process.Start(tDir); } private void MnuToSortDelete(object sender, EventArgs e) { for (int i = 0; i < DB.DirTree.ChildCount; i++) { if (DB.DirTree.Child(i) == _clickedTree) { DB.DirTree.ChildRemove(i); RepairStatus.ReportStatusReset(DB.DirTree); DirTree.Setup(ref DB.DirTree); DatSetSelected(DB.DirTree.Child(i - 1)); DB.Write(); DirTree.Refresh(); return; } } } private void MnuToSortSetPrimary(object sender, EventArgs e) { if (_clickedTree.Tree.Checked == RvTreeRow.TreeSelect.Locked) { MessageBox.Show("Directory Must be ticked.", "RomVault", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } RvFile t = DB.RvFileToSort(); bool wasCache = t.FileStatusIs(FileStatus.CacheToSort); t.FileStatusClear(FileStatus.PrimaryToSort | FileStatus.CacheToSort); _clickedTree.FileStatusSet(FileStatus.PrimaryToSort); if (wasCache) _clickedTree.FileStatusSet(FileStatus.CacheToSort); DB.Write(); DirTree.Refresh(); } private void MnuToSortSetCache(object sender, EventArgs e) { if (_clickedTree.Tree.Checked == RvTreeRow.TreeSelect.Locked) { MessageBox.Show("Directory Must be ticked.", "RomVault", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } RvFile t = DB.RvFileCache(); t.FileStatusClear(FileStatus.CacheToSort); _clickedTree.FileStatusSet(FileStatus.CacheToSort); DB.Write(); DirTree.Refresh(); } private void RomGridSelectionChanged(object sender, EventArgs e) { RomGrid.ClearSelection(); } private void ChkBoxShowCorrectCheckedChanged(object sender, EventArgs e) { if (Settings.rvSettings.chkBoxShowCorrect != this.chkBoxShowCorrect.Checked) { Settings.rvSettings.chkBoxShowCorrect = this.chkBoxShowCorrect.Checked; Settings.WriteConfig(Settings.rvSettings); DatSetSelected(DirTree.Selected); } } private void ChkBoxShowMissingCheckedChanged(object sender, EventArgs e) { if (Settings.rvSettings.chkBoxShowMissing != this.chkBoxShowMissing.Checked) { Settings.rvSettings.chkBoxShowMissing = this.chkBoxShowMissing.Checked; Settings.WriteConfig(Settings.rvSettings); DatSetSelected(DirTree.Selected); } } private void ChkBoxShowFixedCheckedChanged(object sender, EventArgs e) { if (Settings.rvSettings.chkBoxShowFixed != this.chkBoxShowFixed.Checked) { Settings.rvSettings.chkBoxShowFixed = this.chkBoxShowFixed.Checked; Settings.WriteConfig(Settings.rvSettings); DatSetSelected(DirTree.Selected); } } private void ChkBoxShowMergedCheckedChanged(object sender, EventArgs e) { if (Settings.rvSettings.chkBoxShowMerged != this.chkBoxShowMerged.Checked) { Settings.rvSettings.chkBoxShowMerged = this.chkBoxShowMerged.Checked; Settings.WriteConfig(Settings.rvSettings); UpdateSelectedGame(); } } private void btnReport_MouseUp(object sender, MouseEventArgs e) { Report.MakeFixFiles(e.Button == MouseButtons.Left); } private void fixDatReportToolStripMenuItem_Click(object sender, EventArgs e) { Report.MakeFixFiles(); } private void fullReportToolStripMenuItem_Click(object sender, EventArgs e) { Report.GenerateReport(); } private void fixReportToolStripMenuItem_Click(object sender, EventArgs e) { Report.GenerateFixReport(); } private void AboutRomVaultToolStripMenuItemClick(object sender, EventArgs e) { FrmHelpAbout fha = new FrmHelpAbout(); fha.ShowDialog(this); fha.Dispose(); } private void RomGridMouseUp(object sender, MouseEventArgs e) { if (e == null || e.Button != MouseButtons.Right) { return; } int currentMouseOverRow = RomGrid.HitTest(e.X, e.Y).RowIndex; if (currentMouseOverRow < 0) { return; } string name = (RomGrid.Rows[currentMouseOverRow].Cells[1].Value ?? "").ToString(); string size = (RomGrid.Rows[currentMouseOverRow].Cells[3].Value ?? "").ToString(); if (size.Contains(" ")) { size = size.Substring(0, size.IndexOf(" ")); } string crc = (RomGrid.Rows[currentMouseOverRow].Cells[4].Value ?? "").ToString(); if (crc.Length > 8) { crc = crc.Substring(0, 8); } string sha1 = (RomGrid.Rows[currentMouseOverRow].Cells[5].Value ?? "").ToString(); if (sha1.Length > 40) { sha1 = sha1.Substring(0, 40); } string md5 = (RomGrid.Rows[currentMouseOverRow].Cells[6].Value ?? "").ToString(); if (md5.Length > 32) { md5 = md5.Substring(0, 32); } string clipText = "Name : " + name + Environment.NewLine; clipText += "Size : " + size + Environment.NewLine; clipText += "CRC32: " + crc + Environment.NewLine; if (sha1.Length > 0) { clipText += "SHA1 : " + sha1 + Environment.NewLine; } if (md5.Length > 0) { clipText += "MD5 : " + md5 + Environment.NewLine; } try { Clipboard.Clear(); Clipboard.SetText(clipText); } catch { } } private void GameGrid_MouseUp(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) { return; } int currentMouseOverRow = GameGrid.HitTest(e.X, e.Y).RowIndex; if (currentMouseOverRow < 0) { return; } object r1 = GameGrid.Rows[currentMouseOverRow].Cells[1].FormattedValue; string filename = r1?.ToString() ?? ""; object r2 = GameGrid.Rows[currentMouseOverRow].Cells[2].FormattedValue; string description = r2?.ToString() ?? ""; try { Clipboard.Clear(); Clipboard.SetText("Name : " + filename + Environment.NewLine + "Desc : " + description + Environment.NewLine); } catch { } } // Override the default "string" sort of the values in the 'Size' column of the RomGrid private void RomGrid_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { try // to sort by 'Size', then by 'Name'. { if (e.Column.Index != 2) { return; } // compare only the value found before the first space character in each CellValue (excludes " (DHV)", etc..) e.SortResult = int.Parse(e.CellValue1.ToString().Split(' ')[0]) .CompareTo(int.Parse(e.CellValue2.ToString().Split(' ')[0])); if (e.SortResult == 0) // when sizes are the same, sort by the name in column 1 { e.SortResult = string.CompareOrdinal( RomGrid.Rows[e.RowIndex1].Cells[1].Value.ToString(), RomGrid.Rows[e.RowIndex2].Cells[1].Value.ToString()); } e.Handled = true; // bypass the default string sort } catch { } } #region "Main Buttons" private void TsmUpdateDaTsClick(object sender, EventArgs e) { UpdateDats(); } private void BtnUpdateDatsClick(object sender, EventArgs e) { UpdateDats(); } private void UpdateDats() { FrmProgressWindow progress = new FrmProgressWindow(this, "Scanning Dats", DatUpdate.UpdateDat); progress.ShowDialog(this); progress.Dispose(); DirTree.Setup(ref DB.DirTree); DatSetSelected(DirTree.Selected); } private void TsmScanLevel1Click(object sender, EventArgs e) { ScanRoms(EScanLevel.Level1); } private void TsmScanLevel2Click(object sender, EventArgs e) { ScanRoms(EScanLevel.Level2); } private void TsmScanLevel3Click(object sender, EventArgs e) { ScanRoms(EScanLevel.Level3); } private void BtnScanRomsClick(object sender, EventArgs e) { ScanRoms(Settings.rvSettings.ScanLevel); } private void ScanRoms(EScanLevel sd, RvFile StartAt = null) { FileScanning.StartAt = StartAt; FileScanning.EScanLevel = sd; FrmProgressWindow progress = new FrmProgressWindow(this, "Scanning Dirs", FileScanning.ScanFiles); progress.ShowDialog(this); progress.Dispose(); DatSetSelected(DirTree.Selected); } private void TsmFindFixesClick(object sender, EventArgs e) { FindFix(); } private void BtnFindFixesClick(object sender, EventArgs e) { FindFix(); } private void FindFix() { FrmProgressWindow progress = new FrmProgressWindow(this, "Finding Fixes", FindFixes.ScanFiles); progress.ShowDialog(this); progress.Dispose(); DatSetSelected(DirTree.Selected); } private void BtnFixFilesClick(object sender, EventArgs e) { FixFiles(); } private void FixFilesToolStripMenuItemClick(object sender, EventArgs e) { FixFiles(); } private void FixFiles() { FrmProgressWindowFix progress = new FrmProgressWindowFix(this); progress.ShowDialog(this); progress.Dispose(); DatSetSelected(DirTree.Selected); } #endregion #region "DAT display code" private void DatSetSelected(RvFile cf) { DirTree.Refresh(); if (Settings.IsMono) { if (GameGrid.RowCount > 0) { GameGrid.CurrentCell = GameGrid[0, 0]; } if (RomGrid.RowCount > 0) { RomGrid.CurrentCell = RomGrid[0, 0]; } } GameGrid.Rows.Clear(); RomGrid.Rows.Clear(); // clear sorting GameGrid.Columns[_gameGridSortColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.None; _gameGridSortColumnIndex = 0; _gameGridSortOrder = SortOrder.Descending; if (cf == null) { return; } UpdateGameGrid(cf); } private void splitContainer3_Panel1_Resize(object sender, EventArgs e) { // fixes a rendering issue in mono if (splitDatInfoTree.Panel1.Width == 0) { return; } gbDatInfo.Width = splitDatInfoTree.Panel1.Width - gbDatInfo.Left * 2; } private void gbDatInfo_Resize(object sender, EventArgs e) { const int leftPos = 89; int rightPos = (int)(gbDatInfo.Width / _scaleFactorX) - 15; if (rightPos > 600) { rightPos = 600; } int width = rightPos - leftPos; int widthB1 = (int)((double)width * 120 / 340); int leftB2 = rightPos - widthB1; int backD = 97; width = (int)(width * _scaleFactorX); widthB1 = (int)(widthB1 * _scaleFactorX); leftB2 = (int)(leftB2 * _scaleFactorX); backD = (int)(backD * _scaleFactorX); lblDITName.Width = width; lblDITDescription.Width = width; lblDITCategory.Width = widthB1; lblDITAuthor.Width = widthB1; lblDIVersion.Left = leftB2 - backD; lblDIDate.Left = leftB2 - backD; lblDITVersion.Left = leftB2; lblDITVersion.Width = widthB1; lblDITDate.Left = leftB2; lblDITDate.Width = widthB1; lblDITPath.Width = width; lblDITRomsGot.Width = widthB1; lblDITRomsMissing.Width = widthB1; lblDIRomsFixable.Left = leftB2 - backD; lblDIRomsUnknown.Left = leftB2 - backD; lblDITRomsFixable.Left = leftB2; lblDITRomsFixable.Width = widthB1; lblDITRomsUnknown.Left = leftB2; lblDITRomsUnknown.Width = widthB1; } #endregion #region "Game Grid Code" private RvFile GameGridDir; private void UpdateGameGrid(RvFile tDir) { GameGridDir = tDir; lblDITName.Text = tDir.Name; if (tDir.Dat != null) { RvDat tDat = tDir.Dat; lblDITDescription.Text = tDat.GetData(RvDat.DatData.Description); lblDITCategory.Text = tDat.GetData(RvDat.DatData.Category); lblDITVersion.Text = tDat.GetData(RvDat.DatData.Version); lblDITAuthor.Text = tDat.GetData(RvDat.DatData.Author); lblDITDate.Text = tDat.GetData(RvDat.DatData.Date); string header = tDat.GetData(RvDat.DatData.Header); if (!string.IsNullOrWhiteSpace(header)) lblDITName.Text += " (" + header + ")"; } else if (tDir.DirDatCount == 1) { RvDat tDat = tDir.DirDat(0); lblDITDescription.Text = tDat.GetData(RvDat.DatData.Description); lblDITCategory.Text = tDat.GetData(RvDat.DatData.Category); lblDITVersion.Text = tDat.GetData(RvDat.DatData.Version); lblDITAuthor.Text = tDat.GetData(RvDat.DatData.Author); lblDITDate.Text = tDat.GetData(RvDat.DatData.Date); string header = tDat.GetData(RvDat.DatData.Header); if (!string.IsNullOrWhiteSpace(header)) lblDITName.Text += " (" + header + ")"; } else { lblDITDescription.Text = ""; lblDITCategory.Text = ""; lblDITVersion.Text = ""; lblDITAuthor.Text = ""; lblDITDate.Text = ""; } lblDITPath.Text = tDir.FullName; lblDITRomsGot.Text = tDir.DirStatus.CountCorrect().ToString(CultureInfo.InvariantCulture); lblDITRomsMissing.Text = tDir.DirStatus.CountMissing().ToString(CultureInfo.InvariantCulture); lblDITRomsFixable.Text = tDir.DirStatus.CountFixesNeeded().ToString(CultureInfo.InvariantCulture); lblDITRomsUnknown.Text = (tDir.DirStatus.CountUnknown() + tDir.DirStatus.CountInToSort()).ToString(CultureInfo.InvariantCulture); _updatingGameGrid = true; if (Settings.IsMono) { if (GameGrid.RowCount > 0) { GameGrid.CurrentCell = GameGrid[0, 0]; } if (RomGrid.RowCount > 0) { RomGrid.CurrentCell = RomGrid[0, 0]; } } GameGrid.Rows.Clear(); RomGrid.Rows.Clear(); // clear sorting GameGrid.Columns[_gameGridSortColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.None; _gameGridSortColumnIndex = 0; _gameGridSortOrder = SortOrder.Descending; ReportStatus tDirStat; _gameGridColumnXPositions = new int[(int)RepStatus.EndValue]; int rowCount = 0; for (int j = 0; j < tDir.ChildCount; j++) { RvFile tChildDir = tDir.Child(j); if (!tChildDir.IsDir) { continue; } tDirStat = tChildDir.DirStatus; bool gCorrect = tDirStat.HasCorrect(); bool gMissing = tDirStat.HasMissing(); bool gUnknown = tDirStat.HasUnknown(); bool gInToSort = tDirStat.HasInToSort(); bool gFixes = tDirStat.HasFixesNeeded(); bool show = chkBoxShowCorrect.Checked && gCorrect && !gMissing && !gFixes; show = show || chkBoxShowMissing.Checked && gMissing; show = show || chkBoxShowFixed.Checked && gFixes; show = show || gUnknown; show = show || gInToSort; show = show || tChildDir.GotStatus == GotStatus.Corrupt; show = show || !(gCorrect || gMissing || gUnknown || gInToSort || gFixes); if (txtFilter.Text.Length > 0) { show = tChildDir.Name.Contains(txtFilter.Text); } if (!show) { continue; } rowCount++; int columnIndex = 0; for (int l = 0; l < RepairStatus.DisplayOrder.Length; l++) { if (l >= 13) { columnIndex = l; } if (tDirStat.Get(RepairStatus.DisplayOrder[l]) <= 0) { continue; } int len = DigitLength(tDirStat.Get(RepairStatus.DisplayOrder[l])) * 7 + 26; if (len > _gameGridColumnXPositions[columnIndex]) { _gameGridColumnXPositions[columnIndex] = len; } columnIndex++; } } GameGrid.RowCount = rowCount; int t = 0; for (int l = 0; l < (int)RepStatus.EndValue; l++) { int colWidth = _gameGridColumnXPositions[l]; _gameGridColumnXPositions[l] = t; t += colWidth; } int row = 0; for (int j = 0; j < tDir.ChildCount; j++) { RvFile tChildDir = tDir.Child(j); if (!tChildDir.IsDir) { continue; } tDirStat = tChildDir.DirStatus; bool gCorrect = tDirStat.HasCorrect(); bool gMissing = tDirStat.HasMissing(); bool gUnknown = tDirStat.HasUnknown(); bool gFixes = tDirStat.HasFixesNeeded(); bool gInToSort = tDirStat.HasInToSort(); bool show = chkBoxShowCorrect.Checked && gCorrect && !gMissing && !gFixes; show = show || chkBoxShowMissing.Checked && gMissing; show = show || chkBoxShowFixed.Checked && gFixes; show = show || gUnknown; show = show || gInToSort; show = show || tChildDir.GotStatus == GotStatus.Corrupt; show = show || !(gCorrect || gMissing || gUnknown || gInToSort || gFixes); if (txtFilter.Text.Length > 0) { show = tChildDir.Name.Contains(txtFilter.Text); } if (!show) { continue; } GameGrid.Rows[row].Selected = false; GameGrid.Rows[row].Tag = tChildDir; row++; } _updatingGameGrid = false; UpdateRomGrid(tDir); } private static int DigitLength(int number) { int textNumber = number; int len = 0; while (textNumber > 0) { textNumber = textNumber / 10; len++; } return len; } private void GameGridSelectionChanged(object sender, EventArgs e) { UpdateSelectedGame(); } private void GameGridMouseDoubleClick(object sender, MouseEventArgs e) { if (_updatingGameGrid) { return; } if (GameGrid.SelectedRows.Count != 1) { return; } RvFile tGame = (RvFile)GameGrid.SelectedRows[0].Tag; if (tGame.Game == null) { UpdateGameGrid(tGame); DirTree.SetSelected(tGame); } else { string path = tGame.Dat.GetData(RvDat.DatData.DatRootFullName); path = Path.GetDirectoryName(path); if (Settings.rvSettings?.EInfo == null) return; foreach (EmulatorInfo ei in Settings.rvSettings.EInfo) { if (!string.Equals(path, ei.TreeDir, StringComparison.CurrentCultureIgnoreCase)) continue; string commandLineOptions = ei.CommandLine; string dirname = tGame.Parent.FullName; commandLineOptions = commandLineOptions.Replace("{gamename}", tGame.Name); commandLineOptions = commandLineOptions.Replace("{gamedirectory}", dirname); using (Process exeProcess = new Process()) { exeProcess.StartInfo.FileName = ei.ExeName; exeProcess.StartInfo.Arguments = commandLineOptions; exeProcess.StartInfo.UseShellExecute = false; exeProcess.StartInfo.CreateNoWindow = true; exeProcess.Start(); } } } } private void GameGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (_updatingGameGrid) { return; } Rectangle cellBounds = GameGrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false); RvFile tRvDir = (RvFile)GameGrid.Rows[e.RowIndex].Tag; ReportStatus tDirStat = tRvDir.DirStatus; Color bgCol = Color.FromArgb(255, 255, 255); Color fgCol = Color.FromArgb(0, 0, 0); if (cellBounds.Width == 0 || cellBounds.Height == 0) { return; } foreach (RepStatus t1 in RepairStatus.DisplayOrder) { if (tDirStat.Get(t1) <= 0) { continue; } bgCol = _displayColor[(int)t1]; fgCol = _fontColor[(int)t1]; break; } switch (GameGrid.Columns[e.ColumnIndex].Name) { case "Type": { e.CellStyle.BackColor = bgCol; e.CellStyle.SelectionBackColor = bgCol; e.CellStyle.ForeColor = fgCol; Bitmap bmp = new Bitmap(cellBounds.Width, cellBounds.Height); Graphics g = Graphics.FromImage(bmp); string bitmapName; switch (tRvDir.FileType) { case FileType.Zip: if (tRvDir.RepStatus == RepStatus.DirCorrect && tRvDir.ZipStatus == ZipStatus.TrrntZip) { bitmapName = "ZipTZ"; } else { bitmapName = "Zip" + tRvDir.RepStatus; } break; case FileType.SevenZip: if (tRvDir.RepStatus == RepStatus.DirCorrect && tRvDir.ZipStatus == ZipStatus.TrrntZip) { bitmapName = "SevenZipTZ"; } else if (tRvDir.RepStatus == RepStatus.DirCorrect && tRvDir.ZipStatus == ZipStatus.Trrnt7Zip) { bitmapName = "SevenZipT7Z"; } else { bitmapName = "SevenZip" + tRvDir.RepStatus; } break; default: // hack because DirDirInToSort image doesnt exist. if (tRvDir.RepStatus == RepStatus.DirInToSort) { bitmapName = "Dir" + RepStatus.DirUnknown; } else { bitmapName = "Dir" + tRvDir.RepStatus; } break; } Bitmap bm = rvImages.GetBitmap(bitmapName); if (bm != null) { float xSize = (float)bm.Width / bm.Height * (cellBounds.Height - 1); g.DrawImage(bm, (cellBounds.Width - xSize) / 2, 0, xSize, cellBounds.Height - 1); bm.Dispose(); } else { Debug.WriteLine("Missing Graphic for " + bitmapName); } e.Value = bmp; break; } case "CGame": { e.CellStyle.BackColor = bgCol; e.CellStyle.ForeColor = fgCol; if (string.IsNullOrEmpty(tRvDir.FileName)) { e.Value = tRvDir.Name; } else { e.Value = tRvDir.Name + " (Found: " + tRvDir.FileName + ")"; } break; } case "CDescription": { e.CellStyle.BackColor = bgCol; e.CellStyle.ForeColor = fgCol; if (tRvDir.Game != null) { e.Value = tRvDir.Game.GetData(RvGame.GameData.Description); } break; } case "CCorrect": { e.CellStyle.SelectionBackColor = Color.White; Bitmap bmp = new Bitmap(cellBounds.Width, cellBounds.Height); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit; Font drawFont = new Font("Arial", 9); SolidBrush drawBrushBlack = new SolidBrush(Color.Black); int gOff; int columnIndex = 0; for (int l = 0; l < RepairStatus.DisplayOrder.Length; l++) { if (l >= 13) { columnIndex = l; } if (tRvDir.DirStatus.Get(RepairStatus.DisplayOrder[l]) <= 0) { continue; } gOff = _gameGridColumnXPositions[columnIndex]; Bitmap bm = rvImages.GetBitmap(@"G_" + RepairStatus.DisplayOrder[l]); if (bm != null) { g.DrawImage(bm, gOff, 0, 21, 18); bm.Dispose(); } else { Debug.WriteLine("Missing Graphics for " + "G_" + RepairStatus.DisplayOrder[l]); } columnIndex++; } columnIndex = 0; for (int l = 0; l < RepairStatus.DisplayOrder.Length; l++) { if (l >= 13) { columnIndex = l; } if (tRvDir.DirStatus.Get(RepairStatus.DisplayOrder[l]) > 0) { gOff = _gameGridColumnXPositions[columnIndex]; g.DrawString( tRvDir.DirStatus.Get(RepairStatus.DisplayOrder[l]).ToString(CultureInfo.InvariantCulture), drawFont, drawBrushBlack, new PointF(gOff + 20, 3)); columnIndex++; } } drawBrushBlack.Dispose(); drawFont.Dispose(); e.Value = bmp; break; } default: Console.WriteLine( $@"WARN: GameGrid_CellFormatting() unknown column: {GameGrid.Columns[e.ColumnIndex].Name}"); break; } } private void GameGridColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { // only allow sort on CGame/CDescription if (e.ColumnIndex != 1 && e.ColumnIndex != 2) { return; } DataGridViewColumn newColumn = GameGrid.Columns[e.ColumnIndex]; DataGridViewColumn oldColumn = GameGrid.Columns[_gameGridSortColumnIndex]; if (newColumn == oldColumn) { _gameGridSortOrder = _gameGridSortOrder == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending; } else { oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None; _gameGridSortOrder = SortOrder.Ascending; } GameGrid.Sort(new GameGridRowComparer(_gameGridSortOrder, e.ColumnIndex)); newColumn.HeaderCell.SortGlyphDirection = _gameGridSortOrder; _gameGridSortColumnIndex = e.ColumnIndex; } private class GameGridRowComparer : IComparer { private readonly int _sortMod = 1; private readonly int _columnIndex; public GameGridRowComparer(SortOrder sortOrder, int index) { _columnIndex = index; if (sortOrder == SortOrder.Descending) { _sortMod = -1; } } public int Compare(object a, object b) { DataGridViewRow aRow = (DataGridViewRow)a; DataGridViewRow bRow = (DataGridViewRow)b; RvFile aRvDir = (RvFile)aRow?.Tag; RvFile bRvDir = (RvFile)bRow?.Tag; if (aRvDir == null || bRvDir == null) return 0; int result = 0; switch (_columnIndex) { case 1: // CGame result = string.CompareOrdinal(aRvDir.Name, bRvDir.Name); break; case 2: // CDescription string aDes = ""; string bDes = ""; if (aRvDir.Game != null) { aDes = aRvDir.Game.GetData(RvGame.GameData.Description); } if (bRvDir.Game != null) { bDes = bRvDir.Game.GetData(RvGame.GameData.Description); } result = string.CompareOrdinal(aDes, bDes); // if desciptions match, fall through to sorting by name if (result == 0) { result = string.CompareOrdinal(aRvDir.Name, bRvDir.Name); } break; default: Console.WriteLine($@"WARN: GameGridRowComparer::Compare() Invalid columnIndex: {_columnIndex}"); break; } return _sortMod * result; } } #endregion #region "Rom Grid Code" private void splitContainer4_Panel1_Resize(object sender, EventArgs e) { // fixes a rendering issue in mono if (splitGameInfoLists.Panel1.Width == 0) { return; } int chkLeft = splitGameInfoLists.Panel1.Width - 150; if (chkLeft < 430) { chkLeft = 430; } chkBoxShowCorrect.Left = chkLeft; chkBoxShowMissing.Left = chkLeft; chkBoxShowFixed.Left = chkLeft; chkBoxShowMerged.Left = chkLeft; txtFilter.Left = chkLeft; btnClear.Left = chkLeft + txtFilter.Width + 2; picPayPal.Left = chkLeft; picPatreon.Left = chkLeft + picPayPal.Width; gbSetInfo.Width = chkLeft - gbSetInfo.Left - 10; } private void gbSetInfo_Resize(object sender, EventArgs e) { const int leftPos = 84; int rightPos = gbSetInfo.Width - 15; if (rightPos > 750) { rightPos = 750; } int width = rightPos - leftPos; if (_textGameName == null) { return; } { int textWidth = (int)((double)width * 120 / 340); int text2Left = leftPos + width - textWidth; int label2Left = text2Left - 78; _textGameName.Width = width; _textGameDescription.Width = width; _textGameManufacturer.Width = width; _textGameCloneOf.Width = textWidth; _labelGameYear.Left = label2Left; _textGameYear.Left = text2Left; _textGameYear.Width = textWidth; _textGameRomOf.Width = textWidth; _labelGameTotalRoms.Left = label2Left; _textGameTotalRoms.Left = text2Left; _textGameTotalRoms.Width = textWidth; } { int textWidth = (int)(width * 0.20); int text2Left = (int)(width * 0.4 + leftPos); int label2Left = text2Left - 78; int text3Left = leftPos + width - textWidth; int label3Left = text3Left - 78; _textTruripPublisher.Width = (int)(width * 0.6); _textTruripDeveloper.Width = (int)(width * 0.6); _textTruripCloneOf.Width = width; _textTruripRelatedTo.Width = width; _textTruripYear.Width = textWidth; _textTruripPlayers.Width = textWidth; _labelTruripGenre.Left = label2Left; _textTruripGenre.Left = text2Left; _textTruripGenre.Width = textWidth; _labelTruripSubGenre.Left = label2Left; _textTruripSubGenre.Left = text2Left; _textTruripSubGenre.Width = textWidth; _labelTruripTitleId.Left = label3Left; _textTruripTitleId.Left = text3Left; _textTruripTitleId.Width = textWidth; _labelTruripSource.Left = label3Left; _textTruripSource.Left = text3Left; _textTruripSource.Width = textWidth; _labelTruripRatings.Left = label3Left; _textTruripRatings.Left = text3Left; _textTruripRatings.Width = textWidth; _labelTruripScore.Left = label3Left; _textTruripScore.Left = text3Left; _textTruripScore.Width = textWidth; } } private void UpdateSelectedGame() { if (_updatingGameGrid) { return; } if (GameGrid.SelectedRows.Count != 1) { return; } RvFile tGame = (RvFile)GameGrid.SelectedRows[0].Tag; UpdateRomGrid(tGame); } private void UpdateRomGrid(RvFile tGame) { _labelGameName.Visible = true; _textGameName.Text = tGame.Name; if (tGame.Game == null) { _labelGameDescription.Visible = false; _textGameDescription.Visible = false; } if (tGame.Game == null || tGame.Game.GetData(RvGame.GameData.EmuArc) != "yes") { _labelTruripPublisher.Visible = false; _textTruripPublisher.Visible = false; _labelTruripDeveloper.Visible = false; _textTruripDeveloper.Visible = false; _labelTruripTitleId.Visible = false; _textTruripTitleId.Visible = false; _labelTruripSource.Visible = false; _textTruripSource.Visible = false; _labelTruripCloneOf.Visible = false; _textTruripCloneOf.Visible = false; _labelTruripRelatedTo.Visible = false; _textTruripRelatedTo.Visible = false; _labelTruripYear.Visible = false; _textTruripYear.Visible = false; _labelTruripPlayers.Visible = false; _textTruripPlayers.Visible = false; _labelTruripGenre.Visible = false; _textTruripGenre.Visible = false; _labelTruripSubGenre.Visible = false; _textTruripSubGenre.Visible = false; _labelTruripRatings.Visible = false; _textTruripRatings.Visible = false; _labelTruripScore.Visible = false; _textTruripScore.Visible = false; } if (tGame.Game == null || tGame.Game.GetData(RvGame.GameData.EmuArc) == "yes") { _labelGameManufacturer.Visible = false; _textGameManufacturer.Visible = false; _labelGameCloneOf.Visible = false; _textGameCloneOf.Visible = false; _labelGameRomOf.Visible = false; _textGameRomOf.Visible = false; _labelGameYear.Visible = false; _textGameYear.Visible = false; _labelGameTotalRoms.Visible = false; _textGameTotalRoms.Visible = false; } if (tGame.Game != null) { if (tGame.Game.GetData(RvGame.GameData.EmuArc) == "yes") { _labelGameDescription.Visible = true; _textGameDescription.Visible = true; _textGameDescription.Text = tGame.Game.GetData(RvGame.GameData.Description); _labelTruripPublisher.Visible = true; _textTruripPublisher.Visible = true; _textTruripPublisher.Text = tGame.Game.GetData(RvGame.GameData.Publisher); _labelTruripDeveloper.Visible = true; _textTruripDeveloper.Visible = true; _textTruripDeveloper.Text = tGame.Game.GetData(RvGame.GameData.Developer); _labelTruripTitleId.Visible = true; _textTruripTitleId.Visible = true; _textTruripTitleId.Text = tGame.Game.GetData(RvGame.GameData.TitleId); _labelTruripSource.Visible = true; _textTruripSource.Visible = true; _textTruripSource.Text = tGame.Game.GetData(RvGame.GameData.Source); _labelTruripCloneOf.Visible = true; _textTruripCloneOf.Visible = true; _textTruripCloneOf.Text = tGame.Game.GetData(RvGame.GameData.CloneOf); _labelTruripRelatedTo.Visible = true; _textTruripRelatedTo.Visible = true; _textTruripRelatedTo.Text = tGame.Game.GetData(RvGame.GameData.RelatedTo); _labelTruripYear.Visible = true; _textTruripYear.Visible = true; _textTruripYear.Text = tGame.Game.GetData(RvGame.GameData.Year); _labelTruripPlayers.Visible = true; _textTruripPlayers.Visible = true; _textTruripPlayers.Text = tGame.Game.GetData(RvGame.GameData.Players); _labelTruripGenre.Visible = true; _textTruripGenre.Visible = true; _textTruripGenre.Text = tGame.Game.GetData(RvGame.GameData.Genre); _labelTruripSubGenre.Visible = true; _textTruripSubGenre.Visible = true; _textTruripSubGenre.Text = tGame.Game.GetData(RvGame.GameData.SubGenre); _labelTruripRatings.Visible = true; _textTruripRatings.Visible = true; _textTruripRatings.Text = tGame.Game.GetData(RvGame.GameData.Ratings); _labelTruripScore.Visible = true; _textTruripScore.Visible = true; _textTruripScore.Text = tGame.Game.GetData(RvGame.GameData.Score); LoadPannels(tGame); } else { HidePannel(); _labelGameDescription.Visible = true; _textGameDescription.Visible = true; _textGameDescription.Text = tGame.Game.GetData(RvGame.GameData.Description); _labelGameManufacturer.Visible = true; _textGameManufacturer.Visible = true; _textGameManufacturer.Text = tGame.Game.GetData(RvGame.GameData.Manufacturer); _labelGameCloneOf.Visible = true; _textGameCloneOf.Visible = true; _textGameCloneOf.Text = tGame.Game.GetData(RvGame.GameData.CloneOf); _labelGameRomOf.Visible = true; _textGameRomOf.Visible = true; _textGameRomOf.Text = tGame.Game.GetData(RvGame.GameData.RomOf); _labelGameYear.Visible = true; _textGameYear.Visible = true; _textGameYear.Text = tGame.Game.GetData(RvGame.GameData.Year); _labelGameTotalRoms.Visible = true; _textGameTotalRoms.Visible = true; } } else { HidePannel(); } if (Settings.IsMono && RomGrid.RowCount > 0) { RomGrid.CurrentCell = RomGrid[0, 0]; } RomGrid.Rows.Clear(); AddDir(tGame, ""); GC.Collect(); } private void AddDir(RvFile tGame, string pathAdd) { for (int l = 0; l < tGame.ChildCount; l++) { RvFile tBase = tGame.Child(l); RvFile tFile = tBase; if (tFile.IsFile) { AddRom(tFile, pathAdd); } if (tGame.Dat == null) { continue; } RvFile tDir = tBase; if (!tDir.IsDir) { continue; } if (tDir.Game == null) { AddDir(tDir, pathAdd + tGame.Name + "/"); } } } // returns either white or black, depending of quick luminance of the Color " a " // called when the _displayColor is finished, in order to populate the _fontColor table. private static Color Contrasty(Color a) { return (a.R << 1) + a.B + a.G + (a.G << 2) < 1024 ? Color.White : Color.Black; } private void AddRom(RvFile tRomTable, string pathAdd) { if (tRomTable.DatStatus != DatStatus.InDatMerged || tRomTable.RepStatus != RepStatus.NotCollected || chkBoxShowMerged.Checked) { RomGrid.Rows.Add(); int row = RomGrid.Rows.Count - 1; RomGrid.Rows[row].Tag = tRomTable; for (int i = 0; i < RomGrid.Rows[row].Cells.Count; i++) { DataGridViewCellStyle cs = RomGrid.Rows[row].Cells[i].Style; cs.BackColor = _displayColor[(int)tRomTable.RepStatus]; cs.ForeColor = _fontColor[(int)tRomTable.RepStatus]; } string fname = pathAdd + tRomTable.Name; if (!string.IsNullOrEmpty(tRomTable.FileName)) { fname += " (Found: " + tRomTable.FileName + ")"; } if (tRomTable.CHDVersion != null) { fname += " (V" + tRomTable.CHDVersion + ")"; } if (tRomTable.HeaderFileType != HeaderFileType.Nothing) { fname += " (" + tRomTable.HeaderFileType + ")"; } RomGrid.Rows[row].Cells["CRom"].Value = fname; RomGrid.Rows[row].Cells["CMerge"].Value = tRomTable.Merge; RomGrid.Rows[row].Cells["CStatus"].Value = tRomTable.Status; SetCell(RomGrid.Rows[row].Cells["CSize"], tRomTable.Size.ToString(), tRomTable, FileStatus.SizeFromDAT, FileStatus.SizeFromHeader, FileStatus.SizeVerified); SetCell(RomGrid.Rows[row].Cells["CCRC32"], tRomTable.CRC.ToHexString(), tRomTable, FileStatus.CRCFromDAT, FileStatus.CRCFromHeader, FileStatus.CRCVerified); SetCell(RomGrid.Rows[row].Cells["CSHA1"], tRomTable.SHA1.ToHexString(), tRomTable, FileStatus.SHA1FromDAT, FileStatus.SHA1FromHeader, FileStatus.SHA1Verified); SetCell(RomGrid.Rows[row].Cells["CMD5"], tRomTable.MD5.ToHexString(), tRomTable, FileStatus.MD5FromDAT, FileStatus.MD5FromHeader, FileStatus.MD5Verified); SetCell(RomGrid.Rows[row].Cells["CAltSize"], tRomTable.AltSize.ToString(), tRomTable, FileStatus.AltSizeFromDAT, FileStatus.AltSizeFromHeader, FileStatus.AltSizeVerified); SetCell(RomGrid.Rows[row].Cells["CAltCRC32"], tRomTable.AltCRC.ToHexString(), tRomTable, FileStatus.AltCRCFromDAT, FileStatus.AltCRCFromHeader, FileStatus.AltCRCVerified); SetCell(RomGrid.Rows[row].Cells["CAltSHA1"], tRomTable.AltSHA1.ToHexString(), tRomTable, FileStatus.AltSHA1FromDAT, FileStatus.AltSHA1FromHeader, FileStatus.AltSHA1Verified); SetCell(RomGrid.Rows[row].Cells["CAltMD5"], tRomTable.AltMD5.ToHexString(), tRomTable, FileStatus.AltMD5FromDAT, FileStatus.AltMD5FromHeader, FileStatus.AltMD5Verified); if (tRomTable.FileType == FileType.ZipFile) { RomGrid.Rows[row].Cells["ZipIndex"].Value = tRomTable.ZipFileIndex == -1 ? "" : tRomTable.ZipFileIndex.ToString(CultureInfo.InvariantCulture); RomGrid.Rows[row].Cells["ZipHeader"].Value = tRomTable.ZipFileHeaderPosition == null ? "" : tRomTable.ZipFileHeaderPosition.ToString(); } } } private static void SetCell(DataGridViewCell cell, string txt, RvFile tRomTable, FileStatus dat, FileStatus file, FileStatus verified) { cell.Value = txt + ShowFlags(tRomTable, dat, file, verified); if (!string.IsNullOrWhiteSpace(txt) && !tRomTable.FileStatusIs(dat)) cell.Style.ForeColor = Color.FromArgb(0, 0, 255); } private static string ShowFlags(RvFile tRomTable, FileStatus dat, FileStatus file, FileStatus verified) { string flags = ""; if (tRomTable.FileStatusIs(dat)) { flags += "D"; } if (tRomTable.FileStatusIs(file)) { flags += "F"; } if (tRomTable.FileStatusIs(verified)) { flags += "V"; } if (!string.IsNullOrEmpty(flags)) { flags = " (" + flags + ")"; } return flags; } private void RomGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (_updatingGameGrid) { return; } Rectangle cellBounds = RomGrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false); RvFile tRvFile = (RvFile)RomGrid.Rows[e.RowIndex].Tag; if (cellBounds.Width == 0 || cellBounds.Height == 0) { return; } if (RomGrid.Columns[e.ColumnIndex].Name == "CGot") { Bitmap bmp = new Bitmap(cellBounds.Width, cellBounds.Height); Graphics g = Graphics.FromImage(bmp); string bitmapName = "R_" + tRvFile.DatStatus + "_" + tRvFile.RepStatus; Bitmap romIcon = rvImages.GetBitmap(bitmapName); if (romIcon != null) { g.DrawImage(romIcon, 0, 0, 54, 18); e.Value = bmp; } else { Debug.WriteLine($"Missing image for {bitmapName}"); } } } #endregion private void picPayPal_Click(object sender, EventArgs e) { Process.Start("http://paypal.me/romvault"); } private void picPatreon_Click(object sender, EventArgs e) { Process.Start("https://www.patreon.com/romvault"); } /* private void jsonDataDumpToolStripMenuItem_Click(object sender, EventArgs e) { DB.WriteJson(); } */ private void TabArtworkInitialize() { splitListArt.Panel2Collapsed = true; splitListArt.Panel2.Hide(); tabArtWork_Resize(null, new EventArgs()); tabScreens_Resize(null, new EventArgs()); tabInfo_Resize(null, new EventArgs()); } private void tabArtWork_Resize(object sender, EventArgs e) { int imageWidth = tabArtWork.Width - 20; if (imageWidth < 2) imageWidth = 2; picArtwork.Left = 10; picArtwork.Width = imageWidth; picArtwork.Top = (int)(tabArtWork.Height * 0.05); picArtwork.Height = (int)(tabArtWork.Height * 0.4); picLogo.Left = 10; picLogo.Width = imageWidth; picLogo.Top = (int)(tabArtWork.Height * 0.55); picLogo.Height = (int)(tabArtWork.Height * 0.4); } private void tabScreens_Resize(object sender, EventArgs e) { int imageWidth = tabScreens.Width - 20; if (imageWidth < 2) imageWidth = 2; picScreenTitle.Left = 10; picScreenTitle.Width = imageWidth; picScreenTitle.Top = (int)(tabScreens.Height * 0.05); picScreenTitle.Height = (int)(tabScreens.Height * 0.4); picScreenShot.Left = 10; picScreenShot.Width = imageWidth; picScreenShot.Top = (int)(tabScreens.Height * 0.55); picScreenShot.Height = (int)(tabScreens.Height * 0.4); } private void tabInfo_Resize(object sender, EventArgs e) { } private void LoadPannels(RvFile tGame) { TabEmuArc.TabPages.Remove(tabArtWork); TabEmuArc.TabPages.Remove(tabScreens); TabEmuArc.TabPages.Remove(tabInfo); /* * artwork_front.png * artowrk_back.png * logo.png * medium_front.png * screentitle.png * screenshot.png * story.txt * * System.Diagnostics.Process.Start(@"D:\stage\RomVault\RomRoot\SNK\Neo Geo CD (World) - SuperDAT\Games\Double Dragon (19950603)\video.mp4"); * */ bool artLoaded = picArtwork.TryLoadImage(tGame, "artwork_front"); bool logoLoaded = picLogo.TryLoadImage(tGame, "logo"); bool titleLoaded = picScreenTitle.TryLoadImage(tGame, "screentitle"); bool screenLoaded = picScreenShot.TryLoadImage(tGame, "screenshot"); bool storyLoaded = txtInfo.LoadText(tGame, "story.txt"); if (artLoaded || logoLoaded) TabEmuArc.TabPages.Add(tabArtWork); if (titleLoaded || screenLoaded) TabEmuArc.TabPages.Add(tabScreens); if (storyLoaded) TabEmuArc.TabPages.Add(tabInfo); if (artLoaded || logoLoaded || titleLoaded || screenLoaded || storyLoaded) { splitListArt.Panel2Collapsed = false; splitListArt.Panel2.Show(); } else { splitListArt.Panel2Collapsed = true; splitListArt.Panel2.Hide(); } } private void HidePannel() { splitListArt.Panel2Collapsed = true; splitListArt.Panel2.Hide(); picArtwork.ClearImage(); picLogo.ClearImage(); picScreenTitle.ClearImage(); picScreenShot.ClearImage(); txtInfo.ClearText(); } private void colorKeyToolStripMenuItem_Click(object sender, EventArgs e) { if (_fk == null || _fk.IsDisposed) { _fk = new FrmKey(); } _fk.Show(); } private void BtnClear_Click(object sender, EventArgs e) { txtFilter.Text = ""; } private void TxtFilter_TextChanged(object sender, EventArgs e) { if (GameGridDir != null) UpdateGameGrid(GameGridDir); } private void RomVaultSettingsToolStripMenuItem_Click(object sender, EventArgs e) { using (FrmSettings fcfg = new FrmSettings()) { fcfg.ShowDialog(this); } } private void RegistrationSettingsToolStripMenuItem_Click(object sender, EventArgs e) { using (FrmRegistration fReg = new FrmRegistration()) { fReg.ShowDialog(); } } private void DirectorySettingsToolStripMenuItem_Click(object sender, EventArgs e) { using (FrmSetDirSettings sd = new FrmSetDirSettings()) { string tDir = "RomVault"; sd.SetLocation(tDir); sd.SetDisplayType(false); sd.ShowDialog(this); if (sd.ChangesMade) UpdateDats(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics.Contracts; using System.Linq; using System.Text; namespace Torshify.Radio.Framework { /// <summary> /// Extension methods for all kinds of (typed) enumerable data (Array, List, ...) /// </summary> public static class EnumerableExtensions { #region Methods [Pure] public static IEnumerable<TTarget> CountSelect<TSource, TTarget>(this IEnumerable<TSource> source, Func<TSource, int, TTarget> func) { int i = 0; foreach (var item in source) { yield return func(item, i++); } } /// <summary> /// Returns true if all items in the list are unique using /// <see cref="EqualityComparer{T}.Default">EqualityComparer&lt;T&gt;.Default</see>. /// </summary> /// <exception cref="ArgumentNullException">if <param name="source"/> is null.</exception> [Pure] public static bool AllUnique<T>(this IList<T> source) { EqualityComparer<T> comparer = EqualityComparer<T>.Default; return source.TrueForAllPairs((a, b) => !comparer.Equals(a, b)); } /// <summary> /// Returns true if <paramref name="compare"/> returns /// true for every pair of items in <paramref name="source"/>. /// </summary> [Pure] public static bool TrueForAllPairs<T>(this IList<T> source, Func<T, T, bool> compare) { for (int i = 0; i < source.Count; i++) { for (int j = i + 1; j < source.Count; j++) { if (!compare(source[i], source[j])) { return false; } } } return true; } /// <summary> /// Returns true if <paramref name="compare"/> returns true of every /// adjacent pair of items in the <paramref name="source"/>. /// </summary> /// <remarks> /// <para> /// If there are n items in the collection, n-1 comparisons are done. /// </para> /// <para> /// Every valid [i] and [i+1] pair are passed into <paramref name="compare"/>. /// </para> /// <para> /// If <paramref name="source"/> has 0 or 1 items, true is returned. /// </para> /// </remarks> [Pure] public static bool TrueForAllAdjacentPairs<T>(this IEnumerable<T> source, Func<T, T, bool> compare) { return source.SelectAdjacentPairs().All(t => compare(t.Item1, t.Item2)); } public static IEnumerable<Tuple<T, T>> SelectAdjacentPairs<T>(this IEnumerable<T> source) { bool hasPrevious = false; T previous = default(T); foreach (var item in source) { if (!hasPrevious) { previous = item; hasPrevious = true; } else { yield return Tuple.Create(previous, item); previous = item; } } } /// <summary> /// Returns true if all of the items in <paramref name="source"/> are not /// null or empty. /// </summary> /// <exception cref="ArgumentNullException">if <param name="source"/> is null.</exception> [Pure] public static bool AllNotNullOrEmpty(this IEnumerable<string> source) { return source.All(item => !string.IsNullOrEmpty(item)); } /// <summary> /// Returns true if all items in <paramref name="source"/> exist /// in <paramref name="set"/>. /// </summary> /// <exception cref="ArgumentNullException">if <param name="source"/> or <param name="set"/> are null.</exception> [Pure] public static bool AllExistIn<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> set) { return source.All(set.Contains); } /// <summary> /// Returns true if <paramref name="source"/> has no items in it; otherwise, false. /// </summary> /// <remarks> /// <para> /// If an <see cref="ICollection{TSource}"/> is provided, /// <see cref="ICollection{TSource}.Count"/> is used. /// </para> /// <para> /// Yes, this does basically the same thing as the /// <see cref="System.Linq.Enumerable.Any{TSource}(IEnumerable{TSource})"/> /// extention. The differences: 'IsEmpty' is easier to remember and it leverages /// <see cref="ICollection{TSource}.Count">ICollection.Count</see> if it exists. /// </para> /// </remarks> [Pure] public static bool IsEmpty<TSource>(this IEnumerable<TSource> source) { if (source is ICollection<TSource>) { return ((ICollection<TSource>)source).Count == 0; } else { using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { return !enumerator.MoveNext(); } } } /// <summary> /// Returns the index of the first item in <paramref name="source"/> /// for which <paramref name="predicate"/> returns true. If none, -1. /// </summary> /// <param name="source">The source enumerable.</param> /// <param name="predicate">The function to evaluate on each element.</param> [Pure] public static int IndexOf<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { int index = 0; foreach (TSource item in source) { if (predicate(item)) { return index; } index++; } return -1; } /// <summary> /// Returns a new <see cref="ReadOnlyCollection{T}"/> using the /// contents of <paramref name="source"/>. /// </summary> /// <remarks> /// The contents of <paramref name="source"/> are copied to /// an array to ensure the contents of the returned value /// don't mutate. /// </remarks> public static ReadOnlyCollection<TSource> ToReadOnlyCollection<TSource>(this IEnumerable<TSource> source) { return new ReadOnlyCollection<TSource>(source.ToArray()); } /// <summary> /// Removes the last element from <paramref name="source"/>. /// </summary> /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">The list from which to remove the last element.</param> /// <returns>The last element.</returns> /// <remarks><paramref name="source"/> must have at least one element and allow changes.</remarks> public static TSource RemoveLast<TSource>(this IList<TSource> source) { TSource item = source[source.Count - 1]; source.RemoveAt(source.Count - 1); return item; } /// <summary> /// If <paramref name="source"/> is null, return an empty <see cref="IEnumerable{TSource}"/>; /// otherwise, return <paramref name="source"/>. /// </summary> public static IEnumerable<TSource> EmptyIfNull<TSource>(this IEnumerable<TSource> source) { return source ?? Enumerable.Empty<TSource>(); } /// <summary> /// Recursively projects each nested element to an <see cref="IEnumerable{TSource}"/> /// and flattens the resulting sequences into one sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">A sequence of values to project.</param> /// <param name="recursiveSelector">A transform to apply to each element.</param> /// <returns> /// An <see cref="IEnumerable{TSource}"/> whose elements are the /// result of recursively invoking the recursive transform function /// on each element and nested element of the input sequence. /// </returns> /// <remarks>This is a depth-first traversal. Be careful if you're using this to find something /// shallow in a deep tree.</remarks> public static IEnumerable<TSource> SelectRecursive<TSource>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TSource>> recursiveSelector) { Stack<IEnumerator<TSource>> stack = new Stack<IEnumerator<TSource>>(); stack.Push(source.GetEnumerator()); try { while (stack.Count > 0) { if (stack.Peek().MoveNext()) { TSource current = stack.Peek().Current; yield return current; stack.Push(recursiveSelector(current).GetEnumerator()); } else { stack.Pop().Dispose(); } } } finally { while (stack.Count > 0) { stack.Pop().Dispose(); } } } public static IEnumerable<T> Concat<T>(this IEnumerable<T> source, params T[] items) { return source.Concat(items.AsEnumerable()); } [Pure] public static bool Contains<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { return dictionary.Contains(new KeyValuePair<TKey, TValue>(key, value)); } [Pure] public static bool CountAtLeast<T>(this IEnumerable<T> source, int count) { if (source is ICollection<T>) { return ((ICollection<T>)source).Count >= count; } else { using (var enumerator = source.GetEnumerator()) { while (count > 0) { if (enumerator.MoveNext()) { count--; } else { return false; } } } return true; } } public static IEnumerable<TSource> Except<TSource, TOther>(this IEnumerable<TSource> source, IEnumerable<TOther> other, Func<TSource, TOther, bool> comparer) { return from item in source where !other.Any(x => comparer(item, x)) select item; } public static IEnumerable<TSource> Intersect<TSource, TOther>(this IEnumerable<TSource> source, IEnumerable<TOther> other, Func<TSource, TOther, bool> comparer) { return from item in source where other.Any(x => comparer(item, x)) select item; } public static INotifyCollectionChanged AsINPC<T>(this ReadOnlyObservableCollection<T> source) { return (INotifyCollectionChanged)source; } /// <summary> /// Creates an <see cref="ObservableCollection{T}"/> from the <see cref="IEnumerable"/>. /// </summary> /// <typeparam name="T">The type of the source elements.</typeparam> /// <param name="source">The <see cref="IEnumerable"/> to create the <see cref="ObservableCollection{T}"/> from.</param> /// <returns>An <see cref="ObservableCollection{T}"/> that contains elements from the input sequence.</returns> public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source) { return new ObservableCollection<T>(source); } /// <summary> /// Performs an action for each item in the enumerable /// </summary> /// <typeparam name = "T">The enumerable data type</typeparam> /// <param name = "values">The data values.</param> /// <param name = "action">The action to be performed.</param> /// <example> /// var values = new[] { "1", "2", "3" }; /// values.ConvertList&lt;string, int&gt;().ForEach(Console.WriteLine); /// </example> /// <remarks> /// This method was intended to return the passed values to provide method chaining. Howver due to defered execution the compiler would actually never run the entire code at all. /// </remarks> public static void ForEach<T>(this IEnumerable<T> values, Action<T> action) { foreach (var value in values) action(value); } ///<summary> /// Returns enumerable object based on target, which does not contains null references. /// If target is null reference, returns empty enumerable object. ///</summary> ///<typeparam name = "T">Type of items in target.</typeparam> ///<param name = "target">Target enumerable object. Can be null.</param> ///<example> /// object[] items = null; /// foreach(var item in items.NotNull()){ /// // result of items.NotNull() is empty but not null enumerable /// } /// /// object[] items = new object[]{ null, "Hello World!", null, "Good bye!" }; /// foreach(var item in items.NotNull()){ /// // result of items.NotNull() is enumerable with two strings /// } ///</example> ///<remarks> /// Contributed by tencokacistromy, http://www.codeplex.com/site/users/view/tencokacistromy ///</remarks> public static IEnumerable<T> IgnoreNulls<T>(this IEnumerable<T> target) { if (ReferenceEquals(target, null)) yield break; foreach (var item in target.Where(item => !ReferenceEquals(item, null))) yield return item; } /// <summary> /// Returns the maximum item based on a provided selector. /// </summary> /// <typeparam name = "TItem">The item type</typeparam> /// <typeparam name = "TValue">The value item</typeparam> /// <param name = "items">The items.</param> /// <param name = "selector">The selector.</param> /// <param name = "maxValue">The max value as output parameter.</param> /// <returns>The maximum item</returns> /// <example> /// <code> /// int age; /// var oldestPerson = persons.MaxItem(p =&gt; p.Age, out age); /// </code> /// </example> public static TItem MaxItem<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> selector, out TValue maxValue) where TItem : class where TValue : IComparable { TItem maxItem = null; maxValue = default(TValue); foreach (var item in items) { if (item == null) continue; var itemValue = selector(item); if ((maxItem != null) && (itemValue.CompareTo(maxValue) <= 0)) continue; maxValue = itemValue; maxItem = item; } return maxItem; } /// <summary> /// Returns the maximum item based on a provided selector. /// </summary> /// <typeparam name = "TItem">The item type</typeparam> /// <typeparam name = "TValue">The value item</typeparam> /// <param name = "items">The items.</param> /// <param name = "selector">The selector.</param> /// <returns>The maximum item</returns> /// <example> /// <code> /// var oldestPerson = persons.MaxItem(p =&gt; p.Age); /// </code> /// </example> public static TItem MaxItem<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> selector) where TItem : class where TValue : IComparable { TValue maxValue; return items.MaxItem(selector, out maxValue); } /// <summary> /// Returns the minimum item based on a provided selector. /// </summary> /// <typeparam name = "TItem">The item type</typeparam> /// <typeparam name = "TValue">The value item</typeparam> /// <param name = "items">The items.</param> /// <param name = "selector">The selector.</param> /// <param name = "minValue">The min value as output parameter.</param> /// <returns>The minimum item</returns> /// <example> /// <code> /// int age; /// var youngestPerson = persons.MinItem(p =&gt; p.Age, out age); /// </code> /// </example> public static TItem MinItem<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> selector, out TValue minValue) where TItem : class where TValue : IComparable { TItem minItem = null; minValue = default(TValue); foreach (var item in items) { if (item == null) continue; var itemValue = selector(item); if ((minItem != null) && (itemValue.CompareTo(minValue) >= 0)) continue; minValue = itemValue; minItem = item; } return minItem; } /// <summary> /// Returns the minimum item based on a provided selector. /// </summary> /// <typeparam name = "TItem">The item type</typeparam> /// <typeparam name = "TValue">The value item</typeparam> /// <param name = "items">The items.</param> /// <param name = "selector">The selector.</param> /// <returns>The minimum item</returns> /// <example> /// <code> /// var youngestPerson = persons.MinItem(p =&gt; p.Age); /// </code> /// </example> public static TItem MinItem<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> selector) where TItem : class where TValue : IComparable { TValue minValue; return items.MinItem(selector, out minValue); } ///<summary> /// Get Distinct ///</summary> ///<param name = "source"></param> ///<param name = "expression"></param> ///<typeparam name = "T"></typeparam> ///<typeparam name = "TKey"></typeparam> ///<returns></returns> /// <remarks> /// Contributed by Michael T, http://about.me/MichaelTran /// </remarks> public static IEnumerable<T> Distinct<T, TKey>(this IEnumerable<T> source, Func<T, TKey> expression) { return source == null ? Enumerable.Empty<T>() : source.GroupBy(expression).Select(i => i.First()); } /// <summary> /// Removes matching items from a sequence /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="predicate">The predicate.</param> /// <returns></returns> /// /// <remarks> /// Renamed by James Curran, to match corresponding HashSet.RemoveWhere() /// </remarks> public static IEnumerable<T> RemoveWhere<T>(this IEnumerable<T> source, Predicate<T> predicate) { if (source == null) yield break; foreach (T t in source) if (!predicate(t)) yield return t; } ///<summary> /// Remove item from a list ///</summary> ///<param name = "source"></param> ///<param name = "predicate"></param> ///<typeparam name = "T"></typeparam> ///<returns></returns> /// <remarks> /// Contributed by Michael T, http://about.me/MichaelTran /// </remarks> [Obsolete("Use RemoveWhere instead..")] public static IEnumerable<T> RemoveAll<T>(this IEnumerable<T> source, Predicate<T> predicate) { if (source == null) return Enumerable.Empty<T>(); var list = source.ToList(); list.RemoveAll(predicate); return list; } ///<summary> /// Turn the list of objects to a string of Common Seperated Value ///</summary> ///<param name="source"></param> ///<param name="separator"></param> ///<typeparam name="T"></typeparam> ///<returns></returns> /// <example> /// <code> /// var values = new[] { 1, 2, 3, 4, 5 }; /// string csv = values.ToCSV(';'); /// </code> /// </example> /// <remarks> /// Contributed by Moses, http://mosesofegypt.net /// </remarks> public static string ToCSV<T>(this IEnumerable<T> source, char separator) { if (source == null) return string.Empty; var csv = new StringBuilder(); source.ForEach(value => csv.AppendFormat("{0}{1}", value, separator)); return csv.ToString(0, csv.Length - 1); } ///<summary> /// Turn the list of objects to a string of Common Seperated Value ///</summary> ///<param name="source"></param> ///<typeparam name="T"></typeparam> ///<returns></returns> /// <example> /// <code> /// var values = new[] {1, 2, 3, 4, 5}; /// string csv = values.ToCSV(); /// </code> /// </example> /// <remarks> /// Contributed by Moses, http://mosesofegypt.net /// </remarks> public static string ToCSV<T>(this IEnumerable<T> source) { return source.ToCSV(','); } /// <summary> /// Overload the Select to allow null as a return /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="source"></param> /// <param name="selector"></param> /// <param name="allowNull"></param> /// <returns>An <see cref="IEnumerable{TResult}"/> using the selector containing null or non-null results based on <see cref="allowNull"/>.</returns> /// <example> /// <code> /// var list = new List{object}{ new object(), null, null }; /// var noNulls = list.Select(x => x, false); /// </code> /// </example> /// <remarks> /// Contributed by thinktech_coder /// </remarks> public static IEnumerable<TResult> Select<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector, bool allowNull = true) { foreach (var item in source) { var select = selector(item); if (allowNull || !Equals(select, default(TSource))) yield return select; } } /// <summary> /// Returns true if the <paramref name="source"/> is null or without any items. /// </summary> public static bool IsNullOrEmpty<T>(this IEnumerable<T> source) { return (source == null || !source.Any()); } /// <summary> /// Returns true if the <paramref name="source"/> is contains at least one item. /// </summary> public static bool IsNotEmpty<T>(this IEnumerable<T> source) { return !source.IsNullOrEmpty(); } /// <summary> /// Appends an element to the end of the current collection and returns the new collection. /// </summary> /// <typeparam name="T">The enumerable data type</typeparam> /// <param name="source">The data values.</param> /// <param name="item">The element to append the current collection with.</param> /// <returns> /// The modified collection. /// </returns> /// <example> /// var integers = Enumerable.Range(0, 3); // 0, 1, 2 /// integers = integers.Append(3); // 0, 1, 2, 3 /// </example> public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T item) { foreach (var i in source) yield return i; yield return item; } /// <summary> /// Prepends an element to the start of the current collection and returns the new collection. /// </summary> /// <typeparam name="T">The enumerable data type</typeparam> /// <param name="source">The data values.</param> /// <param name="item">The element to prepend the current collection with.</param> /// <returns> /// The modified collection. /// </returns> /// <example> /// var integers = Enumerable.Range(1, 3); // 1, 2, 3 /// integers = integers.Prepend(0); // 0, 1, 2, 3 /// </example> public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item) { yield return item; foreach (var i in source) yield return i; } /// <summary> /// Creates an Array from an IEnumerable&lt;T&gt; using the specified transform function. /// </summary> /// <typeparam name="TSource">The source data type</typeparam> /// <typeparam name="TResult">The target data type</typeparam> /// <param name="source">The source data.</param> /// <param name="selector">A transform function to apply to each element.</param> /// <returns>An Array of the target data type</returns> /// <example> /// var integers = Enumerable.Range(1, 3); /// var intStrings = values.ToArray(i => i.ToString()); /// </example> /// <remarks> /// This method is a shorthand for the frequently use pattern IEnumerable&lt;T&gt;.Select(Func).ToArray() /// </remarks> public static TResult[] ToArray<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector) { return source.Select(selector).ToArray(); } /// <summary> /// Creates a List&lt;T&gt; from an IEnumerable&lt;T&gt; using the specified transform function. /// </summary> /// <typeparam name="TSource">The source data type</typeparam> /// <typeparam name="TResult">The target data type</typeparam> /// <param name="source">The source data.</param> /// <param name="selector">A transform function to apply to each element.</param> /// <returns>An IEnumerable&lt;T&gt; of the target data type</returns> /// <example> /// var integers = Enumerable.Range(1, 3); /// var intStrings = values.ToList(i => i.ToString()); /// </example> /// <remarks> /// This method is a shorthand for the frequently use pattern IEnumerable&lt;T&gt;.Select(Func).ToList() /// </remarks> public static List<TResult> ToList<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector) { return source.Select(selector).ToList(); } /// <summary> /// Computes the sum of a sequence of UInt32 values. /// </summary> /// <param name="source">A sequence of UInt32 values to calculate the sum of.</param> /// <returns>The sum of the values in the sequence.</returns> public static uint Sum(this IEnumerable<uint> source) { return source.Aggregate(0U, (current, number) => current + number); } /// <summary> /// Computes the sum of a sequence of UInt64 values. /// </summary> /// <param name="source">A sequence of UInt64 values to calculate the sum of.</param> /// <returns>The sum of the values in the sequence.</returns> public static ulong Sum(this IEnumerable<ulong> source) { return source.Aggregate(0UL, (current, number) => current + number); } /// <summary> /// Computes the sum of a sequence of nullable UInt32 values. /// </summary> /// <param name="source">A sequence of nullable UInt32 values to calculate the sum of.</param> /// <returns>The sum of the values in the sequence.</returns> public static uint? Sum(this IEnumerable<uint?> source) { return source.Where(nullable => nullable.HasValue).Aggregate(0U, (current, nullable) => current + nullable.GetValueOrDefault()); } /// <summary> /// Computes the sum of a sequence of nullable UInt64 values. /// </summary> /// <param name="source">A sequence of nullable UInt64 values to calculate the sum of.</param> /// <returns>The sum of the values in the sequence.</returns> public static ulong? Sum(this IEnumerable<ulong?> source) { return source.Where(nullable => nullable.HasValue).Aggregate(0UL, (current, nullable) => current + nullable.GetValueOrDefault()); } /// <summary> /// Computes the sum of a sequence of UInt32 values that are obtained by invoking a transformation function on each element of the intput sequence. /// </summary> /// <param name="source">A sequence of values that are used to calculate a sum.</param> /// <param name="selection">A transformation function to apply to each element.</param> /// <returns>The sum of the projected values.</returns> public static uint Sum<T>(this IEnumerable<T> source, Func<T, uint> selection) { return source.Select(selection).Sum(); } /// <summary> /// Computes the sum of a sequence of nullable UInt32 values that are obtained by invoking a transformation function on each element of the intput sequence. /// </summary> /// <param name="source">A sequence of values that are used to calculate a sum.</param> /// <param name="selection">A transformation function to apply to each element.</param> /// <returns>The sum of the projected values.</returns> public static uint? Sum<T>(this IEnumerable<T> source, Func<T, uint?> selection) { return source.Select(selection).Sum(); } /// <summary> /// Computes the sum of a sequence of UInt64 values that are obtained by invoking a transformation function on each element of the intput sequence. /// </summary> /// <param name="source">A sequence of values that are used to calculate a sum.</param> /// <param name="selector">A transformation function to apply to each element.</param> /// <returns>The sum of the projected values.</returns> public static ulong Sum<T>(this IEnumerable<T> source, Func<T, ulong> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the sum of a sequence of nullable UInt64 values that are obtained by invoking a transformation function on each element of the intput sequence. /// </summary> /// <param name="source">A sequence of values that are used to calculate a sum.</param> /// <param name="selector">A transformation function to apply to each element.</param> /// <returns>The sum of the projected values.</returns> public static ulong? Sum<T>(this IEnumerable<T> source, Func<T, ulong?> selector) { return source.Select(selector).Sum(); } /// <summary> /// Converts an enumeration of groupings into a Dictionary of those groupings. /// </summary> /// <typeparam name="TKey">Key type of the grouping and dictionary.</typeparam> /// <typeparam name="TValue">Element type of the grouping and dictionary list.</typeparam> /// <param name="groupings">The enumeration of groupings from a GroupBy() clause.</param> /// <returns>A dictionary of groupings such that the key of the dictionary is TKey type and the value is List of TValue type.</returns> public static Dictionary<TKey, List<TValue>> ToDictionary<TKey, TValue>( this IEnumerable<IGrouping<TKey, TValue>> groupings) { return groupings.ToDictionary(group => group.Key, group => group.ToList()); } #endregion Methods } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ShipController : MonoBehaviour { Rigidbody rb; [Header("Control Variables")] public bool boostEngaged = false; public int boost = 5; [SerializeField] private int forwardSpeed = 100, strafeSpeed = 50, hoverSpeed = 100; private float activeForwardSpeed, activeStrafeSpeed, activeHoverSpeed; private float forwardAcceleration = 2.5f, strafeAcceleration = 2f, hoverAcceleration = 2f; public int maxVelocity = 1000; public float deadZone = .25f; public float lookRateSpeed = 600f; private Vector2 lookInput, screenCenter, mouseDistance; float rollInput; float rollSpeed = 800, rollAcceleration = 90f; [Header("Dampener Variables")] public bool dampenersEngaged = true; public float dampenerDrag = .25f; float normalAngularDrag = .5f; public float angularDampener = 1.5f; public Vector3 currentAngularVelocty; // Start is called before the first frame update private void Start() { rb = GetComponent<Rigidbody>(); rb.useGravity = false; screenCenter.x = Screen.width *.5f; screenCenter.y = Screen.height * .5f; } void Update() { if(Input.GetKeyDown("z")) { dampenersEngaged = !dampenersEngaged; } currentAngularVelocty = rb.angularVelocity; } void FixedUpdate() { rotationHandler(); movementHandler(); } void rotationHandler() { //rotation handler //grab mouse position lookInput.x = Input.mousePosition.x; lookInput.y = Input.mousePosition.y; //divide mouse input by smaller screen dimension to normalize inputs and save these numbers mouseDistance.x = (lookInput.x - screenCenter.x)/ screenCenter.y; mouseDistance.y = (lookInput.y - screenCenter.y) / screenCenter.y; //only allow values between 0 and 1 mouseDistance = Vector2.ClampMagnitude(mouseDistance, 1f); //configure roll axis input rollInput = Mathf.Lerp(rollInput, Input.GetAxisRaw("Roll"), rollAcceleration * Time.deltaTime); //only add torque to the ship if the mouse is outside of a small circle in the center of the screen //within the circle the angular drag increases to give the playe rmore control. if (mouseDistance.magnitude > deadZone) { rb.angularDrag = normalAngularDrag; rb.AddRelativeTorque(-mouseDistance.y * lookRateSpeed * Time.deltaTime, mouseDistance.x * lookRateSpeed * Time.deltaTime, rollInput * rollSpeed * Time.deltaTime); } else { rb.angularDrag = normalAngularDrag * angularDampener; rb.AddRelativeTorque(0,0, rollInput*rollSpeed*Time.deltaTime); } } void movementHandler() { if(rb.velocity.magnitude < maxVelocity) { if(Input.GetKey("left shift")) { activeForwardSpeed = Mathf.Lerp(activeForwardSpeed, Input.GetAxisRaw("Vertical") * forwardSpeed * boost, forwardAcceleration*Time.deltaTime); activeStrafeSpeed = Mathf.Lerp(activeStrafeSpeed, Input.GetAxisRaw("Horizontal") * strafeSpeed * boost, strafeAcceleration * Time.deltaTime); activeHoverSpeed = Mathf.Lerp(activeHoverSpeed, Input.GetAxisRaw("Hover") * hoverSpeed * boost, hoverAcceleration * Time.deltaTime); boostEngaged = true; } else { activeForwardSpeed = Mathf.Lerp(activeForwardSpeed, Input.GetAxisRaw("Vertical") * forwardSpeed, forwardAcceleration*Time.deltaTime); activeStrafeSpeed = Mathf.Lerp(activeStrafeSpeed, Input.GetAxisRaw("Horizontal") * strafeSpeed, strafeAcceleration * Time.deltaTime); activeHoverSpeed = Mathf.Lerp(activeHoverSpeed, Input.GetAxisRaw("Hover") * hoverSpeed, hoverAcceleration * Time.deltaTime); boostEngaged = false; } } else { rb.velocity = rb.velocity.normalized * .9f; } //Inertial Dampeners if (dampenersEngaged) { rb.drag = dampenerDrag; } else { rb.drag = 0f; } rb.AddRelativeForce(activeStrafeSpeed, activeHoverSpeed, activeForwardSpeed); } }
 using System.Collections.Generic; public class Submodules { public string singleValue { get; set; } } public class Menu { public Submodules submodules { get; set; } } public class Focus { public Menu menu { get; set; } } public class OperatorComment { public object operatorComment { get; set; } public bool visibility { get; set; } } public class CommentLayer { public bool userDesiredVisibility { get; set; } public bool commentLayerEmitter { get; set; } } public class CommentPanel { public object dataGridOperation { get; set; } } public class CommentMode { public string mode { get; set; } } public class CommentLock { public bool isLocked { get; set; } } public class CommentPostPanel { public string postFormText { get; set; } public bool postFormEnabled { get; set; } public bool showCommentPostPanel { get; set; } public bool postEnabled { get; set; } public object inputOperation { get; set; } public bool isFocused { get; set; } } public class PostComment { } public class Thread { public bool isJoining { get; set; } } public class MessageServer { public PostComment postComment { get; set; } public Thread thread { get; set; } } public class CommentWidget { public bool isCommentPanelOpen { get; set; } } public class LiveCommentRenderer { public object module { get; set; } } public class Submodules2 { public bool value { get; set; } } public class PostCommentRequesting { public Submodules2 submodules { get; set; } } public class Comment { public OperatorComment operatorComment { get; set; } public CommentLayer commentLayer { get; set; } public CommentPanel commentPanel { get; set; } public CommentMode commentMode { get; set; } public CommentLock commentLock { get; set; } public CommentPostPanel commentPostPanel { get; set; } public MessageServer messageServer { get; set; } public CommentWidget commentWidget { get; set; } public LiveCommentRenderer liveCommentRenderer { get; set; } public PostCommentRequesting postCommentRequesting { get; set; } } public class EdgeStream { public object protocol { get; set; } public object resource { get; set; } public object quality { get; set; } // public List<object> availableQuality { get; set; } } public class LiveVideoComponent { public object module { get; set; } } public class Player { public bool visibility { get; set; } public bool isPlaying { get; set; } } public class PlayerController { public bool visibility { get; set; } public bool reloadButtonIsEnabled { get; set; } public bool muteButtonTextVisibility { get; set; } } public class RetryStreamPlayback { public int retryIntervalMillis { get; set; } public bool isStalled { get; set; } } public class VideoPlay { public EdgeStream edgeStream { get; set; } public LiveVideoComponent liveVideoComponent { get; set; } public Player player { get; set; } public PlayerController playerController { get; set; } public RetryStreamPlayback retryStreamPlayback { get; set; } public bool mute { get; set; } } public class ElapsedTime { } public class Redirect { public object redirectMessage { get; set; } public object jumpMessage { get; set; } public object defaultJumpMessage { get; set; } } public class Room { public object messageServer { get; set; } public object name { get; set; } public object id { get; set; } } public class Vpos { } public class TrialWatch { public bool isTarget { get; set; } public bool isVideoEnabled { get; set; } public string commentMode { get; set; } } public class WatchRestriction { public bool payProgram { get; set; } public bool trialWatchAvailable { get; set; } public bool isMemberFree { get; set; } public TrialWatch trialWatch { get; set; } } public class LiveProgram { public Comment comment { get; set; } public VideoPlay videoPlay { get; set; } public ElapsedTime elapsedTime { get; set; } public Redirect redirect { get; set; } public Room room { get; set; } public Vpos vpos { get; set; } public WatchRestriction watchRestriction { get; set; } } public class Dialog { public bool isOpen { get; set; } public int type { get; set; } } public class ScreenOrientation { public int orientation { get; set; } } public class Services { public object loggingService { get; set; } } public class InputFocus { public bool isFocusingOnTextInputElement { get; set; } } public class BottomNotificationItem { public bool isOpen { get; set; } public int current { get; set; } public int next { get; set; } } public class StartAt { public object value { get; set; } public object format { get; set; } } public class Duration { public object value { get; set; } public object format { get; set; } } public class StatusBar { public StartAt startAt { get; set; } public Duration duration { get; set; } } public class ProgramTitle { public object text { get; set; } } public class ProgramSummary { public ProgramTitle programTitle { get; set; } } public class Name { public object text { get; set; } } public class ProgramProviderSummary { public Name name { get; set; } } public class Program { public object id { get; set; } public StatusBar statusBar { get; set; } public ProgramSummary programSummary { get; set; } public ProgramProviderSummary programProviderSummary { get; set; } public object status { get; set; } } public class BottomNotification { public BottomNotificationItem bottomNotificationItem { get; set; } public Program program { get; set; } } public class Reservation { } public class Submodules3 { public bool value { get; set; } } public class Requesting { public Submodules3 submodules { get; set; } } public class TimeshiftReservation { public Reservation reservation { get; set; } public Requesting requesting { get; set; } } public class Submodules4 { public string singleValue { get; set; } } public class PageNavigations { public Submodules4 submodules { get; set; } } public class LiveCycleMenu { public string selectedLiveCycleName { get; set; } public bool isVisible { get; set; } } public class Favorites { public LiveCycleMenu liveCycleMenu { get; set; } } public class Watch { public bool programDescriptionIsExpanded { get; set; } } public class SuggestTags { // public List<object> suggestTags { get; set; } } public class WatchEventLog { public object instance { get; set; } } public class WatchEvents { public bool isVideoPlaying { get; set; } } public class Submodules5 { public string singleValue { get; set; } } public class Menu2 { public Submodules5 submodules { get; set; } } public class Recent { public Menu2 menu { get; set; } } public class Submodules6 { public string singleValue { get; set; } } public class Menu3 { public Submodules6 submodules { get; set; } } public class Search { public Menu3 menu { get; set; } } public class Submodules7 { public string singleValue { get; set; } } public class Menu4 { public Submodules7 submodules { get; set; } } public class Ranking { public Menu4 menu { get; set; } } public class SearchHistory { // public List<object> searchHistory { get; set; } } public class BrowserRuntime { public Focus focus { get; set; } public LiveProgram liveProgram { get; set; } public Dialog dialog { get; set; } public ScreenOrientation screenOrientation { get; set; } public Services services { get; set; } public InputFocus inputFocus { get; set; } public BottomNotification bottomNotification { get; set; } public TimeshiftReservation timeshiftReservation { get; set; } public PageNavigations pageNavigations { get; set; } public Favorites favorites { get; set; } public Watch watch { get; set; } public SuggestTags suggestTags { get; set; } public WatchEventLog watchEventLog { get; set; } public WatchEvents watchEvents { get; set; } public Recent recent { get; set; } public Search search { get; set; } public Ranking ranking { get; set; } public SearchHistory searchHistory { get; set; } } public class Account { public string id { get; set; } public string nickname { get; set; } public string area { get; set; } public string language { get; set; } public string timezone { get; set; } public string description { get; set; } public long createdAt { get; set; } public bool isPremium { get; set; } public string icon { get; set; } public string birthday { get; set; } public int gender { get; set; } public string prefecture { get; set; } public bool isProfileRegistered { get; set; } public bool isMailRegistered { get; set; } public bool isExplicitlyLoginable { get; set; } } public class Account2 { public string authBaseUrl { get; set; } public string siteId { get; set; } public string sec { get; set; } } public class Top { public string url { get; set; } } public class Video { public string url { get; set; } } public class Live { public string url { get; set; } } public class News { public string url { get; set; } } public class Channel { public string url { get; set; } } public class Manga { public string url { get; set; } } public class Atsumaru { public string url { get; set; } } public class Niconicoq { public string url { get; set; } } public class Point { public string url { get; set; } } public class NiconicoService { public Top top { get; set; } public Video video { get; set; } public Live live { get; set; } public News news { get; set; } public Channel channel { get; set; } public Manga manga { get; set; } public Atsumaru atsumaru { get; set; } public Niconicoq niconicoq { get; set; } public Point point { get; set; } } public class IOS { public string downloadUrl { get; set; } public string playUrl { get; set; } public string broadcastUrl { get; set; } } public class Android { public string downloadUrl { get; set; } public string playUrl { get; set; } public string broadcastUrl { get; set; } } public class Nicolive { public IOS iOS { get; set; } public Android android { get; set; } } public class SpApp { public Nicolive nicolive { get; set; } } public class FrontendServer { } public class WatchEventLog2 { public bool blockConnection { get; set; } } public class PublicNicobusApi { public string apiBaseUrl { get; set; } public WatchEventLog2 watchEventLog { get; set; } } public class Help { public string url { get; set; } } public class Rule { public string url { get; set; } } public class Tokutei { public string url { get; set; } } public class Community { public string url { get; set; } public string followUrl { get; set; } } public class Channel2 { public string url { get; set; } public string admissionUrl { get; set; } public string ticketPurchaseUrl { get; set; } } public class SocialGroup { public Community community { get; set; } public Channel2 channel { get; set; } } public class StaticFiles { public string assetsBasePath { get; set; } public string adsJs { get; set; } } public class Startup { public int denominator { get; set; } } public class RuntimeError { public int denominator { get; set; } } public class WatchStability { public int denominator { get; set; } } public class Types { public Startup startup { get; set; } public RuntimeError runtimeError { get; set; } public WatchStability watchStability { get; set; } } public class Logging { public string endpoint { get; set; } public int timeout { get; set; } public Types types { get; set; } } public class PublicApiServer { public string apiBaseUrl { get; set; } public int timeout { get; set; } } public class SuggestSearch { public string apiBaseUrl { get; set; } public int timeout { get; set; } } public class AssetsConfig { // public List<string> app { get; set; } public string comment { get; set; } public string nico { get; set; } public string vendor { get; set; } public string video { get; set; } // public List<string> css { get; set; } } public class ClientConfig { public Account2 account { get; set; } public NiconicoService niconicoService { get; set; } public string niconicoServiceListPageUrl { get; set; } public string liveAppLandingPageUrl { get; set; } public string live1PcBaseUrl { get; set; } public SpApp spApp { get; set; } public FrontendServer frontendServer { get; set; } public PublicNicobusApi publicNicobusApi { get; set; } public Help help { get; set; } public Rule rule { get; set; } public Tokutei tokutei { get; set; } public SocialGroup socialGroup { get; set; } public StaticFiles staticFiles { get; set; } public Logging logging { get; set; } public PublicApiServer publicApiServer { get; set; } public SuggestSearch suggestSearch { get; set; } public AssetsConfig assetsConfig { get; set; } public bool enableTrialMode { get; set; } public string applicationBaseUrl { get; set; } } public class ClientEnvironment { public int osType { get; set; } public bool isVideoInlinePlaySupported { get; set; } } public class Url { public string protocol { get; set; } public object slashes { get; set; } public object auth { get; set; } public string host { get; set; } public string hostname { get; set; } public object hash { get; set; } public object search { get; set; } public object query { get; set; } public string pathname { get; set; } public string path { get; set; } public string href { get; set; } } public class RequestInfo { public string ipAddress { get; set; } public string userAgent { get; set; } public Url url { get; set; } } public class Maintenance { public object id { get; set; } public object beginAt { get; set; } public object endAt { get; set; } } public class Constants { public Account account { get; set; } public ClientConfig clientConfig { get; set; } public ClientEnvironment clientEnvironment { get; set; } public string frontendId { get; set; } public RequestInfo requestInfo { get; set; } public Maintenance maintenance { get; set; } public string frontendVersion { get; set; } } public class __invalid_type__5 { public int width { get; set; } public int height { get; set; } public string zoneId { get; set; } } public class __invalid_type__6 { public int width { get; set; } public int height { get; set; } public string zoneId { get; set; } } public class Ads2 { public __invalid_type__5 __invalid_name__5 { get; set; } public __invalid_type__6 __invalid_name__6 { get; set; } } public class Ads { public Ads2 ads { get; set; } } public class Submodules8 { public string singleValue { get; set; } } public class LiveCycle { public Submodules8 submodules { get; set; } } public class Submodules10 { public bool value { get; set; } } public class Requesting2 { public Submodules10 submodules { get; set; } } public class Submodules9 { public Requesting2 requesting { get; set; } } public class OnAir { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules9 submodules { get; set; } } public class Submodules12 { public bool value { get; set; } } public class Requesting3 { public Submodules12 submodules { get; set; } } public class Submodules11 { public Requesting3 requesting { get; set; } } public class BeforeOpen { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules11 submodules { get; set; } } public class Submodules14 { public bool value { get; set; } } public class Requesting4 { public Submodules14 submodules { get; set; } } public class Submodules13 { public Requesting4 requesting { get; set; } } public class Ended { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules13 submodules { get; set; } } public class Programs { public OnAir on_air { get; set; } public BeforeOpen before_open { get; set; } public Ended ended { get; set; } } public class Focus2 { public LiveCycle liveCycle { get; set; } public Programs programs { get; set; } } public class PageError { public object pageErrorName { get; set; } } public class TimeshiftReservations { // public List<object> reservationList { get; set; } } public class Programs2 { } public class ReservedPrograms { public Programs2 programs { get; set; } } public class Reservations { public TimeshiftReservations timeshiftReservations { get; set; } public ReservedPrograms reservedPrograms { get; set; } } public class Statistics { public int watchCount { get; set; } public int commentCount { get; set; } public int reservationCount { get; set; } } public class Program2 { public string id { get; set; } public string title { get; set; } public string shortTitle { get; set; } public string userId { get; set; } public string thumbnailUrl { get; set; } public int providerType { get; set; } public string liveCycle { get; set; } public long beginAt { get; set; } public long endAt { get; set; } public bool isMemberOnly { get; set; } // public Statistics statistics { get; set; } public string socialGroupName { get; set; } public string socialGroupThumbnailUrl { get; set; } public string ownerIconUrl { get; set; } public string liveScreenshotThumbnailUrl { get; set; } public object tsScreenshotThumbnailUrl { get; set; } public int? elapsedTimeSeconds { get; set; } public object durationSeconds { get; set; } public bool isTimeshiftEnabled { get; set; } public object timeshiftEndAt { get; set; } } public class FavoritePrograms { public List<Program2> programs { get; set; } } public class Favorites2 { public FavoritePrograms favoritePrograms { get; set; } } public class Statistics2 { public object watchCount { get; set; } public object commentCount { get; set; } public object reservationCount { get; set; } } public class TrialWatch2 { public bool isTarget { get; set; } public bool isVideoEnabled { get; set; } public string commentMode { get; set; } } public class WatchRestriction2 { public bool payProgram { get; set; } public bool trialWatchAvailable { get; set; } public bool isMemberFree { get; set; } public TrialWatch2 trialWatch { get; set; } } public class Program3 { public object id { get; set; } public object title { get; set; } public object shortTitle { get; set; } public object userId { get; set; } public object description { get; set; } public object thumbnailUrl { get; set; } public object liveScreenshotThumbnailUrl { get; set; } public object tsScreenshotThumbnailUrl { get; set; } public int providerType { get; set; } // public List<object> tags { get; set; } public string liveCycle { get; set; } public int openAt { get; set; } public int beginAt { get; set; } public int endAt { get; set; } public bool deleted { get; set; } public int excludeType { get; set; } public object deletedInfo { get; set; } public object visibleAt { get; set; } public bool isSpwebEnabled { get; set; } public bool isIosEnabled { get; set; } public bool isAndroidEnabled { get; set; } public object timeshiftType { get; set; } public bool isTimeshiftButtonEnabled { get; set; } public bool isTimeshiftEnabled { get; set; } public object timeshiftStartAt { get; set; } public object timeshiftEndAt { get; set; } public bool isTimeshiftViewLimited { get; set; } public bool isTimeshiftAvailable { get; set; } public bool isReliveEnabled { get; set; } public bool isPayProgram { get; set; } public bool showAds { get; set; } public object ticketPurchaseUrl { get; set; } public bool isMemberOnly { get; set; } public object socialGroup { get; set; } public object socialGroupId { get; set; } public object socialGroupName { get; set; } public object socialGroupThumbnailUrl { get; set; } public object ownerIconUrl { get; set; } public Statistics2 statistics { get; set; } public string twitterHashTags { get; set; } public object redirectTo { get; set; } public bool isDmc { get; set; } public bool isAllowedToPlay { get; set; } public int mediaServerType { get; set; } public object socialGroupDetail { get; set; } public object audienceLimitation { get; set; } public WatchRestriction2 watchRestriction { get; set; } public bool premiumAppealEnabled { get; set; } public object programProvider { get; set; } } public class WsEndPoint { public object url { get; set; } public object broadcastId { get; set; } public object audienceToken { get; set; } } public class CommentState { public bool locked { get; set; } public string layout { get; set; } } public class OperatorComment2 { public string body { get; set; } public object link { get; set; } public string name { get; set; } public object decoration { get; set; } public bool isPermanent { get; set; } } public class PlayerParams { public object audienceToken { get; set; } public object defaultJump { get; set; } public WsEndPoint wsEndPoint { get; set; } public CommentState commentState { get; set; } public OperatorComment2 operatorComment { get; set; } public int serverTime { get; set; } } public class WatchInformation { public Program3 program { get; set; } public PlayerParams playerParams { get; set; } public object watchingError { get; set; } public object deletedInfo { get; set; } public bool isPlayable { get; set; } public bool isTimeshiftReserved { get; set; } } public class Link { public string text { get; set; } public string url { get; set; } } public class PortalLinks { // public List<Link> links { get; set; } } public class AppMerit { public object appMerit { get; set; } } public class Watch2 { public WatchInformation watchInformation { get; set; } public PortalLinks portalLinks { get; set; } public AppMerit appMerit { get; set; } } public class Submodules15 { public string singleValue { get; set; } } public class LiveCycle2 { public Submodules15 submodules { get; set; } } public class Submodules17 { public bool value { get; set; } } public class Requesting5 { public Submodules17 submodules { get; set; } } public class Submodules16 { public Requesting5 requesting { get; set; } } public class Onair2 { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules16 submodules { get; set; } } public class Submodules19 { public bool value { get; set; } } public class Requesting6 { public Submodules19 submodules { get; set; } } public class Submodules18 { public Requesting6 requesting { get; set; } } public class Past { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules18 submodules { get; set; } } public class Submodules21 { public bool value { get; set; } } public class Requesting7 { public Submodules21 submodules { get; set; } } public class Submodules20 { public Requesting7 requesting { get; set; } } public class Reserved { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules20 submodules { get; set; } } public class Programs3 { public Onair2 onair { get; set; } public Past past { get; set; } public Reserved reserved { get; set; } } public class RecentTab { public string recentTab { get; set; } } public class Submodules22 { public string singleValue { get; set; } } public class SortOrder { public Submodules22 submodules { get; set; } } public class Recent2 { public LiveCycle2 liveCycle { get; set; } public Programs3 programs { get; set; } public RecentTab recentTab { get; set; } public SortOrder sortOrder { get; set; } } public class Submodules24 { public bool value { get; set; } } public class Requesting8 { public Submodules24 submodules { get; set; } } public class Submodules23 { public Requesting8 requesting { get; set; } } public class Onair3 { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules23 submodules { get; set; } } public class Submodules26 { public bool value { get; set; } } public class Requesting9 { public Submodules26 submodules { get; set; } } public class Submodules25 { public Requesting9 requesting { get; set; } } public class Past2 { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules25 submodules { get; set; } } public class Submodules28 { public bool value { get; set; } } public class Requesting10 { public Submodules28 submodules { get; set; } } public class Submodules27 { public Requesting10 requesting { get; set; } } public class Reserved2 { // public List<object> items { get; set; } public int loadedPages { get; set; } public int pageTotal { get; set; } public Submodules27 submodules { get; set; } } public class Programs4 { public Onair3 onair { get; set; } public Past2 past { get; set; } public Reserved2 reserved { get; set; } } public class Submodules29 { public string singleValue { get; set; } } public class LiveCycle3 { public Submodules29 submodules { get; set; } } public class Submodules30 { // public List<object> singleValue { get; set; } } public class ProviderTypes { public Submodules30 submodules { get; set; } } public class Submodules31 { // public List<object> singleValue { get; set; } } public class SearchFilters { public Submodules31 submodules { get; set; } } public class Submodules32 { // public List<object> singleValue { get; set; } } public class SearchOptions { public Submodules32 submodules { get; set; } } public class Submodules33 { public string singleValue { get; set; } } public class SortOrder2 { public Submodules33 submodules { get; set; } } public class SearchConditions { public object date { get; set; } public string keyword { get; set; } public LiveCycle3 liveCycle { get; set; } public ProviderTypes providerTypes { get; set; } public SearchFilters searchFilters { get; set; } public SearchOptions searchOptions { get; set; } public SortOrder2 sortOrder { get; set; } } public class Search2 { public Programs4 programs { get; set; } public SearchConditions searchConditions { get; set; } } public class Tracking { public string actionTrackId { get; set; } public string nicosId { get; set; } } public class Notification { public object notification { get; set; } } public class Programs5 { // public List<object> programs { get; set; } } public class Timetable { public Programs5 programs { get; set; } public string date { get; set; } } public class NicoliveInfo { // public List<object> infoItems { get; set; } // public List<object> maintenanceItems { get; set; } } public class NicoInfo { public NicoliveInfo nicoliveInfo { get; set; } } public class RookiePrograms { // public List<object> programs { get; set; } } public class RecommendedPrograms { // public List<object> programs { get; set; } } /*public class PopularPrograms { public List<object> commonCategoryPrograms { get; set; } public List<object> tryCategoryPrograms { get; set; } public List<object> gameCategoryPrograms { get; set; } public List<object> faceCategoryPrograms { get; set; } public List<object> smartPhoneBroadcastTagPrograms { get; set; } public List<object> reservedFocusedPrograms { get; set; } public List<object> reservedPrograms { get; set; } public List<object> pastPrograms { get; set; } }*/ public class FocusedPrograms { // public List<object> programs { get; set; } } public class FavoritePrograms2 { // public List<object> programs { get; set; } } public class FavoritePastPrograms { // public List<object> programs { get; set; } } public class Top2 { public NicoInfo nicoInfo { get; set; } public RookiePrograms rookiePrograms { get; set; } public RecommendedPrograms recommendedPrograms { get; set; } // public PopularPrograms popularPrograms { get; set; } public FocusedPrograms focusedPrograms { get; set; } public FavoritePrograms2 favoritePrograms { get; set; } public FavoritePastPrograms favoritePastPrograms { get; set; } } public class PickupContents2 { // public List<object> pickupItems { get; set; } } public class PickupContents { public PickupContents2 pickupContents { get; set; } } public class FeaturedContents2 { // public List<object> featuredItems { get; set; } } public class FeaturedContents { public FeaturedContents2 featuredContents { get; set; } } public class Feature { public PickupContents pickupContents { get; set; } public FeaturedContents featuredContents { get; set; } } public class HeatMap { public bool isTarget { get; set; } public int sampleRate { get; set; } } public class ProgramSearchPanel { public string keyword { get; set; } } public class HeaderParts { public ProgramSearchPanel programSearchPanel { get; set; } } public class RankingPrograms { // public List<object> rankingPrograms { get; set; } } public class Submodules34 { public int singleValue { get; set; } } public class ProviderType { public Submodules34 submodules { get; set; } } public class Ranking2 { public RankingPrograms rankingPrograms { get; set; } public ProviderType providerType { get; set; } } public class Redirect2 { public object permanentRedirectTo { get; set; } public object temporaryRedirectTo { get; set; } } public class PageContents { public Ads ads { get; set; } public Focus2 focus { get; set; } public PageError pageError { get; set; } public bool shouldFetchData { get; set; } public Reservations reservations { get; set; } public Favorites2 favorites { get; set; } public Watch2 watch { get; set; } public Recent2 recent { get; set; } public Search2 search { get; set; } public Tracking tracking { get; set; } public Notification notification { get; set; } public Timetable timetable { get; set; } public Top2 top { get; set; } public Feature feature { get; set; } public HeatMap heatMap { get; set; } public HeaderParts headerParts { get; set; } public Ranking2 ranking { get; set; } public Redirect2 redirect { get; set; } } public class EApiClient2 { } public class ApiClient { } public class NicoliveEApiClient { public ApiClient apiClient { get; set; } } public class EApiClient { public EApiClient2 eApiClient { get; set; } public NicoliveEApiClient nicoliveEApiClient { get; set; } } public class ApiClient3 { } public class ApiClient2 { public ApiClient3 apiClient { get; set; } } public class WatchApiClient { public ApiClient2 apiClient { get; set; } } public class ProgramService { public EApiClient eApiClient { get; set; } public WatchApiClient watchApiClient { get; set; } } public class EApiClient4 { } public class ApiClient4 { } public class NicoliveEApiClient2 { public ApiClient4 apiClient { get; set; } } public class EApiClient3 { public EApiClient4 eApiClient { get; set; } public NicoliveEApiClient2 nicoliveEApiClient { get; set; } } public class AdsService { public EApiClient3 eApiClient { get; set; } } public class Channel3 { } /*public class AccountServiceClient { public List<object> __invalid_name__$interceptors { get; set; } public List<object> __invalid_name__$interceptor_providers { get; set; } public Channel3 __invalid_name__$channel { get; set; } }*/ public class Channel4 { } /*public class PremiumMasqueradeServiceClient { public List<object> __invalid_name__$interceptors { get; set; } public List<object> __invalid_name__$interceptor_providers { get; set; } public Channel4 __invalid_name__$channel { get; set; } }*/ public class InternalRepr { } public class MetaData { public InternalRepr _internal_repr { get; set; } } public class ApiClient6 { public int timeoutMs { get; set; } // public List<object> interceptors { get; set; } // public AccountServiceClient accountServiceClient { get; set; } // public PremiumMasqueradeServiceClient premiumMasqueradeServiceClient { get; set; } public MetaData metaData { get; set; } } public class ApiClient5 { public ApiClient6 apiClient { get; set; } } public class AccountService { public ApiClient5 apiClient { get; set; } } public class TrackingService { } public class ApiClient8 { } public class NicoInfoApiClient { public ApiClient8 apiClient { get; set; } } public class ApiClient7 { public NicoInfoApiClient nicoInfoApiClient { get; set; } } public class NotificationService { public ApiClient7 apiClient { get; set; } } public class ApiClient9 { } public class IzumoApiClient2 { public ApiClient9 apiClient { get; set; } } public class IzumoApiClient { public IzumoApiClient2 izumoApiClient { get; set; } } public class EmacsClient2 { } public class ApiClient10 { } public class NicoliveEApiClient3 { public ApiClient10 apiClient { get; set; } } public class EmacsClient { public EmacsClient2 emacsClient { get; set; } public NicoliveEApiClient3 nicoliveEApiClient { get; set; } } public class RecommendedProgramsService { public IzumoApiClient izumoApiClient { get; set; } public EmacsClient emacsClient { get; set; } } public class SugoiSSApiClient { } public class SearchService { public SugoiSSApiClient sugoiSSApiClient { get; set; } } public class EApiClient6 { } public class ApiClient11 { } public class NicoliveEApiClient4 { public ApiClient11 apiClient { get; set; } } public class EApiClient5 { public EApiClient6 eApiClient { get; set; } public NicoliveEApiClient4 nicoliveEApiClient { get; set; } } public class TimeshiftService { public EApiClient5 eApiClient { get; set; } } public class ApiClient13 { } public class NicoInfoApiClient2 { public ApiClient13 apiClient { get; set; } } public class ApiClient12 { public NicoInfoApiClient2 nicoInfoApiClient { get; set; } } public class NicoInfoService { public ApiClient12 apiClient { get; set; } } public class ApiClient14 { } public class IndexStreamListApiClient2 { public ApiClient14 apiClient { get; set; } } public class IndexStreamListApiClient { public IndexStreamListApiClient2 indexStreamListApiClient { get; set; } } public class SugoiSSApiClient2 { } public class FocusedProgramsService { public IndexStreamListApiClient indexStreamListApiClient { get; set; } public SugoiSSApiClient2 sugoiSSApiClient { get; set; } } public class EApiClient8 { } public class ApiClient15 { } public class NicoliveEApiClient5 { public ApiClient15 apiClient { get; set; } } public class EApiClient7 { public EApiClient8 eApiClient { get; set; } public NicoliveEApiClient5 nicoliveEApiClient { get; set; } } public class FeaturedContentsService { public EApiClient7 eApiClient { get; set; } } public class WakutkoolClient { public int timeoutSeconds { get; set; } } public class RelatedContentsService { public WakutkoolClient wakutkoolClient { get; set; } } public class EApiClient10 { } public class ApiClient16 { } public class NicoliveEApiClient6 { public ApiClient16 apiClient { get; set; } } public class EApiClient9 { public EApiClient10 eApiClient { get; set; } public NicoliveEApiClient6 nicoliveEApiClient { get; set; } } public class SubscribedProgramsService { public EApiClient9 eApiClient { get; set; } } public class SuggestSearchService { } public class ApiClient18 { } public class PtaApiClient { public ApiClient18 apiClient { get; set; } public string serviceName { get; set; } } public class ApiClient17 { public PtaApiClient ptaApiClient { get; set; } } public class PtaService { public ApiClient17 apiClient { get; set; } } public class EmacsClient4 { } public class ApiClient19 { } public class NicoliveEApiClient7 { public ApiClient19 apiClient { get; set; } } public class EmacsClient3 { public EmacsClient4 emacsClient { get; set; } public NicoliveEApiClient7 nicoliveEApiClient { get; set; } } public class NgFilteredOnairProgramsService { public EmacsClient3 emacsClient { get; set; } } public class EmacsClient6 { } public class ApiClient20 { } public class NicoliveEApiClient8 { public ApiClient20 apiClient { get; set; } } public class EmacsClient5 { public EmacsClient6 emacsClient { get; set; } public NicoliveEApiClient8 nicoliveEApiClient { get; set; } } public class RankingService { public EmacsClient5 emacsClient { get; set; } } public class Channel5 { } /*public class Client { public List<object> __invalid_name__$interceptors { get; set; } public List<object> __invalid_name__$interceptor_providers { get; set; } public Channel5 __invalid_name__$channel { get; set; } } */ public class InternalRepr2 { } public class MetaData2 { public InternalRepr2 _internal_repr { get; set; } } public class ApiClient21 { public int timeoutMs { get; set; } //public List<object> interceptors { get; set; } //public Client client { get; set; } public MetaData2 metaData { get; set; } } public class DolphinApiClient { public ApiClient21 apiClient { get; set; } } public class PopularProgramsService { public DolphinApiClient dolphinApiClient { get; set; } } public class Channel6 { } public class Client2 { // public List<object> __invalid_name__$interceptors { get; set; } // public List<object> __invalid_name__$interceptor_providers { get; set; } // public Channel6 __invalid_name__$channel { get; set; } } public class InternalRepr3 { } public class MetaData3 { public InternalRepr3 _internal_repr { get; set; } } public class ApiClient22 { public int timeoutMs { get; set; } // public List<object> interceptors { get; set; } public Client2 client { get; set; } public MetaData3 metaData { get; set; } } public class DolphinApiClient2 { public ApiClient22 apiClient { get; set; } } public class RookieProgramsService { public DolphinApiClient2 dolphinApiClient { get; set; } } public class Services2 { public ProgramService programService { get; set; } public AdsService adsService { get; set; } public AccountService accountService { get; set; } public TrackingService trackingService { get; set; } public NotificationService notificationService { get; set; } public RecommendedProgramsService recommendedProgramsService { get; set; } public SearchService searchService { get; set; } public TimeshiftService timeshiftService { get; set; } public NicoInfoService nicoInfoService { get; set; } public FocusedProgramsService focusedProgramsService { get; set; } public FeaturedContentsService featuredContentsService { get; set; } public RelatedContentsService relatedContentsService { get; set; } public SubscribedProgramsService subscribedProgramsService { get; set; } public SuggestSearchService suggestSearchService { get; set; } public PtaService ptaService { get; set; } public NgFilteredOnairProgramsService ngFilteredOnairProgramsService { get; set; } public RankingService rankingService { get; set; } public PopularProgramsService popularProgramsService { get; set; } public RookieProgramsService rookieProgramsService { get; set; } } public class Routing { public object locationBeforeTransitions { get; set; } } public class RootObject { public BrowserRuntime browserRuntime { get; set; } public Constants constants { get; set; } public PageContents pageContents { get; set; } public Services2 services { get; set; } public Routing routing { get; set; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UIControl; using TMPro; public class ChallengeModeManager : MonoBehaviour, IGameMode { public int TimeScore { get; private set; } [Header("Game elements")] [SerializeField] private GameObject wall; [SerializeField] private GameObject challengeModeScoreboard; [SerializeField] private GameObject storyModeScoreboard; [Header("Settings")] [SerializeField] private float introLength = 3.0f; [SerializeField] private Vector3 ballStartPosition; [SerializeField] private float difficultyIncrease = 0.25f; [SerializeField] private int countdown = 3; [TextArea, SerializeField] private string levelDescription; [Header("References")] [SerializeField] private ChallengeModeScoreboard scoreBoard; [SerializeField] private ChallengeDifficultyController difficultyController; [SerializeField] private TimerCountdown timerCountdown; public TimerCountdown TimerCountdown { get { return timerCountdown; } } [SerializeField] private StartGameCountdownController startGameCountdown; [SerializeField] private GoalsManager goalsManager; [SerializeField] private BallManager ballManager; public BallManager BallManager { get { return ballManager; } } private GameManager gameManager; private CharacterController player1; private bool subcribedToEvents = false; public void Initialize(GameManager gameManager) { this.gameManager = gameManager; difficultyController.Initialize(this); goalsManager.Initialize(); } public void StartGameMode() { if (!subcribedToEvents) { subcribedToEvents = true; goalsManager.OnScoredGoal += OnScoredGoal; gameManager.OnGameStarted += OnGameStarted; } scoreBoard.Initialize(); wall.SetActive(true); challengeModeScoreboard.SetActive(true); storyModeScoreboard.SetActive(false); player1 = ReferencesHolder.Instance.CharacterFactory.CreateCharacter(CharacterFactory.CharactersType.Player); player1.Intialize(); player1.SetInput(new PlayerInput()); gameManager.SKillHudController.Initialize(player1.GetComponent<CharacterSkillController>()); ballManager.Initialize(); ReferencesHolder.Instance.CamerasController.SetEnemyIntroCamera(); ReferencesHolder.Instance.ScreenFader.StartFadeIn(StartPlay); } private void StartPlay() { StartCoroutine(StartPlayCoroutine()); } private IEnumerator StartPlayCoroutine() { ReferencesHolder.Instance.UIStateManager.OpenPanel(UIPanelsIDs.EnemyNamePanel); yield return new WaitForSeconds(introLength); ReferencesHolder.Instance.UIStateManager.ClosePanel(UIPanelsIDs.EnemyNamePanel); ballManager.SpawnBall(ballStartPosition); //start countdown ReferencesHolder.Instance.CamerasController.SetGameCameraCamera(); ReferencesHolder.Instance.UIStateManager.OpenPanel(UIPanelsIDs.StartCountDownPanel); float time = countdown; while (time >= 0) { time -= Time.deltaTime; startGameCountdown.DisplayCountdownText(((int)time + 1).ToString()); yield return null; } ReferencesHolder.Instance.CamerasController.SetGameCameraCamera(); ReferencesHolder.Instance.UIStateManager.ClosePanel(UIPanelsIDs.StartCountDownPanel); ReferencesHolder.Instance.UIStateManager.OpenLayout(UILayoutsIDs.HUDLayout); gameManager.StartGame(); difficultyController.StartDiffiultyIncreasing(); yield return null; } public int GetChallengeScore() { return timerCountdown.TimerCurrentTime; } public void GameModeOver() { ballManager.DisableBall(); timerCountdown.StopTimer(); difficultyController.Stop(); int score = timerCountdown.TimerCurrentTime; ReferencesHolder.Instance.UIStateManager.CloseAll(); ReferencesHolder.Instance.UIStateManager.OpenLayout(UILayoutsIDs.ChallengeLevelFinishedLayout); if (ReferencesHolder.Instance.LeadersBoardManager.CheckNewHighScore(score) > -1) { ReferencesHolder.Instance.UIStateManager.OpenLayout(UILayoutsIDs.NewHighScoreLayout, true); } gameManager.GameOver(); } public void FinishGameMode() { if (player1 != null) { Destroy(player1.gameObject); player1 = null; } if (subcribedToEvents) { subcribedToEvents = false; goalsManager.OnScoredGoal -= OnScoredGoal; gameManager.OnGameStarted -= OnGameStarted; } wall.SetActive(false); challengeModeScoreboard.SetActive(false); storyModeScoreboard.SetActive(true); ballManager.DestroyBall(); timerCountdown.StopTimer(); difficultyController.Stop(); ReferencesHolder.Instance.CamerasController.SetMainMenuCamera(); ReferencesHolder.Instance.ScreenFader.StartFadeIn (() => { ReferencesHolder.Instance.UIStateManager.OpenLayout(UILayoutsIDs.MainMenuLayout); }); } public void RestartGameMode() { if (player1 != null) { Destroy(player1.gameObject); player1 = null; } ballManager.DestroyBall(); gameManager.StartGameMode(GameModeEnums.GameModes.Challenge); } public string GetLevelDescription() { return levelDescription; } public void IncreaseDifficulty() { ballManager.ModifyBallSpeed(difficultyIncrease); } public void StartTimer() { timerCountdown.StartTimer(scoreBoard.SetTimerDisplay); } private void OnScoredGoal(int player) { ballManager.GoalScored(); GameModeOver(); } private void OnGameStarted() { StartTimer(); ballManager.LaunchBall(1); } }
using MoneyBack.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Money.ViewModels.Companies { public class CompanyListItemViewModel { public int ID { get; set; } public string Name { get; set; } public int StockPriceType { get; set; } public string Symbol { get; set; } public int FrontsCount { get; set; } public int Broker { get; set; } public string BrokerName => ((StockBroker)Broker).ToString(); } }
using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QuickCollab.Session { public class SessionInstance { [BsonId] public string Name { get; set; } [BsonRequired] public DateTime DateCreated { get; set; } [BsonRequired] public int ConnectionExpiryInHours { get; set; } [BsonRequired] public bool IsVisible { get; set; } [BsonRequired] public bool PersistHistory { get; set; } public string HashedPassword { get; set; } public string Salt { get; set; } } }
using UnityEngine; public class NPCSign : MonoBehaviour { public enum Direction { None, Up, Down, Left, Right } public Direction signDirection = Direction.None; public SpriteRenderer dialogueHint; public string diaKey = ""; public string speakerKey = ""; public AudioClip sfx; private GameManager game; private DialogueData diaData; private DialogueTextTyper boxPrint; private TeamManager team; private void Awake() { game = GameManager.instance; diaData = GetComponent<DialogueData>(); boxPrint = game.UI.dialogueBox.GetComponent<DialogueTextTyper>(); team = TeamManager.instance; } private void Start() { if (dialogueHint) { dialogueHint.color = Color.clear; } } //Prints text when player presses space key private void OnTriggerStay2D(Collider2D col) { CharacterInfo info = col.GetComponent<CharacterInfo>(); if (info != null && team.IsLeader(col.gameObject)) { info.CanInteract = true; if (dialogueHint) { dialogueHint.color = Color.white; } if (Input.GetKeyDown(KeyCode.Space) && boxPrint.CanPrint) { game.UI.EnableUI(game.UI.dialogueBox, true); if (diaData != null) { boxPrint.ChangeText(diaData.GetRandomDialogue()); } else if (!diaKey.IsEmpty() && !speakerKey.IsEmpty()) { boxPrint.ChangeText(diaKey, speakerKey, 0.05f, signDirection, sfx); } } } } private void OnTriggerExit2D(Collider2D col) { CharacterInfo info = col.GetComponent<CharacterInfo>(); if (info != null && team.IsLeader(col.gameObject)) { if (dialogueHint) { dialogueHint.color = Color.clear; } info.CanInteract = false; } } }
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. // VisualNovelToolkit /_/_/_/_/_/_/_/_/_/. // Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/. //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class ByteCodeReader : MonoBehaviour{ #if true static public int readString( byte[] array , int index ){ // Int Length Version. #if true int charNum = readInt( array , index ); int startIndex = index + 4; // Byte Length Version. #else int charNum = array[ index ]; int startIndex = index + 1; #endif int len = charNum * 2; // Debug.Log( "ByteCodeReader:str len : " + len); byte[] dst = new byte[ len ]; Array.Copy( array , startIndex , dst , 0 , len ); VirtualMachine.loadedString = System.Text.Encoding.Unicode.GetString( dst ); // Debug.Log( "the string:" + VirtualMachine.loadedString ); return startIndex + len; } #else // For Debugging. public string[] stringBuffer = new string[ 200 ]; static private ByteCodeReader m_Instance; static private int bufferIndex; static public int readString( byte[] array , int index ){ int charNum = array[ index ]; int startIndex = index + 1; int len = charNum * 2; byte[] dst = new byte[ len ]; Array.Copy( array , startIndex , dst , 0 , len ); VirtualMachine.loadedString = System.Text.Encoding.Unicode.GetString( dst ); if( m_Instance == null ){ GameObject obj = new GameObject(); m_Instance = obj.AddComponent<ByteCodeReader>(); DontDestroyOnLoad( obj ); } m_Instance.stringBuffer[ bufferIndex ] = VirtualMachine.loadedString; bufferIndex++; if( bufferIndex >= 200 ){ bufferIndex = 0; } return startIndex + len; } #endif static public int readInt(byte[] array, int index) { return (array[index] << 24) | ((array[index + 1] & 0xff) << 16) | ((array[index + 2] & 0xff) << 8) | (array[index + 3] & 0xff); } static public int readShort(byte[] array, int index) { return (array[index] << 8) | (array[index + 1] & 0xff); } // Current Opcode.TABLE and readTable... static public int readTable( byte[] codes , int programCounter , ref Hashtable param ){ param = new Hashtable(); programCounter++; int count = codes[ programCounter ]; // TABLE KEYs Count MUST Be Within 255. programCounter++; for( int i=0;i<count;i++){ programCounter = readString( codes , programCounter + 1 ); string key = VirtualMachine.loadedString; // Debug.Log( "table key:" + key ); programCounter = readString( codes , programCounter + 1 ); string val = VirtualMachine.loadedString; // Debug.Log( "table key:" + key ); param[ key ] = val; } return programCounter; } static public int readVar( byte[] codes , int programCounter , ref Hashtable param , ref System.Text.StringBuilder textBuild , bool stubIndentOption=false ){ programCounter = readString( codes , programCounter + 2 ); #if false if( VirtualMachine.symbolTable.ContainsKey( VirtualMachine.loadedString ) ){ string text = VirtualMachine.symbolTable[ VirtualMachine.loadedString ] as string; if( ! string.IsNullOrEmpty( text ) ){ // Trim space. if( ! stubIndentOption ){ text = text.Trim(); } // textBuf += text; textBuild.Append( text ); VirtualMachine.loadedTextLiteralString = text; } else{ Hashtable tbl = VirtualMachine.symbolTable[ VirtualMachine.loadedString ] as Hashtable; param = tbl; } } else{ ViNoDebugger.LogError( "Var name : " + VirtualMachine.loadedString + " NOT Found." ); } #else // Append Word from FlagTable. ScenarioNode scenario = ScenarioNode.Instance; if( scenario != null && scenario.flagTable != null ){ string word = scenario.flagTable.GetStringValue( VirtualMachine.loadedString ); textBuild.Append( word ); VirtualMachine.loadedTextLiteralString = word; } #endif return programCounter; } /* /// <summary> /// Reads the func. /// </summary> /// <returns> /// return the endpoint of this func. /// </returns> /// <param name='codes'> /// Codes. /// </param> /// <param name='programCounter'> /// Program counter is Now , Opcode.FUNC. /// </param> [ Obsolete ] static public int readFunc( byte[] codes , int programCounter , Dictionary<string,FuncInfo> functionTable ){ int retPos = readInt( codes , programCounter + 1 ); // Opcode.FUNC , Opcode.STRING , name. programCounter = readString( codes , programCounter + 6 ); if( ! VirtualMachine.loadedString.Equals( string.Empty ) ){ FuncInfo info = new FuncInfo(); info.m_PcEntry = programCounter; info.m_ReturnPos = retPos; functionTable[ VirtualMachine.loadedString ] = info;//programCounter; } // Now , Skip the Inner code of function . programCounter = retPos + 1; return programCounter; } static public int readReturn( byte[] code , Stack<int> callstack ){ int retPos = 100000; if( callstack.Count > 0 ){ retPos = callstack.Pop(); } #if false else{ pc = code.Length + 10; // <==== DANGER !!!. } #endif return retPos; } //*/ }
using System; using System.ComponentModel.DataAnnotations; namespace GlobalModels { /// <summary> /// DTO Model for frontend -> backend /// </summary> public sealed class NewComment { [Required] public Guid Discussionid { get; set; } [Required] [StringLength(50)] public string Userid { get; set; } [Required] [StringLength(300)] public string Text { get; set; } [Required] public bool Isspoiler { get; set; } public string ParentCommentid {get; set;} public NewComment() { } public NewComment(Guid discussionid, string uid, string text, bool isspoiler, string parentcommentid) { Discussionid = discussionid; Userid = uid; Text = text; Isspoiler = isspoiler; ParentCommentid = parentcommentid; } public NewComment(Comment comment) { Discussionid = comment.Discussionid; Userid = comment.Userid; Text = comment.Text; Isspoiler = comment.Isspoiler; } } }
using System; using DilemaPrisionero; using System.Collections; using System.Collections.Generic; namespace DilemaPrisionero { class Program { static void Main(string[] args) { Jugador pere = new Jugador("Coopera", new Coopera()); Jugador carla = new Jugador("Descarta", new Descarta()); Jugador pedro = new Jugador("Aleatorio", new Aleatorio()); Juego game = new Juego(new List<Jugador> { pere, carla, pedro }, 50 , new Logica(), new Write()); game.JuegoEmpezar(); } } }
using FastSQL.Core; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; namespace FastSQL.MySQL { public class FastAdapter : BaseSqlAdapter { public FastAdapter(FastProvider provider) : base(provider) { } protected override DbConnection GetConnection() { var builder = new ConnectionStringBuilder(Options); return new MySqlConnection(builder.Build()); } public override bool TryConnect(out string message) { IDbConnection conn = null; try { message = "Connected."; using (conn = GetConnection()) { conn.Open(); return true; } } catch (Exception ex) { message = ex.Message; return false; } finally { conn?.Dispose(); } } public override IEnumerable<string> GetTables() { using (var conn = GetConnection()) { conn.Open(); var schema = conn.GetSchema("Tables"); return schema.Rows.Cast<DataRow>().Select(r => r["TABLE_NAME"].ToString()); } } public override IEnumerable<string> GetViews() { using (var conn = GetConnection()) { conn.Open(); var dbName = Options.FirstOrDefault(o => o.Name == "Database")?.Value; var schema = conn.GetSchema("Views"); return schema.Rows.Cast<DataRow>() .Where(r => r["TABLE_SCHEMA"].ToString() == dbName || string.IsNullOrWhiteSpace(dbName)) .Select(r => r["TABLE_NAME"].ToString()); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace VS.GUI { public partial class EditEntityControl : BaseControl { public EditEntityControl() { InitializeComponent();} private void EditEntityControl_Load(object sender, EventArgs e) { base.ControlLoad(sender, e); } protected override void BindControlData() { } private void btnNew_Click(object sender, EventArgs e) { New(); } private void btnSave_Click(object sender, EventArgs e) { Save(); } private void btnDelete_Click(object sender, EventArgs e) {Delete(); } private void btnSaveAs_Click(object sender, EventArgs e) { SaveAs(); } protected virtual void New() { } protected virtual void Save() { } protected virtual void SaveAs() { } protected virtual void Delete() { } protected virtual void SelectedEntityChangedHandler(object sender, EventArgs args) { } } }
using UnityEngine; using System.Collections; public class RightMenu { private Rect menuRect2 = new Rect(Screen.width - 10- 145, 10, 125, 320); private Rect menuRect3 = new Rect(Screen.width - 10- 145, 10, 125, 450); public const int MODEL_LONG = 1; public const int MODEL_SHORT = 2; public const int COLOR_BLUE = 0; public const int COLOR_GREEN = 1; public const int COLOR_BLACK = 2; public const int BAG_1 = 0; public const int BAG_2 = 3; public int model = 1; public int color = 0; public int bag = 0; public RightMenu() { Debug.Log ("RightMenu Created"); } public void initModel(int winId) { GUILayout.BeginVertical (); if (GUILayout.Button ("长裤", "STYLE_BTN_LONG")) { model = MODEL_LONG; } GUILayout.Space (45); if (GUILayout.Button ("短裤", "STYLE_BTN_SHORT")) { model = MODEL_SHORT; } GUILayout.Space (45); GUILayout.EndVertical (); } public void initColor(int winId) { GUILayout.BeginVertical (); if (GUILayout.Button ("蓝色", "STYLE_BTN_BLUE")) { color = COLOR_BLUE; } GUILayout.Space (45); if (GUILayout.Button ("绿色", "STYLE_BTN_GREEN")) { color = COLOR_GREEN; } GUILayout.Space (45); if (GUILayout.Button ("黑色", "STYLE_BTN_BLACK")) { color = COLOR_BLACK; } GUILayout.EndVertical (); } public void initDetail(int winId) { GUILayout.BeginVertical (); if (GUILayout.Button ("尖袋", "STYLE_BTN_BAG1")) { bag = BAG_1; } GUILayout.Space (45); if (GUILayout.Button ("方袋", "STYLE_BTN_BAG2")) { bag = BAG_2; } GUILayout.Space (45); GUILayout.EndVertical (); } public Rect getRect(int type) { switch (type) { case LeftMenu.TYPE_MODEL: case LeftMenu.TYPE_DETAIL: return menuRect2; case LeftMenu.TYPE_COLOR: return menuRect3; } return menuRect3; } }
using FA.JustBlog.Core.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FA.JustBlog.Models { public class JustBlogContext : DbContext { //Ex. 5 public JustBlogContext() : base("FA.JustBlog.Core") { Database.SetInitializer(new JustBlogInitializer()); } public DbSet<Category> Categories { get; set; } public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } public DbSet<Comment> comments { get; set; } // Ex. 4 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Post>().HasMany<Tag>(p => p.Tags).WithMany(t => t.Posts).Map(tp => { tp.MapLeftKey("PostId"); tp.MapRightKey("TagId"); tp.ToTable("PostTagMap"); }); } } }
using System; using System.Collections.Generic; namespace HCL.Academy.Model { public class Logos { public String logoSRC { get; set; } } public class LogoList { public List<Logos> logoListdetails { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using UnityEngine.UI; public class Manager : MonoBehaviour { public static Manager instance; public GameObject player; private NavMeshSurface surface; private Transform currentTrans; private void Start() { #region SingleTon if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); return; } #endregion //surface = GameObject.Find("Navmesh").GetComponent<NavMeshSurface>(); } public void refreshNavMesh() { StartCoroutine(buildNavMesh()); } public void startDialog(Transform npcTrans, List<Dialog> dialogs) { currentTrans = npcTrans; StartCoroutine(dialogCoroutine(dialogs)); } IEnumerator buildNavMesh() { yield return new WaitForSeconds(0.1f); //surface.BuildNavMesh(); } IEnumerator dialogCoroutine(List<Dialog> dialogs) { Transform anim = currentTrans.GetChild(0).GetChild(0); for (int i = 0; i < dialogs.Count; i++) { anim.GetComponentInChildren<Text>().text = dialogs[i].text; anim.GetComponent<Animator>().Play("FadeIn"); Debug.Log(dialogs[i].duration); yield return new WaitForSeconds(dialogs[i].duration); } anim.GetComponent<Animator>().Play("FadeOut"); } public void StopPlayerControlls(bool stop) { player.GetComponent<controlPlay>().enabled = !stop; Debug.Log(!stop); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace OnSale.Web.Data.Entity { public class Category { public int CategoryID { get; set; } [DisplayName("Codigo Categoria")] [MaxLength(50)] [Range(0, int.MaxValue, ErrorMessage = "Favor Digite un Numero Entero Valido")] [Required] public int CategoryCode { get; set; } [DisplayName("Nombre Negocio")] [MaxLength(50)] [StringLength(50, ErrorMessage = "Debe tener entre {2} y {1} Caracteres", MinimumLength = 3)] [Required(ErrorMessage = "El Campo {0} es Requerido")] public string CategoryName { get; set; } public Guid CategoryImageId { get; set; } //TODO: Pending to put the correct paths [Display(Name = "Image")] public string ImageFullPath => CategoryImageId == Guid.Empty ? $"https://localhost:44390/images/noimage.png" : $"https://onsale.blob.core.windows.net/categories/{CategoryImageId}"; } }
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace ALM.Empresa.Entidades { [Serializable] public class ESubCatalogo { public int IdEmpresa { get; set; } [DisplayName("IdCatalogo")] public int IdSubCatalogo { get; set; } [Required(ErrorMessage = "Dato requerido")] public int IdCatalogo { get; set; } public int IdTipoCatalogo { get; set; } [Required(ErrorMessage = "Dato requerido")] [StringLength(12, ErrorMessage = Constante.TamanioCampo)] [DisplayName("Clave")] public string Clave { get; set; } [Required(ErrorMessage = "Dato requerido")] [StringLength(64, ErrorMessage = Constante.TamanioCampo)] [DisplayName("Nombre")] public string Nombre { get; set; } [StringLength(256, ErrorMessage = Constante.TamanioCampo)] [DisplayName("Descripción")] public string Descripcion { get; set; } [DisplayName("CatalogoPadre")] public string Catalogo { get; set; } public bool EsActivo { get; set; } public int EsActivoFiltro { get; set; } } }
using System; using Paylocity.Benefits; using Paylocity.Models; namespace Paylocity.Discount { public class EmployeePackageDiscount : IBenefitsPackageDiscountChain { private readonly IConfiguration _configuration; private readonly IBenefitsPackageDiscountChain _dependentBenefitsPackageDiscountChain; public EmployeePackageDiscount(IConfiguration configuration, IBenefitsPackageDiscountChain dependentBenefitsPackageDiscountChain) { _configuration = configuration; _dependentBenefitsPackageDiscountChain = dependentBenefitsPackageDiscountChain; } public IBenefitsPackage ApplyDiscount(IBenefitsPackage benefitsPackage, IEmployee employee) { benefitsPackage = _dependentBenefitsPackageDiscountChain.ApplyDiscount(benefitsPackage, employee); var employeeDiscount = employee.Name.StartsWith(_configuration.DiscountNamePrefix, StringComparison.InvariantCultureIgnoreCase) ? _configuration.StandardBenefitPackageDiscount : 0; if (employeeDiscount > 0) { benefitsPackage.EmployeeCost = DiscountUtility.GetDiscount(benefitsPackage.EmployeeCost, employeeDiscount); } return benefitsPackage; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using CommonCore.LockPause; namespace CommonCore.UI { public class IngameMenuController : BaseMenuController { public static IngameMenuController Current; public string DefaultPanel; public bool HandlePause = true; public bool Autohide = true; public GameObject MainPanel; public GameObject ContainerPanel; public GameObject EphemeralRoot; private string CurrentPanel; public override void Start() { base.Start(); Current = this; EphemeralRoot = new GameObject("InGameMenu_EphemeralRoot"); EphemeralRoot.transform.parent = transform.root; if(Autohide) { foreach(Transform child in ContainerPanel.transform) { child.gameObject.SetActive(false); } MainPanel.SetActive(false); } } public override void Update() { base.Update(); CheckMenuOpen(); } private void CheckMenuOpen() { bool menuToggled = UnityEngine.Input.GetKeyDown(KeyCode.Escape); if(menuToggled) { //if we're locked out, let the menu be closed but not opened if (!AllowMenu) { if (MainPanel.activeSelf) { MainPanel.SetActive(false); if(HandlePause) { DoUnpause(); } foreach (Transform child in ContainerPanel.transform) { child.gameObject.SetActive(false); } ClearEphemeral(); } } else { //otherwise, flip state bool newState = !MainPanel.activeSelf; MainPanel.SetActive(newState); if(HandlePause) { if (newState) DoPause(); else DoUnpause(); } if(newState && !string.IsNullOrEmpty(DefaultPanel)) { OnClickSelectButton(DefaultPanel); } if(!newState) { foreach (Transform child in ContainerPanel.transform) { child.gameObject.SetActive(false); } ClearEphemeral(); } } } } private void DoPause() { LockPauseModule.PauseGame(PauseLockType.AllowMenu, this); LockPauseModule.LockControls(InputLockType.GameOnly, this); } private void DoUnpause() { LockPauseModule.UnlockControls(this); LockPauseModule.UnpauseGame(this); } private void ClearEphemeral() { //destroy ephemeral modals (a bit hacky) foreach (Transform child in EphemeralRoot.transform) { Destroy(child.gameObject); } } public void OnClickSelectButton(string menuName) { foreach(Transform child in ContainerPanel.transform) { child.gameObject.SetActive(false); } try { var childPanel = ContainerPanel.transform.Find(menuName); if(childPanel != null) { childPanel.gameObject.SetActive(true); childPanel.GetComponent<PanelController>().SignalPaint(); } CurrentPanel = menuName; } catch(Exception e) { Debug.LogError(e); } } private bool AllowMenu { get { var lockState = LockPauseModule.GetInputLockState(); return (lockState == null || lockState.Value >= InputLockType.GameOnly); } } } }
using UnityEngine; using System.Collections; public class PanelMenu : MonoBehaviour { UIPanel _panel; void Start() { _panel = GetComponent<UIPanel>(); } public void LoadMiniGame1() { MiniGame1_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame2() { MiniGame2_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame3() { MiniGame3_Manager.instance.NewGame(45); Hide(); } public void LoadMiniGame4() { MiniGame4_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame5() { MiniGame5_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame6() { MiniGame6_Manager.instance.NewGame(60); Hide(); } public void LoadMiniGame7() { //MiniGame7_Manager.instance.NewGame(); //Hide(); } public void LoadMiniGame8() { MiniGame8_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame9() { MiniGame9_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame10() { MiniGame10_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame11() { MiniGame11_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame12() { MiniGame12_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame13() { MiniGame13_Manager.instance.NewGame(); Hide(); } public void LoadMiniGame14() { // MiniGame14_Manager.instance.NewGame(); // Hide(); } public void LoadMiniGame15() { MiniGame15_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame16() { //MiniGame16_Manager.instance.NewGame(); //Hide(); } public void LoadMiniGame17() { MiniGame17_Manager.instance.NewGame(35); Hide(); } public void LoadMiniGame18() { MiniGame18_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame19() { MiniGame19_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame20() { MiniGame20_Manager.instance.NewGame(60); Hide(); } public void LoadMiniGame21() { MiniGame21_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame22() { MiniGame22_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame23() { MiniGame23_Manager.instance.NewGame(60); Hide(); } public void LoadMiniGame24() { MiniGame24_Manager.instance.NewGame(60); Hide(); } public void LoadMiniGame25() { MiniGame25_Manager.instance.NewGame(60); Hide(); } public void LoadMiniGame26() { //MiniGame26_Manager.instance.NewGame(); //Hide(); } public void LoadMiniGame27() { MiniGame27_Manager.instance.NewGame(60); Hide(); } public void LoadMiniGame28() { MiniGame28_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame29() { MiniGame29_Manager.instance.NewGame(45); Hide(); } public void LoadMiniGame30() { MiniGame30_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame31() { MiniGame31_Manager.instance.NewGame(30); Hide(); } public void LoadMiniGame32() { MiniGame32_Manager.instance.NewGame(30); Hide(); } public void Hide() { if (_panel != null) _panel.alpha = 0f; } public void Show() { if (_panel != null) _panel.alpha = 1f; } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("TraySection")] public class TraySection : MonoBehaviour { public TraySection(IntPtr address) : this(address, "TraySection") { } public TraySection(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void ClearDeckInfo() { base.method_8("ClearDeckInfo", Array.Empty<object>()); } public void CloseDoor() { base.method_9("CloseDoor", new Class272.Enum20[0], Array.Empty<object>()); } public void CloseDoorImmediately() { base.method_9("CloseDoorImmediately", new Class272.Enum20[0], Array.Empty<object>()); } public Bounds GetDoorBounds() { return base.method_11<Bounds>("GetDoorBounds", Array.Empty<object>()); } public bool HideIfNotInBounds(Bounds bounds) { object[] objArray1 = new object[] { bounds }; return base.method_11<bool>("HideIfNotInBounds", objArray1); } public bool IsDeckBoxShown() { return base.method_11<bool>("IsDeckBoxShown", Array.Empty<object>()); } public bool IsOpen() { return base.method_11<bool>("IsOpen", Array.Empty<object>()); } public void OpenDoor() { base.method_9("OpenDoor", new Class272.Enum20[0], Array.Empty<object>()); } public void OpenDoorImmediately() { base.method_9("OpenDoorImmediately", new Class272.Enum20[0], Array.Empty<object>()); } public void ShowDoor(bool show) { object[] objArray1 = new object[] { show }; base.method_8("ShowDoor", objArray1); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public static Vector3 DECKBOX_LOCAL_EULER_ANGLES { get { return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "TraySection", "DECKBOX_LOCAL_EULER_ANGLES"); } } public static float DOOR_ANIM_SPEED { get { return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "TraySection", "DOOR_ANIM_SPEED"); } } public string DOOR_CLOSE_ANIM_NAME { get { return base.method_4("DOOR_CLOSE_ANIM_NAME"); } } public string DOOR_OPEN_ANIM_NAME { get { return base.method_4("DOOR_OPEN_ANIM_NAME"); } } public CollectionDeckBoxVisual m_deckBox { get { return base.method_3<CollectionDeckBoxVisual>("m_deckBox"); } } public bool m_deckBoxShown { get { return base.method_2<bool>("m_deckBoxShown"); } } public GameObject m_door { get { return base.method_3<GameObject>("m_door"); } } public bool m_inEditPosition { get { return base.method_2<bool>("m_inEditPosition"); } } public bool m_isOpen { get { return base.method_2<bool>("m_isOpen"); } } public bool m_wasTouchModeEnabled { get { return base.method_2<bool>("m_wasTouchModeEnabled"); } } [Attribute38("TraySection.OnDoorStateChangedCallbackData")] public class OnDoorStateChangedCallbackData : MonoClass { public OnDoorStateChangedCallbackData(IntPtr address) : this(address, "OnDoorStateChangedCallbackData") { } public OnDoorStateChangedCallbackData(IntPtr address, string className) : base(address, className) { } public string m_animationName { get { return base.method_4("m_animationName"); } } public object m_callbackData { get { return base.method_3<object>("m_callbackData"); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class timeandate : MonoBehaviour { public static int month = 1; public static int year = 1; public static int week = 1; public static int framesPerWeek = 100; private static int weekIncrementTimer; public static int money = 1000; public static int rent = 50; public static int fans = 0; public static int pendingProfit = 0; public static int pendingFans = 0; public bool autoPlay = false; public static int bankruptoffers = 3; public static int warnings = 0; public bool autoPlaymedium = false; public static int loanmoney = 0; public bool detuctmoneytest = false; public GameObject LoanDisplayScreenUI; public static int LoadNumber = 0; public static bool gameisstopped = false; public GameObject BankruptcyDisplayScreenUI; public static int loansoundnumber = 3; public static int researchPoints = 0; public static int pendingResearchPoints = 0; public int level = 1; public AudioClip LoanOfferSound; public AudioClip Bankruptsound; public Text rentDisplayText; public Text profitDisplayText; public Text pfansDisplayText; public Text BankruptOfferText; static bool created = false; void Awake() { if (!created) { DontDestroyOnLoad(this.gameObject); created = true; } else { Destroy(this.gameObject); } } private void Update() { if (gameisstopped == false) { LoanDisplayScreenUI.SetActive(false); BankruptcyDisplayScreenUI.SetActive(false); GetComponent("RentDisplay.cs"); bankruptoffers = 3; Debug.Log("bank offers left =" + bankruptoffers); if (weekIncrementTimer >= framesPerWeek) { weekIncrementTimer = 0; week++; Debug.Log("Week =" + week); if (week >= 5) { week = 1; money -= rent; StartCoroutine(DisplayRentTaken(rent)); StartCoroutine(DisplayProfitAdded(pendingProfit)); StartCoroutine(DisplayFansAdded(pendingFans)); money = money + pendingProfit; fans = fans + pendingFans; researchPoints = researchPoints + pendingResearchPoints; month++; Bankruptchecker(); Debug.Log("month =" + month); if (month >= 13) { month = 1; year++; Debug.Log("year =" + year); } } } else { weekIncrementTimer++; } if (autoPlay == false) { // do nothing } if (autoPlay == true) { PlayAuto(); } if (autoPlaymedium == false) { // do nothing } if (autoPlaymedium == true) { PlayMedAuto(); } if (detuctmoneytest == false) { // do nothing } if (detuctmoneytest == true) { MoneyDetuctTest(); } } if (gameisstopped == true) { } } IEnumerator DisplayRentTaken(int rent) { rentDisplayText.gameObject.SetActive(true); rentDisplayText.text = "Rent taken: -£ " + rent; yield return new WaitForSeconds(2f); rentDisplayText.gameObject.SetActive(false); } // displays the rent in game IEnumerator DisplayProfitAdded(int pendingProfit) { profitDisplayText.gameObject.SetActive(true); profitDisplayText.text = "Income: +£ " + pendingProfit; yield return new WaitForSeconds(2f); profitDisplayText.gameObject.SetActive(false); } // displays the pedning profit in game IEnumerator DisplayFansAdded(int pendingFans) { pfansDisplayText.gameObject.SetActive(true); pfansDisplayText.text = "Fans: + " + pendingFans; yield return new WaitForSeconds(2f); pfansDisplayText.gameObject.SetActive(false); } // displays the pedning fans in game public static void Reset() { week = 1; month = 1; year = 1; weekIncrementTimer = 0; money = 50; fans = 0; pendingFans = 0; pendingProfit = 0; framesPerWeek = 100; bankruptoffers = 3; warnings = 0; LoadNumber = 0; gameisstopped = false; loansoundnumber = 3; } public void PlayAuto() { framesPerWeek = 1; } public void PlayMedAuto() { framesPerWeek = 50; } public void Bankrupt() { BankruptcyDisplayScreenUI.SetActive(true); AudioSource.PlayClipAtPoint(Bankruptsound, transform.position); Debug.Log("bankruptcy declared for: "); gameisstopped = true; } public void Bankruptchecker() { if (money < 0) { Debug.Log("money is below 0"); warnings++; Debug.Log("Warnings" + warnings); if (warnings >= 3) { Debug.Log("Max warnings exceeded, loading loan"); LoanOffer(); } else if (money > 0) { warnings = 0; Debug.Log("warnings set to 0"); //resets the month calculator } } } private void LoanOffer() { if (LoadNumber == 0) { Debug.Log("creating first loan offer"); LoanOfferDisplay(); bankruptoffers = 2; BankruptOfferText.text = "2"; } if (LoadNumber == 1) { Debug.Log("creating second loan offer"); LoanOfferDisplay(); bankruptoffers = 1; BankruptOfferText.text = "1"; } if (LoadNumber == 2) { Debug.Log("creating final loan offer"); LoanOfferDisplay(); bankruptoffers = 0; BankruptOfferText.text = "0"; } if (LoadNumber > 3) { Bankrupt(); } if (warnings > 3) { Bankrupt(); } else { } //nothing happens } public void MoneyDetuctTest() { money = money - 1000; } public void LoanOfferDisplay() { if (loansoundnumber > 0) { AudioSource.PlayClipAtPoint(LoanOfferSound, transform.position); } gameisstopped = true; Time.timeScale = 0.01f; LoanDisplayScreenUI.SetActive(true); Debug.Log("Load Loan Display"); } public void LoanAccepted () { gameisstopped = false; LoanDisplayScreenUI.SetActive(false); Time.timeScale = 1f; pendingProfit = loanmoney = 10000; money = money + loanmoney; Debug.Log("loan money sent"); pendingProfit = loanmoney = 0; LoadNumber = LoadNumber + 1; Debug.Log("LoadNumber" + LoadNumber); warnings = 0; loansoundnumber = loansoundnumber - 1; } public void LoanDeclined () { LoanDisplayScreenUI.SetActive(false); Time.timeScale = 1f; gameisstopped = false; } public void BankruptAgreed () { Reset(); Debug.Log("Player has lost, loading reason screen"); BankruptcyDisplayScreenUI.SetActive(false); Time.timeScale = 1f; } public void BankruptLoadLevelRequest() { Reset(); Debug.Log("Player has lost, loading load level screen"); BankruptcyDisplayScreenUI.SetActive(false); Time.timeScale = 1f; } public void BankruptImage () { Bankrupt(); } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("MobileChatNotification")] public class MobileChatNotification : MonoBehaviour { public MobileChatNotification(IntPtr address) : this(address, "MobileChatNotification") { } public MobileChatNotification(IntPtr address, string className) : base(address, className) { } public void FireNotification() { base.method_8("FireNotification", Array.Empty<object>()); } public string GetStateText(State state) { object[] objArray1 = new object[] { state }; return base.method_13("GetStateText", objArray1); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void OnEnable() { base.method_8("OnEnable", Array.Empty<object>()); } public void OnTurnChanged(int oldTurn, int newTurn, object userData) { object[] objArray1 = new object[] { oldTurn, newTurn, userData }; base.method_8("OnTurnChanged", objArray1); } public void OnTurnTimerUpdate(TurnTimerUpdate update, object userData) { object[] objArray1 = new object[] { update, userData }; base.method_8("OnTurnTimerUpdate", objArray1); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public State state { get { return base.method_2<State>("state"); } } public enum State { None, GameStarted, YourTurn, TurnCountdown } } }
/* ********************************************** * 版 权:亿水泰科(EWater) * 创建人:zhujun * 日 期:2018/11/23 22:21:22 * 描 述:分页查询返回的通用对象 * *********************************************/ using System; using System.Collections.Generic; using System.Text; namespace EWF.Util.Page { /// <summary> /// 分页查询返回的通用对象 /// </summary> /// <typeparam name="T"></typeparam> public class Page<T> { /// <summary> /// The current page number contained in this page of result set /// </summary> public int PageIndex { get; set; } /// <summary> /// The number of items per page /// </summary> public int PageSize { get; set; } /// <summary> /// The total number of pages in the full result set /// </summary> public int TotalPages { get; set; } /// <summary> /// The total number of records in the full result set /// </summary> public int TotalItems { get; set; } /// <summary> /// The actual records on this page /// </summary> public List<T> Items { get; set; } /// <summary> /// User property to hold anything. /// </summary> public object Context { get; set; } } }
using UnityEngine; using System.Collections; //script for moving camera public class camera : MonoBehaviour { public float distance; public float rotatespeed; private float xDeg = 0.0f; private float yDeg = 0.0f; private float zDeg = 0.0f; public float xSpeed = 200.0f; public float ySpeed = 200.0f; public Quaternion currentRotation; private Quaternion desiredRotation; private Quaternion rotation; public Quaternion transrot; public float zoomDampening = 5.0f; public bool overgui = false; private float camrad; private float vert; void Start () { distance = 10; rotatespeed = 1.5f; zDeg = 15; yDeg = 87; transform.rotation = Quaternion.Euler(87,0,0); } void Update() { camrad = (yDeg) * Mathf.Deg2Rad; transform.Translate(Vector3.right * (Input.GetAxis("Horizontal")),Space.Self); vert = Input.GetAxis("Vertical"); if (vert != 0) { Debug.Log(vert); } if ((vert > 0)&&(yDeg < 89)) { transform.Translate(Vector3.forward * (vert * Mathf.Tan(camrad) * vert), Space.Self); } else if (vert < 0) { transform.Translate(Vector3.forward * (vert * Mathf.Tan(camrad) * vert * -1), Space.Self); } transform.position = new Vector3(transform.position.x, zDeg, transform.position.z); if (Input.GetKey(KeyCode.LeftShift)) { if (Input.GetMouseButton(0)) { xDeg += Input.GetAxis("Mouse X") * xSpeed * 0.02f; yDeg -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; xDeg = xDeg % 360; //Debug.Log(xDeg); yDeg = Mathf.Clamp(yDeg, 35, 87); currentRotation = transform.rotation; desiredRotation = Quaternion.Euler(yDeg, xDeg, 0); rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * zoomDampening); transform.rotation = rotation; } else if (Input.GetMouseButton(1)) { zDeg += Input.GetAxis("Mouse Y") * Time.deltaTime; zDeg = Mathf.Clamp(zDeg, 10, 20); transform.position = new Vector3(transform.position.x, zDeg, transform.position.z); } } } public void OnGUI() { } }
#region MÉTADONNÉES // Nom du fichier : ModeEnum.cs // Auteur : (1835343) // Date de création : 2019-05-19 // Date de modification : 2019-05-19 #endregion namespace BeerOrWine { public enum ModeEnum { Training, Evaluation } }
using System; using System.Collections.Generic; using System.Text; namespace LinqLambda.Entidades { class Categoria { public int Id { get; private set; } public string Nome { get; private set; } public int Nota { get; private set; } public Categoria(int id, string nome, int nota) { Id = id; Nome = nome; Nota = nota; } public override string ToString() { return $@"{Id}, {Nome}, {Nota}"; } } }
using OCP.ContactsNs.ContactsMenu; namespace OC.Contacts.ContactsMenu { class Entry : IEntry { /** @var string|int|null */ private id = null; /** @var string */ private fullName = ""; /** @var string[] */ private emailAddresses = []; /** @var string|null */ private avatar; /** @var IAction[] */ private actions = []; /** @var array */ private properties = []; /** * @param string id */ public function setId(id) { this.id = id; } /** * @param string displayName */ public function setFullName(displayName) { this.fullName = displayName; } /** * @return string */ public function getFullName() { return this.fullName; } /** * @param string address */ public function addEMailAddress(address) { this.emailAddresses[] = address; } /** * @return string */ public function getEMailAddresses() { return this.emailAddresses; } /** * @param string avatar */ public function setAvatar(avatar) { this.avatar = avatar; } /** * @return string */ public function getAvatar() { return this.avatar; } /** * @param IAction action */ public function addAction(IAction action) { this.actions[] = action; this.sortActions(); } /** * @return IAction[] */ public function getActions() { return this.actions; } /** * sort the actions by priority and name */ private function sortActions() { usort(this.actions, function(IAction action1, IAction action2) { prio1 = action1.getPriority(); prio2 = action2.getPriority(); if (prio1 == prio2) { // Ascending order for same priority return strcasecmp(action1.getName(), action2.getName()); } // Descending order when priority differs return prio2 - prio1; }); } /** * @param array contact key-value array containing additional properties */ public function setProperties(array contact) { this.properties = contact; } /** * @param string key * @return mixed */ public function getProperty(key) { if (!isset(this.properties[key])) { return null; } return this.properties[key]; } /** * @return array */ // public function jsonSerialize() { // topAction = !empty(this.actions) ? this.actions[0].jsonSerialize() : null; // otherActions = array_map(function(IAction action) { // return action.jsonSerialize(); // }, array_slice(this.actions, 1)); // // return [ // "id" => this.id, // "fullName" => this.fullName, // "avatar" => this.getAvatar(), // "topAction" => topAction, // "actions" => otherActions, // "lastMessage" => "", // ]; // } } }
using innovation4austria.web.App_Code; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using innovation4austria.web.Models; using innovation4austria.logic; using innovation4austria.web.Models.Raum; using log4net; namespace innovation4austria.web.Controllers { [Authorize(Roles =Const.ROLLE_MITARBEITER_I4A)] public class AuswertungController : BasisController { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //[HttpGet] //public ActionResult MietDauer() //{ // log.Debug("MietDauer"); // StatistikModel model = new StatistikModel(); // model.Daten_XAchse = new List<int>(); // List<RaumartModel> raumArten = AutoMapper.Mapper.Map<List<RaumartModel>>(RaumartVerwaltung.LadeAlle()); // foreach (var raumart in raumArten) // { // model.Daten_XAchse.Add(BuchungVerwaltung.MietDauer(raumart.ID)); // } // model.Beschriftung = raumArten.Select(x => x.Bezeichnung).ToList(); // return View(model); //} [HttpGet] public ActionResult RaumAuslastung() { log.Debug("RaumAuslastung"); StatistikModel model = new StatistikModel(); model.Daten_XAchse = new List<double>(); List<RaumModel> raeume = AutoMapper.Mapper.Map<List<RaumModel>>(RaumVerwaltung.LadeRaeume(null)); foreach (var raum in raeume) { model.Daten_XAchse.Add(RaumVerwaltung.Auslastung(raum.ID, DateTime.Now.Month, DateTime.Now.Year)); } model.Beschriftung = raeume.Select(x => x.RaumName).ToList(); return View(model); } } }
using DipDemo.Cataloguer.Core; using DipDemo.Cataloguer.Infrastructure.AppController; namespace DipDemo.Cataloguer.Requests { public class CloseCatalogueRequest : IRequestData<CloseCatalogueResponse> { public Catalogue Catalogue { get; private set; } public CloseCatalogueRequest(Catalogue catalogue) { Catalogue = catalogue; } } public class CloseCatalogueResponse { public bool IsCancelled { get; private set; } public CloseCatalogueResponse(bool isCancelled) { IsCancelled = isCancelled; } } }
using Volo.Abp.Modularity; namespace SoftDeleteTest { [DependsOn( typeof(SoftDeleteTestApplicationModule), typeof(SoftDeleteTestDomainTestModule) )] public class SoftDeleteTestApplicationTestModule : AbpModule { } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using System.Threading; using CMS_ShopOnline.Helpers; using System; namespace CMS_ShopOnline.Hubs { [HubName("myHub")] public class MyHub : Hub { private static IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); public static List<UserOnline> UserOnlines = new List<UserOnline>(); public override System.Threading.Tasks.Task OnConnected() { //lấy list user đang đăng nhập var userlogin = Helper.CurrentUser.Id; if (UserOnlines.Where(x => x.UserLogginId == userlogin).FirstOrDefault() == null) { UserOnline user = new UserOnline() { Name = Context.User.Identity.Name, ConnectionID = Context.ConnectionId, UserLogginId = userlogin }; UserOnlines.Add(user); Clients.Others.userConnected(user.UserLogginId); } return base.OnConnected(); } public override System.Threading.Tasks.Task OnReconnected() { return base.OnReconnected(); } public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled) { if (stopCalled) { if (UserOnlines.Any(x => x.ConnectionID == Context.ConnectionId)) { UserOnline user = UserOnlines.First(x => x.ConnectionID == Context.ConnectionId); //xoa khoi danh sach cac user dang dang nhap UserOnlines.RemoveAll(x => x.ConnectionID == Context.ConnectionId); user.ConnectionID = null; int count = 5; bool isDisconnected = true; while (count > 0) { if (string.IsNullOrEmpty(user.ConnectionID)) { Thread.Sleep(1000); count--; } else { isDisconnected = false; break; } } if (isDisconnected) { Clients.Others.userLeft(user.UserLogginId); UserOnlines.Remove(user); } } } return base.OnDisconnected(stopCalled); } public static void Noti(string NameTask, string Controller, string Action,string Areas, string UserIDCreate,int? Idtask ,string DateTime,int IdPx) { var listStaffCanView = UserOnlines.Select(x => x.ConnectionID).ToList(); context.Clients.All.updatedClients(NameTask, Controller, Action, Areas, UserIDCreate, Idtask, DateTime,IdPx); } public static void PurchaseOder(int? Id, DateTime NgayTao,int? IdNhanVien, int? IdKhachHang, string TenNV, string TenKH, string GhiChu, string TrangThai, double? TongTien, double? TongKM) { var listStaffCanView = UserOnlines.Select(x => x.ConnectionID).ToList(); if(TenKH == null) { TenKH = "Khách vãng lai"; } if(GhiChu == null) { GhiChu = "Không"; } context.Clients.All.updatedPurchaseOder(Id, NgayTao, IdNhanVien, IdKhachHang, TenNV, TenKH, GhiChu , TrangThai, TongTien, TongKM); } public class UserOnline { public string Name; public string ConnectionID; public int UserLogginId; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SnapshotCamera { private int textureWidth; private int textureHeight; private Transform defaultPosition; private Transform anchor; public Camera camera; public bool isActive { get { return this.camera.gameObject.activeInHierarchy; } } public SnapshotCamera(Camera mainCamera, Transform anchor, int textureWidth, int textureHeight) { this.anchor = anchor; this.textureWidth = textureWidth; this.textureHeight = textureHeight; if (GameObject.Find("Snapshot Camera") == null) { this.defaultPosition = mainCamera.transform; this.camera = Camera.Instantiate(mainCamera); this.camera.name = "Snapshot Camera"; this.camera.targetTexture = new RenderTexture(this.textureWidth, this.textureHeight, 24); this.SetActive(false); } } public void RandomizePosition() { float offsetX = Random.Range(-0.25f, 0.25f); float offsetY = Random.Range(-0.25f, 0.25f); this.camera.transform.position = this.defaultPosition.position + new Vector3(offsetX, offsetY, 0.0f); this.camera.transform.LookAt(this.anchor); } public void SetActive(bool value) { this.camera.gameObject.SetActive(value); } public byte[] Capture() { Texture2D snapshot = new Texture2D(this.textureWidth, this.textureHeight, TextureFormat.RGB24, false); snapshot.hideFlags = HideFlags.HideAndDontSave; RenderTexture currentActiveRT = RenderTexture.active; RenderTexture.active = this.camera.targetTexture; this.camera.Render(); snapshot.ReadPixels(new Rect(0, 0, this.textureWidth, this.textureHeight), 0, 0); byte[] bytes = snapshot.EncodeToPNG(); RenderTexture.active = currentActiveRT; Object.Destroy(snapshot); return bytes; } }
using BPiaoBao.Common.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.DomesticTicket.Domain.Models.Policies { public class SpecialPolicy : LocalPolicy { /// <summary> /// 特价类型 /// </summary> public SpeciaType SpecialType { get; set; } /// <summary> /// 固定特价类型 /// </summary> public FixedOnSaleType Type { get; set; } /// <summary> /// 固定舱位价位 /// </summary> public decimal FixedSeatPirce { get; set; } } }
using Black_Jack; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Args; namespace TestBot.Commands { class BidCommand : Command { public override string Name => "/bid"; public override void Execute(MessageEventArgs e, TelegramBotClient Bot) { Bot.SendTextMessageAsync(e.Message.Chat.Id, "Введіть початкову ставку"); } } }
using System; namespace DbLogic.Repositories.Interfaces { public interface IRepository<T> : IDisposable where T: class { void Create(T item); void Update(T item); void Delete(T item); void Save(); } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using Dnn.PersonaBar.Library.Prompt.Attributes; namespace Dnn.PersonaBar.Prompt.Components.Commands.Portal { /// <summary> /// Alias for list-portals /// </summary> [ConsoleCommand("list-sites", Constants.PortalCategory, "Prompt_ListSites_Description")] public class ListSites : ListPortals { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApiApp.Models; namespace WebApiApp.ViewModels { public class IndexUser { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class DetailUser { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Login { get; set; } public List<int> UserRoles { get; set; } } public class CreateUser { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public string Login { get; set; } public List<int> UserRoles { get; set; } } public class EditUser { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Login { get; set; } public List<int> UserRoles { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary.ViewModels { public class PercursoPoi { public int PoiID { get; set; } public string nome { get; set; } public bool POIdePercurso { get; set; } } }
using System; using System.Net.Http; namespace Fundamentals.HttpClients { public interface ICurrencyClient { public HttpClient Client { get; } } public class CurrencyClientImpl : ICurrencyClient { public HttpClient Client { get; private set; } public CurrencyClientImpl(HttpClient client) { Client = client; Client.BaseAddress = new Uri("https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/"); } } }
using FoodInstructions.Models; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FoodInstructions.Controllers { public class RecipesController : Controller { public IActionResult Index() { var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Recipe>("recipes"); List<Recipe> recipesInDb = collection.Find(r => true).ToList(); return View(recipesInDb); } public IActionResult Create() { var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Ingredient>("ingredients"); List<Ingredient> ingredientsInDb = collection.Find(r => true).ToList(); return View(ingredientsInDb); } [HttpPost] public IActionResult Create(Recipe recipe) { var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Recipe>("recipes"); collection.InsertOne(recipe); return Redirect("/Recipes"); } public IActionResult Show(string Id) { ObjectId objId = new ObjectId(Id); var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Recipe>("recipes"); var ingredientsCollection = database.GetCollection<Ingredient>("ingredients"); Recipe recipe = collection.Find(r => r.Id == objId).FirstOrDefault(); foreach(RecipeIngredient ri in recipe.RecipeIngredients) { ObjectId ingredientId = new ObjectId(ri.IngredientId); Ingredient ingredient = ingredientsCollection.Find(i => i.Id == ingredientId).FirstOrDefault(); ri.IngredientName = ingredient.Name; } return View(recipe); } public IActionResult Edit(string Id) { ObjectId objId = new ObjectId(Id); var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Recipe>("recipes"); var ingredientsCollection = database.GetCollection<Ingredient>("ingredients"); List<Ingredient> ingredientsInDb = ingredientsCollection.Find(r => true).ToList(); Recipe recipe = collection.Find(r => r.Id == objId).FirstOrDefault(); foreach (RecipeIngredient ri in recipe.RecipeIngredients) { ObjectId ingredientId = new ObjectId(ri.IngredientId); Ingredient ingredient = ingredientsCollection.Find(i => i.Id == ingredientId).FirstOrDefault(); ri.IngredientName = ingredient.Name; } RecipeEditViewModel view = new RecipeEditViewModel(); view.Ingredients = ingredientsInDb; view.Recipe = recipe; return View(view); } [HttpPost] public IActionResult Edit(string Id, Recipe recipe) { ObjectId objId = new ObjectId(Id); MongoClient dbClient = new MongoClient(); var database = dbClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Recipe>("recipes"); recipe.Id = objId; collection.ReplaceOne(b => b.Id == objId, recipe); return Redirect("/Recipes/Show/" + Id); } [HttpPost] public IActionResult Delete(string Id) { ObjectId objId = new ObjectId(Id); MongoClient dbClient = new MongoClient(); var database = dbClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Recipe>("recipes"); collection.DeleteOne(i => i.Id == objId); return Redirect("/Recipes"); } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Kers.Models.Entities.KERScore { public partial class TaxExemptArea { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int TaxExemptId {get;set;} public TaxExempt TaxExempt {get;set;} public int UnitId {get;set;} public PlanningUnit Unit {get;set;} public int DistrictId {get;set;} public District District {get;set;} public int RegionId {get;set;} public ExtensionRegion Region {get;set;} public int AreaId {get;set;} public ExtensionArea Area {get;set;} } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FormEsgi.Models { public class TypeQuestion { public int TypeQuestionId { get; set; } public string name { get; set; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using DotNetNuke.Framework.JavaScriptLibraries; namespace DotNetNuke.UI.Skins.Controls { using System; public partial class JavaScriptLibraryInclude : SkinObjectBase { public string Name { get; set; } public Version Version { get; set; } public SpecificVersion? SpecificVersion { get; set; } protected override void OnInit(EventArgs e) { if (this.Version == null) { JavaScript.RequestRegistration(this.Name); } else if (this.SpecificVersion == null) { JavaScript.RequestRegistration(this.Name, this.Version); } else { JavaScript.RequestRegistration(this.Name, this.Version, this.SpecificVersion.Value); } } } }
public class AK { public class EVENTS { public static uint PREVIEWCAVE = 2649092420U; public static uint PREVIEWNOTHING = 572514794U; public static uint PREVIEWPLATEAU = 2161215495U; public static uint PREVIEWSEAMOUNT = 3384173999U; public static uint PREVIEWWELL = 99988447U; public static uint PREVIEWWRECK = 1341998471U; } // public class EVENTS public class GAME_PARAMETERS { public static uint AZIMUTH = 1437246667U; public static uint DISTANCE = 1240670792U; public static uint SS_AIR_FEAR = 1351367891U; public static uint SS_AIR_FREEFALL = 3002758120U; public static uint SS_AIR_FURY = 1029930033U; public static uint SS_AIR_MONTH = 2648548617U; public static uint SS_AIR_PRESENCE = 3847924954U; public static uint SS_AIR_RPM = 822163944U; public static uint SS_AIR_SIZE = 3074696722U; public static uint SS_AIR_STORM = 3715662592U; public static uint SS_AIR_TIMEOFDAY = 3203397129U; public static uint SS_AIR_TURBULENCE = 4160247818U; } // public class GAME_PARAMETERS public class BANKS { public static uint INIT = 1355168291U; public static uint MAIN = 3161908922U; } // public class BANKS public class BUSSES { public static uint MASTER_AUDIO_BUS = 3803692087U; public static uint MASTER_SECONDARY_BUS = 805203703U; } // public class BUSSES }// public class AK
/*// This file is part of SNMP#NET. // // SNMP#NET is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // SNMP#NET is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with SNMP#NET. If not, see <http://www.gnu.org/licenses/>. // // Modified by Andrew Griffin 6/9/12 Nicholas Allam 21/1/16 using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using SnmpSharpNet; namespace Printer_Status { /// <summary> /// Utility class to enable simplified access to SNMP version 1 and version 2 requests and replies. /// </summary> /// <remarks> /// Use this class if you are not looking for "deep" SNMP functionality. Design of the class is based /// around providing simplest possible access to SNMP operations without getting stack into details. /// /// If you are using the simplest way, you will leave SuppressExceptions flag to true and get all errors causing methods to return "null" result /// which will not tell you why operation failed. You can change the SuppressExceptions flag to false and catch any and all /// exception throwing errors. /// /// Either way, have fun. /// </remarks> public class SimpleSnmp { /// <summary> /// SNMP Agents IP address /// </summary> protected IPAddress _peerIP; /// <summary> /// SNMP Agents name /// </summary> protected string _peerName; /// <summary> /// SNMP Agent UDP port number /// </summary> protected int _peerPort; /// <summary> /// Target class /// </summary> protected UdpTarget _target; /// <summary> /// Timeout value in milliseconds /// </summary> protected int _timeout; /// <summary> /// Maximum retry count excluding the first request /// </summary> protected int _retry; /// <summary> /// SNMP community name /// </summary> protected string _community; /// <summary> /// Non repeaters value used in SNMP GET-BULK requests /// </summary> protected int _nonRepeaters = 0; /// <summary> /// Maximum repetitions value used in SNMP GET-BULK requests /// </summary> protected int _maxRepetitions = 50; /// <summary> /// Flag determines if exceptions are suppressed or thrown. When exceptions are suppressed, methods /// return null on errors regardless of what the error is. /// </summary> protected bool _suppressExceptions = true; /// <summary>Constructor.</summary> /// <remarks> /// Class is initialized to default values. Peer IP address is set to loopback, peer port number /// to 161, timeout to 2000 ms (2 seconds), retry count to 2 and community name to public. /// </remarks> public SimpleSnmp() { _peerIP = IPAddress.Loopback; _peerPort = 161; _timeout = 2000; _retry = 2; _community = "public"; _target = null; _peerName = "localhost"; } /// <summary> /// Constructor. /// </summary> /// <remarks> /// Class is initialized with default values with the agent name set to the supplied DNS name (or /// IP address). If peer name is a DNS name, DNS resolution will take place in the constructor attempting /// to resolve it an IP address. /// </remarks> /// <param name="peerName">Peer name or IP address</param> public SimpleSnmp(string peerName) : this() { _peerName = peerName; Resolve(); } /// <summary> /// Constructor /// </summary> /// <param name="peerName">Peer name or IP address</param> /// <param name="community">SNMP community name</param> public SimpleSnmp(string peerName, string community) : this(peerName) { _community = community; } /// <summary> /// Constructor. /// </summary> /// <param name="peerName">Peer name or IP address</param> /// <param name="peerPort">Peer UDP port number</param> /// <param name="community">SNMP community name</param> public SimpleSnmp(string peerName, int peerPort, string community) : this(peerName, community) { _peerPort = peerPort; } /// <summary> /// Constructor. /// </summary> /// <param name="peerName">Peer name or IP address</param> /// <param name="peerPort">Peer UDP port number</param> /// <param name="community">SNMP community name</param> /// <param name="timeout">SNMP request timeout</param> /// <param name="retry">Maximum number of retries excluding the first request (0 = 1 request is sent)</param> public SimpleSnmp(string peerName, int peerPort, string community, int timeout, int retry) : this(peerName, peerPort, community) { _timeout = timeout; _retry = retry; } /// <summary>Class validity flag</summary> /// <remarks> /// Return class validity status. If class is valid, it is ready to send requests and receive /// replies. If false, requests to send requests will fail. /// </remarks> public bool Valid { get { if (_peerIP == IPAddress.None || _peerIP == IPAddress.Any) { return false; } if (_community.Length < 1 || _community.Length > 50) { return false; } return true; } } /// <summary> /// SNMP GET request /// </summary> /// <example>SNMP GET request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "public"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.GET; // type GET /// pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// </code> /// </example> /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> Get(SnmpVersion version, Pdu pdu) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; // class is not fully initialized. } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } try { _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); } catch (Exception ex) { _target = null; if (!_suppressExceptions) { throw ex; } } if (_target == null) { return null; } try { AgentParameters param = new AgentParameters(version, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if (version == SnmpVersion.Ver2 && (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE || v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT)) { if (!res.ContainsKey(v.Oid)) { res.Add(v.Oid, new Null()); } else { res.Add(Oid.NullOid(), v.Value); } } else { if (!res.ContainsKey(v.Oid)) { res.Add(v.Oid, v.Value); } else { if (res[v.Oid].Type == v.Value.Type) { res[v.Oid] = v.Value; // update value of the existing Oid entry } else { throw new SnmpException(SnmpException.OidValueTypeChanged, String.Format("Value type changed from {0} to {1}", res[v.Oid].Type, v.Value.Type)); } } } } //_target.Close(); //_target = null; return res; } else { if (!_suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } } catch (Exception ex) { if (!_suppressExceptions) { //_target.Close(); //_target = null; throw ex; } } // T/ODO: Release if _target != null //_target.Close(); //_target = null; return null; } /// <summary> /// SNMP GET request /// </summary> /// <example>SNMP GET request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "public"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "1.3.6.1.2.1.1.1.0" }); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// </code> /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="oidList">List of request OIDs in string dotted decimal format.</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> Get(SnmpVersion version, string[] oidList) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } Pdu pdu = new Pdu(PduType.Get); foreach (string s in oidList) { pdu.VbList.Add(s); } return Get(version, pdu); } /// <summary> /// SNMP GET-NEXT request /// </summary> /// <example>SNMP GET-NEXT request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.GETNEXT; // type GETNEXT /// pdu.VbList.Add("1.3.6.1.2.1.1"); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// </code> /// </example> /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> GetNext(SnmpVersion version, Pdu pdu) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; // class is not fully initialized. } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } try { _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); } catch { _target = null; } if (_target == null) { return null; } try { AgentParameters param = new AgentParameters(version, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if (version == SnmpVersion.Ver2 && (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW) || (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE) || (v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT)) { break; } if (res.ContainsKey(v.Oid)) { if (res[v.Oid].Type != v.Value.Type) { throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString()); } else { res[v.Oid] = v.Value; } } else { res.Add(v.Oid, v.Value); } } //_target.Close(); //_target = null; return res; } else { if (!_suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } } catch (Exception ex) { if (!_suppressExceptions) { //_target.Close(); //_target = null; throw ex; } } //_target.Close(); //_target = null; return null; } /// <summary> /// SNMP GET-NEXT request /// </summary> /// <example>SNMP GET-NEXT request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "1.3.6.1.2.1.1" }); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// </code> /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="oidList">List of request OIDs in string dotted decimal format.</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> GetNext(SnmpVersion version, string[] oidList) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } Pdu pdu = new Pdu(PduType.GetNext); foreach (string s in oidList) { pdu.VbList.Add(s); } return GetNext(version, pdu); } /// <summary> /// SNMP GET-BULK request /// </summary> /// <remarks> /// GetBulk request type is only available with SNMP v2c agents. SNMP v3 also supports the request itself /// but that version of the protocol is not supported by SimpleSnmp. /// /// GetBulk method will return a dictionary of Oid to value mapped values as returned form a /// single GetBulk request to the agent. You can change how the request itself is made by changing the /// SimpleSnmp.NonRepeaters and SimpleSnmp.MaxRepetitions values. SimpleSnmp properties are only used /// when values in the parameter Pdu are set to 0. /// </remarks> /// <example>SNMP GET-BULK request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.GETBULK; // type GETBULK /// pdu.VbList.Add("1.3.6.1.2.1.1"); /// pdu.NonRepeaters = 0; /// pdu.MaxRepetitions = 10; /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetBulk(pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1 /// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms /// 1.3.6.1.2.1.1.4.0 = OctetString: "msinadinovic@users.sourceforge.net" /// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook" /// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home" /// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms /// </code> /// </example> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> GetBulk(Pdu pdu) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; // class is not fully initialized. } try { pdu.NonRepeaters = _nonRepeaters; pdu.MaxRepetitions = _maxRepetitions; _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); } catch (Exception ex) { _target = null; if (!_suppressExceptions) { throw ex; } } if (_target == null) { return null; } try { AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if ( (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW) || (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE) || (v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT) ) { break; } if (res.ContainsKey(v.Oid)) { if (res[v.Oid].Type != v.Value.Type) { throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString()); } else { res[v.Oid] = v.Value; } } else { res.Add(v.Oid, v.Value); } } //_target.Close(); //_target = null; return res; } else { if (!_suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } } catch (Exception ex) { if (!_suppressExceptions) { //_target.Close(); //_target = null; throw ex; } } //_target.Close(); //_target = null; return null; } /// <summary> /// SNMP GET-BULK request /// </summary> /// <remarks> /// Performs a GetBulk SNMP v2 operation on a list of OIDs. This is a convenience function that /// calls GetBulk(Pdu) method. /// </remarks> /// <example>SNMP GET-BULK request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetBulk(new string[] { "1.3.6.1.2.1.1" }); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// </example> /// <param name="oidList">List of request OIDs in string dotted decimal format.</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> GetBulk(string[] oidList) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; } Pdu pdu = new Pdu(PduType.GetBulk); pdu.MaxRepetitions = _maxRepetitions; pdu.NonRepeaters = _nonRepeaters; foreach (string s in oidList) { pdu.VbList.Add(s); } return GetBulk(pdu); } /// <summary> /// SNMP SET request /// </summary> /// <example>Set operation in SNMP version 1: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.SET; // type SET /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0 /// OctetString setValue = new OctetString("My personal toy"); /// pdu.VbList.Add(setOid, setValue); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// Console.WriteLine("Success!"); /// } /// </code> /// /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2. /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> Set(SnmpVersion version, Pdu pdu) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; // class is not fully initialized. } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } try { _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); } catch (Exception ex) { _target = null; if (!_suppressExceptions) { throw ex; } } if (_target == null) { return null; } try { AgentParameters param = new AgentParameters(version, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if (res.ContainsKey(v.Oid)) { if (res[v.Oid].Type != v.Value.Type) { throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString()); } else { res[v.Oid] = v.Value; } } else { res.Add(v.Oid, v.Value); } } //_target.Close(); //_target = null; return res; } else { if (!_suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } } catch (Exception ex) { if (!_suppressExceptions) { //_target.Close(); //_target = null; throw ex; } } //_target.Close(); //_target = null; return null; } /// <summary> /// SNMP SET request /// </summary> /// <example>Set operation in SNMP version 1: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// List&lt;Vb&gt; vbList = new List&lt;Vb&gt;(); /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0 /// OctetString setValue = new OctetString("My personal toy"); /// vbList.Add(new Vb(setOid, setValue)); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, list.ToArray()); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// Console.WriteLine("Success!"); /// } /// </code> /// /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2. /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="vbs">Vb array containing Oid/AsnValue pairs for the SET operation</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary<Oid, AsnType> Set(SnmpVersion version, Vb[] vbs) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } Pdu pdu = new Pdu(PduType.Set); foreach (Vb vb in vbs) { pdu.VbList.Add(vb); } return Set(version, pdu); } /// <summary>SNMP WALK operation</summary> /// <remarks> /// When using SNMP version 1, walk is performed using GET-NEXT calls. When using SNMP version 2, /// walk is performed using GET-BULK calls. /// </remarks> /// <example>Example SNMP walk operation using SNMP version 1: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Walk(SnmpVersion.Ver1, "1.3.6.1.2.1.1"); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1 /// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms /// 1.3.6.1.2.1.1.4.0 = OctetString: "msinadinovic@users.sourceforge.net" /// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook" /// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home" /// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms /// </code> /// /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2. /// </example> /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and /// SnmpVersion.Ver2</param> /// <param name="rootOid">OID to start WALK operation from. Only child OIDs of the rootOid will be /// retrieved and returned</param> /// <returns>Oid => AsnType value mappings on success, empty dictionary if no data was found or /// null on error</returns> public Dictionary<Oid, AsnType> Walk(SnmpVersion version, string rootOid) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } if (rootOid.Length < 2) { if (!_suppressExceptions) { throw new SnmpException(SnmpException.InvalidOid, "RootOid is not a valid Oid"); } return null; } Oid root = new Oid(rootOid); if (root.Length <= 0) { return null; // unable to parse root oid } Oid lastOid = (Oid)root.Clone(); Dictionary<Oid, AsnType> result = new Dictionary<Oid, AsnType>(); while (lastOid != null && root.IsRootOf(lastOid)) { Dictionary<Oid, AsnType> val = null; if (version == SnmpVersion.Ver1) { val = GetNext(version, new string[] { lastOid.ToString() }); } else { val = GetBulk(new string[] { lastOid.ToString() }); } // check that we have a result if (val == null) { // error of some sort happened. abort... return null; } foreach (KeyValuePair<Oid, AsnType> entry in val) { if (root.IsRootOf(entry.Key)) { if (result.ContainsKey(entry.Key)) { if (result[entry.Key].Type != entry.Value.Type) { throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + entry.Key.ToString()); } else result[entry.Key] = entry.Value; } else { result.Add(entry.Key, entry.Value); } lastOid = (Oid)entry.Key.Clone(); } else { // it's faster to check if variable is null then checking IsRootOf lastOid = null; break; } } } return result; } /// <summary>SNMP WALK operation</summary> /// <remarks> /// When using SNMP version 1, walk is performed using GET-NEXT calls. When using SNMP version 2, /// walk is performed using GET-BULK calls. /// </remarks> /// <example>Example SNMP walk operation using SNMP version 1: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Walk(SnmpVersion.Ver1, "1.3.6.1.2.1.1"); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1 /// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms /// 1.3.6.1.2.1.1.4.0 = OctetString: "msinadinovic@users.sourceforge.net" /// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook" /// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home" /// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms /// </code> /// /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2. /// </example> /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and /// SnmpVersion.Ver2</param> /// <param name="rootOid">OID to start WALK operation from. Only child OIDs of the rootOid will be /// retrieved and returned</param> /// <param name="tryGetBulk">this param is used to use get bulk on V2 requests</param> /// <returns>Oid => AsnType value mappings on success, empty dictionary if no data was found or /// null on error</returns> public Dictionary<Oid, AsnType> Walk(bool tryGetBulk, SnmpVersion version, string rootOid) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return null; } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return null; } if (rootOid.Length < 2) { if (!_suppressExceptions) { throw new SnmpException(SnmpException.InvalidOid, "RootOid is not a valid Oid"); } return null; } Oid root = new Oid(rootOid); if (root.Length <= 0) { return null; // unable to parse root oid } Oid lastOid = (Oid)root.Clone(); Dictionary<Oid, AsnType> result = new Dictionary<Oid, AsnType>(); while (lastOid != null && root.IsRootOf(lastOid)) { Dictionary<Oid, AsnType> val = null; if (version == SnmpVersion.Ver1) { val = GetNext(version, new string[] { lastOid.ToString() }); } else { if (tryGetBulk == true) { val = GetBulk(new string[] { lastOid.ToString() }); } else { val = GetNext(version, new string[] { lastOid.ToString() }); } } // check that we have a result if (val == null) { // error of some sort happened. abort... return null; } foreach (KeyValuePair<Oid, AsnType> entry in val) { if (root.IsRootOf(entry.Key)) { if (result.ContainsKey(entry.Key)) { if (result[entry.Key].Type != entry.Value.Type) { throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + entry.Key.ToString()); } else result[entry.Key] = entry.Value; } else { result.Add(entry.Key, entry.Value); } lastOid = (Oid)entry.Key.Clone(); } else { // it's faster to check if variable is null then checking IsRootOf lastOid = null; break; } } } return result; } #region Properties /// <summary> /// Get/Set peer IP address /// </summary> public IPAddress PeerIP { get { return _peerIP; } set { _peerIP = value; } } /// <summary> /// Get/Set peer name /// </summary> public string PeerName { get { return _peerName; } set { _peerName = value; Resolve(); } } /// <summary> /// Get/Set peer port number /// </summary> public int PeerPort { get { return _peerPort; } set { _peerPort = value; } } /// <summary> /// Get set timeout value in milliseconds /// </summary> public int Timeout { get { return _timeout; } set { _timeout = value; } } /// <summary> /// Get/Set maximum retry count /// </summary> public int Retry { get { return _retry; } set { _retry = value; } } /// <summary> /// Get/Set SNMP community name /// </summary> public string Community { get { return _community; } set { _community = value; } } /// <summary> /// Get/Set NonRepeaters value /// </summary> /// <remarks>NonRepeaters value will only be used by SNMPv2 GET-BULK requests. Any other /// request type will ignore this value.</remarks> public int NonRepeaters { get { return _nonRepeaters; } set { _nonRepeaters = value; } } /// <summary> /// Get/Set MaxRepetitions value /// </summary> /// <remarks>MaxRepetitions value will only be used by SNMPv2 GET-BULK requests. Any other /// request type will ignore this value.</remarks> public int MaxRepetitions { get { return _maxRepetitions; } set { _maxRepetitions = value; } } #endregion #region Utility functions /// <summary> /// Resolve peer name to an IP address /// </summary> /// <remarks> /// This method will not throw any exceptions, even on failed DNS resolution. Make /// sure you call SimpleSnmp.Valid property to verify class state. /// </remarks> /// <returns>true if DNS resolution is successful, otherwise false</returns> internal bool Resolve() { _peerIP = IPAddress.None; if (_peerName.Length > 0) { if (IPAddress.TryParse(_peerName, out _peerIP)) { return true; } else { _peerIP = IPAddress.None; // just in case } IPHostEntry he = null; try { he = Dns.GetHostEntry(_peerName); } catch (Exception ex) { if (!_suppressExceptions) { throw ex; } he = null; } if (he == null) return false; // resolution failed foreach (IPAddress tmp in he.AddressList) { if (tmp.AddressFamily == AddressFamily.InterNetwork) { _peerIP = tmp; break; } } if (_peerIP != IPAddress.None) return true; } return false; } /// <summary> /// Get/Set exception suppression flag. /// /// If exceptions are suppressed all methods return null on any and all errors. With suppression disabled, you can /// capture error details in try/catch blocks around method calls. /// </summary> public bool SuppressExceptions { get { return _suppressExceptions; } set { _suppressExceptions = value; } } #endregion } }*/
using LogicBuilder.RulesDirector; using LogicBuilder.Workflow.Activities.Rules; using System; using System.Collections.Generic; namespace Enrollment.XPlatform.Tests.Mocks { public class RulesCacheMock : IRulesCache { public IDictionary<string, RuleEngine> RuleEngines => throw new NotImplementedException(); public IDictionary<string, string> ResourceStrings => throw new NotImplementedException(); public RuleEngine GetRuleEngine(string ruleSet) { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; namespace WebRequest.Basic { public class CoroutineWebRequest : MonoBehaviour { IEnumerator Start() { var req = UnityWebRequest.Get("https://unity.com/"); yield return req.SendWebRequest(); Debug.Log(req.downloadHandler.text); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; public class MacaroonCallCredentials { public CallCredentials credentials; public MacaroonCallCredentials(string macaroon) { var asyncAuthInterceptor = new AsyncAuthInterceptor(async (context, metadata) => { await Task.Delay(100).ConfigureAwait(false); metadata.Add("macaroon", macaroon); }); credentials = CallCredentials.FromInterceptor(asyncAuthInterceptor); } }