text stringlengths 13 6.01M |
|---|
using EddiEvents;
namespace EddiNavigationService
{
public interface IQueryResolver
{
QueryType Type { get; }
RouteDetailsEvent Resolve ( Query query );
}
}
|
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 Sistema_de_Vendas
{
public partial class Form1 : Form
{
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
txt_username.Focus();
}
private void btn_entrar_Click(object sender, EventArgs e)
{
string queryConsulta = String.Format(@"
SELECT
tbu.N_IDUSUARIO,
tbu.T_USERNAME,
tbu.T_SENHA,
tbu.N_NIVEL,
tbf.T_NOMEFUNCIONARIO
FROM
tb_usuarios as tbu
INNER JOIN
tb_funcionarios as tbf on tbf.N_IDFUNCIONARIO = tbu.N_IDFUNCIONARIO
WHERE
tbu.T_USERNAME ='{0}'
and
tbu.T_SENHA = '{1}'
", txt_username.Text,txt_senha.Text);
if (txt_username.Text == "" || txt_senha.Text == "")
{
MessageBox.Show("Os campos não podem ficar em branco");
return;
}
dt = Banco.dql(queryConsulta);
if (dt.Rows.Count == 1)
{
Globais.nome = dt.Rows[0].Field<string>("T_NOMEFUNCIONARIO");
Globais.username = dt.Rows[0].Field<string>("T_USERNAME");
Globais.senha = dt.Rows[0].Field<string>("T_SENHA");
Globais.nivel = int.Parse(dt.Rows[0].Field<Int64>("N_NIVEL").ToString());
this.Hide();
// MessageBox.Show(Globais.nome);
Frm_Menu frm_Menu = new Frm_Menu(this);
frm_Menu.Show();
}
else
{
MessageBox.Show("Username ou senha incorreto");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc.Formatters;
using UKPR.Hermes.Asp.NetCoreDAL.Services;
using Swashbuckle.AspNetCore.Swagger;
namespace UKPR.Hermes.Asp.NetCoreApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(setupAction =>
{
setupAction.ReturnHttpNotAcceptable = true;
var jsonOutputFormatter = setupAction.OutputFormatters
.OfType<JsonOutputFormatter>().FirstOrDefault();
if (jsonOutputFormatter != null)
{
jsonOutputFormatter.SupportedMediaTypes
.Add("application/ukpr.hermes.getavailibilitywithwindows+json");
}
var jsonInputFormatter = setupAction.InputFormatters
.OfType<JsonInputFormatter>().FirstOrDefault();
if (jsonInputFormatter != null)
{
jsonInputFormatter.SupportedMediaTypes
.Add("application/ukpr.hermes.availibilitywithwindowsforcreation+json");
}
})
.AddJsonOptions(options =>
{
options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "My API",
Description = "My First ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact() { Name = "Talking Dotnet", Email = "contact@talkingdotnet.com", Url = "www.talkingdotnet.com" }
});
});
// Configure CORS so the API allows requests from JavaScript.
// For demo purposes, all origins/headers/methods are allowed.
services.AddCors(options =>
{
options.AddPolicy("AllowAllOriginsHeadersAndMethods",
builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
//// register the DbContext on the container, getting the connection string from
//// appsettings (note: use this during development; in a production environment,
//// it's better to store the connection string in an environment variable)
// var connectionString = Configuration["ConnectionStrings:TourManagementDB"];
//services.AddDbContext<TourManagementContext>(o => o.UseSqlServer(connectionString));
//// register the repository
services.AddScoped<IAvailibilityManagementRepository, AvailibilityManagementRepository>();
// register an IHttpContextAccessor so we can access the current
// HttpContext in services by injecting it
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//// register the user info service
// services.AddScoped<IUserInfoService, UserInfoService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Run(async context =>
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An unexpected fault happened. Try again later.");
});
});
}
AutoMapper.Mapper.Initialize(config =>
{
config.CreateMap<Models.AvailabilityDeclaration, Dtos.AvailibilityDeclaration>();
config.CreateMap<Models.NGWindow, Dtos.NGWindow>();
config.CreateMap<Dtos.AvailibilityDeclarationForCreation, Models.AvailabilityDeclaration>();
config.CreateMap<Dtos.AvailibilityWithWindowsForCreation, Models.AvailabilityDeclaration>();
config.CreateMap<Dtos.NGWindowForCreation, Models.NGWindow>();
config.CreateMap<Models.AvailabilityDeclaration, Dtos.AvailibilityWithWindows>();
config.CreateMap<Models.NGWindow, Dtos.AvailibilityWithWindows>();
});
// Enable CORS
app.UseCors("AllowAllOriginsHeadersAndMethods");
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
}
}
|
using NGeoNames.Entities;
using System;
using System.Globalization;
namespace NGeoNames.Parsers
{
/// <summary>
/// Provides methods for parsing an <see cref="ExtendedGeoName"/> object from a string-array.
/// </summary>
public class ExtendedGeoNameParser : BaseParser<ExtendedGeoName>
{
private static readonly char[] csv = { ',' };
/// <summary>
/// Gets wether the file/stream has (or is expected to have) comments (lines starting with "#").
/// </summary>
public override bool HasComments
{
get { return false; }
}
/// <summary>
/// Gets the number of lines to skip when parsing the file/stream (e.g. 'headers' etc.).
/// </summary>
public override int SkipLines
{
get { return 0; }
}
/// <summary>
/// Gets the number of fields the file/stream is expected to have; anything else will cause a <see cref="ParserException"/>.
/// </summary>
public override int ExpectedNumberOfFields
{
get { return 19; }
}
/// <summary>
/// Parses the specified data into an <see cref="ExtendedGeoName"/> object.
/// </summary>
/// <param name="fields">The fields/data representing an <see cref="ExtendedGeoName"/> to parse.</param>
/// <returns>Returns a new <see cref="ExtendedGeoName"/> object.</returns>
public override ExtendedGeoName Parse(string[] fields)
{
return new ExtendedGeoName
{
Id = int.Parse(fields[0]),
Name = fields[1],
NameASCII = fields[2],
AlternateNames = fields[3].Split(csv, StringSplitOptions.RemoveEmptyEntries),
Latitude = double.Parse(fields[4], CultureInfo.InvariantCulture),
Longitude = double.Parse(fields[5], CultureInfo.InvariantCulture),
FeatureClass = fields[6],
FeatureCode = fields[7],
CountryCode = fields[8],
AlternateCountryCodes = fields[9].Split(csv, StringSplitOptions.RemoveEmptyEntries),
Admincodes = new[] { fields[10], fields[11], fields[12], fields[13] },
Population = long.Parse(fields[14]),
Elevation = fields[15].Length > 0 ? (int?)int.Parse(fields[15]) : null,
Dem = int.Parse(fields[16]),
Timezone = fields[17].Replace("_", " "),
ModificationDate = DateTime.ParseExact(fields[18], "yyyy-MM-dd", CultureInfo.InvariantCulture)
};
}
}
}
|
using EPiServer;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using EPiServer.Web.Mvc;
using EpiserverSiteFromScratch.Models.Pages;
using EpiserverSiteFromScratch.Models.ViewModels;
using System.Web.Mvc;
namespace EpiserverSiteFromScratch.Controllers
{
public class StartPageController : PageController<StartPage>
{
public ActionResult Index(StartPage currentPage)
{
var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
var startpage = contentLoader.Get<PageData>(ContentReference.StartPage);
var logo = startpage.GetPropertyValue<ContentReference>("pageImage");
var model = PageViewModel.Create(currentPage);
return View(model);
}
}
} |
using System;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Collections.Generic;
using ClassLibrary.Models;
using System.Linq;
namespace MongoFeeder.Services
{
public class DataBaseTaker
{
public Car GerCarById(ObjectId id)
{
var db = DBConnection.DBConnectionInstance();
var car = db.GetCollection<Car>("Cars");
var result = car.AsQueryable().FirstOrDefault(c => c.Id == id);
return result;
}
public List<Car> GetAllCars()
{
var db = DBConnection.DBConnectionInstance();
var cars = db.GetCollection<Car>("Cars");
var result = cars.AsQueryable().Select(c => new Car()
{
Brand = c.Brand,
Languages = c.Languages,
Model = c.Model,
ProductionYear = c.ProductionYear
}).ToList();
return result;
}
}
}
|
namespace DZzzz.Net.Serialization.Interfaces
{
public interface ISerializer<T>
{
T Serialize<TK>(TK @object);
TK Deserialize<TK>(T value);
}
} |
namespace PhotonInMaze.Common.Controller {
public interface IArrowButtonController {
bool IsArrowPresent();
void ReinitializeArrowHintsCount();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SpaceHosting.Index.Sparnn.Distances;
using SpaceHosting.Index.Sparnn.Helpers;
using MSparseVector = MathNet.Numerics.LinearAlgebra.Double.SparseVector;
namespace SpaceHosting.Index.Sparnn.Clusters
{
internal sealed class TerminalClusterIndex<TRecord> : BaseClusterIndex<TRecord>
where TRecord : notnull
{
private readonly IMatrixMetricSearchSpaceFactory matrixMetricSearchSpaceFactory;
private IMatrixMetricSearchSpace<TRecord> recordSpace = null!;
private RecordsToIndexMap recordsToIndex = null!;
public TerminalClusterIndex(
Random random,
IList<MSparseVector> featureVectors,
TRecord[] recordsData,
IMatrixMetricSearchSpaceFactory matrixMetricSearchSpaceFactory,
int desiredClusterSize)
: base(random, desiredClusterSize)
{
this.matrixMetricSearchSpaceFactory = matrixMetricSearchSpaceFactory;
Init(featureVectors, recordsData);
}
public override bool IsOverflowed => recordSpace.Elements.Count > desiredClusterSize * 5;
public override Task InsertAsync(IList<MSparseVector> featureVectors, TRecord[] records)
{
return Task.Run(
() =>
{
recordsToIndex.AddRecords(records);
Reindex(featureVectors, records);
});
}
public override (IList<MSparseVector> featureVectors, IList<TRecord> records) GetChildData()
{
return (recordSpace.FeatureMatrix.Vectors, recordSpace.Elements);
}
public override Task DeleteAsync(IList<TRecord> recordsToBeDeleted)
{
return Task.Run(() => DeleteInternal(recordsToBeDeleted));
}
protected override Task<IEnumerable<NearestSearchResult<TRecord>[]>> SearchInternalAsync(IList<MSparseVector> featureVectors, int resultsNumber, int clustersSearchNumber)
{
return recordSpace.SearchNearestAsync(featureVectors, resultsNumber);
}
protected override void Init(IList<MSparseVector> featureVectors, TRecord[] recordsData)
{
recordSpace = matrixMetricSearchSpaceFactory.Create(featureVectors, recordsData, searchBatchSize);
recordsToIndex = new RecordsToIndexMap(recordsData);
}
private void DeleteInternal(IList<TRecord> recordsToBeDeleted)
{
var indexesOfEntitiesToBeDeleted = recordsToIndex
.GetIndexes(recordsToBeDeleted)
.Where(i => i != null)
.Select(i => i!.Value)
.ToHashSet();
if (indexesOfEntitiesToBeDeleted.Count == 0)
return;
var newRecords = recordSpace.Elements
.Where((record, i) => !indexesOfEntitiesToBeDeleted.Contains(i));
var newFeatureVectors = recordSpace.FeatureMatrix.Vectors
.DeleteRows(indexesOfEntitiesToBeDeleted.ToArray());
Init(newFeatureVectors, newRecords.ToArray());
}
private class RecordsToIndexMap
{
private readonly IDictionary<TRecord, int> recordsToIndex;
public RecordsToIndexMap(TRecord[] recordsData)
{
recordsToIndex = recordsData
.Select((record, i) => new {Record = record, Index = i})
.ToDictionary(x => x.Record, x => x.Index);
}
public void AddRecords(TRecord[] recordsData)
{
var nextIndex = recordsToIndex.Keys.Count;
foreach (var record in recordsData)
{
recordsToIndex[record] = nextIndex++;
}
}
public IEnumerable<int?> GetIndexes(IEnumerable<TRecord> recordsToBeDeleted)
{
foreach (var record in recordsToBeDeleted)
{
if (recordsToIndex.TryGetValue(record, out var i))
{
yield return i;
}
else
{
yield return null;
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Models
{
public class Shipping : IModel
{
public int ShippingId { get; set; }
public string CompanyName { get; set; }
public decimal Charge { get; set; }
public void FromSqlReader(SqlDataReader reader)
{
if (!reader.HasRows) return;
ShippingId = int.Parse(reader["ShippingId"].ToString());
CompanyName = reader["CompanyName"].ToString();
Charge = decimal.Parse(reader["Charge"].ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Kingdee.CAPP.UI.ProcessDataManagement
{
/// <summary>
/// 类型说明:公用输入界面
/// 作 者:jason.tang
/// 完成时间:2013-03-13
/// </summary>
public partial class CommonInputFrm : BaseSkinForm
{
#region 变量和属性声明
public object CommonObject
{
get;
set;
}
/// <summary>
/// 窗体标题
/// </summary>
public string FormTitle
{
get;
set;
}
#endregion
#region 窗体控件事件
public CommonInputFrm()
{
InitializeComponent();
}
/// <summary>
/// 确认
/// </summary>
private void btnConfirm_Click(object sender, EventArgs e)
{
CommonObject = pgCommonProperty.SelectedObject;
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
/// <summary>
/// Load事件
/// </summary>
private void CommonInputFrm_Load(object sender, EventArgs e)
{
pgCommonProperty.SelectedObject = CommonObject;
this.Text = FormTitle;
}
/// <summary>
/// 取消
/// </summary>
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
}
}
|
using System;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Atc.CodeAnalysis.CSharp.SyntaxFactories
{
public static class SyntaxAttributeListFactory
{
public static AttributeListSyntax Create(string attributeName)
{
if (attributeName == null)
{
throw new ArgumentNullException(nameof(attributeName));
}
return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxAttributeFactory.Create(attributeName)));
}
public static AttributeListSyntax Create(string attributeName, AttributeArgumentListSyntax attributeArgumentList)
{
if (attributeName == null)
{
throw new ArgumentNullException(nameof(attributeName));
}
return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxAttributeFactory.Create(attributeName)
.WithArgumentList(attributeArgumentList)));
}
public static AttributeListSyntax CreateWithOneItemWithOneArgument(string attributeName, string argumentValue)
{
if (attributeName == null)
{
throw new ArgumentNullException(nameof(attributeName));
}
return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxAttributeFactory.Create(attributeName)
.WithArgumentList(
SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SingletonSeparatedList(
SyntaxAttributeArgumentFactory.Create(argumentValue))))));
}
public static AttributeListSyntax CreateWithOneItemWithOneArgumentWithNameEquals(string attributeName, string argumentName, string argumentValue)
{
if (attributeName == null)
{
throw new ArgumentNullException(nameof(attributeName));
}
return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxAttributeFactory
.Create(attributeName)
.WithArgumentList(
SyntaxAttributeArgumentListFactory.CreateWithOneItemWithNameEquals(argumentName, argumentValue))));
}
}
} |
using System;
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
public class VoidBaseEventReferenceUsage
{
public const int EVENT = 0;
public const int EVENT_INSTANCER = 1;
public const int COLLECTION_CLEARED_EVENT = 2;
public const int LIST_CLEARED_EVENT = 3;
public const int COLLECTION_INSTANCER_CLEARED_EVENT = 4;
public const int LIST_INSTANCER_CLEARED_EVENT = 5;
}
/// <summary>
/// Event Reference of type `Void`. Inherits from `AtomBaseEventReference<Void, VoidEvent, VoidEventInstancer>`.
/// </summary>
[Serializable]
public sealed class VoidBaseEventReference : AtomBaseEventReference<
Void,
VoidEvent,
VoidEventInstancer>, IGetEvent
{
/// <summary>
/// Get or set the Event used by the Event Reference.
/// </summary>
/// <value>The event of type `E`.</value>
public override VoidEvent Event
{
get
{
switch (_usage)
{
case (VoidBaseEventReferenceUsage.COLLECTION_CLEARED_EVENT): return _collection != null ? _collection.Cleared : null;
case (VoidBaseEventReferenceUsage.LIST_CLEARED_EVENT): return _list != null ? _list.Cleared : null;
case (VoidBaseEventReferenceUsage.COLLECTION_INSTANCER_CLEARED_EVENT): return _collectionInstancer != null ? _collectionInstancer.Cleared : null;
case (VoidBaseEventReferenceUsage.LIST_INSTANCER_CLEARED_EVENT): return _listInstancer != null ? _listInstancer.Cleared : null;
case (VoidBaseEventReferenceUsage.EVENT_INSTANCER): return _eventInstancer != null ? _eventInstancer.Event : null;
case (VoidBaseEventReferenceUsage.EVENT):
default:
return _event;
}
}
set
{
switch (_usage)
{
case (VoidBaseEventReferenceUsage.COLLECTION_CLEARED_EVENT):
{
_collection.Cleared = value;
break;
}
case (VoidBaseEventReferenceUsage.LIST_CLEARED_EVENT):
{
_list.Cleared = value;
break;
}
case (VoidBaseEventReferenceUsage.COLLECTION_INSTANCER_CLEARED_EVENT):
{
_collectionInstancer.Cleared = value;
break;
}
case (VoidBaseEventReferenceUsage.LIST_INSTANCER_CLEARED_EVENT):
{
_listInstancer.Cleared = value;
break;
}
case (VoidBaseEventReferenceUsage.EVENT):
{
_event = value;
break;
}
default:
throw new NotSupportedException($"Event not reassignable for usage {_usage}.");
}
}
}
/// <summary>
/// Collection used if `Usage` is set to `COLLECTION_CLEARED_EVENT`.
/// </summary>
[SerializeField]
private AtomCollection _collection = default(AtomCollection);
/// <summary>
/// List used if `Usage` is set to `LIST_CLEARED_EVENT`.
/// </summary>
[SerializeField]
private AtomList _list = default(AtomList);
/// <summary>
/// Collection Instancer used if `Usage` is set to `COLLECTION_INSTANCER_CLEARED_EVENT`.
/// </summary>
[SerializeField]
private AtomCollectionInstancer _collectionInstancer = default(AtomCollectionInstancer);
/// <summary>
/// List Instancer used if `Usage` is set to `LIST_INSTANCER_CLEARED_EVENT`.
/// </summary>
[SerializeField]
private AtomListInstancer _listInstancer = default(AtomListInstancer);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Recursion
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number");
int n = Convert.ToInt32(Console.ReadLine());
fibonacci(0, 1, 1, n);
Console.ReadLine();
}
static void fibonacci(int a, int b, int count, int n)
{
Console.WriteLine(a);
if (count < n)
fibonacci(b, a + b, count + 1, n);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio4
{
class Program
{
static void Main(string[] args)
{
/*Calculadora
suma todo void
resta no recibe pero retorna
multiplicacion reciba parametro pero no retorne
division recibe y retorna*/
int flag = 0;
double n1, n2;
do
{
Console.WriteLine("Bienvenido. Seleccione el calculo a realizar: " +
"\n1.Suma\n2.Resta\n3.Multiplicacion\n4.Division\n5.Salir");
flag = int.Parse(Console.ReadLine());
switch (flag)
{
case 1: Suma();
break;
case 2: double resta = Resta();
Console.WriteLine("El resultado de la resta es: " + resta);
break;
case 3:
Console.WriteLine("Ingrese primer numero (puede contener decimales): ");
n1 = double.Parse(Console.ReadLine());
Console.WriteLine("Ingrese segundo numero (puede contener decimales): ");
n2 = double.Parse(Console.ReadLine());
Multiplicacion(n1, n2);
break;
case 4:
Console.WriteLine("Ingrese primer numero (puede contener decimales): ");
n1 = double.Parse(Console.ReadLine());
eti1:
Console.WriteLine("Ingrese segundo numero (puede contener decimales): ");
n2 = double.Parse(Console.ReadLine());
double div = Division(n1, n2);
if (div == 0.0)
{
Console.WriteLine("Error! No se puede dividir por cero.");
Console.WriteLine("Ingrese un numero valido");
goto eti1;
}
else
{
Console.WriteLine("El resultado de la division es: " + div);
}
break;
case 5: Console.WriteLine("\nGracias por usar mi calculadora. Que tengas un buen dia :)\n");
break;
default: Console.WriteLine("Opcion incorrecta. Seleccione entre el 1 y 5.\n");
break;
}
} while (flag != 5);
}
public static void Suma()
{
Console.WriteLine("Ingrese primer numero (puede contener decimales): ");
double n1 = double.Parse(Console.ReadLine());
Console.WriteLine("Ingrese segundo numero (puede contener decimales): ");
double n2 = double.Parse(Console.ReadLine());
Console.WriteLine("La suma de {0} + {1} es igual a {2}", n1, n2, (n1 + n2));
}
public static double Resta()
{
Console.WriteLine("Ingrese primer numero (puede contener decimales): ");
double n1 = double.Parse(Console.ReadLine());
Console.WriteLine("Ingrese segundo numero (puede contener decimales): ");
double n2 = double.Parse(Console.ReadLine());
return n1 + n2;
}
public static void Multiplicacion(double n1, double n2)
{
Console.WriteLine("La multiplicacion de {0} * {1} es igual a {2}", n1, n2, (n1 * n2));
}
public static double Division(double n1, double n2)
{
if (n2 == 0)
{
return 0.0;
}
else
{
return n1 / n2;
}
}
}
}
|
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Proxy.SAPProvService;
using Pe.Stracon.SGC.Infraestructura.Proxy.SAPBienService;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Pe.Stracon.SGC.Infraestructura.Proxy.SAP
{
/// <summary>
/// Proxy del servicio de SAP
/// </summary>
/// <remarks>
/// Creación: Qualis-Tech : 12/12/2018 <br />
/// </remarks>
public class SAPProxy : ISAPProxy
{
/// <summary>
/// Obtiene los proveedores
/// </summary>
/// <param name="request">Request de búsqueda</param>
/// <returns>Lista de Proveedores</returns>
public List<ProveedorSAPLogic> ZSGC_OBTPROVEEDORES(string request)
{
List<ProveedorSAPLogic> Proveedores = new List<ProveedorSAPLogic>();
ZWS_ZSGC_OBTPROVEEDORESClient get_SAPProveedor = new ZWS_ZSGC_OBTPROVEEDORESClient();
get_SAPProveedor.ClientCredentials.UserName.UserName = "STRACON";
get_SAPProveedor.ClientCredentials.UserName.Password = "seidor2018";
var get_SAPProveedor_Input = new ZSGC_OBTPROVEEDORES();
Int64 Num;
bool isNum = Int64.TryParse(request.ToString(), out Num);
if (isNum)
{
get_SAPProveedor_Input.I_BP = request.ToString() ;
}
else
{
get_SAPProveedor_Input.I_BP = "*" + request.ToString() + "*";
}
var get_SAPProveedor_Response = new ZSGC_OBTPROVEEDORESResponse();
get_SAPProveedor_Response = get_SAPProveedor.ZSGC_OBTPROVEEDORES(get_SAPProveedor_Input);
foreach (var item in get_SAPProveedor_Response.E_PROVEEDOR)
{
ProveedorSAPLogic proveedor = new ProveedorSAPLogic();
proveedor.Ruc = item.IDENT_FISCAL.ToString();
proveedor.Nombre = item.NOMBRE_BP.ToString();
Proveedores.Add(proveedor);
}
return Proveedores;
}
/// <summary>
/// Obtener los equipos de SAP
/// </summary>
/// <returns>Lista de equipos</returns>
public List<BienLogic> ObtenerEquipos()
{
DateTime fromDateValue;
List<BienLogic> equipos = new List<BienLogic>();
ZWS_ZETM_DATOS_EQUIPOSClient get_SAPBien = new ZWS_ZETM_DATOS_EQUIPOSClient();
get_SAPBien.ClientCredentials.UserName.UserName = "STRACON";
get_SAPBien.ClientCredentials.UserName.Password = "seidor2018";
var get_SAPBien_Input = new ZETM_DATOS_EQUIPOS();
get_SAPBien_Input.I_MARCA_DESC = "*";
var get_SAPBien_Response = new ZETM_DATOS_EQUIPOSResponse();
get_SAPBien_Response = get_SAPBien.ZETM_DATOS_EQUIPOS(get_SAPBien_Input);
foreach (var item in get_SAPBien_Response.T_RESULTADO)
{
BienLogic bien = new BienLogic();
bien.Marca = item.HERST.ToString();
bien.Modelo = item.TYPBZ.ToString();
bien.NumeroSerie = item.SERGE.ToString();
bien.CodigoIdentificacion = item.TIDNR.ToString();
bien.Descripcion = item.EQKTX.ToString();
var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
if (DateTime.TryParseExact(item.ANSDT, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
bien.FechaAdquisicion = DateTime.ParseExact(item.ANSDT, "yyyyMMdd", CultureInfo.InvariantCulture);
}
equipos.Add(bien);
}
return equipos;
}
}
}
|
using Alabo.Data.Targets.Iterations.Domain.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Data.Targets.Iterations.Domain.Repositories
{
public interface IIterationRepository : IRepository<Iteration, ObjectId>
{
}
} |
using System;
public interface IMovableBehaviour : IBaseBehaviour
{
ITransform CurrentTransform { get; }
ITransform TargetPoint { get; set; }
Action OnSetMovePoint { get; set; }
void SetMovePoint(ITransform transform);
void Clean();
bool CheckDestination();
} |
using System;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Rendering;
using Unity.Transforms;
using UnityEngine.PlayerLoop;
[Serializable]
public struct BallOriginalTranslation : IComponentData
{
public float3 Value;
}
public partial class MoveBallsSystem : JobComponentSystem
{
private EntityQuery m_Group;
[BurstCompile]
struct MoveBall : IJobChunk
{
public ComponentTypeHandle<Translation> TranslationType;
[ReadOnly] public ComponentTypeHandle<BallOriginalTranslation> BallOriginalTranslationType;
public uint LastSystemVersion;
public double ElapsedTime;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
var chunkTranslation = chunk.GetNativeArray(TranslationType);
var chunkOrigTranslation = chunk.GetNativeArray(BallOriginalTranslationType);
for (int i = 0; i < chunk.Count; i++)
{
chunkTranslation[i] = new Translation { Value
= chunkOrigTranslation[i].Value + (new float3(
(float)Math.Cos(ElapsedTime * 10.0f) * 0.7f,
(float)Math.Sin(ElapsedTime * 10.0f) * 0.7f,
0.0f)) };
}
}
}
protected override void OnCreate()
{
m_Group = GetEntityQuery(new EntityQueryDesc
{
All = new ComponentType[]
{
typeof(Translation),
typeof(BallOriginalTranslation)
},
Options = EntityQueryOptions.FilterWriteGroup
});
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
EntityCommandBuffer entityOriginsCommandBuffer = new EntityCommandBuffer(Allocator.TempJob, PlaybackPolicy.SinglePlayback );
Entities.WithNone<BallOriginalTranslation>().ForEach((Entity entity, in Translation translation, in SphereId sphereId) =>
{
entityOriginsCommandBuffer.AddComponent(entity, new BallOriginalTranslation{ Value = translation.Value });
}).Run();
entityOriginsCommandBuffer.Playback(EntityManager);
entityOriginsCommandBuffer.Dispose();
var moveBallJob = new MoveBall
{
TranslationType = GetComponentTypeHandle<Translation>(),
BallOriginalTranslationType = GetComponentTypeHandle<BallOriginalTranslation>(true),
LastSystemVersion = LastSystemVersion,
ElapsedTime = Time.ElapsedTime
};
var moveBallJobHandle = moveBallJob.Schedule(m_Group, inputDeps);
return moveBallJobHandle;
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace DSSAHP
{
public class RoundNumbersConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int digits = 4;
if (parameter is string s && int.TryParse(s, out int num))
digits = num;
return Math.Round((double)value, digits);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
}
|
using System;
using FactoryMethod.Pizza;
namespace FactoryMethod
{
class Program
{
static void Main(string[] args)
{
IAnimal animal = AnimalFactory.CreateAnimalObject(Animals.Dog);
animal.MakeSound();
Pizza.Pizza pizza = PizzaFactory.CreatePizza(Pizzas.Maxico);
pizza.GetName();
pizza.GetPrice();
Employes.Employee employee = Employes.EmployeeFactory.CreateEmployee(Employes.Employess.Nurse);
float employeePrice = employee.CalculateMonthPrice(20 * 8); // 20 dni * 8 godzin
Console.WriteLine("Pielęgniarka zarobi: {0}", employeePrice);
var x = Console.Read();
}
}
}
|
using System;
using System.Collections.Generic;
namespace ServiceDeskSVC.DataAccess.Models
{
public partial class AssetManager_Software
{
public AssetManager_Software()
{
this.AssetManager_AssetAttachments = new List<AssetManager_AssetAttachments>();
}
public int Id { get; set; }
public int SoftwareAssetNumber { get; set; }
public string Name { get; set; }
public int SoftwareTypeId { get; set; }
public Nullable<int> ProductOwnerId { get; set; }
public Nullable<int> ProductUsersId { get; set; }
public Nullable<int> SupportingCompanyId { get; set; }
public Nullable<int> AssociatedCompanyId { get; set; }
public int PublisherId { get; set; }
public string AccountingReqNumber { get; set; }
public string Notes { get; set; }
public string LicensingInfo { get; set; }
public System.DateTime DateOfPurchase { get; set; }
public Nullable<System.DateTime> EndOfSupportDate { get; set; }
public Nullable<int> LicenseCount { get; set; }
public System.DateTime CreatedDate { get; set; }
public int CreatedById { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public Nullable<int> ModifiedById { get; set; }
public virtual ICollection<AssetManager_AssetAttachments> AssetManager_AssetAttachments { get; set; }
public virtual AssetManager_Companies AssetManager_Companies { get; set; }
public virtual AssetManager_Companies AssetManager_Companies1 { get; set; }
public virtual ServiceDesk_Users ServiceDesk_Users { get; set; }
public virtual ServiceDesk_Users ServiceDesk_Users1 { get; set; }
public virtual ServiceDesk_Users ServiceDesk_Users2 { get; set; }
public virtual ServiceDesk_Users ServiceDesk_Users3 { get; set; }
public virtual ServiceDesk_Users ServiceDesk_Users4 { get; set; }
public virtual AssetManager_Software_AssetType AssetManager_Software_AssetType { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace test
{
public class FoodItem : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.GetComponent<PlayerController>())
{
PlayerController.instance.health = PlayerController.instance.healthMax;
PlayerController.instance.imageHealthBar.fillAmount = PlayerController.instance.health / PlayerController.instance.healthMax;
Destroy(gameObject);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(TimeInteractable))]
public class PlatformAtoB : MonoBehaviour
{
[SerializeField, Tooltip("Transform of point A, also the start position")]
private Transform m_pointA;
[SerializeField, Tooltip("Transform of point B")]
private Transform m_pointB;
[SerializeField, Tooltip("Whether the movement is looped or not")]
private bool m_loop;
private Vector3 m_velocityDirection;
// Start is called before the first frame update
void Start()
{
}
void Awake()
{
gameObject.transform.position = m_pointA.position;
m_velocityDirection = m_pointB.position - m_pointA.position;
m_velocityDirection.Normalize();
}
void FixedUpdate()
{
float displacement = this.gameObject.GetComponent<TimeInteractable>().CurrentSpeed * Time.fixedDeltaTime;
Vector3 newPosition = gameObject.transform.position + Vector3.Scale(m_velocityDirection, new Vector3(displacement, displacement, displacement));
// Checks if newPosition is out of range, if so, corrects its value
float t = (newPosition.x - m_pointA.position.x) / (m_pointB.position.x - m_pointA.position.x);
if (t < 0)
{
if (m_loop == true)
{
newPosition = (m_pointA.position - newPosition) + m_pointA.position;
m_velocityDirection.Scale(new Vector3(-1.0f, -1.0f, -1.0f));
}
else
{
newPosition = m_pointA.position;
}
}
else if (t > 1)
{
if (m_loop == true)
{
newPosition = (m_pointB.position - newPosition) + m_pointB.position;
m_velocityDirection.Scale(new Vector3(-1.0f, -1.0f, -1.0f));
}
else
{
newPosition = m_pointB.position;
}
}
gameObject.transform.position = newPosition;
}
}
|
using ApiSGCOlimpiada.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSGCOlimpiada.Data.LogDAO
{
public interface ILogDAO
{
IEnumerable<Log> GetAll();
Log Find(long id);
bool Add(Log log);
bool Update(Log log, long id);
bool Remove(long id);
}
}
|
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 Negocios;
using DTO;
namespace Apresentacao
{
public partial class FrmMenuAcaoBanca : Form
{
Banca bancaold = new Banca();
public FrmMenuAcaoBanca(string Acao, Banca banca, int tccID, int bancaID, string orientadornome)
{
InitializeComponent();
this.Text = "Banca Examinadora";
if (Acao == "Consultar TCC")
{
dataGridViewAcaoBancaProfessor.Size = new Size(456, 138);
dataGridViewAcaoBancaProfessor.Location = new Point(14, 41);
labelAcaoBancaProfessor.Visible = false;
labelAcaoBancaTCCOrientador.Visible = false;
textBoxAcaoBancaProfessorID.Visible = false;
textBoxAcaoBancaProfessorNome.Visible = false;
buttonAcaoBancaExcluirProfessor.Visible = false;
buttonAcaoBancaInserirProfessor.Visible = false;
buttonAcaoBancaConcluir.Visible = false;
}
labelAcaoBancaTCCOrientador.Text = orientadornome;
textBoxAcaoBancaTCCID.Text = tccID.ToString();
textBoxAcaoBancaID.Text = bancaID.ToString();
textBoxAcaoBancaProfessorID.Text = "";
textBoxAcaoBancaProfessorNome.Text = "";
if (textBoxAcaoBancaProfessorID.Text == "")
{
this.buttonAcaoBancaInserirProfessor.Enabled = false;
}
}
private void buttonAcaoBancaInserirProfessor_Click(object sender, EventArgs e)
{
Banca banca = new Banca();
BancaNegocios bancaNegocios = new BancaNegocios();
banca.BancaID = Convert.ToInt32(textBoxAcaoBancaID.Text);
banca.BancaProfessorID = Convert.ToInt32(textBoxAcaoBancaProfessorID.Text);
int verificacao = bancaNegocios.VerificarProfessorExistente(banca);
if (labelAcaoBancaTCCOrientador.Text == textBoxAcaoBancaProfessorNome.Text)
{
verificacao = -1;
}
if (verificacao > 0)
{
MessageBox.Show("O professor " + textBoxAcaoBancaProfessorNome.Text + " já está nesta banca.", "Erro");
}
else
{
if (verificacao < 0)
{
MessageBox.Show("O professor " + textBoxAcaoBancaProfessorNome.Text + " já foi cadastrado como orientador deste TCC!");
}
else
{
string retorno = bancaNegocios.InserirProfessor(banca);
}
}
textBoxAcaoBancaProfessorID.Text = "";
textBoxAcaoBancaProfessorNome.Text = "";
this.buttonAcaoBancaInserirProfessor.Enabled = false;
ListarProfessores();
}
private void buttonAcaoBancaConcluir_Click(object sender, EventArgs e)
{
BancaNegocios bancaNegocios = new BancaNegocios();
int verificacao = bancaNegocios.VerificarBancaVazia(Convert.ToInt32(textBoxAcaoBancaID.Text));
if (verificacao == 0)
{
MessageBox.Show("Não existe professor cadastrado nesta banca. Esta banca será excluída.");
bancaNegocios.ExcluirBanca(Convert.ToInt32(textBoxAcaoBancaTCCID.Text));
}
this.Close();
}
private void buttonAcaoBancaExcluirProfessor_Click(object sender, EventArgs e)
{
if (dataGridViewAcaoBancaProfessor.SelectedRows.Count == 0)
{
MessageBox.Show("Nenhum registro selecionado!");
}
else
{
if (dataGridViewAcaoBancaProfessor.SelectedRows.Count != 0)
{
DialogResult resultado = MessageBox.Show("Deseja mesmo excluir este professor da banca?", "Aviso", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (resultado == DialogResult.No)
{
}
else
{
Banca bancaSelecao = (dataGridViewAcaoBancaProfessor.SelectedRows[0].DataBoundItem as Banca);
BancaNegocios bancaNegocios = new BancaNegocios();
string retorno = bancaNegocios.ExcluirProfessor(bancaSelecao);
try
{
MessageBox.Show("Registro excluído com sucesso!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Não foi possível excluir. Detalhes: " + retorno, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ListarProfessores();
}
}
}
}
private void ListarProfessores()
{
BancaNegocios bancaNegocios = new BancaNegocios();
BancaColecao bancaColecao = new BancaColecao();
bancaColecao = bancaNegocios.ListarProfessores(Convert.ToInt32(textBoxAcaoBancaID.Text));
dataGridViewAcaoBancaProfessor.DataSource = null;
dataGridViewAcaoBancaProfessor.DataSource = bancaColecao;
dataGridViewAcaoBancaProfessor.Columns["BancaID"].Visible = false;
dataGridViewAcaoBancaProfessor.Columns["BancaBancaProfessorID"].Visible = false;
dataGridViewAcaoBancaProfessor.Columns["BancaProfessorID"].HeaderText = "ID";
dataGridViewAcaoBancaProfessor.Columns["BancaProfessorID"].Width = 30;
dataGridViewAcaoBancaProfessor.Columns["BancaProfessorNome"].HeaderText = "Professor";
dataGridViewAcaoBancaProfessor.Columns["BancaProfessorNome"].Width = 393;
dataGridViewAcaoBancaProfessor.Columns["BancaTCCID"].Visible = false;
dataGridViewAcaoBancaProfessor.Update();
dataGridViewAcaoBancaProfessor.Refresh();
}
private void FrmMenuAcaoBanca_Load(object sender, EventArgs e)
{
ListarProfessores();
}
private void buttonAcaoBancaProfessorSelecionar_Click(object sender, EventArgs e)
{
string modulo = "Professores";
FrmMenuSelecao frmMenuSelecao = new FrmMenuSelecao(modulo);
frmMenuSelecao.ShowDialog();
if (frmMenuSelecao.ValorID != 0)
{
textBoxAcaoBancaProfessorID.Text = Convert.ToString(frmMenuSelecao.ValorID);
textBoxAcaoBancaProfessorNome.Text = frmMenuSelecao.ValorRetorno1;
this.buttonAcaoBancaInserirProfessor.Enabled = true;
}
}
}
}
|
using Newtonsoft.Json;
namespace Infra.Model
{
public class itemRequest
{
public string responsavel { get; set; }
public string titulo { get; set; }
public string descricao { get; set; }
public string estado { get; set; }
}
} |
using System.Threading.Tasks;
using Airelax.Infrastructure.Map.Responses;
namespace Airelax.Infrastructure.Map.Abstractions
{
public interface IGeocodingService
{
Task<GeocodingInfo> GetGeocodingInfo(string address);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommandLine;
using CSBaseLib;
using MessagePack;
namespace ChatServer
{
public class PKHRoom : PKHandler
{
List<Room> RoomList = new List<Room>();
private int StartRoomNumber;
public void SetRoomList(List<Room> roomList)
{
RoomList = roomList;
StartRoomNumber = roomList[0].Number;
}
public void RegistPacketHandler(Dictionary<int, Action<ServerPacketData>> pakcetHandlerMap)
{
pakcetHandlerMap.Add((int)PACKETID.REQ_ROOM_ENTER, RequestRoomEnter);
pakcetHandlerMap.Add((int)PACKETID.REQ_ROOM_LEAVE, RequestLeave);
pakcetHandlerMap.Add((int)PACKETID.NTF_IN_ROOM_LEAVE, NotifyLeaveInternal);
pakcetHandlerMap.Add((int)PACKETID.REQ_ROOM_CHAT, RequestChat);
}
Room GetRoom(int roomNumber)
{
var index = roomNumber - StartRoomNumber;
// RoomList.Count 는 System.Linq Enumerable의 static Method
if (index < 0 || index >= RoomList.Count())
{
return null;
}
return RoomList[index];
}
// tuple 사용
(bool, Room, RoomUser) CheckRoomAndRoomUser(int userNetSessionIndex)
{
var user = UserMgr.GetUser(userNetSessionIndex);
if (user == null)
{
return (false, null, null);
}
var roomNumber = user.RoomNumber;
var room = GetRoom(roomNumber);
if (room == null)
{
return (false, null, null);
}
var roomUser = room.GetUser(userNetSessionIndex);
if (roomUser == null)
{
return (false, room, null);
}
return (true, room, roomUser);
}
public int SelectRoom()
{
int index = -1;
foreach (var room in RoomList)
{
if (room.GetUserCount() == 1)
{
index = room.Index;
}
else
{
continue;
}
}
if (index == -1)
{
foreach (var room in RoomList)
{
if (room.ChkRoomFull() == false)
{
index = room.Index;
break;
}
}
}
return index;
}
public void RequestRoomEnter(ServerPacketData packetData)
{
var sessionID = packetData.SessionID;
var sessionIndex = packetData.SessionIndex;
MainServer.MainLogger.Debug("RequestRoonEnter");
try
{
// user는 User 객체
var user = UserMgr.GetUser(sessionIndex);
if (user == null || user.IsConfirm(sessionID) == false)
{
ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_INVALID_USER, sessionID);
return;
}
if (user.IsStateRoom())
{
ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_INVALID_STATE, sessionID);
return;
}
// Binary --> Object 직렬화
var reqData = MessagePackSerializer.Deserialize<OMKReqRoomEnter>(packetData.BodyData);
// room은 Room 객체
// 06.04 Client는 항상 -1을 Request Body에 담아서 요청을 한다.
// 방을 전부 탐색해서 만약 유저가 1명뿐인 방이 있으면 그 방으로 순차적으로 데이터를 넣어준다
// 그렇게 넣어진 방을 return 한다.
// 방 객체를 Buffer에 두고 Init 시, userCount 변수도 추가
// 방 탐색하는 함수는 또 쓰일 수 있으니, 함수로 빼도록 하자
int roomNumber = SelectRoom();
var room = GetRoom(roomNumber);
//var room = GetRoom(reqData.RoomNumber);
Console.WriteLine("roomNumber : " + room.Number);
if (reqData.RoomNumber != -1 || room == null)
//if(room == null) // test 용
{
ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_INVALID_ROOM_NUMBER, sessionID);
return;
}
// UserList<RoomUser> 객체 추가
if (room.AddUser(user.ID(), sessionIndex, sessionID) == false)
{
ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_FAIL_ADD_USER, sessionID);
return;
}
// User 객체에 유저가 요청하고자 하는 방에 들어갔다고 설정
user.EnteredRoom(roomNumber);
// UserList 추가 됐다는 응답 : Packet 뭉침 --> MainServer.SendData
room.NotifyPacketUserList(sessionID);
// newUser 추가 됐다고 확인 : Packet 뭉침 --> BroadCast
room.NofifyPacketNewUser(sessionIndex, user.ID());
// Client가 문제 없이 Room에 입장했다고 응답 : Packet 뭉침 --> mainServer.SendData
ResponseEnterRoomToClient(ERROR_CODE.NONE, sessionID);
MainServer.MainLogger.Debug("RequestEnterInternal = Success");
}
catch (Exception e)
{
MainServer.MainLogger.Error(e.ToString());
}
}
void ResponseEnterRoomToClient(ERROR_CODE errorCode, string sessionID)
{
var resRoomEnter = new OMKResRoomEnter()
{
Result = (short)errorCode
};
// Object --> Binary (Class만 가능)
var bodyData = MessagePackSerializer.Serialize(resRoomEnter);
//Console.WriteLine($"ResponseEnterRoomToClient BodyData : {Encoding.ASCII.GetString(bodyData)}");
var sendData = PacketToBytes.Make(PACKETID.RES_ROOM_ENTER, bodyData);
//Console.WriteLine($"ResponseEnterRoomToClient sendData : {Encoding.ASCII.GetString(sendData)}");
// Room 에 잘 들어갔다고 MainServer.SendData 실행
ServerNetwork.SendData(sessionID, sendData);
}
public void RequestLeave(ServerPacketData packetData)
{
var sessionID = packetData.SessionID;
var sessionIndex = packetData.SessionIndex;
MainServer.MainLogger.Debug("로그인 요청 받음");
try
{
var user = UserMgr.GetUser(sessionIndex);
if (user == null)
{
return;
}
// 룸에서 유저 떠남
if (LeaveRoomUser(sessionIndex, user.RoomNumber) == false)
{
return;
}
// 유저 객체에 룸에서 떠났다고 알리기
user.LeaveRoom();
// 결과를 해당 유저에게 전달
ResponseLeaveRoomToClient(sessionID);
MainServer.MainLogger.Debug("Room RequestLeave - Success");
}
catch (Exception e)
{
MainServer.MainLogger.Error(e.ToString());
}
}
// 해당 룸에 (roomNumber) 해당 유저(sessinIndex) 떠남
bool LeaveRoomUser(int sessionIndex, int roomNumber)
{
MainServer.MainLogger.Debug($"LeaveRoomUser. SessionIndex:{sessionIndex}");
// 해당 룸의 객체를 불러옴
var room = GetRoom(roomNumber);
// 객체가 비어있으면 fail
if (room == null)
{
return false;
}
// sessionIndex를 사용해서 해당 룸의 RoomUser를 Get
var roomUser = room.GetUser(sessionIndex);
if (roomUser == null)
{
return false;
}
// sessionIndex-room에 있는 userID를 get
var userID = roomUser.UserID;
// 해당 userID를 roomUser에서 삭제
room.RemoveUser(roomUser);
// Pakcet을 뭉쳐서 모든 유저에게 SendData
room.NofifyPacketLeaveUser(userID);
return true;
}
void ResponseLeaveRoomToClient(string sessionID)
{
// MessagePack
var resRoomLeave = new OMKResRoomLeave()
{
Result = (short)ERROR_CODE.NONE
};
var bodyData = MessagePackSerializer.Serialize(resRoomLeave);
var sendData = PacketToBytes.Make(PACKETID.RES_ROOM_LEAVE, bodyData);
// 해당 유저에게 SendData
ServerNetwork.SendData(sessionID, sendData);
}
// Client는 접속이 끊는다 하였는데 룸에는 입장되어 있는 상황일떄
// 이미 이전에 접속 되어있는지 아닌지는 체크를 했다. 이 부분은 체크를 했으니 룸 객체에서 유저를 빼내는 부분을 해야 할 것이다
// 예상 프로세스 : ServerPacketData Object에서 SessionIndex Get -> sessionIndex로 User 객체 Get
// --> 현 User 객체가 들어가 있는 roomNumber, Room Get --> 해당 Room 객체에서 RoomUser.Remove
// 결과 : sessionIndex로 User 객체 Get
// --> roomNumber를 이용해 현 User 객체가 들어가 있는 Room Get --> 해당 Room 객체에서 RoomUser Get
// RoomUser에 속해있는 객체의 데이터 중, 해당 userID를 Get --> RoomUser에서 Remove
// --> 자기자신을 포함한 모든 RoomUser에게 이 userID는 방을 나갔다고 알림.
public void NotifyLeaveInternal(ServerPacketData packetData)
{
// ServerPacketData Object에서 SessionIndex Get
var sessionIndex = packetData.SessionIndex;
MainServer.MainLogger.Debug($"NotifyLeaveInternal. SessionIndex:{sessionIndex}");
// MessagePack 직렬화 (RoomNumber, UserID)
var reqData = MessagePackSerializer.Deserialize<PKTInternalNTFRoomLeave>(packetData.BodyData);
LeaveRoomUser(sessionIndex, reqData.RoomNumber);
}
public void RequestChat(ServerPacketData packetData)
{
var sessionID = packetData.SessionID;
var sessionIndex = packetData.SessionIndex;
MainServer.MainLogger.Debug("Room RequestChat");
try
{
// 반환 결과, room, roomUser Object
var roomObject = CheckRoomAndRoomUser(sessionIndex);
// 만약 객체 반환에 실패했다면 return --> MainLogger에는 Request 만 받았다고 출력됨
if (roomObject.Item1 == false)
{
return;
}
// Packet의 Body Data에 대한 메세지 직렬화
var reqData = MessagePackSerializer.Deserialize<OMKReqRoomChat>(packetData.BodyData);
// MessagePack
var notifyPacket = new OMKRoomChat()
{
// RoomUser의 userID, 여기에는 chat을 보내는 이의 ID
UserID = roomObject.Item3.UserID,
// body안에 있던 chatMessage
ChatMessage = reqData.ChatMessage
};
// Packet 직렬화
var body = MessagePackSerializer.Serialize(notifyPacket);
var sendData = PacketToBytes.Make(PACKETID.NTF_ROOM_CHAT, body);
// BroadCast -1 이니까 모든 Room에 있는 user에게!
roomObject.Item2.Broadcast(-1, sendData);
MainServer.MainLogger.Debug("Room RequestChat - Success");
}
catch (Exception e)
{
MainServer.MainLogger.Error(e.ToString());
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine.SceneManagement;
//TODO:
// В сохранения добавить Лист с квестами
// Решить вопрос с нажатием на кнопки клавиатуры
public class PauseGame : MonoBehaviour {
//Для управления окнами разных Менюшек
public bool ispaused; //true - пауза игры, false - нет паузы
public bool isinventory; //true - инвентарь,
public bool isTabMenu; //true - органайзер
public bool isQuests; //true - задания
public bool isMap; //true - map
public bool isSkills; //true - skills
//Для меню Паузы во время игры
public GameObject PauseMenu; //Панель меню с кнопками
public GameObject thisHPBar; //Для того, чтобы картинка во время паузы принимала полный размер экрана.
//public Image imagePause; //Темный фон во время паузы
//Для меню Органайзера во время игры
public GameObject Organaizer; //Канвас органайзера
//public Image TabMenuImage; //фон для кнопок органайзера
//Способ вызвать инвентарь
public GameObject InventoryCanvas;
//public Image imageInventory; // Фоновая картинка для инвентаря
//Способ вызвать задания
public GameObject QuestsCanvas;
//Пустые фоны для Карты и навыков
public GameObject MapCanvas;
public GameObject SkillsCanvas;
//Для сохранения и загрузки данных
public PlayerScript player; //Объект ГГ для сохранения и загрузки данных
[System.Serializable]
public class PlayerSave //Класс для сохранения данных персонажа
{
//координаты
public float x;
public float y;
public float z;
//Все основные параметры нашего персонажа
public float maxHealth; //Максимальное количество жизней
public float currentHealth; //текущее количество жизней
public float maxEnergy; //Максимальное количество ЭНЕРГИИ
public float currentEnergy; //текущее количество ЭНЕРГИИ
public int currentGold; //Текущее бабло
public int currentWeight; //Насколько тяжела ноша
public int maxWeight; //А сколько сможешь поднять ты!?
public int Level;
//Характеристики
//Основные параметры
public int strength; // Сила ГГ
public int agility; //Ловкость
public int endurance; //Выносливость
public int intellect; //Интеллект
//Дополнительные параметры
public int defense; //Защита
public int magicdefense; //Магическая Защита
public int armor; //Броня
public int magicarmor; //Магическая броня
//Сопротивляемость
public int resistanceToPoisons; //сопротивляемость к ядам
public int resistanceToStunning; // сопротивляемость к оглушению
public int resistanceToBleeding; //сопротивляемость к кровотечению
public int resistanceToMagic; //сопротивляемость к магии
public float attackSpeed; //скорость атаки
public float physicalDamage; // физический урон
public float criticalDamage; // критический урон
public float chanceCriticalDamage; //шанс критический урон
}
// Use this for initialization
void Start () {
//Если в главном меню была нажата кнопка загрузки игры, то мы осуществляем загрузку
if (PlayerPrefs.GetInt("loading") == 1)
{
LoadButton();
PlayerPrefs.SetInt("loading", 0); //на всякий случай.
}
//пауза и инвентарь изначально не показываются
ispaused = false;
isinventory = false;
isTabMenu = false;
/*
//Установке картинке размера во весь экран
imagePause.rectTransform.sizeDelta = new Vector2(thisHPBar.GetComponent<RectTransform>().rect.width, thisHPBar.GetComponent<RectTransform>().rect.height);
//Установке картинке размера во весь экран
TabMenuImage.rectTransform.sizeDelta = new Vector2(thisHPBar.GetComponent<RectTransform>().rect.width, thisHPBar.GetComponent<RectTransform>().rect.height);
//Установке картинке размера во весь экран
imageInventory.rectTransform.sizeDelta = new Vector2(thisHPBar.GetComponent<RectTransform>().rect.width, thisHPBar.GetComponent<RectTransform>().rect.height);
*/
}
// Update is called once per frame
void Update () {
//Любой канвас можно вывать с игры. А также с других канвасов исключая себя
//На данный момент спиок канвасов (Пауза, Инвентарь, Органайзер, Задания)
//Выключаем все и устанавливаем все в false, А по нажатию на опреденную кнопку устанавливаем на труе.
if(Input.GetKeyDown(KeyCode.Escape)){
isinventory = false;
isTabMenu = false;
isQuests = false;
isMap = false;
isSkills = false;
Organaizer.SetActive(false);
InventoryCanvas.SetActive(false);
QuestsCanvas.SetActive(false);
MapCanvas.SetActive(false);
SkillsCanvas.SetActive(false);
if (ispaused == false){
Time.timeScale = 0.0F;
ispaused = true;
PauseMenu.SetActive(true);
thisHPBar.SetActive(false);
}
else{
ResumeButton();
}
}
if(Input.GetKeyDown(KeyCode.Tab)){
ispaused = false;
isinventory = false;
isQuests = false;
isMap = false;
isSkills = false;
PauseMenu.SetActive(false);
InventoryCanvas.SetActive(false);
QuestsCanvas.SetActive(false);
MapCanvas.SetActive(false);
SkillsCanvas.SetActive(false);
if (isTabMenu == false){
Time.timeScale = 0.0F;
isTabMenu = true;
Organaizer.SetActive(true);
thisHPBar.SetActive(false);
}
else{
isTabMenu = false;
Organaizer.SetActive(false);
Time.timeScale = 1.0F;
thisHPBar.SetActive(true);
}
}
if(Input.GetKeyDown(KeyCode.I)){
ispaused = false;
isTabMenu = false;
isQuests = false;
isMap = false;
isSkills = false;
PauseMenu.SetActive(false);
Organaizer.SetActive(false);
QuestsCanvas.SetActive(false);
MapCanvas.SetActive(false);
SkillsCanvas.SetActive(false);
if (isinventory == false){
Time.timeScale = 0.0F;
isinventory = true;
InventoryCanvas.SetActive(true);
thisHPBar.SetActive(false);
}
else{
isinventory = false;
InventoryCanvas.SetActive(false);
Time.timeScale = 1.0F;
thisHPBar.SetActive(true);
}
}
if(Input.GetKeyDown(KeyCode.J)){
ispaused = false;
isinventory = false;
isTabMenu = false;
isMap = false;
isSkills = false;
PauseMenu.SetActive(false);
Organaizer.SetActive(false);
InventoryCanvas.SetActive(false);
MapCanvas.SetActive(false);
SkillsCanvas.SetActive(false);
if (isQuests == false){
Time.timeScale = 0.0F;
isQuests = true;
QuestsCanvas.SetActive(true);
thisHPBar.SetActive(false);
}
else{
isQuests = false;
QuestsCanvas.SetActive(false);
Time.timeScale = 1.0F;
thisHPBar.SetActive(true);
}
}
if (Input.GetKeyDown(KeyCode.K))
{
ispaused = false;
isinventory = false;
isTabMenu = false;
isMap = false;
isQuests = false;
PauseMenu.SetActive(false);
Organaizer.SetActive(false);
InventoryCanvas.SetActive(false);
MapCanvas.SetActive(false);
QuestsCanvas.SetActive(false);
if (isSkills == false)
{
Time.timeScale = 0.0F;
isSkills = true;
SkillsCanvas.SetActive(true);
thisHPBar.SetActive(false);
}
else
{
isSkills = false;
SkillsCanvas.SetActive(false);
Time.timeScale = 1.0F;
thisHPBar.SetActive(true);
}
}
if (Input.GetKeyDown(KeyCode.M))
{
ispaused = false;
isinventory = false;
isTabMenu = false;
isSkills = false;
isQuests = false;
PauseMenu.SetActive(false);
Organaizer.SetActive(false);
InventoryCanvas.SetActive(false);
SkillsCanvas.SetActive(false);
QuestsCanvas.SetActive(false);
if (isMap == false)
{
Time.timeScale = 0.0F;
isMap = true;
MapCanvas.SetActive(true);
thisHPBar.SetActive(false);
}
else
{
isMap = false;
MapCanvas.SetActive(false);
Time.timeScale = 1.0F;
thisHPBar.SetActive(true);
}
}
}
//Кнопка возвратиться к игре, находиться на Панеле паузы
public void ResumeButton()
{
//Убираем Меню паузы
PauseMenu.SetActive(false);
thisHPBar.SetActive(true);
//Возвращаем игру в движение
Time.timeScale = 1.0F;
//Меню паузы не вызвано, т.е. false
ispaused = false;
}
//Кнопка сохранить игру, находиться на Панеле паузы
public void SaveButton()
{
//Передаем необходимые параметры классу сохранения
PlayerSave positionSave = new PlayerSave();
positionSave.x = player.transform.position.x;
positionSave.y = player.transform.position.y;
positionSave.z = player.transform.position.z;
//positionSave.currentHealth = player.currentHealth;
//positionSave.maxHealth = player.maxHealth;
//positionSave.maxEnergy = player.maxEnergy; //Максимальное количество ЭНЕРГИИ
//positionSave.currentEnergy = player.currentEnergy; //текущее количество ЭНЕРГИИ
positionSave.currentGold = player.currentGold; //Текущее бабло
positionSave.currentWeight = player.currentWeight; //Насколько тяжела ноша
positionSave.maxWeight = player.maxWeight; //А сколько сможешь поднять ты!?
positionSave.Level = player.Level;
//Характеристики
//Основные параметры
positionSave.strength = player.strength; // Сила ГГ
positionSave.agility = player.agility; //Ловкость
positionSave.endurance = player.endurance; //Выносливость
positionSave.intellect = player.intellect; //Интеллект
//Дополнительные параметры
positionSave.defense = player.defense; //Защита
positionSave.magicdefense = player.magicdefense; //Магическая Защита
positionSave.armor = player.armor; //Броня
positionSave.magicarmor = player.magicarmor; //Магическая броня
//Сопротивляемость
positionSave.resistanceToPoisons = player.resistanceToPoisons; //сопротивляемость к ядам
positionSave.resistanceToStunning = player.resistanceToStunning; // сопротивляемость к оглушению
positionSave.resistanceToBleeding = player.resistanceToBleeding; //сопротивляемость к кровотечению
positionSave.resistanceToMagic = player.resistanceToMagic; //сопротивляемость к магии
positionSave.attackSpeed = player.attackSpeed; //скорость атаки
positionSave.physicalDamage = player.physicalDamage; // физический урон
positionSave.criticalDamage = player.criticalDamage; // критический урон
positionSave.chanceCriticalDamage = player.chanceCriticalDamage;
//Если папки для сохранения нет, то создаем новую папку
if (!Directory.Exists(Application.dataPath + "/saves")) Directory.CreateDirectory(Application.dataPath + "/saves");
//Создаем новый файл (или перезаписываем старый)
FileStream fs = new FileStream(Application.dataPath + "/saves/save1.sv", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(fs, positionSave);
fs.Close();
//Возвращаем движение игре
ResumeButton();
}
//Кнопка загрузить игру, находиться на Панеле паузы
public void LoadButton()
{
//Проверяем, существует ли файл, из которого надо загрузить
if (File.Exists(Application.dataPath + "/saves/save1.sv"))
{
FileStream fs = new FileStream(Application.dataPath + "/saves/save1.sv", FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
try
{
PlayerSave positionPlayer = (PlayerSave)bformatter.Deserialize(fs);
player.transform.position = new Vector3(positionPlayer.x, positionPlayer.y, positionPlayer.z);
//player.currentHealth = positionPlayer.currentHealth;
//player.maxHealth = positionPlayer.maxHealth;
//player.HPbar.fillAmount = player.currentHealth / player.maxHealth;
//player.maxEnergy = positionPlayer.maxEnergy; //Максимальное количество ЭНЕРГИИ
//player.currentEnergy = positionPlayer.currentEnergy; //текущее количество ЭНЕРГИИ
player.currentGold = positionPlayer.currentGold; //Текущее бабло
player.currentWeight = positionPlayer.currentWeight; //Насколько тяжела ноша
player.maxWeight = positionPlayer.maxWeight; //А сколько сможешь поднять ты!?
player.Level = positionPlayer.Level;
//Характеристики
//Основные параметры
player.strength = positionPlayer.strength; // Сила ГГ
player.agility = positionPlayer.agility; //Ловкость
player.endurance = positionPlayer.endurance; //Выносливость
player.intellect = positionPlayer.intellect; //Интеллект
//Дополнительные параметры
player.defense = positionPlayer.defense; //Защита
player.magicdefense = positionPlayer.magicdefense; //Магическая Защита
player.armor = positionPlayer.armor; //Броня
player.magicarmor = positionPlayer.magicarmor; //Магическая броня
//Сопротивляемость
player.resistanceToPoisons = positionPlayer.resistanceToPoisons; //сопротивляемость к ядам
player.resistanceToStunning = positionPlayer.resistanceToStunning; // сопротивляемость к оглушению
player.resistanceToBleeding = positionPlayer.resistanceToBleeding; //сопротивляемость к кровотечению
player.resistanceToMagic = positionPlayer.resistanceToMagic; //сопротивляемость к магии
player.attackSpeed = positionPlayer.attackSpeed; //скорость атаки
player.physicalDamage = positionPlayer.physicalDamage; // физический урон
player.criticalDamage = positionPlayer.criticalDamage; // критический урон
player.chanceCriticalDamage = positionPlayer.chanceCriticalDamage;
}
catch(System.Exception e)
{
Debug.Log(e.Message);
}
finally
{
fs.Close();
}
}
//Возвращаем движение игре
ResumeButton();
}
//Кнопка настройки игры, находиться на Панеле паузы
public void SettingsButton()
{
//Application.LoadLevel(0);
}
//Кнопка выйти в главное меню, находиться на Панеле паузы
public void BacktoMainSceneButton()
{
//Возвращаем скорость игре, а потом выходим в главное меню
ResumeButton();
//Application.LoadLevel(0);
SceneManager.LoadScene(0);
}
//Кнопка выйти из игры, находиться на Панеле паузы
public void ExitButton()
{
Application.Quit();
}
//Кнопки для органайзера
public void MapButton()
{
isTabMenu = false;
MapCanvas.SetActive(true);
Organaizer.SetActive(false);
isMap = true;
}
public void JornalButton()
{
isTabMenu = false;
QuestsCanvas.SetActive(true);
Organaizer.SetActive(false);
isQuests = true;
}
public void SkillsButton()
{
isTabMenu = false;
SkillsCanvas.SetActive(true);
Organaizer.SetActive(false);
isSkills = true;
}
public void InventoryButton()
{
isTabMenu = false;
isinventory = true;
Organaizer.SetActive(false);
InventoryCanvas.SetActive(true);
}
}
|
using Kafka1.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Core.IRepositories
{
public interface IOrderRepository
{
Task<string> createOrder(OrderRequest orderRequest, CancellationToken cancellationToken);
Task<string> updateOrder(OrderRequest orderRequest, CancellationToken cancellationToken);
Task<string> deleteOrder(string orderId, CancellationToken cancellationToken);
Task<OrderRequest> getOrderById(string orderId, CancellationToken cancellationToken);
Task<List<OrderRequest>> getAllOrder(CancellationToken cancellationToken);
}
}
|
using Backend.Model.PerformingExamination;
using System.ComponentModel.DataAnnotations.Schema;
namespace Backend.Model
{
public class SurveyAboutDoctor
{
private int examination;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int BehaviorOfDoctor { get; set; }
public int DoctorProfessionalism { get; set; }
public int GettingAdviceByDoctor { get; set; }
public int AvailabilityOfDoctor { get; set; }
[ForeignKey("Examination")]
public int ExaminationId { get; set; }
public virtual Examination Examination { get; set; }
public SurveyAboutDoctor() { }
public SurveyAboutDoctor(int behaviorOfDoctor, int doctorProfessionalism, int gettingAdviceByDoctor,
int availabilityOfDoctor, int examinationId)
{
BehaviorOfDoctor = behaviorOfDoctor;
DoctorProfessionalism = doctorProfessionalism;
GettingAdviceByDoctor = gettingAdviceByDoctor;
AvailabilityOfDoctor = availabilityOfDoctor;
ExaminationId = examinationId;
}
public SurveyAboutDoctor(int behaviorOfDoctor, int doctorProfessionalism, int gettingAdviceByDoctor,
int availabilityOfDoctor, Examination examination)
{
BehaviorOfDoctor = behaviorOfDoctor;
DoctorProfessionalism = doctorProfessionalism;
GettingAdviceByDoctor = gettingAdviceByDoctor;
AvailabilityOfDoctor = availabilityOfDoctor;
Examination = examination;
}
}
}
|
using System;
using System.Collections.Generic;
using Conditions.Guards;
using Properties.Core.Interfaces;
namespace Properties.Core.Objects
{
public class Landlord : LifetimeBase, IReferenceable<Landlord>
{
private string _givenName;
private string _familyName;
private string _knownAs;
private string _addressLine1;
private string _addressLine2;
private string _addressLine3;
private string _addressLine4;
private string _postcode;
private string _county;
private string _mobile;
private string _landline;
private string _email;
public int LandlordId { get; set; }
public string LandlordReference { get; set; }
public string GivenName
{
get { return _givenName; }
set
{
if (_givenName != value)
{
_givenName = value;
IsDirty = true;
}
}
}
public string FamilyName
{
get { return _familyName; }
set
{
if (_familyName != value)
{
_familyName = value;
IsDirty = true;
}
}
}
public string KnownAs
{
get { return _knownAs; }
set
{
if (_knownAs != value)
{
_knownAs = value;
IsDirty = true;
}
}
}
public string AddressLine1
{
get { return _addressLine1; }
set
{
if (_addressLine1 != value)
{
_addressLine1 = value;
IsDirty = true;
}
}
}
public string AddressLine2
{
get { return _addressLine2; }
set
{
if (_addressLine2 != value)
{
_addressLine2 = value;
IsDirty = true;
}
}
}
public string AddressLine3
{
get { return _addressLine3; }
set
{
if (_addressLine3 != value)
{
_addressLine3 = value;
IsDirty = true;
}
}
}
public string AddressLine4
{
get { return _addressLine4; }
set
{
if (_addressLine4 != value)
{
_addressLine4 = value;
IsDirty = true;
}
}
}
public string Postcode
{
get { return _postcode; }
set
{
if (_postcode != value)
{
_postcode = value;
IsDirty = true;
}
}
}
public string County
{
get { return _county; }
set
{
if (_county != value)
{
_county = value;
IsDirty = true;
}
}
}
public string Mobile
{
get { return _mobile; }
set
{
if (_email != value)
{
_mobile = value;
IsDirty = true;
}
}
}
public string Landline
{
get { return _landline; }
set
{
if (_landline != value)
{
_landline = value;
IsDirty = true;
}
}
}
public string Email
{
get { return _email; }
set
{
if (_email != value)
{
_email = value;
IsDirty = true;
}
}
}
public List<ContactDetail> AlternateContactDetails { get; set; }
public List<Property> Properties { get; set; }
public List<SubmittedProperty> SubmittedProperties { get; set; }
public User User { get; set; }
public Referrer Referrer { get; set; }
public DateTime DateCreated { get; set; }
public Landlord()
{
LandlordId = 0;
LandlordReference = string.Empty;
GivenName = string.Empty;
FamilyName = string.Empty;
KnownAs = string.Empty;
AddressLine1 = string.Empty;
AddressLine2 = string.Empty;
AddressLine3 = string.Empty;
AddressLine4 = string.Empty;
Postcode = string.Empty;
County = string.Empty;
Mobile = string.Empty;
Landline = string.Empty;
Email = string.Empty;
AlternateContactDetails = new List<ContactDetail>();
Properties = new List<Property>();
SubmittedProperties = new List<SubmittedProperty>();
User = null;
Referrer = null;
DateCreated = DateTime.UtcNow;
}
public Landlord CreateReference(IReferenceGenerator referenceGenerator)
{
Check.If(referenceGenerator).IsNotNull();
LandlordReference = referenceGenerator.CreateReference("L-", Constants.ReferenceLength);
return this;
}
}
}
|
using IdentityServer3.Shaolinq.DataModel.Interfaces;
using Shaolinq;
namespace IdentityServer3.Shaolinq.DataModel
{
[DataAccessModel]
public abstract class IdentityServerDataAccessModel :
DataAccessModel,
IIdentityServerClientDataAccessModel,
IIdentityServerScopeDataAccessModel,
IIdentityServerOperationalDataAccessModel
{
[DataAccessObjects]
public abstract DataAccessObjects<DbClient> Clients { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientClaim> ClientsClaims { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientCorsOrigin> ClientCorsOrigins { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientCustomGrantType> ClientCustomGrantTypes { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientIdpRestriction> ClientIdpRestrictions { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientPostLogoutRedirectUri> ClientPostLogoutRedirectUris { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientRedirectUri> ClientRedirectUris { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientScope> ClientScopes { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbClientSecret> ClientSecrets { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbScope> Scopes { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbScopeClaim> ScopeClaims { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbConsent> Consents { get; }
[DataAccessObjects]
public abstract DataAccessObjects<DbToken> Tokens { get; }
}
} |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEditor;
public static class CreateCachedScrollRectEditor
{
[MenuItem("GameObject/UI/Vertical Cached Scroll View", false, 2063)]
public static void CreateVerticalScrollRect()
{
GameObject root = GetOrCreateCanvasGameObject();
GameObject scrollGO = CreateUIObject("VerticalCachedScrollRect", root);
scrollGO.GetComponent<RectTransform>().sizeDelta = new Vector2(200, 200);
VerticalCachedScrollRect scroll = scrollGO.AddComponent<VerticalCachedScrollRect>();
scroll.enabled = true;
scroll.horizontal = false;
scroll.vertical = true;
scroll.horizontalScrollbar = null;
AddSlicedImage(scrollGO, new Color(1f, 1f, 1f, 0.3921569f), GetBackgroundSprite());
GameObject viewportGO = CreateVerticalScrollViewportGO(scrollGO);
GameObject contentGO = CreateVerticalScrollContentGO(viewportGO);
scroll.viewport = viewportGO.GetComponent<RectTransform>();
scroll.content = contentGO.GetComponent<RectTransform>();
scroll.verticalScrollbar = CreateVerticalScrollbar(scrollGO);
scroll.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
Selection.activeGameObject = scrollGO;
}
[MenuItem("GameObject/UI/Horizontal Cached Scroll View", false, 2064)]
public static void CreaTeHorizontalScrollRect()
{
GameObject root = GetOrCreateCanvasGameObject();
GameObject scrollGO = CreateUIObject("HorizontalCachedScrollRect", root);
scrollGO.GetComponent<RectTransform>().sizeDelta = new Vector2(200, 200);
HorizontallCachedScrollRect scroll = scrollGO.AddComponent<HorizontallCachedScrollRect>();
scroll.enabled = true;
scroll.horizontal = true;
scroll.vertical = false;
scroll.verticalScrollbar = null;
AddSlicedImage(scrollGO, new Color(1f, 1f, 1f, 0.3921569f), GetBackgroundSprite());
GameObject viewportGO = CreateHorizontalScrollViewportGO(scrollGO);
GameObject contentGO = CreateHorizontalScrollContentGO(viewportGO);
scroll.viewport = viewportGO.GetComponent<RectTransform>();
scroll.content = contentGO.GetComponent<RectTransform>();
scroll.horizontalScrollbar = CreateHorizontalScrollbar(scrollGO);
scroll.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
Selection.activeGameObject = scrollGO;
}
private static GameObject CreateVerticalScrollViewportGO(GameObject parent)
{
GameObject viewportGO = CreateUIObject("Viewport", parent);
RectTransform viewportRect = viewportGO.GetComponent<RectTransform>();
SetFullStretch(viewportRect);
viewportRect.pivot = new Vector2(0, 1);
viewportRect.offsetMax = new Vector2(-20, viewportRect.offsetMax.y);
Mask mask = viewportGO.AddComponent<Mask>();
mask.showMaskGraphic = false;
Image bg = viewportGO.AddComponent<Image>();
bg.sprite = GetUIMaskSprite();
bg.color = Color.white;
bg.type = Image.Type.Sliced;
bg.fillCenter = true;
return viewportGO;
}
private static GameObject CreateHorizontalScrollViewportGO(GameObject parent)
{
GameObject viewportGO = CreateUIObject("Viewport", parent);
RectTransform viewportRect = viewportGO.GetComponent<RectTransform>();
SetFullStretch(viewportRect);
viewportRect.pivot = new Vector2(0, 1);
viewportRect.offsetMin = new Vector2(viewportRect.offsetMin.x, 20);
Mask mask = viewportGO.AddComponent<Mask>();
mask.showMaskGraphic = false;
Image bg = viewportGO.AddComponent<Image>();
bg.sprite = GetUIMaskSprite();
bg.color = Color.white;
bg.type = Image.Type.Sliced;
bg.fillCenter = true;
return viewportGO;
}
private static GameObject CreateVerticalScrollContentGO(GameObject parent)
{
GameObject contentGO = CreateUIObject("Content", parent);
RectTransform contentRect = contentGO.GetComponent<RectTransform>();
SetFullStretch(contentRect);
contentRect.pivot = new Vector2(0, 1);
contentRect.anchorMin = new Vector2(0, 1);
contentRect.anchorMax = new Vector2(1, 1);
contentRect.localPosition = Vector3.zero;
return contentGO;
}
private static GameObject CreateHorizontalScrollContentGO(GameObject parent)
{
GameObject contentGO = CreateUIObject("Content", parent);
RectTransform contentRect = contentGO.GetComponent<RectTransform>();
SetFullStretch(contentRect);
contentRect.pivot = new Vector2(0, 1);
contentRect.anchorMin = new Vector2(0, 0);
contentRect.anchorMax = new Vector2(0, 1);
contentRect.localPosition = Vector3.zero;
return contentGO;
}
private static Scrollbar CreateVerticalScrollbar(GameObject parent)
{
GameObject scrollBarGO = CreateUIObject("Scrollbar Vertical", parent);
RectTransform scrollBarRect = scrollBarGO.GetComponent<RectTransform>();
scrollBarRect.anchorMin = new Vector2(1, 0);
scrollBarRect.anchorMax = new Vector2(1, 1);
scrollBarRect.pivot = new Vector2(1, 1);
scrollBarRect.sizeDelta = new Vector2(20, 0);
// ---
GameObject slidingAreaGO = CreateUIObject("Sliding Area", scrollBarGO);
SetFullStretch(slidingAreaGO.GetComponent<RectTransform>());
// ---
GameObject handleGO = CreateUIObject("Handle", slidingAreaGO);
SetFullStretch(handleGO.GetComponent<RectTransform>());
Image handleImage = AddSlicedImage(handleGO, Color.white, GetUISpriteSprite());
// ---
AddSlicedImage(scrollBarGO, Color.white, GetBackgroundSprite());
Scrollbar ret = scrollBarGO.AddComponent<Scrollbar>();
ret.targetGraphic = handleImage;
ret.handleRect = handleGO.GetComponent<RectTransform>();
ret.direction = Scrollbar.Direction.BottomToTop;
ret.value = 0.1452992f;
ret.size = 0.61f;
return ret;
}
private static Scrollbar CreateHorizontalScrollbar(GameObject parent)
{
GameObject scrollBarGO = CreateUIObject("Scrollbar Horizontal", parent);
RectTransform scrollbarRect = scrollBarGO.GetComponent<RectTransform>();
scrollbarRect.pivot = new Vector2(0, 0);
scrollbarRect.anchorMin = new Vector2(0, 0);
scrollbarRect.anchorMax = new Vector2(1, 0);
scrollbarRect.sizeDelta = new Vector2(0, 20);
// ---
GameObject slidingAreaGO = CreateUIObject("Sliding Area", scrollBarGO);
SetFullStretch(slidingAreaGO.GetComponent<RectTransform>());
// ---
GameObject handleGO = CreateUIObject("Handle", slidingAreaGO);
SetFullStretch(handleGO.GetComponent<RectTransform>());
Image handleImage = AddSlicedImage(handleGO, Color.white, GetUISpriteSprite());
// ---
AddSlicedImage(scrollBarGO, Color.white, GetBackgroundSprite());
Scrollbar ret = scrollBarGO.AddComponent<Scrollbar>();
ret.targetGraphic = handleImage;
ret.handleRect = handleGO.GetComponent<RectTransform>();
ret.direction = Scrollbar.Direction.LeftToRight;
ret.value = 0;
ret.size = 1;
return ret;
}
// Helpers ==========================================================
private static void SetFullStretch(RectTransform rectTransform)
{
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
rectTransform.offsetMin = Vector2.zero;
rectTransform.offsetMax = Vector2.zero;
}
private static Image AddSlicedImage(GameObject go, Color color, Sprite sprite = null)
{
Image ret = go.AddComponent<Image>();
ret.sprite = sprite;
ret.color = color;
ret.type = Image.Type.Sliced;
ret.fillCenter = true;
return ret;
}
private static GameObject GetOrCreateCanvasGameObject()
{
GameObject selectedGO = Selection.activeGameObject;
Canvas canvas = selectedGO != null ? selectedGO.GetComponent<Canvas>() : null;
if (canvas != null && canvas.gameObject.activeInHierarchy)
{
return canvas.gameObject;
}
canvas = (Canvas)Object.FindObjectOfType(typeof(Canvas));
if (canvas != null && canvas.gameObject.activeInHierarchy)
{
return canvas.gameObject;
}
return CreateCanvasGameObject();
}
private static GameObject CreateCanvasGameObject()
{
GameObject ret = new GameObject("Canvas");
ret.layer = LayerMask.NameToLayer(s_uiLayer);
Canvas canvas = ret.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
ret.AddComponent<CanvasScaler>();
ret.AddComponent<GraphicRaycaster>();
Undo.RegisterCreatedObjectUndo(ret, "Create " + ret.name);
CreateEventSystemIfNeeded();
return ret;
}
private static void CreateEventSystemIfNeeded(GameObject parent = null)
{
EventSystem evsys = Object.FindObjectOfType<EventSystem>();
if (evsys == null)
{
GameObject evsysRoot = new GameObject("EventSystem");
GameObjectUtility.SetParentAndAlign(evsysRoot, parent);
evsys = evsysRoot.AddComponent<EventSystem>();
evsysRoot.AddComponent<StandaloneInputModule>();
Undo.RegisterCreatedObjectUndo(evsysRoot, "Create " + evsysRoot.name);
}
}
private static GameObject CreateUIObject(string name, GameObject parent)
{
GameObject ret = new GameObject(name);
ret.AddComponent<RectTransform>();
GameObjectUtility.SetParentAndAlign(ret, parent);
return ret;
}
// ==================================================================
// Sprite getters ===================================================
private static Sprite GetBackgroundSprite()
{
return AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Background.psd");
}
private static Sprite GetUISpriteSprite()
{
return AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");
}
private static Sprite GetUIMaskSprite()
{
return AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UIMask.psd");
}
// ==================================================================
private static string s_uiLayer = "UI";
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TeleportScript : MonoBehaviour {
public GameObject destination;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//Teleport ball to new position when colliding with the teleport
private void OnTriggerEnter(Collider other)
{
other.gameObject.transform.position = destination.transform.position;
}
}
|
using UnityEngine;
using UnityAtoms.MonoHooks;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Event Instancer of type `Collider2DGameObject`. Inherits from `AtomEventInstancer<Collider2DGameObject, Collider2DGameObjectEvent>`.
/// </summary>
[EditorIcon("atom-icon-sign-blue")]
[AddComponentMenu("Unity Atoms/Event Instancers/Collider2DGameObject Event Instancer")]
public class Collider2DGameObjectEventInstancer : AtomEventInstancer<Collider2DGameObject, Collider2DGameObjectEvent> { }
}
|
using Android.App;
using Android.OS;
using Android.Widget;
using Java.IO;
using Java.Lang;
using Java.Util;
using SkiaSharp;
using SkiaSharp.Views.Android;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Packaged_Database
{
[Activity(Label = "DrawChordActivity")]
public class DrawChordActivity : Activity
{
// obj
public SKCanvasView m_skiaView_obj;
// containers and constants
private List<int> m_chord_frets_parsed;
private int m_ChordPos; // used for drawing chord diagram
private int m_Dis_ChordPos; //display pos is 1 higher
private string m_ChordName;
// Drawing constants
private float m_space;
private float m_x_start;
private float m_y_start;
private float m_string_len;
private float m_fret_len_space;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_draw);
//set up objs
m_skiaView_obj = FindViewById<SKCanvasView>(Resource.Id.SKIAVIEW_DRAW);
// Get Chord from intent
string chord_frets = Intent.GetStringExtra("Chord");
m_ChordPos = Intent.GetIntExtra("Chord_pos", 0);
m_Dis_ChordPos = m_ChordPos + 1;
m_ChordName = Intent.GetStringExtra("Chord_name");
//Parsing chord string into List
m_chord_frets_parsed = new List<int>();
string holder = null; //holds 2 digit fret numbers
string db_fseperater = Resources.GetString(Resource.String.comma);
char db_s = db_fseperater[0];//converts to char
for (int i = 0; i < (int)chord_frets.Length; i++)
{
if (chord_frets[i] != db_s)
{
holder += chord_frets[i];
}
if (chord_frets[i] == db_s | i == (chord_frets.Length - 1))
{
if (holder.Contains("X") | holder.Contains("x"))
{
m_chord_frets_parsed.Add(100); // 100 represents X
}
else
{
int holder_int;
int.TryParse(holder, out holder_int);
m_chord_frets_parsed.Add(holder_int);
}
holder = null;//empty for next go around
}
}
}
protected override void OnResume()
{
base.OnResume();
m_skiaView_obj.PaintSurface += OnPaintSurface;
}
protected override void OnPause()
{
base.OnPause();
m_skiaView_obj.PaintSurface -= OnPaintSurface;
}
private SKPath DrawX(SKPoint rel_prt)
{
int dis_size = 20;
var path = new SKPath();
path.MoveTo(rel_prt.X - dis_size, rel_prt.Y - dis_size);
path.LineTo(dis_size + rel_prt.X, dis_size + rel_prt.Y);
path.MoveTo(dis_size + rel_prt.X, rel_prt.Y - dis_size);
path.LineTo(rel_prt.X - dis_size, dis_size + rel_prt.Y);
return path;
}
private void gen_note_str(out SKPoint[] str_notes, int string_number)
{
string_number = 6 - string_number; //backwards
str_notes = new SKPoint[4];
int k = 0;
for (int j = string_number; j < (string_number + 1); j++)
{
float x = (m_x_start + (m_space * j));
for (int i = 0; i < 4; i++)
{
float y = m_y_start + m_fret_len_space / 2 + (m_fret_len_space * i);
str_notes[k] = new SKPoint(x, y);
k++;
}
}
}
private void OnPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
// the the canvas and properties
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = args.Surface.Canvas;
// get the screen density for scaling
var scale = Resources.DisplayMetrics.Density;
// get the scaled size of the screen in density-indep pixals
// pixals = (dp pixals) * DisplayMetrics.Density
// (dp pixals) = pixals / DisplayMetrics.Density
var scaledSize = new SKSize(info.Width / scale, info.Height / scale);
// handle the device screen density
canvas.Scale(scale);
// make sure the canvas is blank
canvas.Clear(SKColors.White);
// draw some text
var paint = new SKPaint
{
Color = SKColors.Black,
Style = SKPaintStyle.Stroke,
StrokeWidth = 10, //in dp
IsAntialias = true,
};
var paint_red = new SKPaint
{
Style = SKPaintStyle.Stroke,
Color = SKColors.OrangeRed,
StrokeWidth = 10, // in dp
StrokeCap = SKStrokeCap.Butt,
IsAntialias = true,
};
var paint_blue = new SKPaint
{
Style = SKPaintStyle.Stroke,
Color = SKColors.Blue,
StrokeWidth = 35, //in dp
StrokeCap = SKStrokeCap.Round,
IsAntialias = true,
};
// Create an SKPaint object to display the text
var textPaint = new SKPaint
{
Style = SKPaintStyle.Stroke,
FakeBoldText = true,
StrokeWidth = 3f,
Color = SKColors.Blue,
IsAntialias = true,
};
/*
* Coordinates are specified relative to the upper-left corner of the display surface.
* X coordinates increase to the right and Y coordinates increase going down.
* In discussion about graphics, often the mathematical notation (x, y) is used to denote a point.
* The point (0, 0) is the upper-left corner of the display surface and is often called the origin.
*/
// Adjust TextSize property so text is 95% of screen width
// 95% of width * (Height for width ratio)
textPaint.TextSize = 0.15f * scaledSize.Height;
// Find the text bounds
SKRect textBounds = new SKRect();
textPaint.MeasureText(m_ChordName, ref textBounds);
// Calculate offsets to center the text on the screen
float xText = scaledSize.Width / 2 - textBounds.MidX;
float yText = scaledSize.Height / 7.5f - textBounds.MidY;
// And draw the text
canvas.DrawText(m_ChordName, xText, yText, textPaint);
// 10& of height
textPaint.TextSize = 0.1f * scaledSize.Height;
// Find the text bounds
textBounds = new SKRect();
textPaint.MeasureText(m_Dis_ChordPos.ToString(), ref textBounds);
// Calculate offsets to center the text on the screen
xText = scaledSize.Width / 9 - textBounds.MidX;
yText = scaledSize.Height / 2.5f - textBounds.MidY;
// And draw the text
textPaint.Color = SKColors.Black;
textPaint.Style = SKPaintStyle.StrokeAndFill;
canvas.DrawText(m_Dis_ChordPos.ToString(), xText, yText, textPaint);
// divide the scaled size width into 7 spaces
m_space = ((scaledSize.Width) / 7);
m_x_start = m_space + 25;
m_y_start = 200;
m_string_len = (scaledSize.Height - m_y_start / 2);
m_fret_len_space = (m_string_len - 110) / 4;
// Strings
SKPoint[] string_points = new SKPoint[12];
for (int i = 0; i < 2; i++)
{
float y = m_y_start + (m_string_len * i) - (m_fret_len_space * i);
for (int j = 0; j < 6; j++)
{
float x = m_x_start + m_space * j;
string_points[2 * j + i] = new SKPoint(x, y);
}
}
// Render the points by calling DrawPoints
SKPointMode pointMode = SKPointMode.Lines;
canvas.DrawPoints(pointMode, string_points, paint);
// Frets
SKPoint[] fret_points = new SKPoint[10];
for (int i = 0; i < 2; i++)
{
float x = (m_x_start + (5 * m_space * i));
for (int j = 0; j < 5; j++)
{
float y = m_y_start + (m_fret_len_space -2.5f) * j; // A slight adj with -2.5
fret_points[2 * j + i] = new SKPoint(x, y);
}
}
// Render the points by calling DrawPoints
pointMode = SKPointMode.Lines;
canvas.DrawPoints(pointMode, fret_points, paint);
// Notes on each string
SKPoint[] str_6 = new SKPoint[4];
SKPoint[] str_5 = new SKPoint[4];
SKPoint[] str_4 = new SKPoint[4];
SKPoint[] str_3 = new SKPoint[4];
SKPoint[] str_2 = new SKPoint[4];
SKPoint[] str_1 = new SKPoint[4];
// 6th string E note positions
gen_note_str(out str_6, 6);
// 5th string A note positions
gen_note_str(out str_5, 5);
// 4th string D
gen_note_str(out str_4, 4);
// 3rd string G
gen_note_str(out str_3, 3);
// 2nd string B
gen_note_str(out str_2, 2);
// 1st string E
gen_note_str(out str_1, 1);
// Chord Notes ::::
// Converts the chords frets to actual positions on screen
// subtracts position - 1 to get relative position
// then adds the relative position to an array
SKPoint[] chord_prts = new SKPoint[6];
for (int i = 0; i < m_chord_frets_parsed.Count; i++)
{
// error with larger chords tried m_ChordPos to solve problem
if (!(m_chord_frets_parsed[i] >= 100 | m_chord_frets_parsed[i] <= 0))//100 represents "^"
{
int parse_temp = m_chord_frets_parsed[i];
parse_temp = parse_temp - 1 - m_ChordPos; // -1 for array
switch (i)
{
case 0:
chord_prts[i] = str_6[parse_temp];
break;
case 1:
chord_prts[i] = str_5[parse_temp];
break;
case 2:
chord_prts[i] = str_4[parse_temp];
break;
case 3:
chord_prts[i] = str_3[parse_temp];
break;
case 4:
chord_prts[i] = str_2[parse_temp];
break;
case 5:
chord_prts[i] = str_1[parse_temp];
break;
default:
System.Console.WriteLine("Exep: More than 6 notes");
break;
}
}
else if (m_chord_frets_parsed[i] <= 100)
{
SKPoint temp_adj = new SKPoint();
SKPath x_path = new SKPath();
switch (i)
{
case 0:
temp_adj = str_6[0];
temp_adj.Y = temp_adj.Y - m_fret_len_space / 2;
x_path = DrawX(temp_adj);
canvas.DrawPath(x_path, paint_red);
break;
case 1:
temp_adj = str_5[0];
temp_adj.Y = temp_adj.Y - m_fret_len_space / 2;
x_path = DrawX(temp_adj);
canvas.DrawPath(x_path, paint_red);
break;
case 2:
temp_adj = str_4[0];
temp_adj.Y = temp_adj.Y - m_fret_len_space / 2; ;
x_path = DrawX(temp_adj);
canvas.DrawPath(x_path, paint_red); ;
break;
case 3:
temp_adj = str_3[0];
temp_adj.Y = temp_adj.Y - m_fret_len_space / 2; ;
x_path = DrawX(temp_adj);
canvas.DrawPath(x_path, paint_red);
break;
case 4:
temp_adj = str_2[0];
temp_adj.Y = temp_adj.Y - m_fret_len_space / 2; ;
x_path = DrawX(temp_adj);
canvas.DrawPath(x_path, paint_red);
break;
case 5:
temp_adj = str_1[0];
temp_adj.Y = temp_adj.Y - m_fret_len_space / 2; ;
x_path = DrawX(temp_adj);
canvas.DrawPath(x_path, paint_red);
break;
default:
System.Console.WriteLine("Exep: More than 6 notes");
break;
}
chord_prts[i] = new SKPoint(-50, -50); // open str (0) = off screen
}
else
{
chord_prts[i] = new SKPoint(-50, -50); // open str (0) = off screen
}
}
canvas.DrawPoints(SKPointMode.Points, chord_prts, paint_blue);
}
}
} |
using System;
namespace Euler_Logic.Problems {
public class Problem19 : ProblemBase {
public override string ProblemName {
get { return "19: Counting Sundays"; }
}
public override string GetAnswer() {
return Solve().ToString();
}
private int Solve() {
var date = DateTime.Parse("1901-01-01");
var last = DateTime.Parse("2000-12-31");
int count = 0;
do {
if (date.DayOfWeek == DayOfWeek.Sunday && date.Day == 1) count++;
date = date.AddDays(1);
} while (date <= last);
return count;
}
}
}
|
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-panel-group")]
public class PanelGroupTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string PanelClass { get; set; }
public PanelGroupTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("panel-group " + this.PanelClass));
output.Attributes.SetAttribute("role", (object) "tablist");
output.Attributes.SetAttribute("aria-multiselectable", (object) "true");
// ISSUE: reference to a compiler-generated method
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
class RnaTranscription4
{
public static string ToRna(string nucleotide)
{
return string.Concat(nucleotide.Select(x => ("CGTA".Contains(x) ? RnaCodes[x] :
throw new ArgumentException($"Invalid argument '{x}' specified."))));
}
private static readonly Dictionary<char, char> RnaCodes = new Dictionary<char,char>()
{
{'C', 'G'}, {'G', 'C'}, {'T', 'A'}, {'A','U'}
};
}
|
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System.Diagnostics.CodeAnalysis;
namespace Proxynet
{
[ExcludeFromCodeCoverage]
public partial class Startup
{
public void ConfigureAuth( IAppBuilder app )
{
app.UseCookieAuthentication( new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString( "/Account/Login" ),
} );
}
}
} |
using System;
namespace EPI.Strings
{
public static class StringIntInterConvert
{
/// <summary>
/// Implement string/integer interconversion functions
/// Should be able to handle negative numbers
/// Cannot use built-in parse/ToString functions
/// </summary>
public static int StringToInt(string value)
{
int result = 0;
if (!string.IsNullOrEmpty(value))
{
int index = 0;
bool isNegativeNumber = false;
if (value[0] == '-')
{
isNegativeNumber = true;
index++;
}
for (; index < value.Length; index++)
{
int digit = value[index] - '0';
if (digit < 0 || digit > 9)
{
throw new ArgumentException(value + " is NaN", "value");
}
result = (10 * result) + digit;
}
if (isNegativeNumber)
{
result = -1 * result;
}
}
return result;
}
public static string IntToString(int number)
{
bool isNegativeNumber = false;
if (number == 0) return "0";
else if (number < 0)
{
isNegativeNumber = true;
number = -number;
if (number < 0)
{
throw new OverflowException();
}
}
string result = "";
while (number > 0)
{
int digit = number % 10;
result = (char)('0' + digit) + result;
number = (number - digit) / 10;
}
return isNegativeNumber ? '-' + result : result;
}
}
}
|
using Android.App;
using Android.Content.Res;
namespace MobileCollector.projects
{
public class lspContextManager: BaseContextManager
{
public lspContextManager(AssetManager assetManager, Activity mainContext)
: base(Constants.FILE_LSP_FIELDS, assetManager, mainContext)
{
ProjectCtxt = ProjectContext.Vmmc;
KindDisplayNames = Constants.LSP_KIND_DISPLAYNAMES;
FIELD_VISITDATE = Constants.FIELD_LSP_DATEOFVISIT;
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json;
namespace FindAndCopyFiles
{
[JsonObject(MemberSerialization.OptIn)]
class FindFilesConfiguration
{
[JsonProperty]
private
List<string> _from = new List<string>();
[JsonProperty]
private
List<string> _to = new List<string>();
public IReadOnlyList<string> sources => _from;
public IReadOnlyList<string> destinations => _to;
public
FindFilesConfiguration()
{
}
public
FindFilesConfiguration(
List<string> aFrom,
List<string> aTo
)
{
_from = aFrom;
_to = aTo;
}
public
FindFilesConfiguration(
string[] aFrom,
string[] aTo
)
{
_from.AddRange(aFrom);
_to.AddRange(aTo);
}
}
}
|
using System;
using System.Linq.Expressions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SFA.DAS.PAS.Account.Api.ClientV2;
using SFA.DAS.PAS.Account.Api.ClientV2.Configuration;
using StructureMap;
namespace SFA.DAS.ProviderCommitments.Web.LocalDevRegistry
{
public class LocalDevPasAccountApiClientRegistry : Registry
{
public LocalDevPasAccountApiClientRegistry(Expression<Func<IContext, PasAccountApiConfiguration>> getApiConfig)
{
For<PasAccountApiConfiguration>().Use(getApiConfig);
For<IPasAccountApiClient>().Use(ctx => CreateClient(ctx)).Singleton();
}
private IPasAccountApiClient CreateClient(IContext ctx)
{
var config = ctx.GetInstance<PasAccountApiConfiguration>();
var loggerFactory = ctx.GetInstance<ILoggerFactory>();
var factory = new LocalDevPasAccountApiClientFactory(config, loggerFactory);
return factory.CreateClient();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using SimpleTaskListSPA.Data;
namespace SimpleTaskListSPA.Infrastructure
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class CorrectDateAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime? date = (DateTime?)value;
TaskItem taskItem = (TaskItem)validationContext.ObjectInstance;
bool isDateUsed = taskItem.IsPlanningDateUsed;
string[] memberNames = validationContext.MemberName != null
? new string[] { validationContext.MemberName }
: null;
if (!date.HasValue && isDateUsed)
{
return new ValidationResult("Укажите дату в формате чч.мм.гггг", memberNames);
}
return ValidationResult.Success;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
[SerializeField]
[Range(0.5f, 1.5f)]
private float fireRate = 1;
[SerializeField]
[Range(1, 10)]
private int damage = 1;
[SerializeField]
private Transform firePoint;
[SerializeField]
private ParticleSystem muzzleParticle;
private float timer;
private JoystickController joystickController;
public GameObject bulletObject;
public Transform bulletSpawn;
public GameObject explosionPrefab;
public AudioSource audioSource;
public AudioClip shot_Audio = null;
private void Start()
{
joystickController = gameObject.GetComponent<JoystickController>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (timer >= fireRate)
{
if (joystickController.joystickRightReleased)
{
timer = 0f;
FireGun();
}
}
}
private void FireGun()
{
//Debug.DrawRay(firePoint.position, firePoint.forward * 100, Color.red, 2f);
muzzleParticle.Play();
GenerateBullet();
if(shot_Audio != null)
{
audioSource.PlayOneShot(shot_Audio);
}
}
private void GenerateBullet() {
GameObject bullet = Instantiate(bulletObject);
bullet.transform.position = bulletSpawn.transform.position;
bullet.transform.rotation = bulletSpawn.transform.rotation;
bullet.GetComponent<BulletFly>().initForwardDir = bulletSpawn.transform.up * -1;
bullet.GetComponent<BulletFly>().explosion = explosionPrefab;
}
}
|
using DChild.Inputs;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Player
{
public class LadderClimb : MonoBehaviour
{
[SerializeField]
[TabGroup("Sensor")]
private RaycastSensor m_ladderSensor;
[SerializeField]
[TabGroup("Configuration")]
private float m_climbInterval;
[SerializeField]
[TabGroup("Configuration")]
private float m_climbSpeed;
[SerializeField]
private bool m_skillEnabled;
private PlayerInput m_input;
private CharacterPhysics2D m_characterPhysics2D;
private float m_gravity;
private bool m_climbUp, m_climbDown;
private bool m_moveLeft, m_moveRight;
private bool m_grabbing;
private float m_nextNode;
public void EnableSkill(bool value) => m_skillEnabled = value;
public bool isEnabled => m_skillEnabled;
private void ClimbUp()
{
var endPos = m_characterPhysics2D.transform.position;
endPos.y += m_characterPhysics2D.transform.position.y + m_climbInterval;
m_characterPhysics2D.transform.position = Vector3.Lerp(m_characterPhysics2D.transform.position, endPos, Time.deltaTime * m_climbSpeed);
if (m_characterPhysics2D.transform.position.y >= m_nextNode)
{
m_climbUp = false;
}
}
private void ClimbDown()
{
var endPos = m_characterPhysics2D.transform.position;
endPos.y -= m_characterPhysics2D.transform.position.y - m_climbInterval;
m_characterPhysics2D.transform.position = Vector3.Lerp(m_characterPhysics2D.transform.position, endPos, Time.deltaTime * m_climbSpeed);
if (m_characterPhysics2D.transform.position.y <= m_nextNode)
{
m_climbDown = false;
}
}
private void MoveLeft()
{
var endPos = m_characterPhysics2D.transform.position;
endPos.x = m_characterPhysics2D.transform.position.x - m_climbInterval;
m_characterPhysics2D.transform.position = Vector3.Lerp(m_characterPhysics2D.transform.position, endPos, Time.deltaTime * m_climbSpeed);
if (m_characterPhysics2D.transform.position.x <= m_nextNode)
{
m_moveLeft = false;
}
}
private void MoveRight()
{
var endPos = m_characterPhysics2D.transform.position;
endPos.x = m_characterPhysics2D.transform.position.x + m_climbInterval;
m_characterPhysics2D.transform.position = Vector3.Lerp(m_characterPhysics2D.transform.position, endPos, Time.deltaTime * m_climbSpeed);
if (m_characterPhysics2D.transform.position.x <= m_nextNode)
{
m_moveRight = false;
}
}
private void ReleaseLadder()
{
m_grabbing = false;
m_characterPhysics2D.simulateGravity = true;
m_characterPhysics2D.GetComponentInParent<Rigidbody2D>().gravityScale = m_gravity;
m_characterPhysics2D.Enable();
}
private void Update()
{
if (m_skillEnabled)
{
if (m_ladderSensor.isDetecting)
{
if (Input.GetButton("Interact")) m_grabbing = true;
else if (m_input.isJumpPressed)
{
ReleaseLadder();
}
if (m_grabbing)
{
m_characterPhysics2D.Disable();
m_characterPhysics2D.simulateGravity = false;
m_characterPhysics2D.GetComponentInParent<Rigidbody2D>().gravityScale = 0;
Debug.Log(m_characterPhysics2D.GetComponentInParent<Rigidbody2D>().gravityScale);
if (m_input.direction.isUpPressed || m_input.direction.isUpHeld)
{
m_nextNode = m_characterPhysics2D.transform.position.y + m_climbInterval;
m_climbUp = true;
}
else if (m_input.direction.isDownPressed || m_input.direction.isDownHeld)
{
m_nextNode = m_characterPhysics2D.transform.position.y - m_climbInterval;
m_climbDown = true;
}
else if (m_input.direction.isLeftPressed || m_input.direction.isLeftHeld)
{
m_nextNode = m_characterPhysics2D.transform.position.x - m_climbInterval;
m_moveLeft = true;
}
else if (m_input.direction.isRightPressed || m_input.direction.isRightHeld)
{
m_nextNode = m_characterPhysics2D.transform.position.x + m_climbInterval;
m_moveRight = true;
}
}
}
else
{
ReleaseLadder();
}
if (m_climbUp) ClimbUp();
else if (m_climbDown) ClimbDown();
else if (m_moveLeft) MoveLeft();
else if (m_moveRight) MoveRight();
}
else
{
ReleaseLadder();
}
}
private void Start()
{
m_input = GetComponentInParent<PlayerInput>();
m_characterPhysics2D = GetComponentInParent<CharacterPhysics2D>();
m_gravity = m_characterPhysics2D.GetComponentInParent<Rigidbody2D>().gravityScale;
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading;
namespace Training.Framework
{
public interface Handles<T>
{
void Handle(T message);
}
}
|
using DFC.ServiceTaxonomy.Banners.Models;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata.Models;
namespace DFC.ServiceTaxonomy.Banners.ViewModels
{
public class BannerPartViewModel
{
public string? WebPageName { get; set; }
public string? WebPageURL { get; set; }
public BannerPart? BannerPart { get; set; }
public ContentPart? Part { get; set; }
public ContentTypePartDefinition? PartDefinition { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace Groceries
{
public class Order
{
public User User{ get; set; }
public List<Product> Products{ get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PiDataAdayProje.Models.Entities
{
public class Musteri
{
public Guid Id { get; set; }
public Guid IsyeriId { get; set; }//FK
public string Ad { get; set; }
public string Soyad { get; set; }
[DataType(DataType.PhoneNumber)]
public string Telefon { get; set; }
[DataType(DataType.PhoneNumber)]
[Display(Name ="Cep Telefonu")]
public string CepTelefon { get; set; }
[DataType(DataType.EmailAddress)]
public string Mail { get; set; }
public virtual Isyeri Isyeri { get; set; }
//public virtual IEnumerable<Emlak> Emlaklar { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Models;
namespace Data.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<Data.BookShopContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Data.BookShopContext";
}
protected override void Seed(Data.BookShopContext context)
{
var random = new Random();
//using (var reader = new StreamReader("c:\\temp\\authors.txt"))
//{
// var line = reader.ReadLine();
// line = reader.ReadLine();
// while (line != null)
// {
// var data = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// var firstName = data[0];
// var lastNames = data[1];
// context.Authors.Add(new Author()
// {
// FirstName = firstName,
// LastName = lastNames
// });
// line = reader.ReadLine();
// }
//}
//using (var reader = new StreamReader("c:\\temp\\books.txt"))
//{
// var authors = context.Authors.ToList();
// var line = reader.ReadLine();
// line = reader.ReadLine();
// while (line != null)
// {
// var data = line.Split(new[] { ' ' }, 6);
// var authorIndex = random.Next(0, authors.Count);
// var author = authors[authorIndex];
// var edition = (EditionType)int.Parse(data[0]);
// var releaseData = DateTime.ParseExact(data[1], "d/M/yyyy", CultureInfo.InvariantCulture);
// var copies = int.Parse(data[2]);
// var pricw = decimal.Parse(data[3]);
// var ageRestriction = (AgeRestriction)int.Parse(data[4]);
// var title = data[5];
// var category = context.Categories.ToArray();
// var categList = new HashSet<Category>()
// {
// category[random.Next(0, category.Length)],
// category[random.Next(0, category.Length)],
// category[random.Next(0, category.Length)]
// };
// context.Books.Add(new Book()
// {
// Author = author,
// Edition = edition,
// ReleaseDateTime = releaseData,
// Copies = copies,
// Price = pricw,
// AgeRestriction = ageRestriction,
// Title = title,
// Categories = categList
// });
// line = reader.ReadLine();
// }
//}
//using (var reader = new StreamReader("c:\\temp\\categories.txt"))
//{
// var line = reader.ReadLine();
// line = reader.ReadLine();
// while (line != null)
// {
// var name = line.Trim();
// var books = context.Books.ToArray();
// HashSet<Book> booksToAdd = new HashSet<Book>()
// {
// books[random.Next(1, books.Length)],
// books[random.Next(1, books.Length)],
// books[random.Next(1, books.Length)]
// };
// context.Categories.Add(new Category()
// {
// Name = name,
// Books = booksToAdd
// });
// line = reader.ReadLine();
// }
//}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFIDA.U9.SM.SO;
using HBH.DoNet.DevPlatform.EntityMapping;
using UFSoft.UBF.Business;
using U9.VOB.Cus.HBHTianRiSheng.HBHHelper;
using UFSoft.UBF.PL;
namespace U9.VOB.Cus.HBHTianRiSheng.BEPlugIn
{
public class SO_AfterDeleting: UFSoft.UBF.Eventing.IEventSubscriber
{
public void Notify(params object[] args)
{
if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
{
return;
}
UFSoft.UBF.Business.BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
if (key != null)
{
SO entity = key.GetEntity() as SO;
if (entity != null
//&& entity.OriginalData != null
)
{
SOVouchersHead.EntityList list = SOVouchersHead.Finder.FindAll("SO=@SO", new OqlParam(entity.ID));
if (list != null
&& list.Count > 0
)
{
using (ISession session = Session.Open())
{
foreach (SOVouchersHead soVou in list)
{
if (soVou != null
)
{
soVou.Remove();
}
}
session.Commit();
}
}
}
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class titlePlay : MonoBehaviour {
private GUIStyle style;
void Start(){
style = new GUIStyle();
style.fontSize = 30;
style.fontStyle = FontStyle.Italic;
}
void OnGUI(){
Rect rect = new Rect(220, 110, 400, 300);
GUI.Label(rect, "Play !!", style);
rect = new Rect(230, 250, 400, 300);
GUI.Label(rect, "Score", style);
}
void Update () {
if(Input.GetMouseButtonDown(0)){
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit raycastHit;
bool hit = transform.GetComponent<BoxCollider>().Raycast(ray,out raycastHit,100);
if(hit){
Application.LoadLevel("mainScene");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Traditional.PageObjects;
namespace Traditional
{
public class TraditionalApproach
{
private HackathonPage hackathonPage;
[SetUp]
public void Initialize()
{
Console.WriteLine("Test Initialized");
}
[Test]
public void Verify_Login_Page_Contents()
{
hackathonPage = new HackathonPage(PageUrl.Version2);
//Login Button
Assert.IsTrue(hackathonPage.IsLoginButtonPresent(),"Login Button Present ?");
//User Name
Assert.IsTrue(hackathonPage.IsUserNameLabelPresent(),"UserName Label Present ?");
Assert.IsTrue(hackathonPage.IsUserNameInputFieldPresent(),"User Name Input Field Present ?");
//Bug:Placeholder Showing User Name In V2
Assert.AreEqual(hackathonPage.GetUserNameFieldPlaceHolder(),"Enter your username","Placeholder equal ?");
//Bug: User Name icon is missing in V@
Assert.IsTrue(hackathonPage.IsUserNameIconPresent(),"User Name Icon Present ?");
//Password
//Bug:Password Label Is Changed To "Pwd" in V2
Assert.IsTrue(hackathonPage.IsPasswordLabelPresent(), "Password Label Present ?");
Assert.IsTrue(hackathonPage.IsPasswordInputFieldPresent(), "Password Input Field Present ?");
//Bug:Placeholder Showing Password of a user
Assert.AreEqual(hackathonPage.GetPasswordFieldPlaceHolder(), "Enter your password", "Placeholder equal ?");
//Bug: Password icon is missing in V2
Assert.IsTrue(hackathonPage.IsPasswordIconPresent(), "Password Icon Present ?");
//Remember Me
Assert.IsTrue(hackathonPage.IsRememberMeCheckboxPresent(), "Remember Me Checkbox Present ?");
Assert.IsTrue(hackathonPage.IsRememberMeTextBoxPresent(), "Remember Me Textbox Present ?");
//Social Media Icons
Assert.IsTrue(hackathonPage.IsTwitterIconPresent(), "Twitter Icon Present ?");
Assert.IsTrue(hackathonPage.IsFacebookIconPresent(), "Facebook Icon Present ?");
//Bug:LinkedIn Icon Is missing in V2
Assert.IsTrue(hackathonPage.IsLinkedInIconPresent(), "Linked In Icon Present ?");
//Top Part
Assert.IsTrue(hackathonPage.IsTopLogoPresent(), "Top Logo Present ?");
//Bug: "Login Form" is changed to "Logout Form"
Assert.IsTrue(hackathonPage.IsLoginFormTextPresent(), "Login Form Text Present ?");
}
[Test]
public void Verify_Login_Functionality()
{
hackathonPage = new HackathonPage(PageUrl.Version2);
//Verify Error Thrown When Username and password are no entered
hackathonPage.ClickOnLoginButton();
Assert.IsTrue(hackathonPage.IsErrorMessagePresent(),"Error Message Should Be Present");
/*Validation Message Has Been Changed In V2*/
Assert.AreEqual(hackathonPage.GetErrorMessage(), "Please enter both username and password", "Message Equal ?");
//Verify If Only UserName IS Entered, Error Is Thrown
hackathonPage.EnterUserName("test");
hackathonPage.ClickOnLoginButton();
Assert.IsTrue(hackathonPage.IsErrorMessagePresent(), "Error Message Should Be Present");
/*Bug: Validation Message Is Not Shown In The UI. However, the Assertion Is Correct.*/
Assert.AreEqual(hackathonPage.GetErrorMessage(), "Password must be present", "Message Equal ?");
hackathonPage.ClearTextField("Username");
//Verify If Only Password IS Entered, Error Is Thrown
hackathonPage.EnterPassword("test");
hackathonPage.ClickOnLoginButton();
Assert.IsTrue(hackathonPage.IsErrorMessagePresent(), "Error Message Should Be Present");
/*Validation Message Is Not Aligned.*/
Assert.AreEqual(hackathonPage.GetErrorMessage(), "Username must be present", "Message Equal ?");
hackathonPage.ClearTextField("Password");
//Verify User Is Logged In with both credentials
hackathonPage.EnterUserName("test");
hackathonPage.EnterPassword("test");
hackathonPage.ClickOnLoginButton();
Assert.IsFalse(hackathonPage.IsErrorMessagePresent(), "Error Message Should Be Present");
Assert.IsTrue(hackathonPage.IsUserLoggedIn(),"Is User Logged In ?");
}
[Test]
public void Verify_Table_Sort_Test()
{
hackathonPage = new HackathonPage(PageUrl.Version2);
Dictionary<int, List<string>> tableData= new Dictionary<int,List<string>>()
{
{
1,
new List<string>()
{
"",
"Pending", "Yesterday", "7:45am",
"MailChimp Services", "- 320.00 USD"
}
},
{
2,
new List<string>()
{
"", "Complete", "Jan 7th", "9:51am",
"Ebay Marketplace", "- 244.00 USD"
}
},
{
3,
new List<string>()
{
"", "Pending", "Jan 23rd", "2:7pm",
"Shopify product", "+ 17.99 USD"
}
},
{
4,
new List<string>()
{
"", "Pending", "Jan 9th", "7:45pm",
"Templates Inc", "+ 340.00 USD"
}
},
{
5,
new List<string>()
{
"", "Declined", "Jan 19th", "3:22pm",
"Stripe Payment Processing", "+ 952.23 USD"
}
},
{
6,
new List<string>()
{
"", "Complete", "Today", "1:52am",
"Starbucks coffee", "+ 1,250.00 USD"
}
}
};
hackathonPage.EnterUserName("test");
hackathonPage.EnterPassword("test");
hackathonPage.ClickOnLoginButton();
SiteDriver.WaitForCondition(hackathonPage.IsLoggedInUserNamePresent);
//Verify Sorting
hackathonPage.ClickOnAmountColumn();
var amounts = hackathonPage.GetAllAmounts();
/*Bug : Data is not sorted in ascending order.*/
Assert.IsTrue(amounts.IsInAscendingOrder(),"Are amounts sorted in ascending order ?");
//Verify Rows Are Intact After Sort
for (int i = 1; i <= tableData.Count; i++)
{
CollectionAssert.AreEqual(tableData[i], hackathonPage.GetGridValueByRow(i),
"Data Intact After Sort ?");
}
}
[Test]
public void Verify_Canvas_Chart()
{
hackathonPage = new HackathonPage(PageUrl.Version2);
hackathonPage.EnterUserName("test");
hackathonPage.EnterPassword("test");
hackathonPage.ClickOnLoginButton();
hackathonPage.ClickOnCompareExpensesLink();
Assert.IsTrue(hackathonPage.IsCanvasChartPresent(),"Chart Present ?");
/*
* Chart cannot be validated using selenium traditional approach as we cannot access the data from the DOM element representing the chart.
*/
}
[Test]
public void Verify_Ads_In_The_Page()
{
hackathonPage = new HackathonPage(PageUrl.Version2withAd);
hackathonPage.EnterUserName("test");
hackathonPage.EnterPassword("test");
hackathonPage.ClickOnLoginButton();
/*Bug: Test is passing even though image is missing in version 2 of the app.*/
Assert.IsTrue(hackathonPage.IsFlashSaleAdsPresent(),"Flash Ads Present ?");
}
[TearDown]
public void TestCleanUp()
{
SiteDriver.Close();
}
}
}
|
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 AccManagerKw.Common;
using DataAccess;
using Model;
using Model.Interfaces;
using Utilities;
namespace AccManagerKw.Masters.Accounts
{
public partial class FrmAccGroupMaster : FrmBaseMaster, ICrud
{
private ClsCommonFn _oCommFn = new ClsCommonFn();
private vwAccountGroup row;
private ClsDataFn _oDataFn = new ClsDataFn();
public FrmAccGroupMaster()
{
InitializeComponent();
}
private void FrmAccGroupMaster_Shown(object sender, EventArgs e)
{
_oCommFn.GroupControl_Setting(gclMain);
_oCommFn.GroupControl_Setting(gclOpen);
_oCommFn.GridSetting(gvGroups, gcGroups);
_oDataFn.SetDataSource(ClsGlobalEnums.EDataSourceType.AccGroups, lucGroups, "GroupName", "GrpId");
}
public bool OperationSave()
{
try
{
if (IsValid())
{
if ((Mode == ClsGlobalVarz.Mode.Add || Mode == ClsGlobalVarz.Mode.Edit) &&
_oCommFn.ValidateCrud(Mode))
{
OperationAccGroup();
_oCommFn.MsgBoxCrud(Mode);
return true;
}
else if (Mode != ClsGlobalVarz.Mode.Add && Mode != ClsGlobalVarz.Mode.Edit)
{
_oCommFn.WarningMsg("Check Mode");
return false;
}
}
return false;
}
catch (Exception ex)
{
_oCommFn.TryCatchErrorMsg(ex.Message);
return false;
}
}
private void OperationAccGroup()
{
using (var context = new AccManagerEntities())
{
var oAccGrp = new AccountGroup();
if (Mode == ClsGlobalVarz.Mode.Add)
{
oAccGrp.GrpId = context.AccountGroups.ToList().Count > 0
? context.AccountGroups.Max(x => x.GrpId) + 1 : 1;
}
else if (Mode == ClsGlobalVarz.Mode.Edit)
{
oAccGrp = context.AccountGroups.Single(x => x.GrpId == row.GrpId);
}
oAccGrp.GroupCode = txtCode.Text;
oAccGrp.GroupName = txtName.Text;
oAccGrp.UnderGrpId = lucGroups.Value;
if (oAccGrp.UnderGrpId != 0)
oAccGrp.GroupType = context.AccountGroups.Single(x => x.GrpId == oAccGrp.UnderGrpId).GroupType;
else
oAccGrp.GroupType = txtCode.Text;
if (Mode == ClsGlobalVarz.Mode.Add)
context.AccountGroups.Add(oAccGrp);
context.SaveChanges();
}
}
public void OperationOpen()
{
gclOpen.BringToFront();
var context = new AccManagerEntities();
gcGroups.DataSource = context.vwAccountGroups.ToList();
}
private void gvGroups_DoubleClick(object sender, EventArgs e)
{
row = (vwAccountGroup)gvGroups.GetFocusedRow();
txtCode.Text = row.GroupCode;
txtName.Text = row.GroupName;
lucGroups.EditValue = row.UnderGrpId != 0 ? row.UnderGrpId : null;
_oCommFn.DisableControls(gclMain, true);
gclMain.BringToFront();
}
public void OperationEdit()
{
if (_oCommFn.ValidateOpenRecord(row.GrpId))
{
_oCommFn.DisableControls(gclMain, false);
SetMode(ClsGlobalVarz.Mode.Edit);
}
}
public bool OperationDelete()
{
try
{
if (_oCommFn.ValidateOpenRecord(row.GrpId))
{
SetMode(ClsGlobalVarz.Mode.Delete);
if (_oCommFn.ValidateCrud(Mode))
{
using (var context = new AccManagerEntities())
{
var oAccGrp = context.AccountGroups.Single(x => x.GrpId == row.GrpId);
context.AccountGroups.Remove(oAccGrp);
context.SaveChanges();
_oCommFn.MsgBoxCrud(Mode);
}
return true;
}
}
return false;
}
catch (Exception ex)
{
_oCommFn.TryCatchErrorMsg(ex.Message);
return false;
}
}
public void ResetData()
{
_oCommFn.ClearFields(this);
_oCommFn.DisableControls(gclMain, false);
gclMain.BringToFront();
SetMode(ClsGlobalVarz.Mode.Add);
row = new vwAccountGroup();
_oDataFn.SetDataSource(ClsGlobalEnums.EDataSourceType.AccGroups, lucGroups, "GroupName", "GrpId");
}
public bool IsValid()
{
ccDxValidationProvider1.Validate();
return ccDxValidationProvider1.GetInvalidControls().Count <= 0;
}
}
}
|
using System;
namespace AckermannCalculation
{
class Program
{
static void Main(string[] args)
{
string input = "";
int inputM = -1;
int inputN = -1;
int result = 0;
bool invalidInput = false;
do
{
invalidInput = false;
//Prompt for and read in 'm' typecasting the input string to an integer and check validity
Console.WriteLine("Please enter a positive interger number for M.");
input = Console.ReadLine();
if (!int.TryParse(input, out inputM))
{
Console.WriteLine("Not an integer, try again.");
inputM = -1;
}
else
{
//Prompt for and read in 'n' typecasting the input string to an integer and check validity
Console.WriteLine("Please enter a positive interger number for N.");
input = Console.ReadLine();
if (!int.TryParse(input, out inputN))
{
Console.WriteLine("Not an integer, try again.");
inputN = -1;
}
}
//Ensure M and N are positive
if (inputM < 0 || inputN < 0)
{
Console.WriteLine("Invalid inputs, please enter positive integers for both M and N.");
invalidInput = true;
}
} while (invalidInput != false);
//Call function to calculate the Ackermann value
result = Ackermann(inputM, inputN);
Console.WriteLine("The Ackermann result for {0} and {1} is: {2}.", inputM, inputN, result);
}
//Ackermann recursive function
static int Ackermann(int m, int n)
{
//Base case
if (m == 0)
{
return n + 1;
}
//First recursive path
else if (m > 0 && n == 0)
{
return Ackermann(m - 1, 1);
}
//Second recursive path
else if (m > 0 && n > 0)
{
return Ackermann(m - 1, Ackermann(m, n - 1));
}
return -1;
}
}
}
|
using System;
using System.Collections.Generic;
using PterodactylEngine;
using Xunit;
namespace UnitTestEngine
{
public class TestFlowchartNode_NodeHelper : TheoryData<string, List<FlowchartNode>, int, string>
{
public TestFlowchartNode_NodeHelper()
{
Add("First", null, 0, "First");
Add("Second", new List<FlowchartNode>
{
new FlowchartNode("First", null, 0)
},
0, "Second");
Add("Third", new List<FlowchartNode>
{
new FlowchartNode("First", null, 0),
new FlowchartNode("Second", null, 0)
},
0, "Third");
Add("Third", new List<FlowchartNode>
{
new FlowchartNode("Second", new List<FlowchartNode>
{new FlowchartNode("First", null, 0)}, 0)
},
0, "Third");
Add("First", null, 1, "First");
Add("Third", new List<FlowchartNode>
{
new FlowchartNode("First", null, 0),
new FlowchartNode("Second", null, 0)
},
2, "Third");
Add("Space text", null, 1, "Space_text");
}
}
public class TestFlowchartNode_Node
{
[Theory]
[ClassData(typeof(TestFlowchartNode_NodeHelper))]
public void CorrectData(string text, List<FlowchartNode> previousNodes, int shape, string expectedText)
{
FlowchartNode testObject = new FlowchartNode(text, shape);
Assert.Equal(expectedText, testObject.Text);
Assert.Equal(shape, testObject.Shape);
}
[Fact]
public void TestFlowchartNodeToString()
{
FlowchartNode testObject = new FlowchartNode("Test", 0);
Assert.Equal("Flowchart Node: Test", testObject.ToString());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IdomOffice.Interface.BackOffice.Booking;
using IdomOffice.Interface.BackOffice.Booking.Entity;
using V50_IDOMBackOffice.AspxArea.Booking.Controllers;
using V50_IDOMBackOffice.AspxArea.Booking.Models;
using V50_IDOMBackOffice.AspxArea.MasterData.Controllers;
using V50_IDOMBackOffice.PlugIn.Controller;
namespace V50_IDOMBackOffice.SupportForms
{
public partial class BookingView : System.Web.UI.Page
{
string modelid;
UnitPopUpController controller = new UnitPopUpController();
//BookingProcessController bookingcontroller = new BookingProcessController();
CustomerController customercontroller = new CustomerController();
CustomerViewModel customer;
protected void Page_Load(object sender, EventArgs e)
{
Uri u = HttpContext.Current.Request.Url;
modelid = HttpUtility.ParseQueryString(u.Query).Get("id");
customer = customercontroller.GetCustomer(modelid);
Bind();
}
private void Bind()
{
comboboxSite.DataSource = controller.GetSiteCodes();
comboboxSite.DataBind();
}
protected void comboboxSite_SelectedIndexChanged(object sender, EventArgs e)
{
string data = comboboxSite.SelectedItem.Text;
comboboxUnit.DataSource = controller.GetUnitCodes(data);
comboboxUnit.DataBind();
}
protected void comboboxUnit_SelectedIndexChanged(object sender, EventArgs e)
{
string unit = comboboxUnit.SelectedItem.Text;
string site = comboboxSite.SelectedItem.Text;
comboboxOffer.DataSource = controller.GetOfferCodes(site,unit);
comboboxOffer.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var manager = PlugInManager.GetBookingDataManager();
var bookingprocess = new BookingProcess();
bookingprocess.Id = Guid.NewGuid().ToString();
bookingprocess.Status = DocumentProcessStatus.Close;
bookingprocess.OfferInfo.Country = txtCountry.Text;
bookingprocess.OfferInfo.PlaceName = txtPlace.Text;
bookingprocess.OfferInfo.SiteCode=comboboxSite.SelectedItem!=null?comboboxSite.SelectedItem.Text:"";
string sitecode = bookingprocess.OfferInfo.SiteCode;
string sitename = controller.GetSiteName(sitecode);
bookingprocess.OfferInfo.SiteName = sitename;
bookingprocess.OfferInfo.UnitCode = comboboxUnit.SelectedItem != null ? comboboxUnit.SelectedItem.Text : "";
bookingprocess.OfferInfo.OfferCode = comboboxOffer.SelectedItem != null ? comboboxOffer.SelectedItem.Text : "";
string offercode = bookingprocess.OfferInfo.OfferCode;
string offername = controller.GetOfferName(offercode);
bookingprocess.OfferInfo.OfferName = offername;
bookingprocess.OfferInfo.TourOperatorCode = txtTourOperator.Text.Trim();
bookingprocess.OfferInfo.CheckIn = ASPxDateEditCheckIn.Date;
bookingprocess.OfferInfo.CheckOut = ASPxDateEditCheckOut.Date;
bookingprocess.OfferInfo.Adults = int.Parse(txtAdults.Text.Trim());
bookingprocess.OfferInfo.Children = int.Parse(txtChildren.Text.Trim());
bookingprocess.TravelApplicant.FirstName = customer.FirstName;
bookingprocess.TravelApplicant.LastName = customer.LastName;
bookingprocess.TravelApplicant.Contry = customer.Country;
bookingprocess.TravelApplicant.Adress = customer.Adress;
bookingprocess.TravelApplicantId = customer.CustomerNr;
bookingprocess.SellingPartner = int.Parse(txtPartnerId.Text.Trim());
bookingprocess.Season = txtSeason.Text;
bookingprocess.TravelApplicant.MobilePhone = customer.MobilePhone;
bookingprocess.TravelApplicant.Phone = customer.Phone;
bookingprocess.TravelApplicant.ZipCode = customer.ZipCode;
bookingprocess.TravelApplicant.Place = customer.Place;
bookingprocess.TravelApplicant.Salutation = customer.Salutation;
bookingprocess.TravelApplicant.EMail = customer.EMail;
List<TravelApplicantPayment> payments = bookingprocess.Payments;
TravelApplicantPayment applicantPayment = new TravelApplicantPayment();
applicantPayment.Date = ASPxDateEditPayment.Date;
applicantPayment.Value = Decimal.Parse(txtPaymetnValue.Text.Trim());
payments.Add(applicantPayment);
bookingprocess.Payments = payments;
bookingprocess.BookingNumber = txtBookingNumber.Text;
manager.AddMasterData(bookingprocess);
}
}
} |
using Framework.Core.Common;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.CustomForm.CustomFormBuild
{
public class BuildPageAddCodeDialog : CustomFormBuildPage
{
public BuildPageAddCodeDialog(Driver driver) : base(driver) { }
public IWebElement Name { get { return _driver.FindElement(By.Name("Name")); } }
public IWebElement Description { get { return _driver.FindElement(By.Name("Description")); } }
public IWebElement ParentCodeList { get { return _driver.FindElement(By.ClassName("ParentCodeList")); } }
public IWebElement CreateAndClose { get { return _driver.FindElement(By.Id("createCodeAndClose")); } }
public void SetName(string name)
{
_driver.SendKeys(Name,name);
}
public void ClickCreateAndClose()
{
_driver.Click(CreateAndClose);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SAAS.FrameWork.Extensions
{
public static partial class TypeExtensions
{
#region IsStringType
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Type"></see> is string type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsStringType(this global::System.Type type)
{
return type == typeof(string);
}
#endregion
#region TypeIsValueTypeOrStringType
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Type"></see> is a value type or string type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool TypeIsValueTypeOrStringType(this global::System.Type type)
{
if (type == null)
{
return false;
//throw new ArgumentNullException(nameof(type));
}
return type.IsValueType || type.IsStringType();
}
#endregion
#region GetUnderlyingTypeIfNullable
/// <summary>
/// 若为Nullable类型(例如 long?)则获取对应的值类型(例如long),否则返回自身。
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static global::System.Type GetUnderlyingTypeIfNullable(this global::System.Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
//Nullable.GetUnderlyingType(type);
// We need to check whether the property is NULLABLE
// If it is NULLABLE, then get the underlying type. eg if "Nullable<long>" then this will return just "long"
return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) ? type.GetGenericArguments()[0] : type;
}
#endregion
#region DefaultValue
/// <summary>
/// 功能类似 default(T)
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static object DefaultValue(this Type type)
{
if (null == type || !type.IsValueType) return null;
return Activator.CreateInstance(type);
}
#endregion
#region Convert
/// <summary>
/// 若Type为Nullable类型(例如 long?)则转换为对应的值类型(例如long),否则直接转换。
/// 若转换失败,会返回default(T)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T Convert<T>(this Object value)
{
if (value == null)
{
return default(T);
//throw new ArgumentNullException(nameof(value));
}
//try
//{
return (T)System.Convert.ChangeType(value, typeof(T).GetUnderlyingTypeIfNullable());
//}
//catch (System.Exception)
//{
// throw;
// return default(T);
//}
}
/// <summary>
/// 若为Nullable类型(例如 long?)则转换为对应的值类型(例如long),否则直接转换。
/// </summary>
/// <param name="type"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Object Convert(this Object value, global::System.Type type)
{
if (value == null)
{
return null;
//throw new ArgumentNullException(nameof(value));
}
return System.Convert.ChangeType(value, type.GetUnderlyingTypeIfNullable());
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity.Core;
namespace CNWTT.Models.DAO
{
public class AccountInforDAO
{
public static int addAccountInfor(accountInfor accIn)
{
int idAccInfo = -1;
using (var db = new cnwttEntities())
{
try
{
db.accountInfors.Add(accIn);
db.SaveChanges();
idAccInfo = accIn.id;
}
catch (EntityCommandExecutionException e) { }
catch (EntityException e) { }
}
return idAccInfo;
}
public static bool deleteAccountInfoByIdAccount(int idAccount)
{
bool b = false;
using (var db = new cnwttEntities())
{
using (var dbTransaction = db.Database.BeginTransaction())
{
try
{
accountInfor accInfor = db.accountInfors
.Where(a => a.account_id == idAccount)
.Single();
db.accountInfors.Remove(accInfor);
db.SaveChanges();
dbTransaction.Commit();
b = true;
}
catch (InvalidOperationException) { }
catch (EntityCommandExecutionException e) { }
catch (EntityException e) { }
}
}
return b;
}
public static accountInfor getAccountInfoByIdAccount(int idAccount)
{
accountInfor accountInfo = null;
using (var db = new cnwttEntities())
{
try
{
accountInfo = db.accountInfors
.Where(accIn => accIn.account_id == idAccount)
.Single();
}
catch (InvalidOperationException) { }
catch (EntityCommandExecutionException e) { }
catch (EntityException e) { }
}
return accountInfo;
}
public static IList<accountInfor> getListAll()
{
IList<accountInfor> list = null;
using (var db = new cnwttEntities())
{
try
{
list = db.accountInfors
.ToList();
}
catch (InvalidOperationException) { }
catch (EntityCommandExecutionException e) { }
catch (EntityException e) { }
}
return list;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Crystal.Plot2D.Charts
{
public sealed class MinorNumericTicksProvider : ITicksProvider<double>
{
private readonly ITicksProvider<double> parent;
private Range<double>[] ranges;
internal void SetRanges(IEnumerable<Range<double>> ranges)
{
this.ranges = ranges.ToArray();
}
private double[] coeffs;
public double[] Coeffs
{
get { return coeffs; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
coeffs = value;
Changed.Raise(this);
}
}
internal MinorNumericTicksProvider(ITicksProvider<double> parent)
{
this.parent = parent;
Coeffs = new double[] { 0.3, 0.3, 0.3, 0.3, 0.6, 0.3, 0.3, 0.3, 0.3 };
}
#region ITicksProvider<double> Members
public event EventHandler Changed;
public ITicksInfo<double> GetTicks(Range<double> range, int ticksCount)
{
if (Coeffs.Length == 0)
{
return new TicksInfo<double>();
}
var minorTicks = ranges.Select(r => CreateTicks(r)).SelectMany(m => m);
var res = new TicksInfo<double>
{
TickSizes = minorTicks.Select(m => m.Value).ToArray(),
Ticks = minorTicks.Select(m => m.Tick).ToArray()
};
return res;
}
public MinorTickInfo<double>[] CreateTicks(Range<double> range)
{
double step = (range.Max - range.Min) / (Coeffs.Length + 1);
MinorTickInfo<double>[] res = new MinorTickInfo<double>[Coeffs.Length];
for (int i = 0; i < Coeffs.Length; i++)
{
res[i] = new MinorTickInfo<double>(Coeffs[i], range.Min + step * (i + 1));
}
return res;
}
public int DecreaseTickCount(int ticksCount)
{
return ticksCount;
}
public int IncreaseTickCount(int ticksCount)
{
return ticksCount;
}
public ITicksProvider<double> MinorProvider
{
get { return null; }
}
public ITicksProvider<double> MajorProvider
{
get { return parent; }
}
#endregion
}
}
|
using Divar.Core.Domain.Shared.ValueObjects;
using Divar.Core.Domain.UserProfiles.Entities;
using Divar.Core.Domain.UserProfiles.ValueObjects;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Divar.Infrastructures.Data.SqlServer.UserProfiles
{
public class UserProfileConfig : IEntityTypeConfiguration<UserProfile>
{
public void Configure(EntityTypeBuilder<UserProfile> builder)
{
builder.Property(c => c.FirstName).HasConversion(c => c.Value,
d => FirstName.FromString(d));
builder.Property(c => c.LastName).HasConversion(c => c.Value,
d => LastName.FromString(d));
builder.Property(c => c.DisplayName).HasConversion(c => c.Value,
d => DisplayName.FromString(d));
builder.Property(c => c.Email).HasConversion(c => c.Value,
d => Email.FromString(d));
}
}
}
|
using UnityEngine;
using System.Collections;
public class BONUS : MonoBehaviour {
public static int AllStars;
// Use this for initialization
void Start ()
{
Object[] b = GameObject.FindObjectsOfType (typeof(BONUS));
AllStars = b.Length;
}
// Update is called once per frame
void Update ()
{
}
public void OnTriggerEnter (Collider other)
{
PlayerAttrib.CollectedStars += 1;
this.gameObject.SetActive (false);
}
}
|
using System;
using System.Drawing.Imaging;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Security.Cryptography;
namespace Com.Colin.Lib
{
/// <summary>
/// 枚举,生成缩略图模式
/// </summary>
public enum ThumbnailMod : byte
{
/// <summary>
/// HW
/// </summary>
HW,
/// <summary>
/// W
/// </summary>
W,
/// <summary>
/// H
/// </summary>
H,
/// <summary>
/// Cut
/// </summary>
Cut
};
/// <summary>
/// 操作图片类,生成缩略图,添加水印
/// </summary>
public static class ImageHelper
{
private static Hashtable htmimes = new Hashtable();
internal static readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp";
#region 生成缩略图
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="mode"></param>
/// <returns></returns>
public static bool MakeThumbnail(string originalImagePath, int width, int height, ThumbnailMod mode)
{
string thumbnailPath = originalImagePath.Substring(0, originalImagePath.LastIndexOf('.')) + "s.jpg";
Image originalImage = Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
switch (mode)
{
case ThumbnailMod.HW://指定高宽缩放(可能变形)
break;
case ThumbnailMod.W://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case ThumbnailMod.H://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case ThumbnailMod.Cut://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
Image bitmap = new Bitmap(towidth, toheight);
//新建一个画板
Graphics g = Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel);
bool isok = false;
try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, ImageFormat.Jpeg);
isok = true;
}
catch (Exception)
{
thumbnailPath = originalImagePath;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
return isok;
}
#endregion
#region 在图片上生成图片水印
///// <summary>
///// 在图片上生成图片水印
///// </summary>
///// <param name="Path">原服务器图片路径</param>
///// <param name="Path_syp">生成的带图片水印的图片路径</param>
///// <param name="Path_sypf">水印图片路径</param>
/// <summary>
/// 在图片上生成图片水印
/// </summary>
/// <param name="Path">原服务器图片路径</param>
/// <param name="Path_sypf">水印图片路径</param>
public static void AddWaterPic(string Path, string Path_sypf)
{
try
{
Image image = Image.FromFile(Path);
Image copyImage = Image.FromFile(Path_sypf);
Graphics g = Graphics.FromImage(image);
g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
g.Dispose();
image.Save(Path + ".temp");
image.Dispose();
System.IO.File.Delete(Path);
File.Move(Path + ".temp", Path);
}
catch
{ }
}
#endregion
/// <summary>
/// 公共方法
/// </summary>
private static void GetImgType()
{
htmimes[".jpe"] = "image/jpeg";
htmimes[".jpeg"] = "image/jpeg";
htmimes[".jpg"] = "image/jpeg";
htmimes[".png"] = "image/png";
htmimes[".tif"] = "image/tiff";
htmimes[".tiff"] = "image/tiff";
htmimes[".bmp"] = "image/bmp";
}
#region 返回新图片尺寸
/// <summary>
/// 返回新图片尺寸
/// </summary>
/// <param name="width">原始宽</param>
/// <param name="height">原始高</param>
/// <param name="maxWidth">新图片最大宽</param>
/// <param name="maxHeight">新图片最大高</param>
/// <returns></returns>
public static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
{
decimal MAX_WIDTH = (decimal)maxWidth;
decimal MAX_HEIGHT = (decimal)maxHeight;
decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;
int newWidth, newHeight;
decimal originalWidth = (decimal)width;
decimal originalHeight = (decimal)height;
if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
{
decimal factor;
// determine the largest factor
if (originalWidth / originalHeight > ASPECT_RATIO)
{
factor = originalWidth / MAX_WIDTH;
newWidth = Convert.ToInt32(originalWidth / factor);
newHeight = Convert.ToInt32(originalHeight / factor);
}
else
{
factor = originalHeight / MAX_HEIGHT;
newWidth = Convert.ToInt32(originalWidth / factor);
newHeight = Convert.ToInt32(originalHeight / factor);
}
}
else
{
newWidth = width;
newHeight = height;
}
return new Size(newWidth, newHeight);
}
#endregion
#region 生成随机数字
/// <summary>
/// 生成随机数字
/// </summary>
/// <param name="length">生成长度</param>
public static string Number(int Length)
{
return Number(Length, false);
}
/// <summary>
/// 生成随机数字
/// </summary>
/// <param name="Length">生成长度</param>
/// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
public static string Number(int Length, bool Sleep)
{
if (Sleep) System.Threading.Thread.Sleep(3);
string result = "";
System.Random random = new Random();
for (int i = 0; i < Length; i++)
{
result += random.Next(10).ToString();
}
return result;
}
#endregion
#region 生成随机字母与数字
/// <summary>
/// 生成随机字母与数字
/// </summary>
/// <param name="IntStr">生成长度</param>
public static string Str(int Length)
{
return Str(Length, false);
}
/// <summary>
/// 生成随机字母与数字
/// </summary>
/// <param name="Length">生成长度</param>
/// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
public static string Str(int Length, bool Sleep)
{
if (Sleep) System.Threading.Thread.Sleep(3);
char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
string result = "";
int n = Pattern.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < Length; i++)
{
int rnd = random.Next(0, n);
result += Pattern[rnd];
}
return result;
}
#endregion
#region 生成随机纯字母随机数
/// <summary>
/// 生成随机纯字母随机数
/// </summary>
/// <param name="IntStr">生成长度</param>
public static string Str_char(int Length)
{
return Str_char(Length, false);
}
/// <summary>
/// 生成随机纯字母随机数
/// </summary>
/// <param name="Length">生成长度</param>
/// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
public static string Str_char(int Length, bool Sleep)
{
if (Sleep) System.Threading.Thread.Sleep(3);
char[] Pattern = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
string result = "";
int n = Pattern.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < Length; i++)
{
int rnd = random.Next(0, n);
result += Pattern[rnd];
}
return result;
}
#endregion
}
/// <summary>
/// 验证图片类
/// </summary>
public class YZMHelper
{
#region 私有字段
private string text;
private Bitmap image;
private int letterCount = 4; //验证码位数
private int letterWidth = 16; //单个字体的宽度范围
private int letterHeight = 20; //单个字体的高度范围
private static byte[] randb = new byte[4];
private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
private Font[] fonts =
{
new Font(new FontFamily("Times New Roman"),10 +Next(1),System.Drawing.FontStyle.Regular),
new Font(new FontFamily("Georgia"), 10 + Next(1),System.Drawing.FontStyle.Regular),
new Font(new FontFamily("Arial"), 10 + Next(1),System.Drawing.FontStyle.Regular),
new Font(new FontFamily("Comic Sans MS"), 10 + Next(1),System.Drawing.FontStyle.Regular)
};
#endregion
#region 公有属性
/// <summary>
/// 验证码
/// </summary>
public string Text
{
get { return this.text; }
}
/// <summary>
/// 验证码图片
/// </summary>
public Bitmap Image
{
get { return this.image; }
}
#endregion
#region 私有方法
/// <summary>
/// 获得下一个随机数
/// </summary>
/// <param name="max">最大值</param>
private static int Next(int max)
{
rand.GetBytes(randb);
int value = BitConverter.ToInt32(randb, 0);
value = value % (max + 1);
if (value < 0) value = -value;
return value;
}
/// <summary>
/// 获得下一个随机数
/// </summary>
/// <param name="min">最小值</param>
/// <param name="max">最大值</param>
private static int Next(int min, int max)
{
int value = Next(max - min) + min;
return value;
}
#endregion
#region 公共方法
/// <summary>
/// 绘制验证码
/// </summary>
public void CreateImage()
{
int int_ImageWidth = this.text.Length * letterWidth;
Bitmap image = new Bitmap(int_ImageWidth, letterHeight);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
for (int i = 0; i < 2; i++)
{
int x1 = Next(image.Width - 1);
int x2 = Next(image.Width - 1);
int y1 = Next(image.Height - 1);
int y2 = Next(image.Height - 1);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
int _x = -12, _y = 0;
for (int int_index = 0; int_index < this.text.Length; int_index++)
{
_x += Next(12, 16);
_y = Next(-2, 2);
string str_char = this.text.Substring(int_index, 1);
str_char = Next(1) == 1 ? str_char.ToLower() : str_char.ToUpper();
Brush newBrush = new SolidBrush(GetRandomColor());
Point thePos = new Point(_x, _y);
g.DrawString(str_char, fonts[Next(fonts.Length - 1)], newBrush, thePos);
}
for (int i = 0; i < 10; i++)
{
int x = Next(image.Width - 1);
int y = Next(image.Height - 1);
image.SetPixel(x, y, Color.FromArgb(Next(0, 255), Next(0, 255), Next(0, 255)));
}
image = TwistImage(image, true, Next(1, 3), Next(4, 6));
g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));
this.image = image;
}
/// <summary>
/// 字体随机颜色
/// </summary>
public Color GetRandomColor()
{
Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
int int_Red = RandomNum_First.Next(180);
int int_Green = RandomNum_Sencond.Next(180);
int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);
}
/// <summary>
/// 正弦曲线Wave扭曲图片
/// </summary>
/// <param name="srcBmp">图片路径</param>
/// <param name="bXDir">如果扭曲则选择为True</param>
/// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
/// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
{
double PI = 6.283185307179586476925286766559;
Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
Graphics graph = Graphics.FromImage(destBmp);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
graph.Dispose();
double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
for (int i = 0; i < destBmp.Width; i++)
{
for (int j = 0; j < destBmp.Height; j++)
{
double dx = 0;
dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;
dx += dPhase;
double dy = Math.Sin(dx);
int nOldX = 0, nOldY = 0;
nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
nOldY = bXDir ? j : j + (int)(dy * dMultValue);
Color color = srcBmp.GetPixel(i, j);
if (nOldX >= 0 && nOldX < destBmp.Width
&& nOldY >= 0 && nOldY < destBmp.Height)
{
destBmp.SetPixel(nOldX, nOldY, color);
}
}
}
srcBmp.Dispose();
return destBmp;
}
#endregion
}
}
|
namespace BettingSystem.Domain.Games.Models.Matches
{
using System;
using Exceptions;
using FakeItEasy;
using FluentAssertions;
using Xunit;
using static StadiumFakes.Data;
public class StadiumSpecs
{
[Fact]
public void ValidStadiumShouldNotThrowException()
{
Action act = () => A.Dummy<Stadium>();
act.Should().NotThrow<InvalidMatchException>();
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("cs")]
public void InvalidNameShouldThrowException(string name)
{
Action act = () => GetStadium(name);
act.Should().Throw<InvalidMatchException>();
}
}
}
|
namespace WinAppDriver.UI
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Windows.Input;
using SystemWrapper.Windows.Input;
using WinUserWrapper;
internal class Keyboard : IKeyboard
{
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1214:StaticReadonlyElementsMustAppearBeforeStaticNonReadonlyElements", Justification = "Reviewed.")]
private static ILogger logger = Logger.GetLogger("WinAppDriver");
private static readonly List<Key> ModifierKeys = new List<Key>
{
Key.LeftCtrl, Key.RightCtrl,
Key.LeftAlt, Key.RightAlt,
Key.LeftShift, Key.RightShift,
Key.LWin, Key.RWin,
};
private IKeyboardWrap keyboard;
private IWinUserWrap winUser;
private IKeyInteropWrap keyInterop;
public Keyboard(IKeyboardWrap keyboard, IKeyInteropWrap keyInterop, IWinUserWrap winUser)
{
this.keyboard = keyboard;
this.keyInterop = keyInterop;
this.winUser = winUser;
}
public bool IsModifierKey(Key key)
{
return ModifierKeys.Contains(key);
}
public bool IsModifierKeysPressed(ModifierKeys keys)
{
return (this.keyboard.Modifiers & keys) == keys;
}
public void ReleaseAllModifierKeys()
{
foreach (var key in ModifierKeys)
{
if ((this.keyboard.GetKeyStates(key) & KeyStates.Down) > 0)
{
this.SendKeyboardInput(key, KEYEVENTF.KEYUP);
}
}
}
public void KeyUpOrDown(Key key)
{
bool down = (this.keyboard.GetKeyStates(key) & KeyStates.Down) > 0;
logger.Debug("Toggle the (modifier) key ({0}), currently pressed? {1}", key, down);
KEYEVENTF type = down ? KEYEVENTF.KEYUP : KEYEVENTF.KEYDOWN;
this.SendKeyboardInput(key, type);
}
public void KeyPress(Key key)
{
this.SendKeyboardInput(key, KEYEVENTF.KEYDOWN);
this.SendKeyboardInput(key, KEYEVENTF.KEYUP);
}
public void Type(char key)
{
short vkeyModifiers = this.winUser.VkKeyScan(key);
if (vkeyModifiers != -1)
{
var vkey = vkeyModifiers & 0xff;
var modifiers = vkeyModifiers >> 8; // high-order byte = shift state
bool shiftNeeded = (modifiers & 1) != 0;
bool shiftPressed = this.IsModifierKeysPressed(System.Windows.Input.ModifierKeys.Shift);
if (shiftNeeded && !shiftPressed)
{
this.SendKeyboardInput(Key.LeftShift, KEYEVENTF.KEYDOWN);
this.SendKeyboardInput(vkey, KEYEVENTF.KEYDOWN);
this.SendKeyboardInput(vkey, KEYEVENTF.KEYUP);
this.SendKeyboardInput(Key.LeftShift, KEYEVENTF.KEYUP);
}
else
{
this.SendKeyboardInput(vkey, KEYEVENTF.KEYDOWN);
this.SendKeyboardInput(vkey, KEYEVENTF.KEYUP);
}
}
else
{
var message = string.Format("Unicode input is not supported yet. (U+{0})", ((int)key).ToString("X"));
throw new WinAppDriverException(message); // TODO Unicode input
}
}
private void SendKeyboardInput(Key key, KEYEVENTF type)
{
this.SendKeyboardInput(this.keyInterop.VirtualKeyFromKey(key), type);
}
private void SendKeyboardInput(int vkey, KEYEVENTF type)
{
INPUT input = new INPUT
{
type = (int)INPUTTYPE.KEYBOARD,
u = new InputUnion
{
ki = new KEYBDINPUT
{
wVk = (ushort)vkey,
wScan = 0,
dwFlags = (uint)type,
dwExtraInfo = this.winUser.GetMessageExtraInfo(),
}
}
};
this.winUser.SendInput(1, new INPUT[] { input }, Marshal.SizeOf(typeof(INPUT)));
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class UltiDraw {
[System.Serializable]
public class GUIRect {
[Range(0f, 1f)] public float X = 0.5f;
[Range(0f, 1f)] public float Y = 0.5f;
[Range(0f, 1f)] public float W = 0.5f;
[Range(0f, 1f)] public float H = 0.5f;
public GUIRect(float x, float y, float w, float h) {
X = x;
Y = y;
W = w;
H = h;
}
public Vector2 GetPosition() {
return new Vector2(X, Y);
}
public Vector2 GetSize() {
return new Vector2(W, H);
}
#if UNITY_EDITOR
public void Inspector() {
X = EditorGUILayout.Slider("X", X, 0f, 1f);
Y = EditorGUILayout.Slider("Y", Y, 0f, 1f);
W = EditorGUILayout.Slider("W", W, 0f, 1f);
H = EditorGUILayout.Slider("H", H, 0f, 1f);
}
#endif
}
public static Color None = new Color(0f, 0f, 0f, 0f);
public static Color White = Color.white;
public static Color Black = Color.black;
public static Color Red = Color.red;
public static Color DarkRed = new Color(0.75f, 0f, 0f, 1f);
public static Color Green = Color.green;
public static Color DarkGreen = new Color(0f, 0.75f, 0f, 1f);
public static Color Blue = Color.blue;
public static Color Cyan = Color.cyan;
public static Color Magenta = Color.magenta;
public static Color Yellow = Color.yellow;
public static Color Grey = Color.grey;
public static Color LightGrey = new Color(0.75f, 0.75f, 0.75f, 1f);
public static Color DarkGrey = new Color(0.25f, 0.25f, 0.25f, 1f);
public static Color BlackGrey = new Color(0.125f, 0.125f, 0.125f, 1f);
public static Color Orange = new Color(1f, 0.5f, 0f, 1f);
public static Color Brown = new Color(0.5f, 0.25f, 0f, 1f);
public static Color Mustard = new Color(1f, 0.75f, 0.25f, 1f);
public static Color Teal = new Color(0f, 0.75f, 0.75f, 1f);
public static Color Purple = new Color(0.5f, 0f, 0.5f, 1f);
public static Color DarkBlue = new Color(0f, 0f, 0.75f, 1f);
public static Color IndianRed = new Color(205f/255f, 92f/255f, 92f/255f, 1f);
public static Color Gold = new Color(212f/255f, 175f/255f, 55f/255f, 1f);
private static int Resolution = 30;
private static Mesh Initialised;
private static bool Active;
private static Material GLMaterial;
private static Material MeshMaterial;
private static float GUIOffset = 0.001f;
private static Camera Camera;
private static Vector3 ViewPosition;
private static Quaternion ViewRotation;
private static PROGRAM Program = PROGRAM.NONE;
private enum PROGRAM {NONE, LINES, TRIANGLES, TRIANGLE_STRIP, QUADS};
private static Mesh CircleMesh;
private static Mesh QuadMesh;
private static Mesh CubeMesh;
private static Mesh SphereMesh;
private static Mesh CylinderMesh;
private static Mesh CapsuleMesh;
private static Mesh ConeMesh;
private static Mesh PyramidMesh;
private static Mesh BoneMesh;
private static Vector3[] CircleWire;
private static Vector3[] QuadWire;
private static Vector3[] CubeWire;
private static Vector3[] SphereWire;
private static Vector3[] CylinderWire;
private static Vector3[] CapsuleWire;
private static Vector3[] ConeWire;
private static Vector3[] PyramidWire;
private static Vector3[] BoneWire;
private static Font FontType;
//------------------------------------------------------------------------------------------
//CONTROL FUNCTIONS
//------------------------------------------------------------------------------------------
public static void Begin() {
if(Active) {
Debug.Log("Drawing is still active. Call 'End()' to stop.");
} else {
Initialise();
Camera = GetCamera();
if(Camera != null) {
ViewPosition = Camera.transform.position;
ViewRotation = Camera.transform.rotation;
}
Active = true;
}
}
public static void End() {
if(Active) {
SetProgram(PROGRAM.NONE);
Camera = null;
ViewPosition = Vector3.zero;
ViewRotation = Quaternion.identity;
Active = false;
} else {
Debug.Log("Drawing is not active. Call 'Begin()' to start.");
}
}
public static void SetDepthRendering(bool enabled) {
Initialise();
SetProgram(PROGRAM.NONE);
GLMaterial.SetInt("_ZWrite", enabled ? 1 : 0);
GLMaterial.SetInt("_ZTest", enabled ? (int)UnityEngine.Rendering.CompareFunction.LessEqual : (int)UnityEngine.Rendering.CompareFunction.Always);
MeshMaterial.SetInt("_ZWrite", enabled ? 1 : 0);
MeshMaterial.SetInt("_ZTest", enabled ? (int)UnityEngine.Rendering.CompareFunction.LessEqual : (int)UnityEngine.Rendering.CompareFunction.Always);
}
public static void SetCurvature(float value) {
Initialise();
SetProgram(PROGRAM.NONE);
MeshMaterial.SetFloat("_Power", value);
}
public static void SetFilling(float value) {
value = Mathf.Clamp(value, 0f, 1f);
Initialise();
SetProgram(PROGRAM.NONE);
MeshMaterial.SetFloat("_Filling", value);
}
//------------------------------------------------------------------------------------------
//3D SCENE DRAWING FUNCTIONS
//------------------------------------------------------------------------------------------
public static void DrawLine(Vector3 start, Vector3 end, Color color) {
if(Return()) {return;};
SetProgram(PROGRAM.LINES);
GL.Color(color);
GL.Vertex(start);
GL.Vertex(end);
}
public static void DrawLine(Vector3 start, Vector3 end, float thickness, Color color) {
DrawLine(start, end, thickness, thickness, color);
}
public static void DrawLine(Vector3 start, Vector3 end, float startThickness, float endThickness, Color color) {
if(Return()) {return;};
SetProgram(PROGRAM.QUADS);
GL.Color(color);
Vector3 dir = (end-start).normalized;
Vector3 orthoStart = startThickness/2f * (Quaternion.AngleAxis(90f, (start - ViewPosition)) * dir);
Vector3 orthoEnd = endThickness/2f * (Quaternion.AngleAxis(90f, (end - ViewPosition)) * dir);
GL.Vertex(end+orthoEnd);
GL.Vertex(end-orthoEnd);
GL.Vertex(start-orthoStart);
GL.Vertex(start+orthoStart);
}
public static void DrawTriangle(Vector3 a, Vector3 b, Vector3 c, Color color) {
if(Return()) {return;};
SetProgram(PROGRAM.TRIANGLES);
GL.Color(color);
GL.Vertex(b);
GL.Vertex(a);
GL.Vertex(c);
}
public static void DrawCircle(Vector3 position, float size, Color color) {
DrawMesh(CircleMesh, position, ViewRotation, size*Vector3.one, color);
}
public static void DrawCircle(Vector3 position, Quaternion rotation, float size, Color color) {
DrawMesh(CircleMesh, position, rotation, size*Vector3.one, color);
}
public static void DrawWireCircle(Vector3 position, float size, Color color) {
DrawWire(CircleWire, position, ViewRotation, size*Vector3.one, color);
}
public static void DrawWireCircle(Vector3 position, Quaternion rotation, float size, Color color) {
DrawWire(CircleWire, position, rotation, size*Vector3.one, color);
}
public static void DrawWiredCircle(Vector3 position, float size, Color circleColor, Color wireColor) {
DrawCircle(position, size, circleColor);
DrawWireCircle(position, size, wireColor);
}
public static void DrawWiredCircle(Vector3 position, Quaternion rotation, float size, Color circleColor, Color wireColor) {
DrawCircle(position, rotation, size, circleColor);
DrawWireCircle(position, rotation, size, wireColor);
}
public static void DrawEllipse(Vector3 position, float width, float height, Color color) {
DrawMesh(CircleMesh, position, ViewRotation, new Vector3(width, height, 1f), color);
}
public static void DrawEllipse(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawMesh(CircleMesh, position, rotation, new Vector3(width, height, 1f), color);
}
public static void DrawWireEllipse(Vector3 position, float width, float height, Color color) {
DrawWire(CircleWire, position, ViewRotation, new Vector3(width, height, 1f), color);
}
public static void DrawWireEllipse(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawWire(CircleWire, position, rotation, new Vector3(width, height, 1f), color);
}
public static void DrawWiredEllipse(Vector3 position, float width, float height, Color ellipseColor, Color wireColor) {
DrawEllipse(position, ViewRotation, width, height, ellipseColor);
DrawWireEllipse(position, ViewRotation, width, height, wireColor);
}
public static void DrawWiredEllipse(Vector3 position, Quaternion rotation, float width, float height, Color ellipseColor, Color wireColor) {
DrawEllipse(position, rotation, width, height, ellipseColor);
DrawWireEllipse(position, rotation, width, height, wireColor);
}
public static void DrawArrow(Vector3 start, Vector3 end, float tipPivot, float shaftWidth, float tipWidth, Color color) {
tipPivot = Mathf.Clamp(tipPivot, 0f, 1f);
Vector3 pivot = start + tipPivot * (end-start);
DrawLine(start, pivot, shaftWidth, color);
DrawLine(pivot, end, tipWidth, 0f, color);
}
public static void DrawArrow(Vector3 start, Vector3 end, float tipPivot, float shaftWidth, float tipWidth, Color shaftColor, Color tipColor) {
tipPivot = Mathf.Clamp(tipPivot, 0f, 1f);
Vector3 pivot = start + tipPivot * (end-start);
DrawLine(start, pivot, shaftWidth, shaftColor);
DrawLine(pivot, end, tipWidth, 0f, tipColor);
}
public static void DrawGrid(Vector3 center, Quaternion rotation, int cellsX, int cellsY, float sizeX, float sizeY, Color color) {
if(Return()) {return;}
float width = cellsX * sizeX;
float height = cellsY * sizeY;
Vector3 start = center - width/2f * (rotation * Vector3.right) - height/2f * (rotation * Vector3.forward);
Vector3 dirX = rotation * Vector3.right;
Vector3 dirY = rotation * Vector3.forward;
for(int i=0; i<cellsX+1; i++) {
DrawLine(start + i*sizeX*dirX, start + i*sizeX*dirX + height*dirY, color);
}
for(int i=0; i<cellsY+1; i++) {
DrawLine(start + i*sizeY*dirY, start + i*sizeY*dirY + width*dirX, color);
}
}
public static void DrawQuad(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawMesh(QuadMesh, position, rotation, new Vector3(width, height, 1f), color);
}
public static void DrawWireQuad(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawWire(QuadWire, position, rotation, new Vector3(width, height, 1f), color);
}
public static void DrawWiredQuad(Vector3 position, Quaternion rotation, float width, float height, Color quadColor, Color wireColor) {
DrawQuad(position, rotation, width, height, quadColor);
DrawWireQuad(position, rotation, width, height, wireColor);
}
public static void DrawCube(Vector3 position, Quaternion rotation, float size, Color color) {
DrawMesh(CubeMesh, position, rotation, size*Vector3.one, color);
}
public static void DrawCube(Matrix4x4 matrix, float size, Color color) {
DrawCube(matrix.GetPosition(), matrix.GetRotation(), size, color);
}
public static void DrawWireCube(Vector3 position, Quaternion rotation, float size, Color color) {
DrawWire(CubeWire, position, rotation, size*Vector3.one, color);
}
public static void DrawWireCube(Matrix4x4 matrix, float size, Color color) {
DrawWireCube(matrix.GetPosition(), matrix.GetRotation(), size, color);
}
public static void DrawWiredCube(Vector3 position, Quaternion rotation, float size, Color cubeColor, Color wireColor) {
DrawCube(position, rotation, size, cubeColor);
DrawWireCube(position, rotation, size, wireColor);
}
public static void DrawWiredCube(Matrix4x4 matrix, float size, Color cubeColor, Color wireColor) {
DrawWiredCube(matrix.GetPosition(), matrix.GetRotation(), size, cubeColor, wireColor);
}
public static void DrawCuboid(Vector3 position, Quaternion rotation, Vector3 size, Color color) {
DrawMesh(CubeMesh, position, rotation, size, color);
}
public static void DrawCuboid(Matrix4x4 matrix, Color color) {
DrawMesh(CubeMesh, matrix, color);
}
public static void DrawWireCuboid(Vector3 position, Quaternion rotation, Vector3 size, Color color) {
DrawWire(CubeWire, position, rotation, size, color);
}
public static void DrawWireCuboid(Matrix4x4 matrix, Color color) {
DrawWire(CubeWire, matrix, color);
}
public static void DrawWiredCuboid(Vector3 position, Quaternion rotation, Vector3 size, Color cuboidColor, Color wireColor) {
DrawCuboid(position, rotation, size, cuboidColor);
DrawWireCuboid(position, rotation, size, wireColor);
}
public static void DrawWiredCuboid(Matrix4x4 matrix, Color cuboidColor, Color wireColor) {
DrawCuboid(matrix, cuboidColor);
DrawWireCuboid(matrix, wireColor);
}
public static void DrawSphere(Vector3 position, Quaternion rotation, float size, Color color) {
DrawMesh(SphereMesh, position, rotation, size*Vector3.one, color);
}
public static void DrawSphere(Matrix4x4 matrix, float size, Color color) {
DrawMesh(SphereMesh, matrix.GetPosition(), matrix.GetRotation(), size*Vector3.one, color);
}
public static void DrawWireSphere(Vector3 position, Quaternion rotation, float size, Color color) {
DrawWire(SphereWire, position, rotation, size*Vector3.one, color);
}
public static void DrawWireSphere(Matrix4x4 matrix, float size, Color color) {
DrawWire(SphereWire, matrix.GetPosition(), matrix.GetRotation(), size*Vector3.one, color);
}
public static void DrawWiredSphere(Vector3 position, Quaternion rotation, float size, Color sphereColor, Color wireColor) {
DrawSphere(position, rotation, size, sphereColor);
DrawWireSphere(position, rotation, size, wireColor);
}
public static void DrawWiredSphere(Matrix4x4 matrix, float size, Color sphereColor, Color wireColor) {
DrawSphere(matrix, size, sphereColor);
DrawWireSphere(matrix, size, wireColor);
}
public static void DrawEllipsoid(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawMesh(SphereMesh, position, rotation, new Vector3(width, height, width), color);
}
public static void DrawWireEllipsoid(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawWire(SphereWire, position, rotation, new Vector3(width, height, width), color);
}
public static void DrawWiredEllipsoid(Vector3 position, Quaternion rotation, float width, float height, Color ellipsoidColor, Color wireColor) {
DrawEllipsoid(position, rotation, width, height, ellipsoidColor);
DrawWireEllipsoid(position, rotation, width, height, wireColor);
}
public static void DrawCylinder(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawMesh(CylinderMesh, position, rotation, new Vector3(width, height/2f, width), color);
}
public static void DrawCylinder(Matrix4x4 matrix, float width, float height, Color color) {
DrawCylinder(matrix.GetPosition(), matrix.GetRotation(), width, height, color);
}
public static void DrawWireCylinder(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawWire(CylinderWire, position, rotation, new Vector3(width, height/2f, width), color);
}
public static void DrawWireCylinder(Matrix4x4 matrix, float width, float height, Color color) {
DrawWireCylinder(matrix.GetPosition(), matrix.GetRotation(), new Vector3(width, height/2f, width), color);
}
public static void DrawWiredCylinder(Vector3 position, Quaternion rotation, float width, float height, Color cylinderColor, Color wireColor) {
DrawCylinder(position, rotation, width, height, cylinderColor);
DrawWireCylinder(position, rotation, width, height, wireColor);
}
public static void DrawWiredCylinder(Matrix4x4 matrix, float width, float height, Color cylinderColor, Color wireColor) {
DrawWiredCylinder(matrix.GetPosition(), matrix.GetRotation(), width, height, cylinderColor, wireColor);
}
public static void DrawCylinder(Vector3 position, Quaternion rotation, Vector3 size, Color color) {
DrawMesh(CylinderMesh, position, rotation, new Vector3(size.x, size.y/2f, size.z), color);
}
public static void DrawWireCylinder(Vector3 position, Quaternion rotation, Vector3 size, Color color) {
DrawWire(CylinderWire, position, rotation, new Vector3(size.x, size.y/2f, size.z), color);
}
public static void DrawWiredCylinder(Vector3 position, Quaternion rotation, Vector3 size, Color cylinderColor, Color wireColor) {
DrawCylinder(position, rotation, size, cylinderColor);
DrawWireCylinder(position, rotation, size, wireColor);
}
public static void DrawCapsule(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawMesh(CapsuleMesh, position, rotation, new Vector3(width, height/2f, width), color);
}
public static void DrawWireCapsule(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawWire(CapsuleWire, position, rotation, new Vector3(width, height/2f, width), color);
}
public static void DrawWiredCapsule(Vector3 position, Quaternion rotation, float width, float height, Color capsuleColor, Color wireColor) {
DrawCapsule(position, rotation, width, height, capsuleColor);
DrawWireCapsule(position, rotation, width, height, wireColor);
}
public static void DrawCone(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawMesh(ConeMesh, position, rotation, new Vector3(width, height, width), color);
}
public static void DrawWireCone(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawWire(ConeWire, position, rotation, new Vector3(width, height, width), color);
}
public static void DrawWiredCone(Vector3 position, Quaternion rotation, float width, float height, Color coneColor, Color wireColor) {
DrawCone(position, rotation, width, height, coneColor);
DrawWireCone(position, rotation, width, height, wireColor);
}
public static void DrawPyramid(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawMesh(PyramidMesh, position, rotation, new Vector3(width, height, width), color);
}
public static void DrawWirePyramid(Vector3 position, Quaternion rotation, float width, float height, Color color) {
DrawWire(PyramidWire, position, rotation, new Vector3(width, height, width), color);
}
public static void DrawWiredPyramid(Vector3 position, Quaternion rotation, float width, float height, Color pyramidColor, Color wireColor) {
DrawPyramid(position, rotation, width, height, pyramidColor);
DrawWirePyramid(position, rotation, width, height, wireColor);
}
public static void DrawBone(Vector3 position, Quaternion rotation, float width, float length, Color color) {
DrawMesh(BoneMesh, position, rotation, new Vector3(width, width, length), color);
}
public static void DrawWireBone(Vector3 position, Quaternion rotation, float width, float length, Color color) {
DrawWire(BoneWire, position, rotation, new Vector3(width, width, length), color);
}
public static void DrawWiredBone(Vector3 position, Quaternion rotation, float width, float length, Color boneColor, Color wireColor) {
DrawBone(position, rotation, width, length, boneColor);
DrawWireBone(position, rotation, width, length, wireColor);
}
public static void DrawTranslateGizmo(Vector3 position, Quaternion rotation, float size) {
if(Return()) {return;}
DrawLine(position, position + 0.8f*size*(rotation*Vector3.right), Red);
DrawCone(position + 0.8f*size*(rotation*Vector3.right), rotation*Quaternion.Euler(0f, 0f, -90f), 0.15f*size, 0.2f*size, Red);
DrawLine(position, position + 0.8f*size*(rotation*Vector3.up), Green);
DrawCone(position + 0.8f*size*(rotation*Vector3.up), rotation*Quaternion.Euler(0f, 0f, 0f), 0.15f*size, 0.2f*size, Green);
DrawLine(position, position + 0.8f*size*(rotation*Vector3.forward), Blue);
DrawCone(position + 0.8f*size*(rotation*Vector3.forward), rotation*Quaternion.Euler(90f, 0f, 0f), 0.15f*size, 0.2f*size, Blue);
}
public static void DrawTranslateGizmo(Matrix4x4 matrix, float size) {
DrawTranslateGizmo(matrix.GetPosition(), matrix.GetRotation(), size);
}
public static void DrawRotateGizmo(Vector3 position, Quaternion rotation, float size) {
if(Return()) {return;}
SetProgram(PROGRAM.NONE);
DrawWireCircle(position, rotation*Quaternion.Euler(0f, 90f, 0f), 2f*size, Red);
SetProgram(PROGRAM.NONE);
DrawWireCircle(position, rotation*Quaternion.Euler(90f, 0f, 90f), 2f*size, Green);
SetProgram(PROGRAM.NONE);
DrawWireCircle(position, rotation*Quaternion.Euler(0f, 0f, 0f), 2f*size, Blue);
SetProgram(PROGRAM.NONE);
}
public static void DrawScaleGizmo(Vector3 position, Quaternion rotation, float size) {
if(Return()) {return;}
DrawLine(position, position + 0.85f*size*(rotation*Vector3.right), Red);
DrawCube(position + 0.925f*size*(rotation*Vector3.right), rotation, 0.15f, Red);
DrawLine(position, position + 0.85f*size*(rotation*Vector3.up), Green);
DrawCube(position + 0.925f*size*(rotation*Vector3.up), rotation, 0.15f, Green);
DrawLine(position, position + 0.85f*size*(rotation*Vector3.forward), Blue);
DrawCube(position + 0.925f*size*(rotation*Vector3.forward), rotation, 0.15f, Blue);
}
public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Vector3 scale, Color color) {
if(Return()) {return;}
SetProgram(PROGRAM.NONE);
MeshMaterial.color = color;
MeshMaterial.SetPass(0);
Graphics.DrawMeshNow(mesh, Matrix4x4.TRS(position, rotation, scale));
}
public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Color color) {
if(Return()) {return;}
SetProgram(PROGRAM.NONE);
MeshMaterial.color = color;
MeshMaterial.SetPass(0);
Graphics.DrawMeshNow(mesh, matrix);
}
//------------------------------------------------------------------------------------------
//GUI DRAWING FUNCTIONS
//------------------------------------------------------------------------------------------
public static bool DrawGUIButton(Rect rect, string text, Color backgroundColor, Color fontColor) {
GUI.backgroundColor = backgroundColor;
GUIStyle style = new GUIStyle(GUI.skin.button);
style.font = FontType;
style.normal.textColor = fontColor;
style.alignment = TextAnchor.MiddleCenter;
bool value = GUI.Button(rect, text);
GUI.backgroundColor = Color.black;
return value;
}
public static void DrawGUILabel(float x, float y, float size, string text, Color color) {
int fontSize = Mathf.RoundToInt(size*Screen.width);
if(fontSize == 0) {
return;
}
GUIStyle style = new GUIStyle();
style.font = FontType;
style.alignment = TextAnchor.UpperLeft;
style.fontSize = fontSize;
style.normal.textColor = color;
GUI.Label(new Rect(x*Screen.width, y*Screen.height, (1f-x)*Screen.width, fontSize), text, style);
}
public static void DrawGUILine(Vector2 start, Vector2 end, Color color) {
if(Camera == null) {return;}
if(Return()) {return;}
SetProgram(PROGRAM.LINES);
GL.Color(color);
start.x *= Screen.width;
start.y *= Screen.height;
end.x *= Screen.width;
end.y *= Screen.height;
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(start.x, start.y, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(end.x, end.y, Camera.nearClipPlane + GUIOffset)));
}
public static void DrawGUILine(Vector2 start, Vector2 end, float thickness, Color color) {
if(Camera == null) {return;}
if(Return()) {return;}
SetProgram(PROGRAM.QUADS);
GL.Color(color);
start.x *= Screen.width;
start.y *= Screen.height;
end.x *= Screen.width;
end.y *= Screen.height;
thickness *= Screen.width;
Vector3 p1 = new Vector3(start.x, start.y, Camera.nearClipPlane + GUIOffset);
Vector3 p2 = new Vector3(end.x, end.y, Camera.nearClipPlane + GUIOffset);
Vector3 dir = end-start;
Vector3 ortho = thickness/2f * (Quaternion.AngleAxis(90f, Vector3.forward) * dir).normalized;
GL.Vertex(Camera.ScreenToWorldPoint(p1-ortho));
GL.Vertex(Camera.ScreenToWorldPoint(p1+ortho));
GL.Vertex(Camera.ScreenToWorldPoint(p2+ortho));
GL.Vertex(Camera.ScreenToWorldPoint(p2-ortho));
}
public static void DrawGUILine(Vector2 start, Vector2 end, float startThickness, float endThickness, Color color) {
if(Camera == null) {return;}
if(Return()) {return;}
SetProgram(PROGRAM.QUADS);
GL.Color(color);
start.x *= Screen.width;
start.y *= Screen.height;
end.x *= Screen.width;
end.y *= Screen.height;
startThickness *= Screen.width;
endThickness *= Screen.width;
Vector3 p1 = new Vector3(start.x, start.y, Camera.nearClipPlane + GUIOffset);
Vector3 p2 = new Vector3(end.x, end.y, Camera.nearClipPlane + GUIOffset);
Vector3 dir = end-start;
Vector3 orthoStart = startThickness/2f * (Quaternion.AngleAxis(90f, Vector3.forward) * dir).normalized;
Vector3 orthoEnd = endThickness/2f * (Quaternion.AngleAxis(90f, Vector3.forward) * dir).normalized;
GL.Vertex(Camera.ScreenToWorldPoint(p1-orthoStart));
GL.Vertex(Camera.ScreenToWorldPoint(p1+orthoStart));
GL.Vertex(Camera.ScreenToWorldPoint(p2+orthoEnd));
GL.Vertex(Camera.ScreenToWorldPoint(p2-orthoEnd));
}
public static void DrawGUIRectangle(Vector2 center, Vector2 size, Color color) {
if(Camera == null) {return;}
if(Return()) {return;}
SetProgram(PROGRAM.QUADS);
GL.Color(color);
center.x *= Screen.width;
center.y *= Screen.height;
size.x *= Screen.width;
size.y *= Screen.height;
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x+size.x/2f, center.y-size.y/2f, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x-size.x/2f, center.y-size.y/2f, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x+-size.x/2f, center.y+size.y/2f, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x+size.x/2f, center.y+size.y/2f, Camera.nearClipPlane + GUIOffset)));
}
public static void DrawGUIRectangle(Vector2 center, Vector2 size, Color color, float borderWidth, Color borderColor) {
if(Camera == null) {return;}
if(Return()) {return;}
SetProgram(PROGRAM.QUADS);
GL.Color(color);
center.x *= Screen.width;
center.y *= Screen.height;
size.x *= Screen.width;
size.y *= Screen.height;
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x+size.x/2f, center.y-size.y/2f, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x-size.x/2f, center.y-size.y/2f, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x+-size.x/2f, center.y+size.y/2f, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x+size.x/2f, center.y+size.y/2f, Camera.nearClipPlane + GUIOffset)));
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
}
public static void DrawGUITriangle(Vector2 a, Vector2 b, Vector2 c, Color color) {
//TODO: There is some dependency here on the order of triangles, need to fix...
if(Camera == null) {return;}
if(Return()) {return;}
SetProgram(PROGRAM.TRIANGLES);
GL.Color(color);
a.x *= Screen.width;
a.y *= Screen.height;
b.x *= Screen.width;
b.y *= Screen.height;
c.x *= Screen.width;
c.y *= Screen.height;
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(a.x, a.y, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(b.x, b.y, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(c.x, c.y, Camera.nearClipPlane + GUIOffset)));
}
public static void DrawGUICircle(Vector2 center, float size, Color color) {
if(Camera == null) {return;}
if(Return()) {return;}
SetProgram(PROGRAM.TRIANGLES);
GL.Color(color);
center.x *= Screen.width;
center.y *= Screen.height;
for(int i=0; i<CircleWire.Length-1; i++) {
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x + size*CircleWire[i].x*Screen.width, center.y + size*CircleWire[i].y*Screen.width, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x, center.y, Camera.nearClipPlane + GUIOffset)));
GL.Vertex(Camera.ScreenToWorldPoint(new Vector3(center.x + size*CircleWire[i+1].x*Screen.width, center.y + size*CircleWire[i+1].y*Screen.width, Camera.nearClipPlane + GUIOffset)));
}
}
public static void DrawGUITexture(Vector2 center, float size, Texture texture, Color color) {
Vector2 area = size * Screen.width * new Vector2(texture.width, texture.height) / texture.width;
Vector2 pos = new Vector2(center.x*Screen.width - area.x/2f, center.y*Screen.height - area.y/2f);
GUI.DrawTexture(new Rect(pos.x, pos.y, area.x, area.y), texture, ScaleMode.StretchToFill, true, 1f, color, 0f, 100f);
}
public static void DrawGUIRectangleFrame(Vector2 center, Vector2 size, float thickness, Color color) {
DrawGUIRectangle(new Vector2(center.x - size.x/2f - thickness/2f, center.y), new Vector2(thickness, size.y), color);
DrawGUIRectangle(new Vector2(center.x + size.x/2f + thickness/2f, center.y), new Vector2(thickness, size.y), color);
DrawGUIRectangle(new Vector2(center.x, center.y - size.y/2f - thickness*Screen.width/Screen.height/2f), new Vector2(size.x + 2f*thickness, thickness*Screen.width/Screen.height), color);
DrawGUIRectangle(new Vector2(center.x, center.y + size.y/2f + thickness*Screen.width/Screen.height/2f), new Vector2(size.x + 2f*thickness, thickness*Screen.width/Screen.height), color);
}
//------------------------------------------------------------------------------------------
//PLOTTING FUNCTIONS
//------------------------------------------------------------------------------------------
public static void DrawGUIFunction(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, Color background, Color line) {
DrawGUIRectangle(center, size, background);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int i=0; i<values.Length-1; i++) {
if(values[i+1] >= yMin && values[i+1] <= yMax) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
line
);
}
}
}
public static void DrawGUIFunction(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, float thickness, Color background, Color line) {
DrawGUIRectangle(center, size, background);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int i=0; i<values.Length-1; i++) {
if(values[i+1] >= yMin && values[i+1] <= yMax) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
thickness,
line
);
}
}
}
public static void DrawGUIFunction(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, Color background, Color line, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int i=0; i<values.Length-1; i++) {
if(values[i+1] >= yMin && values[i+1] <= yMax) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
line
);
}
}
}
public static void DrawGUIFunction(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, float thickness, Color background, Color line, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int i=0; i<values.Length-1; i++) {
if(values[i+1] >= yMin && values[i+1] <= yMax) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values.Length-1)*size.x, y + Mathf.Clamp(Normalise(values[i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
thickness,
line
);
}
}
}
public static void DrawGUIFunctions(Vector2 center, Vector2 size, List<float[]> values, float yMin, float yMax, Color background, Color[] lines) {
DrawGUIRectangle(center, size, background);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int k=0; k<values.Count; k++) {
for(int i=0; i<values[k].Length-1; i++) {
bool prevValid = values[k][i] >= yMin && values[k][i] <= yMax;
bool nextValid = values[k][i+1] >= yMin && values[k][i+1] <= yMax;
if(prevValid || nextValid) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
lines[k]
);
}
}
}
}
public static void DrawGUIFunctions(Vector2 center, Vector2 size, List<float[]> values, float yMin, float yMax, float thickness, Color background, Color[] lines) {
DrawGUIRectangle(center, size, background);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int k=0; k<values.Count; k++) {
for(int i=0; i<values[k].Length-1; i++) {
bool prevValid = values[k][i] >= yMin && values[k][i] <= yMax;
bool nextValid = values[k][i+1] >= yMin && values[k][i+1] <= yMax;
if(prevValid || nextValid) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
thickness,
lines[k]
);
}
}
}
}
public static void DrawGUIFunctions(Vector2 center, Vector2 size, List<float[]> values, float yMin, float yMax, Color background, Color[] lines, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int k=0; k<values.Count; k++) {
for(int i=0; i<values[k].Length-1; i++) {
bool prevValid = values[k][i] >= yMin && values[k][i] <= yMax;
bool nextValid = values[k][i+1] >= yMin && values[k][i+1] <= yMax;
if(prevValid || nextValid) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
lines[k]
);
}
}
}
}
public static void DrawGUIFunctions(Vector2 center, Vector2 size, List<float[]> values, float yMin, float yMax, float thickness, Color background, Color[] lines, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
float x = center.x - size.x/2f;
float y = center.y - size.y/2f;
for(int k=0; k<values.Count; k++) {
for(int i=0; i<values[k].Length-1; i++) {
bool prevValid = values[k][i] >= yMin && values[k][i] <= yMax;
bool nextValid = values[k][i+1] >= yMin && values[k][i+1] <= yMax;
if(prevValid || nextValid) {
DrawGUILine(
new Vector2(x + (float)i/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
new Vector2(x + (float)(i+1)/(float)(values[k].Length-1)*size.x, y + Mathf.Clamp(Normalise(values[k][i+1], yMin, yMax, 0f, 1f), 0f, 1f)*size.y),
thickness,
lines[k]
);
}
}
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, Color background, Color color) {
DrawGUIRectangle(center, size, background);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + (float)i / (float)(values.Length-1) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, color);
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, Color background, Color[] colors) {
DrawGUIRectangle(center, size, background);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + (float)i / (float)(values.Length-1) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, colors[i]);
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, float thickness, Color background, Color color) {
DrawGUIRectangle(center, size, background);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + Normalise((float)i / (float)(values.Length-1), 0f, 1f, thickness/2f, 1f-thickness/2f) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, thickness, color);
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, float thickness, Color background, Color[] colors) {
DrawGUIRectangle(center, size, background);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + Normalise((float)i / (float)(values.Length-1), 0f, 1f, thickness/2f, 1f-thickness/2f) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, thickness, colors[i]);
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, Color background, Color color, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + (float)i / (float)(values.Length-1) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, color);
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, Color background, Color[] colors, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + (float)i / (float)(values.Length-1) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, colors[i]);
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, float thickness, Color background, Color color, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + Normalise((float)i / (float)(values.Length-1), 0f, 1f, thickness/2f, 1f-thickness/2f) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, thickness, color);
}
}
public static void DrawGUIBars(Vector2 center, Vector2 size, float[] values, float yMin, float yMax, float thickness, Color background, Color[] colors, float borderWidth, Color borderColor) {
DrawGUIRectangle(center, size, background);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
for(int i=0; i<values.Length; i++) {
float x = center.x - size.x/2f + Normalise((float)i / (float)(values.Length-1), 0f, 1f, thickness/2f, 1f-thickness/2f) * size.x;
float y = center.y - size.y/2f;
Vector3 pivot = new Vector2(x, y + Normalise(0f, yMin, yMax, 0f, 1f)*size.y);
Vector2 tip = new Vector2(x, y + Mathf.Clamp(Normalise(values[i], yMin, yMax, 0f, 1f), 0f, 1f)*size.y);
DrawGUILine(pivot, tip, thickness, colors[i]);
}
}
public static void DrawGUIHorizontalBar(Vector2 center, Vector2 size, Color backgroundColor, float borderWidth, Color borderColor, float fillAmount, Color fillColor) {
fillAmount = Mathf.Clamp(fillAmount, 0f, 1f);
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
DrawGUIRectangle(center, size, backgroundColor);
DrawGUIRectangle(new Vector2(center.x - size.x/2f + fillAmount * size.x/2f, center.y), new Vector2(fillAmount * size.x, size.y), fillColor);
}
public static void DrawGUIHorizontalPivot(Vector2 center, Vector2 size, Color backgroundColor, float borderWidth, Color borderColor, float pivot, float pivotWidth, Color pivotColor) {
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
DrawGUIRectangle(center, size, backgroundColor);
DrawGUIRectangle(new Vector2(center.x - size.x/2f + Normalise(pivot * size.x, 0f, size.x, pivotWidth/2f, size.x - pivotWidth/2f), center.y), new Vector2(pivotWidth, size.y), pivotColor);
}
public static void DrawGUIVerticalPivot(Vector2 center, Vector2 size, Color backgroundColor, float borderWidth, Color borderColor, float pivot, float pivotHeight, Color pivotColor) {
DrawGUIRectangleFrame(center, size, borderWidth, borderColor);
DrawGUIRectangle(center, size, backgroundColor);
DrawGUIRectangle(new Vector2(center.x, center.y - size.y/2f + Normalise(pivot * size.y, 0f, size.y, pivotHeight/2f, size.y - pivotHeight/2f)), new Vector2(size.x, pivotHeight), pivotColor);
}
public static void DrawGUICircularPivot(Vector2 center, float size, Color backgroundColor, float degrees, float length, Color pivotColor) {
degrees = Mathf.Repeat(degrees, 360f);
DrawGUICircle(center, size, backgroundColor);
Vector2 end = length * size * (Quaternion.AngleAxis(-degrees, Vector3.forward) * Vector2.up);
end.x = end.x / Screen.width * Screen.height;
DrawGUILine(center, center + end, Mathf.Abs(length*size/5f), 0f, pivotColor);
}
public static void DrawGUICircularPoint(Vector2 center, float size, Vector2 position, Color backgroundColor, Color pointColor) {
DrawGUICircle(center, size, backgroundColor);
Vector2 point = size * position;
point.x = point.x / Screen.width * Screen.height;
DrawGUICircle(center + point, size/10f, pointColor);
}
public static void DrawGUIGreyscaleImage(Vector2 center, Vector2 size, int w, int h, float[] intensities, bool normalise=false) {
if(w*h != intensities.Length) {
Debug.Log("Resolution does not match number of intensities.");
return;
}
if(normalise) {
float min = intensities.Min();
float max = intensities.Max();
float patchWidth = size.x / (float)w;
float patchHeight = size.y / (float)h;
for(int x=0; x<w; x++) {
for(int y=0; y<h; y++) {
UltiDraw.DrawGUIRectangle(
center - size/2f + new Vector2(Normalise(x, 0, w-1, patchWidth/2f, size.x-patchWidth/2f), Normalise(y, 0, h-1, patchHeight/2f, size.y-patchHeight/2f)), //new Vector2((float)x*size.x, (float)y*size.y) / (float)(Resolution-1),
new Vector2(patchWidth, patchHeight),
Color.Lerp(Color.black, Color.white, Normalise(intensities[y*w + x], min, max, 0f, 1f))
);
}
}
} else {
float patchWidth = size.x / (float)w;
float patchHeight = size.y / (float)h;
for(int x=0; x<w; x++) {
for(int y=0; y<h; y++) {
UltiDraw.DrawGUIRectangle(
center - size/2f + new Vector2(Normalise(x, 0, w-1, patchWidth/2f, size.x-patchWidth/2f), Normalise(y, 0, h-1, patchHeight/2f, size.y-patchHeight/2f)), //new Vector2((float)x*size.x, (float)y*size.y) / (float)(Resolution-1),
new Vector2(patchWidth, patchHeight),
Color.Lerp(Color.black, Color.white, intensities[y*w + x])
);
}
}
}
}
public static void DrawGUIColorImage(Vector2 center, Vector2 size, int w, int h, Color[] pixels) {
if(w*h != pixels.Length) {
Debug.Log("Resolution does not match number of color pixels.");
return;
}
float patchWidth = size.x / (float)w;
float patchHeight = size.y / (float)h;
for(int x=0; x<w; x++) {
for(int y=0; y<h; y++) {
UltiDraw.DrawGUIRectangle(
center - size/2f + new Vector2(Normalise(x, 0, w-1, patchWidth/2f, size.x-patchWidth/2f), Normalise(y, 0, h-1, patchHeight/2f, size.y-patchHeight/2f)), //new Vector2((float)x*size.x, (float)y*size.y) / (float)(Resolution-1),
new Vector2(patchWidth, patchHeight),
pixels[y*w + x]
);
}
}
}
//------------------------------------------------------------------------------------------
//UTILITY FUNCTIONS
//------------------------------------------------------------------------------------------
public static Color Transparent(this Color color, float opacity) {
return new Color(color.r, color.g, color.b, Mathf.Clamp(opacity, 0f, 1f));
}
public static Color Lighten(this Color color, float amount) {
return Color.Lerp(color, Color.white, amount);
}
public static Color Darken(this Color color, float amount) {
return Color.Lerp(color, Color.black, amount);
}
public static Color GetRainbowColor(int index, int number) {
float frequency = 5f/number;
return new Color(
Normalise(Mathf.Sin(frequency*index + 0f) * (127f) + 128f, 0f, 255f, 0f, 1f),
Normalise(Mathf.Sin(frequency*index + 2f) * (127f) + 128f, 0f, 255f, 0f, 1f),
Normalise(Mathf.Sin(frequency*index + 4f) * (127f) + 128f, 0f, 255f, 0f, 1f),
1f);
}
public static Color[] GetRainbowColors(int number) {
Color[] colors = new Color[number];
for(int i=0; i<number; i++) {
colors[i] = GetRainbowColor(i, number);
}
return colors;
}
public static Color GetRandomColor() {
return new Color(Random.value, Random.value, Random.value, 1f);
}
public static Rect GetGUIRect(float x, float y, float w, float h) {
return new Rect(x*Screen.width, y*Screen.height, w*Screen.width, h*Screen.height);
}
public static float Normalise(float value, float valueMin, float valueMax, float resultMin, float resultMax) {
if(valueMax-valueMin != 0f) {
return (value-valueMin)/(valueMax-valueMin)*(resultMax-resultMin) + resultMin;
} else {
//Not possible to normalise input value.
return value;
}
}
//------------------------------------------------------------------------------------------
//INTERNAL FUNCTIONS
//------------------------------------------------------------------------------------------
private static bool Return() {
if(!Active) {
Debug.Log("Drawing is not active. Call 'Begin()' first.");
}
return !Active;
}
static void Initialise() {
if(Initialised != null) {
return;
}
Resources.UnloadUnusedAssets();
FontType = (Font)Resources.Load("Fonts/Coolvetica");
GLMaterial = new Material(Shader.Find("Hidden/Internal-Colored"));
GLMaterial.hideFlags = HideFlags.HideAndDontSave;
GLMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
GLMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
GLMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Back);
GLMaterial.SetInt("_ZWrite", 1);
GLMaterial.SetInt("_ZTest", (int)UnityEngine.Rendering.CompareFunction.Always);
MeshMaterial = new Material(Shader.Find("UltiDraw"));
MeshMaterial.hideFlags = HideFlags.HideAndDontSave;
MeshMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Back);
MeshMaterial.SetInt("_ZWrite", 1);
MeshMaterial.SetInt("_ZTest", (int)UnityEngine.Rendering.CompareFunction.Always);
MeshMaterial.SetFloat("_Power", 0.25f);
//Meshes
CircleMesh = CreateCircleMesh(Resolution);
QuadMesh = GetPrimitiveMesh(PrimitiveType.Quad);
CubeMesh = GetPrimitiveMesh(PrimitiveType.Cube);
SphereMesh = GetPrimitiveMesh(PrimitiveType.Sphere);
CylinderMesh = GetPrimitiveMesh(PrimitiveType.Cylinder);
CapsuleMesh = GetPrimitiveMesh(PrimitiveType.Capsule);
ConeMesh = CreateConeMesh(Resolution);
PyramidMesh = CreatePyramidMesh();
BoneMesh = CreateBoneMesh();
//
//Wires
CircleWire = CreateCircleWire(Resolution);
QuadWire = CreateQuadWire();
CubeWire = CreateCubeWire();
SphereWire = CreateSphereWire(Resolution);
CylinderWire = CreateCylinderWire(Resolution);
CapsuleWire = CreateCapsuleWire(Resolution);
ConeWire = CreateConeWire(Resolution);
PyramidWire = CreatePyramidWire();
BoneWire = CreateBoneWire();
//
Initialised = new Mesh();
}
private static void SetProgram(PROGRAM program) {
if(Program != program) {
Program = program;
GL.End();
if(Program != PROGRAM.NONE) {
GLMaterial.SetPass(0);
switch(Program) {
case PROGRAM.LINES:
GL.Begin(GL.LINES);
break;
case PROGRAM.TRIANGLES:
GL.Begin(GL.TRIANGLES);
break;
case PROGRAM.TRIANGLE_STRIP:
GL.Begin(GL.TRIANGLE_STRIP);
break;
case PROGRAM.QUADS:
GL.Begin(GL.QUADS);
break;
}
}
}
}
private static void DrawWire(Vector3[] points, Vector3 position, Quaternion rotation, Vector3 scale, Color color) {
if(Return()) {return;};
SetProgram(PROGRAM.LINES);
GL.Color(color);
for(int i=0; i<points.Length; i+=2) {
GL.Vertex(position + rotation * Vector3.Scale(scale, points[i]));
GL.Vertex(position + rotation * Vector3.Scale(scale, points[i+1]));
}
}
private static void DrawWire(Vector3[] points, Matrix4x4 matrix, Color color) {
DrawWire(points, matrix.GetPosition(), matrix.GetRotation(), matrix.GetScale(), color);
}
private static Camera GetCamera() {
#if UNITY_EDITOR
Camera[] cameras = SceneView.GetAllSceneCameras();
if(ArrayExtensions.Contains(ref cameras, Camera.current)) {
return null;
}
#endif
return Camera.current;
}
private static Mesh GetPrimitiveMesh(PrimitiveType type) {
GameObject gameObject = GameObject.CreatePrimitive(type);
gameObject.hideFlags = HideFlags.HideInHierarchy;
gameObject.GetComponent<MeshRenderer>().enabled = false;
Mesh mesh = gameObject.GetComponent<MeshFilter>().sharedMesh;
if(Application.isPlaying) {
GameObject.Destroy(gameObject);
} else {
GameObject.DestroyImmediate(gameObject);
}
return mesh;
}
private static Mesh CreateCircleMesh(int resolution) {
List<Vector3> vertices = new List<Vector3>();
List<int> triangles = new List<int>();
float step = 360.0f / (float)resolution;
Quaternion quaternion = Quaternion.Euler(0f, 0f, step);
vertices.Add(new Vector3(0f, 0f, 0f));
vertices.Add(new Vector3(0f, 0.5f, 0f));
vertices.Add(quaternion * vertices[1]);
triangles.Add(1);
triangles.Add(0);
triangles.Add(2);
for(int i=0; i<resolution-1; i++) {
triangles.Add(vertices.Count - 1);
triangles.Add(0);
triangles.Add(vertices.Count);
vertices.Add(quaternion * vertices[vertices.Count - 1]);
}
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
return mesh;
}
private static Mesh CreateConeMesh(int resolution) {
List<Vector3> vertices = new List<Vector3>();
List<int> triangles = new List<int>();
float step = 360.0f / (float)resolution;
Quaternion quaternion = Quaternion.Euler(0f, step, 0f);
vertices.Add(new Vector3(0f, 1f, 0f));
vertices.Add(new Vector3(0f, 0f, 0f));
vertices.Add(new Vector3(0f, 0f, 0.5f));
vertices.Add(quaternion * vertices[2]);
triangles.Add(2);
triangles.Add(1);
triangles.Add(3);
triangles.Add(2);
triangles.Add(3);
triangles.Add(0);
for(int i=0; i<resolution-1; i++) {
triangles.Add(vertices.Count-1);
triangles.Add(1);
triangles.Add(vertices.Count);
triangles.Add(vertices.Count-1);
triangles.Add(vertices.Count);
triangles.Add(0);
vertices.Add(quaternion * vertices[vertices.Count-1]);
}
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
return mesh;
}
private static Mesh CreatePyramidMesh() {
List<Vector3> vertices = new List<Vector3>();
List<int> triangles = new List<int>();
vertices.Add(new Vector3(-0.5f, 0f, -0.5f));
vertices.Add(new Vector3(0.5f, 0f, -0.5f));
vertices.Add(new Vector3(0.5f, 0f, 0.5f));
vertices.Add(new Vector3(-0.5f, 0f, -0.5f));
vertices.Add(new Vector3(0.5f, 0f, 0.5f));
vertices.Add(new Vector3(-0.5f, 0f, 0.5f));
vertices.Add(new Vector3(-0.5f, 0f, -0.5f));
vertices.Add(new Vector3(0f, 1f, 0f));
vertices.Add(new Vector3(0.5f, 0f, -0.5f));
vertices.Add(new Vector3(0.5f, 0f, -0.5f));
vertices.Add(new Vector3(0f, 1f, 0f));
vertices.Add(new Vector3(0.5f, 0f, 0.5f));
vertices.Add(new Vector3(0.5f, 0f, 0.5f));
vertices.Add(new Vector3(0f, 1f, 0f));
vertices.Add(new Vector3(-0.5f, 0f, 0.5f));
vertices.Add(new Vector3(-0.5f, 0f, 0.5f));
vertices.Add(new Vector3(0f, 1f, 0f));
vertices.Add(new Vector3(-0.5f, 0f, -0.5f));
for(int i=0; i<18; i++) {
triangles.Add(i);
}
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
return mesh;
}
private static Mesh CreateBoneMesh() {
float size = 1f/7f;
List<Vector3> vertices = new List<Vector3>();
List<int> triangles = new List<int>();
vertices.Add(new Vector3(-size, -size, 0.200f));
vertices.Add(new Vector3(-size, size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 0.000f));
vertices.Add(new Vector3(size, size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 1.000f));
vertices.Add(new Vector3(size, -size, 0.200f));
vertices.Add(new Vector3(-size, size, 0.200f));
vertices.Add(new Vector3(-size, -size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 1.000f));
vertices.Add(new Vector3(size, -size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 1.000f));
vertices.Add(new Vector3(-size, -size, 0.200f));
vertices.Add(new Vector3(size, size, 0.200f));
vertices.Add(new Vector3(-size, size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 1.000f));
vertices.Add(new Vector3(size, size, 0.200f));
vertices.Add(new Vector3(size, -size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 0.000f));
vertices.Add(new Vector3(size, size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 0.000f));
vertices.Add(new Vector3(-size, size, 0.200f));
vertices.Add(new Vector3(size, -size, 0.200f));
vertices.Add(new Vector3(-size, -size, 0.200f));
vertices.Add(new Vector3(0.000f, 0.000f, 0.000f));
for(int i=0; i<24; i++) {
triangles.Add(i);
}
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
return mesh;
}
private static Vector3[] CreateCircleWire(int resolution) {
List<Vector3> points = new List<Vector3>();
float step = 360.0f / (float)resolution;
for(int i=0; i<resolution; i++) {
points.Add(Quaternion.Euler(0f, 0f, i*step) * new Vector3(0f, 0.5f, 0f));
points.Add(Quaternion.Euler(0f, 0f, (i+1)*step) * new Vector3(0f, 0.5f, 0f));
}
return points.ToArray();
}
private static Vector3[] CreateQuadWire() {
List<Vector3> points = new List<Vector3>();
points.Add(new Vector3(-0.5f, -0.5f, 0f));
points.Add(new Vector3(0.5f, -0.5f, 0f));
points.Add(new Vector3(0.5f, -0.5f, 0f));
points.Add(new Vector3(0.5f, 0.5f, 0f));
points.Add(new Vector3(0.5f, 0.5f, 0f));
points.Add(new Vector3(-0.5f, 0.5f, 0f));
points.Add(new Vector3(-0.5f, 0.5f, 0f));
points.Add(new Vector3(-0.5f, -0.5f, 0f));
return points.ToArray();
}
private static Vector3[] CreateCubeWire() {
float size = 1f;
Vector3 A = new Vector3(-size/2f, -size/2f, -size/2f);
Vector3 B = new Vector3(size/2f, -size/2f, -size/2f);
Vector3 C = new Vector3(-size/2f, -size/2f, size/2f);
Vector3 D = new Vector3(size/2f, -size/2f, size/2f);
Vector3 p1 = A; Vector3 p2 = B;
Vector3 p3 = C; Vector3 p4 = D;
Vector3 p5 = -D; Vector3 p6 = -C;
Vector3 p7 = -B; Vector3 p8 = -A;
List<Vector3> points = new List<Vector3>();
points.Add(p1); points.Add(p2);
points.Add(p2); points.Add(p4);
points.Add(p4); points.Add(p3);
points.Add(p3); points.Add(p1);
points.Add(p5); points.Add(p6);
points.Add(p6); points.Add(p8);
points.Add(p5); points.Add(p7);
points.Add(p7); points.Add(p8);
points.Add(p1); points.Add(p5);
points.Add(p2); points.Add(p6);
points.Add(p3); points.Add(p7);
points.Add(p4); points.Add(p8);
return points.ToArray();
}
private static Vector3[] CreateSphereWire(int resolution) {
List<Vector3> points = new List<Vector3>();
float step = 360.0f / (float)resolution;
for(int i=0; i<resolution; i++) {
points.Add(Quaternion.Euler(0f, 0f, i*step) * new Vector3(0f, 0.5f, 0f));
points.Add(Quaternion.Euler(0f, 0f, (i+1)*step) * new Vector3(0f, 0.5f, 0f));
}
for(int i=0; i<resolution; i++) {
points.Add(Quaternion.Euler(0f, i*step, 0f) * new Vector3(0f, 0f, 0.5f));
points.Add(Quaternion.Euler(0f, (i+1)*step, 0f) * new Vector3(0f, 0f, 0.5f));
}
for(int i=0; i<resolution; i++) {
points.Add(Quaternion.Euler(i*step, 0f, i*step) * new Vector3(0f, 0f, 0.5f));
points.Add(Quaternion.Euler((i+1)*step, 0f, (i+1)*step) * new Vector3(0f, 0f, 0.5f));
}
return points.ToArray();
}
private static Vector3[] CreateCylinderWire(int resolution) {
List<Vector3> points = new List<Vector3>();
float step = 360.0f / (float)resolution;
for(int i=0; i<resolution; i++) {
points.Add(Quaternion.Euler(0f, i*step, 0f) * new Vector3(0f, 0f, 0.5f) + new Vector3(0f, 1f, 0f));
points.Add(Quaternion.Euler(0f, (i+1)*step, 0f) * new Vector3(0f, 0f, 0.5f) + new Vector3(0f, 1f, 0f));
}
for(int i=0; i<resolution; i++) {
points.Add(Quaternion.Euler(0f, i*step, 0f) * new Vector3(0f, 0f, 0.5f) - new Vector3(0f, 1f, 0f));
points.Add(Quaternion.Euler(0f, (i+1)*step, 0f) * new Vector3(0f, 0f, 0.5f) - new Vector3(0f, 1f, 0f));
}
points.Add(new Vector3(0f, -1f, -0.5f));
points.Add(new Vector3(0f, 1f, -0.5f));
points.Add(new Vector3(0f, -1f, 0.5f));
points.Add(new Vector3(0f, 1f, 0.5f));
points.Add(new Vector3(-0.5f, -1f, 0f));
points.Add(new Vector3(-0.5f, 1f, 0f));
points.Add(new Vector3(0.5f, -1f, 0f));
points.Add(new Vector3(0.5f, 1f, 0));
return points.ToArray();
}
private static Vector3[] CreateCapsuleWire(int resolution) {
List<Vector3> points = new List<Vector3>();
float step = 360.0f / (float)resolution;
for(int i=-resolution/4-1; i<=resolution/4; i++) {
points.Add(Quaternion.Euler(0f, 0f, i*step) * new Vector3(0f, 0.5f, 0f) + new Vector3(0f, 0.5f, 0f));
points.Add(Quaternion.Euler(0f, 0f, (i+1)*step) * new Vector3(0f, 0.5f, 0f) + new Vector3(0f, 0.5f, 0f));
}
for(int i=resolution/2; i<resolution; i++) {
points.Add(Quaternion.Euler(i*step, 0f, i*step) * new Vector3(0f, 0f, 0.5f) + new Vector3(0f, 0.5f, 0f));
points.Add(Quaternion.Euler((i+1)*step, 0f, (i+1)*step) * new Vector3(0f, 0f, 0.5f) + new Vector3(0f, 0.5f, 0f));
}
for(int i=-resolution/4-1; i<=resolution/4; i++) {
points.Add(Quaternion.Euler(0f, 0f, i*step) * new Vector3(0f, -0.5f, 0f) + new Vector3(0f, -0.5f, 0f));
points.Add(Quaternion.Euler(0f, 0f, (i+1)*step) * new Vector3(0f, -0.5f, 0f) + new Vector3(0f, -0.5f, 0f));
}
for(int i=resolution/2; i<resolution; i++) {
points.Add(Quaternion.Euler(i*step, 0f, i*step) * new Vector3(0f, 0f, -0.5f) + new Vector3(0f, -0.5f, 0f));
points.Add(Quaternion.Euler((i+1)*step, 0f, (i+1)*step) * new Vector3(0f, 0f, -0.5f) + new Vector3(0f, -0.5f, 0f));
}
points.Add(new Vector3(0f, -0.5f, -0.5f));
points.Add(new Vector3(0f, 0.5f, -0.5f));
points.Add(new Vector3(0f, -0.5f, 0.5f));
points.Add(new Vector3(0f, 0.5f, 0.5f));
points.Add(new Vector3(-0.5f, -0.5f, 0f));
points.Add(new Vector3(-0.5f, 0.5f, 0f));
points.Add(new Vector3(0.5f, -0.5f, 0f));
points.Add(new Vector3(0.5f, 0.5f, 0));
return points.ToArray();
}
private static Vector3[] CreateConeWire(int resolution) {
List<Vector3> points = new List<Vector3>();
float step = 360.0f / (float)resolution;
for(int i=0; i<resolution; i++) {
points.Add(Quaternion.Euler(0f, i*step, 0f) * new Vector3(0f, 0f, 0.5f));
points.Add(Quaternion.Euler(0f, (i+1)*step, 0f) * new Vector3(0f, 0f, 0.5f));
}
points.Add(new Vector3(-0.5f, 0f, 0f));
points.Add(new Vector3(0f, 1f, 0f));
points.Add(new Vector3(0.5f, 0f, 0f));
points.Add(new Vector3(0f, 1f, 0f));
points.Add(new Vector3(0f, 0f, -0.5f));
points.Add(new Vector3(0f, 1f, 0f));
points.Add(new Vector3(0f, 0f, 0.5f));
points.Add(new Vector3(0f, 1f, 0f));
return points.ToArray();
}
private static Vector3[] CreatePyramidWire() {
List<Vector3> points = new List<Vector3>();
points.Add(new Vector3(-0.5f, 0f, -0.5f));
points.Add(new Vector3(0.5f, 0f, -0.5f));
points.Add(new Vector3(0.5f, 0f, -0.5f));
points.Add(new Vector3(0.5f, 0f, 0.5f));
points.Add(new Vector3(0.5f, 0f, 0.5f));
points.Add(new Vector3(-0.5f, 0f, 0.5f));
points.Add(new Vector3(-0.5f, 0f, 0.5f));
points.Add(new Vector3(-0.5f, 0f, -0.5f));
points.Add(new Vector3(-0.5f, 0f, -0.5f));
points.Add(new Vector3(0f, 1f, 0f));
points.Add(new Vector3(0.5f, 0f, -0.5f));
points.Add(new Vector3(0f, 1f, 0f));
points.Add(new Vector3(-0.5f, 0f, 0.5f));
points.Add(new Vector3(0f, 1f, 0f));
points.Add(new Vector3(0.5f, 0f, 0.5f));
points.Add(new Vector3(0f, 1f, 0f));
return points.ToArray();
}
private static Vector3[] CreateBoneWire() {
float size = 1f/7f;
List<Vector3> points = new List<Vector3>();
points.Add(new Vector3(0.000f, 0.000f, 0.000f));
points.Add(new Vector3(-size, -size, 0.200f));
points.Add(new Vector3(0.000f, 0.000f, 0.000f));
points.Add(new Vector3(size, -size, 0.200f));
points.Add(new Vector3(0.000f, 0.000f, 0.000f));
points.Add(new Vector3(-size, size, 0.200f));
points.Add(new Vector3(0.000f, 0.000f, 0.000f));
points.Add(new Vector3(size, size, 0.200f));
points.Add(new Vector3(-size, -size, 0.200f));
points.Add(new Vector3(0.000f, 0.000f, 1.000f));
points.Add(new Vector3(size, -size, 0.200f));
points.Add(new Vector3(0.000f, 0.000f, 1.000f));
points.Add(new Vector3(-size, size, 0.200f));
points.Add(new Vector3(0.000f, 0.000f, 1.000f));
points.Add(new Vector3(size, size, 0.200f));
points.Add(new Vector3(0.000f, 0.000f, 1.000f));
points.Add(new Vector3(-size, -size, 0.200f));
points.Add(new Vector3(size, -size, 0.200f));
points.Add(new Vector3(size, -size, 0.200f));
points.Add(new Vector3(size, size, 0.200f));
points.Add(new Vector3(size, size, 0.200f));
points.Add(new Vector3(-size, size, 0.200f));
points.Add(new Vector3(-size, size, 0.200f));
points.Add(new Vector3(-size, -size, 0.200f));
return points.ToArray();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using StarBastardCore.Website.Code.Game.Gameworld.Geography;
namespace StarBastardCore.Website.Code.Game.Gameplay.GameGeneration
{
public class SystemGenerator
{
public List<PlanetarySystem> Generate()
{
var system = new List<PlanetarySystem>();
system.AddRange(GenerateSystemForOnePlayer(1));
system.AddRange(GenerateSystemForOnePlayer(2));
return system;
}
private IEnumerable<PlanetarySystem> GenerateSystemForOnePlayer(int playerNumber)
{
var systems = new PlanetarySystem[GameDimensions.SectorSize];
var points = generateScoresForSetOfPlanets();
var random = new Random();
for (var i = 0; i != GameDimensions.SectorSize; i++)
{
var name = NamesRepository.RandomName();
var oneSystem = new PlanetarySystem(name, playerNumber + "_" + (i + 1), points[i], Player.None);
systems[i] = oneSystem;
}
return systems;
}
private List<int> generateScoresForSetOfPlanets()
{
var points = new int[GameDimensions.SectorSize];
var totalPoints = 100;
var random = new Random();
while (totalPoints > 0)
{
// lets make sure we get allocated
//generate planet points
for (var p = 0; p != GameDimensions.SectorSize; p++)
{
var randomBetweenOneAndTen = random.Next(1, 10);
if (randomBetweenOneAndTen > totalPoints)
{
randomBetweenOneAndTen = totalPoints;
}
totalPoints = totalPoints - randomBetweenOneAndTen;
points[p] = randomBetweenOneAndTen;
}
}
Shuffle(points);
// ensure the start position is workable.
if (points[GameDimensions.StartingPlanetarySystem] == 0)
{
for (var i = 0; i < points.Length; i++)
{
if (points[i] > 5)
{
points[18] = points[i];
points[i] = 0;
}
}
}
return points.ToList();
}
private static void Shuffle<T>(IList<T> array)
{
var random = new Random();
for (var i = array.Count; i > 1; i--)
{
var j = random.Next(i);
var tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace TicketSystem.Models
{
public class Ticket
{
//
public int ticketID { get; set; }
public string category { get; set; }
[DataType(DataType.Date)]
public DateTime createdDate { get; set; }
public string description { get; set; }
public string status { get; set; }
}
}
|
using Alabo.Framework.Core.WebApis.Controller;
using Alabo.Framework.Core.WebApis.Filter;
using Alabo.Framework.Tasks.Schedules.Domain.Entities;
using Alabo.Framework.Tasks.Schedules.Domain.Services;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
namespace Alabo.Framework.Tasks.Schedules.Controllers {
[ApiExceptionFilter]
[Route("Api/Schedule/[action]")]
public class ApiScheduleController : ApiBaseController<Schedule, ObjectId> {
public ApiScheduleController() {
BaseService = Resolve<IScheduleService>();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using ExcelApp = Microsoft.Office.Interop.Excel;
namespace Oracle.Admin
{
public partial class FrmAdminSatislar : Form
{
OracleBaglantisi conn = new OracleBaglantisi();
void SatisListele()
{
try
{
OracleCommand cmd = new OracleCommand("select S.SATISID,S.URUNID,S.MUSTERIID,M.MUSTERIADI,M.MUSTERISOYADI,U.URUNMARKA,U.URUNADET,U.SATISFIYATI,S.TARIH from TBL_SATISLAR S INNER JOIN TBL_URUNLER U ON (S.URUNID= U.URUNID) INNER JOIN TBL_MUSTERILER M ON(S.MUSTERIID=M.MUSTERIID)", conn.baglanti());
OracleDataReader reader = cmd.ExecuteReader();
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Reset()
{
txtSatisID.Text = null;
txtMusteriID.Text = null;
txtUrunID.Text = null;
txtTarih.Text = null;
}
public FrmAdminSatislar()
{
InitializeComponent();
}
private void FrmAdminSatislar_Load(object sender, EventArgs e)
{
SatisListele();
}
private void btnSil_Click(object sender, EventArgs e)
{
try
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn.baglanti();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_satis_sil";
cmd.Parameters.Add("v_satis_id", OracleDbType.Varchar2).Value = txtSatisID.Text;
cmd.ExecuteNonQuery();
conn.baglanti().Close();
SatisListele();
Reset();
MessageBox.Show("Müşteri Silindi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnGuncelle_Click(object sender, EventArgs e)
{
try
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn.baglanti();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_satis_guncelle";
cmd.Parameters.Add("v_musteri_id", OracleDbType.Varchar2).Value = txtMusteriID.Text;
cmd.Parameters.Add("v_urun_id", OracleDbType.Varchar2).Value = txtUrunID.Text;
cmd.Parameters.Add("v_tarih", OracleDbType.Varchar2).Value = txtTarih.Text;
cmd.Parameters.Add("v_satis_id", OracleDbType.Varchar2).Value = txtSatisID.Text;
cmd.ExecuteNonQuery();
conn.baglanti().Close();
SatisListele();
Reset();
MessageBox.Show("Müşteri Güncellendi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnEkle_Click(object sender, EventArgs e)
{
try
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn.baglanti();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_satis_kaydet";
cmd.Parameters.Add("v_musteri_id", OracleDbType.Varchar2).Value = txtMusteriID.Text;
cmd.Parameters.Add("v_urun_id", OracleDbType.Varchar2).Value = txtUrunID.Text;
cmd.Parameters.Add("v_tarih", OracleDbType.Varchar2).Value = txtTarih.Text;
cmd.ExecuteNonQuery();
conn.baglanti().Close();
SatisListele();
Reset();
MessageBox.Show("Satis Eklendi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnTemizle_Click(object sender, EventArgs e)
{
SatisListele();
Reset();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int select = dataGridView1.SelectedCells[0].RowIndex;
txtSatisID.Text = dataGridView1.Rows[select].Cells[0].Value.ToString();
txtMusteriID.Text = dataGridView1.Rows[select].Cells[2].Value.ToString();
txtUrunID.Text = dataGridView1.Rows[select].Cells[1].Value.ToString();
txtTarih.Text = dataGridView1.Rows[select].Cells[8].Value.ToString();
}
private void btnImport_Click(object sender, EventArgs e)
{
try
{
btnExport.Visible = true;
string DosyaYolu;
string DosyaAdi;
System.Data.DataTable dt;
OpenFileDialog file = new OpenFileDialog();
file.Filter = "Excel Dosyası | *.xls; *.xlsx; *.xlsm";
if (file.ShowDialog() == DialogResult.OK)
{
DosyaYolu = file.FileName;// seçilen dosyanın tüm yolunu verir
DosyaAdi = file.SafeFileName;// seçilen dosyanın adını verir.
ExcelApp.Application excelApp = new ExcelApp.Application();
if (excelApp == null)
{ //Excel Yüklümü Kontrolü Yapılmaktadır.
MessageBox.Show("Excel yüklü değil.");
return;
}
//Excel Dosyası Açılıyor.
ExcelApp.Workbook excelBook = excelApp.Workbooks.Open(DosyaYolu);
//Excel Dosyasının Sayfası Seçilir.
ExcelApp._Worksheet excelSheet = excelBook.Sheets[1];
//Excel Dosyasının ne kadar satır ve sütun kaplıyorsa tüm alanları alır.
ExcelApp.Range excelRange = excelSheet.UsedRange;
satirSayisi = excelRange.Rows.Count; //Sayfanın satır sayısını alır.
sutunSayisi = excelRange.Columns.Count;//Sayfanın sütun sayısını alır.
dt = ToDataTable(excelRange, satirSayisi, sutunSayisi);
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
//Okuduktan Sonra Excel Uygulamasını Kapatıyoruz.
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
else
{
MessageBox.Show("Dosya Seçilemedi.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public System.Data.DataTable ToDataTable(ExcelApp.Range range, int rows, int cols)
{
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= rows; i++)
{
if (i == 1)
{ // ilk satırı Sutun Adları olarak kullanıldığından
// bunları Sutün Adları Olarak Kaydediyoruz.
for (int j = 1; j <= cols; j++)
{
//Sütunların içeriği boş mu kontrolü yapılmaktadır.
if (range.Cells[i, j] != null && range.Cells[i, j].Value2 != null)
table.Columns.Add(range.Cells[i, j].Value2.ToString());
else //Boş olduğunda Kaçınsı Sutünsa Adı veriliyor.
table.Columns.Add(j.ToString() + ".Sütun");
}
continue;
}
// Yukarıda Sütunlar eklendi
// onun şemasına göre yeni bir satır oluşturuyoruz.
// Okunan verileri yan yana sıralamak için
var yeniSatir = table.NewRow();
for (int j = 1; j <= cols; j++)
{
// Sütunların içeriği boş mu kontrolü yapılmaktadır.
if (range.Cells[i, j] != null && range.Cells[i, j].Value2 != null)
yeniSatir[j - 1] = range.Cells[i, j].Value2.ToString();
else // İçeriği boş hücrede hata vermesini önlemek için
yeniSatir[j - 1] = String.Empty;
}
table.Rows.Add(yeniSatir);
}
return table;
}
public int satirSayisi;
public int sutunSayisi;
private void button1_Click(object sender, EventArgs e)
{
try
{
Excel.Application exceldosya = new Excel.Application();
exceldosya.Visible = true;
object Missing = Type.Missing;
Workbook bolumlistesi = exceldosya.Workbooks.Add(Missing);
Worksheet sheet1 = (Worksheet)bolumlistesi.Sheets[1];
int sutun = 1;
int satır = 1;
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
Range myrange = (Range)sheet1.Cells[satır, sutun + j];
myrange.Value2 = dataGridView1.Columns[j].HeaderText;
}
satır++;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
Range myrange = (Range)sheet1.Cells[satır + i, sutun + j];
myrange.Value2 = dataGridView1[j, i].Value == null ? "" : dataGridView1[j, i].Value;
myrange.Select();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
using DrivingSchool_Api;
using Microsoft.EntityFrameworkCore;
using Models.ViewModels;
using Repository.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Repository.Implementations
{
public class BookingRepository : IBookingRepository
{
private readonly DrivingSchoolDbContext _db;
private readonly IDapperBaseRepository _dapperBaseRepository;
public BookingRepository(DrivingSchoolDbContext db, IDapperBaseRepository dapperBaseRepository)
{
_db = db;
_dapperBaseRepository = dapperBaseRepository;
}
public int Add(Booking booking)
{
var parameters = new
{
booking.BkpId,
booking.TimeId,
booking.CustomerEmail,
booking.DateBooked,
booking.DateBookingFor,
booking.Status,
booking.Price
};
return _dapperBaseRepository.ExecuteWithDynamicParameter("AdddBooking", parameters);
}
public IQueryable<BookingVm> BookingDetails(string userName=null)
{
var parameter = new { userName };
string qeury = "BookingView";
return _dapperBaseRepository.QueryWithParameter<BookingVm>(qeury, parameter);
}
public int Delete(int? bookingId)
{
var parameters = new { bookingId };
return _dapperBaseRepository.ExecuteWithDynamicParameter("DeleteBooking",bookingId);
}
public BookingVm GetSingleRecord(int? bookingId)
{
var parameter = new { bookingId };
string qeury = "BookingDetails";
return _dapperBaseRepository.QuerySingl<BookingVm>(qeury, parameter);
}
public IQueryable<BookingVm> GetAll()
{
return _dapperBaseRepository.Query<BookingVm>("BookingView");
}
public int Update(Booking booking)
{
var parameters = new
{
booking.BookingId,
booking.BkpId,
booking.TimeId,
booking.CustomerEmail,
booking.DateBookingFor,
booking.DateBooked,
booking.Price,
booking.Status
};
return _dapperBaseRepository.Execute("UpdateBooking", parameters);
}
}
}
|
using System;
using System.Collections.Generic;
namespace EPI.Sorting
{
/// <summary>
/// You are given a set of closed intervals. Design an efficient algorithm to find the
/// minimum number of numbers that covers all the intervals
/// </summary>
/// <example>
/// Intervals: {[0,3],[2,6],[3,4],[6,9]} can be covered by visiting at 0,2,3,6 or 3,6 or 3,9 etc...
/// The smallest number of times visit is required is 2. So 3,6 or 3,9 are valid answers
/// </example>
public static class IntervalCoveringProblem
{
public struct Interval
{
public int start;
public int end;
}
private class EntryType : IComparable
{
public Interval interval;
public bool isEndInterval;
public int CompareTo(object obj)
{
EntryType entryType = obj as EntryType;
if (entryType != null)
{
int myValue = isEndInterval ? interval.end : interval.start;
int theirValue = (entryType.isEndInterval) ? entryType.interval.end : entryType.interval.start;
return (myValue != theirValue) ?
myValue.CompareTo(theirValue) : // first sort entry's with lowest value
isEndInterval.CompareTo(entryType.isEndInterval); // then sort by entry type (start is sorted before end)
}
throw new InvalidOperationException();
}
}
public static List<int> FindMinimumIntervalCoveringSet(Interval[] intervals)
{
EntryType[] entries = new EntryType[intervals.Length * 2];
for (int i = 0; i < intervals.Length; i++)
{
entries[2 * i] = new EntryType() { interval = intervals[i], isEndInterval = false };
entries[2 * i + 1] = new EntryType() { interval = intervals[i], isEndInterval = true };
}
QuickSort<EntryType>.Sort(entries); // sort the time entries giving preference to start over end
List<int> result = new List<int>();
HashSet<Interval> visitingEntries = new HashSet<Interval>(); // intervals that are currently being visited/processed
HashSet<Interval> visited = new HashSet<Interval>(); // intervals that already been visited/processed
// iterate all entries
foreach (EntryType entry in entries)
{
if (!entry.isEndInterval)
{
// start entry, mark as visiting
visitingEntries.Add(entry.interval);
}
else // end of an entry
{
if (!visited.Contains(entry.interval)) // end of an entry that we haven't finished visiting
{
result.Add(entry.interval.end); // add value to result
//mark as visiting entries as visited
foreach (var e in visitingEntries)
{
visited.Add(e);
if (visited.Count == intervals.Length) //all entries visited, we are done
{
break;
}
}
visitingEntries.Clear();
}
}
}
return result;
}
}
}
|
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace attendance
{
/// <summary>
/// Interaction logic for AdminProps.xaml
/// </summary>
public partial class AdminProps : Window
{
Connection con = new Connection();
Export ex = new Export();
public List<Record> RecordsList { get; set; }
public AdminProps()
{
InitializeComponent();
UpdateUsers();
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
DragMove();
}
private void CloseButtonClick(object sender, RoutedEventArgs e)
{
Close();
}
private void RegisterButtonClick(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(FirstNameTextBox.Text) & !string.IsNullOrWhiteSpace(LastNameTextBox.Text) & !string.IsNullOrWhiteSpace(UserNameTextBox.Text) & !string.IsNullOrWhiteSpace(PasswordTextBox.Text))
{
if (!IsDuplicate())
{
if (con.IsRegister(FirstNameTextBox.Text, LastNameTextBox.Text, UserNameTextBox.Text, PasswordTextBox.Text))
{
UpdateUsers();
con.CreateTrack(con.GetUserID(UserNameTextBox.Text));
}
}
else
{
MessageBox.Show($"Uživatel {UserNameTextBox.Text} již existuje.");
}
}
else
{
MessageBox.Show("Některá pole jsou stále prázdná.");
}
}
private void ExportButtonClick(object sender, RoutedEventArgs e)
{
if (!ex.IsExportedToExcel(con.GetRecords(UsersComboBox, MonthComboBox, YearComboBox)))
{
MessageBox.Show("Export neproběhl úspěšně");
}
}
private void DisplayButtonClick(object sender, RoutedEventArgs e)
{
RecordsList = con.GetRecords(UsersComboBox, MonthComboBox, YearComboBox);
//Musí být přnastaven až po všech změnách, nejdřív vynuluji, jinak bude fungovat jen poprvé
DataContext = null;
DataContext = this;
}
/// <summary>
/// Aktualizuje combobox s uživateli.
/// </summary>
private void UpdateUsers()
{
UsersComboBox.Items.Clear();
foreach (string s in con.GetUsers())
{
UsersComboBox.Items.Add(s);
}
}
//vrací true pokud uživatel již existuje
private bool IsDuplicate()
{
if (con.GetUsers().Contains(UserNameTextBox.Text))
{
return true;
}
else
{
return false;
}
}
}
}
|
using System;
class StringsTypeCasting
{
static void Main()
{
string firstWord = "Hello";
string secondWord = "World!";
object bothWords = firstWord + " " + secondWord;
string finalWords = bothWords.ToString();
Console.WriteLine(finalWords);
}
}
|
using System.Configuration;
namespace SolarSystemWeb.Models.Application
{
public class ApplicationSettings
{
private static volatile ApplicationSettings _instance;
private static readonly object SyncRoot = new object();
private ApplicationSettings() { }
public static ApplicationSettings Instance
{
get
{
if (_instance == null)
{
lock (SyncRoot)
{
if (_instance == null)
_instance = new ApplicationSettings();
}
}
return _instance;
}
}
/// <summary>
/// Нужна ли оптимизация скриптов и стилей
/// </summary>
public bool OptimizeScriptsAndStyles
{
get
{
string rawValue = ConfigurationManager.AppSettings["OptimizeScriptsAndStyles"]; ;
bool res;
return bool.TryParse(rawValue, out res) && res;
}
}
/// <summary>
/// Максимальный размер загружаемого изображения
/// </summary>
public int MaxImageSize
{
get
{
string rawValue = ConfigurationManager.AppSettings["MaxImageSize"];
int res;
bool parseRes = int.TryParse(rawValue, out res);
return parseRes ? res : 0;
}
}
/// <summary>
/// Списко разрешенных MIME-типов для загружаемых изображений
/// </summary>
public string[] AllowedTypes
{
get { return ConfigurationManager.AppSettings["AllowedTypes"].Split(';'); }
}
}
} |
using System;
namespace HomeAutomation.Referential.Models
{
public abstract class Thing : IThing
{
protected Thing()
{
}
protected Thing(Guid id, string label)
{
Id = id;
Label = label;
}
public Guid Id { get; set; }
public string Label { get; set; }
}
} |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
namespace gView.Framework.system.UI
{
public partial class AboutBox : Form
{
private bool _showCredits = true;
public AboutBox()
: this(true)
{
}
public AboutBox(bool showCredits)
{
_showCredits = showCredits;
InitializeComponent();
MakeGUI();
}
private void MakeGUI()
{
richTextBox1.Text = richTextBox1.Text.Replace("{YEAR}", DateTime.Now.Year.ToString());
lblVersion.Text = "Version: " + SystemInfo.Version.ToString();
lblBit.Text = (gView.Framework.system.Wow.Is64BitProcess ? "64" : "32") + " Bit";
lbPath.Text = "Installation path: " + SystemVariables.ApplicationDirectory;
MakeCredits();
}
private void MakeCredits()
{
if (!_showCredits)
{
return;
}
try
{
XmlDocument doc = new XmlDocument();
doc.Load(SystemVariables.ApplicationDirectory + @"\credits.xml");
int y = 25;
foreach (XmlNode credit in doc.SelectNodes("credits/credit"))
{
if (credit.Attributes["text"] != null)
{
Label lbl = new Label();
lbl.Text = credit.Attributes["text"].Value.Replace("\\n", "\n");
lbl.Width = gpCredits.Width - 20;
lbl.Height = lbl.Font.Height * lbl.Text.Split('\n').Length + 2;
lbl.Location = new Point(10, y);
gpCredits.Controls.Add(lbl);
y += lbl.Height;
}
if (credit.Attributes["hyperlink"] != null)
{
LinkLabel llbl = new LinkLabel();
llbl.Text = credit.Attributes["hyperlink"].Value;
llbl.Width = gpCredits.Width - 20;
llbl.Height = llbl.Font.Height;
llbl.Location = new Point(10, y);
string link = "http://" + llbl.Text;
llbl.Links.Add(0, link.Length, link);
llbl.LinkClicked += new LinkLabelLinkClickedEventHandler(llbl_LinkClicked);
gpCredits.Controls.Add(llbl);
y += llbl.Height;
}
y += 10;
}
}
catch { }
}
void llbl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(e.Link.LinkData.ToString());
}
}
} |
/* Drink.cs
* Author: Agustin Rodriguez
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using DinoDiner.Menu;
namespace DinoDiner.Menu
{
/// <summary>
/// this is the base class for Drinks in Dino-Diner
/// </summary>
public abstract class Drink : IMenuItem, IOrderItem, INotifyPropertyChanged
{
/// <summary>
/// implement interface for INotifyPropertyChanged
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// an event handler to notify if a field/property is changed
/// </summary>
/// <param name="propertyName">name of the property changed</param>
protected void NotifyOfPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// ingredients in each drink
/// </summary>
protected List<string> ingredients = new List<string>();
/// <summary>
/// Gets and sets the price
/// </summary>
public double Price { get; set; }
/// <summary>
/// Gets and sets the calories
/// </summary>
public uint Calories { get; set; }
/// <summary>
/// Gets the ingredients list
/// </summary>
public abstract List<string> Ingredients { get; }
/// <summary>
/// Gets or sets the size
/// </summary>
public virtual Size Size { get; set; }
/// <summary>
/// Ice in the drink
/// </summary>
public bool Ice { get; set; } = true;
/// <summary>
/// no ice in the drink
/// </summary>
public void HoldIce()
{
this.Ice = false;
NotifyOfPropertyChanged("Special");
}
/// <summary>
/// same as the ToString() implementation of the order item
/// </summary>
public abstract string Description { get; }
/// <summary>
/// any special food instructions for food prep
/// </summary>
public abstract string[] Special { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DAL.Contracts;
using DAL.Models;
namespace DAL.Repositories
{
public class GenreRepository : BaseRepository<Genre>, IGenreRepository
{
public GenreRepository(MoviesContext context)
: base(context)
{
}
public Genre GetByTitle(string title)
{
return Context.Genres.FirstOrDefault((c => c.Title == title));
}
public override void Insert(Genre genre)
{
if (genre == null)
return;
var dbGenre = GetByTitle(genre.Title);
if (dbGenre == null)
DbSet.Add(genre);
}
}
} |
using Cs_Notas.Dominio.Entities;
using Cs_Notas.Dominio.Interfaces.Repositorios;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Infra.Data.Repositorios
{
public class RepositorioTransacaoDoi: RepositorioBase<TransacaoDoi>, IRepositorioTransacaoDoi
{
}
}
|
using Alabo.Data.People.PartnerCompanies.Domain.Entities;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Data.People.PartnerCompanies.Domain.Repositories {
public class PartnerCompanyRepository : RepositoryMongo<PartnerCompany, ObjectId>,IPartnerCompanyRepository {
public PartnerCompanyRepository(IUnitOfWork unitOfWork) : base(unitOfWork){
}
}
}
|
using System;
using Framework.Core.Common;
using Tests.Data.Oberon;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.Event
{
public class EventBasePage : SinglePane
{
public EventBasePage(Driver driver) : base(driver) { }
#region Page Objects
public IWebElement DisclosureSelect { get { return _driver.FindElement(By.Id("DesignationId")); } }
public IWebElement NameField { get { return _driver.FindElement(By.CssSelector("#Name")); } }
public IWebElement NameFieldValidationMessage { get { return _driver.FindElement(By.XPath("//span[@for='Name' and contains(@class,'field-validation-error')]")); } }
public IWebElement YesFundRaiserEventRadioButton { get { return _driver.FindElement(By.CssSelector("#IsFundraisingEvent_0")); } }
public IWebElement NoFundRaiserEventRadioButton { get { return _driver.FindElement(By.CssSelector("#IsFundraisingEvent_1")); } }
public IWebElement DescriptionField { get { return _driver.FindElement(By.CssSelector("#Description")); } }
public IWebElement TargetAmountToRaiseField { get { return _driver.FindElement(By.CssSelector("#TargetAmountToRaise")); } }
public IWebElement TargetGuestCountField { get { return _driver.FindElement(By.CssSelector("#TargetGuestCount")); } }
public IWebElement StartDateField { get { return _driver.FindElement(By.CssSelector("#StartDate_datepkr")); } }
public IWebElement StartDateHourSelector { get { return _driver.FindElement(By.CssSelector("#StartDate_timepkr_hr")); } }
public IWebElement StartDateMinuteSelector { get { return _driver.FindElement(By.CssSelector("#StartDate_timepkr_min")); } }
public IWebElement StartDateMeridianSelector { get { return _driver.FindElement(By.CssSelector("#StartDate_timepkr_meridian")); } }
public IWebElement EndDateField { get { return _driver.FindElement(By.CssSelector("#EndDate_datepkr")); } }
public IWebElement EndDateHourSelector { get { return _driver.FindElement(By.CssSelector("#EndDate_timepkr_hr")); } }
public IWebElement EndDateMinuteSelector { get { return _driver.FindElement(By.CssSelector("#EndDate_timepkr_min")); } }
public IWebElement EndDateMeridianSelector { get { return _driver.FindElement(By.CssSelector("#EndDate_timepkr_meridian")); } }
public IWebElement LocationNameField { get { return _driver.FindElement(By.CssSelector("#LocationName")); } }
public IWebElement AddressLine1Field { get { return _driver.FindElement(By.CssSelector("#AddressLine1")); } }
public IWebElement AddressLine2Field { get { return _driver.FindElement(By.CssSelector("#AddressLine2")); } }
public IWebElement CityField { get { return _driver.FindElement(By.CssSelector("#City")); } }
public IWebElement StateProvinceSelector { get { return _driver.FindElement(By.CssSelector("#StateProvince")); } }
public IWebElement PostalCodeSelector { get { return _driver.FindElement(By.CssSelector("#PostalCode")); } }
public IWebElement FindSourceCodeLink { get { return _driver.FindElement(By.CssSelector(".search.ajaxLink")); } }
public IWebElement SelectCodesButton { get { return _driver.FindElement(By.CssSelector("#selectCodesBtn")); } }
public IWebElement CodeTreeContainer { get { return _driver.FindElement(By.CssSelector(".codeTreeContainer")); } }
public By SponserInputLocator = By.CssSelector("#AllDisclosureFields_1__Value");
public IWebElement SponserInput { get { return _driver.FindElement(SponserInputLocator); } }
public IWebElement CrudReportSpecificFieldsHeaderExpanded { get { return _driver.FindElement(By.CssSelector(".sectionSubTitle.isCollapsable.reportSpecificFields")); } }
public IWebElement CrudReportSpecificFieldsHeaderCollapsed { get { return _driver.FindElement(By.CssSelector(".sectionSubTitle.reportSpecificFields.isExpandable")); } }
public IWebElement ReportExander { get { return _driver.FindElement(By.XPath("//div[@id='DisclosureSection']/div/div/h3")); } }
public IWebElement CodesDiv { get { return _driver.FindElement(By.XPath("//h3[contains(text(), 'Codes')]/parent::*")); } }
#endregion
#region Methods
public void ExpandCodesSection()
{
if (CodesDiv.GetAttribute("class").Contains("isExpandable"))
CodesDiv.Click();
}
/// <summary>
/// enters source code
/// </summary>
public void EnterSourceCode(string code)
{
//SourceCodeField.SendKeys(code);
ExpandCodesSection();
_driver.MoveToElement(FindSourceCodeLink);
_driver.ScrollToBottomOfPage();
_driver.Click(FindSourceCodeLink);
_driver.Click(_driver.FindElement(By.XPath("//span[contains(text(), '" + code + "')]/preceding-sibling::input[@type='checkbox']")));
_driver.Click(SelectCodesButton);
}
/// <summary>
/// expands report specific field header
/// </summary>
public void ExpandReportSpecificFieldsHeader(IWebElement expand, IWebElement collapsed)
{
try
{
if (_driver.IsElementPresent(collapsed)) _driver.Click(collapsed);
}
catch (Exception)
{
}
}
/// <summary>
/// creates event with code from event object, returns event id
/// </summary>
public string CreateEvent(string code, TestEvent newEvent)
{
newEvent.Code = code;
return EnterEventDetails(newEvent, "create");
}
/// <summary>
/// creates event from event object, returns event id
/// </summary>
public string CreateEvent(TestEvent newEvent)
{
return EnterEventDetails(newEvent, "create");
}
/// <summary>
/// creates event with code from event object, sets isFundraising radio, returns event id
/// </summary>
public string CreateEvent(bool isFundraising, string code, TestEvent newEvent)
{
newEvent.Code = code;
newEvent.IsFundraising = isFundraising;
return EnterEventDetails(newEvent, "create");
}
/// <summary>
/// udpates event from event object, returns event id
/// </summary>
public string UpdateEvent(TestEvent newEvent)
{
return EnterEventDetails(newEvent, "update");
}
/// <summary>
/// base event function, creates or updates based on createOrUpdate string parameter, returns event ID
/// </summary>
public string EnterEventDetails(TestEvent newEvent, string createOrUpdate)
{
if (createOrUpdate.Contains("create"))
{
var create = new EventCreate(_driver);
create.GoToThisPage();
}
else if (createOrUpdate.Contains("update"))
{
var update = new EventUpdate(_driver);
update.GoToEventUpdate(newEvent.Id);
}
if (newEvent.Sponser != null)
{
_driver.SelectOptionByText(DisclosureSelect, "Oberon Report");
_driver.WaitForElementToDisplayBy(SponserInputLocator);
}
// Event Information
if (newEvent.IsFundraising) _driver.Click(YesFundRaiserEventRadioButton);
else _driver.Click(NoFundRaiserEventRadioButton);
if (newEvent.Name != null)
if (newEvent.Name.Length==0)
_driver.ClearAndTab(NameField);
else
_driver.ClearAndSendKeys(NameField, newEvent.Name);
if (newEvent.Description != null) _driver.ClearAndSendKeys(DescriptionField, newEvent.Description);
if (newEvent.TargetAmountToRaise != null)
_driver.ClearAndSendKeys(TargetAmountToRaiseField, newEvent.TargetAmountToRaise);
if (newEvent.TargetGuestCount != null) _driver.ClearAndSendKeys(TargetGuestCountField, newEvent.TargetGuestCount);
if (newEvent.StartDate != null) _driver.ClearAndSendKeys(StartDateField, newEvent.StartDate);
if (newEvent.StartDateHour != null)
_driver.SelectOptionByText(StartDateHourSelector, newEvent.StartDateHour);
if (newEvent.StartDateMinute != null)
_driver.SelectOptionByText(StartDateMinuteSelector, newEvent.StartDateMinute);
if (newEvent.StartDateMeridian != null)
_driver.SelectOptionByText(StartDateMeridianSelector, newEvent.StartDateMeridian);
if (newEvent.EndDate != null) _driver.ClearAndSendKeys(EndDateField, newEvent.EndDate);
if (newEvent.EndDateHour != null) _driver.SelectOptionByText(EndDateHourSelector, newEvent.EndDateHour);
if (newEvent.EndDateMinute != null) _driver.SelectOptionByText(EndDateMinuteSelector, newEvent.EndDateMinute);
if (newEvent.EndDateMeridian != null) _driver.SelectOptionByText(EndDateMeridianSelector, newEvent.EndDateMeridian);
if (newEvent.LocationName != null) _driver.SendKeys(LocationNameField, newEvent.LocationName);
if (newEvent.Address1 != null) _driver.ClearAndSendKeys(AddressLine1Field, newEvent.Address1);
if (newEvent.Address2 != null) _driver.ClearAndSendKeys(AddressLine2Field, newEvent.Address2);
if (newEvent.City != null) _driver.ClearAndSendKeys(CityField, newEvent.City);
if (newEvent.StateProvince != null) _driver.SelectOptionByText(StateProvinceSelector, newEvent.StateProvince);
if (newEvent.PostalCode != null) _driver.ClearAndSendKeys(PostalCodeSelector, newEvent.PostalCode);
// Report Specific
//ExpandReportSpecificFieldsHeader(CrudReportSpecificFieldsHeaderExpanded,
// CrudReportSpecificFieldsHeaderCollapsed);
if (newEvent.Sponser != null)
{
_driver.ClearAndSendKeys(SponserInput, newEvent.Sponser);
}
// Codes
if (newEvent.Code != null) EnterSourceCode(newEvent.Code);
ClickCreateButtonBottom();
_driver.WaitForElementToDisplayBy(EditLinkLocator);
var detail = new EventDetail(_driver);
return detail.GetEventId();
}
#endregion
}
}
|
using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TriangleCollector.Services;
namespace TriangleCollector.Services
{
class ExchangeServiceInitializer : BackgroundService
{
private readonly ILoggerFactory _factory;
private readonly ILogger<ExchangeServiceInitializer> _logger;
private TelemetryClient _telemetryClient;
public ExchangeServiceInitializer(ILoggerFactory factory, ILogger<ExchangeServiceInitializer> logger, TelemetryClient telemetryClient)
{
_factory = factory;
_logger = logger;
_telemetryClient = telemetryClient;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogDebug($"Initializing Exchange Services...");
stoppingToken.Register(() => _logger.LogDebug("Stopping Exchange Service Initialization..."));
await BackgroundProcessing(stoppingToken);
_logger.LogDebug("Stopped Exchange Service Initialization...");
}
private async Task BackgroundProcessing(CancellationToken stoppingToken)
{
foreach(var exchange in ProjectOrbit.Exchanges)
{
var subscriptionManager = new SubscriptionManager(_factory, _factory.CreateLogger<SubscriptionManager>(), exchange);
await subscriptionManager.StartAsync(stoppingToken);
var clientManager = new ClientManager(_factory, _factory.CreateLogger<ClientManager>(), exchange);
await clientManager.StartAsync(stoppingToken);
var calculator = new TriangleCalculator(_factory.CreateLogger<TriangleCalculator>(), exchange);
await calculator.StartAsync(stoppingToken);
var queueMonitor = new QueueMonitor(_factory, _factory.CreateLogger<QueueMonitor>(), exchange);
await queueMonitor.StartAsync(stoppingToken);
var subscriber = new OrderbookSubscriber(_factory, _factory.CreateLogger<OrderbookSubscriber>(), _telemetryClient, exchange);
await subscriber.StartAsync(stoppingToken);
var statsMonitor = new StatisticsMonitor(_factory.CreateLogger<StatisticsMonitor>(), exchange);
await statsMonitor.StartAsync(stoppingToken);
var activityMonitor = new ActivityMonitor(_factory, _factory.CreateLogger<ActivityMonitor>(), exchange);
await activityMonitor.StartAsync(stoppingToken);
//_logger.LogInformation($"there are {exchange.TradedMarkets.Count} markets traded on {exchange.ExchangeName}. Of these markets, {exchange.TriarbEligibleMarkets.Count} markets interact to form {exchange.UniqueTriangleCount} triangular arbitrage opportunities");
}
}
}
}
|
namespace VnStyle.Web.Controllers.Api.Models
{
public class ResetPassword
{
public string Password { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveEnemyTile : ActiveTile {
EnemyController childEnemy;
WeaponPanelOperator weaponPowerOperator;
public TileSetup tilesetup;
private void Awake(){
weaponPowerOperator =(WeaponPanelOperator) FindObjectOfType(typeof(WeaponPanelOperator));
}
override public void OwnAction (){
childEnemy = GetComponentInChildren<EnemyController>();
if (childEnemy != null && Time.time >= LevelManager.turnPauseTime) {
AttackEnemy();
WeaponPanelOperator.activeWeapon.AttackWeapon();
LevelManager.PlusOneTurn();
}
}
void AttackEnemy () {
weaponPowerOperator.SetWeaponPower();
childEnemy.TakeDamage(WeaponPanelOperator.weaponPower, tilesetup.TileID, HeroController.currentPositionID);
}
}
|
using JhinBot.DiscordObjects;
namespace JhinBot.Database
{
public interface ITagRepository : IRepository<Tag>
{
Tag RetrieveByName(ulong guildID, string name);
}
}
|
using System.Collections.Generic;
using UnityEngine;
public class SpawnAsteroid : MonoBehaviour
{
public int CountAsteroid;
public List<GameObject> _arrayprefubAsteroid = new List<GameObject>();
public float _incrementSpeedAsteroid;
private int _counterForSpawn = 0;
private CheckOnBarrier _checkotheasteroid;
private Vector3 _startPosition;
private Quaternion _startRotation;
private DictionaryAsteroid Componentdictionary;
/*private struct ObjAndSpeed
{
public GameObject Asteroid;
public MoveAsteroid SpeedAsteroid;
public CircleCollider2D AsteroidCirlce;
public ObjAndSpeed(GameObject Asteroid, MoveAsteroid SpeedAsteroid, CircleCollider2D AsteroidCirlce)
{
this.Asteroid = Asteroid;
this.SpeedAsteroid = SpeedAsteroid;
this.AsteroidCirlce = AsteroidCirlce;
}
}*/
//private List<Asteroid> _arrayAsteroid = new List<Asteroid>();
private FindExtremePoints _valueExtremePoints;
private void Start()
{
Componentdictionary = GetComponent<DictionaryAsteroid>();
_valueExtremePoints = GetComponent<FindExtremePoints>();
_checkotheasteroid = GetComponent<CheckOnBarrier>();
_startPosition = new Vector3(_valueExtremePoints.XRight + 10.0f, _valueExtremePoints.YTop, 1.0f);
_startRotation = Quaternion.Euler(0,0,0);
for (_counterForSpawn = 0; _counterForSpawn < CountAsteroid; _counterForSpawn++)
{
_startPosition.y = Random.Range(_valueExtremePoints.YBot, _valueExtremePoints.YTop);
GameObject ObjAsteroid = Instantiate(_arrayprefubAsteroid[Random.Range(0, _arrayprefubAsteroid.Count - 1)], _startPosition, _startRotation);
Componentdictionary._attachedScriptsToObj.Add(ObjAsteroid, ObjAsteroid.GetComponent<Asteroid>());
Componentdictionary._attachedScriptsToObj[ObjAsteroid].GetMovementAsteroid.Speed = Random.Range(1,7);
_checkotheasteroid.SetSrartPositionForRayCast(Componentdictionary._attachedScriptsToObj[ObjAsteroid]);
}
}
private void FixedUpdate()
{
}
public void Respawn(GameObject Asteroid)
{
Asteroid.GetComponent<SpriteRenderer>().sprite = _arrayprefubAsteroid[Random.Range(0, _arrayprefubAsteroid.Count - 1)].GetComponent<SpriteRenderer>().sprite;
_startPosition.y = Random.Range(_valueExtremePoints.YBot, _valueExtremePoints.YTop);
Asteroid.transform.position = _startPosition;
}
}
|
using System;
using System.Windows;
using System.Windows.Input;
using CatalogSearch.ViewModels;
namespace CatalogSearch.Views
{
public partial class CatalogSearchWindow : Window
{
private readonly CatalogSearchViewModel viewModel;
public CatalogSearchWindow(CatalogSearchViewModel vm)
{
viewModel = vm;
viewModel.CatalogSearchView = this;
DataContext = viewModel;
InitializeComponent();
}
private void searchButton_Click(object sender, RoutedEventArgs e)
{
viewModel.Search();
}
private void queryStringTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && viewModel.IsSearchEnabled)
{
searchButton_Click(sender, e);
}
}
}
}
|
using System;
using Xunit;
using Poker.Classes;
using static Poker.Program;
namespace PokerTests
{
public class UnitTest1
{
/// <summary>
/// Tests for StraightFlush Ace Exception
/// </summary>
[Fact]
public void StraightFlushAceException()
{
Card card1 = new Card(Suit.Clubs, Value.Ace);
Card card2 = new Card(Suit.Clubs, Value.Two);
Card card3 = new Card(Suit.Clubs, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Four);
Card card5 = new Card(Suit.Clubs, Value.Five);
Card card6 = new Card(Suit.Diamonds, Value.Queen);
Card card7 = new Card(Suit.Diamonds, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[0]);
}
/// <summary>
/// Tests for StraightFlush with no gaps
/// </summary>
[Fact]
public void StraightFlushTestNoGaps()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Three);
Card card3 = new Card(Suit.Clubs, Value.Four);
Card card4 = new Card(Suit.Clubs, Value.Five);
Card card5 = new Card(Suit.Clubs, Value.Six);
Card card6 = new Card(Suit.Diamonds, Value.Queen);
Card card7 = new Card(Suit.Diamonds, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[0]);
}
/// <summary>
/// Tests for StraightFlush with gaps
/// </summary>
[Fact]
public void StraightFlushTestWithGaps()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Three);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Four);
Card card5 = new Card(Suit.Diamonds, Value.Four);
Card card6 = new Card(Suit.Clubs, Value.Five);
Card card7 = new Card(Suit.Clubs, Value.Six);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[0]);
}
/// <summary>
/// Tests for FourOfAKind with a FullHouse
/// </summary>
[Fact]
public void FourOfAKindFullHouse()
{
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Diamonds, Value.Four);
Card card3 = new Card(Suit.Hearts, Value.Four);
Card card4 = new Card(Suit.Spades, Value.Four);
Card card5 = new Card(Suit.Clubs, Value.Seven);
Card card6 = new Card(Suit.Diamonds, Value.Seven);
Card card7 = new Card(Suit.Hearts, Value.Seven);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[1]);
}
/// <summary>
/// Tests for FourOfAKind with a Flush
/// </summary>
[Fact]
public void FourOfAKindFlush()
{
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Clubs, Value.Four);
Card card3 = new Card(Suit.Spades, Value.Four);
Card card4 = new Card(Suit.Clubs, Value.Four);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Clubs, Value.Seven);
Card card7 = new Card(Suit.Clubs, Value.Seven);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[1]);
}
/// <summary>
/// Tests for FourOfAKind with a Pair
/// </summary>
[Fact]
public void FourOfAKindPair()
{
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Diamonds, Value.Four);
Card card3 = new Card(Suit.Hearts, Value.Four);
Card card4 = new Card(Suit.Spades, Value.Four);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Clubs, Value.Seven);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[1]);
}
/// <summary>
/// Tests for FullHouse with Flush
/// </summary>
[Fact]
public void FullHouseWithFlush()
{
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Clubs, Value.Four);
Card card3 = new Card(Suit.Spades, Value.Four);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Clubs, Value.Queen);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[2]);
}
/// <summary>
/// Tests for FullHouse with TwoPair
/// </summary>
[Fact]
public void FullHouseWithTwoPair()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Clubs, Value.King);
Card card4 = new Card(Suit.Diamonds, Value.King);
Card card5 = new Card(Suit.Hearts, Value.Ace);
Card card6 = new Card(Suit.Diamonds, Value.Ace);
Card card7 = new Card(Suit.Spades, Value.Ace);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[2]);
}
/// <summary>
/// Tests for FullHouse with 2 ThreeOfAKinds
/// </summary>
[Fact]
public void FullHouseWithThreeOfAKinds()
{
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Diamonds, Value.Four);
Card card3 = new Card(Suit.Hearts, Value.Four);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Hearts, Value.Seven);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[2]);
}
/// <summary>
/// Tests for Flush with ThreeOfAKind
/// </summary>
[Fact]
public void FlushWithThreOfAKind()
{
Card card1 = new Card(Suit.Clubs, Value.Three);
Card card2 = new Card(Suit.Spades, Value.Three);
Card card3 = new Card(Suit.Diamonds, Value.Three);
Card card4 = new Card(Suit.Diamonds, Value.Seven);
Card card5 = new Card(Suit.Diamonds, Value.Ten);
Card card6 = new Card(Suit.Diamonds, Value.Jack);
Card card7 = new Card(Suit.Diamonds, Value.Queen);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[3]);
}
/// <summary>
/// Tests for Flush with TwoPair
/// </summary>
[Fact]
public void FlushWithTwoPair()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Clubs, Value.Three);
Card card4 = new Card(Suit.Diamonds, Value.Three);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Diamonds, Value.Eight);
Card card7 = new Card(Suit.Diamonds, Value.Ten);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[3]);
}
/// <summary>
/// Tests for Flush with Pair
/// </summary>
[Fact]
public void FlushWithPair()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Diamonds, Value.Seven);
Card card4 = new Card(Suit.Diamonds, Value.Eight);
Card card5 = new Card(Suit.Diamonds, Value.Jack);
Card card6 = new Card(Suit.Diamonds, Value.Queen);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[3]);
}
/// <summary>
/// Tests for Straight with ThreeOfAKind
/// </summary>
[Fact]
public void StraightWithThreeOfAKind()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Spades, Value.Two);
Card card4 = new Card(Suit.Clubs, Value.Three);
Card card5 = new Card(Suit.Diamonds, Value.Four);
Card card6 = new Card(Suit.Clubs, Value.Five);
Card card7 = new Card(Suit.Clubs, Value.Six);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[4]);
}
/// <summary>
/// Tests for Straight with TwoPair
/// </summary>
[Fact]
public void StraightWithTwoPair()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Three);
Card card5 = new Card(Suit.Diamonds, Value.Four);
Card card6 = new Card(Suit.Clubs, Value.Five);
Card card7 = new Card(Suit.Clubs, Value.Six);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[4]);
}
/// <summary>
/// Tests for Straight with Pair
/// </summary>
[Fact]
public void StraightWithPair()
{
Card card1 = new Card(Suit.Diamonds, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Two);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Four);
Card card5 = new Card(Suit.Diamonds, Value.Five);
Card card6 = new Card(Suit.Clubs, Value.Six);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[4]);
}
/// <summary>
/// Tests for ThreeOfAKind
/// </summary>
[Fact]
public void ThreeOfAKindWith1()
{
Card card1 = new Card(Suit.Clubs, Value.Three);
Card card2 = new Card(Suit.Diamonds, Value.Three);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Four);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Clubs, Value.Eight);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[5]);
}
/// <summary>
/// Tests for ThreeOfAKind
/// </summary>
[Fact]
public void ThreeOfAKind2()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Three);
Card card3 = new Card(Suit.Spades, Value.Four);
Card card4 = new Card(Suit.Clubs, Value.Four);
Card card5 = new Card(Suit.Diamonds, Value.Four);
Card card6 = new Card(Suit.Clubs, Value.Seven);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[5]);
}
/// <summary>
/// Tests for ThreeOfAKind
/// </summary>
[Fact]
public void ThreeOfAKind3()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Three);
Card card3 = new Card(Suit.Spades, Value.Five);
Card card4 = new Card(Suit.Clubs, Value.Ten);
Card card5 = new Card(Suit.Diamonds, Value.King);
Card card6 = new Card(Suit.Hearts, Value.King);
Card card7 = new Card(Suit.Spades, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[5]);
}
/// <summary>
/// Tests for TwoPair with gap between pairs
/// </summary>
[Fact]
public void TwoPairWithGap()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Hearts, Value.Two);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Five);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Clubs, Value.King);
Card card7 = new Card(Suit.Hearts, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[6]);
}
/// <summary>
/// Tests for TwoPair with no gap between pairs
/// </summary>
[Fact]
public void TwoPairWithNoGap()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Three);
Card card5 = new Card(Suit.Diamonds, Value.Eight);
Card card6 = new Card(Suit.Clubs, Value.Ten);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[6]);
}
/// <summary>
/// Tests for TwoPair with Ace High
/// </summary>
[Fact]
public void TwoPairWithAceHigh()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Four);
Card card5 = new Card(Suit.Diamonds, Value.King);
Card card6 = new Card(Suit.Clubs, Value.King);
Card card7 = new Card(Suit.Clubs, Value.Ace);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[6]);
}
/// <summary>
/// Tests for Pair
/// </summary>
[Fact]
public void PairTest1()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Two);
Card card3 = new Card(Suit.Spades, Value.Four);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Diamonds, Value.Eight);
Card card6 = new Card(Suit.Spades, Value.Ten);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[7]);
}
/// <summary>
/// Tests for Pair
/// </summary>
[Fact]
public void PairTest2()
{
Card card1 = new Card(Suit.Spades, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Three);
Card card3 = new Card(Suit.Spades, Value.Five);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Diamonds, Value.Ten);
Card card6 = new Card(Suit.Clubs, Value.Ace);
Card card7 = new Card(Suit.Diamonds, Value.Ace);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[7]);
}
/// <summary>
/// Tests for Pair
/// </summary>
[Fact]
public void PairTest3()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Hearts, Value.Four);
Card card3 = new Card(Suit.Spades, Value.Five);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Diamonds, Value.Seven);
Card card6 = new Card(Suit.Clubs, Value.King);
Card card7 = new Card(Suit.Diamonds, Value.Ace);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[7]);
}
/// <summary>
/// Tests for HighCard
/// </summary>
[Fact]
public void HighCardTest1()
{
Card card1 = new Card(Suit.Diamonds, Value.Two);
Card card2 = new Card(Suit.Hearts, Value.Five);
Card card3 = new Card(Suit.Spades, Value.Seven);
Card card4 = new Card(Suit.Clubs, Value.Jack);
Card card5 = new Card(Suit.Clubs, Value.Queen);
Card card6 = new Card(Suit.Clubs, Value.King);
Card card7 = new Card(Suit.Clubs, Value.Ace);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[8]);
}
/// <summary>
/// Tests for High Card
/// </summary>
[Fact]
public void HighCardTest2()
{
Card card1 = new Card(Suit.Spades, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Three);
Card card3 = new Card(Suit.Diamonds, Value.Four);
Card card4 = new Card(Suit.Hearts, Value.Five);
Card card5 = new Card(Suit.Diamonds, Value.Ten);
Card card6 = new Card(Suit.Clubs, Value.Jack);
Card card7 = new Card(Suit.Clubs, Value.King);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[8]);
}
/// <summary>
/// Tests for HighCard
/// </summary>
[Fact]
public void HighCardTest3()
{
Card card1 = new Card(Suit.Clubs, Value.Two);
Card card2 = new Card(Suit.Diamonds, Value.Four);
Card card3 = new Card(Suit.Hearts, Value.Six);
Card card4 = new Card(Suit.Spades, Value.Eight);
Card card5 = new Card(Suit.Clubs, Value.Ten);
Card card6 = new Card(Suit.Diamonds, Value.Queen);
Card card7 = new Card(Suit.Hearts, Value.Ace);
Deck<Card> hand = new Deck<Card>();
hand.Add(card1);
hand.Add(card2);
hand.Add(card3);
hand.Add(card4);
hand.Add(card5);
hand.Add(card6);
hand.Add(card7);
byte[] results = new byte[9];
results[0] = 1; // StraightFlush
results[1] = 0; // FourOfAKind
results[2] = 0; // FullHouse
results[3] = 0; // Flush
results[4] = 1; // Straight
results[5] = 0; // ThreeOfAKind
results[6] = 0; // TwoPair
results[7] = 0; // Pair
results[8] = 1; // HighCard
CheckHandSevenCards(hand, results);
Assert.Equal(1, results[8]);
}
/// <summary>
/// Tests that PlayerOne wins with same hand as PlayerOne
/// </summary>
[Fact]
public void PlayerOneWinsPlayerTwoLosesSameHand()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 1; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 1; // TwoPair
playerTwoResults[7] = 0; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Two);
Card card1 = new Card(Suit.Clubs, Value.Three);
Card card2 = new Card(Suit.Clubs, Value.Eight);
Card card3 = new Card(Suit.Clubs, Value.Eight);
Card card4 = new Card(Suit.Hearts, Value.Ten);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Three);
Card card7 = new Card(Suit.Spades, Value.Four);
Card card8 = new Card(Suit.Spades, Value.Eight);
Card card9 = new Card(Suit.Diamonds, Value.Eight);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(1, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that PlayerTwo wins with the same hand as PlayerOne
/// </summary>
[Fact]
public void PlayerOneLosesPlayerTwoWinsSameHand()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 1; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 0; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 1; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 0; // TwoPair
playerTwoResults[7] = 0; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Three);
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Clubs, Value.Five);
Card card3 = new Card(Suit.Clubs, Value.Six);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Three);
Card card7 = new Card(Suit.Spades, Value.Four);
Card card8 = new Card(Suit.Spades, Value.Five);
Card card9 = new Card(Suit.Spades, Value.Ace);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(2, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that PlayerOne wins with a different hand from PlayerTwo
/// </summary>
[Fact]
public void PlayerOneWinsDifferentHands()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 1; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 0; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 0; // TwoPair
playerTwoResults[7] = 1; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Three);
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Clubs, Value.Five);
Card card3 = new Card(Suit.Clubs, Value.Six);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Three);
Card card7 = new Card(Suit.Clubs, Value.Four);
Card card8 = new Card(Suit.Spades, Value.Ace);
Card card9 = new Card(Suit.Spades, Value.Ace);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(1, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that PlayerTwo wins with a different hand from PlayeyOne
/// </summary>
[Fact]
public void PlayerTwoWinsDifferentHands()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 1; // ThreeOfAKind
playerOneResults[6] = 0; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 1; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 0; // TwoPair
playerTwoResults[7] = 0; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Three);
Card card1 = new Card(Suit.Clubs, Value.Three);
Card card2 = new Card(Suit.Clubs, Value.Three);
Card card3 = new Card(Suit.Clubs, Value.Six);
Card card4 = new Card(Suit.Diamonds, Value.Seven);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Three);
Card card7 = new Card(Suit.Spades, Value.Four);
Card card8 = new Card(Suit.Spades, Value.Five);
Card card9 = new Card(Suit.Spades, Value.Seven);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(2, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that Players tie with StraightFlush
/// </summary>
[Fact]
public void TieWithStraightFlush()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 1; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 0; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 1; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 0; // TwoPair
playerTwoResults[7] = 0; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Two);
Card card1 = new Card(Suit.Clubs, Value.Three);
Card card2 = new Card(Suit.Clubs, Value.Four);
Card card3 = new Card(Suit.Clubs, Value.Five);
Card card4 = new Card(Suit.Clubs, Value.Ace);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Three);
Card card7 = new Card(Suit.Spades, Value.Four);
Card card8 = new Card(Suit.Spades, Value.Five);
Card card9 = new Card(Suit.Spades, Value.Ace);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(0, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that PlayerOne wins when both players have FourOfAKind
/// </summary>
[Fact]
public void NoTieWithFourOfAKindPlayerOneWins()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 1; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 0; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 1; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 1; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 0; // TwoPair
playerTwoResults[7] = 0; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Three);
Card card1 = new Card(Suit.Diamonds, Value.Three);
Card card2 = new Card(Suit.Hearts, Value.Three);
Card card3 = new Card(Suit.Spades, Value.Three);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Diamonds, Value.Two);
Card card7 = new Card(Suit.Hearts, Value.Two);
Card card8 = new Card(Suit.Clubs, Value.Two);
Card card9 = new Card(Suit.Spades, Value.Ace);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(1, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that players can tie with TwoPair
/// </summary>
[Fact]
public void TieWithTwoPair()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 1; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 1; // TwoPair
playerTwoResults[7] = 0; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Two);
Card card1 = new Card(Suit.Diamonds, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Six);
Card card3 = new Card(Suit.Clubs, Value.Seven);
Card card4 = new Card(Suit.Diamonds, Value.Seven);
Card card5 = new Card(Suit.Hearts, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Two);
Card card7 = new Card(Suit.Spades, Value.Six);
Card card8 = new Card(Suit.Hearts, Value.Seven);
Card card9 = new Card(Suit.Spades, Value.Seven);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(0, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that PlayerTwo wins while both players have TwoPair
/// </summary>
[Fact]
public void TieBreakWithTwoPairPlayerTwoWins()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 1; // TwoPair
playerOneResults[7] = 0; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 1; // TwoPair
playerTwoResults[7] = 0; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Two);
Card card1 = new Card(Suit.Diamonds, Value.Two);
Card card2 = new Card(Suit.Clubs, Value.Five);
Card card3 = new Card(Suit.Clubs, Value.Seven);
Card card4 = new Card(Suit.Diamonds, Value.Seven);
Card card5 = new Card(Suit.Spades, Value.Three);
Card card6 = new Card(Suit.Clubs, Value.Three);
Card card7 = new Card(Suit.Spades, Value.Four);
Card card8 = new Card(Suit.Hearts, Value.Seven);
Card card9 = new Card(Suit.Spades, Value.Seven);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(2, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that players can tie with Pairs
/// </summary>
[Fact]
public void TieWithPair()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 0; // TwoPair
playerOneResults[7] = 1; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 0; // TwoPair
playerTwoResults[7] = 1; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Two);
Card card1 = new Card(Suit.Clubs, Value.Three);
Card card2 = new Card(Suit.Clubs, Value.Four);
Card card3 = new Card(Suit.Clubs, Value.Seven);
Card card4 = new Card(Suit.Hearts, Value.Seven);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Three);
Card card7 = new Card(Suit.Spades, Value.Four);
Card card8 = new Card(Suit.Diamonds, Value.Seven);
Card card9 = new Card(Suit.Spades, Value.Seven);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(0, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
/// <summary>
/// Tests that PlayerOne withs while both players have same Pair
/// </summary>
[Fact]
public void TieBreakWithPairPlayerOneWins()
{
Deck<Card> playerOneHand = new Deck<Card>();
Deck<Card> playerTwoHand = new Deck<Card>();
byte[] playerOneResults = new byte[9];
playerOneResults[0] = 0; // StraightFlush
playerOneResults[1] = 0; // FourOfAKind
playerOneResults[2] = 0; // FullHouse
playerOneResults[3] = 0; // Flush
playerOneResults[4] = 0; // Straight
playerOneResults[5] = 0; // ThreeOfAKind
playerOneResults[6] = 0; // TwoPair
playerOneResults[7] = 1; // Pair
playerOneResults[8] = 0; // HighCard
byte[] playerTwoResults = new byte[9];
playerTwoResults[0] = 0; // StraightFlush
playerTwoResults[1] = 0; // FourOfAKind
playerTwoResults[2] = 0; // FullHouse
playerTwoResults[3] = 0; // Flush
playerTwoResults[4] = 0; // Straight
playerTwoResults[5] = 0; // ThreeOfAKind
playerTwoResults[6] = 0; // TwoPair
playerTwoResults[7] = 1; // Pair
playerTwoResults[8] = 0; // HighCard
Card card0 = new Card(Suit.Clubs, Value.Three);
Card card1 = new Card(Suit.Clubs, Value.Four);
Card card2 = new Card(Suit.Clubs, Value.Six);
Card card3 = new Card(Suit.Diamonds, Value.Six);
Card card4 = new Card(Suit.Clubs, Value.Seven);
Card card5 = new Card(Suit.Spades, Value.Two);
Card card6 = new Card(Suit.Spades, Value.Three);
Card card7 = new Card(Suit.Spades, Value.Four);
Card card8 = new Card(Suit.Hearts, Value.Six);
Card card9 = new Card(Suit.Spades, Value.Six);
Deck<Card> fakeHandPlayerOne = new Deck<Card>();
fakeHandPlayerOne.Add(card0);
fakeHandPlayerOne.Add(card1);
fakeHandPlayerOne.Add(card2);
fakeHandPlayerOne.Add(card3);
fakeHandPlayerOne.Add(card4);
Deck<Card> fakeHandPlayerTwo = new Deck<Card>();
fakeHandPlayerTwo.Add(card5);
fakeHandPlayerTwo.Add(card6);
fakeHandPlayerTwo.Add(card7);
fakeHandPlayerTwo.Add(card8);
fakeHandPlayerTwo.Add(card9);
Assert.Equal(1, GetWinner(fakeHandPlayerOne, playerOneResults, fakeHandPlayerTwo, playerTwoResults));
}
}
}
|
using Discount.Grpc.Protos.v1;
using System.Threading.Tasks;
namespace Basket.Core.Interfaces
{
public interface IDiscountGrpcService
{
Task<CouponResponse> GetDiscount(string productId);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace AnyTest.ClientAuthentication
{
/// <summary>
/// \~english A model of a login result
/// \~ukrainian Модель результату входу користувача
/// </summary>
public class LoginResult
{
/// <summary>
/// \~english Identifies succefull login
/// \~ukrainian Позначає успішний вхід
/// </summary>
public bool Sussessfull { get; set; }
/// <summary>
/// \~english Contains data about login errors
/// \~ukrainian Містить дані про помилки входу
/// </summary>
public string Error { get; set; }
/// <summary>
/// \~english A JWT token for a user
/// \~ukrainian JWT токен корисувача
/// </summary>
public string Token { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data.Collections;
namespace Microsoft.ServiceFabric.Data
{
public class Transaction : ITransaction
{
public Transaction()
{
}
public async Task CommitAsync()
{
var store = Store as ICommitable;
if (store != null)
{
await store.CommitTransactionAsync(this);
}
}
public void Dispose()
{
}
public void Abort()
{
Store = null;
TransactionObject = null;
}
internal object TransactionObject { get; set; }
internal ICommitable Store { get; set; }
}
}
|
using Framework.Core.Common;
using Framework.Core.Config;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.User
{
public class UserList: UserBasePage
{
private static string _url = AppConfig.OberonBaseUrl + "User/List?tenantId="; //"5037";
#region Page Element Declarations
public IWebElement AddLink { get { return _driver.FindElement(By.CssSelector(".add")); } }
public IWebElement UserDetailLink { get { return _driver.FindElement(By.XPath("//a[contains(@href, '/User/Detail/')]")); } }
#endregion
public UserList(Driver driver) : base(driver) { }
#region Methods
/// <summary>
/// navigates directly to the user list page by url
/// </summary>
public void GoToThisPageDirectly()
{
_driver.GoToPage(_url);
}
/// <summary>
/// clicks add link
/// </summary>
public void ClickAddLink()
{
_driver.Click(AddLink);
}
/// <summary>
/// returns user id by parsing the url
/// </summary>
public string GetUserId()
{
_driver.Click(UserDetailLink);
string url = _driver.GetUrl();
string[] urlSplit = url.Split('/');
return urlSplit[urlSplit.Length - 1];
}
#endregion
}
}
|
using Project371.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assig_1.GUI
{
/// <summary>
/// Class that acts as a container for all the gui elements
/// </summary>
class GUIManager
{
/// <summary>
/// Private instance of the singleton
/// </summary>
private static GUIManager instance;
/// <summary>
/// Access the singleton
/// </summary>
public static GUIManager Instance
{
get
{
if (instance == null)
instance = new GUIManager();
return instance;
}
}
/// <summary>
/// The list of guitext objects
/// </summary>
private List<GUIText> allText;
/// <summary>
/// Private constructor
/// </summary>
private GUIManager()
{
allText = new List<GUIText>();
}
/// <summary>
/// Add guitext to the list
/// </summary>
/// <param name="guit">The guitext to be added to the list</param>
public void AddGUIText(GUIText guit)
{
allText.Add(guit);
}
/// <summary>
/// Clear all the guitexts from the list
/// </summary>
public void Clear()
{
allText.Clear();
}
/// <summary>
/// Return the list of guitext objects
/// </summary>
public List<GUIText> GetAllText()
{
return allText;
}
}
}
|
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 Library_App.Class_Lib;
namespace Library_App.Forms
{
public partial class DeleteStudentForm : Form
{
public DeleteStudentForm()
{
InitializeComponent();
}
private void Submit_btn_Click(object sender, EventArgs e)
{
if (Username_TB.Text == "")
{
MessageBox.Show("Please Enter Username");
return;
}
Student S= Student.LoadByUsername(Username_TB.Text);
if (S == null)
{
MessageBox.Show("Username doesn't exist");
}
else
{
S.Delete_Student();
this.Close();
}
}
private void ISBN_lbl_Click(object sender, EventArgs e)
{
}
private void Username_TB_TextChanged(object sender, EventArgs e)
{
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.