text
stringlengths
13
6.01M
using UnityEngine; using UnityEngine.EventSystems; public class TapDetector : MonoBehaviour, IPointerDownHandler { public SigilController Target; public void OnPointerDown(PointerEventData eventData) { Target.Tap(); } }
/* DotNetMQ - A Complete Message Broker For .NET Copyright (C) 2011 Halil ibrahim KALKAN This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ namespace MDS.Organization.Routing { /// <summary> /// Represents a Destination of a Routing. /// </summary> public class RoutingDestination { /// <summary> /// Destination server name. Must be one of following values: /// Empty string or null: Don't change destination server. /// this: Change to this/current server. /// A server name: Change to a specified server name. /// </summary> public string Server { get; set; } /// <summary> /// Destination application name. Must be one of following values: /// Empty string or null: Don't change destination application. /// A application name: Change to a specified application name. /// </summary> public string Application { get; set; } /// <summary> /// Route factor. /// Must be 1 or greater. /// </summary> public int RouteFactor { get; set; } /// <summary> /// Creates a new RoutingDestination object. /// </summary> public RoutingDestination() { Server = ""; Application = ""; RouteFactor = 1; } /// <summary> /// Returns a string that presents a brief information about RoutingFilter object. /// </summary> /// <returns>Brief information about RoutingFilter object</returns> public override string ToString() { return string.Format("Server: {0}, Application: {1}, RouteFactor: {2}", Server, Application, RouteFactor); } } }
 using Controle.Domain.Entities; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using NUnit.Framework; namespace Controle.Teste { [TestFixture] public class CriarBanco { [Test] //[Ignore] public void a__Criar_Banco_De_Dados_Por_Modelo() { Fluently.Configure().Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c .FromAppSetting("Conexao") )).Mappings(m => m.FluentMappings.AddFromAssemblyOf<Entrada>()).Mappings(m => m.MergeMappings()) .ExposeConfiguration(BuildSchema).BuildSessionFactory(); } private void BuildSchema(Configuration config) { new SchemaExport(config) .Drop(true, true); new SchemaExport(config) .Create(true, true); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Game.Models { public class Games { [Key] public String GameId { get; set; } [Required] public int DrawID { get; set; } public String TicketId { get; set; } private Random random; public Random GamePlayed() { int[] array = new int[6]; random = new Random(); for (int i = 0; i < 6; i++) { int result = random.Next(0, 49); int modulo = result % array.Length; array[modulo]++; } #pragma warning disable CS0162 // Unreachable code detected for (int i = 0; i < array.Length; i++) #pragma warning restore CS0162 // Unreachable code detected { return random; } return random; } public virtual Games lotto { get; set; } } }
using LazyVocabulary.Common.Entities; using LazyVocabulary.DataAccess.EF; using LazyVocabulary.DataAccess.Interfaces; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace LazyVocabulary.DataAccess.Repositories { public class LanguageRepository : IRepository<Language> { private readonly ApplicationContext _db; public LanguageRepository(ApplicationContext context) { _db = context; } public IEnumerable<Language> GetAll() { return _db.Languages; } public Language Get(int id) { return _db.Languages.Find(id); } public void Create(Language item) { _db.Languages.Add(item); } public void Update(Language item) { _db.Entry(item).State = EntityState.Modified; } public void Delete(int id) { Language item = _db.Languages.Find(id); if (item != null) { _db.Languages.Remove(item); } } public IEnumerable<Language> Find(Func<Language, bool> predicate) { return _db.Languages.Where(predicate); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; using System.Web.UI; using System.Configuration; using Pes.Core; /// <summary> /// For All Message /// X: Lession, Module, Part, Admin ... /// Y: Function. /// ABC: Optional. /// </summary> public class SessionConstants { public SessionConstants() { } public static string Session_Admin = "SessionAdmin"; public static string Session_GroupRole = "GroupRole"; public static string Session_TempGroupBO = "TempGroupBO"; public static string Session_PartEdit = "PartEdit"; public static string Session_PartInsertEditCompleted = "PartEditCompleted"; public static string Session_PartInsert = "PartInsert"; public static string Session_PartInsertEditItem = "PartInsertEditItem"; public static string Session_LessionInsertCompleted = "LessionInsertCompleted"; public static string Session_LessionInsert = "LessionInsert"; public static string Session_LessionDeleted = "LessionDeleted"; public static string Session_LessionSearch = "LessionSearch"; public static string Session_LessionGroupAction = "LessionGroupAction"; public static string Session_LessionGroupAlert = "LessionGroupAlert"; public static string Session_Action = "SessionAction";// 1: Insert - 2: Update. public static string Session_PageWidth = "PageWidth"; public static string Session_PageHeight = "PageHeight"; public static string Session_PupilLoginID = "PupilLoginID"; public static string Session_PupilLogin = "PupilLogin"; public static string Session_LanguageState = "LanguageState"; public static string Session_RandomGamesForTopTen = "RandomGamesForTopTen"; public static string Session_GamePlayingID = "GamePlayingID"; }
// Copyright (c) 2014 - 2016 George Kimionis // See the accompanying file LICENSE for the Software License Aggrement using System; using System.Linq; using BitcoinLib.Services.Coins.Base; namespace BitcoinLib.ExtensionMethods { public static class StringExtensionMethods { public static string RemoveWhitespace(this string input) { return new string(input.ToCharArray() .Where(c => !Char.IsWhiteSpace(c)) .ToArray()); } } }
using Entidades; using Entidades.Exceptions; using PetShopForms.Vistas.Persona; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PetShopForms.Vistas.Empleados { public partial class Agregar : Form { public PersonaData PersonaDataForm; public EmpleadoData EmpleadoDataForm; string usuario, contrasenia, nombre, apellido; double sueldo, cuil, bono; bool isAdmin, isSuperAdmin; private void Agregar_Paint(object sender, PaintEventArgs e) { Inicio.ResetTimeOutTime(); } private void Agregar_Click(object sender, EventArgs e) { Inicio.ResetTimeOutTime(); } private void Agregar_MouseClick(object sender, MouseEventArgs e) { Inicio.ResetTimeOutTime(); } bool altaOk = false; string userType = ""; public Agregar() { InitializeComponent(); } private void Agregar_Load(object sender, EventArgs e) { this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); EmpleadoDataForm = (EmpleadoData)Inicio.AddFormToControl(pFullContainer.Controls, new EmpleadoData()); PersonaDataForm = (PersonaData)Inicio.AddFormToControl(pFullContainer.Controls, new Persona.PersonaData()); } private void btnAccept_Click(object sender, EventArgs e) { usuario = PersonaDataForm.Usuario; contrasenia = PersonaDataForm.Contrasenia; cuil = PersonaDataForm.Cuil; nombre = PersonaDataForm.Nombre; apellido = PersonaDataForm.Apellido; sueldo = EmpleadoDataForm.Sueldo; isAdmin = EmpleadoDataForm.IsAdmin; isSuperAdmin = EmpleadoDataForm.IsSuperAdmin; bono = EmpleadoDataForm.Bono; if (string.IsNullOrEmpty(usuario) || string.IsNullOrEmpty(contrasenia) || cuil < 1 || string.IsNullOrEmpty(nombre) || string.IsNullOrEmpty(apellido) || sueldo < 1 || (isAdmin && bono < 1)) { MessageBox.Show("Todos los campos son requeridos", "Error", MessageBoxButtons.OK); } else { try { if (isAdmin) { Administrador auxAdmin = new Administrador(nombre, apellido, usuario, contrasenia, cuil, sueldo, isAdmin, isSuperAdmin, bono); altaOk = Core.ListaEmpleados + auxAdmin; userType = auxAdmin.GetType().ToString(); } else { Empleado auxEmpleado = new Empleado(nombre, apellido, usuario, contrasenia, cuil, sueldo); altaOk = Core.ListaEmpleados + auxEmpleado; userType = auxEmpleado.GetType().ToString(); } userType = userType.Split('.')[1]; if (altaOk) { Inicio.PlaySound(Inicio.SucessSoundPath); MessageBox.Show($"Alta de {userType} exitosa", "Carga exitosa", MessageBoxButtons.OK); this.Close(); } else { MessageBox.Show("Error en la carga del empleado", "Error", MessageBoxButtons.OK); } } catch (CuilException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK); } } } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BackPropagation { public partial class LineGraph : UserControl { private double[] data; public double[] Data { get { return data; } } public LineGraph() { InitializeComponent(); } public void SetData(double[] data) { this.data = data; DrawGraph(CreateGraphics()); } private void LineGraph_Paint(object sender, PaintEventArgs e) { DrawGraph(e.Graphics); } private void DrawGraph(Graphics graphics) { Brush axisBrush = new SolidBrush(Color.Gray); Pen axisPen = new Pen(axisBrush); Pen pointPen = new Pen(Color.Black, 1); try { if (data == null) { return; } graphics.Clear(BackColor); int yAxisLines = 10; int axisPadding = 30; int graphWidth = Width - axisPadding; int graphHeight = Height - axisPadding; // Average the data. int averageLength = Math.Max(data.Length / graphWidth, 1); double[] averagedData = new double[graphWidth]; for (int i = 0; i < averagedData.Length; i++) { double sum = 0; for (int j = 0; j < averageLength; j++) { sum += data[i * averageLength + j]; } averagedData[i] = sum / averageLength; } // Draw y axis. double maxValue = averagedData.Max(); for (int i = 0; i <= yAxisLines; i++) { int yPos = graphHeight * i / yAxisLines; int xPos = i + axisPadding; double label = Math.Round(maxValue - maxValue * i / yAxisLines, 3); graphics.DrawLine(axisPen, i + axisPadding, yPos, graphWidth + axisPadding, yPos); graphics.DrawString((label * 100).ToString() + "%", Font, axisBrush, new PointF(0, yPos)); } // Draw the averaged data. for (int i = 0; i < averagedData.Length; i++) { int yPos = (int)(averagedData[i] * graphHeight / maxValue); int xPos = i + axisPadding; graphics.DrawLine(pointPen, xPos, graphHeight, xPos, graphHeight - yPos); } } catch (OverflowException overflowException) { graphics.Clear(BackColor); graphics.DrawString(overflowException.Message, Font, new SolidBrush(Color.Black), 5, 5); } finally { axisBrush.Dispose(); axisPen.Dispose(); pointPen.Dispose(); } } } }
using Azure.Storage.Blobs; using Azure.Storage.Blobs.Specialized; using FluentValidation.AspNetCore; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Publicon.Api.Authorization; using Publicon.Api.Extensions; using Publicon.Api.HostedServices; using Publicon.Api.Middleware; using Publicon.API.Binders.BodyandRoute; using Publicon.Core.DAL; using Publicon.Core.Modules; using Publicon.Infrastructure.Modules; using Publicon.Infrastructure.Settings; using System; namespace Publicon.Api { 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.AddDbContext<PubliconContext>(options => { options.UseLazyLoadingProxies(); //options.UseSqlServer(Environment.GetEnvironmentVariable("ConnectionString")); options.UseSqlServer(Configuration.GetConnectionString("SqlExpress")); }); services.AddSingleton(x => new BlobServiceClient(Environment.GetEnvironmentVariable("ConnectionStrings__AzureStorage"))); services.AddControllers(opt => { opt.ModelBinderProviders.InsertBodyAndRouteBinding(); }).AddFluentValidation(fv => { fv.RegisterValidatorsFromAssemblyContaining<Startup>(); fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false; }); services.AddOptions(); var mailSettingsSection = Configuration.GetSection(nameof(MailSettings)); services.Configure<MailSettings>(mailSettingsSection); var frontendSettingsSection = Configuration.GetSection(nameof(FrontendSettings)); services.Configure<FrontendSettings>(frontendSettingsSection); services.AddHttpContextAccessor(); services.AddScoped<IAuthorizationHandler, MustBeOwnerOrAdminHandler>(); services.AddAuthorization(options => { options.AddPolicy("MustBeOwnerOrAdmin", builder => { builder.RequireAuthenticatedUser(); builder.AddRequirements( new MustBeOwnerOrAdminRequirement()); }); }); services.AddHostedService<SendNotificationService>(); services.AddAuthenticationConfiguration(Configuration); services.AddSwaggerConfiguration(); services.AddRepositoriesModule(); services.AddManagersModule(); services.AddMediatRModule(); services.AddMapperModule(); services.AddPasswordHasherModule(); } // 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.UseMiddleware(typeof(GlobalExceptionMiddleware)); //app.UseDeveloperExceptionPage(); } else { app.UseMiddleware(typeof(GlobalExceptionMiddleware)); } //app.UseHttpsRedirection(); app.UseCorsPolicy(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Publicon v1"); }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
namespace InfiniteMeals { internal class Post { public string Monday { get; set; } public string Tuesday { get; set; } public string Wednesday { get; set; } public string Thursday { get; set; } public string Friday { get; set; } public string Saturday { get; set; } public string Sunday { get; set; } } internal class OrderPost { public string item_name { get; set; } public string item_qty { get; set; } } }
using UnityEngine; using System.Collections; public class Movement : MonoBehaviour { Gridsystem gridSystem; Transform obj_GridSystem; SpriteRenderer sRender; float blockSize; Vector3 playerPosition; public Sprite sprite; void Start () { obj_GridSystem = GameObject.FindGameObjectWithTag ("Grid").transform; gridSystem = obj_GridSystem.GetComponent<Gridsystem> (); sRender = gameObject.GetComponent<SpriteRenderer> (); playerPosition = gameObject.transform.position; blockSize = sprite.rect.x + 0.016f; } // Update is called once per frame void Update () { var objectPosition = gridSystem.getCordinatFromPosistion (gameObject.transform.position); var mousePosition = gridSystem.getMousePosition (); if (objectPosition != mousePosition) { Vector2 goal = new Vector2 (mousePosition.x - objectPosition.x, mousePosition.y - objectPosition.y); pathFinding (goal); } } public void pathFinding (Vector2 goal) { var endGoal = goal; var objectPosition = gridSystem.getCordinatFromPosistion (gameObject.transform.position); int xMovement = 0; int yMovement = 0; if (xMovement == 0) { var xPosition = gameObject.transform.position.x; var goalPositionX = new float (); if (endGoal.x > 0) goalPositionX = gameObject.transform.position.x + blockSize; else goalPositionX = gameObject.transform.position.x - blockSize; if (gameObject.transform.position.x > goalPositionX) { Debug.Log (goalPositionX); gameObject.transform.position -= transform.right * 0.01f; } if (gameObject.transform.position.x < goalPositionX) { gameObject.transform.position += transform.right * 0.01f; Debug.Log (goalPositionX); } if (gameObject.transform.position.x == goalPositionX) { endGoal.x--; xMovement++; } } if (xMovement == 1 && yMovement == 0) { endGoal.y--; yMovement++; } if(endGoal.x > 0 || endGoal.y > 0) { pathFinding(endGoal); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Linq; using Terrasoft.Common; using Terrasoft.Configuration; using Terrasoft.Core; using Terrasoft.Core.DB; using Terrasoft.Core.Entities; using Terrasoft.Core.Entities.Events; namespace ZoomIntegration { [EntityEventListener(SchemaName = "Activity")] public class ActivityEventListener : BaseEntityEventListener { private UserConnection UserConnection; public override void OnSaving(object sender, EntityBeforeEventArgs e) { base.OnSaving(sender, e); Entity activity = (Entity)sender; UserConnection = activity.UserConnection; bool IsZoom = activity.GetTypedColumnValue<bool>("CreateZoomMeeting"); string M = activity.GetTypedColumnValue<String>("MeetingId"); if (IsZoom && String.IsNullOrEmpty(M)){ ZoomMeetingApi zm = new ZoomMeetingApi(UserConnection); DateTime startDate = activity.GetTypedColumnValue<DateTime>("StartDate"); TimeSpan offset = UserConnection.CurrentUser.TimeZone.GetUtcOffset(startDate); /* * DateTime Return in Users LocalTime this need to convert to UTC */ string zoomStart = startDate.Add(-offset).ToString("yyyy-MM-ddTHH:mm:ssZ"); DateTime Due = activity.GetTypedColumnValue<DateTime>("DueDate"); int Duration = (int)Due.Subtract(startDate).TotalMinutes; Guid TimeZoneId = activity.GetTypedColumnValue<Guid>("TimeZoneId"); if (TimeZoneId == Guid.Empty) { // _userConnection.CurrentUser.TimeZoneId = "Eastern" Guid g = IdValue("TimeZone", "Code", UserConnection.CurrentUser.TimeZoneId); TimeZoneId = g; } string ZoomTimeZone = FindZoomTimeZone(TimeZoneId); string topic = activity.GetTypedColumnValue<String>("Title"); string agenda = activity.GetTypedColumnValue<String>("Notes"); MeetingRequest mr = new MeetingRequest(PredifinedMeetings.Certification, topic, agenda, zoomStart, Duration, ZoomTimeZone); zm.CreateZoomMeeting(mr); /* * Update activity after creating a meeting */ activity.SetColumnValue("MeetingId", zm.mResponse.Id); activity.SetColumnValue("MeetingUUID", zm.mResponse.Uuid); activity.SetColumnValue("StartUrl", zm.mResponse.StartUrl); activity.SetColumnValue("JoinUrl", zm.mResponse.JoinUrl); activity.SetColumnValue("RegistrationUrl", zm.mResponse.RegistrationUrl); activity.SetColumnValue("HostId", zm.mResponse.HostId); activity.SetColumnValue("AlternativeHosts", zm.mResponse.Settings.AlternativeHosts); SendMessageToUi(activity.GetTypedColumnValue<Guid>("Id"),"Meeting Created"); } } public override void OnUpdated(object sender, EntityAfterEventArgs e) { base.OnUpdated(sender, e); Entity activity = (Entity)sender; UserConnection = activity.UserConnection; bool NeedUpdate = false; bool IsZoom = activity.GetTypedColumnValue<bool>("CreateZoomMeeting"); if (IsZoom){ //Columns that triger Meeting Update string[] ZoomUpdateColums = { "Title", "Notes", "AlternativeHosts", "StartDate", "DueDate", "TimeZoneId" }; foreach (EntityColumnValue c in e.ModifiedColumnValues) { if (ZoomUpdateColums.Contains(c.Name)) { NeedUpdate = true; break; } } if (NeedUpdate) { UpdateZoomMeeting(activity); } } } public override void OnDeleting(object sender, EntityBeforeEventArgs e) { base.OnDeleting(sender, e); Entity activity = (Entity)sender; UserConnection = activity.UserConnection; bool IsZoom = activity.GetTypedColumnValue<bool>("CreateZoomMeeting"); if (IsZoom) { ZoomMeetingApi zm = new ZoomMeetingApi(UserConnection); string MeetingId = activity.GetTypedColumnValue<String>("MeetingId"); zm.DeleteZoomMeeting(MeetingId); } } private void UpdateZoomMeeting(Entity activity) { ZoomMeetingApi zm = new ZoomMeetingApi(UserConnection); string MeetingId = activity.GetTypedColumnValue<string>("MeetingId"); zm.RetrieveMeeting(MeetingId); MeetingResponse Original = zm.retrieveMeetingResponse; Original.Topic = (activity.GetTypedColumnValue<String>("Title") == Original.Topic) ? Original.Topic : activity.GetTypedColumnValue<String>("Title"); Original.Agenda = (activity.GetTypedColumnValue<String>("Notes") == Original.Topic) ? Original.Agenda : activity.GetTypedColumnValue<String>("Notes"); Original.Settings.AlternativeHosts = activity.GetTypedColumnValue<String>("AlternativeHosts"); DateTime startDate = activity.GetTypedColumnValue<DateTime>("StartDate"); TimeSpan offset = UserConnection.CurrentUser.TimeZone.GetUtcOffset(startDate); //DateTime Return in Users LocalTime this need to convert to UTC string zoomStart = startDate.Add(-offset).ToString("yyyy-MM-ddTHH:mm:ssZ"); DateTime Due = activity.GetTypedColumnValue<DateTime>("DueDate"); Guid TimeZoneId = activity.GetTypedColumnValue<Guid>("TimeZoneId"); string ZoomTimeZone = FindZoomTimeZone(TimeZoneId); Original.TimeZone = ZoomTimeZone; Original.StartTime = zoomStart; Int32 Duration = (Int32)Due.Subtract(startDate).TotalMinutes; Original.Duration = Duration; zm.UpdateZoomMeeting(Original, MeetingId); } #region HelperMethods static void SendMessageToUi(Guid recordId, string MyEvent){ string senderName = "ActivityEventListener"; // Example for message string message = JsonConvert.SerializeObject(new { RecordID = recordId, Event = MyEvent }); // For all users MsgChannelUtilities.PostMessageToAll(senderName, message); } public string FindZoomTimeZone(Guid TimeZoneId) { Select select = new Select(UserConnection) .Column("Id") .Column("Name") .From("ZoomTimeZone") .Where("TimeZoneId").IsEqual(Column.Parameter(TimeZoneId)) as Select; var result = new Dictionary<Guid, string>(); String res = string.Empty; using (DBExecutor dbExecutor = UserConnection.EnsureDBConnection()) { using (IDataReader dataReader = select.ExecuteReader(dbExecutor)) { while (dataReader.Read()) { Guid key = dataReader.GetColumnValue<Guid>("Id"); string value = dataReader.GetColumnValue<string>("Name"); result.Add(key, value); res = value; break; } } } return res; } public Guid IdValue(string Table, string SearchColumn, string SearchValue) { Select select = new Select(UserConnection) .Column("Id") .Column(SearchColumn) .From(Table) .Where(SearchColumn).IsEqual(Column.Parameter(SearchValue)) as Select; var result = new Dictionary<Guid, string>(); using (DBExecutor dbExecutor = UserConnection.EnsureDBConnection()) { using (IDataReader dataReader = select.ExecuteReader(dbExecutor)) { while (dataReader.Read()) { Guid key = dataReader.GetColumnValue<Guid>("Id"); string value = dataReader.GetColumnValue<string>(SearchColumn); result.Add(key, value); } } } Guid MyKey = Guid.Empty; foreach (KeyValuePair<Guid, string> pair in result) { if (pair.Value == SearchValue) { MyKey = pair.Key; break; } } return MyKey; } public string LValue(string Table, string SearchColumn, Guid recordId) { Select select = new Select(UserConnection) .Column("Id") .Column(SearchColumn) .From(Table) .Where("Id").IsEqual(Column.Parameter(recordId)) as Select; var result = new Dictionary<Guid, string>(); using (DBExecutor dbExecutor = UserConnection.EnsureDBConnection()) { using (IDataReader dataReader = select.ExecuteReader(dbExecutor)) { while (dataReader.Read()) { Guid key = dataReader.GetColumnValue<Guid>("Id"); string value = dataReader.GetColumnValue<string>(SearchColumn); result.Add(key, value); } } } return result[recordId]; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Master.Contract; namespace Master.Contract { public class Currency:IContract { public Currency() { } public string CurrencyCode { get; set; } public string Description { get; set; } public string CreatedBy { get; set; } public DateTime CreatedOn { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedOn { 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; using System.Collections.Generic; using System.ComponentModel; using DotNetNuke.Framework; namespace DotNetNuke.Security.Roles.Internal { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use RoleController instead. Scheduled removal in v10.0.0.")] public class TestableRoleController : ServiceLocator<IRoleController, TestableRoleController>, IRoleController { protected override Func<IRoleController> GetFactory() { return () => new TestableRoleController(); } public int AddRole(RoleInfo role) { return RoleController.Instance.AddRole(role); } public int AddRole(RoleInfo role, bool addToExistUsers) { return RoleController.Instance.AddRole(role, addToExistUsers); } public void DeleteRole(RoleInfo role) { RoleController.Instance.DeleteRole(role); } public RoleInfo GetRole(int portalId, Func<RoleInfo, bool> predicate) { return RoleController.Instance.GetRole(portalId, predicate); } public IList<RoleInfo> GetRoles(int portalId) { return RoleController.Instance.GetRoles(portalId); } public IList<RoleInfo> GetRolesBasicSearch(int portalID, int pageSize, string filterBy) { return RoleController.Instance.GetRolesBasicSearch(portalID, pageSize, filterBy); } public IList<RoleInfo> GetRoles(int portalId, Func<RoleInfo, bool> predicate) { return RoleController.Instance.GetRoles(portalId, predicate); } public IDictionary<string, string> GetRoleSettings(int roleId) { return RoleController.Instance.GetRoleSettings(roleId); } public void UpdateRole(RoleInfo role) { RoleController.Instance.UpdateRole(role); } public void UpdateRole(RoleInfo role, bool addToExistUsers) { RoleController.Instance.UpdateRole(role, addToExistUsers); } public void UpdateRoleSettings(RoleInfo role, bool clearCache) { RoleController.Instance.UpdateRoleSettings(role, clearCache); } public void ClearRoleCache(int portalId) { RoleController.Instance.ClearRoleCache(portalId); } } }
using System; using System.Collections.Generic; using UnityEngine; namespace NeuralNetwork { [Serializable] public class NetData { public List<double> netWorkWeights = new List<double>(); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class DungeonManager : MonoBehaviour { public static DungeonManager instance = null; //Static instance of GameManager which allows it to be accessed by any other script. public GameObject stoneEntranceTile; public GameObject stoneDoorOpenTile; public GameObject stoneDoorClosedTile; public GameObject stoneDoorLockedTile; public GameObject stoneDoorSecretTile; public GameObject stoneArchTile; public GameObject stoneStairsUpTile; public GameObject stoneStairsDownTile; public GameObject[] stoneFloorTiles; public GameObject[] stoneWallTiles; public GameObject[] corridorTiles; public List<Dungeon> dungeons; void Awake() { if(instance == null) { instance = this; } } public Dungeon GenerateRandomDungeon() { Dungeon dungeon = new Dungeon(DUNGEON_DIFFICULTY.VETERAN); dungeon.GenerateDungeon(); dungeons.Add(dungeon); return(dungeon); } }
namespace E01_SumOf_3_Numbers { using System; public class SumOf_3_Numbers { public static void Main(string[] args) { // Write a program that reads 3 real numbers from the // console and prints their sum. // Examples: // // a b c sum // 3 4 11 18 // -2 0 3 1 // 5.5 4.5 20.1 30.1 Console.Write("Please, enter value for -> a = "); double a = double.Parse(Console.ReadLine()); Console.Write("Please, enter value for -> b = "); double b = double.Parse(Console.ReadLine()); Console.Write("Please, enter value for -> c = "); double c = double.Parse(Console.ReadLine()); double sum = a + b + c; Console.WriteLine("The sum of the numbers is : sum = {0}", sum); Console.WriteLine(); } } }
using gufi.webAPI.Contexts; using gufi.webAPI.Domains; using gufi.webAPI.Interfaces; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace gufi.webAPI.Repositories { public class TipoUsuarioRepository : ITipoUsuarioRepository { GUFIContext ctx = new GUFIContext(); public void Atualizar(int id, TipoUsuario novoTipoUsuario) { TipoUsuario tipoUsuarioBuscado = BuscarPorId(id); if (tipoUsuarioBuscado != null) { tipoUsuarioBuscado.TituloTipoUsuario = novoTipoUsuario.TituloTipoUsuario; } ctx.TipoUsuarios.Update(tipoUsuarioBuscado); ctx.SaveChanges(); } public TipoUsuario BuscarPorId(int id) { return ctx.TipoUsuarios.FirstOrDefault(t => t.IdTipoUsuario == id); } public void Cadastrar(TipoUsuario tipoUsuario) { ctx.TipoUsuarios.Add(tipoUsuario); ctx.SaveChanges(); } public void Deletar(int id) { TipoUsuario tipoUsuarioBuscado = BuscarPorId(id); if (tipoUsuarioBuscado != null) { ctx.TipoUsuarios.Remove(tipoUsuarioBuscado); ctx.SaveChanges(); } } public List<TipoUsuario> ListarTodos() { return ctx.TipoUsuarios.Include(x => x.Usuarios).ToList(); } } }
using JIoffe.PizzaBot.Model; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Schema; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace PizzaBot.Dialogs.Prompts { //Out of the box, Microsoft.Bot.Builder.Dialogs provides a number of useful prompts including: // -Freeform text // -Yes/No Confirmation // -Multiple Choice // -Date/Time // etc. //However, sometimes you need your own prompt. This is an example of a prompt that specifically //asks the user for a pizza size. This allows it to be decoupled from a particular dialog public class PizzaSizePrompt : Prompt<PizzaSize> { public PizzaSizePrompt(string dialogId, PromptValidator<PizzaSize> validator = null) : base(dialogId, validator) { } protected override async Task OnPromptAsync(ITurnContext turnContext, IDictionary<string, object> state, PromptOptions options, bool isRetry, CancellationToken cancellationToken = default(CancellationToken)) { //Add "suggested actions" which will appear as buttons specific to this point in the conversation var prompt = options?.Prompt ?? MessageFactory.Text(Responses.Orders.SizePrompt); //isRetry is true if this is a a retry attempt if (isRetry && options?.RetryPrompt != null) { prompt = options.RetryPrompt; } //Suggested Actions appear as buttons in most channels. These are specific to a single point in //a conversation and will NOT persist after clicked. Good for answering immediate questions prompt.SuggestedActions = new SuggestedActions() { Actions = new[] { new CardAction() { Title = "Small", Type = ActionTypes.ImBack, Value = "Small" }, new CardAction() { Title = "Medium", Type = ActionTypes.ImBack, Value = "Medium" }, new CardAction() { Title = "Large", Type = ActionTypes.ImBack, Value = "Large" }, } }; await turnContext.SendActivityAsync(prompt); } protected override Task<PromptRecognizerResult<PizzaSize>> OnRecognizeAsync(ITurnContext turnContext, IDictionary<string, object> state, PromptOptions options, CancellationToken cancellationToken = default(CancellationToken)) { var input = turnContext.Activity.Value as string ?? turnContext.Activity.Text; PizzaSize size = 0; var success = Enum.TryParse(input, true, out size); //If "succeeded" is false, control will not go to the next step and will instead //return to OnPromptAsync var result = new PromptRecognizerResult<PizzaSize>() { Succeeded = success, Value = size }; return Task.FromResult(result); } } }
using ReturnOfThePioneers.MasterData; namespace ReturnOfThePioneers.Cards { public class FamilyCardDetail : FamilyCard { public Card CardBase { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using CTCT.Util; namespace CTCT.Components.EventSpot { /// <summary> /// EventSpot Item Attribute /// </summary> [DataContract] [Serializable] public class Attribute : Component { /// <summary> /// The attribute's unique ID /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Name of attribute being sold /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Number of item attributes that are still available for sale /// </summary> [DataMember(Name = "quantity_available", EmitDefaultValue = true)] public int QuantityAvailable { get; set; } /// <summary> /// Number of attributes offered for sale /// </summary> [DataMember(Name = "quantity_total", EmitDefaultValue = true)] public int QuantityTotal { get; set; } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_UILineInfo : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { UILineInfo uILineInfo = default(UILineInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, uILineInfo); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_startCharIdx(IntPtr l) { int result; try { UILineInfo uILineInfo; LuaObject.checkValueType<UILineInfo>(l, 1, out uILineInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, uILineInfo.startCharIdx); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_startCharIdx(IntPtr l) { int result; try { UILineInfo uILineInfo; LuaObject.checkValueType<UILineInfo>(l, 1, out uILineInfo); int startCharIdx; LuaObject.checkType(l, 2, out startCharIdx); uILineInfo.startCharIdx = startCharIdx; LuaObject.setBack(l, uILineInfo); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_height(IntPtr l) { int result; try { UILineInfo uILineInfo; LuaObject.checkValueType<UILineInfo>(l, 1, out uILineInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, uILineInfo.height); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_height(IntPtr l) { int result; try { UILineInfo uILineInfo; LuaObject.checkValueType<UILineInfo>(l, 1, out uILineInfo); int height; LuaObject.checkType(l, 2, out height); uILineInfo.height = height; LuaObject.setBack(l, uILineInfo); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.UILineInfo"); LuaObject.addMember(l, "startCharIdx", new LuaCSFunction(Lua_UnityEngine_UILineInfo.get_startCharIdx), new LuaCSFunction(Lua_UnityEngine_UILineInfo.set_startCharIdx), true); LuaObject.addMember(l, "height", new LuaCSFunction(Lua_UnityEngine_UILineInfo.get_height), new LuaCSFunction(Lua_UnityEngine_UILineInfo.set_height), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_UILineInfo.constructor), typeof(UILineInfo), typeof(ValueType)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class UpdatePokemonInformationCanvas : MonoBehaviour { public GameObject pokemonName, type, hp, attack, specialAttack, defense, specialDefense, velocity; public Image panel; public Image[] attacksImage; public TextMeshProUGUI[] attacksName; private Camera cam; private void OnEnable() { //Con el nombre del pokemon padre coger de recursos el scriptable object del pokemon string father = GetComponentInParent<BoxCollider>().gameObject.name; Pokemon[] pokemons = GameManager.instance.player.GetComponent<Player>().pokemons; Pokemon SelectedPokemon = new Pokemon(); foreach (var item in pokemons) { if(item.name.Equals(father)){ SelectedPokemon = item; break; } } cam = Camera.main; GetComponent<Canvas>().worldCamera = cam; panel.color = SelectedPokemon.typeColor; pokemonName.GetComponent<TextMeshProUGUI>().text = SelectedPokemon.name; type.GetComponent<Image>().sprite = SelectedPokemon.typeSprite; hp.GetComponent<TextMeshProUGUI>().text = "HP - " + SelectedPokemon.hp; attack.GetComponent<TextMeshProUGUI>().text = "ATTACK - " + SelectedPokemon.attack; specialAttack.GetComponent<TextMeshProUGUI>().text = "SPECIAL ATTACK - " + SelectedPokemon.specialAttack; defense.GetComponent<TextMeshProUGUI>().text = "DEFENSE - " + SelectedPokemon.defense; specialDefense.GetComponent<TextMeshProUGUI>().text = "SPECIAL DEFENSE - " + SelectedPokemon.specialDefense; velocity.GetComponent<TextMeshProUGUI>().text = "VELOCITY - " + SelectedPokemon.velocity; for (int i = 0; i < attacksImage.Length; i++) { attacksImage[i].sprite = SelectedPokemon.m_attacks[i].typeSprite; attacksName[i].text = SelectedPokemon.m_attacks[i].name; } } private void LateUpdate() { transform.LookAt(cam.transform.position, Vector2.up); } }
using System.Collections; using System; using System.Collections.Generic; using UnityEngine; using Zenject; public class BossFigthController : MonoBehaviour { private ViewWeaponCount _weaponCount; private Weapon _weapon = new Weapon(); [SerializeField] private GameObject _panelWin; [SerializeField] private GameObject _panelLose; [SerializeField] private GameObject _attackPanel; private void Awake() { _weaponCount = GetComponent<ViewWeaponCount>(); } private void Start() { _weaponCount.YouWin += EndFight; _weaponCount.StartFight += StartFight; } public void Damage1() { _weaponCount.Punch(_weapon.Damage1); } public void Damage2() { _weaponCount.Punch(_weapon.Damage2); } public void Damage3() { _weaponCount.Punch(_weapon.Damage3); } public void Damage4() { _weaponCount.Punch(_weapon.Damage4); } public void Damage5() { _weaponCount.Punch(_weapon.Damage5); } public void Damage6() { _weaponCount.Punch(_weapon.Damage6); } public void Damage7() { _weaponCount.Punch(_weapon.Damage7); } public void Damage8() { _weaponCount.Punch(_weapon.Damage8); } public void Damage9() { _weaponCount.Punch(_weapon.Damage9); } public void StartFight() { StartCoroutine(Fight()); } IEnumerator Fight() { yield return new WaitForSecondsRealtime(60); _panelLose.SetActive(true); _attackPanel.SetActive(false); } private void EndFight() { _panelWin.SetActive(true); _attackPanel.SetActive(false); } }
#region License //=================================================================================== //Copyright 2010 HexaSystems Corporation //=================================================================================== //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //=================================================================================== //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //=================================================================================== #endregion using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Globalization; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks; namespace Hexa.xText.MSBuildTasks { /// <summary> /// /// </summary> public sealed class PO2Assembly : Task { #region Properties /// <summary> /// Gets or sets the PO path. /// </summary> /// <value>The PO path.</value> public ITaskItem[] POFiles { get; set; } /// <summary> /// Gets or sets the output path. /// </summary> /// <value>The output path.</value> public string OutputPath { get; set; } /// <summary> /// Gets or sets the gettext assembly path. /// </summary> /// <value>The gettext path.</value> public string GNUGetTextAssemblyPath { get; set; } /// <summary> /// Gets or sets the name of the assembly without the extension. /// </summary> /// <value>The name of the assembly.</value> public string AssemblyName { get; set; } #endregion Properties #region Methods /// <summary> /// Executes a task. /// </summary> /// <returns> /// true if the task executed successfully; otherwise, false. /// </returns> public override bool Execute() { if (POFiles != null) { foreach (ITaskItem item in POFiles) { // Verify that POFile exists. if (!File.Exists(item.ItemSpec)) { _LogMessage(string.Format(CultureInfo.InvariantCulture, "File {0} does not exists.", item.ItemSpec)); return false; } // Get file info from file. FileInfo fileInfo = new FileInfo(item.ItemSpec); // Assume that FileName is in the format: locale.extension // Get locale from FileName. string locale = fileInfo.Name.Replace(fileInfo.Extension, string.Empty); string outputPath = OutputPath + "\\" + locale; // If OutputPath directory does not exist, create it. if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath); // Create the output assembly name. string assemblyFileName = Path.Combine(outputPath, AssemblyName + ".resources.dll"); // Verify if assemblyFile exists if (File.Exists(assemblyFileName)) { //FileInfo dllInfo = new FileInfo(assemblyFileName); //if (dllInfo.LastWriteTime.CompareTo(fileInfo.LastWriteTime) > 0) // continue; // Continue to next item cause Assembly is newer than current po file. //else File.Delete(assemblyFileName); } //Get the temporary path to store the C# classes. string csOutputPath = System.IO.Path.GetTempPath(); // Get the C# file template from embedded resources. string template = Resource.template; // Get the file name for the C# class string csFileName = Path.Combine(csOutputPath, string.Format(CultureInfo.InvariantCulture, "{0}.{1}", AssemblyName, "cs")); // Get the class name for the C# class string className = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", ConstructClassName(AssemblyName), locale.Replace("-", "_")); // String builder to hold the key value pairs retrieved from the po file. StringBuilder s = new StringBuilder(); using (FileStream fileStream = new FileStream(item.ItemSpec, FileMode.Open)) { // Read the po file. _ReadPOFile(s, new StreamReader(fileStream, Encoding.UTF8)); } // Get bytes for the new C# class byte[] bytes = Encoding.UTF8.GetBytes(template.Replace("{0}", className).Replace("{1}", s.ToString())); // Write the C# class to disk. using (FileStream csStream = new FileStream(csFileName, FileMode.Create)) { csStream.Write(bytes, 0, bytes.Length); } _LogMessage(string.Format(CultureInfo.InvariantCulture, "Created file {0}", csFileName)); // Log if GNU.Gettext.dll not found. if (!File.Exists(GNUGetTextAssemblyPath)) { _LogMessage(string.Format(CultureInfo.InvariantCulture, "Unable to find dependency file: {0}", GNUGetTextAssemblyPath)); return false; } var fileinfo = new FileInfo(GNUGetTextAssemblyPath); // Compile c# class. Csc csc = new Csc(); csc.HostObject = this.HostObject; csc.BuildEngine = this.BuildEngine; csc.AdditionalLibPaths = new string[] { fileinfo.Directory.FullName }; csc.TargetType = "library"; csc.References = new TaskItem[] { new TaskItem(fileinfo.Name) }; csc.OutputAssembly = new TaskItem(assemblyFileName); csc.Sources = new TaskItem[] { new TaskItem(csFileName) }; csc.Execute(); _LogMessage(string.Format(CultureInfo.InvariantCulture, "Created assembly {0}", assemblyFileName)); } return true; } return true; } /// <summary> /// Reads a file stream and fills the string builder s. /// </summary> /// <param name="s">The s.</param> /// <param name="fileStream">The file stream.</param> private static void _ReadPOFile(StringBuilder s, StreamReader fileStream) { var file = fileStream.ReadToEnd(); Regex exp = new Regex(@"/*msgid\s*\x22(?<text>(.|[\r\n])*?)\x22"); List<string> msgids = exp.Matches(file) .Cast<Match>() .Select(m => m.Groups["text"].Value) .ToList(); exp = new Regex(@"/*msgstr\s*\x22(?<text>(.|[\r\n])*?)\x22"); List<string> msgstrs = exp.Matches(file) .Cast<Match>() .Select(m => m.Groups["text"].Value) .ToList(); for (int idx = 0; idx < msgids.Count(); idx++) { if (!string.IsNullOrEmpty(msgids[idx]) && !string.IsNullOrEmpty(msgstrs[idx])) s.Append(string.Format(CultureInfo.InvariantCulture, "t.Add(\"{0}\",\"{1}\");", msgids[idx], msgstrs[idx])).Append("\n"); } } /// <summary> /// Logs the message. /// </summary> /// <param name="message">The message.</param> private void _LogMessage(string message) { if (!System.Diagnostics.Debugger.IsAttached) { BuildMessageEventArgs args = new BuildMessageEventArgs(message, string.Empty, "PO2Assembly", MessageImportance.Normal); BuildEngine.LogMessageEvent(args); } } /// <summary> /// Converts a resource name to a class name. /// </summary> /// <returns>a nonempty string consisting of alphanumerics and underscores /// and starting with a letter or underscore</returns> private static String ConstructClassName(String resourceName) { // We could just return an arbitrary fixed class name, like "Messages", // assuming that every assembly will only ever contain one // GettextResourceSet subclass, but this assumption would break the day // we want to support multi-domain PO files in the same format... bool valid = (resourceName.Length > 0); for (int i = 0; valid && i < resourceName.Length; i++) { char c = resourceName[i]; if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_') || (i > 0 && c >= '0' && c <= '9'))) valid = false; } if (valid) return resourceName; else { // Use hexadecimal escapes, using the underscore as escape character. String hexdigit = "0123456789abcdef"; StringBuilder b = new StringBuilder(); b.Append("__UESCAPED__"); for (int i = 0; i < resourceName.Length; i++) { char c = resourceName[i]; if (c >= 0xd800 && c < 0xdc00 && i + 1 < resourceName.Length && resourceName[i + 1] >= 0xdc00 && resourceName[i + 1] < 0xe000) { // Combine two UTF-16 words to a character. char c2 = resourceName[i + 1]; int uc = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); b.Append('_'); b.Append('U'); b.Append(hexdigit[(uc >> 28) & 0x0f]); b.Append(hexdigit[(uc >> 24) & 0x0f]); b.Append(hexdigit[(uc >> 20) & 0x0f]); b.Append(hexdigit[(uc >> 16) & 0x0f]); b.Append(hexdigit[(uc >> 12) & 0x0f]); b.Append(hexdigit[(uc >> 8) & 0x0f]); b.Append(hexdigit[(uc >> 4) & 0x0f]); b.Append(hexdigit[uc & 0x0f]); i++; } else if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) { int uc = c; b.Append('_'); b.Append('u'); b.Append(hexdigit[(uc >> 12) & 0x0f]); b.Append(hexdigit[(uc >> 8) & 0x0f]); b.Append(hexdigit[(uc >> 4) & 0x0f]); b.Append(hexdigit[uc & 0x0f]); } else b.Append(c); } return b.ToString(); } } #endregion } }
using System; using System.Data; using System.Collections.Generic; using System.Text; using Npgsql; using NpgsqlTypes; using QTHT.DataAccess; namespace QTHT.BusinesLogic { /// <summary> /// Mô tả thông tin cho bảng ChucVu /// Cung cấp các hàm xử lý, thao tác với bảng ChucVu /// Người tạo (C): /// Ngày khởi tạo: 14/10/2014 /// </summary> public class chucvuBL { private chucvu objchucvuDA = new chucvu(); public chucvuBL() { objchucvuDA = new chucvu(); } #region Public Method /// <summary> /// Lấy toàn bộ dữ liệu từ bảng ChucVu /// </summary> /// <returns>DataTable</returns> public DataTable GetAll() { return objchucvuDA.GetAll(); } /// <summary> /// Hàm lấy ChucVu theo mã /// </summary> /// <returns>Trả về objChucVu </returns> public chucvu GetByID(int intIDChucVu) { return objchucvuDA.GetByID(intIDChucVu); } /// <summary> /// Thêm mới dữ liệu vào bảng: ChucVu /// </summary> /// <param name="obj">objChucVu</param> /// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns> public string Insert(chucvu objchucvu) { return objchucvuDA.Insert(objchucvu); } /// <summary> /// Cập nhật dữ liệu vào bảng: ChucVu /// </summary> /// <param name="obj">objChucVu</param> /// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns> public string Update(chucvu objchucvu) { return objchucvuDA.Update(objchucvu); } /// <summary> /// Xóa dữ liệu từ bảng ChucVu /// </summary> /// <returns>Trả về trắng: xóa thành công; Trả về khác trắng: xóa không thành công</returns> public string Delete(int intIDChucVu) { return objchucvuDA.Delete(intIDChucVu); } /// <summary> /// Hàm kiểm tra trùng tên chức vụ /// </summary> /// <param name="sid">Mã chức vụ</param> /// <param name="sten">Tên chức vụ</param> /// <returns>bool: False-Không tồn tại;True-Có tồn tại</returns> public bool CheckExit(int iidchucvu, string stenchucvu) { return objchucvuDA.CheckExit(iidchucvu, stenchucvu); } #endregion } }
using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using VehicleManagement.Domain.Entities; namespace VehicleManagement.Application.Common.Interfaces { public interface IApplicationDbContext { DbSet<Announcement> Announcements { get; set; } DbSet<Brand> Brands { get; set; } DbSet<Model> Models { get; set; } DbSet<Vehicle> Vehicles { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CommonLib.Core.Utility { public class DailySequence { private static DailySequence _instance = new DailySequence(); private long _dailyTimer = -1; private int _sequence = 0; private String _savedFile; private DailySequence() { _savedFile = Path.Combine(FileLogger.Logger.LogPath, "DailySequence.txt"); try { if (File.Exists(_savedFile)) { var data = File.ReadAllLines(_savedFile); long.TryParse(data[0], out _dailyTimer); int.TryParse(data[1], out _sequence); } } catch(Exception ex) { FileLogger.Logger.Error(ex); } } public static int NextSequenceNo { get { lock(_instance) { _instance.adjustSequence(); } return _instance._sequence; } } private void adjustSequence() { if(_dailyTimer<DateTime.Now.Ticks) { _dailyTimer = DateTime.Today.AddDays(1).Ticks; _sequence = 0; } _sequence++; try { File.WriteAllText(_savedFile, String.Concat(_dailyTimer, "\r\n", _sequence)); } catch(Exception ex) { FileLogger.Logger.Error(ex); } } } }
using System; namespace _2.WildFarm.Models { public class Tiger : Felime { public Tiger(string animalName, double weight, string livingRegion) : base(animalName, weight, livingRegion) { } public override void MakeSound() { Console.WriteLine("ROAAR!!!"); } public override void Eat(Food food) { if (food.GetType().Name != "Meat") { Console.WriteLine("Tigers are not eating that type of food!"); } else { this.FoodEaten += food.Quantity; } } } }
using System.Diagnostics.CodeAnalysis; using System.IO; namespace PhysicalCache.Items { public class CacheItem : ICacheItem { public string Key { get; set; } [MaybeNull] public FileInfo File { get; set; } = null; [MaybeNull] public byte[] RawBytes { get; set; } = null; private CacheItem() { } private CacheItem(string key) => Key = key; public CacheItem(string key, [NotNull]FileInfo file) : this(key) => File = file; public CacheItem(string key, [NotNull]byte[] rawFileBytes) : this(key) => RawBytes = rawFileBytes; } }
 using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Dynamic; using System.Text; using System.Threading.Tasks; using Abp; using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.AutoMapper; using Abp.Configuration; using Abp.Domain.Repositories; using Abp.Extensions; using Abp.Linq.Extensions; using Eur.Abp.Elbe; using MyCompanyName.AbpZeroTemplate.Authorization; using MyCompanyName.AbpZeroTemplate.Authorization.Users; using MyCompanyName.AbpZeroTemplate.Card.Dtos; using MyCompanyName.AbpZeroTemplate.Dto; namespace MyCompanyName.AbpZeroTemplate.Card { /// <summary> /// 财务明细服务实现 /// </summary> [AbpAuthorize(AppPermissions.FinancialDetails)] public class FinancialDetailsAppService : AbpZeroTemplateAppServiceBase, IFinancialDetailsAppService { private readonly IRepository<FinancialDetails, long> _financialDetailsRepository; private readonly IRepository<User, long> _userRepository; private readonly IFinancialDetailsListExcelExporter _financialDetailsListExcelExporter; /// <summary> /// 构造方法 /// </summary> public FinancialDetailsAppService( IRepository<FinancialDetails, long> financialDetailsRepository , IFinancialDetailsListExcelExporter financialDetailsListExcelExporter , IRepository<User, long> userRepository ) { _financialDetailsRepository = financialDetailsRepository; _financialDetailsListExcelExporter = financialDetailsListExcelExporter; _userRepository = userRepository; } #region 实体的自定义扩展方法 private IQueryable<FinancialDetails> _financialDetailsRepositoryAsNoTrack => _financialDetailsRepository.GetAll().AsNoTracking(); #endregion #region 财务明细管理 /// <summary> /// 根据查询条件获取财务明细分页列表 /// </summary> public async Task<PagedResultDto<FinancialDetailsListDto>> GetPagedFinancialDetailssAsync(GetFinancialDetailsInput input) { var query = _financialDetailsRepositoryAsNoTrack.Include(m => m.User); //TODO:根据传入的参数添加过滤条件 var financialDetailsCount = await query.CountAsync(); //var financialDetailss = await query // .LeftJoin(_userRepository.GetAll(), m => m.CreatorUserId, c => c.Id, (m, c) => new FinancialDetailsListDto // { // CreationTime = m.CreationTime, // Mark = m.Mark, // Desc = m.Desc, // Money = m.Money, // NowMoney = m.NowMoney, // PayType = m.PayType, // Type = m.Type, // // UserUserName = m.User.UserName, // OperUserName = c.UserName // }) //.OrderBy(input.Sorting) //.PageBy(input) //.ToListAsync(); var financialDetailss = await query .OrderBy(input.Sorting) .PageBy(input) .ToListAsync(); var financialDetailsListDtos = financialDetailss.MapTo<List<FinancialDetailsListDto>>(); return new PagedResultDto<FinancialDetailsListDto>( financialDetailsCount, financialDetailsListDtos ); } /// <summary> /// 通过Id获取财务明细信息进行编辑或修改 /// </summary> public async Task<GetFinancialDetailsForEditOutput> GetFinancialDetailsForEditAsync(NullableIdDto<long> input) { var output = new GetFinancialDetailsForEditOutput(); FinancialDetailsEditDto financialDetailsEditDto; if (input.Id.HasValue) { var entity = await _financialDetailsRepository.GetAsync(input.Id.Value); financialDetailsEditDto = entity.MapTo<FinancialDetailsEditDto>(); } else { financialDetailsEditDto = new FinancialDetailsEditDto(); } output.FinancialDetails = financialDetailsEditDto; return output; } /// <summary> /// 通过指定id获取财务明细ListDto信息 /// </summary> public async Task<FinancialDetailsListDto> GetFinancialDetailsByIdAsync(EntityDto<long> input) { var entity = await _financialDetailsRepository.GetAsync(input.Id); return entity.MapTo<FinancialDetailsListDto>(); } #endregion #region 财务明细的Excel导出功能 public async Task<FileDto> GetFinancialDetailsToExcel() { var entities = await _financialDetailsRepository.GetAll().ToListAsync(); var dtos = entities.MapTo<List<FinancialDetailsListDto>>(); var fileDto = _financialDetailsListExcelExporter.ExportFinancialDetailsToFile(dtos); return fileDto; } #endregion } }
using System; using Microsoft.Extensions.Logging; using SharpDL; using SharpDL.Graphics; namespace Example2_DrawTexture { public class MainGame : IGame { private readonly ILogger<MainGame> logger; private readonly IGameEngine engine; private IWindow window; private IRenderer renderer; private Texture textureGitLogo; private Texture textureVisualStudioLogo; private Texture textureYboc; public MainGame( IGameEngine engine, ILogger<MainGame> logger = null) { this.engine = engine; this.logger = logger; engine.Initialize = () => Initialize(); engine.LoadContent = () => LoadContent(); engine.Update = (gameTime) => Update(gameTime); engine.Draw = (gameTime) => Draw(gameTime); engine.UnloadContent = () => UnloadContent(); } public void Run() { engine.Start(GameEngineInitializeType.Everything); } /// <summary>Initialize SDL and any sub-systems. Window and Renderer must be initialized before use. /// </summary> private void Initialize() { window = engine.WindowFactory.CreateWindow("Example 2 - Draw Texture"); renderer = engine.RendererFactory.CreateRenderer(window); renderer.SetRenderLogicalSize(1280, 720); } /// <summary>Load any game assets such as textures and audio. /// </summary> private void LoadContent() { // Creates an in memory SDL Surface from the PNG at the passed path Surface surfaceGitLogo = new Surface("Content/logo_git.png", SurfaceType.PNG); Surface surfaceVisualStudioLogo = new Surface("Content/logo_vs_2019.png", SurfaceType.PNG); Surface surfaceYboc = new Surface("Content/logo_yboc.png", SurfaceType.PNG); // Creates a GPU-driven SDL texture using the initialized renderer and created surface textureGitLogo = new Texture(renderer, surfaceGitLogo); textureVisualStudioLogo = new Texture(renderer, surfaceVisualStudioLogo); textureYboc = new Texture(renderer, surfaceYboc); } /// <summary>Update the state of the game. /// </summary> /// <param name="gameTime"></param> private void Update(GameTime gameTime) { } /// <summary>Render the current state of the game. /// </summary> /// <param name="gameTime"></param> private void Draw(GameTime gameTime) { // Clear the screen on each iteration so that we don't get stale renders renderer.ClearScreen(); // Draw the Git logo at (0,0) and -45 degree angle rotated around the center (calculated Vector) textureGitLogo.Draw(0, 0, -45, new Vector(textureGitLogo.Width / 2, textureGitLogo.Height / 2)); // Draw the Git logo at (300,300) and 45 degree angle rotated around the center (calculated Vector) textureGitLogo.Draw(300, 300, 45, new Vector(textureGitLogo.Width / 2, textureGitLogo.Height / 2)); // Draw the Visual Studio logo at (700, 400) with no rotation textureVisualStudioLogo.Draw(700, 400); // Draw the YBOC logo at (900, 900) cropped to a 50x50 rectangle with (0,0) being the starting point textureYboc.Draw(800, 600, new Rectangle(0, 0, 50, 50)); // Update the rendered state of the screen renderer.RenderPresent(); } /// <summary>Unload and dispose of any assets. Remember to dispose SDL-native objects! /// </summary> private void UnloadContent() { textureGitLogo.Dispose(); textureVisualStudioLogo.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace ImageRenderManagerService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together. public class ImageRenderManager : IImageRenderManager { public void RenderImageVolume(MprGenerationContracts.MprGenerationRequestV1 request) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Resources; using System.Windows; using System.Windows.Controls; using System.Windows.Markup; /// <summary> /// Windows presentation foundation translator namespace /// </summary> namespace WPFTranslator { /// <summary> /// Translator class /// </summary> public static class Translator { /// <summary> /// Language resource manager /// </summary> private static ResourceManager languageResourceManager; /// <summary> /// Fallback language resource manager /// </summary> private static ResourceManager fallbackLanguageResourceManager; /// <summary> /// Translator interface /// </summary> private static ITranslatorInterface translatorInterface; /// <summary> /// Translator interface /// </summary> public static ITranslatorInterface TranslatorInterface { get { return translatorInterface; } set { if (value != null) { translatorInterface = value; } } } /// <summary> /// Initialize language /// </summary> public static void InitLanguage() { if (translatorInterface != null) { if (languageResourceManager == null) { try { Assembly a = Assembly.Load(translatorInterface.AssemblyName); languageResourceManager = new ResourceManager(translatorInterface.AssemblyName + ".Languages." + translatorInterface.Language, a); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } if (fallbackLanguageResourceManager == null) { try { Assembly a = Assembly.Load(translatorInterface.AssemblyName); fallbackLanguageResourceManager = new ResourceManager(translatorInterface.AssemblyName + ".Languages." + translatorInterface.FallbackLanguage, a); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } } } /// <summary> /// Try translatie /// </summary> /// <param name="input">Input</param> /// <param name="output">Output</param> /// <returns>Success</returns> public static bool TryTranslate(string input, out string output) { bool ret = false; output = input; if (input.StartsWith("{$") && input.EndsWith("$}") && (input.Length > 4)) { output = GetTranslation(input.Substring(2, input.Length - 4)); ret = (input != output); } return ret; } /// <summary> /// Load language /// </summary> /// <param name="parent">Parent UI element</param> private static void LoadLanguage(UIElement parent) { try { string translated = ""; InitLanguage(); IEnumerable<UIElement> ui_elements = GetSelfAndChildrenRecursive(parent); foreach (UIElement ui_element in ui_elements) { if (ui_element is ContentControl) { ContentControl content_control = (ContentControl)ui_element; if (content_control.HasContent) { if (content_control.Content is string) { if (TryTranslate((string)(content_control.Content), out translated)) { content_control.Content = translated; } } else if (content_control.Content is ITranslatable) { ITranslatable translatable = (ITranslatable)(content_control.Content); if (TryTranslate(translatable.TranslatableText, out translated)) { translatable.TranslatableText = translated; } } } } if (ui_element is ItemsControl) { ItemsControl item_control = (ItemsControl)ui_element; if (item_control.Items != null) { for (int i = 0, count = item_control.Items.Count; i < count; i++) { object item = item_control.Items[i]; if (item is string) { if (TryTranslate((string)item, out translated)) { item_control.Items[i] = translated; } } else if (item is ITranslatable) { ITranslatable translatable = (ITranslatable)item; if (TryTranslate(translatable.TranslatableText, out translated)) { translatable.TranslatableText = translated; } } } } } } } catch (Exception e) { Console.Error.WriteLine(e.Message); } } /// <summary> /// Get translation /// </summary> /// <param name="key">Key</param> /// <returns>Value</returns> public static string GetTranslation(string key) { string ret = null; if (languageResourceManager != null) { try { ret = languageResourceManager.GetString(key); } catch (Exception e) { Console.Error.WriteLine(e.Message); } if (ret == null) { if (fallbackLanguageResourceManager != null) { try { ret = fallbackLanguageResourceManager.GetString(key); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } } } else if (fallbackLanguageResourceManager != null) { try { ret = fallbackLanguageResourceManager.GetString(key); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } if (ret == null) { ret = "{$" + key + "$}"; } return ret; } /// <summary> /// Change language /// </summary> /// <param name="language">Language</param> /// <returns>Success</returns> public static bool ChangeLanguage(Language language) { bool ret = false; if (translatorInterface.Language != language.Culture) { translatorInterface.Language = language.Culture; translatorInterface.SaveSettings(); ret = true; } return ret; } /// <summary> /// Load translation /// </summary> /// <param name="parent">Parent UI element</param> public static void LoadTranslation(UIElement parent) { if (translatorInterface != null) { LoadLanguage(parent); } } /// <summary> /// Get self and children recursive /// </summary> /// <param name="parent">Parent UI element</param> /// <returns>All children recursive</returns> public static IEnumerable<UIElement> GetSelfAndChildrenRecursive(UIElement parent) { List<UIElement> ret = new List<UIElement>(); if (parent != null) { if (parent is ItemsControl) { ItemsControl items_control = (ItemsControl)parent; if (items_control.Items != null) { foreach (object child in items_control.Items) { if (child is UIElement) { ret.AddRange(GetSelfAndChildrenRecursive((UIElement)child)); } } } } if (parent is Panel) { Panel panel = (Panel)parent; foreach (UIElement child in panel.Children) { ret.AddRange(GetSelfAndChildrenRecursive(child)); } } ret.Add(parent); } return ret; } /// <summary> /// Enumerator to combo box /// </summary> /// <typeparam name="T">Enumerator type</typeparam> /// <param name="comboBox">Combo box</param> public static void EnumToComboBox<T>(ComboBox comboBox) { EnumToComboBox<T>(comboBox, null); } /// <summary> /// Enumerator to combo box /// </summary> /// <typeparam name="T">Enumerator type</typeparam> /// <param name="comboBox">Combo box</param> /// <param name="exclusions">Exclusions</param> public static void EnumToComboBox<T>(ComboBox comboBox, T[] exclusions) { comboBox.Items.Clear(); Array arr = Enum.GetValues(typeof(T)); foreach (var e in arr) { bool s = true; if (exclusions != null) { foreach (var ex in exclusions) { if (ex.Equals(e)) { s = false; break; } } } if (s) { comboBox.Items.Add(e); } } } /// <summary> /// Enumerable to combo box /// </summary> /// <typeparam name="T">Type to enumerate</typeparam> /// <param name="comboBox">Combo box</param> /// <param name="items">Items</param> public static void EnumerableToComboBox<T>(ComboBox comboBox, IEnumerable<T> items) { comboBox.Items.Clear(); foreach (var item in items) { comboBox.Items.Add(item); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Table; using System.Configuration; namespace ModernWeb.Handlers { public class GetReaderDataGridData : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write(retrieveData(context.Request.Form["id"])); } private string retrieveData(string id) { string tempData = "{ \"result\" : ["; switch (id) { case "10": tempData += "{\"id\": " + "0" + ", \"col1\": \"Lorem Epsum Lorem Epsum \", \"col2\": \"Lorem Epsum, Lorem Epsum \", \"col3\": \"01/12/2013 12:01 AM\", \"col4\": \"Lorem Epsum Lorem Epsum \", \"col5\": \"Lorem Epsum \", \"col6\": \"Active\", \"col7\": \"$56,000.00\", \"isDefault\": \"true\"} "; for (int i = 1; i < 40; i++) { tempData += ",{\"id\": " + i.ToString() + ", \"col1\": \"Lorem Epsum Lorem Epsum \", \"col2\": \"Lorem Epsum, Lorem Epsum \", \"col3\": \"01/12/2013 12:01 AM\", \"col4\": \"Lorem Epsum Lorem Epsum \", \"col5\": \"Lorem Epsum \", \"col6\": \"Active\", \"col7\": \"$56,000.00\"} "; } break; default: tempData += "{\"id\": " + "0" + ", \"col1\": \"Lorem Epsum Lorem Epsum \", \"col2\": \"Lorem Epsum, Lorem Epsum \", \"col3\": \"01/12/2013 12:01 AM\", \"col4\": \"Lorem Epsum Lorem Epsum \", \"col5\": \"Lorem Epsum \", \"col6\": \"Active\", \"col7\": \"$56,000.00\", \"isDefault\": \"true\"} "; for (int i = 1; i < 40; i++) { tempData += ",{\"id\": " + i.ToString() + ", \"col1\": \"Lorem Epsum Lorem Epsum \", \"col2\": \"Lorem Epsum, Lorem Epsum \", \"col3\": \"01/12/2013 12:01 AM\", \"col4\": \"Lorem Epsum Lorem Epsum \", \"col5\": \"Lorem Epsum \", \"col6\": \"Active\", \"col7\": \"$56,000.00\"} "; } break; } tempData += "]}"; return tempData; } public bool IsReusable { get { return false; } } } }
/*********************** @ author:zlong @ Date:2015-01-17 @ Desc:物品界面层 * ********************/ using System; using System.Collections.Generic; using System.Linq; using System.Web; using DriveMgr; using DriveMgr.BLL; namespace DriveMgr.WebUI.GoodsMgr { /// <summary> /// bg_goodsHandler 的摘要说明 /// </summary> public class bg_goodsHandler : IHttpHandler { DriveMgr.Model.UserOperateLog userOperateLog = null; //操作日志对象 GoodsBLL goodsBll = new GoodsBLL(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = context.Request.Params["action"]; try { DriveMgr.Model.User userFromCookie = DriveMgr.Common.UserHelper.GetUser(context); //获取cookie里的用户对象 userOperateLog = new Model.UserOperateLog(); userOperateLog.UserIp = context.Request.UserHostAddress; userOperateLog.UserName = userFromCookie.UserId; switch (action) { case "search": SearchGoods(context); break; case "add": AddGoods(userFromCookie, context); break; case "getGoodsCategoryDT": GoodsCategoryBLL goodsCategoryBll = new GoodsCategoryBLL(); context.Response.Write(goodsCategoryBll.GetGoodsCategoryDT()); break; case "edit": EditGoods(userFromCookie, context); break; case "delete": DelGoods(userFromCookie, context); break; default: context.Response.Write("{\"msg\":\"参数错误!\",\"success\":false}"); break; } } catch (Exception ex) { context.Response.Write("{\"msg\":\"" + DriveMgr.Common.JsonHelper.StringFilter(ex.Message) + "\",\"success\":false}"); userOperateLog.OperateInfo = "用户功能异常"; userOperateLog.IfSuccess = false; userOperateLog.Description = DriveMgr.Common.JsonHelper.StringFilter(ex.Message); DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } } public bool IsReusable { get { return false; } } /// <summary> /// 查询物品 /// </summary> /// <param name="context"></param> private void SearchGoods(HttpContext context) { string sort = context.Request.Params["sort"]; //排序列 string order = context.Request.Params["order"]; //排序方式 asc或者desc int pageindex = int.Parse(context.Request.Params["page"]); int pagesize = int.Parse(context.Request.Params["rows"]); int totalCount; //输出参数 string strJson = goodsBll.GetPagerData(sort + " " + order, pagesize, pageindex, out totalCount); context.Response.Write("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}"); userOperateLog.OperateInfo = "查询物品"; userOperateLog.IfSuccess = true; userOperateLog.Description = "排序:" + sort + " " + order + " 页码/每页大小:" + pageindex + " " + pagesize; DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } /// <summary> /// 添加物品 /// </summary> /// <param name="userFromCookie"></param> /// <param name="context"></param> private void AddGoods(DriveMgr.Model.User userFromCookie, HttpContext context) { if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("goods", "add", userFromCookie.Id)) { string ui_goods_GoodsName_add = context.Request.Params["ui_goods_GoodsName_add"] ?? ""; int ui_goods_GoodsCategory_add = Int32.Parse(context.Request.Params["ui_goods_GoodsCategory_add"]); int ui_goods_MinQuantity_add = Int32.Parse(context.Request.Params["ui_goods_MinQuantity_add"]); int ui_goods_MaxQuantity_add = Int32.Parse(context.Request.Params["ui_goods_MaxQuantity_add"]); int ui_goods_RealQuantity_add = Int32.Parse(context.Request.Params["ui_goods_RealQuantity_add"]); string ui_goods_Specification_add = context.Request.Params["ui_goods_Specification_add"] ?? ""; string ui_goods_Remark_add = context.Request.Params["ui_goods_Remark_add"] ?? ""; DriveMgr.Model.GoodsModel goodsAdd = new Model.GoodsModel(); goodsAdd.GoodsName = ui_goods_GoodsName_add.Trim(); goodsAdd.GoodsCategoryID = ui_goods_GoodsCategory_add; goodsAdd.MinQuantity = ui_goods_MinQuantity_add; goodsAdd.MaxQuantity = ui_goods_MaxQuantity_add; goodsAdd.RealQuantity = ui_goods_RealQuantity_add; goodsAdd.Specification = ui_goods_Specification_add.Trim(); goodsAdd.Remark = ui_goods_Remark_add.Trim(); goodsAdd.CreateDate = DateTime.Now; goodsAdd.CreatePerson = userFromCookie.UserId; goodsAdd.UpdatePerson = userFromCookie.UserId; goodsAdd.UpdateDate = DateTime.Now; if (!goodsBll.IsExistGoods(goodsAdd.GoodsName)) { if (goodsBll.AddGoods(goodsAdd)) { userOperateLog.OperateInfo = "添加物品"; userOperateLog.IfSuccess = true; userOperateLog.Description = "添加成功,物品:" + ui_goods_GoodsName_add.Trim(); context.Response.Write("{\"msg\":\"添加成功!\",\"success\":true}"); } else { userOperateLog.OperateInfo = "添加物品"; userOperateLog.IfSuccess = false; userOperateLog.Description = "添加失败"; context.Response.Write("{\"msg\":\"添加失败!\",\"success\":false}"); } } else { context.Response.Write("{\"msg\":\"该物品已经存在!\",\"success\":true}"); } } else { userOperateLog.OperateInfo = "添加物品"; userOperateLog.IfSuccess = false; userOperateLog.Description = "无权限,请联系管理员"; context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}"); } DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } /// <summary> /// 编辑物品 /// </summary> /// <param name="userFromCookie"></param> /// <param name="context"></param> private void EditGoods(DriveMgr.Model.User userFromCookie, HttpContext context) { if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("goods", "edit", userFromCookie.Id)) { int id = Convert.ToInt32(context.Request.Params["id"]); DriveMgr.Model.GoodsModel goodsEdit = goodsBll.GetGoodsModel(id); string ui_goods_GoodsName_edit = context.Request.Params["ui_goods_GoodsName_edit"] ?? ""; int ui_goods_GoodsCategory_edit = Int32.Parse(context.Request.Params["ui_goods_GoodsCategory_edit"]); int ui_goods_MinQuantity_edit = Int32.Parse(context.Request.Params["ui_goods_MinQuantity_edit"]); int ui_goods_MaxQuantity_edit = Int32.Parse(context.Request.Params["ui_goods_MaxQuantity_edit"]); int ui_goods_RealQuantity_edit = Int32.Parse(context.Request.Params["ui_goods_RealQuantity_edit"]); string ui_goods_Specification_edit = context.Request.Params["ui_goods_Specification_edit"] ?? ""; string ui_goods_Remark_edit = context.Request.Params["ui_goods_Remark_edit"] ?? ""; goodsEdit.GoodsName = ui_goods_GoodsName_edit.Trim(); goodsEdit.GoodsCategoryID = ui_goods_GoodsCategory_edit; goodsEdit.MinQuantity = ui_goods_MinQuantity_edit; goodsEdit.MaxQuantity = ui_goods_MaxQuantity_edit; goodsEdit.RealQuantity = ui_goods_RealQuantity_edit; goodsEdit.Specification = ui_goods_Specification_edit.Trim(); goodsEdit.Remark = ui_goods_Remark_edit.Trim(); goodsEdit.UpdatePerson = userFromCookie.UserId; goodsEdit.UpdateDate = DateTime.Now; if (goodsBll.UpdateGoods(goodsEdit)) { userOperateLog.OperateInfo = "修改物品"; userOperateLog.IfSuccess = true; userOperateLog.Description = "修改成功,物品主键:" + goodsEdit.Id; context.Response.Write("{\"msg\":\"修改成功!\",\"success\":true}"); } else { userOperateLog.OperateInfo = "修改物品"; userOperateLog.IfSuccess = false; userOperateLog.Description = "修改失败"; context.Response.Write("{\"msg\":\"修改失败!\",\"success\":false}"); } } else { userOperateLog.OperateInfo = "修改物品"; userOperateLog.IfSuccess = false; userOperateLog.Description = "无权限,请联系管理员"; context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}"); } DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } /// <summary> /// 删除物品 /// </summary> /// <param name="userFromCookie"></param> /// <param name="context"></param> private void DelGoods(DriveMgr.Model.User userFromCookie, HttpContext context) { if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("goods", "delete", userFromCookie.Id)) { string ids = context.Request.Params["id"].Trim(','); if (goodsBll.DeleteGoodsList(ids)) { userOperateLog.OperateInfo = "删除物品"; userOperateLog.IfSuccess = true; userOperateLog.Description = "删除成功,物品主键:" + ids; context.Response.Write("{\"msg\":\"删除成功!\",\"success\":true}"); } else { userOperateLog.OperateInfo = "删除物品"; userOperateLog.IfSuccess = false; userOperateLog.Description = "删除失败"; context.Response.Write("{\"msg\":\"删除失败!\",\"success\":false}"); } } else { userOperateLog.OperateInfo = "删除物品"; userOperateLog.IfSuccess = false; userOperateLog.Description = "无权限,请联系管理员"; context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}"); } DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } } }
using System; using System.Collections.Generic; namespace QLTHPT.Models { public partial class Thongtindaotao { public string TtdtMa { get; set; } public string HinhthucsHtMa { get; set; } public string ChuyennganhCnMa { get; set; } public string VanbangVbMa { get; set; } public string CanboCbMa { get; set; } public virtual Canbo CanboCbMaNavigation { get; set; } public virtual Chuyennganh ChuyennganhCnMaNavigation { get; set; } public virtual Hinhthuc HinhthucsHtMaNavigation { get; set; } public virtual Vanbang VanbangVbMaNavigation { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FuzzyLogic.Sets; namespace FuzzyLogic.PropertiesOperations { public interface IBinaryProperty { bool Operate(Set set1, Set set2); } }
using System; namespace Funcoes { class Program { static void Main(string[] args) { Console.WriteLine("Digite 3 números:"); int n1 = int.Parse(Console.ReadLine()); int n2 = int.Parse(Console.ReadLine()); int n3 = int.Parse(Console.ReadLine()); Console.WriteLine("O maior número é: " + DefineMaior(n1, n2, n3)); } public static int DefineMaior(int n1, int n2, int n3) { int maior = 0; if (n1 > n2 && n1 > n3) { maior = n1; } else if (n2 > n3) { maior = n2; } else { maior = n3; } return maior; } } }
using System; using API.Domain.Models; using API.Shared.Models; using Microsoft.EntityFrameworkCore.ChangeTracking; using Tango.Types; namespace API.Shared.Extension { public static class TryClass { public static Either<Falha, TEntity> Try<TEntity>(this Func<EntityEntry<TEntity>> funcao) where TEntity: EntidadeBase { try{ return funcao().Entity; } catch(Exception ex){ return new Falha(Processo.ErroNoBanco, new MensagemDeErro(ex.Message)); } } public static Either<Falha, TRetorno> Try<TRetorno>(this Func<TRetorno> funcao) { try{ return funcao(); } catch(Exception ex){ return new Falha(Processo.ErroNoBanco, new MensagemDeErro(ex.Message)); } } } }
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace SeleniumFirst { class Program { static void Main(string[] args) { } [SetUp] public void Initialize() { PropertiesCollection.Driver = new ChromeDriver(); // Navigate to Execute Automation demo page PropertiesCollection.Driver.Navigate().GoToUrl("http://executeautomation.com/demosite/Login.html"); Console.WriteLine("Opened URL"); } [Test] public void ExecuteTest() { // Login to application LoginPageObject pageLogin = new LoginPageObject(); EAPageObject pageEa = pageLogin.Login("execute", "automation"); pageEa.FillUserForm("W.", "Rebecca", "A."); //// Initialize the page by calling its reference //EAPageObject page = new EAPageObject(); //page.InitialElement.SendKeys("W."); //page.FirstNameElement.SendKeys("Rebecca"); //page.MiddleNameElement.SendKeys("A."); //page.ButtonSaveElement.Click(); //// TitleId //SeleniumSetMethods.SelectDropDown(PropertyType.Id, "TitleId", "Mr."); //// Initial //SeleniumSetMethods.EnterText(PropertyType.Name, "Initial", "execute automation"); //// Get the title value //Console.WriteLine("The value from my Title is: " + SeleniumGetMethods.GetTextFromDropdownList(PropertyType.Id, "TitleId")); //// Get the initial value //Console.WriteLine("The value from my Initial is: " + SeleniumGetMethods.GetText(PropertyType.Name, "Initial")); //// Click //SeleniumSetMethods.ClickElement(PropertyType.Name, "Save"); } [Test] public void NextTest() { Console.WriteLine("Next Test"); } [TearDown] public void CleanUp() { PropertiesCollection.Driver.Close(); Console.WriteLine("Closed the browser"); } } }
/* Copyright © 2005 - 2017 Annpoint, s.r.o. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------------- NOTE: Reuse requires the following acknowledgement (see also NOTICE): This product includes DayPilot (http://www.daypilot.org) developed by Annpoint, s.r.o. */ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web.UI; namespace DayPilot.Web.Mvc.Utils { internal class PropertyLoader { internal static string GetString(object dataItem, string propertyName, string dataFieldName) { if (String.IsNullOrEmpty(propertyName)) { throw new NullReferenceException(dataFieldName + " property must be specified."); } object val; if (dataItem is DataRow) { DataRow dr = (DataRow) dataItem; if (dr.Table.Columns.Contains(propertyName)) { val = ((DataRow)dataItem)[propertyName]; } else { return null; } } else { val = DataBinder.GetPropertyValue(dataItem, propertyName, null); } return val.ToString(); } internal static DateTime GetDateTime(object dataItem, string propertyName, string dataFieldName) { if (String.IsNullOrEmpty(propertyName)) { throw new NullReferenceException(dataFieldName + " property must be specified."); } object val; if (dataItem is DataRow) { val = ((DataRow)dataItem)[propertyName]; } else { val = DataBinder.GetPropertyValue(dataItem, propertyName, null); } DateTime result; if (DateTimeParser.IsParseable(val)) { return DateTimeParser.Parse(val); } throw new FormatException(String.Format("Unable to convert '{0}' (from {1} column) to DateTime.", val, dataFieldName)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace GameDoMin { public partial class HightScore : Form { public HightScore() { InitializeComponent(); } private void HightScore_Load(object sender, EventArgs e) { HienThiDiem(); } void HienThiDiem() { SqlConnection connect = new SqlConnection(@"Data Source=DESKTOP-V4QPNQU\SQLEXPRESS;Initial Catalog=QuanLiDiem;Integrated Security=True"); SqlDataAdapter adap = new SqlDataAdapter("select * from Diem order by ThoiGian ",connect); DataTable table = new DataTable(); adap.Fill(table); dgvHightScore.DataSource = table; } } }
using System; using ClosestNodeBinaryTree.Classes; namespace ClosestNodeBinaryTree.Classes { public class ClosestInTree { /// <summary> /// This is for a binary search tree /// </summary> /// <returns>The number.</returns> /// <param name="nodeInput">Node input.</param> /// <param name="numberInput">Number input.</param> public int ClosestNumber(Node nodeInput, int numberInput) { if(nodeInput.Value == numberInput) { return nodeInput.Value; } if(nodeInput.Value > numberInput) { if(nodeInput.LeftChild == null) { return nodeInput.Value; } int closest = ClosestNumber(nodeInput.LeftChild, numberInput); if (Math.Abs(closest - numberInput) > Math.Abs(nodeInput.Value - numberInput)) { return nodeInput.Value; } return closest; } else { if(nodeInput.RightChild == null) { return nodeInput.Value; } int closest = ClosestNumber(nodeInput.RightChild, numberInput); if (Math.Abs(closest - numberInput) > Math.Abs(nodeInput.Value - numberInput)) { return nodeInput.Value; } return closest; } } } }
// C# Excel Writer library v2.1 // by Serhiy Perevoznyk, 2008-2018 using System; using System.Collections.Generic; using System.Text; namespace Export.XLS { [Flags] public enum FontStyle { Regular = 0, Bold = 1, Italic = 2, Underline = 4, Strikeout = 8 } }
using System; using System.Collections.Generic; using System.Text; using TanoApp.Data.EF.EF; using TanoApp.Data.Entities; using TanoApp.Data.IRepositories; namespace TanoApp.Data.EF.Repositories { public class ProductQuantityRepository: EFRepository<ProductQuantity, int>, IProductQuantityRepository { private AppDbContext _context; public ProductQuantityRepository(AppDbContext dbContext): base(dbContext) { _context = dbContext; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; namespace WindowsFormsApp1 { public partial class frmReturn : Form { public frmReturn() { InitializeComponent(); //receive studentCounter hideButtons(); } public string[] data; //Put Data from Array into Labels private void DisplayReport() { lblID.Text = data[0]; lblFirst.Text = data[1]; lblLast.Text = data[2]; ea = data[3]; lblGrade.Text = data[4]; } //Sign Out Button private void btnOut_Click(object sender, EventArgs e) { this.Close(); } private void frmReturn_Load(object sender, EventArgs e) { //Receive Student Array from Home Page Login DisplayReport(); } //Checks if Email is Valid public static bool IsValidEmail(string emailaddress) { try { Regex rx = new Regex( @"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$"); return rx.IsMatch(emailaddress); } catch (FormatException) { return false; } } string ea = ""; private void changeEmail() { try { bool check = IsValidEmail(txtCurrent.Text); bool valid = IsValidEmail(txtNew.Text); if (txtCurrent.Text != ea || !valid) { MessageBox.Show("Invalid Email"); } else { frmConfirm confirm = new frmConfirm(); DialogResult result = confirm.ShowDialog(); if (result == DialogResult.Yes) { //Update Email in database String[] rows; string filename = @"..\..\books.txt"; using (StreamReader sr = File.OpenText(filename)) { rows = Regex.Split(sr.ReadToEnd(), "\r\n"); } bool match = false; using (StreamWriter sw = new StreamWriter(filename)) { for (int i = 0; i < (rows.Length - 1); i++) { if (rows[i].Contains(txtCurrent.Text) && !match) { rows[i] = rows[i].Replace(txtCurrent.Text, txtNew.Text); match = true; } sw.WriteLine(rows[i]); } } MessageBox.Show("Email Updated"); hideButtons(); } else { MessageBox.Show("Email not Updated"); hideButtons(); } } } catch (Exception ex) { //MessageBox.Show("Please enter a valid email"); MessageBox.Show(ex.Message); //handles any error } } private void changePassword() { try { frmConfirm confirm = new frmConfirm(); DialogResult result = confirm.ShowDialog(); if (result == DialogResult.Yes) { //Update password in database String[] rows; string filename = @"..\..\books.txt"; using (StreamReader sr = File.OpenText(filename)) { rows = Regex.Split(sr.ReadToEnd(), "\r\n"); } using (StreamWriter sw = new StreamWriter(filename)) { for (int i = 0; i < (rows.Length - 1); i++) { if (rows[i].Contains(txtCurrent.Text)) { rows[i] = rows[i].Replace(txtCurrent.Text, txtNew.Text); } sw.WriteLine(rows[i]); } } } MessageBox.Show("Password Updated"); hideButtons(); } catch (Exception ex) { //MessageBox.Show("Please enter a valid email"); MessageBox.Show(ex.Message); //handles any error } } private void changeName() { try { if (txtCurrent.Text == "" || txtNew.Text == "") { MessageBox.Show("Please fill all fields"); } else { frmConfirm confirm = new frmConfirm(); DialogResult result = confirm.ShowDialog(); if (result == DialogResult.Yes) { //Update name in database String[] rows; string filename = @"..\..\books.txt"; using (StreamReader sr = File.OpenText(filename)) { rows = Regex.Split(sr.ReadToEnd(), "\r\n"); } using (StreamWriter sw = new StreamWriter(filename)) { for (int i = 0; i < rows.Length - 1; i++) { if (rows[i].Contains(data[1])) { rows[i] = rows[i].Replace(data[1], txtCurrent.Text); rows[i] = rows[i].Replace(data[2], txtNew.Text); } sw.WriteLine(rows[i]); } } MessageBox.Show("Name Changed"); hideButtons(); lblFirst.Text = txtCurrent.Text; lblLast.Text = txtNew.Text; } else { MessageBox.Show("Name not updated"); } } } catch (Exception ex) { //MessageBox.Show("Please enter a valid email"); MessageBox.Show(ex.Message); //handles any error } } private void changeGrade() { try { frmConfirm confirm = new frmConfirm(); DialogResult result = confirm.ShowDialog(); if (result == DialogResult.Yes) { //Update grade in database String[] rows; string filename = @"..\..\books.txt"; using (StreamReader sr = File.OpenText(filename)) { rows = Regex.Split(sr.ReadToEnd(), "\r\n"); } using (StreamWriter sw = new StreamWriter(filename)) { for (int i = 0; i < rows.Length - 1; i++) { if (rows[i].Contains(data[4])) { rows[i] = rows[i].Replace(data[4], cboGrade.Text); } sw.WriteLine(rows[i]); } } } } catch (Exception ex) { //MessageBox.Show("Please enter a valid email"); MessageBox.Show(ex.Message); //handles any error } } private void btnDelete_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Are you sure you would like to delete this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result==DialogResult.Yes) { //delete current record String[] rows; string filename = @"..\..\books.txt"; int records = File.ReadAllLines(filename).Length; using (StreamReader sr = File.OpenText(filename)) { rows = Regex.Split(sr.ReadToEnd(), "\r\n"); } File.Delete(filename); int newlines = rows.Length - 1; using (StreamWriter sw = File.CreateText(filename)) { for (int i = 0; i < newlines; i++) { if (!rows[i].Contains(data[0])) { sw.WriteLine(rows[i]); } } } this.Close(); } } private void btnChangeEmail_Click(object sender, EventArgs e) { lblCategory.Text = "Change Email"; lblCurrent.Text = "Current Email"; lblNew.Text = "New Email"; showButtons(); hideGrade(); } private void btnChangePassword_Click(object sender, EventArgs e) { lblCategory.Text = "Change Password"; lblCurrent.Text = "Current Password"; lblNew.Text = "New Password"; showButtons(); hideGrade(); } private void hideButtons() { lblCategory.Visible = false; lblCurrent.Visible = false; lblNew.Visible = false; txtCurrent.Visible = false; txtNew.Visible = false; btnCancel.Visible = false; btnUpdate.Visible = false; } private void hideGrade() { lblChangeGrade.Visible = false; cboGrade.Visible = false; } private void showButtons() { lblCategory.Visible = true; lblCurrent.Visible = true; lblNew.Visible = true; txtCurrent.Visible = true; txtNew.Visible = true; btnCancel.Visible = true; btnUpdate.Visible = true; } private void btnUpdate_Click(object sender, EventArgs e) { if (lblCategory.Text == "Change Email") { if (txtCurrent.Text == "" || txtNew.Text == "") { MessageBox.Show("Please fill all fields"); } else { changeEmail(); txtCurrent.Clear(); txtNew.Clear(); } } else if (lblCategory.Text == "Change Password") { if (txtNew.Text == "" || txtCurrent.Text == "") { MessageBox.Show("Please fill all fields"); } else { changePassword(); txtCurrent.Clear(); txtNew.Clear(); } } else if (lblCategory.Text == "Change Name:") { bool first = txtCurrent.Text.All(Char.IsLetter); bool last = txtNew.Text.All(Char.IsLetter); if (!first || !last) { MessageBox.Show("Please enter letters only"); } else { changeName(); txtCurrent.Clear(); txtNew.Clear(); } } else { if (cboGrade.Text == "") { MessageBox.Show("Please select an item from the list"); } else { changeGrade(); MessageBox.Show("Grade Changed"); lblChangeGrade.Visible = false; cboGrade.Visible = false; btnUpdate.Visible = false; btnCancel.Visible = false; lblGrade.Text = cboGrade.Text; txtCurrent.Clear(); txtNew.Clear(); } } } //Change Name Button private void btnName_Click(object sender, EventArgs e) { lblCategory.Text = "Change Name:"; lblCurrent.Text = "Enter First Name:"; lblNew.Text = "Enter Last Name:"; showButtons(); hideGrade(); } private void btnGrade_Click(object sender, EventArgs e) { lblCategory.Text = "Change Grade:"; hideButtons(); btnUpdate.Visible = true; btnCancel.Visible = true; lblChangeGrade.Visible = true; cboGrade.Visible = true; } private void lblName_Click(object sender, EventArgs e) { } private void lblCategory_Click(object sender, EventArgs e) { } private void btnClear_Click(object sender, EventArgs e) { txtCurrent.Clear(); txtNew.Clear(); cboGrade.SelectedIndex = -1; } private void btnHelp_Click(object sender, EventArgs e) { frmLoginHelp help = new frmLoginHelp(); help.ShowDialog(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Linq; namespace SnakeGame { class ScoreXmlHandler { private XmlReader xmlReader { get; set; } private XmlWriter xmlWriter { get; set; } private List<ScoreData> Scores; public ScoreXmlHandler() { try { UpdateScores(); } catch (Exception) { xmlWriter = XmlWriter.Create("SnakeScores.xml"); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("players"); xmlWriter.WriteStartElement("player"); xmlWriter.WriteAttributeString("name", "BOSS"); xmlWriter.WriteAttributeString("score", "999"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); } } public void WriteScores(string name , int score) { this.ArrangeScores(name, score); xmlWriter = XmlWriter.Create("SnakeScores.xml"); xmlWriter.WriteStartDocument(); int tempInt = 0; if (this.Scores.Count < 3) { tempInt = this.Scores.Count; } else { tempInt = 3; } for (int i = 0; i < tempInt; i++) { xmlWriter.WriteStartElement("players"); xmlWriter.WriteStartElement("player"); xmlWriter.WriteAttributeString("name", this.Scores[i].Name); xmlWriter.WriteAttributeString("score", this.Scores[i].Score.ToString()); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndDocument(); xmlWriter.Close(); } private void UpdateScores() { this.Scores = new List<ScoreData>(); xmlReader = XmlReader.Create("SnakeScores.xml"); while (xmlReader.Read()) { if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "player")) { if (xmlReader.HasAttributes) { Scores.Add(new ScoreData(int.Parse(xmlReader.GetAttribute("score")), xmlReader.GetAttribute("name"))); } } } xmlReader.Close(); } public List<ScoreData> GetScores() { UpdateScores(); return Scores; } private void ArrangeScores(string newName, int newScore) { UpdateScores(); this.Scores.Add(new ScoreData(newScore, newName)); ScoreData temp; for (int i = 0; i < this.Scores.Count; i++) { for (int j = 0; j < this.Scores.Count-1; j++) { if (this.Scores[j].Score < this.Scores[j+1].Score) { temp = new ScoreData(this.Scores[j].Score, this.Scores[j].Name); Scores[j] = new ScoreData(this.Scores[j + 1].Score, this.Scores[j + 1].Name); this.Scores[j +1] = new ScoreData(temp.Score, temp.Name); } } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class tap : MonoBehaviour { // Use this for initialization public GameObject popUps; private int popUpIndex; void Start () { StartCoroutine(waiter()); } IEnumerator waiter() { yield return new WaitForSeconds(2); popUps.SetActive(true); } // Update is called once per frame }
using System; using System.Data; using System.Collections.Generic; using System.Text; using Npgsql; using NpgsqlTypes; using CGCN.Framework; using CGCN.DataAccess; namespace QTHT.DataAccess { /// <summary> /// Mô tả thông tin cho bảng quyen_nhom /// Cung cấp các hàm xử lý, thao tác với bảng quyen_nhom /// Người tạo (C): /// Ngày khởi tạo: 17/10/2014 /// </summary> public class quyen_nhom { #region Private Variables private string strid; private string stridnhom; private int intmenuid; #endregion #region Public Constructor Functions public quyen_nhom() { strid = string.Empty; stridnhom = string.Empty; intmenuid = 0; } public quyen_nhom(string strid, string stridnhom, int intmenuid) { this.strid = strid; this.stridnhom = stridnhom; this.intmenuid = intmenuid; } #endregion #region Properties public string id { get { return strid; } set { strid = value; } } public string idnhom { get { return stridnhom; } set { stridnhom = value; } } public int menuid { get { return intmenuid; } set { intmenuid = value; } } #endregion #region Public Method private readonly DataAccessLayerBaseClass mDataAccess = new DataAccessLayerBaseClass(Data.ConnectionString); /// <summary> /// Lấy toàn bộ dữ liệu từ bảng quyen_nhom /// </summary> /// <returns>DataTable</returns> public DataTable GetAll() { string strFun = "fn_quyen_nhom_getall"; try { DataSet dsquyen_nhom = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure); return dsquyen_nhom.Tables[0]; } catch { return null; } } /// <summary> /// Hàm lấy quyen_nhom theo mã /// </summary> /// <returns>Trả về objquyen_nhom </returns> public quyen_nhom GetByID(string strid) { quyen_nhom objquyen_nhom = new quyen_nhom(); string strFun = "fn_quyen_nhom_getobjbyid"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = strid; DataSet dsquyen_nhom = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if ((dsquyen_nhom != null) && (dsquyen_nhom.Tables.Count > 0)) { if (dsquyen_nhom.Tables[0].Rows.Count > 0) { DataRow dr = dsquyen_nhom.Tables[0].Rows[0]; objquyen_nhom.id = dr["id"].ToString(); objquyen_nhom.idnhom = dr["idnhom"].ToString(); try{ objquyen_nhom.menuid = Convert.ToInt32("0" + dr["menuid"].ToString());} catch{ objquyen_nhom.menuid = 0;} return objquyen_nhom; } return null; } return null; } catch { return null; } } /// <summary> /// Hàm lấy danh sách chức năng theo mã nhóm /// </summary> /// <param name="stridnhom">Mã nhóm kiểu string</param> /// <returns>DataTable</returns> public DataTable GetByIDNhom(string stridnhom) { quyen_nhom objquyen_nhom = new quyen_nhom(); string strFun = "fn_quyen_nhom_getbyidnhom"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar); prmArr[0].Value = stridnhom; DataSet dsquyen_nhom = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); return dsquyen_nhom.Tables[0]; } catch { return null; } } /// <summary> /// Thêm mới dữ liệu vào bảng: quyen_nhom /// </summary> /// <param name="obj">objquyen_nhom</param> /// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns> public string Insert(quyen_nhom objquyen_nhom) { string strProc = "fn_quyen_nhom_insert"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[4]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = objquyen_nhom.strid; prmArr[1] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar); prmArr[1].Value = objquyen_nhom.stridnhom; prmArr[2] = new NpgsqlParameter("menuid", NpgsqlDbType.Integer); prmArr[2].Value = objquyen_nhom.intmenuid; prmArr[3] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[3].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[3].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Add".ToUpper()) == true) return ""; return "Thêm mới dữ liệu không thành công"; } catch(Exception ex) { return "Thêm mới dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Cập nhật dữ liệu vào bảng: quyen_nhom /// </summary> /// <param name="obj">objquyen_nhom</param> /// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns> public string Update(quyen_nhom objquyen_nhom) { string strProc = "fn_quyen_nhom_Update"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[4]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = objquyen_nhom.strid; prmArr[1] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar); prmArr[1].Value = objquyen_nhom.stridnhom; prmArr[2] = new NpgsqlParameter("menuid", NpgsqlDbType.Integer); prmArr[2].Value = objquyen_nhom.intmenuid; prmArr[3] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[3].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[3].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Update".ToUpper()) == true) return ""; return "Cập nhật dữ liệu không thành công"; } catch(Exception ex) { return "Cập nhật dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Hàm xóa dữ liệu theo mã /// </summary> /// <param name="strid">Mã kiểu string</param> /// <returns>Trả về trắng: xóa thành công; Trả về khác trắng: xóa không thành công</returns> public string Delete(string strid) { string strProc = "fn_quyen_nhom_delete"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Varchar); prmArr[0].Value = strid; prmArr[1] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[1].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string KQ = prmArr[1].Value.ToString().Trim(); if (KQ.ToUpper().Equals("Del".ToUpper()) == true) return ""; return "Xóa dữ liệu không thành công"; } catch(Exception ex) { return "Xóa dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Hàm xóa dữ liệu theo mã nhóm /// </summary> /// <param name="stridnhom">Mã nhóm kiểu string</param> /// <returns>Trả về trắng: xóa thành công; Trả về khác trắng: xóa không thành công</returns> public string DeletebyIDNhom(string stridnhom) { string strProc = "fn_quyen_nhom_deletebyidnhom"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar); prmArr[0].Value = stridnhom; prmArr[1] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[1].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string KQ = prmArr[1].Value.ToString().Trim(); if (KQ.ToUpper().Equals("Del".ToUpper()) == true) return ""; return "Xóa dữ liệu không thành công"; } catch (Exception ex) { return "Xóa dữ liệu không thành công. Chi Tiết: " + ex.Message; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace fingerPrint_Manag.Views { /// <summary> /// Interaction logic for StatisticsView.xaml /// </summary> public partial class StatisticsView : UserControl { public StatisticsView() { InitializeComponent(); GetPresentation(); } public class Presentation { public string Name { get; set; } public string Function { get; set; } public int Number { get; set; } } public void GetPresentation() { List<Presentation> _presentation = new List<Presentation>(); new Presentation() { Name = "Elijah", Function = "SA", Number = 1820, }; new Presentation() { Name = "Alain", Function = "SE", Number = 2040, }; new Presentation() { Name = "Gedeon", Function = "CE", Number = 1456, }; new Presentation() { Name = "Regiss", Function = "CI", Number = 1435, }; // StatisticsDatagrid.ItemsSource = _presentation; } } }
using UnityEngine; using UnityEngine.SceneManagement; public class MainMenuController : MonoBehaviour { #region Methods public void StartGame() { SceneManager.LoadScene(1); Time.timeScale = 1; } public void Exit() { Application.Quit(); } #endregion }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; class Dictionary { static void Main() { string[] dictionary = { ".NET – platform for applications from Microsoft", "CLR – managed execution environment for .NET", "namespace – hierarchical organization of classes" }; Console.WriteLine("Enter a word(.NET, CLR, namespace): "); string input = Console.ReadLine(); for (int i = 0; i < dictionary.Length; i++) { Match word = Regex.Match(dictionary[i], @"(.*)( – )(.*)"); if (input == word.Groups[1].Value) { Console.WriteLine(Regex.Match(dictionary[i], @"(.*)( – )(.*)").Groups[3]); } } } }
///<summury> /// TCP Server /// System.Net.Sockets /// TCP Socket 통신시에는 Receive 할때 정해진 바이트로 리시브를 받음 /// 그래서 수신할 바이트를 크기를 미리 보낸다. example 4byte data_size /// TCP Socket 통신시 Send시에도 마찬가지 /// </summury> using System; using System.Net; using System.Net.Sockets; using System.Text; class Program { static void Main() { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.0.13"), 7000); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 소캣 순서 server.Bind(ipep); // Bind server.Listen(20); // Listen Console.WriteLine("Starting Server"); Socket client = server.Accept(); // Accept IPEndPoint ip = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("{0}주소, {1}포트 접속", ip.Address, ip.Port); byte[] data = Encoding.Default.GetBytes("환영 합니다"); // send Byte data client.Send(data, data.Length, SocketFlags.None); data = new byte[1024]; if (client.Receive(data) != 0) { Console.WriteLine("수신 메시지 {0}", Encoding.Default.GetString(data)); } client.Close(); server.Close(); } }; /* ///<summury> /// TCP Server /// System.Net.Sockets /// TCP Socket 통신시에는 Receive 할때 정해진 바이트로 리시브를 받음 /// 그래서 수신할 바이트를 크기를 미리 보낸다. example 4byte data_size /// TCP Socket 통신시 Send시에도 마찬가지 /// </summury> using System; using System.Net; using System.Net.Sockets; using System.Text; class Program { static void Main() { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.0.13"), 7000); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 소캣 순서 server.Bind(ipep); // Bind server.Listen(20); // Listen Console.WriteLine("Starting Server"); Socket client = server.Accept(); // Accept IPEndPoint ip = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("{0}주소, {1}포트 접속", ip.Address, ip.Port); byte[] data = Encoding.Default.GetBytes("환영 합니다"); // send Byte data //client.Send(data, data.Length, SocketFlags.None); SendData(data, client); data = new byte[1024]; ReceiveData(data, client); client.Close(); server.Close(); } static void SendData(byte[] data, Socket client) { try { int total = 0; int size = data.Length; int left_data = size; int send_data = 0; // 전송할 데이터의 크기 전달 byte[] data_size = new byte[4]; data_size = BitConverter.GetBytes(size); send_data = client.Send(data_size); // 실제 데이터 전송 while (total < size) { send_data = client.Send(data, total, left_data, SocketFlags.None); total += send_data; left_data -= send_data; } } catch (Exception ex) { Console.WriteLine(ex.Message); } } static void ReceiveData(byte[] data, Socket client) { try { int total = 0; int size = 0; int left_data = 0; int recv_data = 0; // 수신할 데이터 크기 알아내기 byte[] data_size = new byte[4]; recv_data = client.Receive(data_size, 0, 4, SocketFlags.None); size = BitConverter.ToInt32(data_size, 0); left_data = size; data = new byte[size]; // 실제 데이터 수신 while (total < size) { recv_data = client.Receive(data, total, left_data, 0); if (recv_data == 0) break; total += recv_data; left_data -= recv_data; } } catch (Exception ex) { Console.WriteLine(ex.Message); return; } } }; */
using System; using System.ComponentModel.DataAnnotations; namespace Domain { public class Transaction { public Guid Id { get; set; } [Required] public string Symbol { get; set; } [Required] public string CompanyName { get; set; } public string Type { get; set; } public DateTime TransactionDate { get; set; } public float PurchasePrice { get; set; } public float SellPrice { get; set; } public float TransactionPrice { get; set; } public int TransactionAmount { get; set; } [Required] public AppUser AppUser { get; set; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using WhiteList.Attributes; using WhiteList.Data.Context; using WhiteList.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WhiteList.Controllers { [Route("api/[controller]")] [ServiceFilter(typeof(IpControlAttribute))] [ApiController] public class ExamsController : ControllerBase { private ExamDbContext _dbContext; public ExamsController(ExamDbContext dbContext) { _dbContext = dbContext; } [HttpGet(Name = nameof(GetExams))] public IActionResult GetExams() { List<Exam> songs = _dbContext.Exams.ToList(); return Ok(songs); } [HttpGet("{id}")] public IActionResult Get(int id) { Exam exam = _dbContext.Exams.FirstOrDefault(exam => exam.Id == id); return Ok(exam); } [HttpPost] public IActionResult Post([FromBody] Exam exam) { _dbContext.Add(exam); return Ok(); } } }
namespace OOP_FrancisBulu.Models { public class Reisbureau { } }
using System; using System.Collections.Generic; using System.Text; namespace BoardGame { public class AIPlayer : Player { public AIPlayer(string name): base(name) { } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace SGDE.DataEFCoreSQL.Migrations { public partial class Add_Fields_Prices : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "PriceHourSale", table: "ProfessionInClient"); migrationBuilder.AddColumn<decimal>( name: "PriceHourExtra", table: "ProfessionInClient", nullable: false, defaultValue: 0m); migrationBuilder.AddColumn<decimal>( name: "PriceHourFestive", table: "ProfessionInClient", nullable: false, defaultValue: 0m); migrationBuilder.AddColumn<decimal>( name: "PriceHourOrdinary", table: "ProfessionInClient", nullable: false, defaultValue: 0m); migrationBuilder.AddColumn<decimal>( name: "PriceHourSaleExtra", table: "ProfessionInClient", nullable: false, defaultValue: 0m); migrationBuilder.AddColumn<decimal>( name: "PriceHourSaleFestive", table: "ProfessionInClient", nullable: false, defaultValue: 0m); migrationBuilder.AddColumn<decimal>( name: "PriceHourSaleOrdinary", table: "ProfessionInClient", nullable: false, defaultValue: 0m); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "PriceHourExtra", table: "ProfessionInClient"); migrationBuilder.DropColumn( name: "PriceHourFestive", table: "ProfessionInClient"); migrationBuilder.DropColumn( name: "PriceHourOrdinary", table: "ProfessionInClient"); migrationBuilder.DropColumn( name: "PriceHourSaleExtra", table: "ProfessionInClient"); migrationBuilder.DropColumn( name: "PriceHourSaleFestive", table: "ProfessionInClient"); migrationBuilder.DropColumn( name: "PriceHourSaleOrdinary", table: "ProfessionInClient"); migrationBuilder.AddColumn<decimal>( name: "PriceHourSale", table: "ProfessionInClient", type: "decimal(18,2)", nullable: false, defaultValue: 0m); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web; using TxHumor.BLL; using TxHumor.Common; using TxHumor.Model; namespace TxHumor.Tool.Humor { public class AddHumor { public static T_Humor_HumorInfo GetHumor(string html) { string regTitle = @"<div class=""mala-title""> <h2>(.+)?</h2> </div>"; string regContent = @"<div class=""mala-img""> <a class=""mala-link-jump"" [^>]*> (.+)?</a> <div class=""mala-img-sponsor fn-clear""> <!--广告位--> 广告 <!--广告位end--> </div> <!-- // mala-img-sponsor end --> </div>"; string regGood = @"<i class=""ui-icon give-good""></i>[^<]*<em>(\d+)?</em>"; string regBad = @"<i class=""ui-icon give-bad""></i>[^<]*<em>(\d+)?</em>"; var match = Regex.Match(html, regTitle); string title = match.Groups[1].Value; var contentMatch = Regex.Match(html, regContent); string content = contentMatch.Groups[1].Value; int supportNum = Regex.Match(html, regGood).Groups[1].Value.ToSimpleT(0); int opposeNum = Regex.Match(html, regBad).Groups[1].Value.ToSimpleT(0); string regUserInfo = @"<a class=""mala-author-avatar"" href=""#"">[^<]*?<img src=""([^""]+)?""[^>]*?></a>[^<]*?<h5><a href=""http://www.jiongshibaike.com/users/([^""]+)?"">([^<]+)?</a></h5>"; string regTags = @"<a href=""http://www.jiongshibaike.com/gs/([^""]+)?"" title=""([^""]+)?"">([^<]+)?</a>"; Match matchUser=Regex.Match(html, regUserInfo); string face = "http://www.jiongshibaike.com/Data/Static/face/default.png"; int userId = 0; string userName = "匿名"; if (matchUser.Success) { face = matchUser.Groups[1].Value; userId = Convert.ToInt32(matchUser.Groups[2].Value); userName = matchUser.Groups[3].Value; } var matchs = Regex.Matches(html, regTags); string tags = string.Empty; foreach (Match m in matchs) { string tag = m.Groups[1].Value; tags += HttpUtility.UrlDecode(tag) + ","; } T_Humor_HumorInfo humorInfo=new T_Humor_HumorInfo() { HumorTitle = title, HumorContent = content, CreateUserId = userId, CreateUserName = userName, SupportNum = supportNum, OpposeNum = opposeNum, TagIds = tags, HumorUbbContent = "", HumorType = GetHumorType(content), IpAddress = "127.0.0.1" }; return humorInfo; } public static int GetHumorType(string content) { if (content.Contains("img")) { return 1; } return 0; } private static Queue<string> queue=new Queue<string>(); public static void ThreadPoolAddHumor(int humorId) { for (int j = 0; j < 10000; j++) { queue.Enqueue("http://www.jiongshibaike.com/contents/"+humorId); humorId++; } for (int j = 0; j < max; j++) { ThreadPool.QueueUserWorkItem(GetContent, queue.Dequeue()); } while (true) { if (k == max) { break; } } } private static int i = 0; private static readonly int max = 100; static volatile int k = 1; private static object o=new object(); public static void GetContent(object url) { while (true) { using (WebClient wc = new WebClient()) { string html; try { html = wc.DownloadString(url.ToString()); } catch (Exception ex) { continue; } T_Humor_HumorInfo humorInfo=GetHumor(html); lock (o) { bll_HumorInfo.AddHumorInfo(humorInfo); } } if (i == max) { break; } } k++; } } }
using System; namespace Minesweeper { public static class Printer { public static void Print(Field field) { for (int i = 0; i < field.Rows; i++) { for (int j = 0; j < field.Columns; j++) { var point = new Point(i, j); Console.BackgroundColor = ConsoleColor.Gray; if (point.IsMine(field)) { Console.ForegroundColor = ConsoleColor.Black; Console.Write(field.Mines[point].Output); } else if (point.IsNeighbor(field)) { switch (field.MinesNeighbors[point].Value) { case 1: Console.ForegroundColor = ConsoleColor.Blue; break; case 2: Console.ForegroundColor = ConsoleColor.DarkGreen; break; case 3: Console.ForegroundColor = ConsoleColor.Red; break; case 4: Console.ForegroundColor = ConsoleColor.DarkBlue; break; case 5: Console.ForegroundColor = ConsoleColor.DarkRed; break; case 6: Console.ForegroundColor = ConsoleColor.Green; break; default: Console.ForegroundColor = ConsoleColor.Magenta; break; } Console.Write(field.MinesNeighbors[point].Output); } else { Console.Write(" "); } } Console.ResetColor(); Console.Write(Environment.NewLine); } } } }
using PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json; namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing; internal class ThingExistsOutgoingMessage : JsonOutgoingMessage<JsonThingExistsOutgoingMessage> { internal ThingExistsOutgoingMessage(bool exists) : base(new JsonThingExistsOutgoingMessage(exists)) { } }
using System; namespace UnityWebGLSpeechDetection { [Serializable] public class Language { public string name = string.Empty; public string display = string.Empty; public Dialect[] dialects; } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// Milestones can have associated activities which provide additional information about the context, challenges, modifiers, state etc... related to this Milestone. Information we need to be able to return that data is defined here, along with Tier data to establish a relationship between a conceptual Activity and its difficulty levels and variants. /// </summary> [DataContract] public partial class DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition : IEquatable<DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition" /> class. /// </summary> /// <param name="ConceptualActivityHash">The \&quot;Conceptual\&quot; activity hash. Basically, we picked the lowest level activity and are treating it as the canonical definition of the activity for rendering purposes. If you care about the specific difficulty modes and variations, use the activities under \&quot;Variants\&quot;..</param> /// <param name="Variants">A milestone-referenced activity can have many variants, such as Tiers or alternative modes of play. Even if there is only a single variant, the details for these are represented within as a variant definition. It is assumed that, if this DestinyMilestoneActivityDefinition is active, then all variants should be active. If a Milestone could ever split the variants&#39; active status conditionally, they should all have their own DestinyMilestoneActivityDefinition instead! The potential duplication will be worth it for the obviousness of processing and use..</param> public DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition(uint? ConceptualActivityHash = default(uint?), Dictionary<string, DestinyDefinitionsMilestonesDestinyMilestoneActivityVariantDefinition> Variants = default(Dictionary<string, DestinyDefinitionsMilestonesDestinyMilestoneActivityVariantDefinition>)) { this.ConceptualActivityHash = ConceptualActivityHash; this.Variants = Variants; } /// <summary> /// The \&quot;Conceptual\&quot; activity hash. Basically, we picked the lowest level activity and are treating it as the canonical definition of the activity for rendering purposes. If you care about the specific difficulty modes and variations, use the activities under \&quot;Variants\&quot;. /// </summary> /// <value>The \&quot;Conceptual\&quot; activity hash. Basically, we picked the lowest level activity and are treating it as the canonical definition of the activity for rendering purposes. If you care about the specific difficulty modes and variations, use the activities under \&quot;Variants\&quot;.</value> [DataMember(Name="conceptualActivityHash", EmitDefaultValue=false)] public uint? ConceptualActivityHash { get; set; } /// <summary> /// A milestone-referenced activity can have many variants, such as Tiers or alternative modes of play. Even if there is only a single variant, the details for these are represented within as a variant definition. It is assumed that, if this DestinyMilestoneActivityDefinition is active, then all variants should be active. If a Milestone could ever split the variants&#39; active status conditionally, they should all have their own DestinyMilestoneActivityDefinition instead! The potential duplication will be worth it for the obviousness of processing and use. /// </summary> /// <value>A milestone-referenced activity can have many variants, such as Tiers or alternative modes of play. Even if there is only a single variant, the details for these are represented within as a variant definition. It is assumed that, if this DestinyMilestoneActivityDefinition is active, then all variants should be active. If a Milestone could ever split the variants&#39; active status conditionally, they should all have their own DestinyMilestoneActivityDefinition instead! The potential duplication will be worth it for the obviousness of processing and use.</value> [DataMember(Name="variants", EmitDefaultValue=false)] public Dictionary<string, DestinyDefinitionsMilestonesDestinyMilestoneActivityVariantDefinition> Variants { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition {\n"); sb.Append(" ConceptualActivityHash: ").Append(ConceptualActivityHash).Append("\n"); sb.Append(" Variants: ").Append(Variants).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition); } /// <summary> /// Returns true if DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition instances are equal /// </summary> /// <param name="input">Instance of DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyDefinitionsMilestonesDestinyMilestoneActivityDefinition input) { if (input == null) return false; return ( this.ConceptualActivityHash == input.ConceptualActivityHash || (this.ConceptualActivityHash != null && this.ConceptualActivityHash.Equals(input.ConceptualActivityHash)) ) && ( this.Variants == input.Variants || this.Variants != null && this.Variants.SequenceEqual(input.Variants) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ConceptualActivityHash != null) hashCode = hashCode * 59 + this.ConceptualActivityHash.GetHashCode(); if (this.Variants != null) hashCode = hashCode * 59 + this.Variants.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebhookSend.Services { public interface IMessageQueueService { bool SendMessage(string message); } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(Rigidbody2D), typeof(Collider2D))] public class Projectile : MonoBehaviour { private Weapon _weapon; private float health = 100; public void Initialize(Weapon stats) { _weapon = stats; Invoke("Die", _weapon.Stats.Lifetime); } private void Die() { Destroy(gameObject); } private void OnTriggerEnter2D(Collider2D coll) { var unit = coll.GetComponent<Unit>(); if (unit) { if (Random.value > _weapon.Stats.PierceRate) { health -= 100; } if (health <= 0) Die(); unit.TakeDamage(_weapon.Stats.Damage); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WUIShared.Objects; namespace WUIServer.Components { class TextRenderer : GameObject { private string text; private Color color; public TextRenderer(string text, Color color) : base(Objects.TextRenderer, false) { this.text = text; this.color = color; } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Criptomoedas.Models { public class CriptomoedaContexto : DbContext { public DbSet<Moeda> Moedas { get; set; } public CriptomoedaContexto(DbContextOptions<CriptomoedaContexto> opcoes) : base(opcoes) { } } }
using DTO.Results; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Reflection; namespace Test { [TestClass] public class UnitTest1 { private Type _magicType; [TestInitialize] public void Setup() { _magicType = GetTypes("Fns.EmployeeHelper"); } [TestMethod] public void TestGetDiscount() { //test data expected 10 double discountPercentage = 10; double Preimium = 100; double expected = 10; object[] tesdata = new object[] { discountPercentage, Preimium }; MethodInfo magicMethod = _magicType.GetMethod("GetDiscount"); object result = magicMethod.Invoke(magicMethod, tesdata); Assert.AreEqual(result, expected); } [TestMethod] public void TestGetDependendentPremium() { //test data double depdendentCost = 120; int totalPayCheck = 12; int depdendents = 1; double expected = 10; //Formula //(depdendentCost / totalPayCheck) * depdendents; object[] tesdata = new object[] { depdendentCost, totalPayCheck, depdendents }; MethodInfo magicMethod = _magicType.GetMethod("GetDependendentPremium"); object result = magicMethod.Invoke(magicMethod, tesdata); Assert.AreEqual(result, expected); } [TestMethod] public void TestGetNameDiscountFlag() { //test data var emp = new EmployeeDetails() { FirstName = "syed", LastName = "Abdi", Dependents = new List<DTO.Results.Info>() { new DTO.Results.Info() { FirstName="Adam",LastName = "Steve"} } }; string name = "a"; object[] tesdata = new object[] { emp,name }; MethodInfo magicMethod = _magicType.GetMethod("GetNameDiscountFlag"); object result = magicMethod.Invoke(magicMethod, tesdata); Assert.IsTrue(Convert.ToBoolean(result)); } [TestMethod] public void TestGetNameDiscountFlagFailed() { //test data var emp = new EmployeeDetails() { FirstName = "syed", LastName = "Abdi", Dependents = new List<DTO.Results.Info>() { new DTO.Results.Info() { FirstName="John",LastName = "Steve"} } }; string name = "a"; object[] tesdata = new object[] { emp, name }; MethodInfo magicMethod = _magicType.GetMethod("GetNameDiscountFlag"); object result = magicMethod.Invoke(magicMethod, tesdata); Assert.IsFalse(Convert.ToBoolean(result)); } //To find particular assembly public static Type GetTypes(string typeName) { var type = Type.GetType(typeName); if (type != null) return type; var t = AppDomain.CurrentDomain.GetAssemblies(); foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) { type = a.GetType(typeName); if (type != null) return type; } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using FakeItEasy; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using SoSmartTv.VideoService.Dto; using Xunit; using Assert = Xunit.Assert; namespace SoSmartTv.VideoService.Tests.Store { public class FetchCollectionTests : RedundantDataStoreTests { private IList<VideoItem> GetVideoItems() { return Enumerable.Range(0, 20).Select(x => new VideoItem() {Id = x, Title = "Title" + x}).ToList(); } private void Arrange(IList<VideoItem> localStoreItems, IList<VideoItem> externalStoreItems) { A.CallTo(() => _localStoreReader.GetVideoItems(A<IEnumerable<string>>._)) .Returns(Observable.Return(localStoreItems)); A.CallTo(() => _externalStoreReader.GetVideoItems(A<IEnumerable<string>>._)) .Returns(Observable.Return(externalStoreItems)); } private IObservable<IList<VideoItem>> Act(IEnumerable<string> titles) { return _sut.FetchCollection(titles, x => x, y => y.Title, (x, y) => x == y.Title, (store, x) => store.GetVideoItems(x), (store, x) => store.PersistVideoItems(x)); } private void AssertFetchCollection(IList<VideoItem> results, IList<VideoItem> expected) { Assert.Equal(results.Count, expected.Count); CollectionAssert.AreEqual(results.Select(x => x.Id).ToList(), expected.Select(x => x.Id).ToList()); CollectionAssert.AreEqual(results.Select(x => x.Title).ToList(), expected.Select(x => x.Title).ToList()); } [Fact] public void Returns_all_data_from_localReader_and_ignores_externalReader() { var localItems = GetVideoItems(); var externalItems = GetVideoItems().Do(x => x.Id += 100).ToList(); Arrange(localItems, externalItems); var results = Act(GetVideoItems().Select(i => i.Title)).Wait(); AssertFetchCollection(results, localItems); A.CallTo(() => _externalStoreReader.GetVideoItems(A<IEnumerable<string>>._)).MustNotHaveHappened(); } [Fact] public void Returns_all_data_from_externalReader_when_localReader_empty() { var localItems = new List<VideoItem>(); var externalItems = GetVideoItems().Do(x => x.Id += 100).ToList(); Arrange(localItems, externalItems); var results = Act(GetVideoItems().Select(i => i.Title)).Wait(); AssertFetchCollection(results, externalItems); } [Fact] public void Persists_all_data_from_externalReader() { var localItems = new List<VideoItem>(); var externalItems = GetVideoItems().Do(x => x.Id += 100).ToList(); Arrange(localItems, externalItems); var results = Act(GetVideoItems().Select(i => i.Title)).Wait(); A.CallTo(() => _localStoreWriter.PersistVideoItems(externalItems)).MustHaveHappened(); } [Fact] public void Returns_part_of_data_from_externalReader_when_localReader_returns_only_part_of_it() { var localItems = GetVideoItems().Take(2).Skip(2).Take(2).TakeLast(2).ToList(); var externalItems = GetVideoItems().Skip(2).Take(2).Skip(2).Take(12).Do(x => x.Id += 100).ToList(); var expected = localItems.Concat(externalItems).OrderBy(x => x.Title).ToList(); Arrange(localItems, externalItems); var results = Act(GetVideoItems().Select(i => i.Title)).Wait(); AssertFetchCollection(results, expected); } [Fact] public void Returns_only_matched_records() { var localItems = GetVideoItems().Take(2).ToList(); var externalItems = GetVideoItems().TakeLast(2).Do(x => x.Id += 100).ToList(); var expected = localItems.Concat(externalItems).OrderBy(x => x.Title).ToList(); Arrange(localItems, externalItems); var results = Act(GetVideoItems().Select(i => i.Title)).Wait(); AssertFetchCollection(results, expected); } [Fact] public void Returns_empty_when_no_matched_records() { var localItems = new List<VideoItem>(); var externalItems = new List<VideoItem>(); Arrange(localItems, externalItems); var results = Act(GetVideoItems().Select(i => i.Title)).Wait(); AssertFetchCollection(results, new List<VideoItem>()); } } }
using UnityEngine; using UnityEngine.EventSystems; using TMPro; using UnityEngine.SceneManagement; public class MapController : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { GameObject arrow; TextMeshProUGUI locationName; public string nextScene; void Start() { arrow = transform.parent.GetChild(0).gameObject; locationName = transform.parent.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>(); // TODO: If character is at this location, disable this game object. } public void OnPointerEnter(PointerEventData eventData) { arrow.SetActive(true); arrow.GetComponent<RectTransform>().localPosition = GetComponent<RectTransform>().localPosition + new Vector3(0, 65, 0); locationName.text = name.TrimEnd('1','2'); } public void OnPointerExit (PointerEventData eventdata) { arrow.SetActive(false); locationName.text = ""; } public void LoadLocation() { SceneManager.LoadScene(nextScene); } }
using System; namespace ClearSight.Core.Log { /// <summary> /// A IDisposable object for automatic closing of loggroups. /// </summary> /// <remarks> /// Usage example: /// /// using(new ScopedLogGroup("TestGroup")) /// { /// Log.Info("Info from within the group."); /// } /// </remarks> public class ScopedLogGroup : IDisposable { private Log targetedLogger; /// <summary> /// Begins a new group on the targeted logger. /// </summary> /// <param name="groupName">Name of the group to open.</param> /// <param name="targetedLogger">Logger on which the group should be created and later ended. /// Defaults to Logger.Default when null is passed.</param> public ScopedLogGroup(string groupName, Log targetedLogger = null) { this.targetedLogger = targetedLogger ?? Log.Default; Log.BeginGroup(this.targetedLogger, groupName); } public void Dispose() { Log.EndGroup(targetedLogger); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Grisaia.Extensions; namespace Grisaia.Utils { /// <summary> /// A static helper class for loading embedded resource streams. /// </summary> public static class Embedded { #region GetResources /// <summary> /// Returns the names of all the resources in the calling assembly. /// </summary> /// <returns>An array that contains the names of all embedded resources.</returns> public static string[] GetResources() { return GetResources(Assembly.GetCallingAssembly()); } /// <summary> /// Returns the names of all the resources in the calling assembly that start with the specified path. /// </summary> /// <param name="path">The path resources must start with.</param> /// <returns>An array that contains the names of all the matching embedded resources.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is null. /// </exception> public static string[] GetResources(string path) { return GetResources(Assembly.GetCallingAssembly(), path); } /// <summary> /// Returns the names of all the resources in this assembly. /// </summary> /// <param name="assembly">The assembly to get the resources of.</param> /// <returns>An array that contains the names of all embedded resources.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> is null. /// </exception> public static string[] GetResources(Assembly assembly) { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); return assembly.GetManifestResourceNames(); } /// <summary> /// Returns the names of all the resources in this assembly that start with the specified path. /// </summary> /// <param name="assembly">The assembly to get the resources of.</param> /// <param name="path">The path resources must start with.</param> /// <returns>An array that contains the names of all the matching embedded resources.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="path"/> is null. /// </exception> public static string[] GetResources(Assembly assembly, string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return GetResources(assembly).Where(s => s.StartsWith(path, StringComparison.InvariantCultureIgnoreCase)).ToArray(); } /// <summary> /// Returns the names of all the resources in type's the assembly. /// </summary> /// <param name="type">The type whose assembly is used to get the resources of.</param> /// <returns>An array that contains the names of all embedded resources.</returns> public static string[] GetResources(Type type) { return GetResources(type.Assembly); } /// <summary> /// Returns the names of all the resources in the type's assembly that start with the specified path. /// </summary> /// <param name="type">The type whose assembly is used to get the resources of.</param> /// <param name="path">The path resources must start with.</param> /// <returns>An array that contains the names of all the matching embedded resources.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/> or <paramref name="path"/> is null. /// </exception> public static string[] GetResources(Type type, string path) { return GetResources(type.Assembly, path); } #endregion #region Open /// <summary> /// Loads the specified manifest resource from the calling assembly. /// </summary> /// <param name="path">The paths to combine to create the resource path.</param> /// <returns>The <see cref="Stream"/> for the resource.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static Stream Open(string path) { return Open(Assembly.GetCallingAssembly(), path); } /*/// <summary> /// Loads the specified manifest resource from the calling assembly. /// </summary> /// <param name="paths">The paths to combine to create the resource path.</param> /// <returns>The <see cref="Stream"/> for the resource.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="paths"/> is null. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static Stream Open(params string[] paths) { return Open(Assembly.GetCallingAssembly(), Combine(paths)); }*/ /// <summary> /// Loads the specified manifest resource from the specified assembly. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <returns>The <see cref="Stream"/> for the resource.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static Stream Open(Assembly assembly, string path) { Stream stream = assembly.GetManifestResourceStream(path); return stream ?? throw new ResourceNotFoundException(assembly, path); } /*/// <summary> /// Loads the specified manifest resource from the specified assembly. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="paths">The paths to combine to create the resource path.</param> /// <returns>The <see cref="Stream"/> for the resource.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="paths"/> is null. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static Stream GetStream(Assembly assembly, params string[] paths) { return GetStream(assembly, Combine(paths)); }*/ /// <summary> /// Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly. /// </summary> /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <returns>The <see cref="Stream"/> for the resource.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/> or <paramref name="name"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static Stream Open(Type type, string name) { Stream stream = type.Assembly.GetManifestResourceStream(type, name); return stream ?? throw new ResourceNotFoundException(type, name); } #endregion #region ReadAllBytes /// <summary> /// Loads the specified manifest resource from the calling assembly as a byte array. /// </summary> /// <param name="path">The resource path.</param> /// <returns>The byte array of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static byte[] ReadAllBytes(string path) { return ReadAllBytes(Assembly.GetCallingAssembly(), path); } /// <summary> /// Loads the specified manifest resource from the specified assembly as a byte array. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <returns>The byte array of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static byte[] ReadAllBytes(Assembly assembly, string path) { using (Stream stream = Open(assembly, path)) return stream.ReadToEnd(); } /// <summary> /// Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// as a byte array /// </summary> /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <returns>The byte array of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/> or <paramref name="name"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static byte[] ReadAllBytes(Type type, string name) { using (Stream stream = Open(type, name)) return stream.ReadToEnd(); } #endregion #region ReadAllText /// <summary> /// Loads the specified manifest resource from the calling assembly as a string. /// </summary> /// <param name="path">The resource path.</param> /// <returns>The string of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string ReadAllText(string path) { return ReadAllText(Assembly.GetCallingAssembly(), path, Encoding.UTF8); } /// <summary> /// Loads the specified manifest resource from the specified assembly as a string. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <returns>The string of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string ReadAllText(Assembly assembly, string path) { return ReadAllText(assembly, path, Encoding.UTF8); } /// <summary> /// Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// as a string. /// </summary> /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <returns>The string of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/> or <paramref name="name"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string ReadAllText(Type type, string name) { return ReadAllText(type, name, Encoding.UTF8); } #endregion #region ReadAllText (Encoding) /// <summary> /// Loads the specified manifest resource from the calling assembly as a string. /// </summary> /// <param name="path">The resource path.</param> /// <param name="encoding">The encoding applied to the contents of the resource.</param> /// <returns>The string of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> or <paramref name="encoding"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string ReadAllText(string path, Encoding encoding) { return ReadAllText(Assembly.GetCallingAssembly(), path, encoding); } /// <summary> /// Loads the specified manifest resource from the specified assembly as a string. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <param name="encoding">The encoding applied to the contents of the resource.</param> /// <returns>The string of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/>, <paramref name="path"/>, or <paramref name="encoding"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string ReadAllText(Assembly assembly, string path, Encoding encoding) { using (Stream stream = Open(assembly, path)) using (StreamReader reader = new StreamReader(stream, encoding)) return reader.ReadToEnd(); } /// <summary> /// Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// as a string. /// </summary> /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <param name="encoding">The encoding applied to the contents of the resource.</param> /// <returns>The string of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/>, <paramref name="name"/>, or <paramref name="encoding"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string ReadAllText(Type type, string name, Encoding encoding) { using (Stream stream = Open(type, name)) using (StreamReader reader = new StreamReader(stream, encoding)) return reader.ReadToEnd(); } #endregion #region ReadAllLines /// <summary> /// Loads the specified manifest resource from the calling assembly as a string array of lines. /// </summary> /// <param name="path">The resource path.</param> /// <returns>The string array of lines of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string[] ReadAllLines(string path) { return ReadAllLines(Assembly.GetCallingAssembly(), path, Encoding.UTF8); } /// <summary> /// Loads the specified manifest resource from the specified assembly as a string array of lines. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <returns>The string array of lines of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string[] ReadAllLines(Assembly assembly, string path) { return ReadAllLines(assembly, path, Encoding.UTF8); } /// <summary> /// Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// as a string array of lines. /// </summary> /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <returns>The string array of lines of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/> or <paramref name="name"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string[] ReadAllLines(Type type, string name) { return ReadAllLines(type, name, Encoding.UTF8); } #endregion #region ReadAllLines (Encoding) /// <summary> /// Loads the specified manifest resource from the calling assembly as a string array of lines. /// </summary> /// <param name="path">The resource path.</param> /// <param name="encoding">The encoding applied to the contents of the resource.</param> /// <returns>The string array of lines of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> or <paramref name="encoding"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string[] ReadAllLines(string path, Encoding encoding) { return ReadAllLines(Assembly.GetCallingAssembly(), path, encoding); } /// <summary> /// Loads the specified manifest resource from the specified assembly as a string array of lines. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <param name="encoding">The encoding applied to the contents of the resource.</param> /// <returns>The string array of lines of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/>, <paramref name="path"/>, or <paramref name="encoding"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string[] ReadAllLines(Assembly assembly, string path, Encoding encoding) { using (Stream stream = Open(assembly, path)) using (StreamReader reader = new StreamReader(stream, encoding)) { string line; List<string> lines = new List<string>(); while ((line = reader.ReadLine()) != null) lines.Add(line); return lines.ToArray(); } } /// <summary> /// Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// as a string array of lines. /// </summary> /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <param name="encoding">The encoding applied to the contents of the resource.</param> /// <returns>The string array of lines of the resource's data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/>, <paramref name="name"/>, or <paramref name="encoding"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static string[] ReadAllLines(Type type, string name, Encoding encoding) { using (Stream stream = Open(type, name)) using (StreamReader reader = new StreamReader(stream, encoding)) { string line; List<string> lines = new List<string>(); while ((line = reader.ReadLine()) != null) lines.Add(line); return lines.ToArray(); } } #endregion #region SaveToFile /// <summary> /// Saves the specified manifest resource from the calling assembly to the specified file. /// </summary> /// <param name="path">The resource path.</param> /// <param name="file">The path of the file to save the resource to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> or <paramref name="file"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static void SaveToFile(string path, string file) { SaveToFile(Assembly.GetCallingAssembly(), path, file); } /// <summary> /// Saves the specified manifest resource from the specified assembly to the specified file. /// </summary> /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <param name="file">The path of the file to save the resource to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/>, <paramref name="path"/>, or <paramref name="file"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static void SaveToFile(Assembly assembly, string path, string file) { using (Stream inStream = Open(assembly, path)) using (FileStream outStream = File.Create(file)) inStream.CopyTo(outStream); } /// <summary> /// Saves the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// to the specified file. /// </summary> /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <param name="file">The path of the file to save the resource to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/>, <paramref name="name"/>, or <paramref name="file"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static void SaveToFile(Type type, string name, string file) { using (Stream inStream = Open(type, name)) using (FileStream outStream = File.Create(file)) inStream.CopyTo(outStream); } #endregion #region SaveToStream /// <summary> /// Saves the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// to the specified stream. /// </summary> /// /// <param name="path">The resource path.</param> /// <param name="stream">The stream to save the resource to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> or <paramref name="stream"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static void SaveToStream(string path, Stream stream) { SaveToStream(Assembly.GetCallingAssembly(), path, stream); } /// <summary> /// Saves the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// to the specified stream. /// </summary> /// /// <param name="assembly">The assembly to load the resource from.</param> /// <param name="path">The resource path.</param> /// <param name="stream">The stream to save the resource to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/>, <paramref name="path"/>, or <paramref name="stream"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static void SaveToStream(Assembly assembly, string path, Stream stream) { using (Stream inStream = Open(assembly, path)) inStream.CopyTo(stream); } /// <summary> /// Saves the specified manifest resource, scoped by the namespace of the specified type, from this assembly /// to the specified stream. /// </summary> /// /// <param name="type">The type whose namespace is used to scope the manifest resource name.</param> /// <param name="name">The case-sensitive name of the manifest resource being requested.</param> /// <param name="stream">The stream to save the resource to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="type"/>, <paramref name="name"/>, or <paramref name="stream"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> /// <exception cref="ResourceNotFoundException"> /// The resource could not be located. /// </exception> public static void SaveToStream(Type type, string name, Stream stream) { using (Stream inStream = Open(type, name)) inStream.CopyTo(stream); } #endregion #region Combine /// <summary> /// Combines the embedded paths with a '.' separating each part and trimming '.'s. /// </summary> /// /// <param name="paths">The paths to combine.</param> /// <returns>The combined resource path.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="paths"/> or any of its values are null. /// </exception> /// <exception cref="ArgumentException"> /// One of <paramref name="paths"/>'s values is an empty string. /// </exception> public static string Combine(params string[] paths) { foreach (string path in paths) CombineCheckPath(path); return string.Join(".", paths); //return string.Join(".", paths.Select(p => CheckPath(p))); } /// <summary> /// Combines the embedded paths with a '.' separating each part and trimming '.'s. /// </summary> /// /// <param name="paths">The paths to combine.</param> /// <returns>The combined resource path.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="paths"/> or any of its values are null. /// </exception> /// <exception cref="ArgumentException"> /// One of <paramref name="paths"/>'s values is an empty string. /// </exception> public static string Combine(IEnumerable<string> paths) { return string.Join(".", paths.Select(p => CombineCheckPath(p))); } /// <summary> /// Combines the embedded paths with a '.' separating each part and trimming '.'s. /// </summary> /// /// <param name="startPath">The first path to add.</param> /// <param name="paths">The remaining paths to add.</param> /// <returns>The combined resource path.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="startPath"/> or <paramref name="paths"/> or any of its values are null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="startPath"/> or one of <paramref name="paths"/>'s values is an empty string. /// </exception> public static string Combine(string startPath, IEnumerable<string> paths) { paths = new[] { startPath }.Concat(paths); //paths = paths.Prepend(startPath); return string.Join(".", paths.Select(p => CombineCheckPath(p))); } #endregion #region CombineIgnoreNull /// <summary> /// Combines the embedded paths with a '.' separating each part and trimming '.'s. Ignores all null strings. /// </summary> /// /// <param name="paths">The paths to combine.</param> /// <returns>The combined resource path.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="paths"/> is null. /// </exception> public static string CombineIgnoreNull(params string[] paths) { return CombineIgnoreNull((IEnumerable<string>) paths); } /// <summary> /// Combines the embedded paths with a '.' separating each part and trimming '.'s. Ignores all null strings. /// </summary> /// /// <param name="paths">The paths to combine.</param> /// <returns>The combined resource path.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="paths"/> is null. /// </exception> public static string CombineIgnoreNull(IEnumerable<string> paths) { paths = paths.Where(p => p != null); return string.Join(".", paths.Select(p => CombineCheckPath(p))); } /// <summary> /// Combines the embedded paths with a '.' separating each part and trimming '.'s. Ignores all null strings. /// </summary> /// /// <param name="startPath">The first path to add.</param> /// <param name="paths">The remaining paths to add.</param> /// <returns>The combined resource path.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="paths"/> is null. /// </exception> public static string CombineIgnoreNull(string startPath, IEnumerable<string> paths) { paths = new[] { startPath }.Concat(paths).Where(p => p != null); //paths = paths.Prepend(startPath).Where(p => p != null); return string.Join(".", paths.Select(p => CombineCheckPath(p))); } #endregion #region Private /// <summary> /// Performs a null or empty check of the path during <see cref="Combine"/> and /// <see cref="CombineIgnoreNull"/>. /// </summary> /// <param name="path">The path to check.</param> /// <returns>The same string that was passed in.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string. /// </exception> private static string CombineCheckPath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException($"{nameof(path)} is an empty or whitespace string!"); return path; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Extension_Methods_Delegates_Lambda_LINQ { /// <summary> /// Problem 7. Timer /// Using delegates write a class Timer that can execute certain method at each t seconds. /// </summary> class Timer { System.Timers.Timer timer; public delegate void MyMethodsDelegate(); private MyMethodsDelegate funcs; public Timer(int seconds) { timer = new System.Timers.Timer(seconds * 1000); } public void Start() { timer.Start(); timer.Elapsed += timer_Elapsed; } private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (funcs != null) { funcs(); } } public void Stop() { timer.Stop(); } public void AddDelegate(MyMethodsDelegate d) { funcs += d; } } }
using System; using System.Globalization; namespace FileSearch { public static class MeasurementUnitConverters { public static string Formatbytes(long bytes) { string filesize; if (bytes >= 1073741824) { decimal size = decimal.Divide(bytes, 1073741824); filesize = string.Format(CultureInfo.CurrentCulture, "{0:##.##} GB", size); } else if (bytes >= 1048576) { decimal size = decimal.Divide(bytes, 1048576); filesize = string.Format(CultureInfo.CurrentCulture, "{0:##.##} MB", size); } else if (bytes >= 1024) { decimal size = decimal.Divide(bytes, 1024); filesize = string.Format(CultureInfo.CurrentCulture, "{0:##.##} KB", size); } else if (bytes > 0 & bytes < 1024) { decimal size = bytes; filesize = string.Format(CultureInfo.CurrentCulture, "{0:##.##} Bytes", size); } else { filesize = "0 Bytes"; } return filesize.PadLeft(8); } public static decimal BytesPerSecond(long bytes, TimeSpan time) { return Convert.ToDecimal(bytes / (time.TotalMilliseconds * 0.001d), new NumberFormatInfo { NumberDecimalDigits = 3 }); } public static decimal MegaBytesPerSecond(long bytes, TimeSpan time) { return BytesPerSecond(bytes / (1024 * 1024), time); } public static decimal FilesPerSecond(long fileCount, TimeSpan time) { var seconds = time.TotalMilliseconds * 0.001d; return Convert.ToDecimal(fileCount / seconds, new NumberFormatInfo { NumberDecimalDigits = 3 }); } } }
using BeatmapAssetMaker; using NUnit.Framework; using QuestomAssets.AssetsChanger; using QuestomAssets.Models; using QuestomAssets.Utils; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; namespace QuestomAssets.Tests { public class FolderAssetsTestNotCombined : FolderAssetsTestCombined { protected override IFileProvider GetProvider() { return new FolderFileProvider($".\\TestAssets{TestRandomNum}\\", false, true); } } }
using UnityEngine; using System.Collections; using SimpleJSON; using UnityEngine.Networking; public class WeatherAPI : MonoBehaviour { //public string url = "http://api.openweathermap.org/data/2.5/weather?q=melbourne&APPID=09c983f6e8fc5eebb04bfe1cf1b42e27"; //public string url = "http://api.openweathermap.org/data/2.5/weather?id=2158177&APPID=446e2655762a7411c97c9da1916d5c96"; //public string url = "http://api.openweathermap.org/data/2.5/weather?lat=12.9716&lon=77.5946&APPID=446e2655762a7411c97c9da1916d5c96"; public ParticleSystem particleLauncher; public ParticleSystem particleLauncher1; public GameObject swipy; public GameObject cuby; public string city; public string country; public string weatherDescription; public float temp; public float temp_min; public float temp_max; public float rain; public float wind; public float clouds; public GameObject y20; public GameObject y19; public float aqi; // Use this for initialization IEnumerator Start () { //WWW request = new WWW(url); //yield return request; UnityWebRequest lalala = UnityWebRequest.Get("https://api.breezometer.com/air-quality/v2/current-conditions?lat=-37.8136&lon=144.9631&key=c750f0c3b1674a7bab19dde8f3e6d176&features=breezometer_aqi,local_aqi"); yield return lalala.SendWebRequest(); /* if (request.error == null || request.error == "") { setWeatherAttributes(request.text); Debug.Log("blahhhh"); } else { Debug.Log("Error: " + request.error); } */ if (lalala.isNetworkError || lalala.isHttpError) { Debug.Log(lalala.error); } else { // Show results as text setPollutionAttributes(lalala.downloadHandler.text); Debug.Log(" Result: "+lalala.downloadHandler.text); // Or retrieve results as binary data byte[] results = lalala.downloadHandler.data; } } // Update is called once per frame void Update () { } void setWeatherAttributes(string jsonString) { var weatherJson = JSON.Parse(jsonString); city = weatherJson["name"].Value; Debug.Log("city" + city); country = weatherJson["sys"]["country"].Value; weatherDescription = weatherJson["weather"][0]["description"].Value; temp = weatherJson["main"]["temp"].AsFloat; temp_min = weatherJson["main"]["temp_min"].AsFloat; temp_max = weatherJson["main"]["temp_max"].AsFloat; rain = weatherJson["rain"]["3h"].AsFloat; clouds = weatherJson["clouds"]["all"].AsInt; wind = weatherJson["wind"]["speed"].AsFloat; } void setPollutionAttributes(string jsonString) { var pollJson = JSON.Parse(jsonString); aqi = pollJson["data"]["indexes"]["baqi"]["aqi"].AsFloat; Debug.Log("The Air Quality Index of Melb is: " + aqi); } public void emitter() { particleLauncher.Emit((int)aqi*20); particleLauncher1.Emit((int)aqi * 80); Destroy(cuby); } private void OnMouseDown() { particleLauncher.Emit((int)aqi); Destroy(cuby); } private void Awake() { SwipeDetector.OnSwipe += SwipeDetector_OnSwipe; } private void SwipeDetector_OnSwipe(SwipeData data) { Debug.Log("Swipe in Direction: " + data.Direction); if (data.Direction == SwipeDirection.Left) { //2019 Debug.Log("yeeee it works"); //particleLauncher.Emit((int)aqi * 20); particleLauncher.Emit(1000); //particleLauncher1.Emit((int)aqi * 80); y19.SetActive(true); y20.SetActive(false); swipy.SetActive(false); } if (data.Direction == SwipeDirection.Right) { //2020 Debug.Log("yeeee it works"); particleLauncher.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear); particleLauncher1.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear); particleLauncher.Emit(600); //particleLauncher.Emit((int)aqi); //particleLauncher1.Emit((int)aqi); y19.SetActive(false); y20.SetActive(true); swipy.SetActive(false); } } } //EXAMPLE RESPONSE OBJECT //{"coord":{"lon":139,"lat":35}, // "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049}, // "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}], // "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04}, // "wind":{"speed":7.31,"deg":187.002}, // "rain":{"3h":0}, // "clouds":{"all":92}, // "dt":1369824698, // "id":1851632, // "name":"Shuzenji", // "cod":200}
using System; using UnityEngine; [Serializable] public class pb_Vector2 { public float x; public float y; public pb_Vector2(Vector2 v) { this.x = v.x; this.y = v.y; } public static implicit operator Vector2(pb_Vector2 v) { return new Vector2(v.x, v.y); } public static implicit operator pb_Vector2(Vector2 v) { return new pb_Vector2(v); } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("NAX01_AnubRekhan")] public class NAX01_AnubRekhan : NAX_MissionEntity { public NAX01_AnubRekhan(IntPtr address) : this(address, "NAX01_AnubRekhan") { } public NAX01_AnubRekhan(IntPtr address, string className) : base(address, className) { } public void InitEmoteResponses() { base.method_8("InitEmoteResponses", Array.Empty<object>()); } public void PreloadAssets() { base.method_8("PreloadAssets", Array.Empty<object>()); } public bool m_heroPowerLinePlayed { get { return base.method_2<bool>("m_heroPowerLinePlayed"); } } public bool m_locustSwarmLinePlayed { get { return base.method_2<bool>("m_locustSwarmLinePlayed"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data; using Com.Cdi.Merp.Web; using System.Web.Script.Services; using Newtonsoft.Json; /// <summary> /// CommonWebService의 요약 설명입니다. /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class Common : System.Web.Services.WebService { public Common() { //디자인된 구성 요소를 사용하는 경우 다음 줄의 주석 처리를 제거합니다. //InitializeComponent(); } #region Login [WebMethod] public Results login(Staffs staff) { if (HttpContext.Current.Request.Cookies["c_stf"] != null) { HttpCookie cookie = new HttpCookie("c_stf"); cookie.Expires = DateTime.Now.AddDays(-100); HttpContext.Current.Response.Cookies.Add(cookie); } Results results = new Results(); string stf_login_id = staff.stf_login_id; string stf_password = staff.stf_password; Com.Cdi.Merp.Biz.Contents.Common _login = new Com.Cdi.Merp.Biz.Contents.Common(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnType = string.Empty; string remote_address = IP_Filter.GetIP(); ds = new DataSet(); ds = _login.login(stf_login_id, stf_password, ref rtnStatus, ref rtnMessage, ref rtnType); if (!IP_Filter.GetIsAccessIP(remote_address)) { rtnType = "3"; rtnStatus = "failed"; } else if (ds == null) { rtnStatus = "failed"; rtnMessage = "meg_error"; } else if(ds.Tables[0].Rows.Count == 0) { rtnStatus = "failed"; rtnMessage = "msg_login_failed"; } else { string _stf_id = Convert.ToString(ds.Tables[0].Rows[0]["stf_id"]); string _stf_firstname = Convert.ToString(ds.Tables[0].Rows[0]["stf_firstname"]); string _stf_lastname = Convert.ToString(ds.Tables[0].Rows[0]["stf_lastname"]); string _stf_isteacher = Convert.ToString(ds.Tables[0].Rows[0]["stf_isteacher"]); string _brch_iscdi = Convert.ToString(ds.Tables[0].Rows[0]["brch_iscdi"]); string _brch_iscenter = Convert.ToString(ds.Tables[0].Rows[0]["brch_iscenter"]); string _stf_login_id = Convert.ToString(ds.Tables[0].Rows[0]["stf_login_id"]); int _chk_team_leader = Convert.ToInt32(ds.Tables[0].Rows[0]["chk_team_leader"]); int cnt_cdi = Convert.ToInt32(ds.Tables[1].Rows[0]["cnt_cdi"]); int cnt_april = Convert.ToInt32(ds.Tables[1].Rows[0]["cnt_april"]); int cnt_qc = Convert.ToInt32(ds.Tables[1].Rows[0]["cnt_qc"]); string _brandGubun = string.Empty; if (cnt_april > 0 && cnt_cdi > 0) _brandGubun = "B"; else if (cnt_april > 0) _brandGubun = "A"; else if (cnt_cdi > 0) _brandGubun = "C"; if(_brch_iscenter.ToUpper() == "TRUE") _brandGubun = "B"; if (cnt_qc > 0) _brandGubun = "Q"; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); // 로그인 처리 진행 Staffs staff_info = new Staffs(); staff_info.stf_id = Convert.ToInt32(_stf_id); staff_info.stf_firstname = HttpUtility.UrlEncode(_stf_firstname); staff_info.stf_lastname = HttpUtility.UrlEncode(_stf_lastname); staff_info.stf_isteacher = _stf_isteacher.ToUpper() == "TRUE" ? 1 : 0; staff_info.brch_iscdi = _brch_iscdi.ToUpper() == "TRUE" ? 1 : 0; staff_info.brch_iscenter = _brch_iscenter.ToUpper() == "TRUE" ? 1 : 0; staff_info.brandGubun = _brandGubun; staff_info.stf_login_id = _stf_login_id; staff_info.chk_team_leader = _chk_team_leader; if (staff_info.brch_iscenter > 0 && _stf_isteacher.ToUpper().Equals("FALSE")) staff_info.brandGubun = "HQ"; HttpCookie cookie_staff = new HttpCookie("c_stf", HttpUtility.UrlEncode(serializer.Serialize(staff_info))); HttpContext.Current.Response.SetCookie(cookie_staff); if (_stf_isteacher.ToUpper().Equals("TRUE")) { DataSet ds_class = new DataSet(); ds_class = _login.getInsFirstClass(_stf_id, ref rtnStatus, ref rtnMessage); if (ds_class.Tables[0].Rows.Count > 0) { ClassSearch class_search = new ClassSearch(); class_search.brch_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["brch_id"]); class_search.bsem_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["bsem_id"]); class_search.cls_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["cls_id"]); class_search.cls_name = Convert.ToString(ds_class.Tables[0].Rows[0]["cls_name"]); class_search.cjrn_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["cjrn_id"]); class_search.cjsec_section_type = Convert.ToInt32(ds_class.Tables[0].Rows[0]["cjsec_section_type"]); class_search.classdate = Convert.ToString(ds_class.Tables[0].Rows[0]["classdate"]); class_search.classdatetime = Convert.ToString(ds_class.Tables[0].Rows[0]["cjsec_start_time"]); HttpCookie cookie_class = new HttpCookie("c_cls", HttpUtility.UrlEncode(serializer.Serialize(class_search))); HttpContext.Current.Response.SetCookie(cookie_class); } } DataSet dsCheckPassword = _login.checkChangePassword(Convert.ToInt32(_stf_id)); if (dsCheckPassword != null && dsCheckPassword.Tables.Count > 0 && dsCheckPassword.Tables[0].Rows.Count > 0 && dsCheckPassword.Tables[0].Rows[0]["ischeck"].ToString() == "Y") rtnType = "2"; // 로그인로그 저장 _login.InsertLogin("M2ERP", Convert.ToInt32(_stf_id), "H", HttpContext.Current.Request.ServerVariables["HTTP_REFERER"], IP_Filter.GetIP(), HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"], HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"]); } results.result = rtnStatus; results.message = rtnMessage; results.type = rtnType; return results; } [WebMethod] public Results autoLogin(Login login) { if (HttpContext.Current.Request.Cookies["c_stf"] != null) { HttpCookie cookie = new HttpCookie("c_stf"); cookie.Expires = DateTime.Now.AddDays(-100); HttpContext.Current.Response.Cookies.Add(cookie); } Results results = new Results(); int stf_id = login.stf_id; string menu = login.menu; Com.Cdi.Merp.Biz.Contents.Common _login = new Com.Cdi.Merp.Biz.Contents.Common(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnType = string.Empty; ds = new DataSet(); ds = _login.autoLogin(stf_id, ref rtnStatus, ref rtnMessage, ref rtnType); if (ds == null) { rtnStatus = "failed"; rtnMessage = "meg_error"; } else if (ds.Tables[0].Rows.Count == 0) { rtnStatus = "failed"; rtnMessage = "msg_login_failed"; } else { string _stf_id = Convert.ToString(ds.Tables[0].Rows[0]["stf_id"]); string _stf_firstname = Convert.ToString(ds.Tables[0].Rows[0]["stf_firstname"]); string _stf_lastname = Convert.ToString(ds.Tables[0].Rows[0]["stf_lastname"]); string _stf_isteacher = Convert.ToString(ds.Tables[0].Rows[0]["stf_isteacher"]); string _brch_iscdi = Convert.ToString(ds.Tables[0].Rows[0]["brch_iscdi"]); string _brch_iscenter = Convert.ToString(ds.Tables[0].Rows[0]["brch_iscenter"]); string _stf_login_id = Convert.ToString(ds.Tables[0].Rows[0]["stf_login_id"]); int cnt_cdi = Convert.ToInt32(ds.Tables[1].Rows[0]["cnt_cdi"]); int cnt_april = Convert.ToInt32(ds.Tables[1].Rows[0]["cnt_april"]); int cnt_qc = Convert.ToInt32(ds.Tables[1].Rows[0]["cnt_qc"]); string _brandGubun = string.Empty; if (cnt_april > 0 && cnt_cdi > 0) _brandGubun = "B"; else if (cnt_april > 0) _brandGubun = "A"; else if (cnt_cdi > 0) _brandGubun = "C"; if (_brch_iscenter.ToUpper() == "TRUE") _brandGubun = "B"; if (cnt_qc > 0) _brandGubun = "Q"; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); // 로그인 처리 진행 Staffs staff_info = new Staffs(); staff_info.stf_id = Convert.ToInt32(_stf_id); staff_info.stf_firstname = HttpUtility.UrlEncode(_stf_firstname); staff_info.stf_lastname = HttpUtility.UrlEncode(_stf_lastname); staff_info.stf_isteacher = _stf_isteacher.ToUpper() == "TRUE" ? 1 : 0; staff_info.brch_iscdi = _brch_iscdi.ToUpper() == "TRUE" ? 1 : 0; staff_info.brch_iscenter = _brch_iscenter.ToUpper() == "TRUE" ? 1 : 0; staff_info.brandGubun = _brandGubun; staff_info.stf_login_id = _stf_login_id; HttpCookie cookie_staff = new HttpCookie("c_stf", HttpUtility.UrlEncode(serializer.Serialize(staff_info))); HttpContext.Current.Response.SetCookie(cookie_staff); if (_stf_isteacher.ToUpper().Equals("TRUE")) { DataSet ds_class = new DataSet(); ds_class = _login.getInsFirstClass(_stf_id, ref rtnStatus, ref rtnMessage); if (ds_class.Tables[0].Rows.Count > 0) { ClassSearch class_search = new ClassSearch(); class_search.brch_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["brch_id"]); class_search.bsem_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["bsem_id"]); class_search.cls_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["cls_id"]); class_search.cls_name = Convert.ToString(ds_class.Tables[0].Rows[0]["cls_name"]); class_search.cjrn_id = Convert.ToInt32(ds_class.Tables[0].Rows[0]["cjrn_id"]); class_search.cjsec_section_type = Convert.ToInt32(ds_class.Tables[0].Rows[0]["cjsec_section_type"]); class_search.classdate = Convert.ToString(ds_class.Tables[0].Rows[0]["classdate"]); class_search.classdatetime = Convert.ToString(ds_class.Tables[0].Rows[0]["cjsec_start_time"]); HttpCookie cookie_class = new HttpCookie("c_cls", HttpUtility.UrlEncode(serializer.Serialize(class_search))); HttpContext.Current.Response.SetCookie(cookie_class); } } } results.result = rtnStatus; results.message = rtnMessage; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results ipCheck(Staffs staff) { Results results = new Results(); string rtnStatus = string.Empty; string rtnMessage = string.Empty; string remote_address = IP_Filter.GetIP(); if (!IP_Filter.GetIsAccessIP(remote_address)) rtnStatus = "failed"; else rtnStatus = "ok"; results.status = rtnStatus; results.message = rtnMessage; return results; } #endregion [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results staffImage(Staffs staff) { int stf_id = staff.stf_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.staffImageSrc(stf_id, ref rtnStatus, ref rtnMessage); string staffImagePath = System.Configuration.ConfigurationManager.AppSettings["URL_STAFF_IMAGE"].ToString(); if (ds == null || ds.Tables[0].Rows.Count == 0) { results.result = "/assets/img/avatar.png"; } else { results.result = staffImagePath + Convert.ToString(ds.Tables[0].Rows[0]["stf_image"]); } } catch (Exception ex) { results.result = "/assets/img/avatar.png"; } results.status = rtnStatus; results.message = rtnMessage; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results getConfig(List<Dictionary<string, string>> appKeys) { Results results = new Results(); string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); try { List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>(); Dictionary<string, string> row; row = new Dictionary<string, string>(); foreach (Dictionary<string, string> appkey in appKeys) { foreach (var list in appkey.Values) { row.Add(list, System.Configuration.ConfigurationManager.AppSettings[list].ToString()); } } rows.Add(row); rtnStatus = "ok"; rtnJsonString = serializer.Serialize(rows); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results codeTable(Codetable codeTable) { string code_type = codeTable.code_type; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.getCodeTable(code_type, ref rtnStatus, ref rtnMessage); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } #region navigation [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results navigation(Staffs staff) { int stf_id = staff.stf_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.getNavigation(stf_id, ref rtnStatus, ref rtnMessage); if (ds != null && ds.Tables.Count > 0) { List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); Dictionary<string, object> row; foreach (DataRow dr in ds.Tables[0].Rows) { row = new Dictionary<string, object>(); foreach (DataColumn col in ds.Tables[0].Columns) { row.Add(col.ColumnName, dr[col]); } rows.Add(row); } rtnJsonString = serializer.Serialize(rows); } } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } #endregion #region appDownloads [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results appDownloads(Staffs staff) { int stf_id = staff.stf_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.getAppDownloads(stf_id, ref rtnStatus, ref rtnMessage); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } #endregion #region Message [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results messageList(Staffs staff, Message message) { int stf_id = staff.stf_id; string sdate = message.sdate; string edate = message.edate; string msg_name = message.msg_name; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; string rtnType = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.getMessageList(stf_id, sdate, edate, msg_name, ref rtnStatus, ref rtnMessage, ref rtnType); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results messageView(Message message) { int mmem_id = message.mmem_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; string rtnType = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.getMessageView(mmem_id, ref rtnStatus, ref rtnMessage, ref rtnType); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results messageDelete(Message message) { int mmem_id = message.mmem_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; string rtnType = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.setMessageDelete(mmem_id, ref rtnStatus, ref rtnMessage, ref rtnType); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results messageSend(Message message, Staffs staff) { string msg_name = message.msg_name; string msg_note = message.msg_note; bool msg_high_priority = message.msg_high_priority; string to_stf_id = message.to_stf_id; int stf_id = staff.stf_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; string rtnType = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.setMessageSend(msg_name, msg_note, msg_high_priority, to_stf_id, stf_id, ref rtnStatus, ref rtnMessage, ref rtnType); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results messageProc(Message message, List<Message> messages) { string proc = message.proc; int[] mmem_id = new int[messages.Count]; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; string rtnType = string.Empty; try { for (int i = 0; i < messages.Count; i++) { mmem_id[i] = messages[i].mmem_id; } Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); int rtn = _common.setMessageProc(mmem_id, proc); if (rtn == messages.Count) rtnStatus = "ok"; } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } #endregion #region Profile [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results profile(Staffs staff) { int stf_id = staff.stf_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; string rtnType = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.getProfile(stf_id,ref rtnStatus, ref rtnMessage, ref rtnType); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Results setProfile(Staffs staff) { string stf_gender = staff.stf_gender; string stf_birthday = staff.stf_birthday; string stf_nickname = staff.stf_nickname; string stf_handphone = staff.stf_handphone; string stf_homephone = staff.stf_homephone; string stf_nationality = staff.stf_nationality; string stf_email = staff.stf_email; string stf_homepage = staff.stf_homepage; int stf_id = staff.stf_id; Results results = new Results(); DataSet ds = null; string rtnStatus = string.Empty; string rtnMessage = string.Empty; string rtnJsonString = string.Empty; string rtnType = string.Empty; try { Com.Cdi.Merp.Biz.Contents.Common _common = new Com.Cdi.Merp.Biz.Contents.Common(); ds = new DataSet(); ds = _common.setProfile(stf_gender, stf_birthday, stf_nickname, stf_handphone, stf_homephone, stf_nationality, stf_email, stf_homepage, stf_id, ref rtnStatus, ref rtnMessage, ref rtnType); rtnJsonString = JsonConvert.SerializeObject(ds); } catch (Exception ex) { throw ex; } results.status = rtnStatus; results.message = rtnMessage; results.result = rtnJsonString; return results; } #endregion }
using FacultyV3.Core.Interfaces; using FacultyV3.Core.Interfaces.IServices; using FacultyV3.Core.Models.Entities; using FacultyV3.Core.Models.Enums; using FacultyV3.Core.Utilities; using Microsoft.Security.Application; using PagedList; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace FacultyV3.Core.Services { public class AccountService : IAccountService { private IDataContext context; public AccountService(IDataContext context) { this.context = context; } public IEnumerable<Account> PageList(string name, int page, int pageSize) { if (!string.IsNullOrEmpty(name)) { return context.Accounts.Where(x => x.FullName.Contains(name)).OrderBy(x => x.FullName).ToPagedList(page, pageSize); } return context.Accounts.Include(x => x.Role).OrderBy(x => x.FullName).ToPagedList(page, pageSize); } public Account GetAccountByID(string id) { try { Guid ID = new Guid(id); return context.Accounts.Include(x => x.Role).Where(x => x.Id == ID).SingleOrDefault(); } catch (Exception) { } return null; } public Account GetEmail(string email) { try { return context.Accounts.Include(x => x.Role).Where(x => x.Email.Equals(email)).SingleOrDefault(); } catch (Exception) { } return null; } public Account GetAccountByEmail(string email) { try { return context.Accounts.Include(x => x.Role).Where(x => x.Email.Contains(email)).SingleOrDefault(); } catch (Exception) { } return null; } public List<Account> GetAccounts() { try { return context.Accounts.Include(x => x.Role).Select(x => x).OrderBy(x => x.Email).ToList(); } catch (Exception) { } return null; } public LoginAttemptStatus LastLoginStatus { get; private set; } = LoginAttemptStatus.LoginSuccessful; public bool ValidateUser(string email, string password) { email = Sanitizer.GetSafeHtmlFragment(email); password = Sanitizer.GetSafeHtmlFragment(password); LastLoginStatus = LoginAttemptStatus.LoginSuccessful; var user = GetEmail(email); if (user == null) { LastLoginStatus = LoginAttemptStatus.UserNotFound; return false; } var passwordMatches = Hash.Instance.ComputeSha256Hash(password) == user.Password; if (!passwordMatches) { LastLoginStatus = LoginAttemptStatus.PasswordIncorrect; return false; } return LastLoginStatus == LoginAttemptStatus.LoginSuccessful; } } }
 using Dapper; using Dapper.Contrib.Extensions; using System.Collections.Generic; namespace Dados.Data { public abstract class AbstractRepository<T> where T : class, new() { #region Instancias protected Connection<T> conexao = new Connection<T>(); #endregion #region Métodos publicos public virtual long Insert(T t) { return GlobalConnection.Connection.Insert<T>(t); } public virtual bool Atualizar(T t) { return GlobalConnection.Connection.Update<T>(t); } public virtual bool Delete(T t) { return GlobalConnection.Connection.Delete<T>(t); } public virtual List<T> GetAll() { return GlobalConnection.Connection.GetAll<T>().AsList(); } public virtual T Get(int codigo) { return GlobalConnection.Connection.Get<T>(codigo); } #endregion } }
using System; using System.Collections.Generic; using DesiClothing4u.Common.Models; #nullable disable namespace DesiClothing4u.Common.Models { //[Serializable] public partial class Customer { public Customer() { //ActivityLogs = new HashSet<ActivityLog>(); //BackInStockSubscriptions = new HashSet<BackInStockSubscription>(); //CustomerAddresses = new HashSet<CustomerAddress>(); //CustomerCustomerRoleMappings = new HashSet<CustomerCustomerRoleMapping>(); //CustomerPasswords = new HashSet<CustomerPassword>(); //ExternalAuthenticationRecords = new HashSet<ExternalAuthenticationRecord>(); //Logs = new HashSet<Log>(); //NewsComments = new HashSet<NewsComment>(); //Orders = new HashSet<Order>(); //PollVotingRecords = new HashSet<PollVotingRecord>(); //ProductReviews = new HashSet<ProductReview>(); //ReturnRequests = new HashSet<ReturnRequest>(); //RewardPointsHistories = new HashSet<RewardPointsHistory>(); //ShoppingCartItems = new HashSet<ShoppingCartItem>(); } public int Id { get; set; } public string Username { get; set; } public string Email { get; set; } public string EmailToRevalidate { get; set; } public string SystemName { get; set; } public int? BillingAddressId { get; set; } public int? ShippingAddressId { get; set; } public Guid CustomerGuid { get; set; } public string AdminComment { get; set; } public bool IsTaxExempt { get; set; } public int AffiliateId { get; set; } public int VendorId { get; set; } public bool HasShoppingCartItems { get; set; } public bool RequireReLogin { get; set; } public int FailedLoginAttempts { get; set; } public DateTime? CannotLoginUntilDateUtc { get; set; } public bool Active { get; set; } public bool Deleted { get; set; } public bool IsSystemAccount { get; set; } public string LastIpAddress { get; set; } public DateTime CreatedOnUtc { get; set; } public DateTime? LastLoginDateUtc { get; set; } public DateTime LastActivityDateUtc { get; set; } public int RegisteredInStoreId { get; set; } public string Apitoken { get; set; } public string Password { get; set; } public virtual Address BillingAddress { get; set; } public virtual Address ShippingAddress { get; set; } //public virtual ICollection<ActivityLog> ActivityLogs { get; set; } //public virtual ICollection<BackInStockSubscription> BackInStockSubscriptions { get; set; } // public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; } //public virtual ICollection<CustomerCustomerRoleMapping> CustomerCustomerRoleMappings { get; set; } //public virtual ICollection<CustomerPassword> CustomerPasswords { get; set; } //public virtual ICollection<ExternalAuthenticationRecord> ExternalAuthenticationRecords { get; set; } //public virtual ICollection<Log> Logs { get; set; } //public virtual ICollection<NewsComment> NewsComments { get; set; } //public virtual ICollection<Order> Orders { get; set; } //public virtual ICollection<PollVotingRecord> PollVotingRecords { get; set; } //public virtual ICollection<ProductReview> ProductReviews { get; set; } //public virtual ICollection<ReturnRequest> ReturnRequests { get; set; } //public virtual ICollection<RewardPointsHistory> RewardPointsHistories { get; set; } //public virtual ICollection<ShoppingCartItem> ShoppingCartItems { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace fes.Models { public class ParsedViewModel { public List<ClaimHeaderTableViewModel> lsCHTVM; public ClaimFile cf; public ParsedViewModel() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BusinessLogic; using BusinessLogic.Common; using BusinessLogic.Exceptions; using DataAccess; namespace Mediathek_Webfrontend { public partial class MediaDetailMusic : System.Web.UI.Page { #region Fields /// <summary> /// Business logic handler instance /// </summary> private BusinessLogicHandler bl = new BusinessLogicHandler(); /// <summary> /// The ID of the currently displayed media /// </summary> private int mediaId; #endregion /// <summary> /// On page load /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { if (int.TryParse(Request.QueryString["mediaId"], out mediaId)) { FillMediaData(); SessionInfo session = (SessionInfo)Session[Constants.SessionInfo]; if (bl.IsReservationOpen(mediaId, session.UserId)) { this.ButReservation.Visible = false; this.LblAlreadyRes.Visible = true; } } else { Response.Redirect("MediaTypeSelection.aspx"); } } /// <summary> /// Get media data and display it in the page controls /// </summary> private void FillMediaData() { MediaMusic media = bl.GetMediaMusicById(mediaId); this.LblTitle.Text = media.Title; this.LblDesc.Text = media.Description; this.LblTag.Text = media.Tag; this.LblCat.Text = media.Category.Name; this.LblCreationDate.Text = media.CreationDate.ToShortDateString(); this.LblState.Text = media.MediaState.StateName; this.LblArtist .Text = media.Artist; this.LblGenre.Text = media.Genre; this.LblTrackList.Text = media.Tracklist; // display image if (media.Image != null) { this.ImgMedia.ImageUrl = "ShowMediaImage.ashx?mediaId=" + mediaId; } else { this.ImgMedia.Visible = false; } } /// <summary> /// Button "reservation" clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ButReservation_Click(object sender, EventArgs e) { SessionInfo session = (SessionInfo)Session[Constants.SessionInfo]; if (session != null && mediaId > 0) { try { // add new reservation bl.CreateReservation(mediaId, session.UserId); // refresh page to show reservation state Response.Redirect(Request.UrlReferrer.AbsolutePath + "?mediaId=" + mediaId); } catch (ConditionException ex) { this.LblError.Text = ex.Message; this.LblError.Visible = true; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace View.Game { /// <summary> /// Перечисление типов игроков /// </summary> public enum TypePlayer { Bot, Player, Dealer }; /// <summary> /// Класс игрока /// </summary> public class Player { public TypePlayer TypePlayer { get; set; } public string Name { get; set; } public Hand Hand { get; set; } public int Money { get; set; } public int Bet { get; set; } public Player() { Hand = new Game.Hand(); Money = 1000; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace CombatSim { class Program { //enemy count static int EnemiesLeft = 0; //life count static int BulletsLeft = 0; //money count static int MoneyLeft = 0; //if the user wants to stop playing static bool ContinuePlaying = true; //auto atk static int AutomaticFire = 0; //semi auto atk static int SemiAuto = 0; //chance for the current atk to do damage static int ChanceToHit = 0; //user select choice static int UserSelection = 0; //string to store if the user wants to keep playing static string KeepPlayingSelection = null; //only animate captions once static int CaptionCount = 0; //how much damage enemy does static int EnemyDamage = 0; //how many cities have been cleared //can go up infinitely static int CitiesCleared = 0; //how many cities have been lost //lost game at 5 cities lost static int CitiesLost = 0; //Confirm attack type static string UserConfirmation = null; //stats static int katanaAtk = 0; static int katanaDmg = 0; static int pistolAtk = 0; static int pistolDmg = 0; static int APDAtk = 0; static int APDDmg = 0; static int TacticalNuke = 0; //how many times to give payment static int MoneyIncrement = 0; //sets reinforcement max, scales with levels static int MaxReinforcement = 20; //tracks enemy kills for cash rewards static int enemiesKill = 0; //counts how many times user buys ammo during game static int buyAmmo = 0; //tracks total cash earned static int CashEarned = 0; //tracks whether grenade debuff is active or not static int grenade = 0; //tracks # of grenades purchased static int GrenadeUsage = 0; //base auto accuracy static int APDAccuracy = 30; //base katana accuracy static int KatAccuracy = 65; //implants buff on or off static int Implants = 0; //total implants purcased static int ImplantsTotal = 0; //increases difficutly static int EnemySpawnChance = 150; //increases enemy damage per round static int EnemyScalingDamage = 10; //increases money reward per ever 50 extra enemies every 2 rounds static int MoneyReward = 0; //counts current level static int LevelCounter = 1; static void Main(string[] args) { Random rand = new Random(); //set window size Console.WindowHeight = 69; //scroll text from top TitleScrollFromTop(); Console.Clear(); //basic hud template without data CityLogo(); TitleScroll(); //user prompt Console.WriteLine("\n Press Enter To Play: "); Console.ReadKey(); //StoryLine(); //set all initial gam values BulletsLeft = 100; EnemiesLeft = EnemySpawnChance; MoneyLeft = 50; //continue playing while (ContinuePlaying == true) { //while player is alive while (BulletsLeft > 0 && EnemiesLeft > 0) { //reset user selection each iteration UserSelection = 0; HeadsUpDisplay(); //prompt GameScreen(); //try to parse user input to int int.TryParse(Console.ReadLine(), out UserSelection); //checks case of user input CombatSelector(UserSelection); //adds money kill awards NewMoneyAdder(); //checks if implants are active if (Implants > 0) { //then reduce by 1 //implants are active for 5 rounds Implants--; } //implants deactivate, reset default values else if (Implants <= 0) { KatAccuracy = 65; APDAccuracy = 30; } } //if there are NO ENEMEIES LEFT or OUT OF LIFE while (EnemiesLeft <= 0 || BulletsLeft <= 0) { //bullets/enemies = 0 //keeps numbers from display negative if (BulletsLeft <= 0) { BulletsLeft = 0; } if (EnemiesLeft <= 0) { EnemiesLeft = 0; } //if user loses 3 cities game over if (CitiesLost == 3) { //give a value so that loop is broken BulletsLeft = 1; EnemiesLeft = 1; ContinuePlaying = false; GameOverAnimation(); } //User loses when 5 cities are lost else if (CitiesLost < 5) { //when enemies are all killed if (EnemiesLeft <= 0) { Console.ForegroundColor = ConsoleColor.DarkCyan; //you win! YouWinAnimation(); //ask if user keeps playing KeepPlaying(); //count number of cities cleared CitiesCleared++; //reset reward counter enemiesKill = 0; } //when the user runs ouf of bullets/life else if (BulletsLeft <= 0) { //does not display negative number BulletsLeft = 0; Console.ForegroundColor = ConsoleColor.DarkCyan; YouLose(); //ask if user wnats to keep playing KeepPlaying(); MoneyLeft = 50; BulletsLeft = 100; //reset money and ammo to default CitiesLost++; //reset reward counter enemiesKill = 0; //reset difficulty EnemySpawnChance = 150; EnemyScalingDamage = 15; EnemiesLeft = EnemySpawnChance; MaxReinforcement = 20; } //increases enemy difficulty Per Level if (CitiesCleared > 0) { EnemySpawnChance = EnemySpawnChance + 25; EnemyScalingDamage = EnemyScalingDamage + 5; EnemiesLeft = EnemySpawnChance; MaxReinforcement = MaxReinforcement + 5; } //Grants an extra 5 bucks per 50 extra enemies if (CitiesCleared > 0 && CitiesCleared % 2 == 0) { //earn an extra 5 bucks per 50 extra enemies MoneyReward += 5; //if there are a lot of enemies, more bonus if (EnemiesLeft > 250) { MoneyReward = MoneyReward + 5; } } LevelCounter = CitiesCleared + CitiesLost + 1; } } } //refresh display HeadsUpDisplay(); Stat(); string endingText = "\nThe world will continue on in darkness...\n ...until all of the Replicants are dead. "; //scroll text foreach (object c in endingText) { Console.Write(c); Thread.Sleep(40); } Console.ReadKey(); //Game Over GameOverAnimation(); Console.ReadKey(); } /// <summary> /// ask the user to keep playing /// </summary> public static void KeepPlaying() { Console.ForegroundColor = ConsoleColor.DarkCyan; //refrersh display HeadsUpDisplay(); //prompt KeepPlayingSelection = null; Console.WriteLine("\nTime to clear another city? Y/N"); while (KeepPlayingSelection == null) { Random rand = new Random(); KeepPlayingSelection = Console.ReadLine().ToUpper(); switch (KeepPlayingSelection) { //yes case "Y": //reset counters for new game //do not reset money, or bullets. //money is earned in the game break; //no case "N": // + 1 breaks out of input loop //playing = false breaks out of game loop ContinuePlaying = false; EnemiesLeft = 1; BulletsLeft = 1; break; default: //re prompt for real input Console.WriteLine("You must press Y or N to advance: "); KeepPlayingSelection = null; break; } } } /// <summary> /// YOU WIN!!! /// </summary> public static void YouWinAnimation() { int loopCount = 0; while (loopCount < 5) { Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(@" __ __ ______ __ __ __ __ ______ __ __ / \ / |/ \ / | / | / | _ / |/ |/ \ / | $$ \ /$$//$$$$$$ |$$ | $$ | $$ | / \ $$ |$$$$$$/ $$ \ $$ | $$ \/$$/ $$ | $$ |$$ | $$ | $$ |/$ \$$ | $$ | $$$ \$$ | $$ $$/ $$ | $$ |$$ | $$ | $$ /$$$ $$ | $$ | $$$$ $$ | $$$$/ $$ | $$ |$$ | $$ | $$ $$/$$ $$ | $$ | $$ $$ $$ | $$ | $$ \__$$ |$$ \__$$ | $$$$/ $$$$ | _$$ |_ $$ |$$$$ | $$ | $$ $$/ $$ $$/ $$$/ $$$ |/ $$ |$$ | $$$ | $$/ $$$$$$/ $$$$$$/ $$/ $$/ $$$$$$/ $$/ $$/ "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(@" __ __ ______ __ __ __ __ ______ __ __ | \ / \ / \ | \ | \ | \ _ | \| \| \ | \ \$$\ / $$| $$$$$$\| $$ | $$ | $$ / \ | $$ \$$$$$$| $$\ | $$ \$$\/ $$ | $$ | $$| $$ | $$ | $$/ $\| $$ | $$ | $$$\| $$ \$$ $$ | $$ | $$| $$ | $$ | $$ $$$\ $$ | $$ | $$$$\ $$ \$$$$ | $$ | $$| $$ | $$ | $$ $$\$$\$$ | $$ | $$\$$ $$ | $$ | $$__/ $$| $$__/ $$ | $$$$ \$$$$ _| $$_ | $$ \$$$$ | $$ \$$ $$ \$$ $$ | $$$ \$$$| $$ \| $$ \$$$ \$$ \$$$$$$ \$$$$$$ \$$ \$$ \$$$$$$ \$$ \$$ "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(@" $$\ $$\ $$$$$$\ $$\ $$\ $$\ $$\ $$$$$$\ $$\ $$\ \$$\ $$ |$$ __$$\ $$ | $$ | $$ | $\ $$ |\_$$ _|$$$\ $$ | \$$\ $$ / $$ / $$ |$$ | $$ | $$ |$$$\ $$ | $$ | $$$$\ $$ | \$$$$ / $$ | $$ |$$ | $$ | $$ $$ $$\$$ | $$ | $$ $$\$$ | \$$ / $$ | $$ |$$ | $$ | $$$$ _$$$$ | $$ | $$ \$$$$ | $$ | $$ | $$ |$$ | $$ | $$$ / \$$$ | $$ | $$ |\$$$ | $$ | $$$$$$ |\$$$$$$ | $$ / \$$ |$$$$$$\ $$ | \$$ | \__| \______/ \______/ \__/ \__|\______|\__| \__| "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(@" /$$ /$$ /$$$$$$ /$$ /$$ /$$ /$$ /$$$$$$ /$$ /$$ | $$ /$$//$$__ $$| $$ | $$ | $$ /$ | $$|_ $$_/| $$$ | $$ \ $$ /$$/| $$ \ $$| $$ | $$ | $$ /$$$| $$ | $$ | $$$$| $$ \ $$$$/ | $$ | $$| $$ | $$ | $$/$$ $$ $$ | $$ | $$ $$ $$ \ $$/ | $$ | $$| $$ | $$ | $$$$_ $$$$ | $$ | $$ $$$$ | $$ | $$ | $$| $$ | $$ | $$$/ \ $$$ | $$ | $$\ $$$ | $$ | $$$$$$/| $$$$$$/ | $$/ \ $$ /$$$$$$| $$ \ $$ |__/ \______/ \______/ |__/ \__/|______/|__/ \__/ "); Thread.Sleep(200); loopCount++; } Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(@" ██╗ ██╗ ██████╗ ██╗ ██╗ ██╗ ██╗██╗███╗ ██╗ ╚██╗ ██╔╝██╔═══██╗██║ ██║ ██║ ██║██║████╗ ██║ ╚████╔╝ ██║ ██║██║ ██║ ██║ █╗ ██║██║██╔██╗ ██║ ╚██╔╝ ██║ ██║██║ ██║ ██║███╗██║██║██║╚██╗██║ ██║ ╚██████╔╝╚██████╔╝ ╚███╔███╔╝██║██║ ╚████║ ╚═╝ ╚═════╝ ╚═════╝ ╚══╝╚══╝ ╚═╝╚═╝ ╚═══╝ "); Thread.Sleep(3000); Console.ForegroundColor = ConsoleColor.White; } public static void YouLose() { Console.ForegroundColor = ConsoleColor.DarkRed; Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / / ,---------------. ,-, / `-' | [ | | \ ,-. | `---------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / / ,---------------. ,-, / `-' | [ | | \ ,-. | `---------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / / ,---------------. ,-, / `-' | [ | | \ ,-. | `---------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / ,-------------. ,-, / `-' | [ | | \ ,-. | `-------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / ,-----------. ,-, / `-' | [ | | \ ,-. | `-----------' `-` __________________"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / // ,----.,-, [ || `----' `-` _________________________________"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / // ,----.,-, [ || `----' `-` _________________________________"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) ▄· ▄▌ ▄• ▄▌ ▄▄▌ .▄▄ · ▄▄▄ .▄▄ ▄▄ ▄▄ ▐█▪██▌▪ █▪██▌ ██• ▪ ▐█ ▀. ▀▄.▀·██▌██▌██▌ ▐█▌▐█▪ ▄█▀▄ █▌▐█▌ ██▪ ▄█▀▄ ▄▀▀▀█▄▐▀▀▪▄▐█·▐█·▐█· ▐█▀·.▐█▌.▐▌▐█▄█▌ ▐█▌▐▌▐█▌.▐▌▐█▄▪▐█▐█▄▄▌.▀ .▀ .▀ ▀ • ▀█▄▀▪ ▀▀▀ .▀▀▀ ▀█▄▀▪ ▀▀▀▀ ▀▀▀ ▀ ▀ ▀ _ _ _ _ _ . . . . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . ------------------------------------------------------------------------------- "); Thread.Sleep(300); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) ▄· ▄▌ ▄• ▄▌ ▄▄▌ .▄▄ · ▄▄▄ .▄▄ ▄▄ ▄▄ ▐█▪██▌▪ █▪██▌ ██• ▪ ▐█ ▀. ▀▄.▀·██▌██▌██▌ ▐█▌▐█▪ ▄█▀▄ █▌▐█▌ ██▪ ▄█▀▄ ▄▀▀▀█▄▐▀▀▪▄▐█·▐█·▐█· ▐█▀·.▐█▌.▐▌▐█▄█▌ ▐█▌▐▌▐█▌.▐▌▐█▄▪▐█▐█▄▄▌.▀ .▀ .▀ ▀ • ▀█▄▀▪ ▀▀▀ .▀▀▀ ▀█▄▀▪ ▀▀▀▀ ▀▀▀ ▀ ▀ ▀ . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . -------------------------------------------------------------------------- "); Thread.Sleep(300); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) ▄· ▄▌ ▄• ▄▌ ▄▄▌ .▄▄ · ▄▄▄ .▄▄ ▄▄ ▄▄ ▐█▪██▌▪ █▪██▌ ██• ▪ ▐█ ▀. ▀▄.▀·██▌██▌██▌ ▐█▌▐█▪ ▄█▀▄ █▌▐█▌ ██▪ ▄█▀▄ ▄▀▀▀█▄▐▀▀▪▄▐█·▐█·▐█· ▐█▀·.▐█▌.▐▌▐█▄█▌ ▐█▌▐▌▐█▌.▐▌▐█▄▪▐█▐█▄▄▌.▀ .▀ .▀ ▀ • ▀█▄▀▪ ▀▀▀ .▀▀▀ ▀█▄▀▪ ▀▀▀▀ ▀▀▀ ▀ ▀ ▀ . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . . . . ( . ( ( ( | | ) ) )\ ) . ( /(| / ( )) ) ) )) ) . . . . . . . . . . ( . ( ((((_(|)_))))) ) . ------------------------------------------------------------------------------- "); Thread.Sleep(300); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) ▄· ▄▌ ▄• ▄▌ ▄▄▌ .▄▄ · ▄▄▄ .▄▄ ▄▄ ▄▄ ▐█▪██▌▪ █▪██▌ ██• ▪ ▐█ ▀. ▀▄.▀·██▌██▌██▌ ▐█▌▐█▪ ▄█▀▄ █▌▐█▌ ██▪ ▄█▀▄ ▄▀▀▀█▄▐▀▀▪▄▐█·▐█·▐█· ▐█▀·.▐█▌.▐▌▐█▄█▌ ▐█▌▐▌▐█▌.▐▌▐█▄▪▐█▐█▄▄▌.▀ .▀ .▀ ▀ • ▀█▄▀▪ ▀▀▀ .▀▀▀ ▀█▄▀▪ ▀▀▀▀ ▀▀▀ ▀ ▀ ▀ . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . . . . ( . ( ( ( | | ) ) )\ ) . ( /(| / ( )) ) ) )) ) . . . . . . . . . . ( . ( ((((_(|)_))))) ) . . . ( . ||\(|(|)|/|| . . ) . . . . ( . |(||(||)|||| . ) . . . . . . . ( //|/l|||)|\\ \ ) . . . (/ / // /|//||||\\ \ \ \ _) ------------------------------------------------------------------------------- "); Thread.Sleep(2500); } /// <summary> /// Displayed on GAME OVER, either USER LOSE, or USER STOPS PLAYING /// </summary> public static void GameOverAnimation() { Console.ForegroundColor = ConsoleColor.Red; int loop = 0; while (loop < 10) { Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(@" ▄████ ▄▄▄ ███▄ ▄███▓▓█████ ▒█████ ██▒ █▓▓█████ ██▀███ ██▒ ▀█▒▒████▄ ▓██▒▀█▀ ██▒▓█ ▀ ▒██▒ ██▒▓██░ █▒▓█ ▀ ▓██ ▒ ██▒ ▒██░▄▄▄░▒██ ▀█▄ ▓██ ▓██░▒███ ▒██░ ██▒ ▓██ █▒░▒███ ▓██ ░▄█ ▒ ░▓█ ██▓░██▄▄▄▄██ ▒██ ▒██ ▒▓█ ▄ ▒██ ██░ ▒██ █░░▒▓█ ▄ ▒██▀▀█▄ ░▒▓███▀▒ ▓█ ▓██▒▒██▒ ░██▒░▒████▒ ░ ████▓▒░ ▒▀█░ ░▒████▒░██▓ ▒██▒ ░▒ ▒ ▒▒ ▓▒█░░ ▒░ ░ ░░░ ▒░ ░ ░ ▒░▒░▒░ ░ ▐░ ░░ ▒░ ░░ ▒▓ ░▒▓░ ░ ░ ▒ ▒▒ ░░ ░ ░ ░ ░ ░ ░ ▒ ▒░ ░ ░░ ░ ░ ░ ░▒ ░ ▒░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(@" "); Thread.Sleep(200); loop++; } CityLogo(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(@" ▄████ ▄▄▄ ███▄ ▄███▓▓█████ ▒█████ ██▒ █▓▓█████ ██▀███ ██▒ ▀█▒▒████▄ ▓██▒▀█▀ ██▒▓█ ▀ ▒██▒ ██▒▓██░ █▒▓█ ▀ ▓██ ▒ ██▒ ▒██░▄▄▄░▒██ ▀█▄ ▓██ ▓██░▒███ ▒██░ ██▒ ▓██ █▒░▒███ ▓██ ░▄█ ▒ ░▓█ ██▓░██▄▄▄▄██ ▒██ ▒██ ▒▓█ ▄ ▒██ ██░ ▒██ █░░▒▓█ ▄ ▒██▀▀█▄ ░▒▓███▀▒ ▓█ ▓██▒▒██▒ ░██▒░▒████▒ ░ ████▓▒░ ▒▀█░ ░▒████▒░██▓ ▒██▒ ░▒ ▒ ▒▒ ▓▒█░░ ▒░ ░ ░░░ ▒░ ░ ░ ▒░▒░▒░ ░ ▐░ ░░ ▒░ ░░ ▒▓ ░▒▓░ ░ ░ ▒ ▒▒ ░░ ░ ░ ░ ░ ░ ░ ▒ ▒░ ░ ░░ ░ ░ ░ ░▒ ░ ▒░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ "); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Sets default values for combat upon selection by user /// </summary> /// <param name="userInput"></param> public static void CombatSelector(int userInput) { //random number Random rand = new Random(); //switch on 1, 2, 3, 4 switch (userInput) { //automatic gun case 1: HeadsUpDisplay(); Console.WriteLine(@" THE ADP: Cost: 5 Bullets"); Console.Write("Chance to Hit: {0}\n Max Damage: 40", 100 - APDAccuracy); Console.WriteLine("\n\nDo you want to continue using the ADP? Y/N"); //Are you sure? UserConfirmation = null; while (UserConfirmation == null) { UserConfirmation = Console.ReadLine().ToUpper(); switch (UserConfirmation) { case "Y": //It takes 5 bullets to atk with this weapon BulletsLeft = BulletsLeft - 5; if (BulletsLeft < 0) { BulletsLeft = 0; } CityLogo(); //animations for auto gun AutoGunAnimation(); //how much damage to do AutomaticFire = rand.Next(15, 40); //user hit chance ChanceToHit = rand.Next(1, 101); //70% chance to hit if (ChanceToHit > APDAccuracy) { //kill enemies for amount of damage done EnemiesLeft = EnemiesLeft - AutomaticFire; enemiesKill = enemiesKill + AutomaticFire; //stats APDAtk++; APDDmg = APDDmg + AutomaticFire; //if user lands critical hit if (AutomaticFire > 31) { CityLogo(); //special animation BulletImpactAnimation(); HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYour aim was critically precise, killing {0} Replicants.", AutomaticFire); } //normal hit else { //normal text, no critical hit HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYou killed {0} Replicants.", AutomaticFire); } } //if the user misses else { HeadsUpDisplay(); //You Miss! Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYou miss every shot!"); } //Keeps combat messages on screen Console.WriteLine("\nPress Enter: "); Console.ReadKey(); Console.ForegroundColor = ConsoleColor.White; //now enemy attacks EnemyAttack(); break; //do not continue with combat action //chose again case "N": break; //Not valid input default: Console.WriteLine("\nPlease enter Y or N: "); UserConfirmation = null; break; } } break; //Pistol 100% chance to hit case 2: HeadsUpDisplay(); Console.WriteLine(@" .45 Cal ANTI-MATTER PISTOL: Cost: 2 Bullets Chance to Hit: 100 Max Damage: 25"); Console.WriteLine("\nDo you want to continue using the Side-Arm? Y/N"); UserConfirmation = null; while (UserConfirmation == null) { UserConfirmation = Console.ReadLine().ToUpper(); //Are you sure? switch (UserConfirmation) { //Yes case "Y": CityLogo(); //pistol animation SemiAutoGunAnimation(); //subtract bullets spent by action BulletsLeft = BulletsLeft - 2; if (BulletsLeft < 0) { BulletsLeft = 0; } Console.ForegroundColor = ConsoleColor.DarkRed; SemiAuto = rand.Next(10, 25); //enemies reduced by atk EnemiesLeft = EnemiesLeft - SemiAuto; if (EnemiesLeft <= 0) { EnemiesLeft = 0; } //keep track of enemy kills enemiesKill = enemiesKill + SemiAuto; //stats pistolAtk++; pistolDmg = pistolDmg + SemiAuto; //If user lands crit if (SemiAuto > 18) { CityLogo(); //special animation BulletImpactAnimation(); HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYour aim was critically precise, killing {0} Replicants!", SemiAuto); } //no crit else { //normal messages HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYou killed {0} Replicants.", SemiAuto); } //keep combat messages on screen Console.WriteLine("\nPress Enter: "); Console.ReadKey(); //enemy attack EnemyAttack(); Console.ForegroundColor = ConsoleColor.White; break; //do not continue with combat action //make new slection case "N": break; //invalid input default: Console.WriteLine("\nPlease Select Y or N: "); UserConfirmation = null; break; } } break; //supply drop case 3: //if user has money left if (MoneyLeft > 0) { int supplyDrop = 0; int newBullets = 0; int numOfDrops = 0; Console.WriteLine("\nHow many supply drops would you like to call? \n 1 Drop: $5"); Console.WriteLine(" (Select: 5, 10, 15, 20, 25 etc.)"); int.TryParse(Console.ReadLine(), out supplyDrop); Console.ForegroundColor = ConsoleColor.DarkRed; //if input is a number if (supplyDrop != 0) { //if they didn't type in too much money if (supplyDrop % 5 == 0) { //and if input is divisible by 5 if (supplyDrop <= MoneyLeft) { //subtract money MoneyLeft = MoneyLeft - supplyDrop; //total number of supply drops = input / 5 numOfDrops = supplyDrop / 5; //how many crates of ammo were purchased buyAmmo = buyAmmo + numOfDrops; while (numOfDrops > 0) { //random number of bullets awarded in bulk newBullets = newBullets + rand.Next(10, 20); numOfDrops--; } //add new bullets to count BulletsLeft = BulletsLeft + newBullets; HeadsUpDisplay(); Console.WriteLine("\nYou purchased {0} bullets.", newBullets); } else if (supplyDrop > MoneyLeft) { //you are cheating! HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("You don't have that kind of cash!"); } } //if input is too high //if input is not divisible by 5 else if (supplyDrop % 5 != 0) { //5, 10, 15, are valid inputs only HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("That isn't in $5 increments."); } //bullets added to pool //how many bullets are awarded } //subtract cost } //User is out of money else { HeadsUpDisplay(); Console.WriteLine("\nYou're out of money!!!"); } //keep combat messages on screen Console.WriteLine("\nPress Enter: "); Console.ReadKey(); //enemy attacks now EnemyAttack(); break; //KATANA!!!!!!!!!!! case 4: HeadsUpDisplay(); Console.WriteLine(@" KATANA: Cost: Free"); Console.WriteLine("Chance to Hit: {0}\n Max Damage: 100", 100 - KatAccuracy); Console.WriteLine("\nDo you want to continue using the KATANA? Y/N"); UserConfirmation = null; while (UserConfirmation == null) { UserConfirmation = Console.ReadLine().ToUpper(); //are you sure? switch (UserConfirmation) { //Yes case "Y": //Katana anmimation Katana(); ChanceToHit = rand.Next(1, 101); Console.ForegroundColor = ConsoleColor.DarkRed; //IF user hits if (ChanceToHit > KatAccuracy) { katanaAtk++; //how much damage SemiAuto = rand.Next(30, 101); //stats katanaDmg = katanaDmg + SemiAuto; //subtract damage from enemy total EnemiesLeft = EnemiesLeft - SemiAuto; if (EnemiesLeft < 0) { EnemiesLeft = 0; } //keep track of enemy kills for kill rewards enemiesKill = enemiesKill + SemiAuto; HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYou killed {0} Replicants!", SemiAuto); } //user misses else { HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYou missed completely."); } //keep combat messages on screen Console.WriteLine("\nPress Enter: "); Console.ReadKey(); EnemyAttack(); Console.ForegroundColor = ConsoleColor.White; break; //do not continue with combat action //make new selection case "N": break; //invalid input default: Console.WriteLine("\nPlease Enter Y or N: "); UserConfirmation = null; break; } } break; case 5: HeadsUpDisplay(); Console.WriteLine(@" GRENADE: Cost: $10 Chance to Hit: 55% Max Damage: 50 Bonus: 100% Chance to reduce enemy Reinforments for 3 rounds "); //only displays while effect active if (grenade > 0) { Console.WriteLine("\nRounds Left of Bonus Effect: {0}", grenade); } Console.WriteLine("Do you want to continue using the Grenade? Y/N"); UserConfirmation = null; while (UserConfirmation == null) { UserConfirmation = Console.ReadLine().ToUpper(); //are you sure? switch (UserConfirmation) { //Yes case "Y": //check to see if user has money if (MoneyLeft <= 10) { //User has NO money HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nYou trying to cheat me, boy?\n You aint got the funds for these munitions."); } //user HAS money else if (MoneyLeft > 10) { GrenadeBoom(); //Grenade animation MoneyLeft = MoneyLeft - 10; ChanceToHit = rand.Next(1, 101); Console.ForegroundColor = ConsoleColor.DarkRed; //IF user hits if (ChanceToHit > 45) { //does damage SemiAuto = rand.Next(30, 50); //counts grenades GrenadeUsage++; //stats grenade = 3; //subtract damage from enemy total EnemiesLeft = EnemiesLeft - SemiAuto; if (EnemiesLeft < 0) { EnemiesLeft = 0; } //keep track of enemy kills for kill rewards enemiesKill = enemiesKill + SemiAuto; HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; //combat message Console.WriteLine("\nYou killed {0} Replicants!", SemiAuto); Console.WriteLine("\nReplicants have a reduced chance to reinforce for a while."); } else { GrenadeUsage++; grenade = 3; //combat message HeadsUpDisplay(); Console.WriteLine("\nYour grenade missed, but the explosion can be heard for miles."); Console.WriteLine("\nDue to the EMP Effect, \n Replicants have a reduced chance to reinforce for a while."); } } //keep combat messages on screen Console.WriteLine("\nPress Enter: "); Console.ReadKey(); EnemyAttack(); Console.ForegroundColor = ConsoleColor.White; break; //do not continue with combat action //make new selection case "N": break; //invalid input default: Console.WriteLine("\nPlease Enter Y or N: "); UserConfirmation = null; break; } } break; case 6: HeadsUpDisplay(); Console.WriteLine(@" IMPLANTS: Cost: $50 Bonus: 100% Accuracy with ADP and KATANA for 5 Rounds! "); //only displays while effect active if (Implants > 0) { Console.WriteLine("\nRounds Left of Bonus Effect: {0}", Implants); } Console.WriteLine("Do you wish to purchase IMPLANTS? Y/N"); UserConfirmation = null; while (UserConfirmation == null) { UserConfirmation = Console.ReadLine().ToUpper(); //are you sure? switch (UserConfirmation) { //Yes case "Y": if (MoneyLeft >= 50) { //implants total purchased this game ImplantsTotal++; //subtract cost MoneyLeft = MoneyLeft - 50; //activate implants for 5 rounds //since implants decrements after each round //user has 5 rounds of COMBAT to use implants Implants = 6; //change accuracy for both items APDAccuracy = 1; KatAccuracy = 20; HeadsUpDisplay(); Console.WriteLine("\nYou now have perfect accuracy with the APD, \n and improved accuracy with the KATANA for 5 rounds."); } //if user doesn't have enough money else if (MoneyLeft < 50) { //don't activate implant effect HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nDon't try to cheat me! \n I can see you don't have enough money for those implants!"); } //keep combat messages on screen Console.WriteLine("\nPress Enter: "); Console.ReadKey(); EnemyAttack(); Console.ForegroundColor = ConsoleColor.White; break; //do not continue with combat action //make new selection case "N": break; //invalid input default: Console.WriteLine("\nPlease Enter Y or N: "); UserConfirmation = null; break; } } break; case 7: if (MoneyReward > 100) HeadsUpDisplay(); Console.WriteLine(@" TACTICAL NUKE: Cost: $100 Effect: Reduces Enemy Count to 0 Debuff: Reduce bonus cash to default "); Console.WriteLine("Do you wish to purchase TACTICAL NUKE? Y/N"); UserConfirmation = null; while (UserConfirmation == null) { UserConfirmation = Console.ReadLine().ToUpper(); //are you sure? switch (UserConfirmation) { //Yes case "Y": if (MoneyLeft >= 100) { MoneyReward = 0; //implants total purchased this game TacticalNuke++; //subtract cost MoneyLeft = MoneyLeft - 100; //defeats infinite nuke at end of game until very very high levels if (enemiesKill <= 100) { enemiesKill = EnemiesLeft + (enemiesKill / 2); } if(enemiesKill>= 100) { enemiesKill = EnemiesLeft + (enemiesKill / 4); } //activate implants for 5 rounds //since implants decrements after each round //user has 5 rounds of COMBAT to use implants Console.WriteLine("You killed {0} Replicants!!!", EnemiesLeft); EnemiesLeft = 0; //change accuracy for both items TacticalNukeAnimation(); TacticalNuke++; } //user doesn't have enough money else if (MoneyLeft < 100) { //if user doesn't have enough money Console.WriteLine("You can't use this option yet!!!"); } //keep combat messages on screen Console.WriteLine("\nPress Enter: "); Console.ReadKey(); EnemyAttack(); Console.ForegroundColor = ConsoleColor.White; break; //do not continue with combat action //make new selection case "N": break; //invalid input default: Console.WriteLine("\nPlease Enter Y or N: "); UserConfirmation = null; break; } } break; //user did not select 1, 2, 3, 4 or 5 default: //User gun jams, loses 1 bullet BulletsLeft = BulletsLeft - 1; HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; //suggests that the user tries putting correct input Console.WriteLine("\nYour gun jammed! \n\nYou can't be losing your precious ammo like that!"); Console.WriteLine("\nPress Enter: "); Console.ReadKey(); //enemy still attacks EnemyAttack(); break; } } /// <summary> /// instructions on how to play /// </summary> public static void HowToPlay() { //list of instructions to play game List<string> instructions = new List<string>() { "As Blade Runner, \n you have 2 tools at your disposal for eliminating Replicant Husks.", "First is your Automatic Machine Dispersion Pistol, or \"ADP\".", "With a high cyclic rate of fire, \n you are much more likely to MISS using this weapon.", }; for (int i = 0; i < instructions.Count; i++) { Console.WriteLine("How to play: \n\n"); //scroll text from list foreach (object c in instructions[i]) { Console.Write(c); Thread.Sleep(10); } Thread.Sleep(300); Console.WriteLine("\n\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); //show static automatic gun AutoMaticGun(); Console.ForegroundColor = ConsoleColor.White; } //second set of instructions for pistol List<string> instructions2 = new List<string>() { "Next is your semi-automatic side-arm.", "The .45 Cal Anti-Matter Pistol is much more reliable, \n but is much less effective \n against the metallic frame of the Replicant Husks.", "\n Each attack uses ammo: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \n so be careful.", "If you run out of ammo while there are still Replicants left to eliminate, \n they will overwhelm the city, and eat it's remnants alive.", "We cannot lose 3 of our major cities, Blade Runner. \nWe're counting on you!" }; for (int i = 0; i < instructions2.Count; i++) { Console.WriteLine("How to play: \n\n"); //scroll text foreach (object a in instructions2[i]) { Console.Write(a); Thread.Sleep(10); } Thread.Sleep(300); Console.WriteLine("\n\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); Console.ForegroundColor = ConsoleColor.DarkRed; //show static pistol SemiAutoGun(); Console.ForegroundColor = ConsoleColor.White; } } /// <summary> /// scrolls text from top of screen /// </summary> public static void TitleScrollFromTop() { Console.ForegroundColor = ConsoleColor.DarkCyan; int middle = 0; string title = @" ██████╗██╗ ██╗██████╗ ███████╗██████╗ ███╗ ██╗███████╗████████╗██╗██╗ ██╗ ██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗████╗ ██║██╔════╝╚══██╔══╝██║╚██╗██╔╝ ██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝██╔██╗ ██║█████╗ ██║ ██║ ╚███╔╝ ██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗██║╚██╗██║██╔══╝ ██║ ██║ ██╔██╗ ╚██████╗ ██║ ██████╔╝███████╗██║ ██║██║ ╚████║███████╗ ██║ ██║██╔╝ ██╗ ╚═════╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ "; while (middle < 17) { Console.Clear(); title = "\n\n" + title; Console.WriteLine(title); Thread.Sleep(200); middle++; } Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Basic Display Logo /// </summary> public static void TitleScroll() { Console.ForegroundColor = ConsoleColor.DarkCyan; string caption = "Humans Vs. Machines\n"; string title = @" ██████╗██╗ ██╗██████╗ ███████╗██████╗ ███╗ ██╗███████╗████████╗██╗██╗ ██╗ ██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗████╗ ██║██╔════╝╚══██╔══╝██║╚██╗██╔╝ ██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝██╔██╗ ██║█████╗ ██║ ██║ ╚███╔╝ ██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗██║╚██╗██║██╔══╝ ██║ ██║ ██╔██╗ ╚██████╗ ██║ ██████╔╝███████╗██║ ██║██║ ╚████║███████╗ ██║ ██║██╔╝ ██╗ ╚═════╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ "; Console.WriteLine(title); Thread.Sleep(700); Console.WriteLine(); //create space for caption placement Console.Write(" "); Console.ForegroundColor = ConsoleColor.Cyan; //only scroll caption once if (CaptionCount == 0) { //scroll text from caption foreach (object c in caption) { Console.Write(c); Thread.Sleep(20); } Thread.Sleep(1000); Console.ForegroundColor = ConsoleColor.White; //only scroll caption once CaptionCount++; } //regular caption placement else { Console.WriteLine(caption); } } /// <summary> /// Story Text /// </summary> public static void StoryLine() { //keeps city at top of screen CityLogo(); TitleScroll(); int loopCounter = 0; //plot List<string> plot = new List<string>() { "The year is 2199.", "Mankind has created the first artificial humans.", "Empty mechanized husks, \n known as Replicants, \n have become the key to perfect health, and immortality.", "The worlds wealthiest men \n had their identities implanted into these Replicants...", "...but what nobody told them \n will change the course of history forever.", "The innate physical needs of man: \n sleep, hunger, touch; \n those needs were not overcome by Replicant technology.", "Slowly, \n\n those who were implanted into Replicant Husks began spiraling downard \n ...into insanity.", "Without the ability to sleep or eat, \n these Replicants became mechanized zombies, \n attacking anything that moved, out of ever worsening dimentia.", "You are a Blade Runner.\n You and your team are all that stand between humanity, \n and humanities self wrought extinction.", }; for (int i = 0; i < plot.Count; i++) { //scroll list text foreach (object c in plot[i]) { Console.Write(c); Thread.Sleep(25); } Console.WriteLine("\n"); Thread.Sleep(500); loopCounter++; //prints out 5 items from list, then asks for user to continue if (loopCounter == 5) { loopCounter = 0; Console.WriteLine("Press any key to continue: "); Console.ReadLine(); Console.Clear(); CityLogo(); TitleScroll(); } } Console.WriteLine(" Press any key to continue: "); Console.ReadKey(); CityLogo(); //call how to play text HowToPlay(); } /// <summary> /// Heads up display /// Showing bullets, money, cities count etc /// </summary> public static void HeadsUpDisplay() { //keeps track of """""" string bulletHud = ""; string enemiesHud = ""; string moneyHud = ""; //indentation count int hudReset = 0; CityLogo(); TitleScroll(); //cities count and implants status //displays current level Console.WriteLine("Cash Bonus: ${1}/20 kills Enemy Max Damage: {2} Level: {0}\n", LevelCounter, 5 + MoneyReward, EnemyScalingDamage); //implants on if (Implants > 0 && grenade > 0) { Console.WriteLine(" Implants: (⌐■_■) on Cities Cleared: {0}", CitiesCleared); Console.WriteLine("EMP Effect: \\-^-/ on Cities Lost: {0}\n", CitiesLost); } else if (Implants > 0) { Console.WriteLine(" Implants: (⌐■_■) on Cities Cleared: {0}", CitiesCleared); Console.WriteLine("EMP Effect: /---\\ off Cities Lost: {0}\n", CitiesLost); } else if (grenade > 0) { Console.WriteLine(" Implants: ( o_o) off Cities Cleared: {0}", CitiesCleared); Console.WriteLine("EMP Effect: \\-^-/ on Cities Lost: {0}\n", CitiesLost); } //implants off else if (Implants <= 0 && grenade <= 0) { Console.WriteLine(" Implants: ( o_o) off Cities Cleared: {0}", CitiesCleared); Console.WriteLine("EMP Effect: /---\\ off Cities Lost: {0}\n", CitiesLost); } //scroll through and ad """"" to bullets hud for (int i = 0; i < BulletsLeft; i += 2) { //add " to string bulletHud = bulletHud + "\""; //onlhy print 25 per line hudReset++; if (hudReset == 25) { bulletHud = bulletHud + "\n"; hudReset = 0; } } //reset hud count for each item //build enemies hud hudReset = 0; Console.WriteLine("Bullets Left: {1}\n{0}", bulletHud, BulletsLeft); for (int i = 0; i < EnemiesLeft; i += 2) { enemiesHud = enemiesHud + "\""; hudReset++; if (hudReset == 25) { enemiesHud = enemiesHud + "\n"; hudReset = 0; } } //build money hud hudReset = 0; Console.WriteLine("Enemies Left: {1}\n{0}", enemiesHud, EnemiesLeft); for (int i = 0; i < MoneyLeft; i += 2) { moneyHud = moneyHud + "\""; hudReset++; if (hudReset == 25) { moneyHud = moneyHud + "\n"; hudReset = 0; } } hudReset = 0; Console.WriteLine("Money Left: ${1}\n{0}", moneyHud, MoneyLeft); } /// <summary> /// City image /// </summary> public static void CityLogo() { Console.ForegroundColor = ConsoleColor.Magenta; Console.Clear(); Console.WriteLine(@" /\ \ \ \/_______/ ______/\ \ /\ \/ /\ \/ /\ \_____________ /\ \ \ \/______ / /\ /:\\ \ ::\ /::\ /::\ /____ ____ __ /\ \ \ \/_______/ /:\\ /:\:\\______\::/ \::/ \::/// / / // /\ \ \ \/_______/ _/____\/:\:\:/_____ / / /\ \/ /\ \///___/ /___//___ _____/___ \ \/_______/ /\::::::\\:\:/_____ / \ /::\ /::\ /____ ____ ____ \ \/_______/ /:\\::::::\\:/_____ / \\::/ \::/// / / / / / \/_______/ /:\:\\______\/______/_____\\/ /\ \///___/ /___/ /_____ \ \______/ /:\:\:/_____:/\ \ ___ / /::\ /____ ____ _/\:::: \\__________\____/ /:\:\:/_____:/:\\ \__ /_______/____/_/___/_ / \::: //__________/___/ _/____:/_____:/:\:\\______\ / /\ /\:: ///\ \/ /\ .----.\___:/:\:\:/_____ // \ / \/ \: ///\\ \ /::\\ \_\ \\_:/:\:\:/_____ //:\ \ /\ /\ /\ //:/\\ \//\::\\ \ \ \\/:\:\:/_____ //:::\ \ / \/ \/+/ /:/:/\\_________/:\/:::\`----' \\:\:/_____ //o:/\:\ \_____________/\ /\ / / :/:/://________//\::/\::\_______\\:/_____ ///\_\ \:\/____________/ \/ \/+/\ /:/:///_/_/_/_/:\/::\ \:/__ __ /:/_____ ///\//\\/:/ _____ ____/\ /\ / / \ :/:///_/_/_/_//\::/\:\///_/ /_//:/______/_/ :~\/::/ /____/ /___/ \/ \/+/\ / /:///_/_/_/_/:\/::\ \:/__ __ /:/____/\ / \\:\/:/ _____ ____/\ /\ / / \/ :///_/_/_/_//\::/\:\///_/ /_//:/____/\:\____\\::/ /____/ /___/ \/ \/+/\ /\ ///_/_/_/_/:\/::\ \:/__ __ /:/____/\:\/____/\\/____________/\ /\ / / \/ \ //_/_/_/_//\::/\:\///_/ /_//::::::/\:\/____/ /----/----/--/ \/ \/+/\ /\ / /_/_/_/_/:\/::\ \:/__ __ /\:::::/\:\/____/ \/____/____/__/\ /\ / / \/ \/_ _/_/_/_//\::/\:\///_/ /_//\:\::::\:\/____/ \_____________/ \/ \/+/\ /\ / /_/_/_/:\/::\ \:/__ __ /\:\:\::::\/____/ \ _ _ _ _ _ /\ /\ / / \/ \/___ _/_/_//\::/\:\///_/ /_//\:\:\:\ \_________/ \/ \/+/\ /\ / / /_/_/:\/::\ \:/__ __ /\:\:\:\:\______________\ /\ /\ / / \/ \/___/_ _/_//\::/\:\///_/ /_//::\:\:\:\/______________/ / \/ \/+/\ /\ / / /_/:\/::\ \:/__ __ /::::\:\:\/______________/\ /\ /\ / / \/ \/___/___ _//\::/\:\///_/ /_//:\::::\:\/______________/ \ / \/ \/+/\ /\ / / / /:\/::\ \:/__ __ /:\:\::::\/______________/ \ /\ /\ / / \/ \/___/___/ /\::/\:\///_/ /_//:\:\:\ \ \/\\\/+/\ /\ / / /+/ \/::\ \:/__ __ /:\:\:\:\_________________________\ ///\\\/ \/ \/___/___/ /_ ::/\:\///_/ /_//:\:\:\:\/_________________________////::\\\ /\ / / /+/ "); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Katana Image /// </summary> public static void Katana() { Console.ForegroundColor = ConsoleColor.DarkRed; string fullKatana = @" ___         |//| |//| |//| |//| |//| |//| |//| ___|//|___ /<>______<>\ // / |/\| \ \\ // //\\ \\ // \\ |/)dd(\| ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ( ) \/"; int katanaFly = 0; //katana flies down the screen while (katanaFly < 15) { fullKatana = "\n" + fullKatana; Console.WriteLine(fullKatana); Thread.Sleep(10); Console.Clear(); katanaFly++; } Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Gun animation /// </summary> public static void AutoGunAnimation() { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW XXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm XXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM XXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW SSSXXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm SSSXXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM SSSXXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW XXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm XXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM XXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW SSSXXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm SSSXXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM SSSXXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW XXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm XXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM XXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW SSSXXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm SSSXXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM SSSXXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW XXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm XXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM XXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Thread.Sleep(300); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// still image of auto gun /// </summary> public static void AutoMaticGun() { Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . OO QQQQ OO OOOO QQ OOOO WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW SSSXXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXWmmmmmm SSSXXXXXXXXXXXX--------XXXXXXWWWWWWWWWWWWMMMMMM SSSXXXXXXXXXXXXxxxxxxxxXXXXXXWWWWWWWWWWWW SSS SSS CEEEEEEEE C Z SSS SS CWXXXXXXW C Z SSSS CWXXXXXXWZZZZ SSS WXXXXXXW SSS WXXXXXXW WXX++XXW NNNNNN NNNNNN "); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Pistol Animation /// </summary> public static void SemiAutoGunAnimation() { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" 8888o.o.o.o.ooooooo00||00oooooooooooooooooooo88o ./' 88:8:8:8:8:888888800||0088888888888888888888888://____ 88:8:8:8:8:888888888888888888888888888888888888:\ Y88:8:8:8:8:8888888888888888888oooooooooooooooP '' ` 8oooooooooooooooooooooooooo .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" 8o.o.o.o.ooooooo00||00oooooooooooooooooooo88o ':/ :8:8:8:8:888888800||0088888888888888888888888:// _______ 8:8:8:8:8:888888888888888888888888888888888888:\\ Y88:8:8:8:8:8888888888888888888oooooooooooooooP\\\ ` 8oooooooooooooooooooooooooo . >\ .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" / .o.o.ooooooo00||00oooooooooooooooooooo88o____ ../ 8:8:888888800||0088888888888888888888888: | _______ 88:8:8:8:8:888888888888888888888888888888888888: Y88:8:8:8:8:8888888888888888888oooooooooooooooP \\ ` 8oooooooooooooooooooooooooo . .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" ooooooo00||00oooooooooooooooooooo88o________ 888888800||0088888888888888888888888: | ______ 88:8:8:8:8:888888888888888888888888888888888888: Y88:8:8:8:8:8888888888888888888oooooooooooooooP ` 8oooooooooooooooooooooooooo .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" .ooooooo00||00oooooooooooooooooooo88o_______ :888888800||0088888888888888888888888: | 88:8:8:8:8:888888888888888888888888888888888888: Y88:8:8:8:8:8888888888888888888oooooooooooooooP ` 8oooooooooooooooooooooooooo .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" .o.o.ooooooo00||00oooooooooooooooooooo88o____ :8:8:888888800||0088888888888888888888888: | 88:8:8:8:8:888888888888888888888888888888888888: Y88:8:8:8:8:8888888888888888888oooooooooooooooP ` 8oooooooooooooooooooooooooo .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" 8888o.o.o.o.ooooooo00||00oooooooooooooooooooo88o 88:8:8:8:8:888888800||0088888888888888888888888: 88:8:8:8:8:888888888888888888888888888888888888: Y88:8:8:8:8:8888888888888888888oooooooooooooooP ` 8oooooooooooooooooooooooooo .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Thread.Sleep(300); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// static image of pistol /// </summary> public static void SemiAutoGun() { Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" 8888o.o.o.o.ooooooo00||00oooooooooooooooooooo88o 88:8:8:8:8:888888800||0088888888888888888888888: 88:8:8:8:8:888888888888888888888888888888888888: Y88:8:8:8:8:8888888888888888888oooooooooooooooP ` 8oooooooooooooooooooooooooo .88888888888.`::: 8 88888888888Yo `` * 8 .88888888888 `oooooooood8o 88888888888' .88888888888 88888888888' .88888888888 98888888888' "); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// critical hit animation /// </summary> public static void BulletImpactAnimation() { Console.ForegroundColor = ConsoleColor.DarkRed; Console.Clear(); CityLogo(); Console.WriteLine(@" ___ '___ CRITICAL HIT!!! / \I/ '\ ____ | '| _ -- | \ | '| -- | / | '| ~~~~ \_________/ "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" ___ '___ CRITICAL HIT!!! / \I/ '\ _____ | '| _ -- | \ | '| -- | / | '| ~~~~ \_________/ "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" ___ '___ CRITICAL HIT!!! / \I/ '\ ____ | '| _ -- | \ | '| -- | / | '| ~~~~~ \_________/ "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" ___ '___ CRITICAL HIT!!! / \I/ '\ _____ | '| _ -- | \ | '| -- | / | '| ~~~~ \_________/ "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" ___ '___ CRITICAL HIT!!! / \I/ '\ _____ | '| _ -- | \ | '| -- | / | '| ~~~~ \_________/ "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" ___ '___ CRITICAL HIT!!! / \I/ '\ ____I '| _ -- | I '| -- | I '| ~~~~ \ ________/ "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" ' ' ___ '__'/ CRITICAL HIT!!! \ / \I/ /// \ ==%//=' . = > %%%%= / ##%%% / \ ____ =\\ ~ '\\ . ' "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" ' ' ___ '__'// \ / \I/ /// \ ==%//= . = > %%%%====%=-' / ##%%%==\ / \ ____ =\\% ~ '\\\ . '\ "); Thread.Sleep(300); Console.Clear(); CityLogo(); Console.WriteLine(@" '//' ___ '__'///' . \ / \I/ /////' ^/. \ ==%//=' . = > %%%%====%=-'===_##&$6 / ##%%%==\\' / \ ____ =\\%\\' ?.,\ ~ '\\\' . '\\' . '' "); Thread.Sleep(300); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// enemy attack function /// determines whether the enemy attacks, reinforces etc /// </summary> public static void EnemyAttack() { Random rand = new Random(); ///enemies chance to hit int reinforcements = 0; int reinforcementChance = 70; ChanceToHit = rand.Next(1, 101); //80% chance to hit if (ChanceToHit > 12) { //if there are still enemies left, attack if (EnemiesLeft > 0) { //enemy damage EnemyDamage = rand.Next(5, EnemyScalingDamage); BulletsLeft = BulletsLeft - EnemyDamage; if (BulletsLeft < 0) { BulletsLeft = 0; } HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\nA replicant attacked a civilian. \n\nYou used {0} bullets to take him down!", EnemyDamage); Console.WriteLine("\nPress Enter: "); Console.ReadKey(); } } ChanceToHit = 0; //enemies have a 30% chance to reinforce their numbers reinforcements = rand.Next(1, 101); //if grenade debuff is active, only 5% chance of reiforcments for 3 rounds //enemies reinforce or don't if (grenade > 0) { reinforcementChance = 95; grenade--; } if (reinforcements > reinforcementChance && EnemiesLeft > 0) { HeadsUpDisplay(); //reinforce with 15-50 enemies per wave ChanceToHit = rand.Next(15, MaxReinforcement); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("A WAVE OF {0} REPLICANTS HAS STORMED THE CITY!!!", ChanceToHit); Console.WriteLine(@" @ \@/ |@__ \@ __@ __@/ @/ __@| /|\ | | |\ /| | /| | / \ / \ / \ / \ / \ / \ / \ / \"); Console.WriteLine(" Enemy numbers reinforced!"); EnemiesLeft = EnemiesLeft + ChanceToHit; Console.WriteLine("\nPress Enter: "); Console.ReadKey(); Console.ForegroundColor = ConsoleColor.White; } } /// <summary> /// tracks average damage per weapon /// </summary> public static void Stat() { //avg katana % int katanaStat = 0; //avg pistol % int pistolStat = 0; //avg int APDStat = 0; int totalDmg = 0; int totalAtk = 0; if (katanaAtk > 0) { katanaStat = katanaDmg / katanaAtk; } if (pistolAtk > 0) { pistolStat = pistolDmg / pistolAtk; } if (APDAtk > 0) { APDStat = APDDmg / APDAtk; } totalDmg = katanaDmg + pistolDmg + APDDmg; totalAtk = (katanaAtk + pistolAtk + APDAtk); int totalStat = totalDmg / totalAtk; CityLogo(); TitleScroll(); //final scoreboard tally Console.WriteLine(@" Cities Cleared: {0} Cities Lost: {1}", CitiesCleared, CitiesLost); Thread.Sleep(500); Console.WriteLine("You did an average of {0} damage with the APD.", APDStat); Thread.Sleep(500); Console.WriteLine("You did an average of {0} damage with the Side-Arm.", pistolStat); Thread.Sleep(500); Console.WriteLine("You did an average of {0} damage with the KATANA.", katanaStat); Thread.Sleep(500); Console.WriteLine(" You bought {0} grenades", GrenadeUsage); Thread.Sleep(500); Console.WriteLine(" You bought {0} supply crates.", buyAmmo); Thread.Sleep(500); Console.WriteLine(" You used {0} implants.", ImplantsTotal); Thread.Sleep(500); Console.WriteLine(" You earned ${0}.", CashEarned); Thread.Sleep(500); Console.WriteLine(" You used {0} Tactical Nukes.", TacticalNuke); Thread.Sleep(500); Console.WriteLine("\nYou did an overall average of {0} damage.", totalStat); Thread.Sleep(500); } /// <summary> /// grenade throw animation /// </summary> public static void GrenadeBoom() { Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" o, / -O- \ /\ ............................... "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" o, / _O/ /| /\ ............................. "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" = o, O___ /| /\ ............................. "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" \ o, O /|\ /\ ............................. "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" \ o, O /|\ /\ ............................. "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" \ O o, /|\ /\ ............................. "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" O \ /|\ o, /\ ............................. "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@"\ . ./ \ .: ;'.:.. / (M^^.^~~:.' ). - (/ . . . \ \) - ((| :. ~ ^ :. .|)) O - (\- | \ / | /) - /|\ -\ \ / /- /\ ...............................\ \ / / "); Thread.Sleep(200); Console.Clear(); CityLogo(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(@" . ./ \ .: ;'.:.. / (M^^.^~~:.' ). - (/ . . . \ \) - . ((| :. ~ ^ :. .|)) \O__. - (\- | \ / | /) - / -\ \ / /- /\ ...............................\ \ / / "); Thread.Sleep(1000); Console.Clear(); } /// <summary> /// this function rewards players for getting accumulated kills /// </summary> public static void NewMoneyAdder() { int newMoney = 0; //adds money to stash for each 25 enemies killed if (enemiesKill >= 20) { HeadsUpDisplay(); Console.ForegroundColor = ConsoleColor.DarkRed; //for every 20 kills get 5 bucks //how many increments are payed out MoneyIncrement = enemiesKill / 20; newMoney = MoneyIncrement * 5; MoneyLeft = MoneyLeft + newMoney + (MoneyReward * MoneyIncrement); CashEarned = CashEarned + (MoneyReward * MoneyIncrement) + newMoney; Console.WriteLine("\nYou killed {1} enemies.\n\n ${0} added to your stash.", (MoneyReward * MoneyIncrement)+ newMoney, enemiesKill); //while subtracting 25 is not negative while (enemiesKill - 20 > 0) { //subtract 25 //this old kills aren't lost enemiesKill -= 20; } Console.WriteLine("\nPress any key to continue: "); Console.ReadKey(); Console.ForegroundColor = ConsoleColor.White; } } /// <summary> /// tatctical nuke animation /// </summary> public static void TacticalNukeAnimation() { Console.ForegroundColor = ConsoleColor.DarkRed; Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / / ,---------------. ,-, / `-' | [ | | \ ,-. | `---------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / / ,---------------. ,-, / `-' | [ | | \ ,-. | `---------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / / ,---------------. ,-, / `-' | [ | | \ ,-. | `---------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / ,-------------. ,-, / `-' | [ | | \ ,-. | `-------------' `-`"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / / / / / / ,-----------. ,-, / `-' | [ | | \ ,-. | `-----------' `-` __________________"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / // ,----.,-, [ || `----' `-` _________________________________"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" / / / / / / // ,----.,-, [ || `----' `-` _________________________________"); Thread.Sleep(200); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) _ _ _ _ _ . . . . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . ------------------------------------------------------------------------------- "); Thread.Sleep(300); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . -------------------------------------------------------------------------- "); Thread.Sleep(300); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . . . . ( . ( ( ( | | ) ) )\ ) . ( /(| / ( )) ) ) )) ) . . . . . . . . . . ( . ( ((((_(|)_))))) ) . ------------------------------------------------------------------------------- "); Thread.Sleep(300); Console.Clear(); Console.WriteLine(@" . . ________________ . . . ____/ ( ( ) ) \___ . /( ( ( ) _ )) ) )\ . . (( ( )( ) ) ( ) ) . . . ((/ ( _( ) ( _) ) ( () ) ) . . ( ( ( (_) (( ( ) .((_ ) . )_ ) ) . . (_((__(_(__(( ( ( | ) ) ) )_))__))_)___) . . ((__) \\||lll|l||/// \_)) . . . / ( |(||(|)|||// \ . . . . . . . ( /(/ ( ) ) )\ . . . . . ( . ( ( ( | | ) ) )\ ) . ( /(| / ( )) ) ) )) ) . . . . . . . . . . ( . ( ((((_(|)_))))) ) . . . ( . ||\(|(|)|/|| . . ) . . . . ( . |(||(||)|||| . ) . . . . . . . ( //|/l|||)|\\ \ ) . . . (/ / // /|//||||\\ \ \ \ _) ------------------------------------------------------------------------------- "); Thread.Sleep(2500); } /// <summary> /// different display screens for whether tactical nuke is available /// </summary> public static void GameScreen() { if (MoneyLeft < 100) { Console.WriteLine(@" Replicants are infesting the city! ....... @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 1. Automatic Dispersion Pistol (ADP) ....... @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ....... @@@@@@@@@@ oo o@@@@o @@@@@@@@@oooo 2. 45 Caliber Anti-Matter Pistol ....... @@@ @a0000000000000000a a00000a00 ....... @@@@ 0000000000000000000 000000000 3. Resupply Drop ........ @@ 0000 0000000000000000000000000 ........ @@@ 0000 000000000000000000000000 4. Katana ........ @@@ 000 0000000000000000000000000 ........ @@@ 000 0000000000000000000000000 5. EMP Grenade ......... @@@ 00 00000000000 00000 0000000 ...... 00;. aaaaa a 6. Accuracy Implants .......0000 00000ta /00000 000\ .......`000 000000000000mn000000 0000mn000 ,-.__________________,======= , ....... 000 00000000000000000000 000000000 [ ( _ _ _ )_______) \\\\\ ((t ........ 00 00000000000000000000 000000000 /================.-.______,--'_\ ......... 0 0000000000000000 00000 0000000 \_,__,_________\ [ ] / ........... 0a 00000000000 0000000 000000 \ ( )) ) o ( ............ 000a00000000000mm mm0000000 \ \____/ \ \ ............ 0000 000000000000000000000000 ' ===''\ \ \ ............ 000000000000 0000 \ \ \ ...... a 000000000m0000000000000000 )____\ | ..... ,' 00a 000000000 00000 ) __, __,' ... ,' 0000a 0000000000000000000000 '--'' . ,' `00000a 00000000000000000000 "); } if (MoneyLeft >= 100) { Console.WriteLine(@" Replicants are infesting the city! ....... @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 1. Automatic Dispersion Pistol (ADP) ....... @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ....... @@@@@@@@@@ oo o@@@@o @@@@@@@@@oooo 2. 45 Caliber Anti-Matter Pistol ....... @@@ @a0000000000000000a a00000a00 ....... @@@@ 0000000000000000000 000000000 3. Resupply Drop ........ @@ 0000 0000000000000000000000000 ........ @@@ 0000 000000000000000000000000 4. Katana ........ @@@ 000 0000000000000000000000000 ........ @@@ 000 0000000000000000000000000 5. EMP Grenade ......... @@@ 00 00000000000 00000 0000000 ...... 00;. aaaaa a 6. Accuracy Implants .......0000 00000ta /00000 000\ .......`000 000000000000mn000000 0000mn000 7. --TACTICAL NUKE ONLINE-- ....... 000 00000000000000000000 000000000 [ ( _ _ _ )_______) \\\\\ ((t ........ 00 00000000000000000000 000000000 /================.-.______,--'_\ ......... 0 0000000000000000 00000 0000000 \_,__,_________\ [ ] / ........... 0a 00000000000 0000000 000000 \ ( )) ) o ( ............ 000a00000000000mm mm0000000 \ \____/ \ \ ............ 0000 000000000000000000000000 ' ===''\ \ \ ............ 000000000000 0000 \ \ \ ...... a 000000000m0000000000000000 )____\ | ..... ,' 00a 000000000 00000 ) __, __,' ... ,' 0000a 0000000000000000000000 '--'' . ,' `00000a 00000000000000000000 "); } } } }
#region The Apache Software License /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ported to C# by Artur Trosin */ #endregion namespace NDDDSample.Tests.Infrastructure.Builders { #region Usings using System; using NDDDSample.Infrastructure.Builders; using NUnit.Framework; #endregion [TestFixture, Category(UnitTestCategories.Infrastructure)] public class EqualsBuilderTest { [Test] public void testReflectionEquals() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); Assert.IsTrue(EqualsBuilder.ReflectionEquals(o1, o1)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(o1, o2)); o2.setA(4); Assert.IsTrue(EqualsBuilder.ReflectionEquals(o1, o2)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(o1, this)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(o1, null)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(null, o2)); Assert.IsTrue(EqualsBuilder.ReflectionEquals((Object) null, (Object) null)); } [Test] public void testReflectionHierarchyEquals() { testReflectionHierarchyEquals(false); testReflectionHierarchyEquals(true); // Transients Assert.IsTrue(EqualsBuilder.ReflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); Assert.IsTrue(EqualsBuilder.ReflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), false)); Assert.IsTrue( !EqualsBuilder.ReflectionEquals(new TestTTLeafObject(1, 0, 0, 4), new TestTTLeafObject(1, 2, 3, 4), true)); Assert.IsTrue( !EqualsBuilder.ReflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 0), true)); Assert.IsTrue( !EqualsBuilder.ReflectionEquals(new TestTTLeafObject(0, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); } public void testReflectionHierarchyEquals(bool testTransients) { TestObject to1 = new TestObject(4); TestObject to1Bis = new TestObject(4); TestObject to1Ter = new TestObject(4); TestObject to2 = new TestObject(5); TestEmptySubObject teso = new TestEmptySubObject(4); TestTSubObject ttso = new TestTSubObject(4, 1); TestTTSubObject tttso = new TestTTSubObject(4, 1, 2); TestTTLeafObject ttlo = new TestTTLeafObject(4, 1, 2, 3); TestSubObject tso1 = new TestSubObject(1, 4); TestSubObject tso1bis = new TestSubObject(1, 4); TestSubObject tso1ter = new TestSubObject(1, 4); TestSubObject tso2 = new TestSubObject(2, 5); testReflectionEqualsEquivalenceRelationship(to1, to1Bis, to1Ter, to2, new TestObject(), testTransients); testReflectionEqualsEquivalenceRelationship(tso1, tso1bis, tso1ter, tso2, new TestSubObject(), testTransients); // More sanity checks: // same values Assert.IsTrue(EqualsBuilder.ReflectionEquals(ttlo, ttlo, testTransients)); Assert.IsTrue(EqualsBuilder.ReflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 10), testTransients)); // same super values, diff sub values Assert.IsTrue( !EqualsBuilder.ReflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 11), testTransients)); Assert.IsTrue( !EqualsBuilder.ReflectionEquals(new TestSubObject(1, 11), new TestSubObject(1, 10), testTransients)); // diff super values, same sub values Assert.IsTrue( !EqualsBuilder.ReflectionEquals(new TestSubObject(0, 10), new TestSubObject(1, 10), testTransients)); Assert.IsTrue( !EqualsBuilder.ReflectionEquals(new TestSubObject(1, 10), new TestSubObject(0, 10), testTransients)); // mix super and sub types: equals Assert.IsTrue(EqualsBuilder.ReflectionEquals(to1, teso, testTransients)); Assert.IsTrue(EqualsBuilder.ReflectionEquals(teso, to1, testTransients)); Assert.IsTrue(EqualsBuilder.ReflectionEquals(to1, ttso, false)); // Force testTransients = false for this assert Assert.IsTrue(EqualsBuilder.ReflectionEquals(ttso, to1, false)); // Force testTransients = false for this assert Assert.IsTrue(EqualsBuilder.ReflectionEquals(to1, tttso, false)); // Force testTransients = false for this assert Assert.IsTrue(EqualsBuilder.ReflectionEquals(tttso, to1, false)); // Force testTransients = false for this assert Assert.IsTrue(EqualsBuilder.ReflectionEquals(ttso, tttso, false)); // Force testTransients = false for this assert Assert.IsTrue(EqualsBuilder.ReflectionEquals(tttso, ttso, false)); // Force testTransients = false for this assert // mix super and sub types: NOT equals Assert.IsTrue(!EqualsBuilder.ReflectionEquals(new TestObject(0), new TestEmptySubObject(1), testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(new TestEmptySubObject(1), new TestObject(0), testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(new TestObject(0), new TestTSubObject(1, 1), testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(new TestTSubObject(1, 1), new TestObject(0), testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(new TestObject(1), new TestSubObject(0, 10), testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(new TestSubObject(0, 10), new TestObject(1), testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(to1, ttlo)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(tso1, this)); } /** * Equivalence relationship tests inspired by "Effective Java": * <ul> * <li>reflection</li> * <li>symmetry</li> * <li>transitive</li> * <li>consistency</li> * <li>non-null reference</li> * </ul> * @param to a TestObject * @param toBis a TestObject, equal to to and toTer * @param toTer Left hand side, equal to to and toBis * @param to2 a different TestObject * @param oToChange a TestObject that will be changed */ public void testReflectionEqualsEquivalenceRelationship( TestObject to, TestObject toBis, TestObject toTer, TestObject to2, TestObject oToChange, bool testTransients) { // reflection test Assert.IsTrue(EqualsBuilder.ReflectionEquals(to, to, testTransients)); Assert.IsTrue(EqualsBuilder.ReflectionEquals(to2, to2, testTransients)); // symmetry test Assert.IsTrue(EqualsBuilder.ReflectionEquals(to, toBis, testTransients) && EqualsBuilder.ReflectionEquals(toBis, to, testTransients)); // transitive test Assert.IsTrue( EqualsBuilder.ReflectionEquals(to, toBis, testTransients) && EqualsBuilder.ReflectionEquals(toBis, toTer, testTransients) && EqualsBuilder.ReflectionEquals(to, toTer, testTransients)); // consistency test oToChange.setA(to.getA()); if (oToChange is TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB()); } Assert.IsTrue(EqualsBuilder.ReflectionEquals(oToChange, to, testTransients)); Assert.IsTrue(EqualsBuilder.ReflectionEquals(oToChange, to, testTransients)); oToChange.setA(to.getA() + 1); if (oToChange is TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB() + 1); } Assert.IsTrue(!EqualsBuilder.ReflectionEquals(oToChange, to, testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(oToChange, to, testTransients)); // non-null reference test Assert.IsTrue(!EqualsBuilder.ReflectionEquals(to, null, testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(to2, null, testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(null, to, testTransients)); Assert.IsTrue(!EqualsBuilder.ReflectionEquals(null, to2, testTransients)); Assert.IsTrue(EqualsBuilder.ReflectionEquals((Object) null, (Object) null, testTransients)); } public void testSuper() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); Assert.AreEqual(true, new EqualsBuilder().AppendSuper(true).Append(o1, o1).IsEquals()); Assert.AreEqual(false, new EqualsBuilder().AppendSuper(false).Append(o1, o1).IsEquals()); Assert.AreEqual(false, new EqualsBuilder().AppendSuper(true).Append(o1, o2).IsEquals()); Assert.AreEqual(false, new EqualsBuilder().AppendSuper(false).Append(o1, o2).IsEquals()); } [Test] public void testObject() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); o2.setA(4); Assert.IsTrue(new EqualsBuilder().Append(o1, o2).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, this).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, null).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(null, o2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append((Object) null, (Object) null).IsEquals()); } [Test] public void testLong() { long o1 = 1L; long o2 = 2L; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); } [Test] public void testInt() { int o1 = 1; int o2 = 2; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); } [Test] public void testShort() { short o1 = 1; short o2 = 2; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); } [Test] public void testChar() { char o1 = '1'; char o2 = '2'; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); } [Test] public void testByte() { byte o1 = 1; byte o2 = 2; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); } [Test] public void testDouble() { double o1 = 1; double o2 = 2; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, Double.NaN).IsEquals()); //TODO: atrosin NaN != NaN in java is equal?? //Assert.IsTrue(new EqualsBuilder().Append(Double.NaN, Double.NaN).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(Double.PositiveInfinity, Double.PositiveInfinity).IsEquals()); } /// <summary> /// Tests Append(double lhs, double rhs, double epsilon). /// </summary> /// <remarks> /// This is not in the Java version /// </remarks> [Test] public void testDoubleApproximate() { double o1 = 0.09; double o2 = 0.10; Assert.IsFalse(new EqualsBuilder().Append(o1, o2, 0.005).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(o1, o2, 0.02).IsEquals()); } [Test] public void testFloat() { float o1 = 1; float o2 = 2; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, float.NaN).IsEquals()); //TODO: atrosin NaN != NaN in java is equal?? //Assert.IsTrue(new EqualsBuilder().Append(float.NaN, float.NaN).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(float.PositiveInfinity, float.PositiveInfinity).IsEquals()); } /// <summary> /// Tests Append(float lhs, float rhs, float epsilon). /// </summary> /// <remarks> /// This is not in the Java version /// </remarks> [Test] public void testFloatApproximate() { float o1 = 0.09f; float o2 = 0.10f; Assert.IsFalse(new EqualsBuilder().Append(o1, o2, 0.005f).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(o1, o2, 0.02f).IsEquals()); } [Test] public void testBoolean() { bool o1 = true; bool o2 = false; Assert.IsTrue(new EqualsBuilder().Append(o1, o1).IsEquals()); Assert.IsTrue(!new EqualsBuilder().Append(o1, o2).IsEquals()); } [Test] public void testObjectArray() { TestObject[] obj1 = new TestObject[3]; obj1[0] = new TestObject(4); obj1[1] = new TestObject(5); obj1[2] = null; TestObject[] obj2 = new TestObject[3]; obj2[0] = new TestObject(4); obj2[1] = new TestObject(5); obj2[2] = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj2, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1].setA(6); Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1].setA(5); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[2] = obj1[1]; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[2] = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testLongArray() { long[] obj1 = new long[2]; obj1[0] = 5L; obj1[1] = 6L; long[] obj2 = new long[2]; obj2[0] = 5L; obj2[1] = 6L; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testIntArray() { int[] obj1 = new int[2]; obj1[0] = 5; obj1[1] = 6; int[] obj2 = new int[2]; obj2[0] = 5; obj2[1] = 6; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testShortArray() { short[] obj1 = new short[2]; obj1[0] = 5; obj1[1] = 6; short[] obj2 = new short[2]; obj2[0] = 5; obj2[1] = 6; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testCharArray() { char[] obj1 = new char[2]; obj1[0] = '5'; obj1[1] = '6'; char[] obj2 = new char[2]; obj2[0] = '5'; obj2[1] = '6'; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = '7'; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testByteArray() { byte[] obj1 = new byte[2]; obj1[0] = 5; obj1[1] = 6; byte[] obj2 = new byte[2]; obj2[0] = 5; obj2[1] = 6; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testDoubleArray() { double[] obj1 = new double[2]; obj1[0] = 5; obj1[1] = 6; double[] obj2 = new double[2]; obj2[0] = 5; obj2[1] = 6; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testFloatArray() { float[] obj1 = new float[2]; obj1[0] = 5; obj1[1] = 6; float[] obj2 = new float[2]; obj2[0] = 5; obj2[1] = 6; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testBooleanArray() { bool[] obj1 = new bool[2]; obj1[0] = true; obj1[1] = false; bool[] obj2 = new bool[2]; obj2[0] = true; obj2[1] = false; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1[1] = true; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj2 = null; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); obj1 = null; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testMultiLongArray() { var array1 = new long[2,2]; var array2 = new long[2,2]; for (int i = 0; i < array1.GetLength(0); ++i) { for (int j = 0; j < array1.GetLength(1); j++) { array1[i, j] = (i + 1) * (j + 1); array2[i, j] = (i + 1) * (j + 1); } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMultiIntArray() { var array1 = new int[2,2]; var array2 = new int[2,2]; for (int i = 0; i < array1.GetLength(0); ++i) { for (int j = 0; j < array1.GetLength(1); j++) { array1[i, j] = (i + 1) * (j + 1); array2[i, j] = (i + 1) * (j + 1); } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMultiShortArray() { var array1 = new short[2,2]; var array2 = new short[2,2]; for (short i = 0; i < array1.GetLength(0); ++i) { for (short j = 0; j < array1.GetLength(1); j++) { array1[i, j] = (short) ((i + 1) * (j + 1)); array2[i, j] = (short) ((i + 1) * (j + 1)); } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMultiCharArray() { var array1 = new char[2,2]; var array2 = new char[2,2]; for (int i = 0; i < array1.GetLength(0); ++i) { for (int j = 0; j < array1.GetLength(1); j++) { array1[i, j] = Convert.ToChar(i); array2[i, j] = Convert.ToChar(i); } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = '0'; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMultiByteArray() { var array1 = new byte[2,2]; var array2 = new byte[2,2]; for (byte i = 0; i < array1.GetLength(0); ++i) { for (byte j = 0; j < array1.GetLength(1); j++) { array1[i, j] = i; array2[i, j] = i; } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMultiFloatArray() { var array1 = new float[2,2]; var array2 = new float[2,2]; for (int i = 0; i < array1.GetLength(0); ++i) { for (int j = 0; j < array1.GetLength(1); j++) { array1[i, j] = i; array2[i, j] = i; } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMultiDoubleArray() { var array1 = new double[2,2]; var array2 = new double[2,2]; for (int i = 0; i < array1.GetLength(0); ++i) { for (int j = 0; j < array1.GetLength(1); j++) { array1[i, j] = i; array2[i, j] = i; } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMultiBooleanArray() { var array1 = new bool[2,2]; var array2 = new bool[2,2]; for (int i = 0; i < array1.GetLength(0); ++i) { for (int j = 0; j < array1.GetLength(1); j++) { array1[i, j] = (i == 1) || (j == 1); array2[i, j] = (i == 1) || (j == 1); } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1, 1] = false; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); // compare 1 dim to 2. var array3 = new bool[] {true, true}; Assert.IsFalse(new EqualsBuilder().Append(array1, array3).IsEquals()); Assert.IsFalse(new EqualsBuilder().Append(array3, array1).IsEquals()); Assert.IsFalse(new EqualsBuilder().Append(array2, array3).IsEquals()); Assert.IsFalse(new EqualsBuilder().Append(array3, array2).IsEquals()); } [Test] public void testRaggedArray() { var array1 = new long[2][]; var array2 = new long[2][]; for (int i = 0; i < array1.Length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < array1[i].Length; ++j) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); array1[1][1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testMixedArray() { var array1 = new object[2]; var array2 = new object[2]; for (int i = 0; i < array1.Length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < 2; ++j) { ((long[]) array1[i])[j] = (i + 1) * (j + 1); ((long[]) array2[i])[j] = (i + 1) * (j + 1); } } Assert.IsTrue(new EqualsBuilder().Append(array1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(array1, array2).IsEquals()); ((long[]) array1[1])[1] = 0; Assert.IsTrue(!new EqualsBuilder().Append(array1, array2).IsEquals()); } [Test] public void testObjectArrayHiddenByObject() { TestObject[] array1 = new TestObject[2]; array1[0] = new TestObject(4); array1[1] = new TestObject(5); TestObject[] array2 = new TestObject[2]; array2[0] = new TestObject(4); array2[1] = new TestObject(5); Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1].setA(6); Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testLongArrayHiddenByObject() { long[] array1 = new long[2]; array1[0] = 5L; array1[1] = 6L; long[] array2 = new long[2]; array2[0] = 5L; array2[1] = 6L; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testIntArrayHiddenByObject() { int[] array1 = new int[2]; array1[0] = 5; array1[1] = 6; int[] array2 = new int[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testShortArrayHiddenByObject() { short[] array1 = new short[2]; array1[0] = 5; array1[1] = 6; short[] array2 = new short[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testCharArrayHiddenByObject() { char[] array1 = new char[2]; array1[0] = '5'; array1[1] = '6'; char[] array2 = new char[2]; array2[0] = '5'; array2[1] = '6'; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = '7'; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testByteArrayHiddenByObject() { byte[] array1 = new byte[2]; array1[0] = 5; array1[1] = 6; byte[] array2 = new byte[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testDoubleArrayHiddenByObject() { double[] array1 = new double[2]; array1[0] = 5; array1[1] = 6; double[] array2 = new double[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testFloatArrayHiddenByObject() { float[] array1 = new float[2]; array1[0] = 5; array1[1] = 6; float[] array2 = new float[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = 7; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } [Test] public void testBooleanArrayHiddenByObject() { bool[] array1 = new bool[2]; array1[0] = true; array1[1] = false; bool[] array2 = new bool[2]; array2[0] = true; array2[1] = false; Object obj1 = array1; Object obj2 = array2; Assert.IsTrue(new EqualsBuilder().Append(obj1, obj1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array1).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, obj2).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(obj1, array2).IsEquals()); array1[1] = true; Assert.IsTrue(!new EqualsBuilder().Append(obj1, obj2).IsEquals()); } /** * Tests two instances of classes that can be equal and that are not "related". The two classes are not subclasses * of each other and do not share a parent aside from Object. * See http://issues.apache.org/bugzilla/show_bug.cgi?id=33069 */ [Test] public void testUnrelatedClasses() { Object[] x = new Object[] {new TestACanEqualB(1)}; Object[] y = new Object[] {new TestBCanEqualA(1)}; // sanity checks: Assert.IsTrue(Array.Equals(x, x)); Assert.IsTrue(Array.Equals(y, y)); //in C# they are false Assert.IsFalse(Array.Equals(x, y)); Assert.IsFalse(Array.Equals(y, x)); // real tests: Assert.IsTrue(x[0].Equals(x[0])); Assert.IsTrue(y[0].Equals(y[0])); Assert.IsTrue(x[0].Equals(y[0])); Assert.IsTrue(y[0].Equals(x[0])); Assert.IsTrue(new EqualsBuilder().Append(x, x).IsEquals()); Assert.IsTrue(new EqualsBuilder().Append(y, y).IsEquals()); //in C# they are false Assert.IsFalse(new EqualsBuilder().Append(x, y).IsEquals()); Assert.IsFalse(new EqualsBuilder().Append(y, x).IsEquals()); } /** * Test from http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 */ [Test] public void testNpeForNullElement() { Object[] x1 = new Object[] {1, null, 3}; Object[] x2 = new Object[] {1, 2, 3}; // causes an NPE in 2.0 according to: // http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 new EqualsBuilder().Append(x1, x2); } #region Test Classes public class TestObject { private int a; public TestObject() {} public TestObject(int a) { this.a = a; } public override bool Equals(object o) { if (o == this) { return true; } if (!(o is TestObject)) { return false; } TestObject rhs = (TestObject) o; return (a == rhs.a); } public override int GetHashCode() { return base.GetHashCode(); } public void setA(int a) { this.a = a; } public int getA() { return a; } } public class TestSubObject : TestObject { private int b; public TestSubObject() : base(0) {} public TestSubObject(int a, int b) : base(a) { this.b = b; } public override bool Equals(object o) { if (o == this) { return true; } if (!(o is TestSubObject)) { return false; } TestSubObject rhs = (TestSubObject) o; return base.Equals(o) && (b == rhs.b); } public override int GetHashCode() { return base.GetHashCode(); } public void setB(int b) { this.b = b; } public int getB() { return b; } } public class TestEmptySubObject : TestObject { public TestEmptySubObject(int a) : base(a) {} } public class TestTSubObject : TestObject { [NonSerialized] private int t; public TestTSubObject(int a, int t) : base(a) { this.t = t; } } public class TestTTSubObject : TestTSubObject { [NonSerialized] private int tt; public TestTTSubObject(int a, int t, int tt) : base(a, t) { this.tt = tt; } } public class TestTTLeafObject : TestTTSubObject { private int leafValue; public TestTTLeafObject(int a, int t, int tt, int leafValue) : base(a, t, tt) { this.leafValue = leafValue; } } public class TestTSubObject2 : TestObject { [NonSerialized] private int t; public TestTSubObject2(int a, int t) : base(a) {} public int getT() { return t; } public void setT(int t) { this.t = t; } } public class TestACanEqualB { private int a; public TestACanEqualB(int a) { this.a = a; } public override bool Equals(Object o) { if (o == this) { return true; } if (o is TestACanEqualB) { return a == ((TestACanEqualB) o).getA(); } if (o is TestBCanEqualA) { return a == ((TestBCanEqualA) o).getB(); } return false; } public override int GetHashCode() { return base.GetHashCode(); } public int getA() { return a; } } public class TestBCanEqualA { private int b; public TestBCanEqualA(int b) { this.b = b; } public override bool Equals(Object o) { if (o == this) { return true; } if (o is TestACanEqualB) { return b == ((TestACanEqualB) o).getA(); } if (o is TestBCanEqualA) { return b == ((TestBCanEqualA) o).getB(); } return false; } public override int GetHashCode() { return base.GetHashCode(); } public int getB() { return b; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace FirstAndroidMonoGame { public class ParticleGenerator { List<ParticleSprite> particles; public List<ParticleSprite> Particles { get { return particles; } } public ParticleGenerator(MovingSprite sprite) { } } }
using Microsoft.CSharp; using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace vp { class TypeDeclaration<T> { public string Name { get; set; } public CodeStatement Statement { get; set; } } class Program { static TypeDeclaration<T> DeclareVar<T>(string name, T defaultValue) { TypeDeclaration<T> x = new TypeDeclaration<T>() { Name = name }; x.Statement = new CodeVariableDeclarationStatement(typeof(T),name, new CodePrimitiveExpression(defaultValue)); return x; } static TypeDeclaration<T> DeclareVar<T>(string name, CodeExpression expression) { TypeDeclaration<T> x = new TypeDeclaration<T>() { Name = name }; x.Statement = new CodeVariableDeclarationStatement(typeof(T), name, expression); return x; } static void Main(string[] args) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace samples = new CodeNamespace("Samples"); samples.Imports.Add(new CodeNamespaceImport("System")); compileUnit.Namespaces.Add(samples); CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1"); samples.Types.Add(class1); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello bnogent !")); CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Public; method.Name = "Test"; method.Statements.Add(cs1); method.Statements.Add(DeclareVar<string>("a", "test1").Statement); method.Statements.Add(DeclareVar<int>("b", 0).Statement); method.Statements.Add(DeclareVar<bool>("c", true).Statement); method.Statements.Add(DeclareVar<double>("d", 3.14).Statement); method.Statements.Add(DeclareVar<long>("e", 454L).Statement); method.Statements.Add(DeclareVar<DateTime>("f", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.DateTime"), "Now")).Statement); CodeExpression addMethod = new CodeBinaryOperatorExpression(new CodePrimitiveExpression(1),CodeBinaryOperatorType.Add,new CodePrimitiveExpression(2)); CodeExpression addMethod2 = new CodeBinaryOperatorExpression(new CodePrimitiveExpression(2),CodeBinaryOperatorType.Modulus,addMethod); method.Statements.Add(DeclareVar<double>("x", addMethod2).Statement); class1.Members.Add(method); // to generate code source text StringBuilder b = new StringBuilder(); { CSharpCodeProvider provider = new CSharpCodeProvider(); using (StringWriter sw = new StringWriter(b)) { IndentedTextWriter tw = new IndentedTextWriter(sw, "\t"); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } } { CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.GenerateInMemory = true; //CompilerResults cr = provider.CompileAssemblyFromSource(cp, b.ToString()); CompilerResults cr = provider.CompileAssemblyFromDom(cp, compileUnit); if (cr.Errors.Count > 0) { foreach (CompilerError ce in cr.Errors) { Console.WriteLine("==> {0}", ce.ToString()); } return; } else { Console.WriteLine("**** SOURCE CODE *******************************************"); Console.WriteLine(b.ToString()); Console.WriteLine("************************************************************"); // exec entry method var x = cr.CompiledAssembly.CreateInstance("Samples.Class1"); Type type = cr.CompiledAssembly.GetType("Samples.Class1"); MethodInfo methodInfo = type.GetMethod("Test"); methodInfo.Invoke(x, null); } } } } }
#region Copyright Syncfusion Inc. 2001-2015. // Copyright Syncfusion Inc. 2001-2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { internal class Bubble : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context);; chart.SetBackgroundColor(Color.White); chart.PrimaryAxis = new CategoryAxis {PlotOffset = 50}; chart.SecondaryAxis = new NumericalAxis(); var bubble = new BubbleSeries(); bubble.ColorModel.ColorPalette = ChartColorPalette.Metro; bubble.DataMarker.ShowLabel = true; bubble.DataMarker.UseSeriesPalette = false; bubble.DataMarker.LabelStyle.TextColor = Color.White; var datas = new ObservableArrayList(); datas.Add(new ChartDataPoint("2010", 45, 30)); datas.Add(new ChartDataPoint("2011", 86, 20)); datas.Add(new ChartDataPoint("2012", 23, 15)); datas.Add(new ChartDataPoint("2013", 43, 25)); datas.Add(new ChartDataPoint("2014", 54, 20)); bubble.DataSource = datas; chart.Series.Add(bubble); return chart; } } }
using GetEdge.Classes; using System; using System.Collections.Generic; namespace GetEdge { public class Program { static void Main(string[] args) { Console.WriteLine("Hello Edge from Graph"); Console.WriteLine(""); //Console.WriteLine(GetEdge(one, two)); Vertex one = new Vertex("Pandora"); Vertex two = new Vertex("Arendelle"); Vertex three = new Vertex("Monstropolis"); Vertex four = new Vertex("Metroville"); Vertex five = new Vertex("Naboo"); Vertex six = new Vertex("Narnia"); Vertex seven = new Vertex("StarTrek"); List<object> nodes = new List<object>(); nodes.Add(one); nodes.Add(two); nodes.Add(three); nodes.Add(four); nodes.Add(five); nodes.Add(six); nodes.Add(seven); Graph graph = new Graph(nodes); graph.AddEdge(one, two, 150); graph.AddEdge(two, three, 42); graph.AddEdge(one, four, 82); graph.AddEdge(four, three, 105); graph.AddEdge(four, two, 99); graph.AddEdge(three, five, 73); graph.AddEdge(four, five, 26); graph.AddEdge(five, six, 250); graph.AddEdge(four, six, 37); graph.AddEdge(one, seven, 987); //Dictionary<string, int> neighbors = graph.GetNeighbors(one); string[] cities = new string[]{ "Metroville", "Pandora" }; Console.WriteLine("Below is the trip from Metroville to Pandora"); Console.WriteLine(graph.GetEdge(graph, cities)); Console.ReadLine(); } /* public static Tuple<bool, int> GetEdge(Graph graph, string[] cities) { bool exsist = false; int cost = 0; Tuple<bool, int> output = new Tuple<bool, int>(exsist, cost); Dictionary<string, int> neighbors = new Dictionary<string, int>(); List<Vertex> vertexList = new List<Vertex>(); for (int i = 0; i < cities.Length; i++) { vertexList.Add(new Vertex(i)); } for (int j = 0; j < cities.Length - 1; j++) { neighbors = graph.GetNeighbors(vertexList[j]); //if (neighbors.ContainsKey(vertexList[j + 1])) if (neighbors.Keys.ToString() == cities[j]) { cost += neighbors[cities[j + 1]]; } else { return output; } } return output; } */ } }
using MetroFramework; using MetroFramework.Forms; using PDV.CONTROLER.Funcoes; using PDV.DAO.Custom; using PDV.DAO.Entidades; using PDV.VIEW.App_Context; using System; using System.Text; using System.Windows.Forms; namespace PDV.VIEW.Forms.Configuracoes { public partial class FCONFIG_Contingencia : DevExpress.XtraEditors.XtraForm { private string NOME_TELA = "CONTINGÊNCIA"; public FCONFIG_Contingencia() { InitializeComponent(); } private void FCONFIG_Contingencia_Load(object sender, EventArgs e) { CarregarConfiguracao(); } private void CarregarConfiguracao() { Configuracao config = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGURACAOCONTINGENCIA_JUSTIFICATIVA); if (config != null) ovTXT_Justificativa.Text = Encoding.UTF8.GetString(config.Valor); config = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGURACAOCONTINGENCIA_TEMPOINTERVALO_MOTOR); if (config != null) ovTXT_TempoIntervalo.Text = Encoding.UTF8.GetString(config.Valor); } private void metroButton2_Click(object sender, EventArgs e) { Close(); } private void metroButton1_Click(object sender, EventArgs e) { try { PDVControlador.BeginTransaction(); if (string.IsNullOrEmpty(ovTXT_Justificativa.Text.Trim())) throw new Exception("Preencha a Justificativa."); if (ovTXT_Justificativa.Text.Trim().Length < 15) throw new Exception("A Justificativa deve ter no mínimo 15 caracteres."); if (!FuncoesConfiguracao.Salvar(ChavesConfiguracao.CHAVE_CONFIGURACAOCONTINGENCIA_JUSTIFICATIVA, Encoding.Default.GetBytes(ovTXT_Justificativa.Text))) throw new Exception("Não foi possível salvar a Justificativa."); if (!FuncoesConfiguracao.Salvar(ChavesConfiguracao.CHAVE_CONFIGURACAOCONTINGENCIA_TEMPOINTERVALO_MOTOR, Encoding.Default.GetBytes(ovTXT_TempoIntervalo.Text))) throw new Exception("Não foi possível salvar o tempo de intervalo."); PDVControlador.Commit(); MessageBox.Show(this, "Configurações Salvas com Sucesso.", NOME_TELA); Close(); } catch (Exception Ex) { PDVControlador.Rollback(); MessageBox.Show(this, Ex.Message, NOME_TELA); } } } }
/* * Title : "UIFW"项目框架 * 主题 : UI框架基类 * Description : * 所有窗体类型都要继承于此基类 * 定义了窗体的基本生命周期:显示、隐藏、再显示、冻结 * 窗体遮罩在生命周期函数中进行了封装,无需客户端程序关心 */ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UIFW { public class UIBaseForm : MonoBehaviour { private UIType _CurrentUIType = null; public UIType CurrentUIType { get { return _CurrentUIType; } set { _CurrentUIType = value; } } #region 窗体生命周期 /// <summary> /// 显示 /// </summary> public virtual void Display() { this.gameObject.SetActive(true); if (_CurrentUIType.UIForm_Type == UIFormType.PopUp) { UIMaskMgr.instance.SetMask(this, _CurrentUIType.UIForm_LenecyType); } } /// <summary> /// 隐藏 /// </summary> public virtual void Hiding() { this.gameObject.SetActive(false); if (_CurrentUIType.UIForm_Type == UIFormType.PopUp) { UIMaskMgr.instance.CloseMask(); } } /// <summary> /// 再显示 /// </summary> public virtual void ReDisplay() { this.gameObject.SetActive(true); if (_CurrentUIType.UIForm_Type == UIFormType.PopUp) { UIMaskMgr.instance.SetMask(this, _CurrentUIType.UIForm_LenecyType); } } /// <summary> /// 窗体冻结 /// </summary> public virtual void Freeze() { this.gameObject.SetActive(true); } #endregion /// <summary> /// 发送消息(可供子类修改) /// </summary> /// <param name="msgType"><c>消息类别</c></param> /// <param name="msgName"><c>消息名称</c></param> /// <param name="msgContent"><c>消息内容</c></param> protected virtual void SendMsg(string msgType,string msgName,object msgContent) { MessageKeyValueUpdate msgValue = new MessageKeyValueUpdate(msgName, msgContent); UIMessageMgr.SendMsg(msgType, msgValue); } /// <summary> /// 订阅消息 / 就是对消息增加监听; /// Description : /// 为防止重复监听消息委托,故:先取消对其监听再重新恢复... /// </summary> /// <param name="msgType"><c></c></param> /// <param name="msgTransmitDel"></param> public void RegisterMsg(string msgType,MessageTransmitEventHandler msgTransmitDel) { //先注销对"msgType"类型消息的监听 UIMessageMgr.ClearMsgListener(msgType); //重新添加对"msgType"类型消息的监听 UIMessageMgr.AddMsgListener(msgType, msgTransmitDel); } } }
using System; using System.Collections.Generic; namespace exe_26 { class Program { static void Main(string[] args) { Console.WriteLine("======* Lista de nomes *======"); /* Criando a lista */ List<string> nomes = new List<string>(); int opcao = 1; /* indicando que opção tem que ser igual a 1 para um futuro menu */ while(opcao == 1) /* enquanto opção 1 for verdade o usuario podera prosseguir */ { System.Console.Write("Insira o nome: "); string nomeIns = Console.ReadLine(); /* string nomeIns guarda o nome inserido */ nomes.Add(nomeIns); /* Adiciona o nome na lista */ System.Console.Write("Deseja inserir mais nomes? | 1 = Sim | 2 = Não |: "); opcao = int.Parse(Console.ReadLine()); /*dependendo a opção do usuario ele consegue inserir mais nomes (caso for 1) ou não */ } System.Console.WriteLine();/* pular linha */ nomes.Sort(); /* Vai comparar os nomes usando um comparador padrão */ Console.WriteLine("A lista tem " + nomes.Count + " itens:"); /* aqui ele ira contar quantos itens tem na lista, com o + nomes.Count + */ nomes.ForEach(i => Console.WriteLine(i));/* Não sei muito bem como funciona, mas ele mostra as strings que estão na lista */ } } }
namespace Triton.Game.Mapping { using System; public enum HighlightStateType { NONE, CARD, HIGHLIGHT } }
using JigneshPractical.Model; using System; using System.Collections.Generic; using System.Data.Entity.Core.Objects; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JigneshPractical.Repository { public class User_Repository : IUser_Repository { #region :: Defult Constructor :: private JigneshPracticalEntities context; public User_Repository(JigneshPracticalEntities _context) { this.context = _context; } #endregion public List<MST_City_List_Get_Result> GetCityList() { return context.MST_City_List_Get().ToList(); } public int GetUserCode() { int MessageOutput = 0; var outParam = new ObjectParameter("UserCode", typeof(int)); context.MST_User_Code_Get(outParam); MessageOutput = Convert.ToInt32(outParam.Value); return MessageOutput; } public List<MST_User_Register_Result> MST_User_Register(string UserName, string EmailId, string Passwod, int CityId, out int ReturnValue, out string RetuenMsg) { ReturnValue = 0; RetuenMsg = ""; List<MST_User_Register_Result> _List = new List<MST_User_Register_Result>(); var outRetunrValue = new ObjectParameter("ReturnValue", typeof(int)); var outReturnMsg = new ObjectParameter("RetuenMsg", typeof(string)); _List = context.MST_User_Register(UserName, EmailId, Passwod, CityId, outRetunrValue, outReturnMsg).ToList(); ReturnValue = Convert.ToInt32(outRetunrValue.Value); RetuenMsg = Convert.ToString(outReturnMsg.Value); return _List; } public List<User_Login_Result> User_Login(string UserName, string Passwod, out int ReturnValue, out string RetuenMsg) { ReturnValue = 0; RetuenMsg = ""; List<User_Login_Result> _List = new List<User_Login_Result>(); var outRetunrValue = new ObjectParameter("ReturnValue", typeof(int)); var outReturnMsg = new ObjectParameter("RetuenMsg", typeof(string)); _List = context.User_Login(UserName, Passwod, outRetunrValue, outReturnMsg).ToList(); ReturnValue = Convert.ToInt32(outRetunrValue.Value); RetuenMsg = Convert.ToString(outReturnMsg.Value); return _List; } #region :: Disposed Event :: private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
namespace HandyControlDemo.Data { public class MessageToken { public static readonly string GrowlDemoCtl = nameof(GrowlDemoCtl); public static readonly string LoadingDemoCtl = nameof(LoadingDemoCtl); public static readonly string ImageBrowserDemoCtl = nameof(ImageBrowserDemoCtl); public static readonly string ColorPickerDemoCtl = nameof(ColorPickerDemoCtl); public static readonly string CarouselDemoCtl = nameof(CarouselDemoCtl); public static readonly string CompareSliderDemoCtl = nameof(CompareSliderDemoCtl); public static readonly string TimeBarDemoCtl = nameof(TimeBarDemoCtl); public static readonly string PaginationDemoCtl = nameof(PaginationDemoCtl); public static readonly string AnimationPathDemoCtl = nameof(AnimationPathDemoCtl); public static readonly string StepBarDemoCtl = nameof(StepBarDemoCtl); public static readonly string CirclePanelDemoCtl = nameof(CirclePanelDemoCtl); public static readonly string NumericUpDownDemoCtl = nameof(NumericUpDownDemoCtl); public static readonly string WindowDemoCtl = nameof(WindowDemoCtl); public static readonly string ScrollViewerDemoCtl = nameof(ScrollViewerDemoCtl); public static readonly string PreviewSliderDemoCtl = nameof(PreviewSliderDemoCtl); public static readonly string CircleProgressBarDemoCtl = nameof(CircleProgressBarDemoCtl); public static readonly string TextBoxDemoCtl = nameof(TextBoxDemoCtl); public static readonly string ComboBoxDemoCtl = nameof(ComboBoxDemoCtl); public static readonly string PasswordBoxDemoCtl = nameof(PasswordBoxDemoCtl); public static readonly string SearchBarDemoCtl = nameof(SearchBarDemoCtl); public static readonly string TagDemoCtl = nameof(TagDemoCtl); public static readonly string GifImageDemoCtl = nameof(GifImageDemoCtl); public static readonly string OutlineTextDemoCtl = nameof(OutlineTextDemoCtl); public static readonly string FlipClockDemoCtl = nameof(FlipClockDemoCtl); public static readonly string QQGroupView = nameof(QQGroupView); public static readonly string BlurWindow = nameof(BlurWindow); public static readonly string NoNonClientAreaDragableWindow = nameof(NoNonClientAreaDragableWindow); public static readonly string RateDemoCtl = nameof(RateDemoCtl); public static readonly string ShieldDemoCtl = nameof(ShieldDemoCtl); public static readonly string WaterfallPanelDemoCtl = nameof(WaterfallPanelDemoCtl); public static readonly string CoverViewDemoCtl = nameof(CoverViewDemoCtl); public static readonly string CoverFlowDemoCtl = nameof(CoverFlowDemoCtl); public static readonly string ButtonDemoCtl = nameof(ButtonDemoCtl); public static readonly string ToggleButtonDemoCtl = nameof(ToggleButtonDemoCtl); public static readonly string ExpanderDemoCtl = nameof(ExpanderDemoCtl); public static readonly string ProgressBarDemoCtl = nameof(ProgressBarDemoCtl); public static readonly string TabControlDemoCtl = nameof(TabControlDemoCtl); public static readonly string NaiveTextBoxDemoCtl = nameof(NaiveTextBoxDemoCtl); public static readonly string TextBlockDemoCtl = nameof(TextBlockDemoCtl); public static readonly string NaiveComboBoxDemoCtl = nameof(NaiveComboBoxDemoCtl); public static readonly string NaivePasswordBoxDemoCtl = nameof(NaivePasswordBoxDemoCtl); public static readonly string NaiveTabControlDemoCtl = nameof(NaiveTabControlDemoCtl); public static readonly string CheckBoxDemoCtl = nameof(CheckBoxDemoCtl); public static readonly string ListBoxDemoCtl = nameof(ListBoxDemoCtl); public static readonly string MenuDemoCtl = nameof(MenuDemoCtl); public static readonly string TreeViewDemoCtl = nameof(TreeViewDemoCtl); public static readonly string BorderDemoCtl = nameof(BorderDemoCtl); public static readonly string RadioButtonDemoCtl = nameof(RadioButtonDemoCtl); public static readonly string NaiveScrollViewerDemoCtl = nameof(NaiveScrollViewerDemoCtl); public static readonly string BrushDemoCtl = nameof(BrushDemoCtl); public static readonly string SliderDemoCtl = nameof(SliderDemoCtl); public static readonly string GroupBoxDemoCtl = nameof(GroupBoxDemoCtl); public static readonly string ListViewDemoCtl = nameof(ListViewDemoCtl); public static readonly string RichTextBoxDemoCtl = nameof(RichTextBoxDemoCtl); public static readonly string ToolBarDemoCtl = nameof(ToolBarDemoCtl); public static readonly string CommonWindow = nameof(CommonWindow); public static readonly string CustomNonClientAreaWindow = nameof(CustomNonClientAreaWindow); public static readonly string LoadShowContent = nameof(LoadShowContent); public static readonly string FullSwitch = nameof(FullSwitch); public static readonly string ContributorsView = nameof(ContributorsView); public static readonly string ClearLeftSelected = nameof(ClearLeftSelected); } }
/// /// Generated by Sybase AFX Compiler with templateJ /// Compiler version - 2.2.6.482 /// mbs - false /// using System; using System.Reflection; namespace MMSCAN { public class KeyGenerator : Sybase.Reflection.IClassWithMetaData { #region MetaData private static MMSCAN.intrnl.KeyGeneratorMetaData META_DATA = new MMSCAN.intrnl.KeyGeneratorMetaData(); /// <summary> /// return MetaData object /// </summary> public Sybase.Reflection.ClassMetaData GetClassMetaData() { return META_DATA; } /// <summary> /// return MetaData object /// </summary> public static Sybase.Reflection.EntityMetaData GetMetaData() { return META_DATA; } #endregion /// <summary> /// return EntityClass object for the MBO /// </summary> public static Sybase.Persistence.EntityClass GetMetaClass() { return Sybase.Persistence.EntityClass.GetInstance(META_DATA, MMSCAN.MMSCANDB_RM.Instance); } #region Properties private const int MEMORY_ID_SIZE = 100; //We need to assume that the in memory slot is exhausted //every time the application is launched. Otherwise we //could get duplicated keys problem. private static int __s_memoryIdPointer = 100; private long __firstId ; private long __lastId ; private long __nextId ; private string __remoteId ; private long __batchId ; /// <summary> /// Gets or Sets FirstId /// </summary> public long FirstId { get { return __firstId; } set { if(__firstId != value) { _isDirty = true; } __firstId = value; } } /// <summary> /// Gets or Sets LastId /// </summary> public long LastId { get { return __lastId; } set { if(__lastId != value) { _isDirty = true; } __lastId = value; } } /// <summary> /// Gets or Sets NextId /// </summary> public long NextId { get { return __nextId; } set { if(__nextId != value) { _isDirty = true; } __nextId = value; } } /// <summary> /// Gets or Sets RemoteId /// </summary> public string RemoteId { get { return __remoteId; } set { if(__remoteId != value) { _isDirty = true; } __remoteId = value; } } /// <summary> /// Gets or Sets BatchId /// </summary> public long BatchId { get { return __batchId; } set { if(__batchId != value) { _isDirty = true; } __batchId = value; } } // ignore submited child when call SubmitPending() #endregion #region Constructor and init /// <summary> /// Creates an instance of MMSCAN.KeyGenerator /// </summary> public KeyGenerator() { _init(); } protected void _init() { } #endregion #region Miscs methods protected bool _isNew = true; protected bool _isDirty = false; protected bool _isDeleted = false; /// <summary> /// Returns true if this entity was loaded from the database and was subsequently modified (in memory), ////but the change has not yet been saved to the database. /// </summary> public bool IsDirty { get { return _isDirty; } set { _isDirty = value; } } /// <summary> /// Returns true if this mobile business object is new (i.e. has not yet been created in the database). /// </summary> public bool IsNew { get { return _isNew; } } /// <summary> /// Returns true if this entity was loaded from the database and was subsequently deleted. /// </summary> public bool IsDeleted { get { return _isDeleted; } } /// <summary> /// Get surroget key of the mobile business object /// </summary> public MMSCAN.KeyGeneratorPK _pk() { MMSCAN.KeyGeneratorPK _key = new MMSCAN.KeyGeneratorPK(); _key.RemoteId =(RemoteId); _key.BatchId =(BatchId); return _key; } /// <summary> /// Returns the surroget key as a string /// </summary> public string KeyToString() { return MMSCAN.KeyGeneratorPK.ToJSON(_pk()).ToString(); } /// <summary> /// override method /// </summary> public override bool Equals(object that) { MMSCAN.KeyGenerator that_1 = that as MMSCAN.KeyGenerator; if (that_1 == null) { return false; } MMSCAN.KeyGeneratorPK id_2 = this._pk(); MMSCAN.KeyGeneratorPK id_3 = that_1._pk(); if ((id_2 == null) || (id_3 == null)) { return false; } return id_2.Equals(id_3); } /// <summary> /// override method /// </summary> public override int GetHashCode() { try { return _pk().GetHashCode(); } catch(System.Exception) { MMSCAN.KeyGeneratorPK _key = new MMSCAN.KeyGeneratorPK(); _key.RemoteId =(RemoteId); _key.BatchId =(BatchId); return _key.GetHashCode(); } } #endregion #region copyAll method /// <summary> /// copy the MBO attributes to current MBO /// </summary> public void CopyAll(MMSCAN.KeyGenerator entity) { this._isNew = entity._isNew; this.__firstId = entity.__firstId; this.__lastId = entity.__lastId; this.__nextId = entity.__nextId; this.__remoteId = entity.__remoteId; this.__batchId = entity.__batchId; } #endregion #region callbackHandler private static Sybase.Persistence.ICallbackHandler _callbackHandler; /// <summary> /// Install a callback handler for this MBO /// </summary> public static void RegisterCallbackHandler(Sybase.Persistence.ICallbackHandler handler) { _callbackHandler = handler; } /// <summary> /// Return the callback handler installed for this MBO /// </summary> public static Sybase.Persistence.ICallbackHandler GetCallbackHandler() { if (_callbackHandler == null) { RegisterCallbackHandler(new Sybase.Persistence.DefaultCallbackHandler()); } return _callbackHandler; } #endregion #region Refresh, find and loading methods /// <summary> /// Refresh the mobile business object from database. /// </summary> public void Refresh() { if (!_isNew) { MMSCAN.KeyGenerator ent = Load(_pk()); CopyAll(ent); _isNew = false; _isDirty = false; } } private static MMSCAN.KeyGenerator _find(MMSCAN.KeyGeneratorPK id, String sql, bool findOs, bool findNonPending) { Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBReadConnection(); System.Data.IDataReader _rs = null; int count = 0; try { MMSCAN.KeyGenerator _rt = null; using (System.Data.IDbCommand ps = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, sql)) { com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), ps, "remoteId", id.RemoteId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps, "batchId", id.BatchId); using (_rs = ps.ExecuteReader()) { Sybase.Persistence.ConnectionProfile profile = _conn.GetConnectionProfile(); while (com.sybase.afx.db.ReaderUtil.Read(profile, _rs)) { _rt = new MMSCAN.KeyGenerator(); _rt.Bind(profile, _rs); count++; } if (_rs != null) com.sybase.afx.db.ReaderUtil.Close(profile, _rs, count); if (ps != null) ps.Dispose(); } } return _rt; } catch(System.Data.DataException ex) { throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex); } finally { MMSCAN.MMSCANDB.ReleaseDBConnection(); } } /// <summary> /// Search mobile business object using surrogateKey /// </summary> /// <param name="id">surrogateKey</param> /// <returns>mobile business object</returns> /// <remarks> </remarks> public static MMSCAN.KeyGenerator Find(MMSCAN.KeyGeneratorPK id) { return _find(id, "select \"first_id\",\"last_id\",\"next_id\",\"remote_id\",\"batch_id\" from mmscan_1_8_3_keygenerator where \"remote_id\"=? and \"batch_id\"=?", false, false); } protected void Bind(Sybase.Persistence.ConnectionProfile profile, System.Data.IDataReader rs) { this.__firstId = com.sybase.afx.db.ReaderUtil.GetLong(profile,rs,"firstId",0); this.__lastId = com.sybase.afx.db.ReaderUtil.GetLong(profile,rs,"lastId",1); this.__nextId = com.sybase.afx.db.ReaderUtil.GetLong(profile,rs,"nextId",2); this.__remoteId = com.sybase.afx.db.ReaderUtil.GetString(profile,rs,"remoteId",3); this.__batchId = com.sybase.afx.db.ReaderUtil.GetLong(profile,rs,"batchId",4); _isNew = false; _isDirty = false; } /// <summary> /// Get the mobile business object by surrogate key. /// </summary> /// <param name="id">surrogate key</param> /// <returns>the mobile business object for the surroget key</returns> /// <exception cref="ObjectNotFoundException">Thrown if unable to retrieve mobile business object.</exception> /// <remarks> </remarks> public static MMSCAN.KeyGenerator Load(MMSCAN.KeyGeneratorPK id) { MMSCAN.KeyGenerator _ent = Find(id); if (_ent == null) { throw new Sybase.Persistence.ObjectNotFoundException(Sybase.Persistence.ObjectNotFoundException.OBJECT_NOT_FOUND); } return _ent; } /// <summary> /// Creates or Updates the MBO /// </summary> public void Save() { if (_isNew) { Create(); } else if (_isDirty) { Update(); } } /// <summary> /// Set current MBO attributes by specified MBO. /// </summary> public static MMSCAN.KeyGenerator Merge(MMSCAN.KeyGenerator entity) { MMSCAN.KeyGenerator ent = Find(entity._pk()); if (ent == null) { ent = new MMSCAN.KeyGenerator(); } ent.CopyAll(entity); ent.Save(); return ent; } #endregion #region CUD methods private void CreateBySQL(Sybase.Persistence.ConnectionWrapper _conn, string sql, MMSCAN.KeyGenerator __theObject) { using (System.Data.IDbCommand ps = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, sql)) { com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps, "firstId", __theObject.FirstId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps, "lastId", __theObject.LastId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps, "nextId", __theObject.NextId); com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), ps, "remoteId", __theObject.RemoteId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps, "batchId", __theObject.BatchId); ps.ExecuteNonQuery(); ps.Dispose(); }; } /// <summary> /// create an MBO instance /// </summary> public void Create() { Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBWriteConnection(); try { CreateBySQL(_conn, "insert mmscan_1_8_3_keygenerator (\"first_id\",\"last_id\",\"next_id\",\"remote_id\",\"batch_id\") values (?,?,?,?,?)", this); _isNew = false; _isDeleted = false; _isDirty = false; } catch (Sybase.Persistence.PersistenceException) { throw; } catch (System.Data.DataException ex) { throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex); } finally { MMSCAN.MMSCANDB.ReleaseDBConnection(); } } /// <summary> /// Delete the mobile business object. /// </summary> public void Delete() { Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBWriteConnection(); try { int count = 1; using (System.Data.IDbCommand ps1 = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, "delete mmscan_1_8_3_keygenerator where \"remote_id\"=? and \"batch_id\"=?")) { com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), ps1, "remoteId", this.RemoteId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps1, "batchId", this.BatchId); count = ps1.ExecuteNonQuery(); ps1.Dispose(); }; _isNew = false; _isDeleted = true; } catch (System.Data.DataException ex) { throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex); } finally { MMSCAN.MMSCANDB.ReleaseDBConnection(); } } /// <summary> /// Update the mobile business object /// </summary> public void Update() { Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBWriteConnection(); try { int count = 1; using (System.Data.IDbCommand cmd = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, "update mmscan_1_8_3_keygenerator set \"first_id\"=?,\"last_id\"=?,\"next_id\"=? where \"remote_id\"=? and \"batch_id\"=?")) { com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), cmd, "firstId", this.FirstId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), cmd, "lastId", this.LastId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), cmd, "nextId", this.NextId); com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), cmd, "remoteId", this.RemoteId); com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), cmd, "batchId", this.BatchId); count = cmd.ExecuteNonQuery(); cmd.Dispose(); }; _isNew = false; _isDirty = false; _isDeleted = false; } catch (System.Data.DataException ex) { throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex); } finally { MMSCAN.MMSCANDB.ReleaseDBConnection(); } } #endregion public static Sybase.Persistence.ISynchronizationGroup GetSynchronizationGroup() { return MMSCAN.MMSCANDB.GetSynchronizationGroup("system"); } #region Finder methods /// <summary> /// Find a List of MMSCAN.KeyGenerator /// </summary> /// <exception cref="PersistentException">Thrown if unable to retrieve mobile business object.</exception> /// <remarks> </remarks> public static Sybase.Collections.GenericList<MMSCAN.KeyGenerator> FindAll(int skip, int take) { skip = skip + 1; Sybase.Collections.GenericList<MMSCAN.KeyGenerator> result_2 = new Sybase.Collections.GenericList<MMSCAN.KeyGenerator>(); System.Data.IDataReader rs_4 = null; int count_5 = 0; Sybase.Persistence.ConnectionWrapper _conn = null; try { _conn = MMSCAN.MMSCANDB.AcquireDBReadConnection(); string _selectSQL = " x.\"first_id\",x.\"last_id\",x.\"next_id\",x.\"remote_id\",x.\"batch_id\" from \"mmscan_1_8_3_keygenerator\" x order by x.\"first_id\""; _selectSQL = "select top " + take + " start at " + skip + " " + _selectSQL; using (System.Data.IDbCommand ps_3 = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, _selectSQL)) { using (rs_4 = ps_3.ExecuteReader()) { Sybase.Persistence.ConnectionProfile profile = _conn.GetConnectionProfile(); while (com.sybase.afx.db.ReaderUtil.Read(profile, rs_4)) { MMSCAN.KeyGenerator entity_6 = new MMSCAN.KeyGenerator(); entity_6.Bind(profile, rs_4); count_5++; result_2.Add(entity_6); } if (rs_4 != null) com.sybase.afx.db.ReaderUtil.Close(profile, rs_4, count_5); if (ps_3 != null) ps_3.Dispose(); } } _selectSQL = null; } catch (System.Data.DataException ex) { throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex); } finally { MMSCAN.MMSCANDB.ReleaseDBConnection(); } return result_2; } /// <summary> /// Find a list of MMSCAN.KeyGenerator /// </summary> public static Sybase.Collections.GenericList<MMSCAN.KeyGenerator> FindAll() { return FindAll(0,1000000); } #endregion /// <summary> /// Generate surrogate key. /// </summary> public static long GenerateId() { bool allowConcurrentWrite = false; string strValue = MMSCAN.MMSCANDB.GetConnectionProfile().GetProperty("allowConcurrentWrite"); if (!string.IsNullOrEmpty(strValue)) { allowConcurrentWrite = bool.Parse(strValue); } if (allowConcurrentWrite) { lock(typeof(MMSCAN.KeyGenerator)) { MMSCAN.MMSCANDB.AcquireDBWriteConnection(); try { return _generateId(); } finally { MMSCAN.MMSCANDB.ReleaseDBConnection(); } } } else { MMSCAN.MMSCANDB.AcquireDBWriteConnection(); try { return _generateId(); } finally { MMSCAN.MMSCANDB.ReleaseDBConnection(); } } } private static long _generateId() { Sybase.Collections.GenericList<MMSCAN.KeyGenerator> __list = MMSCAN.KeyGenerator.FindAll(); foreach(MMSCAN.KeyGenerator __o in __list) { long last = __o.LastId; long next = __o.NextId; if (next + MEMORY_ID_SIZE < last) { bool outOfRange = false; if (__s_memoryIdPointer >= MEMORY_ID_SIZE) { outOfRange = true; next += MEMORY_ID_SIZE; __s_memoryIdPointer = 0; } if (__s_memoryIdPointer == 0) { if (outOfRange) __o.NextId =(next); else __o.NextId =(next + MEMORY_ID_SIZE); __o.Update(); } long result = next + __s_memoryIdPointer; __s_memoryIdPointer++; return result; } else if (next <= last) { next = last; __o.NextId = (next + 1); __o.Update(); return next; } } throw new Sybase.Persistence.SynchronizeRequiredException(Sybase.Persistence.SynchronizeRequiredException.KEY_GENERATOR_NOT_POPULATED, "Illegal key generator status: the key generator must be populated first."); } /// <summary> /// Sybase internal use only. /// <summary> public static bool InitSync() { lock(typeof(MMSCAN.MMSCANDB)) { Sybase.Persistence.LocalTransaction _tran = null; bool ok_3 = false; try { _tran = MMSCAN.MMSCANDB.BeginTransaction(); ok_3 = false; Sybase.Collections.GenericList<MMSCAN.KeyGenerator> list_4 = MMSCAN.KeyGenerator.FindAll(); int size_5 = list_4.Count; if ((size_5 == 0)) { MMSCAN.KeyGenerator batch_6 = new MMSCAN.KeyGenerator(); batch_6.RemoteId =("."); batch_6.BatchId =(1); batch_6.LastId =(-1); batch_6.Create(); MMSCAN.KeyGenerator batch_7 = new MMSCAN.KeyGenerator(); batch_7.RemoteId =("."); batch_7.BatchId =(2); batch_7.LastId =(-1); batch_7.Create(); ok_3 = true; return true; } if ((size_5 == 4)) { foreach(MMSCAN.KeyGenerator item_8 in list_4) { if ((item_8.LastId == -1)) { item_8.Delete(); } } list_4 = MMSCAN.KeyGenerator.FindAll(); } MMSCAN.KeyGenerator batch_10 = list_4[0]; ok_3 = true; long last_11 = batch_10.LastId; long next_12 = batch_10.NextId; return ((last_11 == -1)) || (next_12 > last_11); } catch(Sybase.Persistence.PersistenceException) { ok_3 = false; throw; } finally { if(_tran != null) { _tran.EndTransaction(ok_3); } } } } public static string GenerateGuid() { return com.sybase.afx.util.StringUtil.Guid32(); } /// <summary> /// Returns the log record list. /// </summary> public Sybase.Collections.GenericList<Sybase.Persistence.ILogRecord> GetLogRecords() { return MMSCAN.LogRecordImpl.FindByEntity("KeyGenerator", KeyToString()); } #region JSON methods /// <summary> /// Sybase internal use only. /// <summary> public static MMSCAN.KeyGenerator __fromJSON(object _json) { return MMSCAN.KeyGenerator.FromJSON(_json); } internal static MMSCAN.KeyGenerator FromJSON(object _json) { if (_json == null) { return null; } else { MMSCAN.KeyGenerator _obj = new MMSCAN.KeyGenerator(); _obj._fromJSON((com.sybase.afx.json.JsonObject)_json); return _obj; } } internal void _fromJSON(com.sybase.afx.json.JsonObject _json) { __firstId = (_json.GetLong("firstId")); __lastId = (_json.GetLong("lastId")); __nextId = (_json.GetLong("nextId")); __remoteId = (_json.GetString("remoteId")); __batchId = (_json.GetLong("batchId")); char op_2 = _json.GetChar("_op"); _isNew = (op_2 == 'C'); _isDirty = (op_2 == 'U'); _isDeleted = (op_2 == 'D'); } /// <summary> /// Sybase internal use only. /// <summary> public static com.sybase.afx.json.JsonObject __toJSON(MMSCAN.KeyGenerator _object) { return MMSCAN.KeyGenerator.ToJSON(_object); } /// <summary> /// Sybase internal use only. /// <summary> public static com.sybase.afx.json.JsonObject __toJSON(MMSCAN.KeyGenerator _object, bool _includeBigAttribute) { if(_includeBigAttribute) { return MMSCAN.KeyGenerator.ToJSON(_object); } else { return MMSCAN.KeyGenerator.ToJSONWithoutBigAttribute(_object); } } internal static com.sybase.afx.json.JsonObject ToJSONWithoutUserAttributes(MMSCAN.KeyGenerator _object) { return MMSCAN.KeyGenerator.ToJSON(_object, false, false, false); } internal static com.sybase.afx.json.JsonObject ToJSONWithoutBigAttribute(MMSCAN.KeyGenerator _object) { return MMSCAN.KeyGenerator.ToJSON(_object, false, false, true); } internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.KeyGenerator _object) { return MMSCAN.KeyGenerator.ToJSON(_object, false, true, true); } internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.KeyGenerator _object, bool __buildGraph) { return ToJSON(_object, __buildGraph, true, true); } internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.KeyGenerator _object, bool __buildGraph, bool _includeBigAttribute) { return ToJSON(_object, __buildGraph, _includeBigAttribute, true); } internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.KeyGenerator _object, bool __buildGraph, bool _includeBigAttribute, bool _includeUserAttributes) { if ((_object == null)) { return null; } else { return _object._toJSON(__buildGraph,_includeBigAttribute,_includeUserAttributes); } } internal com.sybase.afx.json.JsonObject _toJSON() { return this._toJSON(false, true, true); } internal com.sybase.afx.json.JsonObject _toJSON(bool __buildGraph) { return _toJSON(__buildGraph, true, true); } internal com.sybase.afx.json.JsonObject _toJSON(bool __buildGraph, bool _includeBigAttribute, bool _includeUserAttributes) { com.sybase.afx.json.JsonObject _json = new com.sybase.afx.json.JsonObject(); char op_2 = 'N'; if (this.IsNew) { op_2 = 'C'; } else if (this.IsDirty) { op_2 = 'U'; } else if (this.IsDeleted) { op_2 = 'D'; } _json.Put("_op", op_2); _json.Put("firstId", FirstId); _json.Put("lastId", LastId); _json.Put("nextId", NextId); _json.Put("remoteId", RemoteId); _json.Put("batchId", BatchId); return _json; } /// <summary> /// Sybase internal use only. /// <summary> public static Sybase.Collections.GenericList<KeyGenerator> __fromJSONList(object __array) { return MMSCAN.KeyGenerator.FromJSONList(__array); } /// <summary> /// Sybase internal use only. /// <summary> public static com.sybase.afx.json.JsonArray __toJSONList(Sybase.Collections.GenericList<KeyGenerator> __array) { return MMSCAN.KeyGenerator.ToJSONList(__array); } internal static Sybase.Collections.GenericList<KeyGenerator> FromJSONList(object __array) { com.sybase.afx.json.JsonArray _array = (com.sybase.afx.json.JsonArray)__array; Sybase.Collections.GenericList<KeyGenerator> _list; if (_array == null) { _list = null; } else { int _size = _array.Count; _list = new Sybase.Collections.GenericList<KeyGenerator>(_size); foreach (object __o in _array) { _list.Add((MMSCAN.KeyGenerator)(MMSCAN.KeyGenerator.FromJSON((com.sybase.afx.json.JsonObject)(__o)))); } } return _list; } internal static com.sybase.afx.json.JsonArray ToJSONList(Sybase.Collections.GenericList<KeyGenerator> _list) { return MMSCAN.KeyGenerator.ToJSONList(_list, false); } internal static com.sybase.afx.json.JsonArray ToJSONListWithoutBigAttribute(Sybase.Collections.GenericList<KeyGenerator> _list) { return MMSCAN.KeyGenerator.ToJSONList(_list, false, false); } internal static com.sybase.afx.json.JsonArray ToJSONList(Sybase.Collections.GenericList<KeyGenerator> _list, bool __buildGraph) { return MMSCAN.KeyGenerator.ToJSONList(_list, __buildGraph, true); } internal static com.sybase.afx.json.JsonArray ToJSONList(Sybase.Collections.GenericList<KeyGenerator> _list, bool __buildGraph, bool __includeBig) { com.sybase.afx.json.JsonArray array_1; if ((_list == null)) { array_1 = null; } else { array_1 = new com.sybase.afx.json.JsonArray(_list.Count); foreach(MMSCAN.KeyGenerator __o in _list) { array_1.Add(MMSCAN.KeyGenerator.ToJSON(__o, __buildGraph, __includeBig)); } } return array_1; } #endregion } }