text stringlengths 13 6.01M |
|---|
using EP.CrudModalDDD.Domain.DTO;
using EP.CrudModalDDD.Domain.Entities;
namespace EP.CrudModalDDD.Domain.Interfaces.Repository
{
public interface ICidadeRepository : IRepository<Cidade>
{
Cidade BuscarPorCodigoIbge(string codigoIbge);
Cidade ObterPorNome(string nome);
Paged<Cidade> ObterTodos(string nome, int pageSize, int pageNumber);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHit : MonoBehaviour
{
private Animator enemyAnim;
void Start()
{
enemyAnim = GetComponent<Animator>();
}
void OnTriggerEnter2D(Collider2D player)
{
if (player.CompareTag("Player"))
{
StartCoroutine(player.GetComponent<PlayerController>().Death());
if (!gameObject.CompareTag("Flame"))
enemyAnim.SetBool("PlayerHit", true);
}
}
void OnTriggerExit2D(Collider2D player)
{
if (player.CompareTag("Player"))
{
if (!gameObject.CompareTag("Flame"))
{
enemyAnim.SetBool("PlayerHit", false);
}
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using RMAT3.Models;
namespace RMAT3.Data.Mapping
{
public class ObjectControl_1Map : EntityTypeConfiguration<ObjectControl_1>
{
public ObjectControl_1Map()
{
// Primary Key
HasKey(t => t.ObjectControlId);
// Properties
Property(t => t.AddedByUserId)
.IsRequired()
.HasMaxLength(20);
Property(t => t.AddTs)
.IsRequired()
.IsFixedLength()
.HasMaxLength(8)
.IsRowVersion();
Property(t => t.UpdatedByUserId)
.IsRequired()
.HasMaxLength(20);
Property(t => t.UpdatedCommentTxt)
.HasMaxLength(500);
Property(t => t.ObjectTxt)
.HasMaxLength(100);
Property(t => t.ControlNm)
.HasMaxLength(50);
// Table & Column Mappings
ToTable("ObjectControl_1", "ODS");
Property(t => t.ObjectControlId).HasColumnName("ObjectControlId");
Property(t => t.AddedByUserId).HasColumnName("AddedByUserId");
Property(t => t.AddTs).HasColumnName("AddTs");
Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId");
Property(t => t.UpdatedCommentTxt).HasColumnName("UpdatedCommentTxt");
Property(t => t.UpdatedTs).HasColumnName("UpdatedTs");
Property(t => t.IsActiveInd).HasColumnName("IsActiveInd");
Property(t => t.EffectiveFromDt).HasColumnName("EffectiveFromDt");
Property(t => t.EffectiveToDt).HasColumnName("EffectiveToDt");
Property(t => t.ObjectTxt).HasColumnName("ObjectTxt");
Property(t => t.ControlNm).HasColumnName("ControlNm");
}
}
}
|
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Linq;
/*
Взаимодействие с файловой системой.
1. В файле записана непустая последовательность целых чисел,
являющихся числами Фибоначчи. Приписать еще столько же чисел этой последовательности.
2. Сложить два целых числа А и В.
-Входные данные:
В единственной строке входного файла INPUT.TXT записано два натуральных числа через пробел.
-Выходные данные:
В единственную строку выходного файла OUTPUT.TXT нужно вывести одно целое число — сумму чисел А и В.
*/
namespace thirteenth_homework_files
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\n----------------------1---------------------\n");
string fibonacciFirstText = "0, 1, 1, 2, 3, 5, ";
string fibonacciSecondText = "8, 13, 21, 34, 55, 89";
string path = "text.txt";
string result = "";
if (!File.Exists(path))
{
var stream = File.Create(path);
stream.Close();
}
else
{
//то удаляем и заново создаем
FileInfo temp = new FileInfo(path);
temp.Delete();
var stream = File.Create(path);
stream.Close();
}
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
byte[] data = Encoding.UTF8.GetBytes(fibonacciFirstText);
fileStream.Write(data, 0, data.Length);
}
using (FileStream fileStream = File.OpenRead(path))
{
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
result += Encoding.UTF8.GetString(buffer);
Console.WriteLine($"первая часть: {result}");
}
//File.AppendAllText(path, fibonacciSecondText);
using (StreamWriter writer = File.AppendText(path))
{
writer.WriteLine(fibonacciSecondText);
result += fibonacciSecondText;
}
Console.WriteLine($"всё: {result}");
Console.WriteLine("\n----------------------2---------------------\n");
int firstNumber = 3;
int secondNumber = 5;
string input = "Input.txt";
string output = "Output.txt";
//инициализация input.txt
if (!File.Exists(input))
{
var stream = File.Create(input);
stream.Close();
}
else
{
FileInfo temp = new FileInfo(input);
temp.Delete();
var stream = File.Create(input);
stream.Close();
}
using (StreamWriter fileWriter = new StreamWriter(input))
{
string inputText = $"{firstNumber} {secondNumber}";
fileWriter.WriteLine(inputText);
}
//выведем из файла input.txt строку
string twoNumbers = null;
using (StreamReader fileReader = new StreamReader(input))
{
twoNumbers = fileReader.ReadToEnd();
Console.WriteLine($"Вывод 2-ух чисел из файла Input.txt в виде строки: {twoNumbers}");
}
//Превратим строку в List<int>:
List<int> numbers = new List<int>();
Console.Write("наши числа в int: ");
for (int i = 0; i < twoNumbers.Length; i++)
{
if (Char.IsNumber(twoNumbers[i]))
{
int numberToInt = (int)Char.GetNumericValue(twoNumbers[i]);
//или:
//int numberToInt = Convert.ToInt32(twoNumbers[i] - '0');
numbers.Add(numberToInt);
Console.Write(numberToInt +" ");
}
}
var sum = numbers.Sum();
Console.WriteLine($"\n\nсумма равна {sum}, затем запись в файл Output.txt");
//инициализация output.txt
if (!File.Exists(output))
{
var stream = File.Create(output);
stream.Close();
}
else
{
FileInfo temp = new FileInfo(output);
temp.Delete();
var stream = File.Create(output);
stream.Close();
}
using (StreamWriter fileWriter = new StreamWriter(output))
{
string outputText = $"{sum.ToString()}";
fileWriter.WriteLine(outputText);
}
using (StreamReader fileReader = new StreamReader(output))
{
string sumNumber = fileReader.ReadToEnd();
Console.WriteLine($"\nВывод из файла Output.txt: {sumNumber}");
}
Console.ReadKey();
}
}
} |
namespace VideoServiceBL.Enums
{
public enum Role : byte
{
Admin = 1,
User
}
} |
using AddressBook.Contract;
using AddressBook.Interface;
using AddressBook.Services;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace AddressBook.Test.Services
{
[TestFixture]
[Parallelizable]
[ExcludeFromCodeCoverage]
public class AddressServicesTests
{
private Mock<IFileHelper> _fileHelperMock;
private AddressService addressServices;
[SetUp]
public void SetUp()
{
_fileHelperMock = new Mock<IFileHelper>();
_fileHelperMock.Setup(x => x.ReadFile(It.IsAny<string>())).ReturnsAsync(GetJson);
addressServices = new AddressService(_fileHelperMock.Object);
}
[Test]
public async Task GetAddress_Returns_Address_List()
{
//Act
var address = await addressServices.GetAddress();
//Assert
Assert.IsInstanceOf<IEnumerable<Address>>(address);
}
[Test]
public async Task GetAddress_Calls_ReadFile_Method()
{
// Act
await addressServices.GetAddress();
// Assert
_fileHelperMock.Verify(x => x.ReadFile(It.IsAny<string>()), Times.Once);
}
private string GetJson()
{
var path = System.AppContext.BaseDirectory;
var streamReader = new StreamReader(@path + "Address.json", Encoding.UTF8);
return streamReader.ReadToEnd();
}
}
}
|
using Microsoft.Practices.Unity;
using MKModel;
using MKService;
using MKViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MKView
{
public class Container : UnityContainerExtension
{
public Container()
{
}
protected override void Initialize()
{
ServiceTypeProvider.Instance.UseService = true;
ServiceTypeProvider.Instance.EndPoint = MK2DStartupSettings.WstServiceEndPoint;
this.Container.RegisterType<IArmyBuilder, ArmyBuilder>(new ContainerControlledLifetimeManager());
this.Container.RegisterType<IBattleGround, BattleGround>(new ContainerControlledLifetimeManager());
this.Container.RegisterType<IGameViewModel, GameViewModel>(new ContainerControlledLifetimeManager());
this.Container.RegisterType<IGameModel>(new ContainerControlledLifetimeManager(), new InjectionFactory(x => ServiceTypeProvider.Instance.Game));
this.Container.RegisterType<IUserModel>(new ContainerControlledLifetimeManager(), new InjectionFactory(x => ServiceTypeProvider.Instance.LoggedInUser));
this.Container.RegisterType<IUserCollection>(new ContainerControlledLifetimeManager(), new InjectionFactory(x => ServiceTypeProvider.Instance.UserCollection));
this.Container.RegisterType<IGameModels>(new ContainerControlledLifetimeManager(), new InjectionFactory(x => ServiceTypeProvider.Instance.Games));
this.Container.RegisterType<IUserViewModel, UserViewModel>(new ContainerControlledLifetimeManager());
this.Container.RegisterType<ILoginViewModel, LoginViewModel>(new ContainerControlledLifetimeManager());
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using CommonTypes;
using CommonTypes.NameRegistry;
using CommonTypes.Transactions;
namespace PADI_DSTM
{
/*
* Lib created to be linked to every client application that uses PADI-DSTM
*/
public class PadiDstm
{
/* Variavel com o identificador da transacao actual */
private static int _currentTxInt;
/* Variavel com a lista de servidores */
private static Dictionary<int, RegistryEntry> _serverList = new Dictionary<int, RegistryEntry>();
private static int _version;
/*
* INTERACTION WITH SERVERS
*/
/*
* This method is called only once by the application and initializaes de PADI-DSTM library
*/
public static bool Init()
{
IDictionary properties = new Hashtable();
properties["timeout"] = Config.InvocationTimeout;
var channelServ = new TcpChannel(properties, null, null);
ChannelServices.RegisterChannel(channelServ, false);
Console.WriteLine("[Client.Init] Entering Client.Init");
return UpdateServers();
}
internal static bool UpdateServers()
{
try
{
/* 1. Tem de ser criada a ligação com o servidor principal */
var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
/* 2. Temos que obter a list de servidores do sistema dada pelo MS */
_serverList = mainServer.ListServers();
_version = mainServer.GetVersion();
/* DEBUG PROPOSES*/
for (int i = 0; i < _serverList.Count; i++)
{
Console.WriteLine("[Client.Init] Server {0}: {1}", i, _serverList[i]);
}
}
catch (Exception e)
{
Console.WriteLine("[Client.Init] Exception caught : {0}", e.StackTrace);
return false;
}
return true;
}
/*
* This method starts a new transaction and returns a boolean value indicating whether the
* operation succeeded. This method may throw a TxException
*/
public static bool TxBegin()
{
Console.WriteLine("[Client.TxBegin] Entering Client.TxBegin");
try
{
/* 1. Tem de ser criada a ligação com o servidor principal (Duvida: todas as transacoes vao primeiro ao main server certo) */
var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
/* 2. Chamar o metodo do servidor que dá inicio a transação */
_currentTxInt = mainServer.StartTransaction();
/* DEBUG PROPOSES */
Console.WriteLine("[Client.TxBegin] txInt: {0}", _currentTxInt);
}
catch (Exception e)
{
Console.WriteLine("[Client.TxBegin] Exception caught : {0}", e.StackTrace);
return false;
}
return true;
}
/*
* This method attempts to commit the current transaction and returns a boolean value
* indicating whether the operation succeded. This method may throw a TxException
*/
public static bool TxCommit()
{
/* 1. Chamar o metodo do servidor que dá inicio ao commit da transação */
Console.WriteLine("[Client.TxCommit] Entering Client.TxCommit");
try
{
/* 1. Tem de ser criada a ligação com o servidor principal (Duvida: todas as transacoes vao primeiro ao main server certo) */
var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
/* 2. Chamar o metodo do servidor que dá inicio ao commit da transação */
mainServer.CommitTransaction(_currentTxInt);
}
catch (Exception e)
{
Console.WriteLine("[Client.TxCommit] Exception caught : {0}", e.StackTrace);
return false;
}
return true;
}
/*
* This method aborts the current transaction and returns a boolean value indicating
* whether the operation succeeded. This method may throw a TxException
*/
public static bool TxAbort()
{
/* 1. Chamar o metodo do servidor que aborta current transação*/
Console.WriteLine("[Client.TxAbort] Entering Client.TxAbort");
try
{
/* 1. Tem de ser criada a ligação com o servidor principal (Duvida: todas as transacoes vao primeiro ao main server certo) */
var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
/* 2. Chamar o metodo do servidor que dá inicio ao commit da transação */
mainServer.AbortTransaction(_currentTxInt);
}
catch (Exception e)
{
Console.WriteLine("[Client.TxAbort] Exception caught : {0}", e.StackTrace);
return false;
}
return true;
}
/*
* This method makes all nodes in the system dump to their output their current state
*/
public static bool Status()
{
/* Se não se pode enviar a lista de Servers que o cliente já conhece à priori (devido ao Init()) a
* melhor solução será pedir ao Main Server que por sua vez vai perguntar a todos os servidores
* conhecidos qual o seu estado */
Console.WriteLine("[Client.Status] Entering Status");
try
{
/* 1. Tem de ser criada a ligação com o servidor principal */
var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
/* 2. Temos que obter a list dos status dos servidores */
bool ex = mainServer.GetServerStatus();
/* DEBUG PROPOSES */
Console.WriteLine("[Servers.Status] {0}", ex);
}
catch (Exception e)
{
Console.WriteLine("[Client.Status] Exception : {0}", e.StackTrace);
return false;
}
return true;
}
/*
* This method makes the server at the URL stop responding to external calls except for
* a Recover call
*/
public static bool Fail(String url)
{
Console.WriteLine("[Client.Fail] Entering Fail");
bool fail;
try
{
/* 1. Deverá ser criada uma connecção com o servidor indicado no "url" */
var server = (IServer) Activator.GetObject(typeof (IServer), url);
/* 2. Chamar metodo presente nele que congela ele proprio */
fail = server.Fail();
}
catch (Exception e)
{
Console.WriteLine("[Client.Fail] Exception : {0}", e.StackTrace);
return false;
}
return fail;
}
/*
* This method makes the server at URL stop responding to external calls but it
* maintains all calls for later reply, as if the communication to that server were
* only delayed. A server in freeze mode responds immediately only to a Recover
* call (see below), which triggers the execution of the backlog of operations
* accumulated since the Freeze call
*/
public static bool Freeze(String url)
{
Console.WriteLine("[Client.Freeze] Entering Freeze");
bool freeze;
try
{
/* 1. Deverá ser criada uma connecção com o servidor indicado no "url" */
var server = (IServer) Activator.GetObject(typeof (IServer), url);
/* 2. Chamar metodo presente nele que congela ele proprio */
freeze = server.Freeze();
}
catch (Exception e)
{
Console.WriteLine("[Client.Freeze] Exception : {0}", e.StackTrace);
return false;
}
return freeze;
}
/*
* This method creates a new shared object with the given uid. Returns null if the
* object already exists.
*/
public static bool Recover(String url)
{
Console.WriteLine("[Client.Recover] Entering Recover");
bool recover;
try
{
/* 1. Deverá ser criada uma connecção com o servidor indicado no "url" */
var server = (IServer) Activator.GetObject(typeof (IServer), url);
/* 2. Chamar metodo presente nele que renicia-o */
recover = server.Recover();
}
catch (Exception e)
{
Console.WriteLine("[Client.Recover] Exception : {0}", e.StackTrace);
return false;
}
return recover;
}
/*
* INTERACTION WITH SHARED DISTRIBUTED OBJECTS (PADINT)
*/
/*
* This method creates a new shared object with the given uid. Returns null if
* the object already exists
*/
public static PadInt CreatePadInt(int uid)
{
Console.WriteLine("[Client.CreatePadInt] Entering CreatePadInt");
PadInt newPadInt = null;
/* 2. Verificar se o tem e caso n tiver, cria-lo e retorna-o; caso ja exista retorna null */
try
{
newPadInt = GetPadInt(uid);
newPadInt.Read(); // If it reads the padint is already created
Console.WriteLine("[Client.AccessPadInt] PadInt {0} already exits", uid);
}
catch (TxException)
{
Debug.Assert(newPadInt != null, "newPadInt != null");
newPadInt.Write(0); // Initialize PadInt
return newPadInt;
}
catch (Exception e)
{
Console.WriteLine("[Client.CreatePadInt] Exception : {0}", e.StackTrace);
return null;
}
return null;
}
/*
* This method returns a reference to a shared object with the given uid. Returns
* null if the object does not exist already
*/
public static PadInt AccessPadInt(int uid)
{
Console.WriteLine("[Client.AccessPadInt] Entering AccessPadInt");
PadInt accPadInt;
/* 2. Verificar se o tem e caso o tiver, devolve-lo; caso n tiver retornar null */
try
{
accPadInt = GetPadInt(uid);
accPadInt.Read(); // If it doesn't read the padint doesn't exist
}
catch (TxException)
{
Console.WriteLine("[Client.AccessPadInt] PadInt {0} doesn't exits", uid);
return null;
}
catch (Exception e)
{
Console.WriteLine("[Client.AccessPadInt] Exception : {0}", e.StackTrace);
return null;
}
return accPadInt;
}
internal static PadInt GetPadInt(int uid)
{
int serverNum = ConsistentHashCalculator.GetServerIdForPadInt(_serverList.Count, uid);
RegistryEntry serverEntry;
if (_serverList.TryGetValue(serverNum, out serverEntry) && !serverEntry.Active)
{
serverNum = GetBackupServer(serverNum);
}
string serverUrl = Config.GetServerUrl(serverNum);
var server = (IServer) Activator.GetObject(typeof (IServer), serverUrl);
return new PadInt(_currentTxInt, uid, server, _version);
}
internal static PadInt GetBackupPadInt(int uid)
{
int serverNum = GetBackupServer(uid);
string serverUrl = Config.GetServerUrl(serverNum);
var server = (IServer) Activator.GetObject(typeof (IServer), serverUrl);
return new PadInt(_currentTxInt, uid, server, _version);
}
private static int GetBackupServer(int uid)
{
RegistryEntry serverEntry = _serverList[uid];
if (serverEntry.FaultDetection.Count > 0)
{
return serverEntry.FaultDetection.Max();
}
if (serverEntry.Parent != -1)
{
return serverEntry.Parent;
}
Console.WriteLine("We should never have a server without backup! Is it the first one?");
return -1;
}
}
} |
using System.ComponentModel.DataAnnotations;
namespace RankingsTable.EF.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public class SeasonPlayer
{
public SeasonPlayer()
{
this.HomeFixtures = new HashSet<Fixture>();
this.AwayFixtures = new HashSet<Fixture>();
}
[Key]
public Guid Id { get; set; }
[Required]
public Guid SeasonId { get; set; }
[Required]
public Guid PlayerId { get; set; }
public virtual Season Season { get; set; }
public virtual Player Player { get; set; }
[InverseProperty("HomePlayer")]
public virtual ICollection<Fixture> HomeFixtures { get; set; }
[InverseProperty("AwayPlayer")]
public virtual ICollection<Fixture> AwayFixtures { get; set; }
}
}
|
using System;
using PDV.CONTROLER.FuncoesRelatorios;
using System.Data;
using PDV.DAO.Entidades.PDV;
using System.Collections.Generic;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.Entidades;
namespace PDV.REPORTS.Reports.PedidoVendaTermica
{
public partial class ReciboPedidoVenda : DevExpress.XtraReports.UI.XtraReport
{
private decimal IDVENDA;
public ReciboPedidoVenda(decimal IDVenda)
{
InitializeComponent();
IDVENDA = IDVenda;
}
private void ReciboPedidoVenda_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
DataTable dt = FuncoesPedidoVendaTermica.GetPedidosVendaTermica(IDVENDA);
List<DuplicataNFCe> duplicataNFCe = FuncoesItemDuplicataNFCe.GetPagamentosPorVenda(IDVENDA);
String Pagamento = "";
foreach (var item in duplicataNFCe)
{
FormaDePagamento formaDePagamento = FuncoesFormaDePagamento.GetFormaDePagamento(item.IDFormaDePagamento);
Pagamento += $@"{formaDePagamento.Descricao.PadRight(20)} {item.Valor.ToString("c2")}
";
}
xrLabelPagamentos.Text = Pagamento;
ovSR_ListaItens.ReportSource = new ReciboPedidoVenda_Itens();
dt.TableName = "DADOS";
ovDS_Dados.Tables.Clear();
ovDS_Dados.Tables.Add(dt);
}
private void xrLabel16_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
xrLabel16.Text = DateTime.Now.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factorial_Recursion
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the value to find the Factorial in recursion Method");
string number = Console.ReadLine();
int num = Convert.ToInt32(number);
int result = Factorial(num);
Console.WriteLine("Factrial value is:{0}", result);
Console.Read();
}
private static int Factorial(int num)
{
if (num == 0)
{
return 1;
}
return num * Factorial(num - 1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CheeseSystem
{
interface IProductionLine
{
Production Produce();
}
}
|
/*
Copyright 2015 Manus VR
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
namespace ManusMachina {
/// <summary>
/// ManusController class to load/unload Manus library.
/// To be assigned to an empty GameObject
/// </summary>
public class Manus {
internal const int ERROR = -1;
internal const int SUCCESS = 0;
internal const int INVALID_ARGUMENT = 1;
internal const int OUT_OF_RANGE = 2;
internal const int DISCONNECTED = 3;
// UNITY_STANDALONE //Linux, OSX, Windows
[DllImport("Manus", CallingConvention = CallingConvention.Cdecl)]
internal static extern int ManusGetData(GLOVE_HAND hand, ref GLOVE_DATA data, uint timeout = 0);
[DllImport("Manus", CallingConvention = CallingConvention.Cdecl)]
internal static extern int ManusGetSkeletal(GLOVE_HAND hand, ref GLOVE_SKELETAL model, uint timeout = 0);
[DllImport("Manus", CallingConvention = CallingConvention.Cdecl)]
internal static extern int ManusSetHandedness(GLOVE_HAND hand, bool right_hand);
[DllImport("Manus", CallingConvention = CallingConvention.Cdecl)]
internal static extern int ManusCalibrate(GLOVE_HAND hand, bool gyro = true, bool accel = true, bool fingers = false);
[DllImport("Manus", CallingConvention = CallingConvention.Cdecl)]
internal static extern int ManusSetVibration(GLOVE_HAND hand, float power);
[DllImport("Manus", CallingConvention = CallingConvention.Cdecl)]
internal static extern int ManusInit();
[DllImport("Manus", CallingConvention = CallingConvention.Cdecl)]
internal static extern int ManusExit();
// UNITY_STANDALONE
}
#pragma warning disable 0649 // Disable 'field never assigned' warning
/// <summary>
/// Quaternion representing an orientation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct GLOVE_QUATERNION {
public float w, x, y, z;
internal GLOVE_QUATERNION(float w, float x, float y, float z) {
this.w = w;
this.x = x;
this.y = y;
this.z = z;
}
internal GLOVE_QUATERNION(float[] a) {
this.w = a[0];
this.x = a[1];
this.y = a[2];
this.z = a[3];
}
}
/// <summary>
/// Three element vector, can either represent a rotation, translation or acceleration.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct GLOVE_VECTOR {
public float x, y, z;
internal GLOVE_VECTOR(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
internal GLOVE_VECTOR(float[] a) {
this.x = a[0];
this.y = a[1];
this.z = a[2];
}
}
/// <summary>
/// Pose structure representing an orientation and position.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
struct GLOVE_POSE {
public GLOVE_QUATERNION orientation;
public GLOVE_VECTOR position;
}
/// <summary>
/// Raw data packet from the glove.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct GLOVE_DATA {
/// <summary>
/// Linear acceleration vector in Gs.
/// </summary>
public GLOVE_VECTOR Acceleration;
/// <summary>
/// Orientation in euler angles.
/// </summary>
public GLOVE_VECTOR Euler;
/// <summary>
/// Orientation in quaternions.
/// </summary>
public GLOVE_QUATERNION Quaternion;
/// <summary>
/// Normalized bend value for each finger ranging from 0 to 1.
/// </summary>
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 5)]
public float[] Fingers;
/// <summary>
/// Sequence number of the data packet.
/// </summary>
uint PacketNumber;
}
/// <summary>
/// Structure containing the pose of each bone in the thumb.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
struct GLOVE_THUMB {
public GLOVE_POSE metacarpal, proximal,
distal;
}
/// <summary>
/// Structure containing the pose of each bone in a finger.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
struct GLOVE_FINGER {
public GLOVE_POSE metacarpal, proximal,
intermediate, distal;
}
/// <summary>
/// Skeletal model of the hand which contains a pose for the palm and all the bones in the fingers.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
struct GLOVE_SKELETAL {
public GLOVE_POSE palm;
public GLOVE_FINGER thumb, index, middle,
ring, pinky;
}
#pragma warning restore 0649
/// <summary>
/// Indicates which hand is being queried for.
/// </summary>
public enum GLOVE_HAND {
GLOVE_LEFT = 0,
GLOVE_RIGHT,
};
} |
using PlatformRacing3.Common.Level;
namespace PlatformRacing3.Web.Responses.Procedures;
public class DataAccessGetLockedLevelResponsee : DataAccessDataResponse<LevelData>
{
private DataAccessGetLockedLevelResponsee()
{
}
public DataAccessGetLockedLevelResponsee(LevelData levelData)
{
this.Rows = new List<LevelData>(1)
{
levelData,
};
}
} |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using RealEstate.BusinessObjects;
namespace RealEstate.DataAccess
{
public class LandDA
{
#region ***** Init Methods *****
public LandDA()
{
}
#endregion
#region ***** Get Methods *****
/// <summary>
///
/// </summary>
/// <returns></returns>
public Land Populate(IDataReader myReader)
{
Land obj = new Land();
obj.LandID = (int) myReader["LandID"];
obj.LandTypeID = (int) myReader["LandTypeID"];
obj.RealEstateOwnersID = (int) myReader["RealEstateOwnersID"];
obj.RealEstateOwnersTypeID = (int) myReader["RealEstateOwnersTypeID"];
obj.RealEstateID = (int) myReader["RealEstateID"];
obj.Description = (string) myReader["Description"];
obj.Address = (string) myReader["Address"];
obj.Price = (double) myReader["Price"];
obj.TotalArea = (double) myReader["TotalArea"];
obj.Image1 = (string) myReader["Image1"];
obj.Image2 = (string) myReader["Image2"];
return obj;
}
/// <summary>
/// Get Land by landid
/// </summary>
/// <param name="landid">LandID</param>
/// <returns>Land</returns>
public Land GetByLandID(int landid)
{
using (IDataReader reader = SqlHelper.ExecuteReader(Data.ConnectionString, CommandType.StoredProcedure, "sproc_Land_GetByLandID", Data.CreateParameter("LandID", landid)))
{
if (reader.Read())
{
return Populate(reader);
}
return null;
}
}
/// <summary>
/// Get all of Land
/// </summary>
/// <returns>List<<Land>></returns>
public List<Land> GetList()
{
using (IDataReader reader = SqlHelper.ExecuteReader(Data.ConnectionString, CommandType.StoredProcedure, "sproc_Land_Get"))
{
List<Land> list = new List<Land>();
while (reader.Read())
{
list.Add(Populate(reader));
}
return list;
}
}
/// <summary>
/// Get DataSet of Land
/// </summary>
/// <returns>DataSet</returns>
public DataSet GetDataSet()
{
return SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Land_Get");
}
/// <summary>
/// Get all of Land paged
/// </summary>
/// <param name="recperpage">record per page</param>
/// <param name="pageindex">page index</param>
/// <returns>List<<Land>></returns>
public List<Land> GetListPaged(int recperpage, int pageindex)
{
using (IDataReader reader = SqlHelper.ExecuteReader(Data.ConnectionString, CommandType.StoredProcedure, "sproc_Land_GetPaged"
,Data.CreateParameter("recperpage", recperpage)
,Data.CreateParameter("pageindex", pageindex)))
{
List<Land> list = new List<Land>();
while (reader.Read())
{
list.Add(Populate(reader));
}
return list;
}
}
/// <summary>
/// Get DataSet of Land paged
/// </summary>
/// <param name="recperpage">record per page</param>
/// <param name="pageindex">page index</param>
/// <returns>DataSet</returns>
public DataSet GetDataSetPaged(int recperpage, int pageindex)
{
return SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Land_GetPaged"
,Data.CreateParameter("recperpage", recperpage)
,Data.CreateParameter("pageindex", pageindex));
}
#endregion
#region ***** Add Update Delete Methods *****
/// <summary>
/// Add a new Land within Land database table
/// </summary>
/// <param name="obj">Land</param>
/// <returns>key of table</returns>
public int Add(Land obj)
{
DbParameter parameterItemID = Data.CreateParameter("LandID", obj.LandID);
parameterItemID.Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Land_Add"
,parameterItemID
,Data.CreateParameter("LandTypeID", obj.LandTypeID)
,Data.CreateParameter("RealEstateOwnersID", obj.RealEstateOwnersID)
,Data.CreateParameter("RealEstateOwnersTypeID", obj.RealEstateOwnersTypeID)
,Data.CreateParameter("RealEstateID", obj.RealEstateID)
,Data.CreateParameter("Description", obj.Description)
,Data.CreateParameter("Address", obj.Address)
,Data.CreateParameter("Price", obj.Price)
,Data.CreateParameter("TotalArea", obj.TotalArea)
,Data.CreateParameter("Image1", obj.Image1)
,Data.CreateParameter("Image2", obj.Image2)
);
return (int)parameterItemID.Value;
}
/// <summary>
/// updates the specified Land
/// </summary>
/// <param name="obj">Land</param>
/// <returns></returns>
public void Update(Land obj)
{
SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Land_Update"
,Data.CreateParameter("LandID", obj.LandID)
,Data.CreateParameter("LandTypeID", obj.LandTypeID)
,Data.CreateParameter("RealEstateOwnersID", obj.RealEstateOwnersID)
,Data.CreateParameter("RealEstateOwnersTypeID", obj.RealEstateOwnersTypeID)
,Data.CreateParameter("RealEstateID", obj.RealEstateID)
,Data.CreateParameter("Description", obj.Description)
,Data.CreateParameter("Address", obj.Address)
,Data.CreateParameter("Price", obj.Price)
,Data.CreateParameter("TotalArea", obj.TotalArea)
,Data.CreateParameter("Image1", obj.Image1)
,Data.CreateParameter("Image2", obj.Image2)
);
}
/// <summary>
/// Delete the specified Land
/// </summary>
/// <param name="landid">LandID</param>
/// <returns></returns>
public void Delete(int landid)
{
SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Land_Delete", Data.CreateParameter("LandID", landid));
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
CharacterController charController;
[SerializeField] float jumpSpeed = 20.0f;
[SerializeField] float gravity = 1.0f;
float yVelocity = 0.0f;
[SerializeField] float moveSpeed = 5.0f;
public float h;
public float v;
public Animator anim; //Variables that are stating the character controller, jumpSpeed, gravity, yVelocity, moveSpeed, horizontal and vertical
void Start()
{
charController = GetComponent<CharacterController>();
anim = GetComponentInChildren<Animator>(); //Sets up the character controller and the animator
}
void Update()
{
h = Input.GetAxis("Horizontal");
v = Input.GetAxis("Vertical");
anim.SetFloat("Speed", v);
anim.SetFloat("Direction", h);
Vector3 direction = new Vector3(h, 0, v);
Vector3 velocity = direction * moveSpeed;
if (charController.isGrounded)
{
if (Input.GetButtonDown("Jump"))
{
anim.SetTrigger("Jump");
yVelocity = jumpSpeed;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
velocity = transform.TransformDirection(velocity);
charController.Move(velocity * Time.deltaTime);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace DataLayer.Conexion
{
public class Conexion : IOperacionesConexion
{
#region Elementos privados
private SqlConnection sqlCnn;
private SqlDataAdapter sqlDatAdapt;
private SqlDataReader sqlDatRead;
private SqlCommand sqlCmd;
private SqlTransaction sqlTran;
public Exception errorOcurred;
#endregion Elementos privados
#region Propiedades
/// <summary>
/// Obtiene o establece el comando y la conexión de base de datos que se utilizan para rellenar System.Data.DataSet y actualizar el origen de datos.
/// </summary>
public SqlDataAdapter propSqlDatAdapt
{
get { return sqlDatAdapt; }
set { sqlDatAdapt = value; }
}
/// <summary>
/// Obtiene o establece el modo de lectura de una secuencia de filas de datos sólo avance de un origen de datos.
/// </summary>
public SqlDataReader propSqlDatRead
{
get { return sqlDatRead; }
set { sqlDatRead = value; }
}
/// <summary>
/// Obtiene o establece un comando SQL que se va a ejecutar en un origen de datos.
/// </summary>
public SqlCommand propSqlCmd
{
get { return sqlCmd; }
set { sqlCmd = value; }
}
/// <summary>
/// Obtiene o establece la cadena de conexión
/// </summary>
public String cadenaConexion { get; set; }
private int timeOut;
public int TimeOut { get { return timeOut; } }
public DAOFactory.TipoConexion tipoConexion { get; set; }
#endregion Propiedades
#region Constructores
public Conexion()
{
}
public Conexion(DAOFactory.TipoConexion tipoConexion)
{
this.tipoConexion = tipoConexion;
}
#endregion Constructores
#region Métodos y funciones
/// <summary>
/// Cierra la conexión del objeto hacia el origen de datos.
/// </summary>
/// <returns>System.Boolean</returns>
public bool FnCerrar()
{
try
{
sqlCnn.Close();
return true;
}
catch (Exception e)
{
errorOcurred = e;
}
return false;
}
/// <summary>
/// Establece una conexión con el origen de datos e inicializa la propiedad propAccessCmd con la conexión creada.
/// </summary>
/// <returns>System.Boolean</returns>
public bool FnConectar(int timeOutPer = 0)
{
try
{
if (string.IsNullOrEmpty(cadenaConexion))
{
cadenaConexion = Utilerias.UtileriasData.GetInstance.GetConnectionString(tipoConexion);
}
if (!string.IsNullOrEmpty(cadenaConexion))
{
sqlCnn = new SqlConnection(cadenaConexion);
sqlCnn.Open();
sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCnn;
timeOut = Utilerias.UtileriasData.GetInstance.GetTimeOut(tipoConexion);
if (timeOutPer >= 0)
sqlCmd.CommandTimeout = timeOutPer;
else if (timeOut > 0)
sqlCmd.CommandTimeout = timeOutPer;
return true;
}
return false;
}
catch (Exception e)
{
errorOcurred = e;
}
return false;
}
/// <summary>
/// Inicializa una transacción de base de datos para la conexión actual.
/// </summary>
/// <returns>System.Boolean.</returns>
public bool FnInicioTransaccion()
{
try
{
sqlTran = sqlCnn.BeginTransaction();
return true;
}
catch (Exception ex)
{
errorOcurred = ex;
}
return false;
}
/// <summary>
/// Asigna una transacción a la propiedad propAccessCmd
/// </summary>
/// <returns>System.Boolean.</returns>
public bool FnAsignarTransaccion()
{
try
{
sqlCmd.Transaction = sqlTran;
return true;
}
catch (Exception ex)
{
errorOcurred = ex;
}
return false;
}
/// <summary>
/// Confirma la transacción actual.
/// </summary>
/// <returns>System.Boolean.</returns>
public bool FnCommit()
{
try
{
sqlTran.Commit();
return true;
}
catch (Exception ex)
{
errorOcurred = ex;
}
return false;
}
/// <summary>
/// Deshace los cambios realizados en la transacción actual.
/// </summary>
/// <returns>System.Boolean.</returns>
public bool FnRollBack()
{
try
{
sqlTran.Rollback();
return true;
}
catch (Exception ex)
{
errorOcurred = ex;
}
return false;
}
/// <summary>
/// Asigna el nombre del procedimiento y sus parámetros a la propiedad propAccessCmd.
/// </summary>
/// <remarks>Si el procedimiento no requiere parámetros se envía null en su lugar.</remarks>
/// <param name="nombreStoreProcedure">Nombre del procedimiento</param>
/// <param name="parametros">Parámetros del procedimiento.</param>
/// <returns>System.Boolean.</returns>
public bool FnAsignarStoreProcedureYParametros(string nombreStoreProcedure, SqlParameter[] parametros)
{
if (sqlCmd != null)
{
try
{
sqlCmd.CommandText = nombreStoreProcedure;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Clear();
if (parametros != null)
sqlCmd.Parameters.AddRange(parametros);
return true;
}
catch (Exception e)
{
errorOcurred = e;
}
}
return false;
}
/// <summary>
/// Asigna el nombre de la función y sus parámetros a la propiedad propAccessCmd.
/// </summary>
/// <remarks>Si el procedimiento no requiere parámetros se envía null en su lugar.</remarks>
/// <param name="nombreFuncion">Nombre del procedimiento</param>
/// <param name="parametros">Parámetros del procedimiento.</param>
/// <returns>System.Boolean.</returns>
public bool FnAsignarFuncionYParametros(string nombreFuncion, SqlParameter[] parametros)
{
if (sqlCmd != null)
{
try
{
string str_parametros = string.Empty;
foreach (SqlParameter par in parametros)
str_parametros += "@" + par.ParameterName + ", ";
if (!string.IsNullOrEmpty(str_parametros))
str_parametros = str_parametros.Substring(0, str_parametros.Length - 2);
sqlCmd.CommandText = string.Format("select {0}({1})", nombreFuncion, str_parametros);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.Clear();
if (parametros != null)
sqlCmd.Parameters.AddRange(parametros);
return true;
}
catch (Exception e)
{
errorOcurred = e;
}
}
return false;
}
/// <summary>
/// Asigna el nombre del procedimiento y sus parámetros a la propiedad propAccessCmd.
/// </summary>
/// <remarks>Si el procedimiento no requiere parámetros se envía null en su lugar.</remarks>
/// <param name="nombreStoreProcedure">Nombre del procedimiento</param>
/// <param name="parametros">Parámetros del procedimiento.</param>
/// <returns>System.Boolean.</returns>
public bool FnAsignarStoreProcedureYParametros(string nombreStoreProcedure, object[] parametros)
{
if (sqlCmd != null)
{
try
{
sqlCmd.CommandText = nombreStoreProcedure;
sqlCmd.CommandType = CommandType.StoredProcedure;
// Obteniendo lista de parámetros de entrada
SqlCommandBuilder.DeriveParameters(sqlCmd);
SqlParameter[] parametrosDevueltos = sqlCmd.Parameters
.Cast<ICloneable>()
.Select(p => p.Clone())
.Cast<SqlParameter>()
.Where<SqlParameter>(p => p.Direction != ParameterDirection.ReturnValue && p.Direction != ParameterDirection.Output)
.ToArray();
// Asignando valores a parámetros
for (int i = 0; i < parametrosDevueltos.Length; i++)
{
parametrosDevueltos[i].Value = parametros[i];
}
sqlCmd.Parameters.Clear();
if (parametros != null)
sqlCmd.Parameters.AddRange(parametrosDevueltos);
return true;
}
catch (Exception e)
{
errorOcurred = e;
}
}
return false;
}
private SqlParameter[] DiscoverParameters(string connectionString, string spName)
{
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(spName, connection))
{
command.CommandType = CommandType.StoredProcedure;
connection.Open();
SqlCommandBuilder.DeriveParameters(command);
connection.Close();
return command.Parameters
.Cast<ICloneable>()
.Select(p => p.Clone())
.Cast<SqlParameter>()
.ToArray();
}
}
#endregion Métodos y funciones
}
}
|
using HarmonyLib;
using Verse;
namespace CleaningPriority.ListerFilthPrioritizedNotifiers;
[HarmonyPatch(typeof(Area))]
[HarmonyPatch("Set")]
internal class AreaChange
{
private static void Postfix(Area __instance, AreaManager ___areaManager, IntVec3 c, bool val)
{
___areaManager?.map?.GetListerFilthInAreas()?.OnAreaChange(c, val, __instance);
___areaManager?.map?.GetCleaningManager()?.MarkNeedToRecalculate();
}
} |
using UnityEngine;
public interface ISimulateAble
{
void Process(float time);
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PhonemesAndStuff
{
public class VowelPhone : AbstractPhone
{
public double F1f { get; }
public double F2f { get; }
public double F1m { get; }
public double F2m { get; }
public double F1fSD { get; }
public double F2fSD { get; }
public double F1mSD { get; }
public double F2mSD { get; }
public bool IsLabialized { get; }
public VowelPhone(VowelPhoneSupporter phoneSupporter,
List<Word> wordList) : base(phoneSupporter, wordList)
{
F1f = phoneSupporter.F1f;
F2f = phoneSupporter.F2f;
F1m = phoneSupporter.F1m;
F2m = phoneSupporter.F2m;
F1fSD = phoneSupporter.F1fSD;
F2fSD = phoneSupporter.F2fSD;
F1mSD = phoneSupporter.F1mSD;
F2mSD = phoneSupporter.F2mSD;
IsLabialized = phoneSupporter.IsLabialized;
}
}
}
|
using System.Collections.Generic;
using Asset.Models.Library.EntityModels.AssetsModels.AssetSetups;
using Core.Repository.Library.Core;
namespace Asset.Core.Repository.Library.Repositorys.AssetsModels.AssetSetups
{
public interface IAssetLocationRepository : IRepository<AssetLocation>
{
AssetLocation GetAssetLocationByName(string name);
AssetLocation GetAssetLocationByShortName(string shortName);
AssetLocation GetAssetLocationByCode(string code);
IEnumerable<AssetLocation> AssetLocationsWithOrganizationAndBranch();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using InvoiceClient.Properties;
namespace InvoiceClient
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
this.serviceInstaller1.ServiceName = Settings.Default.ServiceName;
this.serviceInstaller1.DisplayName = Settings.Default.DisplayName;
}
}
}
|
// ----------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="StateTask.cs" company="David Eiwen">
// Copyright © 2016 by David Eiwen
// </copyright>
// <author>David Eiwen</author>
// <summary>
// This file contains the StateTask class.
// </summary>
// ----------------------------------------------------------------------------------------------------------------------------------------
namespace IndiePortable.AdvancedTasks
{
using System;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Wraps a <see cref="Task" /> that is destined to a long life span.
/// </summary>
public class StateTask
{
/// <summary>
/// Represents the communication connection to the <see cref="StateTask" />.
/// </summary>
private readonly ITaskConnection connection;
/// <summary>
/// The <see cref="Task" /> that is wrapped by the <see cref="StateTask" />.
/// </summary>
private readonly Task task;
/// <summary>
/// The backing field for the <see cref="CurrentState" /> property.
/// </summary>
private TaskState currentStateBacking = TaskState.NotStarted;
/// <summary>
/// Initializes a new instance of the <see cref="StateTask" /> class.
/// </summary>
/// <param name="method">
/// The method the <see cref="StateTask" /> shall process.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="method" /> is <c>null</c>.</para>
/// </exception>
public StateTask(Action<ITaskConnection> method)
{
if (object.ReferenceEquals(method, null))
{
throw new ArgumentNullException(nameof(method));
}
this.connection = new TaskConnection(this);
this.task = Task.Factory.StartNew(() => method(this.connection));
this.currentStateBacking = TaskState.Started;
}
/// <summary>
/// Raised when the <see cref="StateTask" /> has returned.
/// </summary>
public event EventHandler Returned;
/// <summary>
/// Raised when an <see cref="Exception" /> has been thrown during the execution of the <see cref="StateTask" />.
/// </summary>
public event EventHandler<ExceptionThrownEventArgs> ExceptionThrown;
/// <summary>
/// Gets the current state of the <see cref="StateTask" />.
/// </summary>
/// <value>
/// Contains the current state of the <see cref="StateTask" />.
/// </value>
public TaskState CurrentState => this.currentStateBacking;
/// <summary>
/// Signals the <see cref="StateTask" /> to stop.
/// </summary>
public void Stop() => this.connection.Stop();
/// <summary>
/// Signals the <see cref="StateTask" /> to stop and waits until the <see cref="StateTask" /> returns.
/// If the <see cref="StateTask" /> has already finished, the call immediately returns.
/// </summary>
/// <remarks>
/// <para>
/// If the <see cref="ITaskConnection.Return()" /> method or the
/// <see cref="ITaskConnection.ThrowException(Exception)" /> method is never called by the task method,
/// calls to the <see cref="StopAndAwait()" /> method will never return.
/// </para>
/// </remarks>
public void StopAndAwait()
{
this.connection.Stop();
this.connection.Await();
}
/// <summary>
/// Signals the <see cref="StateTask" /> to stop and waits until the <see cref="StateTask" /> returns asynchronously.
/// If the <see cref="StateTask" /> has already finished, the call immediately returns.
/// </summary>
/// <returns>
/// Returns the executing <see cref="Task" />.
/// </returns>
/// <remarks>
/// <para>
/// If the <see cref="ITaskConnection.Return()" /> method or the
/// <see cref="ITaskConnection.ThrowException(Exception)" /> method is never called by the task method,
/// calls to the <see cref="StopAndAwaitAsync()" /> method will never return.
/// </para>
/// </remarks>
public async Task StopAndAwaitAsync()
{
this.connection.Stop();
await this.connection.AwaitAsync();
}
/// <summary>
/// Waits until the <see cref="StateTask" /> returns.
/// If the <see cref="StateTask" /> has already finished, the call immediately returns.
/// </summary>
/// <remarks>
/// <para>
/// If the <see cref="ITaskConnection.Return()" /> method or the
/// <see cref="ITaskConnection.ThrowException(Exception)" /> method is never called by the task method,
/// calls to the <see cref="Await()" /> method will never return.
/// </para>
/// </remarks>
public void Await() => this.connection.Await();
/// <summary>
/// Waits until the <see cref="StateTask" /> returns asynchronously.
/// If the <see cref="StateTask" /> has already finished, the call immediately returns.
/// </summary>
/// <returns>
/// Returns the executing <see cref="Task" />.
/// </returns>
/// <remarks>
/// <para>
/// If the <see cref="ITaskConnection.Return()" /> method or the
/// <see cref="ITaskConnection.ThrowException(Exception)" /> method is never called by the task method,
/// calls to the <see cref="Await()" /> method will never return.
/// </para>
/// </remarks>
public Task AwaitAsync() => this.connection.AwaitAsync();
/// <summary>
/// Waits until the <see cref="StateTask" /> returns.
/// If the <see cref="StateTask" /> has already finished, the call immediately returns.
/// </summary>
/// <returns>
/// <c>true</c> if no exception has been thrown; otherwise <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// If the <see cref="ITaskConnection.Return()" /> method or the
/// <see cref="ITaskConnection.ThrowException(Exception)" /> method is never called by the task method,
/// calls to the <see cref="TryAwait()" /> method will never return.
/// </para>
/// </remarks>
public bool TryAwait() => this.connection.TryAwait();
/// <summary>
/// Waits until the <see cref="StateTask" /> returns asynchronously.
/// If the <see cref="StateTask" /> has already finished, the call immediately returns.
/// </summary>
/// <returns>
/// <c>true</c> if no exception has been thrown; otherwise <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// If the <see cref="ITaskConnection.Return()" /> method or the
/// <see cref="ITaskConnection.ThrowException(Exception)" /> method is never called by the task method,
/// calls to the <see cref="TryAwaitAsync()" /> method will never return.
/// </para>
/// </remarks>
public Task<bool> TryAwaitAsync() => this.connection.TryAwaitAsync();
/// <summary>
/// Raises the <see cref="Returned" /> event.
/// </summary>
protected void RaiseReturned() => this.Returned?.Invoke(this, EventArgs.Empty);
/// <summary>
/// Raises the <see cref="ExceptionThrown" /> event.
/// </summary>
/// <param name="exc">
/// The <see cref="Exception" /> that has been thrown.
/// </param>
protected void RaiseExceptionThrown(Exception exc) => this.ExceptionThrown?.Invoke(this, new ExceptionThrownEventArgs(exc));
/// <summary>
/// Represents the connection to the method of the wrapped <see cref="Task" />.
/// </summary>
/// <seealso cref="ITaskConnection" />
private sealed class TaskConnection
: ITaskConnection
{
/// <summary>
/// The <see cref="ManualResetEventSlim" /> used to block for the <see cref="Await()" /> method family.
/// </summary>
private readonly ManualResetEventSlim waitHandle = new ManualResetEventSlim();
/// <summary>
/// The <see cref="StateTask" /> using this <see cref="TaskConnection" /> instance.
/// </summary>
private readonly StateTask task;
/// <summary>
/// The backing field for the <see cref="MustFinish" /> property.
/// </summary>
private bool mustFinishBacking;
/// <summary>
/// The <see cref="Exception" /> that has been thrown, or <c>null</c> if no exception has been thrown.
/// </summary>
private Exception thrownException;
/// <summary>
/// Initializes a new instance of the <see cref="TaskConnection"/> class.
/// </summary>
/// <param name="task">
/// The <see cref="StateTask" /> using the <see cref="TaskConnection" /> instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="task" /> is <c>null</c>.</para>
/// </exception>
public TaskConnection(StateTask task)
{
if (object.ReferenceEquals(task, null))
{
throw new ArgumentNullException(nameof(task));
}
this.task = task;
}
/// <summary>
/// Gets a value indicating whether the <see cref="StateTask" /> must finish.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="StateTask" /> must finish; otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>Implements <see cref="ITaskConnection.MustFinish" /> implicitly.</para>
/// </remarks>
public bool MustFinish => this.mustFinishBacking;
public void Stop()
{
this.mustFinishBacking = true;
}
public void Await()
{
this.waitHandle.Wait();
if (this.task.CurrentState == TaskState.ExceptionThrown &&
!object.ReferenceEquals(this.thrownException, null))
{
throw this.thrownException;
}
}
public async Task AwaitAsync()
{
await Task.Factory.StartNew(() => this.waitHandle.Wait());
if (this.task.CurrentState == TaskState.ExceptionThrown &&
!object.ReferenceEquals(this.thrownException, null))
{
throw this.thrownException;
}
}
public bool TryAwait()
{
this.waitHandle.Wait();
return this.task.currentStateBacking == TaskState.Finished;
}
public async Task<bool> TryAwaitAsync()
{
await Task.Factory.StartNew(() => this.waitHandle.Wait());
return this.task.currentStateBacking == TaskState.Finished;
}
/// <summary>
/// Signals that the <see cref="StateTask" /> has finished its work.
/// </summary>
public void Return()
{
this.task.currentStateBacking = TaskState.Finished;
this.mustFinishBacking = true;
this.waitHandle.Set();
this.task.RaiseReturned();
}
/// <summary>
/// Notifies the <see cref="StateTask" /> of a thrown exception.
/// </summary>
/// <param name="exc">
/// The thrown <see cref="Exception" />.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="exc" /> is <c>null</c>.</para>
/// </exception>
public void ThrowException(Exception exc)
{
if (object.ReferenceEquals(exc, null))
{
throw new ArgumentNullException(nameof(exc));
}
this.task.currentStateBacking = TaskState.ExceptionThrown;
this.mustFinishBacking = true;
this.thrownException = exc;
this.waitHandle.Set();
this.task.RaiseExceptionThrown(exc);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace WindowsServiceHostAPI
{
public partial class SelfHostService : ServiceBase
{
public SelfHostService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
var config = new HttpSelfHostConfiguration("http://192.168.1.13:8082");
config.MaxReceivedMessageSize = 2147483647;
config.Routes.MapHttpRoute(
name: "API",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
HttpSelfHostServer server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
}
protected override void OnStop()
{
// Fermer le service proprement
base.OnStop();
}
}
}
|
using Liddup.Services;
using System.Windows.Input;
using Xamarin.Forms;
namespace Liddup.PageModels
{
class SpotifyUnavailablePageModel : BasePageModel
{
ICommand _connectToSpotifyCommand;
public ICommand ConnectToSpotifyCommand => _connectToSpotifyCommand ?? (_connectToSpotifyCommand = new Command(() => ConnectToSpotify()));
private void ConnectToSpotify()
{
if (!DependencyService.Get<ISpotifyApi>().IsLoggedIn)
DependencyService.Get<ISpotifyApi>().Login();
MessagingCenter.Send(this as BasePageModel, "NavigateToSpotifyLibrary");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using JsonData;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
//Collections to work with
List<Artist> Artists = JsonToFile<Artist>.ReadJson();
List<Group> Groups = JsonToFile<Group>.ReadJson();
//========================================================
//Solve all of the prompts below using various LINQ queries
//========================================================
//There is only one artist in this collection from Mount Vernon, what is their name and age?
// Standard:
// var res=from a in Artists
// where a.Hometown == "Mount Vernon"
// select new{a.ArtistName,a.Age};
// Chaining:
// var res = Artists.Where(a=>a.Hometown == "Mount Vernon").Select(x=>new{x.ArtistName,x.Age});
//Who is the youngest artist in our collection of artists?
// var res = Artists.Select(a=>new{a.ArtistName,a.Age})
// .Min(a=>a.Age);
//Display all artists with 'William' somewhere in their real name
// var res = from artist in Artists
// where artist.RealName.Contains("William")
// select artist.RealName;
//Display the 3 oldest artist from Atlanta
// This took like an hour to figure out
// var res = Artists.Select(a=>new{a.ArtistName,a.Age,a.Hometown})
// .Where(x=>x.Hometown=="Atlanta")
// .OrderByDescending(x=>x.Age)
// .Take(3);
//(Optional) Display the Group Name of all groups that have members that are not from New York City
// var res = Groups.Join(
// Artists.Where(x=>x.Hometown != "New York City"),
// g=>g.Id,
// a=>a.GroupId,
// (g,a)=>{
// return g.GroupName;
// }
// );
//(Optional) Display the artist names of all members of the group 'Wu-Tang Clan'
// Left Join
// var res = Artists.Join(
// Groups.Where(x=>x.GroupName == "Wu-Tang Clan"),
// a=>a.GroupId,
// g=>g.Id,
// (a,g)=>{
// return a.ArtistName;
// }
// );
}
}
}
|
namespace DeliverySystem.Dtos.Delivery
{
public class UpdateDeliveryDto
{
public int Id { get; set; }
public string State { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public enum SpawnerType
{
GROUND,
AIR
}
[System.Serializable]
struct Spawner
{
public GameObject spawner;
public SpawnerType spawnerType;
// This is to be used for enabling the spawner after a set amount of game time has passed
// Allows for progressively more difficult enemies to spawn
//public float enableTime;
}
public class GameManagerScript : MonoBehaviour
{
#region Spawners & Enemies Variables
[SerializeField]
List<Spawner> spawnerList;
// If more enemies are added, this would do better as a dictionary
[SerializeField]
List<GameObject> enemyList;
#endregion
#region Player Variables
[SerializeField]
PlayerControllerScript playerControllerScript;
#endregion
#region Spawning Variables
[SerializeField]
float maxSpawnTime = 5.0f;
[SerializeField]
float maxSpawnTimeReduction = 2.0f;
// This is per-spawn
[SerializeField]
float timeReductionIncrement = 0.02f;
[SerializeField]
float minSpawnTime = 1.0f;
// The randomly selected value between min and max to count up to
float targetSpawnTime = 0.0f;
float spawnTimeCtr = 0.0f;
#endregion
#region Pregame Variables
bool startGame = false;
[SerializeField]
TMP_Text startGameText;
#endregion
void SpawnAttacker()
{
Spawner selectedSpawner = spawnerList[Random.Range(0, spawnerList.Count)];
if(selectedSpawner.spawnerType == SpawnerType.GROUND)
Instantiate(enemyList[0], selectedSpawner.spawner.transform.position, Quaternion.identity);
else if(selectedSpawner.spawnerType == SpawnerType.AIR)
Instantiate(enemyList[1], selectedSpawner.spawner.transform.position, Quaternion.identity);
}
void PreGameUpdate()
{
if(playerControllerScript.GetPlayerMouseScript().GetMouseDown())
{
startGame = true;
startGameText.gameObject.SetActive(false);
}
}
void GameUpdate()
{
/// Spawning
if (spawnTimeCtr >= targetSpawnTime)
{
// Spawn
SpawnAttacker();
spawnTimeCtr = 0;
targetSpawnTime = Random.Range(minSpawnTime, maxSpawnTime - maxSpawnTimeReduction);
if (maxSpawnTime - maxSpawnTimeReduction >= minSpawnTime)
maxSpawnTimeReduction += timeReductionIncrement;
}
spawnTimeCtr += Time.deltaTime;
}
void Update()
{
if (!startGame)
PreGameUpdate();
else
GameUpdate();
}
} |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using SA_Tools;
using SonicRetro.SAModel.Direct3D;
using SonicRetro.SAModel.Direct3D.TextureSystem;
using SonicRetro.SAModel.SAEditorCommon;
using SonicRetro.SAModel.SAEditorCommon.DataTypes;
using SonicRetro.SAModel.SAEditorCommon.SETEditing;
using SonicRetro.SAModel.SAEditorCommon.UI;
namespace SonicRetro.SAModel.SADXLVL2
{
// TODO: Organize this whole class.
// TODO: Unify as much SET/CAM load and save code as possible. They're practically identical.
// TODO: Rename controls to be more distinguishable.
// (Example: sETItemsToolStripMenuItem1 is a dropdown menu. sETITemsToolStripMenuItem is a toggle.)
public partial class MainForm : Form
{
Properties.Settings Settings = Properties.Settings.Default;
public MainForm()
{
Application.ThreadException += Application_ThreadException;
InitializeComponent();
}
void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
using (ErrorDialog ed = new ErrorDialog(e.Exception, true))
if (ed.ShowDialog(this) == DialogResult.Cancel)
Close();
}
internal Device d3ddevice;
SAEditorCommon.IniData ini;
EditorCamera cam = new EditorCamera(EditorOptions.RenderDrawDistance);
string levelID;
internal string levelName;
bool isStageLoaded;
EditorItemSelection selectedItems = new EditorItemSelection();
Dictionary<string, List<string>> levelNames;
bool lookKeyDown;
bool zoomKeyDown;
Point menuLocation;
bool isPointOperation;
// TODO: Make these both configurable.
bool mouseWrapScreen = false;
ushort mouseWrapThreshold = 2;
// helpers / ui stuff
TransformGizmo transformGizmo;
// light list
List<SA1StageLightData> stageLightList;
private void MainForm_Load(object sender, EventArgs e)
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
LevelData.StateChanged += LevelData_StateChanged;
LevelData.PointOperation += LevelData_PointOperation;
panel1.MouseWheel += panel1_MouseWheel;
if (ShowQuickStart())
ShowLevelSelect();
}
private bool ShowQuickStart()
{
bool result;
using (QuickStartDialog dialog = new QuickStartDialog(this, GetRecentFiles()))
{
if (result = (dialog.ShowDialog() == DialogResult.OK))
LoadINI(dialog.SelectedItem);
}
return result;
}
private void ShowLevelSelect()
{
string stageToLoad = string.Empty;
using (LevelSelectDialog dialog = new LevelSelectDialog(levelNames))
{
if (dialog.ShowDialog() == DialogResult.OK)
stageToLoad = dialog.SelectedStage;
}
if (!string.IsNullOrEmpty(stageToLoad))
{
if (isStageLoaded)
{
if (SavePrompt(true) == DialogResult.Cancel)
return;
}
CheckMenuItemByTag(changeLevelToolStripMenuItem, stageToLoad);
LoadStage(stageToLoad);
}
}
private void InitializeDirect3D()
{
if (d3ddevice == null)
{
d3ddevice = new Device(0, DeviceType.Hardware, panel1, CreateFlags.HardwareVertexProcessing,
new PresentParameters
{
Windowed = true,
SwapEffect = SwapEffect.Discard,
EnableAutoDepthStencil = true,
AutoDepthStencilFormat = DepthFormat.D24X8
});
d3ddevice.DeviceResizing += d3ddevice_DeviceResizing;
EditorOptions.Initialize(d3ddevice);
Gizmo.InitGizmo(d3ddevice);
ObjectHelper.Init(d3ddevice, Properties.Resources.UnknownImg);
}
}
private StringCollection GetRecentFiles()
{
if (Settings.MRUList == null)
Settings.MRUList = new StringCollection();
StringCollection mru = new StringCollection();
foreach (string item in Settings.MRUList)
{
if (File.Exists(item))
{
mru.Add(item);
recentProjectsToolStripMenuItem.DropDownItems.Add(item.Replace("&", "&&"));
}
}
Settings.MRUList = mru;
if (mru.Count > 0)
recentProjectsToolStripMenuItem.DropDownItems.Remove(noneToolStripMenuItem2);
if (Program.args.Length > 0)
LoadINI(Program.args[0]);
return mru;
}
void d3ddevice_DeviceResizing(object sender, CancelEventArgs e)
{
// HACK: Not so sure we should have to re-initialize this every time...
EditorOptions.Initialize(d3ddevice);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFile();
}
public bool OpenFile()
{
if (isStageLoaded)
{
if (SavePrompt() == DialogResult.Cancel)
return false;
}
OpenFileDialog a = new OpenFileDialog()
{
DefaultExt = "ini",
Filter = "INI Files|*.ini|All Files|*.*"
};
if (a.ShowDialog(this) == DialogResult.OK)
{
LoadINI(a.FileName);
return true;
}
return false;
}
private void LoadINI(string filename)
{
isStageLoaded = false;
ini = SAEditorCommon.IniData.Load(filename);
Environment.CurrentDirectory = Path.GetDirectoryName(filename);
levelNames = new Dictionary<string, List<string>>();
foreach (KeyValuePair<string, IniLevelData> item in ini.Levels)
{
if (string.IsNullOrEmpty(item.Key))
continue;
string[] split = item.Key.Split('\\');
for (int i = 0; i < split.Length; i++)
{
// If the key doesn't exist (e.g Action Stages), initialize the list
if (!levelNames.ContainsKey(split[0]))
levelNames[split[0]] = new List<string>();
// Then add the stage name (e.g Emerald Coast 1)
if (i > 0)
levelNames[split[0]].Add(split[i]);
}
}
// Set up the Change Level menu...
PopulateLevelMenu(changeLevelToolStripMenuItem, levelNames);
// If no projects have been recently used, clear the list to remove the "(none)" entry.
if (Settings.MRUList.Count == 0)
recentProjectsToolStripMenuItem.DropDownItems.Clear();
// If this project has been loaded before, remove it...
if (Settings.MRUList.Contains(filename))
{
recentProjectsToolStripMenuItem.DropDownItems.RemoveAt(Settings.MRUList.IndexOf(filename));
Settings.MRUList.Remove(filename);
}
// ...so that it can be re-inserted at the top of the Recent Projects list.
Settings.MRUList.Insert(0, filename);
recentProjectsToolStripMenuItem.DropDownItems.Insert(0, new ToolStripMenuItem(filename));
// File menu -> Change Level
changeLevelToolStripMenuItem.Enabled = true;
// load stage lights
string stageLightPath = string.Concat(Environment.CurrentDirectory, "\\Levels\\Stage Lights.ini");
if (File.Exists(stageLightPath))
{
stageLightList = SA1StageLightDataList.Load(stageLightPath);
}
}
private void PopulateLevelMenu(ToolStripMenuItem targetMenu, Dictionary<string, List<string>> levels)
{
// Used for keeping track of menu items
Dictionary<string, ToolStripMenuItem> levelMenuItems = new Dictionary<string, ToolStripMenuItem>();
targetMenu.DropDownItems.Clear();
foreach (KeyValuePair<string, List<string>> item in levels)
{
// For every section (e.g Adventure Fields) in levels, reset the parent menu.
// It gets changed later if necessary.
ToolStripMenuItem parent = targetMenu;
foreach (string stage in item.Value)
{
// If a menu item for this section has not already been initialized...
if (!levelMenuItems.ContainsKey(item.Key))
{
// Create it
ToolStripMenuItem i = new ToolStripMenuItem(item.Key.Replace("&", "&&"));
// Add it to the list to keep track of it
levelMenuItems.Add(item.Key, i);
// Add the new menu item to the parent menu
parent.DropDownItems.Add(i);
// and set the parent so we know where to put the stage
parent = i;
}
else
{
// Otherwise, set the parent to the existing reference
parent = levelMenuItems[item.Key];
}
// And finally, create the menu item for the stage name itself and hook it up to the Clicked event.
// The Tag member here is vital. The code later on uses this to determine what assets to load.
parent.DropDownItems.Add(new ToolStripMenuItem(stage, null, LevelToolStripMenuItem_Clicked)
{
Tag = item.Key + '\\' + stage
});
}
}
}
// TODO: Move this stuff somewhere that it can be accessed by all projects
/// <summary>
/// Iterates recursively through menu items and unchecks all sub-items.
/// </summary>
/// <param name="menu">The parent menu of the items to be unchecked.</param>
private static void UncheckMenuItems(ToolStripDropDownItem menu)
{
foreach (ToolStripMenuItem i in menu.DropDownItems)
{
if (i.HasDropDownItems)
UncheckMenuItems(i);
else
i.Checked = false;
}
}
/// <summary>
/// Unchecks all children of the parent object and checks the target.
/// </summary>
/// <param name="target">The item to check</param>
/// <param name="parent">The parent menu containing the target.</param>
private static void CheckMenuItem(ToolStripMenuItem target, ToolStripItem parent = null)
{
if (target == null)
return;
if (parent == null)
parent = target.OwnerItem;
UncheckMenuItems((ToolStripDropDownItem)parent);
target.Checked = true;
}
/// <summary>
/// Iterates recursively through the parent and checks the first item it finds with a matching Tag.
/// If firstOf is true, recursion stops after the first match.
/// </summary>
/// <param name="parent">The parent menu.</param>
/// <param name="tag">The tag to search for.</param>
/// <param name="firstOf">If true, recursion stops after the first match.</param>
/// <returns></returns>
private static bool CheckMenuItemByTag(ToolStripDropDownItem parent, string tag, bool firstOf = true)
{
foreach (ToolStripMenuItem i in parent.DropDownItems)
{
if (i.HasDropDownItems)
{
if (CheckMenuItemByTag(i, tag, firstOf))
return true;
}
else if ((string)i.Tag == tag)
{
if (firstOf)
{
CheckMenuItem(i, parent);
return true;
}
else
{
i.Checked = true;
}
}
}
return false;
}
/// <summary>
/// Displays a dialog asking if the user would like to save.
/// </summary>
/// <param name="autoCloseDialog">Defines whether or not the save progress dialog should close on completion.</param>
/// <returns></returns>
private DialogResult SavePrompt(bool autoCloseDialog = false)
{
DialogResult result = MessageBox.Show(this, "Do you want to save?", "SADXLVL2",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
switch (result)
{
case DialogResult.Yes:
SaveStage(autoCloseDialog);
break;
}
return result;
}
private void LevelToolStripMenuItem_Clicked(object sender, EventArgs e)
{
fileToolStripMenuItem.HideDropDown();
if (!isStageLoaded || SavePrompt(true) != DialogResult.Cancel)
{
UncheckMenuItems(changeLevelToolStripMenuItem);
((ToolStripMenuItem)sender).Checked = true;
LoadStage(((ToolStripMenuItem)sender).Tag.ToString());
}
}
private void LoadStage(string id)
{
UseWaitCursor = true;
Enabled = false;
levelID = id;
string[] itempath = levelID.Split('\\');
levelName = itempath[itempath.Length - 1];
LevelData.LevelName = levelName;
Text = "SADXLVL2 - Loading " + levelName + "...";
#if !DEBUG
backgroundWorker1.RunWorkerAsync();
#else
backgroundWorker1_DoWork(null, null);
backgroundWorker1_RunWorkerCompleted(null, null);
#endif
}
/// <summary>
/// Loads all of the textures from the file into the scene.
/// </summary>
/// <param name="file">The name of the file.</param>
/// <param name="systemPath">The game's system path.</param>
void LoadTextureList(string file, string systemPath)
{
LoadTextureList(TextureList.Load(file), systemPath);
}
/// <summary>
/// Loads all of the textures specified into the scene.
/// </summary>
/// <param name="textureEntries">The texture entries to load.</param>
/// <param name="systemPath">The game's system path.</param>
private void LoadTextureList(IEnumerable<TextureListEntry> textureEntries, string systemPath)
{
foreach (TextureListEntry entry in textureEntries)
{
if (string.IsNullOrEmpty(entry.Name))
continue;
LoadPVM(entry.Name, systemPath);
}
}
/// <summary>
/// Loads textures from a PVM into the scene.
/// </summary>
/// <param name="pvmName">The PVM name (name only; no path or extension).</param>
/// <param name="systemPath">The game's system path.</param>
void LoadPVM(string pvmName, string systemPath)
{
if (!LevelData.TextureBitmaps.ContainsKey(pvmName))
{
BMPInfo[] textureBitmaps = TextureArchive.GetTextures(Path.Combine(systemPath, pvmName) + ".PVM");
Texture[] d3dTextures = new Texture[textureBitmaps.Length];
for (int i = 0; i < textureBitmaps.Length; i++)
d3dTextures[i] = new Texture(d3ddevice, textureBitmaps[i].Image, Usage.None, Pool.Managed);
LevelData.TextureBitmaps.Add(pvmName, textureBitmaps);
LevelData.Textures.Add(pvmName, d3dTextures);
}
}
bool initerror = false;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
#if !DEBUG
try
{
#endif
int steps = 10;
if (d3ddevice == null)
++steps;
toolStrip1.Enabled = false;
// HACK: Fixes Twinkle Circuit's geometry lingering if loaded before Sky Chase.
// I'm sure the real problem is somewhere below, but this is sort of an all around cleanup.
if (isStageLoaded)
LevelData.Clear();
isStageLoaded = false;
using (ProgressDialog progress = new ProgressDialog("Loading stage: " + levelName, steps))
{
IniLevelData level = ini.Levels[levelID];
string syspath = Path.Combine(Environment.CurrentDirectory, ini.SystemPath);
string modpath = ini.ModPath;
SA1LevelAct levelact = new SA1LevelAct(level.LevelID);
LevelData.leveltexs = null;
cam = new EditorCamera(EditorOptions.RenderDrawDistance);
Invoke((Action<IWin32Window>)progress.Show, this);
if (d3ddevice == null)
{
progress.SetTask("Initializing Direct3D...");
Invoke((Action)InitializeDirect3D);
progress.StepProgress();
}
progress.SetTaskAndStep("Loading level data:", "Geometry");
if (string.IsNullOrEmpty(level.LevelGeometry))
LevelData.geo = null;
else
{
LevelData.geo = LandTable.LoadFromFile(level.LevelGeometry);
LevelData.LevelItems = new List<LevelItem>();
for (int i = 0; i < LevelData.geo.COL.Count; i++)
LevelData.LevelItems.Add(new LevelItem(LevelData.geo.COL[i], d3ddevice, i, selectedItems));
}
progress.StepProgress();
progress.SetStep("Textures");
LevelData.TextureBitmaps = new Dictionary<string, BMPInfo[]>();
LevelData.Textures = new Dictionary<string, Texture[]>();
if (LevelData.geo != null && !string.IsNullOrEmpty(LevelData.geo.TextureFileName))
{
BMPInfo[] TexBmps =
TextureArchive.GetTextures(Path.Combine(syspath, LevelData.geo.TextureFileName) + ".PVM");
Texture[] texs = new Texture[TexBmps.Length];
for (int j = 0; j < TexBmps.Length; j++)
texs[j] = new Texture(d3ddevice, TexBmps[j].Image, Usage.None, Pool.Managed);
if (!LevelData.TextureBitmaps.ContainsKey(LevelData.geo.TextureFileName))
LevelData.TextureBitmaps.Add(LevelData.geo.TextureFileName, TexBmps);
if (!LevelData.Textures.ContainsKey(LevelData.geo.TextureFileName))
LevelData.Textures.Add(LevelData.geo.TextureFileName, texs);
LevelData.leveltexs = LevelData.geo.TextureFileName;
}
progress.StepProgress();
#region Start Positions
progress.SetTaskAndStep("Setting up start positions...");
LevelData.StartPositions = new StartPosItem[LevelData.Characters.Length];
for (int i = 0; i < LevelData.StartPositions.Length; i++)
{
progress.SetStep(string.Format("{0}/{1}", (i + 1), LevelData.StartPositions.Length));
IniCharInfo character;
if (i == 0 && levelact.Level == SA1LevelIDs.PerfectChaos)
character = ini.Characters["SuperSonic"];
else
character = ini.Characters[LevelData.Characters[i]];
Dictionary<SA1LevelAct, SA1StartPosInfo> posini =
SA1StartPosList.Load(character.StartPositions);
Vertex pos = new Vertex();
int rot = 0;
if (posini.ContainsKey(levelact))
{
pos = posini[levelact].Position;
rot = posini[levelact].YRotation;
}
LevelData.StartPositions[i] = new StartPosItem(new ModelFile(character.Model).Model,
character.Textures, character.Height, pos, rot, d3ddevice, selectedItems);
LoadTextureList(character.TextureList, syspath);
}
progress.StepProgress();
#endregion
#region Death Zones
progress.SetTaskAndStep("Death Zones:", "Initializing...");
if (string.IsNullOrEmpty(level.DeathZones))
LevelData.DeathZones = null;
else
{
LevelData.DeathZones = new List<DeathZoneItem>();
DeathZoneFlags[] dzini = DeathZoneFlagsList.Load(level.DeathZones);
string path = Path.GetDirectoryName(level.DeathZones);
for (int i = 0; i < dzini.Length; i++)
{
progress.SetStep(String.Format("Loading model {0}/{1}", (i + 1), dzini.Length));
LevelData.DeathZones.Add(new DeathZoneItem(
new ModelFile(Path.Combine(path, i.ToString(System.Globalization.NumberFormatInfo.InvariantInfo) + ".sa1mdl"))
.Model,
dzini[i].Flags, d3ddevice, selectedItems));
}
}
progress.StepProgress();
#endregion
#region Textures and Texture Lists
progress.SetTaskAndStep("Loading textures for:");
progress.SetStep("Common objects");
// Loads common object textures (e.g OBJ_REGULAR)
LoadTextureList(ini.ObjectTextureList, syspath);
progress.SetStep("Mission objects");
// Loads mission object textures
LoadTextureList(ini.MissionTextureList, syspath);
progress.SetTaskAndStep("Loading stage texture lists...");
// Loads the textures in the texture list for this stage (e.g BEACH01)
foreach (string file in Directory.GetFiles(ini.LevelTextureLists))
{
LevelTextureList texini = LevelTextureList.Load(file);
if (texini.Level != levelact)
continue;
LoadTextureList(texini.TextureList, syspath);
}
progress.SetTaskAndStep("Loading textures for:", "Objects");
// Object texture list(s)
LoadTextureList(level.ObjectTextureList, syspath);
progress.SetStep("Stage");
// The stage textures... again? "Extra"?
if (level.Textures != null && level.Textures.Length > 0)
foreach (string tex in level.Textures)
{
LoadPVM(tex, syspath);
if (string.IsNullOrEmpty(LevelData.leveltexs))
LevelData.leveltexs = tex;
}
progress.StepProgress();
#endregion
#region Object Definitions / SET Layout
progress.SetTaskAndStep("Loading Object Definitions:", "Parsing...");
LevelData.ObjDefs = new List<ObjectDefinition>();
Dictionary<string, ObjectData> objdefini =
IniSerializer.Deserialize<Dictionary<string, ObjectData>>(ini.ObjectDefinitions);
LevelData.MisnObjDefs = new List<ObjectDefinition>();
if (!string.IsNullOrEmpty(level.ObjectList) && File.Exists(level.ObjectList))
{
List<ObjectData> objectErrors = new List<ObjectData>();
ObjectListEntry[] objlstini = ObjectList.Load(level.ObjectList, false);
Directory.CreateDirectory("dllcache").Attributes |= FileAttributes.Hidden;
for (int ID = 0; ID < objlstini.Length; ID++)
{
string codeaddr = objlstini[ID].CodeString;
if (!objdefini.ContainsKey(codeaddr))
codeaddr = "0";
ObjectData defgroup = objdefini[codeaddr];
ObjectDefinition def;
if (!string.IsNullOrEmpty(defgroup.CodeFile))
{
progress.SetStep("Compiling: " + defgroup.CodeFile);
// TODO: Split this out to a function
#region Compile object code files
string ty = defgroup.CodeType;
string dllfile = Path.Combine("dllcache", ty + ".dll");
DateTime modDate = DateTime.MinValue;
if (File.Exists(dllfile))
modDate = File.GetLastWriteTime(dllfile);
string fp = defgroup.CodeFile.Replace('/', Path.DirectorySeparatorChar);
if (modDate >= File.GetLastWriteTime(fp) && modDate > File.GetLastWriteTime(Application.ExecutablePath))
def =
(ObjectDefinition)
Activator.CreateInstance(
Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, dllfile))
.GetType(ty));
else
{
string ext = Path.GetExtension(fp);
CodeDomProvider pr = null;
switch (ext.ToLowerInvariant())
{
case ".cs":
pr = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
break;
case ".vb":
pr = new Microsoft.VisualBasic.VBCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
break;
}
if (pr != null)
{
// System, System.Core, System.Drawing, Microsoft.DirectX, Microsoft.DirectX.Direct3D, Microsoft.DirectX.Direct3DX,
// SADXLVL2, SAModel, SAModel.Direct3D, SA Tools, SAEditorCommon
CompilerParameters para =
new CompilerParameters(new string[]
{
"System.dll", "System.Core.dll", "System.Drawing.dll", Assembly.GetAssembly(typeof (Vector3)).Location,
Assembly.GetAssembly(typeof (Texture)).Location, Assembly.GetAssembly(typeof (D3DX)).Location,
Assembly.GetExecutingAssembly().Location, Assembly.GetAssembly(typeof (LandTable)).Location,
Assembly.GetAssembly(typeof (EditorCamera)).Location, Assembly.GetAssembly(typeof (SA1LevelAct)).Location,
Assembly.GetAssembly(typeof (ObjectDefinition)).Location
})
{
GenerateExecutable = false,
GenerateInMemory = false,
IncludeDebugInformation = true,
OutputAssembly = Path.Combine(Environment.CurrentDirectory, dllfile)
};
CompilerResults res = pr.CompileAssemblyFromFile(para, fp);
if (res.Errors.HasErrors)
{
// TODO: Merge with existing object error handler. I add too many ToDos.
string errors = null;
foreach (CompilerError item in res.Errors)
errors += String.Format("\n\n{0}, {1}: {2}", item.Line, item.Column, item.ErrorText);
MessageBox.Show("Failed to compile object code file:\n" + defgroup.CodeFile + errors,
"Object compilation failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
def = new DefaultObjectDefinition();
}
else
{
def = (ObjectDefinition)Activator.CreateInstance(res.CompiledAssembly.GetType(ty));
}
}
else
def = new DefaultObjectDefinition();
}
#endregion
}
else
{
def = new DefaultObjectDefinition();
}
LevelData.ObjDefs.Add(def);
// The only reason .Model is checked for null is for objects that don't yet have any
// models defined for them. It would be annoying seeing that error all the time!
if (string.IsNullOrEmpty(defgroup.CodeFile) && !string.IsNullOrEmpty(defgroup.Model))
{
progress.SetStep("Loading: " + defgroup.Model);
// Otherwise, if the model file doesn't exist and/or no texture file is defined,
// load the "default object" instead ("?").
if (!File.Exists(defgroup.Model) || string.IsNullOrEmpty(defgroup.Texture) ||
!LevelData.Textures.ContainsKey(defgroup.Texture))
{
ObjectData error = new ObjectData { Name = defgroup.Name, Model = defgroup.Model, Texture = defgroup.Texture };
objectErrors.Add(error);
defgroup.Model = null;
}
}
def.Init(defgroup, objlstini[ID].Name, d3ddevice);
def.SetInternalName(objlstini[ID].Name);
}
// Loading SET Layout
progress.SetTaskAndStep("Loading SET items", "Initializing...");
if (LevelData.ObjDefs.Count > 0)
{
LevelData.SETName = level.SETName ?? level.LevelID;
string setstr = Path.Combine(syspath, "SET" + LevelData.SETName + "{0}.bin");
LevelData.SETItems = new List<SETItem>[LevelData.SETChars.Length];
for (int i = 0; i < LevelData.SETChars.Length; i++)
{
List<SETItem> list = new List<SETItem>();
byte[] setfile = null;
string formatted = string.Format(setstr, LevelData.SETChars[i]);
if (modpath != null && File.Exists(Path.Combine(modpath, formatted)))
setfile = File.ReadAllBytes(Path.Combine(modpath, formatted));
else if (File.Exists(formatted))
setfile = File.ReadAllBytes(formatted);
if (setfile != null)
{
progress.SetTask("SET: " + formatted.Replace(Environment.CurrentDirectory, ""));
int count = BitConverter.ToInt32(setfile, 0);
int address = 0x20;
for (int j = 0; j < count; j++)
{
progress.SetStep(string.Format("{0}/{1}", (j + 1), count));
SETItem ent = new SETItem(setfile, address, selectedItems);
list.Add(ent);
address += 0x20;
}
}
LevelData.SETItems[i] = list;
}
}
else
{
LevelData.SETItems = null;
}
// Checks if there have been any errors added to the error list and does its thing
// This thing is a mess. If anyone can think of a cleaner way to do this, be my guest.
if (objectErrors.Count > 0)
{
int count = objectErrors.Count;
List<string> errorStrings = new List<string> { "The following objects failed to load:" };
foreach (ObjectData o in objectErrors)
{
bool texEmpty = string.IsNullOrEmpty(o.Texture);
bool texExists = (!string.IsNullOrEmpty(o.Texture) && LevelData.Textures.ContainsKey(o.Texture));
errorStrings.Add("");
errorStrings.Add("Object:\t\t" + o.Name);
errorStrings.Add("\tModel:");
errorStrings.Add("\t\tName:\t" + o.Model);
errorStrings.Add("\t\tExists:\t" + File.Exists(o.Model));
errorStrings.Add("\tTexture:");
errorStrings.Add("\t\tName:\t" + ((texEmpty) ? "(N/A)" : o.Texture));
errorStrings.Add("\t\tExists:\t" + texExists);
}
// TODO: Proper logging. Who knows where this file may end up
File.WriteAllLines("SADXLVL2.log", errorStrings.ToArray());
MessageBox.Show(count + ((count == 1) ? " object" : " objects") + " failed to load their model(s).\n"
+
"\nThe level will still display, but the objects in question will not display their proper models." +
"\n\nPlease check the log for details.",
"Error loading models", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
LevelData.SETItems = null;
}
if (!string.IsNullOrEmpty(ini.MissionObjectList) && File.Exists(ini.MissionObjectList))
{
List<ObjectData> objectErrors = new List<ObjectData>();
ObjectListEntry[] objlstini = ObjectList.Load(ini.MissionObjectList, false);
for (int ID = 0; ID < objlstini.Length; ID++)
{
string codeaddr = objlstini[ID].CodeString;
if (!objdefini.ContainsKey(codeaddr))
codeaddr = "0";
ObjectData defgroup = objdefini[codeaddr];
ObjectDefinition def;
if (!string.IsNullOrEmpty(defgroup.CodeFile))
{
progress.SetStep("Compiling: " + defgroup.CodeFile);
// TODO: Split this out to a function
#region Compile object code files
string ty = defgroup.CodeType;
string dllfile = Path.Combine("dllcache", ty + ".dll");
DateTime modDate = DateTime.MinValue;
if (File.Exists(dllfile))
modDate = File.GetLastWriteTime(dllfile);
string fp = defgroup.CodeFile.Replace('/', Path.DirectorySeparatorChar);
if (modDate >= File.GetLastWriteTime(fp) && modDate > File.GetLastWriteTime(Application.ExecutablePath))
def =
(ObjectDefinition)
Activator.CreateInstance(
Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, dllfile))
.GetType(ty));
else
{
string ext = Path.GetExtension(fp);
CodeDomProvider pr = null;
switch (ext.ToLowerInvariant())
{
case ".cs":
pr = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
break;
case ".vb":
pr = new Microsoft.VisualBasic.VBCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
break;
}
if (pr != null)
{
CompilerParameters para =
new CompilerParameters(new string[]
{
"System.dll", "System.Core.dll", "System.Drawing.dll", Assembly.GetAssembly(typeof (Vector3)).Location,
Assembly.GetAssembly(typeof (Texture)).Location, Assembly.GetAssembly(typeof (D3DX)).Location,
Assembly.GetExecutingAssembly().Location, Assembly.GetAssembly(typeof (LandTable)).Location,
Assembly.GetAssembly(typeof (EditorCamera)).Location, Assembly.GetAssembly(typeof (SA1LevelAct)).Location,
Assembly.GetAssembly(typeof (ObjectDefinition)).Location
})
{
GenerateExecutable = false,
GenerateInMemory = false,
IncludeDebugInformation = true,
OutputAssembly = Path.Combine(Environment.CurrentDirectory, dllfile)
};
CompilerResults res = pr.CompileAssemblyFromFile(para, fp);
if (res.Errors.HasErrors)
{
// TODO: Merge with existing object error handler. I add too many ToDos.
string errors = null;
foreach (CompilerError item in res.Errors)
errors += String.Format("\n\n{0}, {1}: {2}", item.Line, item.Column, item.ErrorText);
MessageBox.Show("Failed to compile object code file:\n" + defgroup.CodeFile + errors,
"Object compilation failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
def = new DefaultObjectDefinition();
}
else
{
def = (ObjectDefinition)Activator.CreateInstance(res.CompiledAssembly.GetType(ty));
}
}
else
def = new DefaultObjectDefinition();
}
#endregion
}
else
{
def = new DefaultObjectDefinition();
}
LevelData.MisnObjDefs.Add(def);
// The only reason .Model is checked for null is for objects that don't yet have any
// models defined for them. It would be annoying seeing that error all the time!
if (string.IsNullOrEmpty(defgroup.CodeFile) && !string.IsNullOrEmpty(defgroup.Model))
{
progress.SetStep("Loading: " + defgroup.Model);
// Otherwise, if the model file doesn't exist and/or no texture file is defined,
// load the "default object" instead ("?").
if (!File.Exists(defgroup.Model) || string.IsNullOrEmpty(defgroup.Texture) ||
!LevelData.Textures.ContainsKey(defgroup.Texture))
{
ObjectData error = new ObjectData { Name = defgroup.Name, Model = defgroup.Model, Texture = defgroup.Texture };
objectErrors.Add(error);
defgroup.Model = null;
}
}
def.Init(defgroup, objlstini[ID].Name, d3ddevice);
def.SetInternalName(objlstini[ID].Name);
}
// Loading SET Layout
progress.SetTaskAndStep("Loading Mission SET items", "Initializing...");
if (LevelData.MisnObjDefs.Count > 0)
{
string setstr = Path.Combine(syspath, "SETMI" + level.LevelID + "{0}.bin");
string prmstr = Path.Combine(syspath, "PRMMI" + level.LevelID + "{0}.bin");
LevelData.MissionSETItems = new List<MissionSETItem>[LevelData.SETChars.Length];
for (int i = 0; i < LevelData.SETChars.Length; i++)
{
List<MissionSETItem> list = new List<MissionSETItem>();
byte[] setfile = null;
byte[] prmfile = null;
string setfmt = string.Format(setstr, LevelData.SETChars[i]);
string prmfmt = string.Format(prmstr, LevelData.SETChars[i]);
if (modpath != null && File.Exists(Path.Combine(modpath, setfmt)) && File.Exists(Path.Combine(modpath, prmfmt)))
{
setfile = File.ReadAllBytes(Path.Combine(modpath, setfmt));
prmfile = File.ReadAllBytes(Path.Combine(modpath, prmfmt));
}
else if (File.Exists(setfmt) && File.Exists(prmfmt))
{
setfile = File.ReadAllBytes(setfmt);
prmfile = File.ReadAllBytes(prmfmt);
}
if (setfile != null)
{
progress.SetTask("SET: " + setfmt.Replace(Environment.CurrentDirectory, ""));
int count = BitConverter.ToInt32(setfile, 0);
int setaddr = 0x20;
int prmaddr = 0x20;
for (int j = 0; j < count; j++)
{
progress.SetStep(string.Format("{0}/{1}", (j + 1), count));
MissionSETItem ent = new MissionSETItem(setfile, setaddr, prmfile, prmaddr, selectedItems);
list.Add(ent);
setaddr += 0x20;
prmaddr += 0xC;
}
}
LevelData.MissionSETItems[i] = list;
}
}
else
{
LevelData.MissionSETItems = null;
}
// Checks if there have been any errors added to the error list and does its thing
// This thing is a mess. If anyone can think of a cleaner way to do this, be my guest.
if (objectErrors.Count > 0)
{
int count = objectErrors.Count;
List<string> errorStrings = new List<string> { "The following objects failed to load:" };
foreach (ObjectData o in objectErrors)
{
bool texEmpty = string.IsNullOrEmpty(o.Texture);
bool texExists = (!string.IsNullOrEmpty(o.Texture) && LevelData.Textures.ContainsKey(o.Texture));
errorStrings.Add("");
errorStrings.Add("Object:\t\t" + o.Name);
errorStrings.Add("\tModel:");
errorStrings.Add("\t\tName:\t" + o.Model);
errorStrings.Add("\t\tExists:\t" + File.Exists(o.Model));
errorStrings.Add("\tTexture:");
errorStrings.Add("\t\tName:\t" + ((texEmpty) ? "(N/A)" : o.Texture));
errorStrings.Add("\t\tExists:\t" + texExists);
}
// TODO: Proper logging. Who knows where this file may end up
File.WriteAllLines("SADXLVL2.log", errorStrings.ToArray());
MessageBox.Show(count + ((count == 1) ? " object" : " objects") + " failed to load their model(s).\n"
+
"\nThe level will still display, but the objects in question will not display their proper models." +
"\n\nPlease check the log for details.",
"Error loading models", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
LevelData.MissionSETItems = null;
}
progress.StepProgress();
#endregion
#region CAM Layout
progress.SetTaskAndStep("Loading CAM items", "Initializing...");
string camstr = Path.Combine(syspath, "CAM" + LevelData.SETName + "{0}.bin");
LevelData.CAMItems = new List<CAMItem>[LevelData.SETChars.Length];
for (int i = 0; i < LevelData.SETChars.Length; i++)
{
List<CAMItem> list = new List<CAMItem>();
byte[] camfile = null;
string formatted = string.Format(camstr, LevelData.SETChars[i]);
if (modpath != null && File.Exists(Path.Combine(modpath, formatted)))
camfile = File.ReadAllBytes(Path.Combine(modpath, formatted));
else if (File.Exists(formatted))
camfile = File.ReadAllBytes(formatted);
if (camfile != null)
{
progress.SetTask("CAM: " + formatted.Replace(Environment.CurrentDirectory, ""));
int count = BitConverter.ToInt32(camfile, 0);
int address = 0x40;
for (int j = 0; j < count; j++)
{
progress.SetStep(string.Format("{0}/{1}", (j + 1), count));
CAMItem ent = new CAMItem(camfile, address, selectedItems);
list.Add(ent);
address += 0x40;
}
}
LevelData.CAMItems[i] = list;
}
CAMItem.Init(d3ddevice);
progress.StepProgress();
#endregion
#region Loading Level Effects
LevelData.leveleff = null;
if (!string.IsNullOrEmpty(level.Effects))
{
progress.SetTaskAndStep("Loading Level Effects...");
LevelDefinition def = null;
string ty = "SADXObjectDefinitions.Level_Effects." + Path.GetFileNameWithoutExtension(level.Effects);
string dllfile = Path.Combine("dllcache", ty + ".dll");
DateTime modDate = DateTime.MinValue;
if (File.Exists(dllfile))
modDate = File.GetLastWriteTime(dllfile);
string fp = level.Effects.Replace('/', Path.DirectorySeparatorChar);
if (modDate >= File.GetLastWriteTime(fp) && modDate > File.GetLastWriteTime(Application.ExecutablePath))
{
def =
(LevelDefinition)
Activator.CreateInstance(
Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, dllfile)).GetType(ty));
}
else
{
string ext = Path.GetExtension(fp);
CodeDomProvider pr = null;
switch (ext.ToLowerInvariant())
{
case ".cs":
pr = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
break;
case ".vb":
pr = new Microsoft.VisualBasic.VBCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
break;
}
if (pr != null)
{
CompilerParameters para =
new CompilerParameters(new string[]
{
"System.dll", "System.Core.dll", "System.Drawing.dll", Assembly.GetAssembly(typeof (Vector3)).Location,
Assembly.GetAssembly(typeof (Texture)).Location, Assembly.GetAssembly(typeof (D3DX)).Location,
Assembly.GetExecutingAssembly().Location, Assembly.GetAssembly(typeof (LandTable)).Location,
Assembly.GetAssembly(typeof (EditorCamera)).Location, Assembly.GetAssembly(typeof (SA1LevelAct)).Location,
Assembly.GetAssembly(typeof (Item)).Location
})
{
GenerateExecutable = false,
GenerateInMemory = false,
IncludeDebugInformation = true,
OutputAssembly = Path.Combine(Environment.CurrentDirectory, dllfile)
};
CompilerResults res = pr.CompileAssemblyFromFile(para, fp);
if (!res.Errors.HasErrors)
def = (LevelDefinition)Activator.CreateInstance(res.CompiledAssembly.GetType(ty));
}
}
if (def != null)
def.Init(level, levelact.Act, d3ddevice);
LevelData.leveleff = def;
}
progress.StepProgress();
#endregion
#region Loading Splines
LevelData.LevelSplines = new List<SplineData>();
SplineData.Init();
if (!string.IsNullOrEmpty(ini.Paths))
{
progress.SetTaskAndStep("Reticulating splines...");
String splineDirectory = Path.Combine(Path.Combine(Environment.CurrentDirectory, ini.Paths),
levelact.ToString());
if (Directory.Exists(splineDirectory))
{
List<string> pathFiles = new List<string>();
for (int i = 0; i < int.MaxValue; i++)
{
string path = string.Concat(splineDirectory, string.Format("/{0}.ini", i));
if (File.Exists(path))
{
pathFiles.Add(path);
}
else
break;
}
foreach (string pathFile in pathFiles) // looping through path files
{
SplineData newSpline = new SplineData(PathData.Load(pathFile), selectedItems);
newSpline.RebuildMesh(d3ddevice);
LevelData.LevelSplines.Add(newSpline);
}
}
}
progress.StepProgress();
#endregion
#region Stage Lights
progress.SetTaskAndStep("Loading lights...");
if ((stageLightList != null) && (stageLightList.Count > 0))
{
List<SA1StageLightData> lightList = new List<SA1StageLightData>();
foreach (SA1StageLightData lightData in stageLightList)
{
if ((lightData.Level == levelact.Level) && (lightData.Act == levelact.Act))
lightList.Add(lightData);
}
if (lightList.Count > 0)
{
for (int i = 0; i < d3ddevice.Lights.Count; i++) // clear all default lights
{
d3ddevice.Lights[i].Enabled = false;
}
for (int i = 0; i < lightList.Count; i++)
{
SA1StageLightData lightData = lightList[i];
d3ddevice.Lights[i].Enabled = true;
d3ddevice.Lights[i].Type = (lightData.UseDirection) ? LightType.Directional : LightType.Point;
d3ddevice.Lights[i].Diffuse = lightData.RGB.ToColor();
d3ddevice.Lights[i].DiffuseColor = new ColorValue(lightData.RGB.X, lightData.RGB.Y, lightData.RGB.Z, 1.0f);
d3ddevice.Lights[i].Ambient = lightData.AmbientRGB.ToColor();
d3ddevice.Lights[i].Specular = Color.Black;
d3ddevice.Lights[i].Direction = lightData.Direction.ToVector3();
d3ddevice.Lights[i].Range = lightData.Dif; // guessing here
}
}
else
{
MessageBox.Show("No lights were found for this stage. Using default lights instead.", "No lights found",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
progress.StepProgress();
#endregion
transformGizmo = new TransformGizmo();
Invoke((Action)progress.Close);
}
#if !DEBUG
}
catch (Exception ex)
{
MessageBox.Show(
ex.GetType().Name + ": " + ex.Message + "\nLog file has been saved to " + Path.Combine(Environment.CurrentDirectory, "SADXLVL2.log") + ".\nSend this to MainMemory on the Sonic Retro forums.",
"SADXLVL2 Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
File.WriteAllText("SADXLVL2.log", ex.ToString());
initerror = true;
}
#endif
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (initerror)
{
Close();
return;
}
bool isGeometryPresent = LevelData.geo != null;
bool isSETPreset = LevelData.SETItems != null;
bool isDeathZonePresent = LevelData.DeathZones != null;
// Context menu
// Add -> Level Piece
// Does this even make sense? This thing prompts the user to import a model,
// not select an existing one...
levelPieceToolStripMenuItem.Enabled = isGeometryPresent;
// Add -> Object
objectToolStripMenuItem.Enabled = isSETPreset;
// Add -> Mission Object
missionObjectToolStripMenuItem.Enabled = LevelData.MissionSETItems != null;
// File menu
// Save
saveToolStripMenuItem.Enabled = true;
// Import
importToolStripMenuItem.Enabled = isGeometryPresent;
// Export
exportOBJToolStripMenuItem.Enabled = isGeometryPresent;
// Edit menu
// Clear Level
clearLevelToolStripMenuItem.Enabled = isGeometryPresent;
// SET Items submenu
// Gotta clear up these names at some point...
// Drop the 1, and you get the dropdown menu under View.
sETItemsToolStripMenuItem1.Enabled = true;
// Duplicate
duplicateToolStripMenuItem.Enabled = true;
// Calculate All Bounds
calculateAllBoundsToolStripMenuItem.Enabled = isGeometryPresent;
// The whole view menu!
viewToolStripMenuItem.Enabled = true;
statsToolStripMenuItem.Enabled = isGeometryPresent;
deathZonesToolStripMenuItem.Checked = deathZonesToolStripMenuItem.Enabled = deathZoneToolStripMenuItem.Enabled = isDeathZonePresent;
isStageLoaded = true;
selectedItems.SelectionChanged += SelectionChanged;
UseWaitCursor = false;
Enabled = true;
gizmoSpaceComboBox.Enabled = true;
gizmoSpaceComboBox.SelectedIndex = 0;
toolStrip1.Enabled = isStageLoaded;
LevelData_StateChanged();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (isStageLoaded)
{
if (SavePrompt(true) == DialogResult.Cancel)
e.Cancel = true;
LevelData.StateChanged -= LevelData_StateChanged;
}
Settings.Save();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveStage(false);
}
/// <summary>
/// Saves changes made to the currently loaded stage.
/// </summary>
/// <param name="autoCloseDialog">Defines whether or not the progress dialog should close on completion.</param>
private void SaveStage(bool autoCloseDialog)
{
if (!isStageLoaded)
return;
ProgressDialog progress = new ProgressDialog("Saving stage: " + levelName, 6, true, autoCloseDialog);
progress.Show(this);
Application.DoEvents();
IniLevelData level = ini.Levels[levelID];
string syspath = Path.Combine(Environment.CurrentDirectory, ini.SystemPath);
string modpath = ini.ModPath;
SA1LevelAct levelact = new SA1LevelAct(level.LevelID);
progress.SetTaskAndStep("Saving:", "Geometry...");
if (LevelData.geo != null)
{
LevelData.geo.Tool = "SADXLVL2";
LevelData.geo.SaveToFile(level.LevelGeometry, LandTableFormat.SA1);
}
progress.StepProgress();
progress.Step = "Start positions...";
Application.DoEvents();
for (int i = 0; i < LevelData.StartPositions.Length; i++)
{
Dictionary<SA1LevelAct, SA1StartPosInfo> posini =
SA1StartPosList.Load(ini.Characters[LevelData.Characters[i]].StartPositions);
if (posini.ContainsKey(levelact))
posini.Remove(levelact);
if (LevelData.StartPositions[i].Position.X != 0 || LevelData.StartPositions[i].Position.Y != 0 ||
LevelData.StartPositions[i].Position.Z != 0 || LevelData.StartPositions[i].Rotation.Y != 0)
{
posini.Add(levelact,
new SA1StartPosInfo()
{
Position = LevelData.StartPositions[i].Position,
YRotation = LevelData.StartPositions[i].Rotation.Y
});
}
posini.Save(ini.Characters[LevelData.Characters[i]].StartPositions);
}
progress.StepProgress();
progress.Step = "Death zones...";
Application.DoEvents();
if (LevelData.DeathZones != null)
{
DeathZoneFlags[] dzini = new DeathZoneFlags[LevelData.DeathZones.Count];
string path = Path.GetDirectoryName(level.DeathZones);
for (int i = 0; i < LevelData.DeathZones.Count; i++)
dzini[i] = LevelData.DeathZones[i].Save(path, i);
dzini.Save(level.DeathZones);
}
progress.StepProgress();
#region Saving SET Items
progress.Step = "SET items...";
Application.DoEvents();
if (LevelData.SETItems != null)
{
for (int i = 0; i < LevelData.SETItems.Length; i++)
{
string setstr = Path.Combine(syspath, "SET" + LevelData.SETName + LevelData.SETChars[i] + ".bin");
if (modpath != null)
setstr = Path.Combine(modpath, setstr);
// TODO: Consider simply blanking the SET file instead of deleting it.
// Completely deleting it might be undesirable since Sonic's layout will be loaded
// in place of the missing file. And where mods are concerned, you could have conflicts
// with other mods if the file is deleted.
if (File.Exists(setstr))
File.Delete(setstr);
if (LevelData.SETItems[i].Count == 0)
continue;
List<byte> file = new List<byte>(LevelData.SETItems[i].Count*0x20 + 0x20);
file.AddRange(BitConverter.GetBytes(LevelData.SETItems[i].Count));
file.Align(0x20);
foreach (SETItem item in LevelData.SETItems[i])
file.AddRange(item.GetBytes());
File.WriteAllBytes(setstr, file.ToArray());
}
}
progress.StepProgress();
#endregion
#region Saving CAM Items
progress.Step = "CAM items...";
Application.DoEvents();
if (LevelData.CAMItems != null)
{
for (int i = 0; i < LevelData.CAMItems.Length; i++)
{
string camString = Path.Combine(syspath, "CAM" + LevelData.SETName + LevelData.SETChars[i] + ".bin");
if (modpath != null)
camString = Path.Combine(modpath, camString);
// TODO: Handle this differently. File stream? If the user is using a symbolic link for example, we defeat the purpose by deleting it.
if (File.Exists(camString))
File.Delete(camString);
if (LevelData.CAMItems[i].Count == 0)
continue;
List<byte> file = new List<byte>(LevelData.CAMItems[i].Count*0x40 + 0x40); // setting up file size and header
file.AddRange(BitConverter.GetBytes(LevelData.CAMItems[i].Count));
file.Align(0x40);
foreach (CAMItem item in LevelData.CAMItems[i]) // outputting individual components
file.AddRange(item.GetBytes());
File.WriteAllBytes(camString, file.ToArray());
}
}
progress.StepProgress();
progress.SetTaskAndStep("Save complete!");
Application.DoEvents();
#endregion
#region Saving Mission SET Items
progress.Step = "Mission SET items...";
Application.DoEvents();
if (LevelData.MissionSETItems != null)
{
for (int i = 0; i < LevelData.MissionSETItems.Length; i++)
{
string setstr = Path.Combine(syspath, "SETMI" + level.LevelID + LevelData.SETChars[i] + ".bin");
string prmstr = Path.Combine(syspath, "PRMMI" + level.LevelID + LevelData.SETChars[i] + ".bin");
if (modpath != null)
{
setstr = Path.Combine(modpath, setstr);
prmstr = Path.Combine(modpath, prmstr);
}
// TODO: Consider simply blanking the SET file instead of deleting it.
// Completely deleting it might be undesirable since Sonic's layout will be loaded
// in place of the missing file. And where mods are concerned, you could have conflicts
// with other mods if the file is deleted.
if (File.Exists(setstr))
File.Delete(setstr);
if (File.Exists(prmstr))
File.Delete(prmstr);
if (LevelData.MissionSETItems[i].Count == 0)
continue;
List<byte> setfile = new List<byte>(LevelData.MissionSETItems[i].Count * 0x20 + 0x20);
setfile.AddRange(BitConverter.GetBytes(LevelData.MissionSETItems[i].Count));
setfile.Align(0x20);
List<byte> prmfile = new List<byte>(LevelData.MissionSETItems[i].Count * 0xC + 0x20);
prmfile.AddRange(new byte[] { 0, 0, 0x30, 0x56 });
prmfile.Align(0x20);
foreach (MissionSETItem item in LevelData.MissionSETItems[i])
{
setfile.AddRange(item.GetBytes());
prmfile.AddRange(item.GetPRMBytes());
}
File.WriteAllBytes(setstr, setfile.ToArray());
File.WriteAllBytes(prmstr, prmfile.ToArray());
}
}
progress.StepProgress();
#endregion
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
internal void DrawLevel()
{
if (!isStageLoaded)
return;
cam.FOV = (float)(Math.PI / 4);
cam.Aspect = panel1.Width / (float)panel1.Height;
cam.DrawDistance = 100000;
UpdateTitlebar();
#region D3D Parameters
d3ddevice.SetTransform(TransformType.Projection, Matrix.PerspectiveFovRH(cam.FOV, cam.Aspect, 1, cam.DrawDistance));
d3ddevice.SetTransform(TransformType.View, cam.ToMatrix());
d3ddevice.SetRenderState(RenderStates.FillMode, (int)EditorOptions.RenderFillMode);
d3ddevice.SetRenderState(RenderStates.CullMode, (int)EditorOptions.RenderCullMode);
d3ddevice.Material = new Material { Ambient = Color.White };
d3ddevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black.ToArgb(), 1, 0);
d3ddevice.RenderState.ZBufferEnable = true;
#endregion
d3ddevice.BeginScene();
//all drawings after this line
MatrixStack transform = new MatrixStack();
if (LevelData.leveleff != null & backgroundToolStripMenuItem.Checked)
LevelData.leveleff.Render(d3ddevice, cam);
cam.DrawDistance = EditorOptions.RenderDrawDistance;
d3ddevice.SetTransform(TransformType.Projection, Matrix.PerspectiveFovRH(cam.FOV, cam.Aspect, 1, cam.DrawDistance));
d3ddevice.SetTransform(TransformType.View, cam.ToMatrix());
cam.BuildFrustum(d3ddevice.Transform.View, d3ddevice.Transform.Projection);
EditorOptions.RenderStateCommonSetup(d3ddevice);
List<RenderInfo> renderlist = new List<RenderInfo>();
#region Adding Level Geometry
if (LevelData.LevelItems != null)
{
foreach (LevelItem item in LevelData.LevelItems)
{
bool display = false;
if (visibleToolStripMenuItem.Checked && item.Visible)
display = true;
else if (invisibleToolStripMenuItem.Checked && !item.Visible)
display = true;
else if (allToolStripMenuItem.Checked)
display = true;
if (display)
renderlist.AddRange(item.Render(d3ddevice, cam, transform));
}
}
#endregion
renderlist.AddRange(LevelData.StartPositions[LevelData.Character].Render(d3ddevice, cam, transform));
#region Adding splines
if (splinesToolStripMenuItem.Checked)
{
foreach (SplineData spline in LevelData.LevelSplines)
renderlist.AddRange(spline.Render(d3ddevice, cam, transform));
}
#endregion
#region Adding SET Layout
if (LevelData.SETItems != null && sETITemsToolStripMenuItem.Checked)
{
foreach (SETItem item in LevelData.SETItems[LevelData.Character])
renderlist.AddRange(item.Render(d3ddevice, cam, transform));
}
#endregion
#region Adding Death Zones
if (LevelData.DeathZones != null & deathZonesToolStripMenuItem.Checked)
{
foreach (DeathZoneItem item in LevelData.DeathZones)
{
if (item.Visible)
renderlist.AddRange(item.Render(d3ddevice, cam, transform));
}
}
#endregion
#region Adding CAM Layout
if (LevelData.CAMItems != null && cAMItemsToolStripMenuItem.Checked)
{
foreach (CAMItem item in LevelData.CAMItems[LevelData.Character])
renderlist.AddRange(item.Render(d3ddevice, cam, transform));
}
#endregion
#region Adding SET Layout
if (LevelData.MissionSETItems != null && missionSETItemsToolStripMenuItem.Checked)
{
foreach (MissionSETItem item in LevelData.MissionSETItems[LevelData.Character])
renderlist.AddRange(item.Render(d3ddevice, cam, transform));
}
#endregion
RenderInfo.Draw(renderlist, d3ddevice, cam);
d3ddevice.EndScene(); // scene drawings go before this line
#region Draw Helper Objects
foreach (PointHelper pointHelper in PointHelper.Instances)
{
pointHelper.DrawBox(d3ddevice, cam);
}
transformGizmo.Draw(d3ddevice, cam);
foreach (PointHelper pointHelper in PointHelper.Instances)
{
pointHelper.Draw(d3ddevice, cam);
}
#endregion
d3ddevice.Present();
}
private void UpdateTitlebar()
{
Text = "SADXLVL2 - " + levelName + " (" + cam.Position.X + ", " + cam.Position.Y + ", " + cam.Position.Z
+ " Pitch=" + cam.Pitch.ToString("X") + " Yaw=" + cam.Yaw.ToString("X")
+ " Speed=" + cam.MoveSpeed + (cam.mode == 1 ? " Distance=" + cam.Distance : "") + ")";
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
DrawLevel();
}
private void LevelData_PointOperation()
{
MessageBox.Show(this, "You have just begun a Point To operation. Left click on the point or item you want the selected item(s) to point to, or right click to cancel.", "SADXLVL2", MessageBoxButtons.OK, MessageBoxIcon.Information);
isPointOperation = true;
}
#region User Keyboard / Mouse Methods
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (!isStageLoaded)
return;
switch (e.Button)
{
// If the mouse button pressed is not one we're looking for,
// we can avoid re-drawing the scene by bailing out.
default:
return;
case MouseButtons.Left:
Item item;
if (isPointOperation)
{
HitResult res = PickItem(e.Location, out item);
if (item != null)
{
using (PointToDialog dlg = new PointToDialog(res.Position.ToVertex(), item.Position))
if (dlg.ShowDialog(this) == DialogResult.OK)
foreach (SETItem it in System.Linq.Enumerable.OfType<SETItem>(selectedItems.GetSelection()))
it.PointTo(dlg.SelectedLocation);
isPointOperation = false;
}
return;
}
// If we have any helpers selected, don't execute the rest of the method!
if (transformGizmo.SelectedAxes != GizmoSelectedAxes.NONE) return;
foreach (PointHelper pointHelper in PointHelper.Instances) if (pointHelper.SelectedAxes != GizmoSelectedAxes.NONE) return;
PickItem(e.Location, out item);
if (item != null)
{
if (ModifierKeys == Keys.Control)
{
if (selectedItems.GetSelection().Contains(item))
selectedItems.Remove(item);
else
selectedItems.Add(item);
}
else if (!selectedItems.GetSelection().Contains(item))
{
selectedItems.Clear();
selectedItems.Add(item);
}
}
else if ((ModifierKeys & Keys.Control) == 0)
{
selectedItems.Clear();
}
break;
case MouseButtons.Right:
if (isPointOperation)
{
isPointOperation = false;
return;
}
bool cancopy = false;
foreach (Item obj in selectedItems.GetSelection())
{
if (obj.CanCopy)
cancopy = true;
}
if (cancopy)
{
/*cutToolStripMenuItem.Enabled = true;
copyToolStripMenuItem.Enabled = true;*/
deleteToolStripMenuItem.Enabled = true;
cutToolStripMenuItem.Enabled = false;
copyToolStripMenuItem.Enabled = false;
}
else
{
cutToolStripMenuItem.Enabled = false;
copyToolStripMenuItem.Enabled = false;
deleteToolStripMenuItem.Enabled = false;
}
pasteToolStripMenuItem.Enabled = false;
menuLocation = e.Location;
contextMenuStrip1.Show(panel1, e.Location);
break;
}
LevelData_StateChanged();
}
private HitResult PickItem(Point mouse)
{
return PickItem(mouse, out Item item);
}
private HitResult PickItem(Point mouse, out Item item)
{
HitResult closesthit = HitResult.NoHit;
HitResult hit;
item = null;
Vector3 mousepos = new Vector3(mouse.X, mouse.Y, 0);
Viewport viewport = d3ddevice.Viewport;
Matrix proj = d3ddevice.Transform.Projection;
Matrix view = d3ddevice.Transform.View;
Vector3 Near, Far;
Near = mousepos;
Near.Z = 0;
Far = Near;
Far.Z = -1;
#region Picking Level Items
if (LevelData.LevelItems != null)
{
for (int i = 0; i < LevelData.LevelItems.Count; i++)
{
bool display = false;
if (visibleToolStripMenuItem.Checked && LevelData.LevelItems[i].Visible)
display = true;
else if (invisibleToolStripMenuItem.Checked && !LevelData.LevelItems[i].Visible)
display = true;
else if (allToolStripMenuItem.Checked)
display = true;
if (display)
{
hit = LevelData.LevelItems[i].CheckHit(Near, Far, viewport, proj, view);
if (hit < closesthit)
{
closesthit = hit;
item = LevelData.LevelItems[i];
}
}
}
}
#endregion
#region Picking Start Positions
hit = LevelData.StartPositions[LevelData.Character].CheckHit(Near, Far, viewport, proj, view);
if (hit < closesthit)
{
closesthit = hit;
item = LevelData.StartPositions[LevelData.Character];
}
#endregion
#region Picking SET Items
if (LevelData.SETItems != null && sETITemsToolStripMenuItem.Checked)
foreach (SETItem setitem in LevelData.SETItems[LevelData.Character])
{
hit = setitem.CheckHit(Near, Far, viewport, proj, view);
if (hit < closesthit)
{
closesthit = hit;
item = setitem;
}
}
#endregion
#region Picking CAM Items
if ((LevelData.CAMItems != null) && (cAMItemsToolStripMenuItem.Checked))
{
foreach (CAMItem camItem in LevelData.CAMItems[LevelData.Character])
{
hit = camItem.CheckHit(Near, Far, viewport, proj, view);
if (hit < closesthit)
{
closesthit = hit;
item = camItem;
}
}
}
#endregion
#region Picking Death Zones
if (LevelData.DeathZones != null)
{
foreach (DeathZoneItem dzitem in LevelData.DeathZones)
{
if (dzitem.Visible & deathZonesToolStripMenuItem.Checked)
{
hit = dzitem.CheckHit(Near, Far, viewport, proj, view);
if (hit < closesthit)
{
closesthit = hit;
item = dzitem;
}
}
}
}
#endregion
#region Picking Mission SET Items
if (LevelData.MissionSETItems != null && missionSETItemsToolStripMenuItem.Checked)
foreach (MissionSETItem setitem in LevelData.MissionSETItems[LevelData.Character])
{
hit = setitem.CheckHit(Near, Far, viewport, proj, view);
if (hit < closesthit)
{
closesthit = hit;
item = setitem;
}
}
#endregion
#region Picking Splines
if ((LevelData.LevelSplines != null) && (splinesToolStripMenuItem.Checked))
{
foreach (SplineData spline in LevelData.LevelSplines)
{
hit = spline.CheckHit(Near, Far, viewport, proj, view);
if (hit < closesthit)
{
closesthit = hit;
item = spline;
}
}
}
#endregion
return closesthit;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
UpdatePropertyGrid();
}
private void panel1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Left:
case Keys.Right:
case Keys.Up:
e.IsInputKey = true;
break;
}
}
private void panel1_KeyUp(object sender, KeyEventArgs e)
{
lookKeyDown = e.Alt;
zoomKeyDown = e.Control;
}
private void panel1_KeyDown(object sender, KeyEventArgs e)
{
if (!isStageLoaded)
return;
bool draw = false;
if (cam.mode == 0)
{
if (e.KeyCode == Keys.E)
{
cam.Position = new Vector3();
draw = true;
}
if (e.KeyCode == Keys.R)
{
cam.Pitch = 0;
cam.Yaw = 0;
draw = true;
}
}
if ((lookKeyDown = e.Alt) && panel1.ContainsFocus)
e.Handled = false;
zoomKeyDown = e.Control;
switch (e.KeyCode)
{
case Keys.X:
cam.mode = (cam.mode + 1) % 2;
if (cam.mode == 1)
{
if (selectedItems.GetSelection().Count > 0)
cam.FocalPoint = Item.CenterFromSelection(selectedItems.GetSelection()).ToVector3();
else
cam.FocalPoint = cam.Position += cam.Look * cam.Distance;
}
draw = true;
break;
case Keys.Z:
if(selectedItems.ItemCount > 1)
{
BoundingSphere combinedBounds = selectedItems.GetSelection()[0].Bounds;
for (int i = 0; i < selectedItems.ItemCount; i++)
{
combinedBounds = Direct3D.Extensions.Merge(combinedBounds, selectedItems.GetSelection()[i].Bounds);
}
cam.MoveToShowBounds(combinedBounds);
}
else if (selectedItems.ItemCount == 1)
{
cam.MoveToShowBounds(selectedItems.GetSelection()[0].Bounds);
}
draw = true;
break;
case Keys.N:
if (EditorOptions.RenderFillMode == FillMode.Solid)
EditorOptions.RenderFillMode = FillMode.Point;
else
EditorOptions.RenderFillMode += 1;
draw = true;
break;
case Keys.Delete:
foreach (Item item in selectedItems.GetSelection())
item.Delete();
selectedItems.Clear();
draw = true;
break;
case Keys.Add:
cam.MoveSpeed += 0.0625f;
UpdateTitlebar();
break;
case Keys.Subtract:
cam.MoveSpeed -= 0.0625f;
UpdateTitlebar();
break;
case Keys.Enter:
cam.MoveSpeed = EditorCamera.DefaultMoveSpeed;
UpdateTitlebar();
break;
case Keys.Tab:
if (isStageLoaded && e.Control)
{
if (e.Shift)
--LevelData.Character;
else
LevelData.Character = (LevelData.Character + 1) % 6;
if (LevelData.Character < 0)
LevelData.Character = 5;
characterToolStripMenuItem.DropDownItems[LevelData.Character].PerformClick();
}
break;
}
if (draw)
DrawLevel();
}
Point mouseLast;
private void Panel1_MouseMove(object sender, MouseEventArgs e)
{
if (!isStageLoaded)
return;
Point mouseEvent = e.Location;
if (mouseLast == Point.Empty)
{
mouseLast = mouseEvent;
return;
}
Point mouseDelta = mouseEvent - (Size)mouseLast;
bool performedWrap = false;
if (e.Button != MouseButtons.None)
{
Rectangle mouseBounds = (mouseWrapScreen) ? Screen.GetBounds(ClientRectangle) : panel1.RectangleToScreen(panel1.Bounds);
if (Cursor.Position.X < (mouseBounds.Left + mouseWrapThreshold))
{
Cursor.Position = new Point(mouseBounds.Right - mouseWrapThreshold, Cursor.Position.Y);
mouseEvent = new Point(mouseEvent.X + mouseBounds.Width - mouseWrapThreshold, mouseEvent.Y);
performedWrap = true;
}
else if (Cursor.Position.X > (mouseBounds.Right - mouseWrapThreshold))
{
Cursor.Position = new Point(mouseBounds.Left + mouseWrapThreshold, Cursor.Position.Y);
mouseEvent = new Point(mouseEvent.X - mouseBounds.Width + mouseWrapThreshold, mouseEvent.Y);
performedWrap = true;
}
if (Cursor.Position.Y < (mouseBounds.Top + mouseWrapThreshold))
{
Cursor.Position = new Point(Cursor.Position.X, mouseBounds.Bottom - mouseWrapThreshold);
mouseEvent = new Point(mouseEvent.X, mouseEvent.Y + mouseBounds.Height - mouseWrapThreshold);
performedWrap = true;
}
else if (Cursor.Position.Y > (mouseBounds.Bottom - mouseWrapThreshold))
{
Cursor.Position = new Point(Cursor.Position.X, mouseBounds.Top + mouseWrapThreshold);
mouseEvent = new Point(mouseEvent.X, mouseEvent.Y - mouseBounds.Height + mouseWrapThreshold);
performedWrap = true;
}
}
switch (e.Button)
{
case MouseButtons.Middle:
// all cam controls are now bound to the middle mouse button
if (cam.mode == 0)
{
if (zoomKeyDown)
{
cam.Position += cam.Look * (mouseDelta.Y * cam.MoveSpeed);
}
else if (lookKeyDown)
{
cam.Yaw = unchecked((ushort)(cam.Yaw - mouseDelta.X * 0x10));
cam.Pitch = unchecked((ushort)(cam.Pitch - mouseDelta.Y * 0x10));
}
else if (!lookKeyDown && !zoomKeyDown) // pan
{
cam.Position += cam.Up * (mouseDelta.Y * cam.MoveSpeed);
cam.Position += cam.Right * (mouseDelta.X * cam.MoveSpeed) * -1;
}
}
else if (cam.mode == 1)
{
if (zoomKeyDown)
{
cam.Distance += (mouseDelta.Y * cam.MoveSpeed) * 3;
}
else if (lookKeyDown)
{
cam.Yaw = unchecked((ushort)(cam.Yaw - mouseDelta.X * 0x10));
cam.Pitch = unchecked((ushort)(cam.Pitch - mouseDelta.Y * 0x10));
}
else if (!lookKeyDown && !zoomKeyDown) // pan
{
cam.FocalPoint += cam.Up * (mouseDelta.Y * cam.MoveSpeed);
cam.FocalPoint += cam.Right * (mouseDelta.X * cam.MoveSpeed) * -1;
}
}
DrawLevel();
break;
case MouseButtons.Left:
foreach(PointHelper pointHelper in PointHelper.Instances)
{
pointHelper.TransformAffected(mouseDelta.X / 2 * cam.MoveSpeed, mouseDelta.Y / 2 * cam.MoveSpeed, cam);
}
transformGizmo.TransformAffected(mouseDelta.X / 2 * cam.MoveSpeed, mouseDelta.Y / 2 * cam.MoveSpeed, cam);
DrawLevel();
break;
case MouseButtons.None:
Vector3 mousepos = new Vector3(e.X, e.Y, 0);
Viewport viewport = d3ddevice.Viewport;
Matrix proj = d3ddevice.Transform.Projection;
Matrix view = d3ddevice.Transform.View;
Vector3 Near = mousepos;
Near.Z = 0;
Vector3 Far = Near;
Far.Z = -1;
GizmoSelectedAxes oldSelection = transformGizmo.SelectedAxes;
transformGizmo.SelectedAxes = transformGizmo.CheckHit(Near, Far, viewport, proj, view, cam);
if (oldSelection != transformGizmo.SelectedAxes)
{
transformGizmo.Draw(d3ddevice, cam);
d3ddevice.Present();
break;
}
foreach (PointHelper pointHelper in PointHelper.Instances)
{
GizmoSelectedAxes oldHelperAxes = pointHelper.SelectedAxes;
pointHelper.SelectedAxes = pointHelper.CheckHit(Near, Far, viewport, proj, view, cam);
if (oldHelperAxes != pointHelper.SelectedAxes) pointHelper.Draw(d3ddevice, cam);
d3ddevice.Present();
}
break;
}
if (performedWrap || Math.Abs(mouseDelta.X / 2) * cam.MoveSpeed > 0 || Math.Abs(mouseDelta.Y / 2) * cam.MoveSpeed > 0)
{
mouseLast = mouseEvent;
if (e.Button != MouseButtons.None && selectedItems.ItemCount > 0)
UpdatePropertyGrid();
}
}
void panel1_MouseWheel(object sender, MouseEventArgs e)
{
if (!isStageLoaded || !panel1.Focused)
return;
float detentValue = -1;
if (e.Delta < 0)
detentValue = 1;
if (cam.mode == 0)
cam.Position += cam.Look * (detentValue * cam.MoveSpeed);
else if (cam.mode == 1)
cam.Distance += (detentValue * cam.MoveSpeed);
DrawLevel();
}
#endregion
void SelectionChanged(EditorItemSelection sender)
{
propertyGrid1.SelectedObjects = sender.GetSelection().ToArray();
if (cam.mode == 1)
{
cam.FocalPoint = Item.CenterFromSelection(selectedItems.GetSelection()).ToVector3();
}
if (sender.ItemCount > 0) // set up gizmo
{
transformGizmo.Enabled = true;
transformGizmo.AffectedItems = selectedItems.GetSelection();
}
else
{
if (transformGizmo != null)
{
transformGizmo.AffectedItems = new List<Item>();
transformGizmo.Enabled = false;
}
}
}
/// <summary>
/// Refreshes the properties for the currently selected items.
/// </summary>
private void UpdatePropertyGrid()
{
propertyGrid1.Refresh();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Item> selitems = new List<Item>();
foreach (Item item in selectedItems.GetSelection())
{
if (item.CanCopy)
{
item.Delete();
selitems.Add(item);
}
}
selectedItems.Clear();
LevelData_StateChanged();
if (selitems.Count == 0) return;
Clipboard.SetData(DataFormats.Serializable, selitems);
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Item> selitems = new List<Item>();
foreach (Item item in selectedItems.GetSelection())
{
if (item.CanCopy)
selitems.Add(item);
}
if (selitems.Count == 0)
return;
Clipboard.SetData("SADXLVLObjectList", selitems);
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
object obj = Clipboard.GetData("SADXLVLObjectList");
if (obj == null)
{
MessageBox.Show("Paste operation failed - this is a known issue and is being worked on.");
return; // todo: finish implementing proper copy/paste
}
List<Item> objs = (List<Item>)obj;
Vector3 center = new Vector3();
foreach (Item item in objs)
center.Add(item.Position.ToVector3());
center = new Vector3(center.X / objs.Count, center.Y / objs.Count, center.Z / objs.Count);
foreach (Item item in objs)
{
item.Position = new Vertex(item.Position.X - center.X + cam.Position.X, item.Position.Y - center.Y + cam.Position.Y, item.Position.Z - center.Z + cam.Position.Z);
item.Paste();
}
selectedItems.Clear();
selectedItems.Add(new List<Item>(objs));
LevelData_StateChanged();
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Item item in selectedItems.GetSelection())
{
if (item.CanCopy)
item.Delete();
}
selectedItems.Clear();
LevelData_StateChanged();
}
private void characterToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
LevelData.Character = characterToolStripMenuItem.DropDownItems.IndexOf(e.ClickedItem);
// Character view buttons
toolSonic.Checked = false;
toolTails.Checked = false;
toolKnuckles.Checked = false;
toolAmy.Checked = false;
toolBig.Checked = false;
toolGamma.Checked = false;
UncheckMenuItems(characterToolStripMenuItem);
((ToolStripMenuItem)e.ClickedItem).Checked = true;
switch (LevelData.Character)
{
default:
toolSonic.Checked = true;
break;
case 1:
toolTails.Checked = true;
break;
case 2:
toolKnuckles.Checked = true;
break;
case 3:
toolAmy.Checked = true;
break;
case 4:
toolGamma.Checked = true;
break;
case 5:
toolBig.Checked = true;
break;
}
transformGizmo.Enabled = false;
if (transformGizmo.AffectedItems != null)
transformGizmo.AffectedItems.Clear();
DrawLevel();
}
private void onClickCharacterButton(object sender, EventArgs e)
{
if (sender == toolTails)
tailsToolStripMenuItem.PerformClick();
else if (sender == toolKnuckles)
knucklesToolStripMenuItem.PerformClick();
else if (sender == toolAmy)
amyToolStripMenuItem.PerformClick();
else if (sender == toolBig)
bigToolStripMenuItem.PerformClick();
else if (sender == toolGamma)
gammaToolStripMenuItem.PerformClick();
else
sonicToolStripMenuItem.PerformClick();
}
private void levelToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
UncheckMenuItems(levelToolStripMenuItem);
((ToolStripMenuItem)e.ClickedItem).Checked = true;
transformGizmo.Enabled = false;
transformGizmo.AffectedItems.Clear();
DrawLevel();
}
private void levelPieceToolStripMenuItem_Click(object sender, EventArgs e)
{
if (importFileDialog.ShowDialog() != DialogResult.OK)
return;
foreach (string s in importFileDialog.FileNames)
{
selectedItems.Add(LevelData.ImportFromFile(s, d3ddevice, cam, out bool errorFlag, out string errorMsg, selectedItems));
if (errorFlag)
MessageBox.Show(errorMsg);
}
LevelData_StateChanged();
}
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
if (importFileDialog.ShowDialog() != DialogResult.OK)
return;
DialogResult userClearLevelResult = MessageBox.Show("Do you want to clear the level models first?", "Clear Level?", MessageBoxButtons.YesNoCancel);
if (userClearLevelResult == DialogResult.Cancel)
return;
if (userClearLevelResult == DialogResult.Yes)
{
DialogResult clearAnimsResult = MessageBox.Show("Do you also want to clear any animated level models?", "Clear anims too?", MessageBoxButtons.YesNo);
LevelData.ClearLevelGeometry();
if (clearAnimsResult == DialogResult.Yes)
{
LevelData.ClearLevelGeoAnims();
}
}
foreach (string s in importFileDialog.FileNames)
{
selectedItems.Add(LevelData.ImportFromFile(s, d3ddevice, cam, out bool errorFlag, out string errorMsg, selectedItems));
if (errorFlag)
MessageBox.Show(errorMsg);
}
LevelData_StateChanged();
}
private void objectToolStripMenuItem_Click(object sender, EventArgs e)
{
using (NewObjectDialog dlg = new NewObjectDialog(false))
if (dlg.ShowDialog(this) == DialogResult.OK)
{
HitResult hit = PickItem(menuLocation);
SETItem item = new SETItem(dlg.ID, selectedItems);
Vector3 pos;
if (hit.IsHit)
{
pos = hit.Position + (hit.Normal * item.GetObjectDefinition().DistanceFromGround);
item.SetOrientation(hit.Normal.ToVertex());
}
else
pos = cam.Position + (-20 * cam.Look);
item.Position = new Vertex(pos.X, pos.Y, pos.Z);
LevelData.SETItems[LevelData.Character].Add(item);
selectedItems.Clear();
selectedItems.Add(item);
LevelData_StateChanged();
}
}
private void cameraToolStripMenuItem_Click(object sender, EventArgs e)
{
Vector3 pos = cam.Position + (-20 * cam.Look);
CAMItem item = new CAMItem(new Vertex(pos.X, pos.Y, pos.Z), selectedItems);
LevelData.CAMItems[LevelData.Character].Add(item);
selectedItems.Clear();
selectedItems.Add(item);
LevelData_StateChanged();
}
private void missionObjectToolStripMenuItem_Click(object sender, EventArgs e)
{
using (NewObjectDialog dlg = new NewObjectDialog(true))
if (dlg.ShowDialog(this) == DialogResult.OK)
{
HitResult hit = PickItem(menuLocation);
MissionSETItem item = new MissionSETItem(dlg.ObjectList, dlg.ID, selectedItems);
Vector3 pos;
if (hit.IsHit)
{
pos = hit.Position + (hit.Normal * item.GetObjectDefinition().DistanceFromGround);
item.SetOrientation(hit.Normal.ToVertex());
}
else
pos = cam.Position + (-20 * cam.Look);
item.Position = new Vertex(pos.X, pos.Y, pos.Z);
LevelData.MissionSETItems[LevelData.Character].Add(item);
selectedItems.Clear();
selectedItems.Add(item);
LevelData_StateChanged();
}
}
private void exportOBJToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog a = new SaveFileDialog
{
DefaultExt = "obj",
Filter = "OBJ Files|*.obj"
};
if (a.ShowDialog() == DialogResult.OK)
{
using (StreamWriter objstream = new StreamWriter(a.FileName, false))
using (StreamWriter mtlstream = new StreamWriter(Path.ChangeExtension(a.FileName, "mtl"), false))
{
#region Material Exporting
string materialPrefix = LevelData.leveltexs;
objstream.WriteLine("mtllib " + Path.GetFileNameWithoutExtension(a.FileName) + ".mtl");
int stepCount = LevelData.TextureBitmaps[LevelData.leveltexs].Length + LevelData.geo.COL.Count;
if (LevelData.geo.Anim != null)
stepCount += LevelData.geo.Anim.Count;
ProgressDialog progress = new ProgressDialog("Exporting stage: " + levelName, stepCount, true, false);
progress.Show(this);
progress.SetTaskAndStep("Exporting...");
// This is admittedly not an accurate representation of the materials used in the model - HOWEVER, it makes the materials more managable in MAX
// So we're doing it this way. In the future we should come back and add an option to do it this way or the original way.
for (int i = 0; i < LevelData.TextureBitmaps[LevelData.leveltexs].Length; i++)
{
mtlstream.WriteLine("newmtl {0}_material_{1}", materialPrefix, i);
mtlstream.WriteLine("Ka 1 1 1");
mtlstream.WriteLine("Kd 1 1 1");
mtlstream.WriteLine("Ks 0 0 0");
mtlstream.WriteLine("illum 1");
if (!string.IsNullOrEmpty(LevelData.leveltexs))
{
mtlstream.WriteLine("Map_Kd " + LevelData.TextureBitmaps[LevelData.leveltexs][i].Name + ".png");
// save texture
string mypath = Path.GetDirectoryName(a.FileName);
BMPInfo item = LevelData.TextureBitmaps[LevelData.leveltexs][i];
item.Image.Save(Path.Combine(mypath, item.Name + ".png"));
}
progress.Step = String.Format("Texture {0}/{1}", i + 1, LevelData.TextureBitmaps[LevelData.leveltexs].Length);
progress.StepProgress();
Application.DoEvents();
}
#endregion
int totalVerts = 0;
int totalNorms = 0;
int totalUVs = 0;
bool errorFlag = false;
for (int i = 0; i < LevelData.geo.COL.Count; i++)
{
Direct3D.Extensions.WriteModelAsObj(objstream, LevelData.geo.COL[i].Model, materialPrefix, new MatrixStack(),
ref totalVerts, ref totalNorms, ref totalUVs, ref errorFlag);
progress.Step = String.Format("Mesh {0}/{1}", i + 1, LevelData.geo.COL.Count);
progress.StepProgress();
Application.DoEvents();
}
if (LevelData.geo.Anim != null)
{
for (int i = 0; i < LevelData.geo.Anim.Count; i++)
{
Direct3D.Extensions.WriteModelAsObj(objstream, LevelData.geo.Anim[i].Model, materialPrefix, new MatrixStack(),
ref totalVerts, ref totalNorms, ref totalUVs, ref errorFlag);
progress.Step = String.Format("Animation {0}/{1}", i + 1, LevelData.geo.Anim.Count);
progress.StepProgress();
Application.DoEvents();
}
}
if (errorFlag)
{
MessageBox.Show("Error(s) encountered during export. Inspect the output file for more details.", "Failure",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
progress.SetTaskAndStep("Export complete!");
}
}
}
private void deathZoneToolStripMenuItem_Click(object sender, EventArgs e)
{
DeathZoneItem item = new DeathZoneItem(d3ddevice, selectedItems);
Vector3 pos = cam.Position + (-20 * cam.Look);
item.Position = new Vertex(pos.X, pos.Y, pos.Z);
switch (LevelData.Character)
{
case 0:
item.Sonic = true;
break;
case 1:
item.Tails = true;
break;
case 2:
item.Knuckles = true;
break;
case 3:
item.Amy = true;
break;
case 4:
item.Gamma = true;
break;
case 5:
item.Big = true;
break;
}
selectedItems.Clear();
selectedItems.Add(item);
LevelData_StateChanged();
}
private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
LevelData_StateChanged();
propertyGrid1.Refresh();
}
private void backgroundToolStripMenuItem_Click(object sender, EventArgs e)
{
DrawLevel();
}
private void recentProjectsToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
LoadINI(Settings.MRUList[recentProjectsToolStripMenuItem.DropDownItems.IndexOf(e.ClickedItem)]);
}
private void reportBugToolStripMenuItem_Click(object sender, EventArgs e)
{
using (BugReportDialog dlg = new BugReportDialog("SADXLVL2", null))
dlg.ShowDialog(this);
}
void LevelData_StateChanged()
{
if (transformGizmo != null)
transformGizmo.AffectedItems = selectedItems.GetSelection();
DrawLevel();
}
private void statsToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(LevelData.GetStats());
}
private void sETITemsToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
DrawLevel();
}
private void cAMItemsToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
DrawLevel();
}
private void deathZonesToolStripMenuItem_Click(object sender, EventArgs e)
{
DrawLevel();
}
private void findReplaceToolStripMenuItem_Click(object sender, EventArgs e)
{
SETFindReplace findReplaceForm = new SETFindReplace();
DialogResult findReplaceResult = findReplaceForm.ShowDialog();
if (findReplaceResult == DialogResult.OK)
{
LevelData_StateChanged();
}
}
private void duplicateToolStripMenuItem_Click(object sender, EventArgs e)
{
LevelData.DuplicateSelection(d3ddevice, selectedItems, out bool errorFlag, out string errorMsg);
if (errorFlag) MessageBox.Show(errorMsg);
}
private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
{
EditorOptionsEditor optionsEditor = new EditorOptionsEditor(cam);
optionsEditor.FormUpdated += optionsEditor_FormUpdated;
optionsEditor.Show();
}
void optionsEditor_FormUpdated()
{
DrawLevel();
}
#region Gizmo Button Event Methods
private void selectModeButton_Click(object sender, EventArgs e)
{
if (transformGizmo != null)
{
transformGizmo.Mode = TransformMode.NONE;
gizmoSpaceComboBox.Enabled = true;
moveModeButton.Checked = false;
rotateModeButton.Checked = false;
DrawLevel(); // TODO: possibly find a better way of doing this than re-drawing the entire scene? Possibly keep a copy of the last render w/o gizmo in memory?
}
}
private void moveModeButton_Click(object sender, EventArgs e)
{
if (transformGizmo != null)
{
transformGizmo.Mode = TransformMode.TRANFORM_MOVE;
gizmoSpaceComboBox.Enabled = true;
selectModeButton.Checked = false;
rotateModeButton.Checked = false;
scaleModeButton.Checked = false;
DrawLevel();
}
}
private void rotateModeButton_Click(object sender, EventArgs e)
{
if (transformGizmo != null)
{
transformGizmo.Mode = TransformMode.TRANSFORM_ROTATE;
transformGizmo.LocalTransform = true;
gizmoSpaceComboBox.SelectedIndex = 1;
gizmoSpaceComboBox.Enabled = false;
selectModeButton.Checked = false;
moveModeButton.Checked = false;
scaleModeButton.Checked = false;
DrawLevel();
}
}
private void gizmoSpaceComboBox_DropDownClosed(object sender, EventArgs e)
{
if (transformGizmo != null)
{
transformGizmo.LocalTransform = (gizmoSpaceComboBox.SelectedIndex != 0);
DrawLevel();
}
}
private void scaleModeButton_Click(object sender, EventArgs e)
{
if (transformGizmo != null)
{
transformGizmo.Mode = TransformMode.TRANSFORM_SCALE;
transformGizmo.LocalTransform = true;
gizmoSpaceComboBox.SelectedIndex = 1;
gizmoSpaceComboBox.Enabled = false;
selectModeButton.Checked = false;
moveModeButton.Checked = false;
DrawLevel();
}
}
#endregion
private void duplicateToToolStripMenuItem_Click(object sender, EventArgs e)
{
if (selectedItems.ItemCount > 0)
{
MessageBox.Show("To use this feature you must have a selection!");
return;
}
DuplicateTo duplicateToWindow = new DuplicateTo(selectedItems);
duplicateToWindow.ShowDialog();
}
private void deleteAllOfTypeToolStripMenuItem_Click(object sender, EventArgs e)
{
transformGizmo.Enabled = false;
transformGizmo.AffectedItems = null; // just in case we wind up deleting our selection
SETDeleteType typeDeleter = new SETDeleteType();
typeDeleter.ShowDialog();
}
private void splinesToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
DrawLevel();
}
private void changeLevelToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowLevelSelect();
}
private void recentProjectsToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowQuickStart();
}
private void toolClearGeometry_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("This will remove all of the geometry from the stage.\n\nAre you sure you want to continue?",
"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result != DialogResult.Yes)
return;
LevelData.ClearLevelGeometry();
}
private void toolClearAnimations_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("This will remove all of the geometry animations from the stage.\n\nAre you sure you want to continue?",
"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result != DialogResult.Yes)
return;
LevelData.ClearLevelGeoAnims();
}
private void toolClearSetItems_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("This will remove all objects from the stage for the current character.\n\nAre you sure you want to continue?",
"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result != DialogResult.Yes)
return;
LevelData.ClearSETItems(LevelData.Character);
}
private void toolClearCamItems_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("This will remove all camera items from the stage for the current character.\n\nAre you sure you want to continue?",
"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result != DialogResult.Yes)
return;
LevelData.ClearCAMItems(LevelData.Character);
}
private void toolClearMissionSetItems_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("This will remove all mission objects from the stage for the current character.\n\nAre you sure you want to continue?",
"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result != DialogResult.Yes)
return;
LevelData.ClearMissionSETItems(LevelData.Character);
}
private void toolClearAll_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("This will clear the entire stage.\n\nAre you sure you want to continue?",
"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
return;
result = MessageBox.Show("Would you like to clear SET & CAM items for all characters?", "SET Items", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
if (result == DialogResult.Cancel)
return;
if (result == DialogResult.Yes)
{
LevelData.ClearSETItems();
LevelData.ClearCAMItems();
LevelData.ClearMissionSETItems();
}
else
{
LevelData.ClearSETItems(LevelData.Character);
LevelData.ClearCAMItems(LevelData.Character);
LevelData.ClearMissionSETItems(LevelData.Character);
}
LevelData.ClearLevelGeoAnims();
LevelData.ClearLevelGeometry();
}
private void pointToolStripMenuItem_Click(object sender, EventArgs e)
{
for (int i = 1; i < selectedItems.ItemCount; i++)
{
Item a = selectedItems.Get(i - 1);
Item b = selectedItems.Get(i);
// TODO: Put somewhere else for use with other things, and configurable axis to point on (i.e Y for springs)
Matrix m = Matrix.LookAtLH(a.Position.ToVector3(), b.Position.ToVector3(), new Vector3(0, 1, 0));
a.Rotation.YDeg = (float)Math.Atan2(m.M13, m.M33) * MathHelper.Rad2Deg;
a.Rotation.XDeg = (float)Math.Asin(-m.M23) * MathHelper.Rad2Deg;
a.Rotation.ZDeg = (float)Math.Atan2(m.M21, m.M22) * MathHelper.Rad2Deg;
LevelData_StateChanged();
}
}
private void calculateAllBoundsToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (LevelItem item in LevelData.LevelItems)
item.CalculateBounds();
}
}
} |
using ALM.ServicioAdminEmpresas.Datos;
using ALM.ServicioAdminEmpresas.Entidades;
using System.Collections.Generic;
namespace ALM.ServicioAdminEmpresas.Negocio
{
public class NReemplazarMVC
{
public List<EReemplazarMVC> ObtenerReemplazarMVC()
{
return new DReemplazarMVC().ObtenerReemplazarMVC();
}
}
}
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
namespace Publicon.API.Binders.BodyandRoute
{
public class BodyAndRouteModelBinderProvider : IModelBinderProvider
{
private BodyModelBinderProvider _bodyModelBinderProvider;
private ComplexTypeModelBinderProvider _complexTypeModelBinderProvider;
public BodyAndRouteModelBinderProvider(BodyModelBinderProvider bodyModelBinderProvider, ComplexTypeModelBinderProvider complexTypeModelBinderProvider)
{
_bodyModelBinderProvider = bodyModelBinderProvider;
_complexTypeModelBinderProvider = complexTypeModelBinderProvider;
}
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
var bodyBinder = _bodyModelBinderProvider.GetBinder(context);
var complexBinder = _complexTypeModelBinderProvider.GetBinder(context);
if (context.BindingInfo.BindingSource != null
&& context.BindingInfo.BindingSource.CanAcceptDataFrom(BodyAndRouteBindingSource.BodyAndRoute))
{
return new BodyAndRouteModelBinder(bodyBinder, complexBinder);
}
else
{
return null;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace billetera
{
class Billetera
{
//Es para definir todas las propiedades
#region Propiedades
public string Gastar { get; set; }
public int Depositar { get; set; }
#endregion
public void ImprimirDienro(List<Billetera> billeteras)
{
Console.WriteLine("Ingrese cunato quire gastar");
Gastar = Console.ReadLine();
Console.WriteLine("Ingrese cuanto quiere depositar");
Depositar = Convert.ToInt32(Console.ReadLine());
}
public void Listarbilletera(List<Billetera> users)
{
foreach (var item in users)
{
Console.WriteLine($"Gastar: {item.Gastar} Depositar: {item.Depositar}");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using SFP.Persistencia.Dao;
using SFP.Persistencia.Model;
using SFP.SIT.SERV.Model.ADM;
namespace SFP.SIT.SERV.Dao.ADM
{
public class SIT_ADM_DIANOLABORALDao : BaseDao
{
public SIT_ADM_DIANOLABORALDao(DbConnection cn, DbTransaction transaction, String dataAdapter) : base(cn, transaction, dataAdapter)
{
}
public Object dmlAgregar(SIT_ADM_DIANOLABORAL oDatos)
{
String sSQL = " INSERT INTO SIT_ADM_DIANOLABORAL( diatipo, diaclave) VALUES ( :P0, :P1) ";
return EjecutaDML ( sSQL, oDatos.diatipo, oDatos.diaclave );
}
public int dmlImportar( List<SIT_ADM_DIANOLABORAL> lstDatos)
{
int iTotReg = 0;
String sSQL = " INSERT INTO SIT_ADM_DIANOLABORAL( diatipo, diaclave) VALUES ( :P0, :P1) ";
foreach (SIT_ADM_DIANOLABORAL oDatos in lstDatos)
{
EjecutaDML ( sSQL, oDatos.diatipo, oDatos.diaclave );
iTotReg++;
}
return iTotReg;
}
public int dmlEditar(SIT_ADM_DIANOLABORAL oDatos)
{
String sSQL = " UPDATE SIT_ADM_DIANOLABORAL SET diatipo = :P0 WHERE diaclave = :P1 ";
return (int) EjecutaDML ( sSQL, oDatos.diatipo, oDatos.diaclave );
}
public int dmlBorrar(SIT_ADM_DIANOLABORAL oDatos)
{
String sSQL = " DELETE FROM SIT_ADM_DIANOLABORAL WHERE diaclave = :P0 ";
return (int) EjecutaDML ( sSQL, oDatos.diaclave );
}
public List<SIT_ADM_DIANOLABORAL> dmlSelectTabla( )
{
String sSQL = " SELECT * FROM SIT_ADM_DIANOLABORAL ";
return CrearListaMDL<SIT_ADM_DIANOLABORAL>(ConsultaDML(sSQL) as DataTable);
}
public List<ComboMdl> dmlSelectCombo( )
{
throw new NotImplementedException();
}
public Dictionary<int, string> dmlSelectDiccionario( )
{
throw new NotImplementedException();
}
public SIT_ADM_DIANOLABORAL dmlSelectID(SIT_ADM_DIANOLABORAL oDatos )
{
String sSQL = " SELECT * FROM SIT_ADM_DIANOLABORAL WHERE diaclave = :P0 ";
return CrearListaMDL<SIT_ADM_DIANOLABORAL>(ConsultaDML ( sSQL, oDatos.diaclave ) as DataTable)[0];
}
public object dmlCRUD( Dictionary<string, object> dicParam )
{
int iOper = (int)dicParam[CMD_OPERACION];
if (iOper == OPE_INSERTAR)
return dmlAgregar(dicParam[CMD_ENTIDAD] as SIT_ADM_DIANOLABORAL );
else if (iOper == OPE_EDITAR)
return dmlEditar(dicParam[CMD_ENTIDAD] as SIT_ADM_DIANOLABORAL );
else if (iOper == OPE_BORRAR)
return dmlBorrar(dicParam[CMD_ENTIDAD] as SIT_ADM_DIANOLABORAL );
else
return 0;
}
/*INICIO*/
public DataTable dmlSelectGrid(BasePagMdl baseMdl)
{
String sqlQuery = " WITH Resultado AS( select COUNT(*) OVER() RESULT_COUNT, rownum recid, a.* from ( "
+ " SELECT diaclave, diatipo from SIT_ADM_DIANOLABORAL "
+ " ) a ) SELECT * from Resultado WHERE recid between :P0 and :P1 ";
return (DataTable)ConsultaDML(sqlQuery, baseMdl.LimInf, baseMdl.LimSup);
}
public Dictionary<Int64, char> dmlSelectDiccionarioDiaLaboral()
{
Dictionary<Int64, char> dicParametros = new Dictionary<Int64, char>();
DataTable dtDatos;
DateTime dmDia;
string sqlQuery = " SELECT diaclave, diatipo from SIT_ADM_DIANOLABORAL ";
dtDatos = (DataTable)ConsultaDML(sqlQuery);
foreach (DataRow drDatos in dtDatos.Rows)
{
dmDia = (DateTime)drDatos["diaclave"];
dicParametros.Add(dmDia.Ticks, Convert.ToChar(drDatos["diatipo"]));
}
return dicParametros;
}
/*FIN*/
}
}
|
using System.Collections;
namespace Game.Online.API.Requests
{
public interface IAPIRequest
{
string AdditionalPath { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Store.Books.Localization.Model;
namespace Store.Books.Localization.Data
{
public class StoreBooksLocalizationContext : DbContext
{
public StoreBooksLocalizationContext (DbContextOptions<StoreBooksLocalizationContext> options)
: base(options)
{
}
public DbSet<Store.Books.Localization.Model.Translation> Translation { get; set; }
}
}
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using lianda.Component;
namespace lianda.LD30
{
/// <summary>
/// LD3050 的摘要说明。
/// </summary>
public class LD3050 : BasePage
{
protected System.Web.UI.WebControls.Button Button3;
protected Infragistics.WebUI.WebSchedule.WebDateChooser dcsWTRQ;
protected Infragistics.WebUI.WebSchedule.WebDateChooser dcsWTRQ2;
protected System.Web.UI.WebControls.TextBox txtPM;
protected System.Web.UI.WebControls.TextBox WTDWMC;
protected System.Web.UI.WebControls.TextBox WTDW;
protected System.Web.UI.WebControls.TextBox SHDWMC;
protected System.Web.UI.WebControls.TextBox SHDW;
protected System.Web.UI.HtmlControls.HtmlImage IMG1;
protected System.Web.UI.HtmlControls.HtmlImage Img2;
protected DataDynamics.ActiveReports.Web.WebViewer WebViewer1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!this.IsPostBack)
{
this.dcsWTRQ.Value = DateTime.Today.AddDays(-1);
this.dcsWTRQ2.Value = DateTime.Today;
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
#region 报表数据源
/// <summary>
/// 报表数据源
/// </summary>
/// <returns>报表数据源</returns>
private SqlDataReader rptData()
{
string strSql = "";
strSql = "SELECT a.CKDH, a.CKRQ, a.WTDW, a.WTDWMC, a.SHDW, a.SHDWMC, a.CCM, a.JZHJ,";
strSql += " a.MZHJ, a.JSHJ, a.BZ, b.MXXH, b.PM, b.HTH, b.GG, b.GZ, b.CLH, b.JZ, b.MZ, b.JS, ";
strSql += " b.BZ AS MXBZ, b.RKDH, b.RKMXH";
strSql += " FROM C_CKD a LEFT OUTER JOIN C_CKDMX b ON a.CKDH = b.CKDH AND b.SC = 'N'";
strSql += " WHERE (a.SC = 'N') ";
// 委托单位
if (this.WTDW.Text != "")
strSql += " and a.WTDW='"+ this.WTDW.Text +"'";
// 收货单位
if (this.SHDW.Text != "")
strSql += " and a.SHDW='"+ this.SHDW.Text +"'";
// 品名
if (this.txtPM.Text.Trim() != "")
strSql += " and b.PM='"+ this.txtPM.Text.Trim() +"'";
// 出库时间
if (this.dcsWTRQ.Value != null && this.dcsWTRQ.Value != System.DBNull.Value)
strSql += " and CONVERT(char(8),a.CKRQ,112) >= '"+ Convert.ToDateTime(this.dcsWTRQ.Value).ToString("yyyyMMdd") +"'";
if (this.dcsWTRQ2.Value != null && this.dcsWTRQ2.Value != System.DBNull.Value)
strSql += " and CONVERT(char(8),a.CKRQ,112) <= '"+ Convert.ToDateTime(this.dcsWTRQ2.Value).ToString("yyyyMMdd") +"'";
strSql += " ORDER BY a.CKDH, b.MXXH";
SqlDataReader dr;
dr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSql,null);
return dr;
}
#endregion
private void Button3_Click(object sender, System.EventArgs e)
{
if(this.dcsWTRQ.Value == null || this.dcsWTRQ2.Value == null || this.dcsWTRQ.Value == DBNull.Value || this.dcsWTRQ2.Value == DBNull.Value)
{
this.msgbox("请先选择日期!");
return;
}
this.WebViewer1.ClearCachedReport();
DataDynamics.ActiveReports.ActiveReport ar;
ar = new LD305010RP(Session["UserName"].ToString(),this.WTDW.Text,this.dcsWTRQ.Value.ToString(),this.dcsWTRQ2.Value.ToString());
ar.DataSource = rptData();
ar.Run(false);
this.WebViewer1.Report = ar;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AJP.ElasticBand.API.Models;
using Force.DeepCloner;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace AJP.ElasticBand.API
{
public class AddCollectionsDocumentFilter : IDocumentFilter
{
private readonly IElasticBand _elasticBand;
public AddCollectionsDocumentFilter(IElasticBand elasticBand)
{
_elasticBand = elasticBand;
}
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var collectionPathToCloneId = swaggerDoc.Paths["/Collection/{collectionName}/{id}"];
var collectionPathToClone = swaggerDoc.Paths["/Collection/{collectionName}"];
var collectionPathToCloneQuery = swaggerDoc.Paths["/Collection/{collectionName}/query"];
var collectionDefinitions = GetCollections().Result;
if (collectionDefinitions == null)
return;
foreach (var collectionDefinition in collectionDefinitions)
{
var tag = new OpenApiTag
{
Name = $"{collectionDefinition.Name}"
};
var deepClonedCollectionPathId = (OpenApiPathItem)collectionPathToCloneId.DeepClone();
deepClonedCollectionPathId.Summary = $"summary for {collectionDefinition.Name}";
deepClonedCollectionPathId.Description = $"description {collectionDefinition.Name}";
AddTagsToOperations(deepClonedCollectionPathId.Operations.Values, tag);
StripCollectionNameParamFromOperations(deepClonedCollectionPathId.Operations.Values);
foreach (var operation in deepClonedCollectionPathId.Operations)
{
var idParam = FindParameterByName("id", operation.Value.Parameters);
if (idParam.Parameter != null)
{
idParam.Parameter.Example = new OpenApiString($"{collectionDefinition.ExampleIdPattern}");
}
if (operation.Key == OperationType.Post)
{
operation.Value.RequestBody.Description = $"When posting to {collectionDefinition.Name} the json example will be pre-populated in the body for convenience. \n\n ### Timestamp \n\n A timestamp property will be automatically added if it doesn't exist on the object. \n\n ### Object Id \n\n The id will also be added to the object automatically. \n\n ### Automatic Password Hashing \n\n If the payload object contains a property named 'passwordToHash' it will be replaced (before indexing) with a property named 'hashedPassword' containing a cryptographically secure has of the supplied value. (Argon2-id)";
foreach (var content in operation.Value.RequestBody.Content)
{
content.Value.Example = new OpenApiString($"{collectionDefinition.ExampleJsonObjectString}");
}
}
}
swaggerDoc.Paths.Add($"/Collection/{collectionDefinition.Name}/{{id}}", deepClonedCollectionPathId);
var deepClonedCollectionPath = (OpenApiPathItem)collectionPathToClone.DeepClone();
AddTagsToOperations(deepClonedCollectionPath.Operations.Values, tag);
StripCollectionNameParamFromOperations(deepClonedCollectionPath.Operations.Values);
swaggerDoc.Paths.Add($"/Collection/{collectionDefinition.Name}", deepClonedCollectionPath);
var deepClonedCollectionPathQuery = (OpenApiPathItem)collectionPathToCloneQuery.DeepClone();
AddTagsToOperations(deepClonedCollectionPathQuery.Operations.Values, tag);
StripCollectionNameParamFromOperations(deepClonedCollectionPathQuery.Operations.Values);
swaggerDoc.Paths.Add($"/Collection/{collectionDefinition.Name}/query", deepClonedCollectionPathQuery);
// remove the original collection paths
swaggerDoc.Paths.Remove("/Collection/{collectionName}/{id}");
swaggerDoc.Paths.Remove("/Collection/{collectionName}");
swaggerDoc.Paths.Remove("/Collection/{collectionName}/query");
}
}
private async Task<List<CollectionDefinition>> GetCollections()
{
var response = await _elasticBand.Query<CollectionDefinition>(CollectionsIndex.Name, "").ConfigureAwait(false);
if (response.Ok)
return response.Data;
return null;
}
private void AddTagsToOperations(ICollection<OpenApiOperation> operations, OpenApiTag tag)
{
foreach (var operation in operations)
{
operation.Tags.Clear();
operation.Tags.Add(tag);
}
}
private void StripCollectionNameParamFromOperations(ICollection<OpenApiOperation> operations)
{
foreach (var operation in operations)
{
var collectionNameParam = FindParameterByName("collectionName", operation.Parameters);
operation.Parameters.RemoveAt(collectionNameParam.Index);
}
}
private (OpenApiParameter Parameter, int Index) FindParameterByName(string name, IList<OpenApiParameter> parameters)
{
var index = -1;
foreach (var param in parameters)
{
if (param.Name == name)
{
index = parameters.IndexOf(param);
return (param, index);
}
}
return (null, index);
}
}
}
|
using System;
namespace SDMClasses
{
public class Pergunta
{
private int _id;
private string _questao;
private string _resposta;
private Uri _localizacaoDaimagemDaPergunta;
private int _indexCorreto;
private string[] _alternativas;
public string Questao
{
get { return this._questao; }
}
public int ID
{
get { return this._id; }
}
public string Resposta
{
get { return this._resposta; }
set { this._resposta = value; }
}
public string[] Alternativas
{
get { return this._alternativas; }
}
public int IndexCorreto
{
get { return this._indexCorreto; }
}
public Uri LocalizacaoDaImagemDaPergunta
{
get { return this._localizacaoDaimagemDaPergunta; }
set { this._localizacaoDaimagemDaPergunta = value; }
}
public Pergunta(string Q, string[] Alt, int IndexDaCorreta)
{
this._id++;
this._alternativas = Alt;
this._questao = Q;
this.Resposta = Alternativas[IndexDaCorreta];
this._indexCorreto = IndexDaCorreta;
}
public Pergunta(string Q, string[] Alt, int IndexDaCorreta, Uri LocalizacaoDaImagem)
{
this._id++;
this._alternativas = Alt;
this._questao = Q;
this.Resposta = Alternativas[IndexDaCorreta];
this._indexCorreto = IndexDaCorreta;
this.LocalizacaoDaImagemDaPergunta = LocalizacaoDaImagem;
}
public bool CheckAnswer(string R)
{
return R.Contains(Resposta);
}
}
}
|
using System.Text;
using Newtonsoft.Json.Serialization;
namespace SoSmartTv.TheMovieDatabaseApi.JsonResolvers
{
public class UnderscoreToPascalCaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
var builder = new StringBuilder();
foreach (var c in propertyName)
{
if (char.IsUpper(c))
builder.Append('_');
builder.Append(char.ToLower(c));
}
if (char.IsUpper(propertyName, 0))
builder.Remove(0, 1);
return base.ResolvePropertyName(builder.ToString());
}
}
} |
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved.
using System.Threading.Tasks;
using UnityCommon;
using UnityEngine;
namespace Naninovel.UI
{
public class RollbackUI : ScriptableUIBehaviour, IRollbackUI
{
[SerializeField] private float hideTime = 1f;
private StateManager stateManager;
private Timer hideTimer;
public Task InitializeAsync () => Task.CompletedTask;
protected override void Awake ()
{
base.Awake();
stateManager = Engine.GetService<StateManager>();
hideTimer = new Timer(coroutineContainer: this, onCompleted: Hide);
}
protected override void OnEnable ()
{
base.OnEnable();
stateManager.OnRollbackStarted += HandleRollbackStarted;
stateManager.OnRollbackFinished += HandleRollbackFinished;
}
protected override void OnDisable ()
{
base.OnDisable();
stateManager.OnRollbackStarted -= HandleRollbackStarted;
stateManager.OnRollbackFinished -= HandleRollbackFinished;
}
private void HandleRollbackStarted ()
{
if (hideTimer.IsRunning)
hideTimer.Reset();
Show();
}
private void HandleRollbackFinished ()
{
if (!stateManager.RollbackInProgress)
hideTimer.Run(hideTime);
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Design
{
/// <summary>
/// Represents usage of an attribute.
/// </summary>
public class AttributeCodeFragment
{
private readonly List<object> _arguments;
/// <summary>
/// Initializes a new instance of the <see cref="AttributeCodeFragment" /> class.
/// </summary>
/// <param name="type"> The attribute's CLR type. </param>
/// <param name="arguments"> The attribute's arguments. </param>
public AttributeCodeFragment(Type type, params object[] arguments)
{
Check.NotNull(type, nameof(type));
Check.NotNull(arguments, nameof(arguments));
Type = type;
_arguments = new List<object>(arguments);
}
/// <summary>
/// Gets or sets the attribute's type.
/// </summary>
/// <value> The attribute's type. </value>
public virtual Type Type { get; }
/// <summary>
/// Gets the method call's arguments.
/// </summary>
/// <value> The method call's arguments. </value>
public virtual IReadOnlyList<object> Arguments
=> _arguments;
}
}
|
namespace Belot.UI.Console
{
using System;
using System.Globalization;
using System.Text;
using System.Threading;
using Belot.AI.SmartPlayer;
using Belot.Engine;
using Belot.Engine.Cards;
using Belot.Engine.Players;
public static class Program
{
public static void Main()
{
Console.OutputEncoding = Encoding.Unicode;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
ConsoleHelper.ResizeConsole(80, 20);
Console.Title = "Console Belot 1.0";
IPlayer southPlayer = new ConsoleHumanPlayer();
IPlayer eastPlayer = new SmartPlayer();
IPlayer northPlayer = new SmartPlayer();
IPlayer westPlayer = new SmartPlayer();
var game = new BelotGame(southPlayer, eastPlayer, northPlayer, westPlayer);
var result = game.PlayGame(PlayerPosition.South);
Console.WriteLine("Winner: " + result.Winner);
//// RandomCards();
}
private static void RandomCards()
{
for (var i = 0; i < 100; i++)
{
var deck = new Deck();
deck.Shuffle();
for (var j = 0; j < 32; j++)
{
Console.Write(deck.GetNextCard() + " ");
}
Console.WriteLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace apiInovaPP.Models.Financeiro
{
public class CustoFrete
{
public int IdCusto { get; set; }
public int Km { get; set; }
public int IdCidade { get; set; }
public int IdTipoEncomenda { get; set; }
public decimal Custo { get; set; }
public CustoFrete()
{
LimparAtributos();
}
private void LimparAtributos()
{
IdCusto = 0;
Km = 0;
IdCidade = 0;
IdTipoEncomenda = 0;
Custo = 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Sockets;
namespace HTTPClient
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("server name");
string server = Console.ReadLine();
TcpClient client = new TcpClient(server, 80);
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine("GET /RegneWcfService.svc/RESTjson/Add?a=1&b=1 HTTP/1.1");
sw.WriteLine("Host: webservicedemo.datamatiker-skolen.dk\n\n");
sw.Flush();
int data = sr.Read();
while (data != -1)
{
char c = (char)data;
Console.Write(c);
data = sr.Read();
}
//string data = sr.ReadToEnd();
//while (data != null)
//{
// Console.WriteLine("data");
// data = sr.ReadLine();
//}
Console.ReadKey();
client.Close();
}
}
}
|
using Game.Entity.Enum;
using Game.Entity.Treasure;
using Game.Facade;
using Game.Utils;
using Game.Web.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Game.Web.Module.AppManager
{
public partial class LotteryConfigSet : AdminPage
{
#region 窗口事件
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
AuthUserOperationPermission(Permission.Edit);
LotteryConfig model = FacadeManage.aideTreasureFacade.GetLotteryConfig(1);
model.FreeCount = CtrlHelper.GetInt(txtFreeCount, 0);
model.ChargeFee = CtrlHelper.GetInt(txtChargeFee, 0);
model.IsCharge = (byte)(cbIsCharge.Checked ? 1 : 0);
try
{
FacadeManage.aideTreasureFacade.UpdateLotteryConfig(model);
ShowInfo("更新成功");
}
catch
{
ShowError("更新失败");
}
}
#endregion
#region 数据加载
private void BindData()
{
LotteryConfig model = FacadeManage.aideTreasureFacade.GetLotteryConfig(1);
if (model == null)
return;
CtrlHelper.SetText(txtFreeCount, model.FreeCount.ToString());
CtrlHelper.SetText(txtChargeFee, model.ChargeFee.ToString());
cbIsCharge.Checked = model.IsCharge == 0 ? false : true;
}
#endregion
}
} |
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Hybrid.Swagger
{
/// <summary>
///
/// </summary>
public class SwaggerCustomOptions
{
/// <summary>
///
/// </summary>
public SwaggerCustomOptions()
{
}
/// <summary>
///
/// </summary>
/// <param name="apiVersionDescriptionProvider"></param>
public SwaggerCustomOptions(IApiVersionDescriptionProvider apiVersionDescriptionProvider)
{
ApiVersions = apiVersionDescriptionProvider.ApiVersionDescriptions.Select(s => s.GroupName).ToList();
}
/// <summary>
///
/// </summary>
/// <param name="apiVersions"></param>
public SwaggerCustomOptions(List<string> apiVersions)
{
ApiVersions = apiVersions;
}
/// <summary>
/// 接口文档显示版本
/// </summary>
public List<string> ApiVersions { get; set; } = new List<string>();
/// <summary>
/// 接口文档访问路由前缀
/// </summary>
public string RoutePrefix { get; set; } = "swagger";
/// <summary>
/// 使用自定义首页
/// </summary>
public bool UseCustomIndex { get; set; }
/// <summary>
/// 使用导出文档功能
/// </summary>
public bool UseExportDoc { get; set; }
/// <summary>
/// swagger login账号,未指定则不启用
/// </summary>
public List<SwaggerAuthUser> SwaggerAuthUsers { get; set; } = new List<SwaggerAuthUser>();
/// <summary>
/// 生成文档信息
/// </summary>
public Info Info { get; set; } = new Info();
/// <summary>
/// UseSwagger Hook
/// </summary>
public Action<SwaggerOptions> UseSwaggerAction { get; set; }
/// <summary>
/// UseSwaggerUI Hook
/// </summary>
public Action<SwaggerUIOptions> UseSwaggerUiAction { get; set; }
/// <summary>
/// AddSwaggerGen Hook
/// </summary>
public Action<SwaggerGenOptions> AddSwaggerGenAction { get; set; }
}
} |
using System;
using System.Collections.Generic;
using FictionFantasyServer.Data.Entities.Base;
using FictionFantasyServer.Data.Enums;
namespace FictionFantasyServer.Data.Entities
{
public class CharacterEntity : IEntity
{
public Guid Id { get; set; }
public string FullName { get; set; }
public string Nickname { get; set; }
public string Background { get; set; }
public Gender Gender { get; set; }
public Orientation Orientation { get; set; }
public string Occupation { get; set; }
public ICollection<BookCharacterEntity> BookCharacters { get; set; }
public DateTime Created { get; set; }
public DateTime? Modified { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using UnityEngine;
namespace Yasl
{
public class Vector3Serializer : StructSerializer<Vector3>
{
public Vector3Serializer()
{
}
public override void SerializeConstructor(ref Vector3 value, ISerializationWriter writer)
{
writer.Write<float>("X", value.x);
writer.Write<float>("Y", value.y);
writer.Write<float>("Z", value.z);
}
public override void DeserializeConstructor(out Vector3 value, int version, ISerializationReader reader)
{
value.x = reader.Read<float>("X");
value.y = reader.Read<float>("Y");
value.z = reader.Read<float>("Z");
}
}
}
|
using System;
namespace OCP.Migration
{
/**
* Interface IOutput
*
* @package OCP\Migration
* @since 9.1.0
*/
public interface IOutput
{
/**
* @param string message
* @since 9.1.0
*/
void info(string message);
/**
* @param string message
* @since 9.1.0
*/
void warning(string message);
/**
* @param int max
* @since 9.1.0
*/
void startProgress(int max = 0);
/**
* @param int step
* @param string description
* @since 9.1.0
*/
void advance(int step = 1, string description = "");
/**
* @param int max
* @since 9.1.0
*/
void finishProgress();
}
}
|
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 ProyectoFinalParadigmas
{
public partial class menuusuario : Form
{
public menuusuario()
{
InitializeComponent();
//inicializa la ventana poniendo en pantalla la fecha y hora actual y el usuario activo
DateTime dt = DateTime.Now;
label3.Text = dt.ToLongTimeString();
timer1.Enabled = true;
}
//abre ventana de modificar datos personales
private void button1_Click(object sender, EventArgs e)
{
Modif_datos_pers nuevo = new Modif_datos_pers();
nuevo.Show(this);
}
//abre ventana para ver viajes comprados
private void button2_Click(object sender, EventArgs e)
{
ver_viajes nuevo = new ver_viajes();
nuevo.Show(this);
}
//abre ventana para seleccionar nuevo viaje
private void button3_Click(object sender, EventArgs e)
{
seleccionar_viaje nuevo = new seleccionar_viaje();
nuevo.Show(this);
}
//cierra la sesión
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Close();
}
//para actualizar la hora cada segundo
private void timer1_Tick(object sender, EventArgs e)
{
label3.Text = DateTime.Now.ToString();
}
private void menuusuario_Load(object sender, EventArgs e)
{
}
}
}
|
//
// commercio.sdk - Sdk for Commercio Network
//
// Riccardo Costacurta
// Dec. 30, 2019
// BlockIt s.r.l.
//
// Interfaces for asymmetric public and private keys
//
using System;
using System.Text;
using System.Collections.Generic;
namespace commercio.sdk
{
public interface PrivateKey
{
}
public interface PublicKey
{
String getEncoded();
String getType();
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Penumbra;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Game1
{
public class Block
{
Dictionary<string, string> neighbours;
static Rectangle rect;
int texRegionX, texRegionY;
BlockType type;
Hull hull;
public Block(BlockType type, int x, int y)
{
this.type = type;
neighbours = new Dictionary<string, string>();
rect = new Rectangle(0, 0, 16, 16);
setDefaultNeighbours();
if(type != BlockType.AIR)
{
hull = new Hull(new Vector2(1.0f), new Vector2(-1.0f, 1.0f), new Vector2(-1.0f), new Vector2(1.0f, -1.0f))
{
Position = new Vector2(x * 16 + 8, y* 16 + 8),
Scale = new Vector2(8)
};
Game1.penumbra.Hulls.Add(hull);
}
}
public void removeHull()
{
if(type != BlockType.AIR) {
//Game1.penumbra.Hulls.CollectionChanged += delegate { Console.WriteLine("Test"); };
Game1.penumbra.Hulls.Remove(hull);
hull = null;
}
}
public void draw(SpriteBatch spriteBatch, int x, int y)
{
rect.X = x * 16;
rect.Y = y * 16;
//setTexRegions();
int texWidth = type.Texture.Width / 4; int texHeight = type.Texture.Height / 4;
spriteBatch.Draw(type.Texture,
destinationRectangle: rect,
sourceRectangle: new Rectangle(texRegionX * texWidth, texRegionY * texHeight, texWidth, texHeight),
color: Color.White);
}
public void drawIllumination(SpriteBatch spriteBatch, int x, int y)
{
if (type.Illumination)
{
rect.X = x * 16;
rect.Y = y * 16;
//setTexRegions();
int texWidth = type.Texture.Width / 4; int texHeight = type.Texture.Height / 4;
spriteBatch.Draw(type.Texture,
destinationRectangle: rect,
sourceRectangle: new Rectangle(texRegionX * texWidth, texRegionY * texHeight, texWidth, texHeight),
color: new Color(0.15f, 0.15f, 0.15f, 1));
}
}
public Dictionary<string, string> Neighbours { get { return neighbours; } }
public BlockType Type { get { return type; } }
public void setDefaultNeighbours()
{
string air = "Air";
Neighbours["Left"] = air;
Neighbours["Right"] = air;
Neighbours["Up"] = air;
Neighbours["Down"] = air;
Neighbours["UpLeft"] = air;
Neighbours["UpRight"] = air;
Neighbours["DownLeft"] = air;
Neighbours["DownRight"] = air;
}
public void setTexRegions()
{
if (type.isConnectsToSelf)
{
if (Neighbours["Left"] == type.Name && Neighbours["Right"] != type.Name)
{
texRegionX = 2;
texRegionY = 1;
}
if (Neighbours["Right"] == type.Name && Neighbours["Left"] != type.Name)
{
texRegionX = 0;
texRegionY = 1;
}
if (Neighbours["Up"] == type.Name && Neighbours["Down"] != type.Name)
{
texRegionX = 1;
texRegionY = 2;
}
if (Neighbours["Down"] == type.Name && Neighbours["Up"] != type.Name)
{
texRegionX = 1;
texRegionY = 0;
}
if (Neighbours["Down"] == type.Name && Neighbours["Up"] != type.Name && Neighbours["Left"] == type.Name && Neighbours["Right"] != type.Name)
{
texRegionX = 2;
texRegionY = 0;
}
if (Neighbours["Down"] == type.Name && Neighbours["Up"] != type.Name && Neighbours["Left"] != type.Name && Neighbours["Right"] == type.Name)
{
texRegionX = 0;
texRegionY = 0;
}
if (Neighbours["Down"] != type.Name && Neighbours["Up"] == type.Name && Neighbours["Left"] == type.Name && Neighbours["Right"] != type.Name)
{
texRegionX = 2;
texRegionY = 2;
}
if (Neighbours["Down"] != type.Name && Neighbours["Up"] == type.Name && Neighbours["Left"] != type.Name && Neighbours["Right"] == type.Name)
{
texRegionX = 0;
texRegionY = 2;
}
if (Neighbours["Left"] == type.Name && Neighbours["Right"] == type.Name && Neighbours["Up"] == type.Name && Neighbours["Down"] == type.Name)
{
texRegionX = 1;
texRegionY = 1;
}
if (Neighbours["Down"] == type.Name && Neighbours["Up"] == type.Name && Neighbours["Left"] == type.Name && Neighbours["Right"] == type.Name &&
Neighbours["DownLeft"] == type.Name && Neighbours["DownRight"] == type.Name && Neighbours["UpRight"] != type.Name && Neighbours["UpLeft"] == type.Name)
{
texRegionX = 2;
texRegionY = 3;
}
if (Neighbours["Down"] == type.Name && Neighbours["Up"] == type.Name && Neighbours["Left"] == type.Name && Neighbours["Right"] == type.Name &&
Neighbours["DownLeft"] == type.Name && Neighbours["DownRight"] != type.Name && Neighbours["UpRight"] == type.Name && Neighbours["UpLeft"] == type.Name)
{
texRegionX = 1;
texRegionY = 3;
}
if (Neighbours["Down"] == type.Name && Neighbours["Up"] == type.Name && Neighbours["Left"] == type.Name && Neighbours["Right"] == type.Name &&
Neighbours["DownLeft"] != type.Name && Neighbours["DownRight"] == type.Name && Neighbours["UpRight"] == type.Name && Neighbours["UpLeft"] == type.Name)
{
texRegionX = 0;
texRegionY = 3;
}
if (Neighbours["Down"] == type.Name && Neighbours["Up"] == type.Name && Neighbours["Left"] == type.Name && Neighbours["Right"] == type.Name &&
Neighbours["DownLeft"] == type.Name && Neighbours["DownRight"] == type.Name && Neighbours["UpRight"] == type.Name && Neighbours["UpLeft"] != type.Name)
{
texRegionX = 3;
texRegionY = 3;
}
}
else
{
if (Neighbours["Right"] != type.Name && Neighbours["Right"] != BlockType.AIR.Name)
{
texRegionX = 0;
texRegionY = 1;
}
if (Neighbours["Left"] != type.Name && Neighbours["Left"] != BlockType.AIR.Name)
{
texRegionX = 2;
texRegionY = 1;
}
if (Neighbours["Down"] != type.Name && Neighbours["Down"] != BlockType.AIR.Name)
{
texRegionX = 1;
texRegionY = 0;
}
if (Neighbours["Up"] != type.Name && Neighbours["Up"] != BlockType.AIR.Name)
{
texRegionX = 1;
texRegionY = 2;
}
}
if (type.isConnectsToOthers)
{
if (Neighbours["Left"] != "Air" && Neighbours["Right"] == "Air")
{
texRegionX = 2;
texRegionY = 1;
}
if (Neighbours["Right"] != "Air" && Neighbours["Left"] == "Air")
{
texRegionX = 0;
texRegionY = 1;
}
if (Neighbours["Up"] != "Air" && Neighbours["Down"] == "Air")
{
texRegionX = 1;
texRegionY = 2;
}
if (Neighbours["Down"] != "Air" && Neighbours["Up"] == "Air")
{
texRegionX = 1;
texRegionY = 0;
}
if (Neighbours["Down"] != "Air" && Neighbours["Up"] == "Air" && Neighbours["Left"] != "Air" && Neighbours["Right"] == "Air")
{
texRegionX = 2;
texRegionY = 0;
}
if (Neighbours["Down"] != "Air" && Neighbours["Up"] == "Air" && Neighbours["Left"] == "Air" && Neighbours["Right"] != "Air")
{
texRegionX = 0;
texRegionY = 0;
}
if (Neighbours["Down"] == "Air" && Neighbours["Up"] != "Air" && Neighbours["Left"] != "Air" && Neighbours["Right"] == "Air")
{
texRegionX = 2;
texRegionY = 2;
}
if (Neighbours["Down"] == "Air" && Neighbours["Up"] != "Air" && Neighbours["Left"] == "Air" && Neighbours["Right"] != "Air")
{
texRegionX = 0;
texRegionY = 2;
}
if (Neighbours["Left"] != "Air" && Neighbours["Right"] != "Air" && Neighbours["Up"] != "Air" && Neighbours["Down"] != "Air")
{
texRegionX = 1;
texRegionY = 1;
}
if (Neighbours["Down"] != "Air" && Neighbours["Up"] != "Air" && Neighbours["Left"] != "Air" && Neighbours["Right"] != "Air" &&
Neighbours["DownLeft"] != "Air" && Neighbours["DownRight"] != "Air" && Neighbours["UpRight"] == "Air" && Neighbours["UpLeft"] != "Air")
{
texRegionX = 2;
texRegionY = 3;
}
if (Neighbours["Down"] != "Air" && Neighbours["Up"] != "Air" && Neighbours["Left"] != "Air" && Neighbours["Right"] != "Air" &&
Neighbours["DownLeft"] != "Air" && Neighbours["DownRight"] == "Air" && Neighbours["UpRight"] != "Air" && Neighbours["UpLeft"] != "Air")
{
texRegionX = 1;
texRegionY = 3;
}
if (Neighbours["Down"] != "Air" && Neighbours["Up"] != "Air" && Neighbours["Left"] != "Air" && Neighbours["Right"] != "Air" &&
Neighbours["DownLeft"] == "Air" && Neighbours["DownRight"] != "Air" && Neighbours["UpRight"] != "Air" && Neighbours["UpLeft"] != "Air")
{
texRegionX = 0;
texRegionY = 3;
}
if (Neighbours["Down"] != "Air" && Neighbours["Up"] != "Air" && Neighbours["Left"] != "Air" && Neighbours["Right"] != "Air" &&
Neighbours["DownLeft"] != "Air" && Neighbours["DownRight"] != "Air" && Neighbours["UpRight"] != "Air" && Neighbours["UpLeft"] == "Air")
{
texRegionX = 3;
texRegionY = 3;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForm.UI.Forms
{
[ToolboxBitmap(typeof(TableLayoutPanel))]
public partial class HeaderTableLayoutPanel : System.Windows.Forms.TableLayoutPanel
{
/// <summary>
/// Header text
/// </summary>
[Browsable(true), DefaultValue(null), Category("Header"), Description("Header text")]
public string CaptionText
{
get { return this.captionText; }
set
{
if (this.captionText != value)
{
this.captionText = value;
this.CalculateCaptionParams();
Invalidate();
}
}
}
private string captionText = null;
/// <summary>
/// Drawing styles for Header
/// </summary>
public enum HighlightCaptionStyle
{
ForeColor, HighlightColor, ForeStyle, HighlightStyle, NavisionAxaptaStyle, GroupBoxStyle
}
/// <summary>
/// Drawing header style
/// </summary>
[Browsable(true), DefaultValue(HighlightCaptionStyle.ForeColor), Category("Header"), Description("Drawing header style")]
public HighlightCaptionStyle CaptionStyle
{
get { return this.captionStyle; }
set
{
if (this.captionStyle != value)
{
this.captionStyle = value;
this.CalculateCaptionParams();
Invalidate();
}
}
}
private HighlightCaptionStyle captionStyle = HighlightCaptionStyle.ForeColor;
/// <summary>
/// Width of the header line
/// </summary>
[Browsable(true), DefaultValue((byte)2), Category("Header"), Description("Width of the header line")]
public byte CaptionLineWidth
{
get { return this.captionLineWidth; }
set
{
if (this.captionLineWidth != value)
{
this.captionLineWidth = value;
this.CalculateCaptionParams();
Invalidate();
}
}
}
private byte captionLineWidth = 2;
protected override void OnForeColorChanged(EventArgs e)
{
base.OnForeColorChanged(e);
this.CalculateCaptionParams();
Invalidate();
}
protected override void OnBackColorChanged(EventArgs e)
{
base.OnBackColorChanged(e);
this.CalculateCaptionParams();
Invalidate();
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
this.CalculateCaptionParams();
Invalidate();
}
// calculating and storing params for drawing
private int captionTextWidth;
private int captionTextHeight;
private Color captionTextColor;
private Color captionLineBeginColor;
private Color captionLineEndColor;
private void CalculateCaptionParams()
{
if (!string.IsNullOrEmpty(this.captionText))
using (var g = this.CreateGraphics())
{
var _size = g.MeasureString(this.captionText + "I", this.Font).ToSize();
this.captionTextWidth = _size.Width;
this.captionTextHeight = _size.Height;
}
else
{
this.captionTextWidth = 0;
this.captionTextHeight = 0;
}
if (this.captionStyle == HighlightCaptionStyle.ForeColor)
{
this.captionTextColor = this.ForeColor;
this.captionLineBeginColor = this.ForeColor;
this.captionLineEndColor = this.BackColor;
}
else if (this.captionStyle == HighlightCaptionStyle.ForeStyle)
{
this.captionTextColor = this.BackColor;
this.captionLineBeginColor = this.ForeColor;
this.captionLineEndColor = this.BackColor;
}
else
{
this.captionTextColor = this.captionStyle == HighlightCaptionStyle.HighlightStyle ? SystemColors.HighlightText : SystemColors.Highlight;
this.captionLineBeginColor = SystemColors.MenuHighlight;
this.captionLineEndColor = this.BackColor;
}
}
// changing Rectangle according CaptionText and CaptionStyle
public override Rectangle DisplayRectangle
{
get
{
var result = base.DisplayRectangle;
int resize = 0;
if (this.captionTextHeight > 0)
{
resize = this.captionTextHeight;
if (this.captionStyle == HighlightCaptionStyle.NavisionAxaptaStyle) resize += 1;
else if (this.captionStyle == HighlightCaptionStyle.ForeStyle || this.captionStyle == HighlightCaptionStyle.HighlightStyle) resize += 1;
else if (this.captionStyle != HighlightCaptionStyle.GroupBoxStyle) resize += this.captionLineWidth > 0 ? 2 : 1;
}
else if (this.captionStyle == HighlightCaptionStyle.GroupBoxStyle) resize += 10;
if (this.captionStyle == HighlightCaptionStyle.ForeStyle || this.captionStyle == HighlightCaptionStyle.HighlightStyle) resize += this.captionLineWidth * 2;
else if (this.captionStyle == HighlightCaptionStyle.ForeColor || this.captionStyle == HighlightCaptionStyle.HighlightColor) resize += this.captionLineWidth;
result.Height -= resize;
result.Offset(0, resize);
return result;
}
}
// changing Size according CaptionText and CaptionStyle
protected override Size SizeFromClientSize(Size clientSize)
{
var result = base.SizeFromClientSize(clientSize);
int resize = 0;
if (this.captionTextHeight > 0)
{
resize = this.captionTextHeight;
if (this.captionStyle == HighlightCaptionStyle.NavisionAxaptaStyle) resize += 1;
else if (this.captionStyle == HighlightCaptionStyle.ForeStyle || this.captionStyle == HighlightCaptionStyle.HighlightStyle) resize += 1;
else if (this.captionStyle != HighlightCaptionStyle.GroupBoxStyle) resize += this.captionLineWidth > 0 ? 2 : 1;
}
else if (this.captionStyle == HighlightCaptionStyle.GroupBoxStyle) resize += 10;
if (this.captionStyle == HighlightCaptionStyle.ForeStyle || this.captionStyle == HighlightCaptionStyle.HighlightStyle) resize += this.captionLineWidth * 2;
else if (this.captionStyle == HighlightCaptionStyle.ForeColor || this.captionStyle == HighlightCaptionStyle.HighlightColor) resize += this.captionLineWidth;
result.Height += resize;
return result;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// draw gradient
if (this.captionStyle == HighlightCaptionStyle.ForeStyle || this.captionStyle == HighlightCaptionStyle.HighlightStyle)
{ // HighlightCaptionStyle.HighlightStyle allways draw
float _wPen = this.captionLineWidth * 2 + this.captionTextHeight;
if (_wPen > 0)
using (Brush _gBrush = new LinearGradientBrush(new Point(0, 0), new Point(this.Width, 0), this.captionLineBeginColor, this.captionLineEndColor))
using (Pen _gPen = new Pen(_gBrush, _wPen))
e.Graphics.DrawLine(_gPen, 0, _wPen / 2, this.Width, _wPen / 2);
}
else if (this.captionStyle == HighlightCaptionStyle.GroupBoxStyle)
{ // HighlightCaptionStyle.GroupBox draw GroupBox canvas
string _capText = this.captionText;
if (!string.IsNullOrEmpty(_capText))
{
_capText = _capText.Trim();
if (!string.IsNullOrEmpty(_capText)) _capText = string.Format(" {0} ", _capText);
}
GroupBoxRenderer.DrawGroupBox(e.Graphics, this.ClientRectangle, _capText, this.Font, this.captionTextColor, this.Enabled ? System.Windows.Forms.VisualStyles.GroupBoxState.Normal : System.Windows.Forms.VisualStyles.GroupBoxState.Disabled);
}
else if (this.captionLineWidth > 0)
if (this.captionStyle != HighlightCaptionStyle.NavisionAxaptaStyle)
{ // HighlightCaptionMode.ForeColor | HighlightCaptionMode.HighlightColor
using (Brush _gradientBrush = new LinearGradientBrush(new Point(0, 0), new Point(this.Width, 0), this.captionLineBeginColor, this.captionLineEndColor))
using (Pen _gradientPen = new Pen(_gradientBrush, this.captionLineWidth))
e.Graphics.DrawLine(_gradientPen, 0, this.captionTextHeight + this.captionLineWidth / 2, this.Width, this.captionTextHeight + this.captionLineWidth / 2);
}
else if (this.captionTextWidth + 1 < this.Width)
{ // HighlightCaptionMode.NavisionAxapta
using (Brush _gradientBrush = new LinearGradientBrush(new Point(this.captionTextWidth, 0), new Point(this.Width, 0), this.captionLineBeginColor, this.captionLineEndColor))
using (Pen _gradientPen = new Pen(_gradientBrush, this.captionLineWidth > this.captionTextHeight ? this.captionTextHeight : this.captionLineWidth))
e.Graphics.DrawLine(_gradientPen, this.captionTextWidth, this.captionTextHeight / 2 + 1, this.Width, this.captionTextHeight / 2 + 1);
}
// draw Text
if (this.captionTextHeight > 0 && this.captionStyle != HighlightCaptionStyle.GroupBoxStyle)
using (Brush _textBrush = new SolidBrush(this.captionTextColor))
e.Graphics.DrawString(this.captionText, this.Font, _textBrush, 0, this.captionStyle == HighlightCaptionStyle.HighlightStyle || this.captionStyle == HighlightCaptionStyle.ForeStyle ? this.CaptionLineWidth : 0);
}
}
}
|
using System;
namespace MODEL.ORDER
{
/// <summary>
/// 实体类 OrderStepModel
/// 编写者:
/// 日期:2015/2/7 星期六 1:25:15
/// </summary>
public class OrderStepModel
{
private int stepid = 0;
private int orderid = 0;
private int step = 0;
private int lastuserid = 0;
private int lastdeptid = 0;
private int curuserid = 0;
private int curdeptid = 0;
private string dealopinion = string.Empty;
private DateTime submittime = DateTime.Now;
private string remark = string.Empty;
/// <summary>
/// StepId
/// </summary>
public int StepId
{
set { stepid = value; }
get { return stepid; }
}
/// <summary>
/// OrderId
/// </summary>
public int OrderId
{
set { orderid = value; }
get { return orderid; }
}
/// <summary>
/// Step
/// </summary>
public int Step
{
set { step = value; }
get { return step; }
}
/// <summary>
/// LastUserId
/// </summary>
public int LastUserId
{
set { lastuserid = value; }
get { return lastuserid; }
}
/// <summary>
/// LastDeptId
/// </summary>
public int LastDeptId
{
set { lastdeptid = value; }
get { return lastdeptid; }
}
/// <summary>
/// CurUserId
/// </summary>
public int CurUserId
{
set { curuserid = value; }
get { return curuserid; }
}
/// <summary>
/// CurDeptId
/// </summary>
public int CurDeptId
{
set { curdeptid = value; }
get { return curdeptid; }
}
/// <summary>
/// DealOpinion
/// </summary>
public string DealOpinion
{
set { dealopinion = value; }
get { return dealopinion; }
}
/// <summary>
/// SubmitTime
/// </summary>
public DateTime SubmitTime
{
set { submittime = value; }
get { return submittime; }
}
/// <summary>
/// Remark
/// </summary>
public string Remark
{
set { remark = value; }
get { return remark; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime;
using System.Threading;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Net;
using Bitcoin.Blox;
using Bitcoin.Blox.Network;
using Bitcoin.BitcoinUtilities;
using Bitcoin.Blox.Data_Interface;
using System.Net.Sockets;
namespace TestUI
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
P2PConnection p2p;
P2PNetworkParameters _networkParameters = new P2PNetworkParameters(P2PNetworkParameters.ProtocolVersion, false, 22122,1,1,true,true);
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
Thread connectThread = new Thread(new ThreadStart(() =>
{
ushort port = 8333;
if (_networkParameters.IsTestNet)
{
port = 18333;
}
p2p = new P2PConnection(IPAddress.Parse("82.45.214.119"), _networkParameters, new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp),port);
bool success = p2p.ConnectToPeer(1);
if (!success)
{
MessageBox.Show("Not connected");
}
}));
connectThread.IsBackground = true;
connectThread.Start();
Thread threadLable = new Thread(new ThreadStart(() =>
{
while (true)
{
Dispatcher.Invoke(() =>
{
label.Content = "Inbound: " + P2PConnectionManager.GetInboundP2PConnections().Count + " Outbound: " + P2PConnectionManager.GetOutboundP2PConnections().Count;
});
Thread.CurrentThread.Join(250);
}
}));
threadLable.IsBackground = true;
threadLable.Start();
}
private async void button1_Click(object sender, RoutedEventArgs e)
{
Thread threadLable = new Thread(new ThreadStart(() =>
{
while (true)
{
Dispatcher.Invoke(() =>
{
List<P2PConnection> inNodes = P2PConnectionManager.GetInboundP2PConnections();
label.Content = "Inbound: " + inNodes.Count + " Outbound: " + P2PConnectionManager.GetOutboundP2PConnections().Count;
if (inNodes.Count > 0)
{
}
});
Thread.CurrentThread.Join(1000);
}
}));
threadLable.IsBackground = true;
threadLable.Start();
await P2PConnectionManager.ListenForIncomingP2PConnectionsAsync(IPAddress.Any,_networkParameters);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
P2PConnectionManager.StopListeningForIncomingP2PConnections();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
p2p.Send(new Bitcoin.Blox.Protocol_Messages.Ping(_networkParameters));
}
private async void button4_Click(object sender, RoutedEventArgs e)
{
List<PeerAddress> ips;
if (!_networkParameters.IsTestNet)
{
ips = await P2PConnectionManager.GetDNSSeedIPAddressesAsync(P2PNetworkParameters.DNSSeedHosts, _networkParameters);
}
else
{
ips = await P2PConnectionManager.GetDNSSeedIPAddressesAsync(P2PNetworkParameters.TestNetDNSSeedHosts, _networkParameters);
}
MessageBox.Show(ips.Count.ToString());
}
private async void button5_Click(object sender, RoutedEventArgs e)
{
List<PeerAddress> ips = await P2PConnectionManager.GetDNSSeedIPAddressesAsync(P2PNetworkParameters.DNSSeedHosts, _networkParameters);
Thread threadLable = new Thread(new ThreadStart(() =>
{
while (true)
{
Dispatcher.Invoke(()=>
{
label.Content = "Inbound: " + P2PConnectionManager.GetInboundP2PConnections().Count + " Outbound: " + P2PConnectionManager.GetOutboundP2PConnections().Count;
});
Thread.CurrentThread.Join(1000);
}
}));
threadLable.IsBackground = true;
threadLable.Start();
foreach (PeerAddress ip in ips)
{
Thread connectThread = new Thread(new ThreadStart(() =>
{
P2PConnection p2p = new P2PConnection(ip.IPAddress, _networkParameters, new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));
p2p.ConnectToPeer(1);
}));
connectThread.IsBackground = true;
connectThread.Start();
}
}
private async void button6_Click(object sender, RoutedEventArgs e)
{
PeerAddress myip = await p2p.GetMyExternalIPAsync();
MessageBox.Show(myip.ToString());
}
private void button7_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(new DatabaseConnection(_networkParameters).ConnectionString);
}
private async void button8_Click(object sender, RoutedEventArgs e)
{
await P2PConnectionManager.SetNATPortForwardingUPnPAsync(_networkParameters.P2PListeningPort, _networkParameters.P2PListeningPort);
}
private async void button9_Click(object sender, RoutedEventArgs e)
{
Thread threadLable = new Thread(new ThreadStart(() =>
{
while (true)
{
Dispatcher.Invoke(() =>
{
List<P2PConnection> inNodes = P2PConnectionManager.GetInboundP2PConnections();
label.Content = "Inbound: " + inNodes.Count + " Outbound: " + P2PConnectionManager.GetOutboundP2PConnections().Count;
if (inNodes.Count > 0)
{
}
});
Thread.CurrentThread.Join(1000);
}
}));
threadLable.IsBackground = true;
threadLable.Start();
await P2PConnectionManager.ListenForIncomingP2PConnectionsAsync(IPAddress.Any,_networkParameters);
P2PConnectionManager.MaintainConnectionsOutbound(_networkParameters);
}
}
}
|
using Superpower.Model;
using SuppaCompiler.CodeAnalysis.Syntax;
namespace SuppaCompiler.CodeAnalysis.Superpower
{
public static class ParserExtensions
{
public static SyntaxToken ToSyntaxToken(this Token<SyntaxKind> token)
{
return ToSyntaxToken(token, null);
}
public static SyntaxToken ToSyntaxToken(this Token<SyntaxKind> token, object value)
{
return new SyntaxToken(token, value);
}
public static ExpressionSyntax ToBinary(SyntaxToken op, ExpressionSyntax left, ExpressionSyntax right)
{
return new BinaryExpressionSyntax(left, op, right);
}
public static ExpressionSyntax ToLiteral(this SyntaxToken toSyntaxToken, object value)
{
return new LiteralExpressionSyntax(toSyntaxToken, value);
}
}
} |
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 ISKlinike
{
public partial class DatumiPosjeta : Form
{
private Pacijenti Pacijent;
private DBContext db = Baza.baza;
public DatumiPosjeta()
{
InitializeComponent();
dgvDatumiDolazaka.AutoGenerateColumns = false;
}
public DatumiPosjeta(Pacijenti pacijent):this()
{
Pacijent = pacijent;
UcitajPodatke();
}
private void UcitajPodatke()
{
dgvDatumiDolazaka.DataSource = null;
dgvDatumiDolazaka.DataSource = db.KartonDatumiPosjeta.Where(karton => karton.Pacijenti.Id == Pacijent.Id).ToList();
}
private void btnUredi_Click(object sender, EventArgs e)
{
DatumiPosjetaUredi posjeta = new DatumiPosjetaUredi(Pacijent);
posjeta.Show();
UcitajPodatke();
}
private void DatumiPosjeta_Load(object sender, EventArgs e)
{
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class Fiksu : MonoBehaviour {
//public static functions to communicate with the Fiksu SDK
public static void Initialize(){
if(!Application.isEditor){
if(!initialized){
#if UNITY_ANDROID
AndroidJavaObject jniApplication = jniCurrentActivity.Call<AndroidJavaObject>("getApplication");
jniFiksuTrackingManager.CallStatic("initialize",jniApplication);
jniFiksuRegistrationEvents = new Dictionary<FiksuRegistrationEvent, AndroidJavaObject>();
AndroidJavaClass jniFiksuRegistrationEventClass = new AndroidJavaClass("com.fiksu.asotracking.FiksuTrackingManager$RegistrationEvent");
jniFiksuRegistrationEvents.Add(FiksuRegistrationEvent.EVENT1,jniFiksuRegistrationEventClass.GetStatic<AndroidJavaObject>("EVENT1"));
jniFiksuRegistrationEvents.Add(FiksuRegistrationEvent.EVENT2,jniFiksuRegistrationEventClass.GetStatic<AndroidJavaObject>("EVENT2"));
jniFiksuRegistrationEvents.Add(FiksuRegistrationEvent.EVENT3,jniFiksuRegistrationEventClass.GetStatic<AndroidJavaObject>("EVENT3"));
jniFiksuPurchaseEvents = new Dictionary<FiksuPurchaseEvent, AndroidJavaObject>();
AndroidJavaClass jniFiksuPurchaseEventClass = new AndroidJavaClass("com.fiksu.asotracking.FiksuTrackingManager$PurchaseEvent");
jniFiksuPurchaseEvents.Add(FiksuPurchaseEvent.EVENT1,jniFiksuPurchaseEventClass.GetStatic<AndroidJavaObject>("EVENT1"));
jniFiksuPurchaseEvents.Add(FiksuPurchaseEvent.EVENT2,jniFiksuPurchaseEventClass.GetStatic<AndroidJavaObject>("EVENT2"));
jniFiksuPurchaseEvents.Add(FiksuPurchaseEvent.EVENT3,jniFiksuPurchaseEventClass.GetStatic<AndroidJavaObject>("EVENT3"));
jniFiksuPurchaseEvents.Add(FiksuPurchaseEvent.EVENT4,jniFiksuPurchaseEventClass.GetStatic<AndroidJavaObject>("EVENT4"));
jniFiksuPurchaseEvents.Add(FiksuPurchaseEvent.EVENT5,jniFiksuPurchaseEventClass.GetStatic<AndroidJavaObject>("EVENT5"));
#endif
//initializing on iOS happens in Xcode. (PostBuildScript adds this functionality)
}
}
initialized = true;
}
public enum FiksuRegistrationEvent{
EVENT1 = 1,
EVENT2,
EVENT3,
};
public enum FiksuPurchaseEvent{
EVENT1 = 1,
EVENT2,
EVENT3,
EVENT4,
EVENT5
}
public static void UploadRegistrationEvent(string username){
if(!Application.isEditor && initialized){
#if UNITY_ANDROID
jniFiksuTrackingManager.CallStatic("uploadRegistration",jniCurrentActivity,jniFiksuRegistrationEvents[FiksuRegistrationEvent.EVENT1]);
#elif UNITY_IPHONE
UploadRegistrationEvent_(username);
#endif
}
}
public static void UploadRegistration(FiksuRegistrationEvent registrationEvent){
if(!Application.isEditor && initialized){
#if UNITY_ANDROID
jniFiksuTrackingManager.CallStatic("uploadRegistration",jniCurrentActivity,jniFiksuRegistrationEvents[registrationEvent]);
#elif UNITY_IPHONE
UploadRegistration_((int)registrationEvent);
#endif
}
}
public static void UploadPurchase(string username, double price, string currency){
if(!Application.isEditor && initialized){
if(username == null){
username = "";
}
if(currency == null){
currency = "";
}
#if UNITY_ANDROID
jniFiksuTrackingManager.CallStatic("uploadPurchaseEvent",jniCurrentActivity,username,price,currency);
#elif UNITY_IPHONE
UploadPurchaseEventWithUsername_(username, price, currency);
#endif
}
}
public static void UploadPurchase(FiksuPurchaseEvent purchaseEvent, double price, string currency){
if(!Application.isEditor && initialized){
if(currency == null){
currency = "";
}
#if UNITY_ANDROID
jniFiksuTrackingManager.CallStatic("uploadPurchase",jniCurrentActivity,jniFiksuPurchaseEvents[purchaseEvent],price,currency);
#elif UNITY_IPHONE
UploadPurchase_((int)purchaseEvent, price, currency);
#endif
}
}
public static void UploadPurchaseEvent(string username, string currency){
if(!Application.isEditor && initialized){
if(username == null){
username = "";
}
if(currency == null){
currency = "";
}
#if UNITY_ANDROID
jniFiksuTrackingManager.CallStatic("uploadPurchaseEvent",jniCurrentActivity,username,null,currency);
#elif UNITY_IPHONE
UploadPurchaseEventNoPrice_(username, currency);
#endif
}
}
public static void UploadCustomEvent(){
if(!Application.isEditor && initialized){
#if UNITY_ANDROID
//jniFiksuTrackingManager.CallStatic("uploadCustomEvent",jniCurrentActivity);
#elif UNITY_IPHONE
UploadCustomEvent_();
#endif
}
}
public static void SetClientID(string clientID){
if(!Application.isEditor && initialized){
#if UNITY_ANDROID
jniFiksuTrackingManager.CallStatic("setClientId",jniCurrentActivity,clientID);
#elif UNITY_IPHONE
SetFiksuClientID_(clientID);
#endif
}
}
public static void SetAppTrackingEnabled(bool enabled){
if(!Application.isEditor && initialized){
#if UNITY_ANDROID
jniFiksuTrackingManager.CallStatic("setAppTrackingEnabled",jniCurrentActivity,enabled);
#elif UNITY_IPHONE
SetAppTrackingEnabled_(enabled);
#endif
}
}
public static bool IsAppTrackingEnabled(){
if(!Application.isEditor && initialized){
#if UNITY_ANDROID
return jniFiksuTrackingManager.CallStatic<bool>("isAppTrackingEnabled");
#elif UNITY_IPHONE
return IsAppTrackingEnabled_();
#endif
}
return false;
}
//Monobehavior functions to start the Fiksu SDK automaticly
void Awake(){
if(initialized){
Destroy(gameObject);
}else{
DontDestroyOnLoad(gameObject);
#if UNITY_ANDROID
if(!Application.isEditor){
jniFiksuTrackingManager = new AndroidJavaClass("com.fiksu.asotracking.FiksuTrackingManager");
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
jniCurrentActivity = jc.GetStatic<AndroidJavaObject>("currentActivity");
}
#endif
Initialize();
}
}
/*
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
*/
//private function and vars to connect to the sdks
//TODO make private again.
public static bool initialized = false;
#if UNITY_ANDROID
private static AndroidJavaClass jniFiksuTrackingManager;
private static AndroidJavaObject jniCurrentActivity;
private static Dictionary<FiksuRegistrationEvent,AndroidJavaObject> jniFiksuRegistrationEvents;
private static Dictionary<FiksuPurchaseEvent,AndroidJavaObject> jniFiksuPurchaseEvents;
#elif UNITY_IOS
[DllImport ("__Internal")]
private static extern void UploadRegistrationEvent_(string username);
[DllImport ("__Internal")]
private static extern void UploadRegistration_(int eventNumber);
[DllImport ("__Internal")]
private static extern void UploadPurchaseEventWithUsername_(string username, double price, string currency);
[DllImport ("__Internal")]
private static extern void UploadPurchaseEventNoPrice_(string username, string currency);
[DllImport ("__Internal")]
private static extern void UploadPurchase_(int eventNumber, double price, string currency);
[DllImport ("__Internal")]
private static extern void UploadCustomEvent_();
[DllImport ("__Internal")]
private static extern void SetFiksuClientID_(string clientID);
[DllImport ("__Internal")]
private static extern void SetAppTrackingEnabled_(bool enabled);
[DllImport ("__Internal")]
private static extern bool IsAppTrackingEnabled_();
#endif
}
|
using EatDrinkApplication.Contracts;
using EatDrinkApplication.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace EatDrinkApplication.Services
{
public class RecipeByIngredientsRequest : IRecipeByIngredientsRequest
{
public RecipeByIngredientsRequest()
{
}
public async Task<List<JObject>> GetRecipesByIngredients(string ingredients)
{
string url = $"https://api.spoonacular.com/recipes/findByIngredients?ingredients={ingredients}&number=10&apiKey=44486bab87864bd2828d594c8e459825";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
json = "{" + "results :" + json + "}";
var jsonResults = JsonConvert.DeserializeObject<JObject>(json);
List<JObject> foods = new List<JObject>();
for(int i =0; i< jsonResults["results"].Count(); i++)
{
foods.Add(jsonResults["results"][i].ToObject<JObject>());
}
//var results = jsonResults["results"][0];
//var test = jsonResults["missedIngredients"];
//List<JObject> test = new List<JObject>();
//for (int i = 0; i < jsonResults.Count; i++)
//{
// test.Add(jsonResults[i].ToObject<JObject>());
//}
//Console.WriteLine(foods[0]["title"]);
return foods;
}
return null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LinePageSim : MonoBehaviour {
// Simulation parameters
public int N = 2; // num vertices
public float totalMass = 0.01f;
public float stretchStrength = 1.0f;
public float bendStrength = 1.0f;
public int constraintSteps = 2;
public int[] anchoredVertices;
public float timeScale = 1.0f;
public float edgePadding = 0.01f;
public float extent = 2.0f;
public bool move = true;
float CEIL_MAX = 3 * Mathf.PI / 2;
float FLOOR_MIN = Mathf.PI / 2;
// Radial heightmaps calculated to prevent inter-page collision
public Tuple<float, float>[] polar { get; private set; }
GameObject anchor;
Vector3 rotOrigin;
float baseAngle;
public LinePageSim nextPage;
public LinePageSim prevPage;
bool isGrabbing;
public PageCollection pages;
int grabVertex;
LineRenderer line;
float[] default_inv_mass;
float[] inv_mass;
Vector3[] pos;
Vector3[] ppos;
Vector3[] vel;
float[] restDist;
float[] restBend;
// Use this for initialization
void Start()
{
line = GetComponent<LineRenderer>();
anchor = transform.parent.gameObject;
Debug.Assert(anchor != null, "Page cannot find anchor object as reference");
Debug.Assert(N >= line.numPositions, "N needs to be at least the same as line.numPositions");
// Get begin and end points from line, and interpolate N points between
// Also retransform so we can get make the transform component the identity
pos = new Vector3[N];
baseAngle = Quaternion.Angle(transform.localRotation, Quaternion.identity) * Mathf.Deg2Rad;
for(int i = 0; i < N; i++)
{
// TODO: Experiment with nonlinear meshing, as used here. Note, you'll have to fix the mesh uv stuff
//var p = Vector3.Lerp(line.GetPosition(0), line.GetPosition(line.numPositions - 1), (float)Mathf.Pow(N, (i - N) / 10.0f));
var p = Vector3.Lerp(line.GetPosition(0), line.GetPosition(line.numPositions-1), (float) (i+1) / N);
var r = p.magnitude;
var t = Mathf.Atan2(p.x, -p.y);
if (p.x < 0) t += 2.0f * Mathf.PI;
t += baseAngle;
pos[i] = new Vector3(r * Mathf.Sin(t), r * -Mathf.Cos(t), p.z);
}
transform.localRotation = Quaternion.identity;
line.numPositions = N;
line.SetPositions(pos);
ppos = new Vector3[N];
vel = new Vector3[N];
polar = new Tuple<float, float>[N];
restDist = new float[N-1];
for(int i = 0; i < N-1; i++)
{
restDist[i] = Vector3.Distance(pos[i + 1], pos[i]);
}
restBend = new float[N-2];
for(int i = 0; i < N-2; i++)
{
restBend[i] = Mathf.Acos(Vector3.Dot((pos[i] - pos[i+1]).normalized, (pos[i+2] - pos[i+1]).normalized));
Debug.LogFormat("Bend {0}: {1}", i, restBend[i]);
}
UpdatePolarCoords();
rotOrigin = line.GetPosition(0);
Debug.LogFormat("Origin: {0}", rotOrigin);
Debug.LogFormat("Base Angle: {0}", baseAngle * Mathf.Rad2Deg);
}
void UpdatePolarCoords()
{
// Update polar coordinates for boundary calculation
for(int i = 0; i < N; i++)
{
Vector3 p = ppos[i];
float r = p.magnitude;
float theta = Mathf.Atan2(p.x, -p.y);
if (p.x < 0)
theta += 2.0f * Mathf.PI;
polar[i] = new Tuple<float, float>(r, theta);
}
}
void BoundsCheck()
{
var floor = GetFloorRegion();
var ceil = GetCeilRegion();
// Check all points and push them back within bounds, if necessary
for(int i = 0; i < N; i++)
{
float r = polar[i].Item1;
float t = polar[i].Item2;
float ft = GetBoundAngle(polar[i], floor, false);
float ct = GetBoundAngle(polar[i], ceil, true);
// Positive = within bounds
// If both bounds are < 0, choose the closest bound
float dft = t - ft;
float dct = ct - t;
float targetAngle;
if (dft >= 0 && dct >= 0) continue;
else if (dft < 0 && dct < 0)
{
if (dft < dct)
targetAngle = ct;
else
targetAngle = ft;
}
else if (dft < 0)
{
targetAngle = ft;
}
else
{
targetAngle = ct;
}
//// Floor only
//if (dft >= 0) continue;
//targetAngle = ft;
// Displace point along theta
float dx = r * Mathf.Sin(targetAngle) - ppos[i].x;
float dy = r * -Mathf.Cos(targetAngle) - ppos[i].y;
//pos[i].x += dx;
//pos[i].y += dy;
ppos[i].x += dx;
ppos[i].y += dy;
//vel[i] = new Vector3();
}
}
List<Tuple<float, float>> GetFloorRegion()
{
var region = new List<Tuple<float, float>>();
region.Add(new Tuple<float, float>(0.0f, FLOOR_MIN + edgePadding));
if(nextPage)
{
var p = nextPage.polar;
float maxR = -1.0f;
for(int i = 0; i < p.Length; i++)
{
float r = p[i].Item1;
float t = p[i].Item2;
if(r > maxR)
{
maxR = r;
region.Add(new Tuple<float, float>(r, t + edgePadding));
}
}
// Add extra region to mark end of page
region.Add(new Tuple<float, float>(p[p.Length-1].Item1 + Mathf.Epsilon, FLOOR_MIN + edgePadding));
}
region.Add(new Tuple<float, float>(extent, FLOOR_MIN + edgePadding));
return region;
}
List<Tuple<float, float>> GetCeilRegion()
{
var region = new List<Tuple<float, float>>();
region.Add(new Tuple<float, float>(0.0f, CEIL_MAX - edgePadding));
if(prevPage)
{
var p = prevPage.polar;
float maxR = -1.0f;
for(int i = 0; i < p.Length; i++)
{
float r = p[i].Item1;
float t = p[i].Item2;
if(r > maxR)
{
maxR = r;
region.Add(new Tuple<float, float>(r, t - edgePadding));
}
}
// Add extra region to mark end of page
region.Add(new Tuple<float, float>(p[p.Length-1].Item1 + Mathf.Epsilon, CEIL_MAX - edgePadding));
}
region.Add(new Tuple<float, float>(extent, CEIL_MAX - edgePadding));
return region;
}
float GetBoundAngle(Tuple<float, float> p, List<Tuple<float, float>> region, bool ceil)
{
float r = p.Item1;
float t = p.Item2;
for(int j = 0; j < region.Count-1; j++)
{
// Find portion of region that this point falls between
float r0 = region[j].Item1;
float r1 = region[j+1].Item1;
if(r >= r0 && r <= r1)
{
float t01 = Mathf.Lerp(region[j].Item2,
region[j + 1].Item2,
(r1 - r) / (r1 - r0));
return t01;
}
}
if(ceil)
{
return Mathf.Infinity;
}
else
{
return -Mathf.Infinity;
}
}
// Update is called once per frame
//void FixedUpdate()
public void Tick()
{
if(!move)
{
UpdatePolarCoords();
return;
}
float dt = Time.fixedDeltaTime * timeScale;
default_inv_mass = new float[N];
inv_mass = new float[N];
for(int i = 0; i < N; i++)
{
default_inv_mass[i] = 1.0f / (totalMass / N);
}
int s = line.GetPositions(pos);
ppos = pos;
//Debug.LogFormat("Polar {0} : <{1}, {2}>", N - 1, polar[N - 1].Item1, polar[N - 2].Item2);
// Reset mass
for (int i = 0; i < N; i++)
{
inv_mass[i] = default_inv_mass[i];
}
// Apply external forces
for(int i = 0; i < N; i++)
{
var f = 10.0f * Vector3.down;
vel[i] += f * dt;
}
// Apply mass changes
if(pages.grabLine == line)
{
inv_mass[pages.grabVertex] = 0.0001f;
}
// Apply velocity change from user input, if any
foreach(var a in anchoredVertices)
{
inv_mass[a] = 0.0f;
vel[a] = new Vector3();
}
if(pages.grabLine == line)
{
vel[pages.grabVertex] = pages.grabVel;
}
for(int i = 0; i < N; i++)
{
ppos[i] = pos[i] + dt * vel[i];
}
// Solve constraints
for (int i = 0; i < constraintSteps; i++)
{
UpdatePolarCoords();
BoundsCheck();
SolveConstraints();
}
// Final position update
for (int i = 0; i < N; i++)
{
vel[i] = (ppos[i] - pos[i]) / dt;
pos[i] = ppos[i];
}
line.SetPositions(pos);
}
public void SolveConstraints()
{
for (int i = 0; i < N - 1; i++)
{
// Calculate stretch constraints
Vector3 d = (ppos[i] - ppos[i + 1]);
float s = (d.magnitude - restDist[i]) / (inv_mass[i] + inv_mass[i + 1]);
Vector3 dp0 = -inv_mass[i] * s * d.normalized;
Vector3 dp1 = inv_mass[i + 1] * s * d.normalized;
ppos[i] += stretchStrength * dp0;
ppos[i+1] += stretchStrength * dp1;
// // Update rotations
// // TOOD: Make this work
// if (i < N - 2)
// {
// Vector3 d0 = d;
// Vector3 d1 = (ppos[i+2] - ppos[i+1]);
// Vector3 axis = -transform.forward;
// Vector3 N0 = Vector3.Cross(axis, d0);
// Vector3 N1 = Vector3.Cross(axis, d1);
// Vector3 n0 = N0.normalized;
// Vector3 n1 = N1.normalized;
// float dot = Vector3.Dot(d0, d1);
// float dot2 = dot * dot;
// Vector3 q3 = (Vector3.Cross(axis,n1) + (Vector3.Cross(n0,axis) * dot)) / (Vector3.Cross(axis,d0)).magnitude;
// Vector3 q4 = (Vector3.Cross(axis,n0) + (Vector3.Cross(n1,axis) * dot)) / (Vector3.Cross(axis,d1)).magnitude;
// Vector3 q2 = - ((Vector3.Cross(d0,n1) + (Vector3.Cross(n0,d0) * dot)) / Vector3.Cross(axis,d0).magnitude)
// - ((Vector3.Cross(d1,n0) + (Vector3.Cross(n1,d1) * dot)) / Vector3.Cross(axis,d1).magnitude);
// Vector3 q1 = -q2 - q3 - q4;
// float denom = inv_mass[i+1] * q1.sqrMagnitude
// + inv_mass[i+1] * q2.sqrMagnitude
// + inv_mass[i] * q3.sqrMagnitude
// + inv_mass[i+2] * q4.sqrMagnitude;
// ppos[i+1] += bendStrength * q1 * -(inv_mass[i+1] * Mathf.Sqrt(1.0f - dot2)) * (Mathf.Acos(dot) - restBend[i]) / denom;
// ppos[i+1] += bendStrength * q2 * -(inv_mass[i+1] * Mathf.Sqrt(1.0f - dot2)) * (Mathf.Acos(dot) - restBend[i]) / denom;
// ppos[i] += bendStrength * q3 * -(inv_mass[i] * Mathf.Sqrt(1.0f - dot2)) * (Mathf.Acos(dot) - restBend[i]) / denom;
// ppos[i+2] += bendStrength * q4 * -(inv_mass[i+2] * Mathf.Sqrt(1.0f - dot2)) * (Mathf.Acos(dot) - restBend[i]) / denom;
// /*
//ofVec3f q3 = (axis.crossed(n1) + (n0.crossed(axis) * dot)) / (axis.crossed(d0)).length();
//ofVec3f q4 = (axis.crossed(n0) + (n1.crossed(axis) * dot)) / (axis.crossed(d1)).length();
//ofVec3f q2 = - ((d0.crossed(n1) + (n0.crossed(d0) * dot)) / axis.crossed(d0).length())
// - ((d1.crossed(n0) + (n1.crossed(d1) * dot)) / axis.crossed(d1).length());
//ofVec3f q1 = -q2 - q3 - q4;
//float denom = invPointMass[t.p1] * q1.lengthSquared()
// + invPointMass[t.axis] * q2.lengthSquared()
// + invPointMass[t.d0] * q3.lengthSquared()
// + invPointMass[t.d1] * q4.lengthSquared();
//ppos[t.p1] += BEND_STRENGTH * q1 * -(invPointMass[t.p1] * sqrtf(1.0f - dot*dot)) * (acosf(dot) - restBend[i]) / denom;
//ppos[t.axis] += BEND_STRENGTH * q2 * -(invPointMass[t.axis] * sqrtf(1.0f - dot*dot)) * (acosf(dot) - restBend[i]) / denom;
//ppos[t.d0] += BEND_STRENGTH * q3 * -(invPointMass[t.d0] * sqrtf(1.0f - dot*dot)) * (acosf(dot) - restBend[i]) / denom;
//ppos[t.d1] += BEND_STRENGTH * q4 * -(invPointMass[t.d1] * sqrtf(1.0f - dot*dot)) * (acosf(dot) - restBend[i]) / denom;
// */
// }
//ppos[t.p1] += BEND_STRENGTH * q1 * -(invPointMass[t.p1] * sqrtf(1.0f - d * d)) * (acosf(d) - restBend[i]) / denom;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Waffles;
using Waffles.UserControls;
public partial class form_submission_delete : AdminModal
{
public override void Build()
{
Modal.Script.Append(ModalScript.Text);
Modal.Style.Append(ModalStyle.Text);
List = SPContext.Current.Site.RootWeb.GetList("/Lists/w_forms");
WList = new Waffles.WList(List);
Modal = new WAdminModal();
Modal.Size = WAdminModal.Sizes.Small;
Modal.Breadcrumb.Add(new string[] { "Forms", "#/forms" });
string error = "";
int form_id_int;
string
form_id = ListSlug,
submission_id = ActionID;
Modal.FormAction = string.Format("/_admin/form-submission-delete", form_id, submission_id);
if (form_id != null && int.TryParse(form_id, out form_id_int) && form_id_int > 0)
try { Item = List.GetItemById(form_id_int); }
catch { error = string.Format("A form with the id of '{0}' does not exist.", form_id_int); }
else
error = "<a href='#/forms'><span class='text-danger'>Select a form</span></a> to view submissions.";
if (error.Length > 0)
{
Modal.Breadcrumb.Add("Submissions");
Modal.Body.AppendFormat("<div class='alert alert-danger'>{0}</div>", error);
return;
}
Modal.Breadcrumb.Add(new string[] { "Submissions", "#/form-submissions/" + form_id });
Modal.Breadcrumb.Add("<span class='text-danger'>Delete Form Submission</span>");
Modal.Body.Append("<input type='hidden' name='web_guid' value='" + Web.ID + "' /><p>Are you sure you want to <span class='text-danger'>permanently</span> delete this submission from the form <em>'" + Item.Title + "'</em> ?</p>");
Modal.Footer.Append(
"<a class='btn btn-default pull-left' href='" + WAdmin.list_view_url(WList.slug) + "'>Cancel</a>" +
"<button type='submit' class='btn btn-danger'>" +
"<i class='fa fa-trash-o'></i> Delete</button>" +
"<input type='hidden' name='form_id' value='" + form_id + "'>" +
"<input type='hidden' name='submission_id' value='" + submission_id + "'>" +
"<input type='hidden' name='confirmed' value='1'>"
);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using sfShareLib;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json.Linq;
using CDSShareLib.Helper;
namespace sfAPIService.Models
{
public class WidgetCatalogModel
{
public class Format_Detail
{
public int Id { get; set; }
public int? MessageCatalogId { get; set; }
public string Name { get; set; }
public string Level { get; set; }
public string MessageCatalogName { get; set; }
public int WidgetClassKey { get; set; }
public string Title { get; set; }
public string TitleBgColor { get; set; }
public JObject Content { get; set; }
public string ContentBgColor { get; set; }
}
public class Format_Create
{
public int? MessageCatalogId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Level { get; set; }
[Required]
public int WidgetClassKey { get; set; }
[Required]
public string Title { get; set; }
public string TitleBgColor { get; set; }
public string Content { get; set; }
public string ContentBgColor { get; set; }
}
public class Format_Update
{
public int? MessageCatalogId { get; set; }
public string Name { get; set; }
public string Level { get; set; }
public int? WidgetClassKey { get; set; }
public string Title { get; set; }
public string TitleBgColor { get; set; }
public string Content { get; set; }
public string ContentBgColor { get; set; }
}
public List<Format_Detail> getAllWidgetCatalogByCompanyId(int companyId, string level)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
var L2Enty = from c in dbEntity.WidgetCatalog.AsNoTracking()
where c.CompanyID == companyId && c.Level == level
select c;
List<WidgetCatalog> widgetClassList = (from c in dbEntity.WidgetCatalog.AsNoTracking()
where c.CompanyID == companyId && c.Level == level
select c).ToList();
List<Format_Detail> returnData = new List<Format_Detail>();
foreach (var widgetClass in widgetClassList)
{
returnData.Add(new Format_Detail()
{
Id = widgetClass.Id,
MessageCatalogId = widgetClass.MessageCatalogID,
MessageCatalogName = widgetClass.MessageCatalog == null ? "" : widgetClass.MessageCatalog.Name,
Name = widgetClass.Name,
Level = widgetClass.Level,
WidgetClassKey = widgetClass.WidgetClassKey,
Title = widgetClass.Title,
TitleBgColor = widgetClass.TitleBgColor,
Content = JObject.Parse(widgetClass.Content),
ContentBgColor = widgetClass.ContentBgColor
});
}
return returnData;
}
}
public Format_Detail GetById(int id)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
WidgetCatalog existingData = (from c in dbEntity.WidgetCatalog.AsNoTracking()
where c.Id == id
select c).SingleOrDefault<WidgetCatalog>();
if (existingData == null)
throw new CDSException(10701);
return new Format_Detail()
{
Id = existingData.Id,
MessageCatalogId = existingData.MessageCatalogID,
MessageCatalogName = existingData.MessageCatalog == null ? "" : existingData.MessageCatalog.Name,
Name = existingData.Name,
Level = existingData.Level,
WidgetClassKey = existingData.WidgetClassKey,
Title = existingData.Title,
TitleBgColor = existingData.TitleBgColor,
Content = JObject.Parse(existingData.Content),
ContentBgColor = existingData.ContentBgColor
};
}
}
public int Create(int companyId, Format_Create parseData)
{
try
{
JObject.Parse(parseData.Content);
}
catch
{
throw new CDSException(12303);
}
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
WidgetCatalog newData = new WidgetCatalog();
newData.CompanyID = companyId;
newData.MessageCatalogID = parseData.MessageCatalogId;
newData.Name = parseData.Name;
newData.Level = parseData.Level;
newData.WidgetClassKey = parseData.WidgetClassKey;
newData.Title = parseData.Title;
newData.TitleBgColor = parseData.TitleBgColor ?? "";
newData.Content = parseData.Content;
newData.ContentBgColor = parseData.ContentBgColor ?? "";
dbEntity.WidgetCatalog.Add(newData);
dbEntity.SaveChanges();
return newData.Id;
}
}
public void Update(int id, Format_Update parseData)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
var existingData = dbEntity.WidgetCatalog.Find(id);
if (existingData == null)
throw new CDSException(12302);
if (parseData.Content != null)
{
try
{
JObject.Parse(parseData.Content);
}
catch
{
throw new CDSException(12303);
}
existingData.Content = parseData.Content;
}
if (parseData.Name != null)
existingData.Name = parseData.Name;
if (parseData.MessageCatalogId.HasValue)
existingData.MessageCatalogID = parseData.MessageCatalogId;
if (parseData.Level != null)
existingData.Level = parseData.Level;
if (parseData.WidgetClassKey.HasValue)
existingData.WidgetClassKey = (int)parseData.WidgetClassKey;
if (parseData.Title != null)
existingData.Title = parseData.Title;
if (parseData.TitleBgColor != null)
existingData.TitleBgColor = parseData.TitleBgColor;
if (parseData.ContentBgColor != null)
existingData.ContentBgColor = parseData.ContentBgColor;
dbEntity.SaveChanges();
}
}
public void DeleteById(int id)
{
using (CDStudioEntities dbEntity = new CDStudioEntities())
{
WidgetCatalog existingData = dbEntity.WidgetCatalog.Find(id);
if (existingData == null)
throw new CDSException(12302);
dbEntity.WidgetCatalog.Remove(existingData);
dbEntity.SaveChanges();
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Glock18Magazine : Magazine {
public override void OnAwake()
{
base.OnAwake();
id = 11;
usingWeaponId = 5;
bulletCount = 18;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using InvoiceClient.Properties;
using Model.Schema.EIVO;
using InvoiceClient.Agent;
using Utility;
using Newtonsoft.Json;
namespace InvoiceClient.TransferManagement
{
public class MIGInvoiceTransferManager : ITransferManager
{
private InvoiceWatcher _InvoiceWatcher;
private InvoiceWatcher _CancellationWatcher;
private AllowanceWatcher _AllowanceWatcher;
private AllowanceCancellationWatcher _AllowanceCancellationWatcher;
private MIGInvoiceTransferManager.LocalSettings _Settings;
public MIGInvoiceTransferManager()
{
string path = Path.Combine(Logger.LogPath, "MIGInvoiceTransferManager.json");
if (File.Exists(path))
{
this._Settings = JsonConvert.DeserializeObject<MIGInvoiceTransferManager.LocalSettings>(File.ReadAllText(path));
}
else
{
this._Settings = new MIGInvoiceTransferManager.LocalSettings();
File.WriteAllText(path, JsonConvert.SerializeObject((object)this._Settings));
}
}
public void EnableAll(String fullPath)
{
_InvoiceWatcher = new MIGInvoiceWatcher(Path.Combine(fullPath, _Settings.InvoiceRequestPath));
_InvoiceWatcher.StartUp();
_CancellationWatcher = new MIGInvoiceCancellationWatcher(Path.Combine(fullPath, _Settings.VoidInvoiceRequestPath));
_CancellationWatcher.StartUp();
_AllowanceWatcher = new D0401Watcher(Path.Combine(fullPath, _Settings.AllowanceRequestPath));
_AllowanceWatcher.StartUp();
_AllowanceCancellationWatcher = new D0501Watcher(Path.Combine(fullPath, _Settings.VoidAllowanceRequestPath));
_AllowanceCancellationWatcher.StartUp();
}
public void PauseAll()
{
if (_InvoiceWatcher != null)
{
_InvoiceWatcher.Dispose();
}
if (_CancellationWatcher != null)
{
_CancellationWatcher.Dispose();
}
if (_AllowanceWatcher != null)
{
_AllowanceWatcher.Dispose();
}
if (_AllowanceCancellationWatcher != null)
{
_AllowanceCancellationWatcher.Dispose();
}
}
public String ReportError()
{
StringBuilder sb = new StringBuilder();
if (_InvoiceWatcher != null)
sb.Append(_InvoiceWatcher.ReportError());
if (_CancellationWatcher != null)
sb.Append(_CancellationWatcher.ReportError());
if (_AllowanceWatcher != null)
sb.Append(_AllowanceWatcher.ReportError());
if (_AllowanceCancellationWatcher != null)
sb.Append(_AllowanceCancellationWatcher.ReportError());
return sb.ToString();
}
public void SetRetry()
{
_InvoiceWatcher.Retry();
_CancellationWatcher.Retry();
_AllowanceWatcher.Retry();
_AllowanceCancellationWatcher.Retry();
}
public Type UIConfigType
{
get { return typeof(InvoiceClient.MainContent.MIGInvoiceConfig); }
}
private class LocalSettings
{
public string InvoiceRequestPath { get; set; } = "SellerInvoice_C0401";
public string VoidInvoiceRequestPath { get; set; } = "CancelInvoice_C0501";
public string AllowanceRequestPath { get; set; } = "Allowance_D0401";
public string VoidAllowanceRequestPath { get; set; } = "CancelAllowance_D0501";
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TreeListSettings.cs" company="Soloplan GmbH">
// Copyright (c) Soloplan GmbH. All rights reserved.
// Licensed under the MIT License. See License-file in the project root for license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Soloplan.WhatsON.GUI.Common.VisualConfig
{
using System.Collections.Generic;
public class TreeListSettings
{
public IList<GroupExpansionSettings> GroupExpansions { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace QuestomAssets.AssetOps
{
public static class OpsExtensions
{
public static void WaitForFinish(this IEnumerable<AssetOp> ops)
{
var opsCopy = ops.ToList();
using (new LogTiming($"waiting for {opsCopy.Count} ops to complete"))
{
while (opsCopy.Count > 0)
{
var waitOps = opsCopy.Take(64);
WaitHandle.WaitAll(waitOps.Select(x => x.FinishedEvent).ToArray());
opsCopy.RemoveAll(x => waitOps.Contains(x));
}
}
}
}
}
|
using System.Threading.Tasks;
using Dapper;
using DDDSouthWest.Domain.Features.Public.News.NewsDetail;
using Npgsql;
namespace DDDSouthWest.Domain.Features.Account.Admin.ManageNews.ViewNewsDetail
{
public class QueryAnyNewsById
{
private readonly ClientConfigurationOptions _options;
public QueryAnyNewsById(ClientConfigurationOptions options)
{
_options = options;
}
public async Task<NewsDetailModel> Invoke(int id, bool live = true)
{
using (var connection = new NpgsqlConnection(_options.Database.ConnectionString))
{
return await connection.QuerySingleOrDefaultAsync<NewsDetailModel>("SELECT Id, Title, Filename, BodyMarkdown, BodyHtml, IsLive, DatePosted FROM news WHERE Id = @id LIMIT 1", new {id});
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Caliburn.Micro;
using Voronov.Nsudotnet.BuildingCompanyIS.Entities.RelationTables;
using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces;
namespace Voronov.Nsudotnet.BuildingCompanyIS.UI.ViewModels
{
public class OrganizationUnitManagerViewModel : PropertyChangedBase
{
public OrganizationUnitManagerViewModel(OrganizationUnitManager entity)
{
OrganizationUnitManagerEntity = entity;
OrganizationUnit = new OrganizationUnitViewModel(entity.OrganizationUnit);
Engineer = new EngineerViewModel(entity.Engineer);
}
public OrganizationUnitManager OrganizationUnitManagerEntity { get; private set; }
public OrganizationUnitViewModel OrganizationUnit { get; private set;}
public EngineerViewModel Engineer { get; private set;}
}
public class OrganizationUnitManagerDetailedViewModel : PropertyChangedBaseWithError
{
public OrganizationUnitManagerDetailedViewModel(IOrganizationUnitManagerService service, IEngineerService engineerService, IOrganizationUnitsService organizationUnitsService )
{
_organizationUnitManagerService = service;
_cachedEngineers = new LinkedList<EngineerViewModel>();
foreach (var engineer in engineerService.All)
{
_cachedEngineers.Add(new EngineerViewModel(engineer));
}
Engineers = new BindableCollection<EngineerViewModel>(_cachedEngineers);
OrganizationUnits = new BindableCollection<OrganizationUnitSimpleViewModel>();
foreach (var organizationUnit in organizationUnitsService.GetOrganizationUnitsWithManager())
{
OrganizationUnits.Add(new OrganizationUnitSimpleViewModel(organizationUnit));
}
Relations = new BindableCollection<OrganizationUnitManagerViewModel>();
foreach (var organizationUnitManager in service.GetAll())
{
Relations.Add(new OrganizationUnitManagerViewModel(organizationUnitManager));
}
}
private IOrganizationUnitManagerService _organizationUnitManagerService;
private ICollection<EngineerViewModel> _cachedEngineers;
public BindableCollection<EngineerViewModel> Engineers { get; private set; }
private EngineerViewModel _selectedEngineer;
public EngineerViewModel SelectedEngineer
{
get { return _selectedEngineer; }
set
{
if (value == _selectedEngineer) return;
_selectedEngineer = value;
NotifyOfPropertyChange(()=>SelectedEngineer);
}
}
public BindableCollection<OrganizationUnitSimpleViewModel> OrganizationUnits { get; private set; }
private OrganizationUnitSimpleViewModel _selectedOrganizationUnit;
public OrganizationUnitSimpleViewModel SelectedOrganizationUnit
{
get { return _selectedOrganizationUnit;}
set
{
if (value == _selectedOrganizationUnit) return;
_selectedOrganizationUnit = value;
NotifyOfPropertyChange(()=>SelectedOrganizationUnit);
EngineerFilter();
}
}
public BindableCollection<OrganizationUnitManagerViewModel> Relations { get; private set; }
private OrganizationUnitManagerViewModel _selectedRelation;
public OrganizationUnitManagerViewModel SelectedRelation
{
get { return _selectedRelation; }
set
{
if (value == _selectedRelation) return;
_selectedRelation = value;
NotifyOfPropertyChange(()=>SelectedRelation);
}
}
public void Delete()
{
try
{
if (_selectedRelation == null)
return;
var tmp = _selectedRelation;
_organizationUnitManagerService.DeleteOrganizationUnitManager(tmp.OrganizationUnitManagerEntity);
_organizationUnitManagerService.Save();
Relations.Remove(_selectedRelation);
NotifyOfPropertyChange(() => Relations);
}
catch (DbException e)
{
Console.Out.WriteLine(e);
Error = Messages.ErrorMessageOnDeleteEntity;
}
}
public void Add()
{
try
{
if (_selectedOrganizationUnit == null || _selectedEngineer == null)
return;
var tmp = _selectedOrganizationUnit;
var newRel = new OrganizationUnitManager
{
ManagerId = _selectedEngineer.EmployeeEntity.Id,
OrganizationUnitId = tmp.OrganizationUnitEntity.Id
};
_organizationUnitManagerService.CreateOrUpdateOrganizationUnitManager(newRel);
_organizationUnitManagerService.Save();
Relations.Add(new OrganizationUnitManagerViewModel(newRel));
NotifyOfPropertyChange(() => Relations);
}
catch (Exception e)
{
Console.Out.WriteLine(e);
Error = Messages.ErrorMessageOnDeleteEntity;
}
}
private void EngineerFilter()
{
Engineers.Clear();
if (_selectedOrganizationUnit == null)
{
Engineers.AddRange(_cachedEngineers);
}
else
{
Engineers.AddRange(_cachedEngineers.Where(e=>e.EngineerEntity.OrganizationUnitId == _selectedOrganizationUnit.OrganizationUnitEntity.Id));
}
}
}
} |
using ActionMailer.Net.Mvc;
using DominosPizza.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DominosPizza.Controllers
{
public class FeedbackController : MailerBase
{
public EmailResult SendEmail(FeedbackMail feedbackMail, string viewmailname)
{
DominosContext db = new DominosContext();
To.Add(feedbackMail.To);
From = feedbackMail.From; //e-mail user
Subject = feedbackMail.Subject;
return Email(viewmailname, feedbackMail);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Clime.Messages
{
class NewMeasurementAddedMessage
{
public NewMeasurementAddedMessage(Guid? v)
{
MeasurementAdded = v;
}
public Guid? MeasurementAdded { get; private set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
public enum AnimationType
{
Stop,
Idle,
WindUp,
Attack,
BiteFollowThrough,
Stun,
WalkingDown,
WalkingUp,
Victory
}
public class CustomSpriteAnimator : MonoBehaviour {
public List<Sprite> idleSprites;
public List<Sprite> windUpSprites;
public List<Sprite> attackSprites;
public List<Sprite> biteFollowThroughSprites;
public List<Sprite> stunSprites;
public List<Sprite> walkingDownSprites;
public List<Sprite> walkingUpSprites;
public List<Sprite> victorySprites;
float animationLength = 0;
float currentAnimationTime = 0;
SpriteRenderer sRend;
public AnimationType currentAnimationType = AnimationType.Idle;
// Use this for initialization
void Start ()
{
animationLength = SongManager.instance.secondsPerBeat;
currentAnimationTime = SongManager.instance.nextBeatTime - SongManager.instance.currentDSPTime;
sRend = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update ()
{
currentAnimationTime += SongManager.instance.deltaDSPTime;
if (currentAnimationTime >= animationLength)
{
currentAnimationTime -= animationLength;
}
float currentAnimationPercent = currentAnimationTime / animationLength;
switch (currentAnimationType)
{
case AnimationType.Stop:
break;
case AnimationType.Idle:
sRend.sprite = idleSprites[(int)(currentAnimationPercent * idleSprites.Count)];
break;
case AnimationType.WindUp:
sRend.sprite = windUpSprites[(int)(currentAnimationPercent * windUpSprites.Count)];
break;
case AnimationType.Attack:
sRend.sprite = attackSprites[(int)(currentAnimationPercent * attackSprites.Count)];
break;
case AnimationType.BiteFollowThrough:
sRend.sprite = biteFollowThroughSprites[(int)(currentAnimationPercent * biteFollowThroughSprites.Count)];
break;
case AnimationType.Stun:
sRend.sprite = stunSprites[(int)(currentAnimationPercent * stunSprites.Count)];
break;
case AnimationType.WalkingDown:
sRend.sprite = walkingDownSprites[(int)(currentAnimationPercent * walkingDownSprites.Count)];
break;
case AnimationType.WalkingUp:
sRend.sprite = walkingUpSprites[(int)(currentAnimationPercent * walkingUpSprites.Count)];
break;
case AnimationType.Victory:
sRend.sprite = victorySprites[(int)(currentAnimationPercent * victorySprites.Count)];
break;
}
}
public void ChangeAnimation(AnimationType type)
{
currentAnimationType = type;
}
public void FlipX()
{
sRend.flipX = !sRend.flipX;
}
}
|
using UnityEngine;
using System;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
[Category("Pools")]
[TestOf(typeof(Pool<V3BezierCurve>))]
public class TestPool
{
Pool<V3BezierCurve> pool;
V3BezierCurve original;
Func<V3BezierCurve, V3BezierCurve> allocator;
[SetUp]
public void SetupPoolAllocatorAndOriginal()
{
original = new V3BezierCurve();
original.Set(Vector3.one, new Vector3(5, 5, 5), new Vector3(8, 6, 7), new Vector3(10, 10, 10), 4);
allocator = (c) => { V3BezierCurve newInstance = new V3BezierCurve(); newInstance.Copy(original); return newInstance; };
pool = new Pool<V3BezierCurve>(allocator, original, 10, (c) => { c.ValidPoints = 3; });
}
[Test]
public void TestInitializzationPreallocation()
{
Assert.That(pool.ElementsStored, Is.EqualTo(10));
}
[Test]
public void TestInitializzationPreallocationRedLight()
{
Assert.That(pool.ElementsStored, Is.Not.EqualTo(0));
}
[Test]
public void TestInitializzationOnPreallocation()
{
Assert.That(pool.Get(original).ValidPoints, Is.EqualTo(3));
}
[Test]
public void TestInitializzationOnPreallocationRedLight()
{
Assert.That(pool.Get(original).ValidPoints, Is.Not.EqualTo(4));
}
[Test]
public void TestGetNonNullStored()
{
Assert.That(pool.Get(original), Is.Not.Null);
}
[Test]
public void TestGetNonNullStoredRedLight()
{
Assert.That(pool.Get(original), !Is.Null);
}
[Test]
public void TestStoredCount()
{
pool.Get(original);
Assert.That(pool.ElementsStored, Is.EqualTo(9));
}
[Test]
public void TestStoredCountRedLight()
{
pool.Get(original);
Assert.That(pool.ElementsStored, Is.Not.EqualTo(10));
}
[Test]
public void TestGetNonNullInstanciated()
{
for (int i = 0; i < 10; i++)
{
pool.Get(original);
}
Assert.That(pool.Get(original), Is.Not.Null);
}
[Test]
public void TestGetNonNullInstanciatedRedLight()
{
for (int i = 0; i < 10; i++)
{
pool.Get(original);
}
Assert.That(pool.Get(original), !Is.Null);
}
[Test]
public void TestGetValidCopyInstanciated()
{
for (int i = 0; i < 10; i++)
{
pool.Get(original);
}
Assert.That(pool.Get(original).ValidPoints, Is.EqualTo(4));
}
[Test]
public void TestGetValidCopyInstanciatedRedLight()
{
for (int i = 0; i < 10; i++)
{
pool.Get(original);
}
Assert.That(pool.Get(original).ValidPoints, Is.Not.EqualTo(3));
}
[Test]
public void TestDifferenceStoredAndInstanciated()
{
V3BezierCurve current = null;
for (int i = 0; i < 10; i++)
{
current = pool.Get(original);
}
Assert.That(pool.Get(original).ValidPoints, Is.Not.EqualTo(current.ValidPoints));
}
[Test]
public void TestDifferenceStoredAndInstanciatedRedLight()
{
for (int i = 0; i < 10; i++)
{
pool.Get(original);
}
Assert.That(pool.Get(original).ValidPoints, Is.EqualTo(4));
}
[Test]
public void TestRecycleCountIncrease()
{
pool.Recycle(new V3BezierCurve());
Assert.That(pool.ElementsStored, Is.EqualTo(11));
}
[Test]
public void TestRecycleCountIncreaseRedLight()
{
pool.Recycle(new V3BezierCurve());
Assert.That(pool.ElementsStored, Is.Not.EqualTo(10));
}
[Test]
public void TestDifferenceRecycledAndGetted()
{
for (int i = 0; i < 10; i++)
{
pool.Get(original);
}
pool.Recycle(new V3BezierCurve());
Assert.That(pool.Get(original).ValidPoints, Is.EqualTo(V3BezierCurve.MinValidPoints));
}
[Test]
public void TestDifferenceRecycledAndGettedRedLight()
{
for (int i = 0; i < 10; i++)
{
pool.Get(original);
}
pool.Recycle(new V3BezierCurve());
Assert.That(pool.Get(original).ValidPoints, Is.Not.EqualTo(4));
}
[Test]
public void TestClearCount()
{
pool.Clear((o) => { });
Assert.That(pool.ElementsStored, Is.EqualTo(0));
}
[Test]
public void TestClearCountRedLight()
{
pool.Clear((o) => { });
Assert.That(pool.ElementsStored, Is.Not.EqualTo(10));
}
[Test]
public void TestClearOnDestroy()
{
V3BezierCurve temp = new V3BezierCurve();
pool.Recycle(temp);
pool.Clear((o) => { if (o.ValidPoints == 2) o.Set(new Vector3(100, 100, 100), Vector3.one); });
Assert.That(temp.Start.x, Is.EqualTo(100));
Assert.That(temp.Start.y, Is.EqualTo(100));
Assert.That(temp.Start.z, Is.EqualTo(100));
}
[Test]
public void TestClearOnDestroyRedLight()
{
V3BezierCurve temp = new V3BezierCurve();
pool.Recycle(temp);
pool.Clear((o) => { if (o.ValidPoints == 2) o.Set(new Vector3(100, 100, 100), Vector3.one); });
Assert.That(temp.Start.x, Is.Not.EqualTo(1));
Assert.That(temp.Start.y, Is.Not.EqualTo(1));
Assert.That(temp.Start.z, Is.Not.EqualTo(1));
}
} |
using System;
using System.Web.UI;
public partial class Admin_Main_Frame : System.Web.UI.Page
{
const string randomFolder = "UserControls/";
string Action = "";
public string t_rand = "";
protected void Page_Load(object sender, EventArgs e)
{
t_rand = DateTime.Now.ToString("yyyyMMddHHmmssff");
if (Request.QueryString["action"] != null && !string.IsNullOrEmpty(Request.QueryString["action"].ToString()))
{
Action = Request.QueryString["action"].ToString();
}
else
{
return;
}
Control featuredProduct = Page.LoadControl(randomFolder + Action + ".ascx");
nPanel.Controls.Add(featuredProduct);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BatTransformFixer : MonoBehaviour {
GameObject bat;
// Use this for initialization
void Start () {
bat = GameObject.FindGameObjectWithTag ("cricketBat");
bat.transform.localPosition = transform.position;
bat.transform.localRotation = transform.localRotation;
}
}
|
using UnityEngine;
using System.Collections;
using Extensions;
public class ResetScript : MonoBehaviour
{
public Clickable cl = null;
void Awake()
{
if(cl == null)
cl = gameObject.GetComponent<Clickable>();
if(cl != null)
cl.action += res;
}
void res()
{
this.DataLog("Restarting " + Application.loadedLevelName);
Application.LoadLevel(Application.loadedLevelName);
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace _1_setup.Controllers{
public class HomeController:Controller{
[Route("")]
public string Index(){
return "Hello World!";
}
}
}
|
namespace Caliburn.Light
{
/// <summary>
/// Denotes a node within a parent/child hierarchy.
/// </summary>
public interface IChild
{
/// <summary>
/// Gets or sets the parent.
/// </summary>
object Parent { get; set; }
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelertApp.Models;
using TravelertApp.Services;
using TravelertApp.ViewModels;
using TravelertApp.Views.ProfilePageUsers;
using TravelertApp.Views.RegisterUsers;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace TravelertApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GeneralPublicPage : ContentPage
{
private string ConsumerUID;
private int userpinCount = 0;
public GeneralPublicPage(string consumerUID)
{
InitializeComponent();
ConsumerUID = consumerUID;
BindingContext = new ConsumersMapViewModel();
//consumersMapViewModel = new ConsumersMapViewModel(consumerUID);
#region DesiredVehicle Picker
//Calling DesiredVehicle picker to add elements
DesiredVehicle.Items.Add("Class 1: Car, Jeepney, Van, Pickup, Motorcycle, Tricycle");
DesiredVehicle.Items.Add("Class 2: Bus, Truck, Trailer Vehicle");
DesiredVehicle.Items.Add("Class 3: Large Truck, Large Truck w/Trailer");
DesiredVehicle.Items.Add("Train, Boat and Airplane");
#endregion DesiredVehicle Picker
Position center = new Position(14.598978831983539, 121.00537096699053);
var pinLocations = new List<Position>();
Pin consumerPin;
//Pin pinPUP = new Pin()
//{
// Type = PinType.Place,
// Label = "PUP CEA",
// Address = "Anonas, Sta. Mesa, Maynila, 1008 Kalakhang Maynila",
// Position = new Position(14.598978493230458d, 121.00537569264561d),
// Rotation = 33.3f,
// Tag = "id_tokyo",
//};
//map.Pins.Add(pinPUP);
//map.MoveToRegion(MapSpan.FromCenterAndRadius(pinPUP.Position, Distance.FromMeters(5000)));
GenPubMap.MoveToRegion(MapSpan.FromCenterAndRadius(center, Distance.FromMeters(500)));
var response = ConsumerApiServices.ServiceClientInstance.GetConsumer(ConsumerUID);
GenPubMap.MapClicked += async (sender, args) =>
{
//if (Btn_Confirm.IsPressed) { } d ko pa alam to kasi nabobobo ako
//await DisplayAlert("Coordinates", $"Lat: {args.Position.Latitude} Long: {args.Position.Longitude}", "Ok");
Position positionClicked = new Position(args.Position.Latitude, args.Position.Longitude);
consumerPin = new Pin()
{
Position = positionClicked,
Label = "Other user location"
};
//Checking if the position exists in the firebase
var responseLocationList = await FirebaseHelperConsumer.GetAllLocationsConsumer();
foreach (var responseLocation in responseLocationList)
{
//GenPubMap.Pins.Add(new Pin() { Position = new Position(responseLocation.Location.Latitude, responseLocation.Location.Longitude), Label = "Other user location" });
//await DisplayAlert("TRY", $"consumerPin: response.Result.Location: Lat: {responseLocation.Location.Latitude} \nLong: {responseLocation.Location.Longitude}", "OK");
if (responseLocation.Location.Latitude != 0 && responseLocation.Location.Longitude != 0)
{
userpinCount = 1;
await DisplayAlert("Alert", "You have already set your location", "OK");
break;
}
else if(responseLocation.Location.Latitude == 0 && responseLocation.Location.Longitude == 0)
{
userpinCount = 0;
}
}
if (userpinCount == 0 && !GenPubMap.Pins.Contains(consumerPin))
{
GenPubMap.Pins.Add(consumerPin);
var consumerLocation = await FirebaseHelperConsumer.AddLocationConsumer(response.Result.FullName, response.Result.Age, response.Result.Username, response.Result.ConsumerUID, response.Result.Email, response.Result.Password, args.Position);
//await DisplayAlert("", $"consumerPin: response.Result.Location: Lat: {consumerLocation.Latitude} \nLong: {consumerLocation.Longitude}", "OK");
userpinCount++;
}
//Getting the Location
//var responseLocationList = await FirebaseHelperConsumer.GetAllLocationsConsumer();
//foreach (var responseLocation in responseLocationList)
//{
// await DisplayAlert("TRY", $"consumerPin: response.Result.Location: Lat: {responseLocation.Location.Latitude} \nLong: {responseLocation.Location.Longitude}", "OK");
//}
};
//Pag meron na (Count == 1), ang kailangan mangyare is idelete ung previous pin (ung nasa database bago iupdate)
//Issue: Hindi tama ung pagreretrieve ng data mula sa database
//Showing Pin Locations of all users (kaso d pa alam pano)
GetConsumerPins();
//Setting MyMenu to get the list of Menu
//MyMenu = GetMenus();
//Setting the binding contxt of this page to itself
// - to bring the data from this page
//this.BindingContext = this;
#region GestureRecognizers
//tapgesturerecognizer experiment
//var tapGestureRecognizerHomePage = new TapGestureRecognizer();
//tapGestureRecognizerHomePage.Tapped += async (s, e) => {
// // handle the tap
// await Navigation.PushAsync(new GeneralPublicPage(ConsumerUID));
//};
//Lbl_GoToHomePage.GestureRecognizers.Add(tapGestureRecognizerHomePage);
//var tapGestureRecognizerProfilePage = new TapGestureRecognizer();
//tapGestureRecognizerProfilePage.Tapped += async (s, e) => {
// // handle the tap
// await Navigation.PushAsync(new ConsumerProfilePage(ConsumerUID));
//};
//Lbl_GoToProfilePage.GestureRecognizers.Add(tapGestureRecognizerProfilePage);
//var tapGestureRecognizerSettingsPage = new TapGestureRecognizer();
//tapGestureRecognizerSettingsPage.Tapped += async (s, e) => {
// // handle the tap
// await Navigation.PushAsync(new ConsumerSettingsPage(ConsumerUID));
//};
//Lbl_GoToSettingsPage.GestureRecognizers.Add(tapGestureRecognizerSettingsPage);
#endregion GestureRecognizers
}
//Kailangan muna d magzero ung response location
private async void GetConsumerPins()
{
try
{
//var responseLocationList = await FirebaseHelperConsumer.GetAllLocationsConsumer();
//foreach (var response in responseLocationList)
//{
// GenPubMap.Pins.Add(new Pin() { Position = new Position(response.Location.Latitude, response.Location.Longitude), Label = "Other user location" });
// //await DisplayAlert("", $"consumerPin: response.Location: Lat: {response.Location.Latitude} \nLong: {response.Location.Longitude}", "OK");
//}
var responseLocationList = await FirebaseHelperConsumer.GetAllLocationsConsumer();
foreach (var responseLocation in responseLocationList)
{
GenPubMap.Pins.Add(new Pin() { Position = new Position(responseLocation.Location.Latitude, responseLocation.Location.Longitude), Label = "Other user location" });
//await DisplayAlert("TRY", $"consumerPin: response.Result.Location: Lat: {responseLocation.Location.Latitude} \nLong: {responseLocation.Location.Longitude}", "OK");
}
}
catch (Exception ex)
{
await App.Current.MainPage.DisplayAlert("Error", $"{ex.Message}\n{ex.StackTrace}", "Ok");
}
}
private void DesiredVehicle_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
|
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using Store.Books.Domain;
using Store.Books.Domain.Enums;
using System.Threading.Tasks;
using Store.Books.Infrastructure.Interfaces;
namespace Store.Books.Order.Services
{
public class StoreService : Interfaces.IStoreService
{
private readonly IOrderRepository _orders;
private readonly IPaymentRepository _payments;
private readonly IBusketRepository _buskets;
private readonly ILogger<StoreService> _logger;
public StoreService(IOrderRepository orders,
IPaymentRepository payments,
IBusketRepository buskets,
ILogger<StoreService> logger)
{
_orders = orders;
_payments = payments;
_buskets = buskets;
_logger = logger;
}
public async Task<Domain.Order> CreateOrUpdateOrder(int bookId, string title, int priceId, decimal price, string userName)
{
if (0 >= bookId)
{
_logger.LogWarning($"CreateOrder: bookId <= 0: {bookId}");
throw new ArgumentOutOfRangeException($"bookId <= 0: {bookId}");
}
if (price < 0)
{
_logger.LogWarning($"CreateOrder: price amount too low for bookId: {bookId}");
throw new ArgumentOutOfRangeException($"lastPrice not found for bookId: {bookId}");
}
var order = await GetLastUnpayedOrder(userName);
if (order is null)
{
_logger.LogWarning($"CreateOrder: last order for user: {userName} not found, creating new.");
await _orders.Insert(new Domain.Order
{
UserName = userName,
Status = OrderStatusEnum.Created,
Created = DateTime.Now,
Total = price
});
order = await GetLastUnpayedOrder(userName);
}
await AddToBusket(order, bookId, title, priceId, price);
return order;
}
public async Task<bool> AddToBusket(Domain.Order order, int bookId, string title, int priceId, decimal price)
{
var existing = _buskets
.Get(p => p.Order.Id == order.Id && p.BookId == bookId, includeProperties: "Order, Book");
if (!(existing is null))
{
_logger.LogWarning($"AddToBusket: bookId: {bookId} exist in busket");
return false;
}
await _buskets.Insert(new Busket { Order = order, BookId = bookId, PriceId=priceId, Price = price });
return SafeSave();
}
public bool DeleteFromBusket(Domain.Order order, int bookId)
{
//var busket = ????;
return false;
}
public async Task<Domain.Order> FindOrder(int orderId)
{
return await _orders.GetById(orderId);
}
public bool CompleteOrder(int orderId)
{
throw new NotImplementedException();
}
public bool SafeSave()
{
try
{
return true;
}
catch (Exception exception)
{
return false;
}
}
public async Task<Domain.Order> GetLastUnpayedOrder(string userName)
{
return (await _orders.Get(p => p.UserName == userName && p.Status == OrderStatusEnum.Created))
.OrderByDescending(p => p.Created)
.FirstOrDefault();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace MyFrame
{
public class INI
{
static string INIPath;
static StringBuilder result;
static string temp;
static INI()
{
INIPath = Root + @"\Config.ini";
result = new StringBuilder();
}
//示例
public static void SetXXX(object Value)
{
Set("Basic", "XXX", Value);
}
public static string GetXXX()
{
return Get("Basic", "XXX");
}
#region 其他封装
public static string Root//根目录
{
get { return Environment.CurrentDirectory; }
}
public static void OpenRoot()//打开根目录
{
MyProcess.Run(Root);
}
public static void OpenConfig()//打开配置文件
{
MyProcess.Run(INIPath);
}
#endregion
#region 二次封装
public static void Set(string section, string key, object value)//写入配置
{
WritePrivateProfileString(section, key, value.ToString(), INIPath);
}
public static string Get(string section, string key)//读取配置
{
GetPrivateProfileString(section, key, "Not Found", result, 34, INIPath);//最大只能读34位字符
temp = result.ToString();
if (temp.Equals("") || temp.Equals("Not Found"))
{
if (temp == "Not Found")
Console.WriteLine("意外:请检查配置文件是否存在,或配置中是否存在指定的键。[{0}]-{1}", section, key);
if (temp == "")
Console.WriteLine("意外:配置文件中的指定键值为空。[{0}]-{1}", section, key);
temp = "ERROR";//两种情况的默认返回值
}
return temp;
}
#endregion
#region 方法引用
/// <summary>
/// 向指定配置文件的指定块写入指定键的值。若配置文件不存在,则创建文件并添加指定的键。
/// </summary>
/// <param name="section">块</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="INIPath">路径</param>
/// <returns>非零表示成功,零表示失败(类型可以是任意整数类型,除了sbyte)</returns>
[DllImport("kernel32")]
static extern byte WritePrivateProfileString(string section, string key, string value, string INIPath);//写入配置
/// <summary>
/// 从指定配置文件的指定块读取指定键的值。
/// </summary>
/// <param name="section">块</param>
/// <param name="key">键</param>
/// <param name="default_value">默认值</param>
/// <param name="result">结果(引用类型)</param>
/// <param name="size">目的缓存器的大小</param>
/// <param name="INIPath">路径</param>
/// <returns>string的长度(类型可以是任意整数类型)</returns>
[DllImport("kernel32")]
static extern sbyte GetPrivateProfileString(string section, string key, string default_value, StringBuilder result, int size, string INIPath);//读取配置
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DivideAndConque
{
public class MedianOf2Array
{
/*http://www.geeksforgeeks.org/median-of-two-sorted-arrays/
* Question: There are 2 sorted arrays A and B of size n each.
* Write an algorithm to find the median of the array obtained
* after merging the above 2 arrays(i.e. array of length 2n).
* The complexity should be O(log(n))
*
* 1) Calculate the medians m1 and m2 of the input arrays ar1[]
and ar2[] respectively.
2) If m1 and m2 both are equal then we are done.
return m1 (or m2)
3) If m1 is greater than m2, then median is present in one
of the below two subarrays.
a) From first element of ar1 to m1 (ar1[0...|_n/2_|])
b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1])
4) If m2 is greater than m1, then median is present in one
of the below two subarrays.
a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1])
b) From first element of ar2 to m2 (ar2[0...|_n/2_|])
5) Repeat the above process until size of both the subarrays
becomes 2.
6) If size of the two arrays is 2 then use below formula to get
the median.
Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
* the previous method is good for both array are same size.
*/
public int FindMedian(int[] a, int[] b)
{
return FindKth(a, b, (a.Length + b.Length) / 2);
}
private int FindKth(int[] a, int[] b, int k)
{
int n = a.Length;
int m = b.Length;
int i = a.Length * k / (a.Length + b.Length);
int j = k - i - 1;
int ai = a[i];
int ai_1 = (i - 1) >= 0 ? a[i - 1] : 0;
int bj = b[j];
int bj_1 = (j - 1) >= 0 ? b[j - 1] : 0;
if (ai >= bj_1 && ai <= bj)
return ai;
else if (bj >= ai_1 && bj <= ai)
return bj;
if (ai < bj)
{
return FindKth(trimArray(a, i), b, k - i - 1);
}
else
{
return FindKth(a, trimArray(b, j), k - j - 1);
}
}
private int[] trimArray(int[] input, int i)
{
int[] res = new int[input.Length - i];
for (int k = i + 1; k < input.Length; k++)
{
res[k - i - 1] = input[k];
}
return res;
}
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("InitialConversationLines")]
public class InitialConversationLines : MonoClass
{
public InitialConversationLines(IntPtr address) : this(address, "InitialConversationLines")
{
}
public InitialConversationLines(IntPtr address, string className) : base(address, className)
{
}
public static List<string> BRM_INITIAL_CONVO_LINES
{
get
{
Class245 class2 = MonoClass.smethod_7<Class245>(TritonHs.MainAssemblyPath, "", "InitialConversationLines", "BRM_INITIAL_CONVO_LINES");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public static List<string> LOE_INITIAL_CONVO_LINES
{
get
{
Class245 class2 = MonoClass.smethod_7<Class245>(TritonHs.MainAssemblyPath, "", "InitialConversationLines", "LOE_INITIAL_CONVO_LINES");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
}
}
|
namespace medicine_dose_kata_domain.dependencies
{
public enum Medicine
{
PressureRaisingMedicine,
PressureLoweringMedicine
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace farkliTurlerdeUrunEkleme
{
class elektronik
{
public string marka;
public string model;
public double fiyat;
public int stok;
}
class gida
{
public string marka;
public string urunAdi;
public DateTime sonKullanmaTarihi;
public double fiyat;
public int stok;
}
class multimedia
{
public string urunAdi;
public string yayimci;
public double fiyat;
public int stok;
}
}
|
namespace Ambassador.Models.AnnouncementModels.Interfaces
{
public interface IAdminEditAnnouncementModel
{
string Id { get; set; }
string Message { get; set; }
string Url { get; set; }
string ForUserType { get; set; }
byte[] RowVersion { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ExchagneUI : MonoBehaviour {
public GameObject m_exchangeUI;
public Image m_leftCard;
public Image m_partnerCard;
public Image m_rightCard;
public void Hide()
{
m_exchangeUI.SetActive(false);
}
public void View()
{
m_exchangeUI.SetActive(true);
}
}
|
using Library.DataAccess.Interface;
using Library.Services;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Library.UnitTests
{
[TestFixture]
public class BookServiceTests
{
//nunit, xunit -> Not specific ones
//Naming convention for a test: Name of the method to test[i.e. AddBook_[Scenerio(i.e.InvalidAuthorId)]_[Expected Result(i.e.Exception)]
//Arrange Act Assert is good practice
[TestCase("Harry Potter",-1)]
[TestCase("Cirque du Soleil",0)]
[TestCase("Watchmen",-3)]
public async Task AddBook_InvalidAuthorId_Exception(string title,int badId) {
//Arrange->Preparing variables and objects for tests
Mock<IBookRepository> fakeBookRepo = new Mock<IBookRepository>();
Mock<ILibraryLogRepository> fakeLogRepo = new Mock<ILibraryLogRepository>();
BookService bookService = new BookService(fakeBookRepo.Object,fakeLogRepo.Object);
//Act->Calling all methods
await bookService.AddBook(title, badId);
//Assert->Verify result
Assert.ThrowsAsync<ArgumentException>(() => bookService.AddBook(title,badId));
}
}
}
|
namespace JonahRuleEngine
{
internal class Constants
{
internal const string SUCCESS = "Success";
internal const string EXIT = "Bye";
internal const string FAILURE = "Fail";
internal const string BAD_REQUEST = "Bad Request";
internal const string REMOVE_SUCCESS = "Rule remove success";
internal const string RULE_NOT_EXISTS = "Rule not available";
internal const string RULE_ADD_SUCCESS = "Rule add success";
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NewsMooseConsole.Controller;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NewsMooseConsole.Controller.Tests
{
[TestClass]
public class CommandControllerTests
{
[TestMethod]
public void CanExecuteTest_ExecuteDisplayMainMenu_ShouldBeExecutable()
{
CommandController controller = new CommandController();
Assert.IsTrue(controller.CanExecute("DisplayMainMenu"));
}
[TestMethod]
public void CanExecuteTest_ExecuteRandomMethod_ShouldNotExecute()
{
CommandController controller = new CommandController();
Assert.IsFalse(controller.CanExecute("RandomBlaBullBla" + Guid.NewGuid()));
}
[TestMethod]
public void ExecuteTest_ExecuteDisplayMainMenu_ShouldExecute()
{
CommandController controller = new CommandController();
controller.Execute("DisplayMainMenu");
}
[TestMethod]
public void ExecuteTest_ExecuteRandomMethod_ShouldThrowException()
{
CommandController controller = new CommandController();
Assert.ThrowsException<Exception>(() => controller.Execute("RandomBla" + Guid.NewGuid()));
}
[TestMethod]
public void DisplayPublishersTest_ShouldExecute()
{
CommandController controller = new CommandController();
controller.Execute("ShowPublishers");
}
[TestMethod]
public void DisplayNewspapersTest_ShouldExecute()
{
CommandController controller = new CommandController();
controller.Execute("ShowNewsPaper");
}
}
} |
using System.Collections.Generic;
using UnityEngine;
namespace Lowscope.Saving.Components
{
[AddComponentMenu("Saving/Components/Extras/Write Save To Disk"), DisallowMultipleComponent]
public class WriteSaveToDisk : MonoBehaviour
{
public enum Trigger
{
OnEnable,
OnStart
}
[Tooltip("Triggers that can save the game.")]
[Header("You can also call save using ")]
public Trigger[] saveTriggers = new Trigger[1] { Trigger.OnEnable };
private HashSet<Trigger> triggers = new HashSet<Trigger>();
private void Awake()
{
int triggerCount = saveTriggers.Length;
for (int i = 0; i < triggerCount; i++)
{
Trigger trigger = saveTriggers[i];
if (!triggers.Contains(trigger))
triggers.Add(trigger);
}
}
private void OnEnable()
{
if (triggers.Contains(Trigger.OnEnable))
TriggerSave();
}
private void Start()
{
if (triggers.Contains(Trigger.OnStart))
TriggerSave();
}
public void TriggerSave()
{
SaveMaster.WriteActiveSaveToDisk();
}
}
}
|
using NUnit.Framework;
using System.Linq;
using OnlinerCore.Pages;
using static OnlinerCore.Pages.FilterNotebooksComponent;
using static OnlinerCore.Pages.FilterNotebooksComponent.ProcessorType;
namespace OnlinerTests.Tests.Filter.Notebooks
{
[TestFixture]
[Parallelizable]
public class FilterProcessorsTests : TestsSetup
{
[TestCaseSource(typeof(ProcessorsData), "processors")]
public void FilterProcessorTest(ProcessorType[] processors)
{
var notebooksComponent = new FilterNotebooksComponent(_webDriver);
var resultsComponent = new ResultsComponent(_webDriver);
resultsComponent.Open("https://catalog.onliner.by/notebook");
notebooksComponent.SelectProcessor(processors);
resultsComponent.WaitPageLoad();
string[] description = resultsComponent.GetDescription();
if (!description.All(descr => processors.Any(p => descr.Contains(p.ToString().Replace("_", " ")))))
{
Assert.Fail("item with description " + " not contains model ");
}
string message = "filter processor: success";
log.Pass(message);
}
}
class ProcessorsData
{
static object[] processors = {
new ProcessorType[] { AMD_A6, AMD_A10 },
new ProcessorType[] { Intel_Atom, Intel_Core_i7},
new ProcessorType[] { Intel_Atom}
};
}
}
|
/*
Keyboard and mouse based control scheme.
Good key mapping discussion here:
https://forum.unity.com/threads/most-common-keyboard-mouse-inputs-for-pc-games.380594/
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using Assets.Source.Controls;
public class PcControlScheme : MonoBehaviour, IVehicleManager
{
public float _sensitivity=2.0f; // mouse look speed (degrees rotation per pixel of mouse movement?)
// User Input data
public UserInput ui;
public Vector3 playerPosition; // <- in global coordinates
public Vector3 playerVelocity; // <- for keeping an eye on speed
private GameObject playerObject;
private Transform playerTransform;
private Transform cameraTransform;
private IVehicleMotionScheme currentVehicle;
private Stack<IVehicleMotionScheme> vehicleStack;
public void PushVehicle(IVehicleMotionScheme newVehicle)
{
vehicleStack.Push(currentVehicle);
currentVehicle=newVehicle;
ui.yaw=0.0f; // face forward in vehicle
}
public void PopVehicle()
{
if (vehicleStack.Count>0) {
currentVehicle=vehicleStack.Pop();
}
}
public void Start()
{
playerObject = gameObject; // This script is loaded as a component of the Player
playerTransform = playerObject.transform;
cameraTransform = Camera.main.transform; // The main camera, inside the Player
ui.yaw=playerTransform.eulerAngles.y;
Cursor.lockState = CursorLockMode.Locked; // grab mouse
Debug.Log("Started Pc Controls");
// WASD move the player around
SetMove(KeyCode.W, new Vector3(1, 0, 0));
SetMove(KeyCode.S, new Vector3(-1, 0, 0));
SetMove(KeyCode.A, new Vector3(0, 0, 1));
SetMove(KeyCode.D, new Vector3(0, 0, -1));
// + and - scale the player up and down
SetMove(KeyCode.Plus, new Vector3(0, +1, 0));
SetMove(KeyCode.Equals, new Vector3(0, +1, 0));
SetMove(KeyCode.Minus, new Vector3(0, -1, 0));
SetMove(KeyCode.Underscore, new Vector3(0, -1, 0));
currentVehicle = gameObject.AddComponent<WalkingMotion>(); // new WalkingMotion();
vehicleStack=new Stack<IVehicleMotionScheme>();
}
// This maps a keyboard character to a player motion vector.
// The up direction is overloaded to mean "scale the player".
private Dictionary<KeyCode, Vector3> _movementControls = new Dictionary<KeyCode, Vector3>();
public void SetMove(KeyCode keyCode, Vector3 direction)
{
_movementControls.Add(keyCode, direction);
}
// Apply physics forces
public void FixedUpdate()
{
/*
var moveVector = new Vector3();
foreach(var key in _movementControls.Keys)
{
if (Input.GetKey(key))
{
moveVector += _movementControls[key];
}
}
ui.move=moveVector;
*/
ui.move=new Vector3(
Input.GetAxis("Vertical"), //<- move.x: forward direction (WS keys)
0.0f, //<- move.y: upward direction
-Input.GetAxis("Horizontal") //<- move.z: turning left (AD keys)
);
ui.action=Input.GetKey(KeyCode.F) || Input.GetKey(KeyCode.Mouse0) || Input.GetKey(KeyCode.Return);
ui.jump=Input.GetKey(KeyCode.Space);
ui.sprint=Input.GetKey(KeyCode.LeftShift);
ui.menu=Input.GetKey(KeyCode.Tab);
currentVehicle.VehicleFixedUpdate(ref ui,playerTransform,cameraTransform);
}
private Vector2 smoothedMouse; // for smoothing between frames
private float lastFpsTime=0;
private int lastFpsCount=0;
// Update graphics motions
public void Update()
{
// var mouseInput = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
var mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
mouseInput *= _sensitivity; // no Time.deltaTime, because "you do not need to be concerned about varying frame-rates when using this value."
float smooth=Mathf.Clamp(1.0f-60.0f*Time.deltaTime,0.01f,1.0f); // amount of mouse smoothing to apply
smoothedMouse = (1.0f-smooth)*mouseInput + smooth*smoothedMouse;
float Y_look_direction=+1.0f; // normal Y mouse
// Y_look_direction=-1.0f; // inverted Y look
// Apply incremental mouse movement to the look directions
ui.pitch += -Y_look_direction*smoothedMouse.y; // degrees rotation about X axis (pitch)
ui.yaw += smoothedMouse.x; // degrees rotation about Y axis (yaw)
currentVehicle.VehicleUpdate(ref ui,playerTransform,cameraTransform);
lastFpsTime+=Time.deltaTime;
lastFpsCount++;
if (lastFpsTime>10.0f) {
float fps=(int)(lastFpsCount/lastFpsTime);
Debug.Log("Framerate: "+fps+" frames per second");
lastFpsCount=0;
lastFpsTime=0;
}
}
}
|
/****************************************************************************
*
* CRI Middleware SDK
*
* Copyright (c) 2011-2012 CRI Middleware Co., Ltd.
*
* Library : CRI Atom
* Module : CRI Atom for Unity
* File : CriAtomProjInfo_Unity.cs
* Tool Ver. : CRI Atom Craft LE Ver.2.13.00
* Date Time : 2016/03/16 17:48
* Project Name : adx2letest
* Project Comment :
*
****************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public partial class CriAtomAcfInfo
{
static partial void GetCueInfoInternal()
{
acfInfo = new AcfInfo("ACF", 0, "", "adx2letest.acf","ee13379b-6d7f-424f-b5cd-02800eec27c9","DspBusSetting_0");
acfInfo.aisacControlNameList.Add("Any");
acfInfo.aisacControlNameList.Add("Distance");
acfInfo.aisacControlNameList.Add("AisacControl02");
acfInfo.aisacControlNameList.Add("AisacControl03");
acfInfo.aisacControlNameList.Add("AisacControl04");
acfInfo.aisacControlNameList.Add("AisacControl05");
acfInfo.aisacControlNameList.Add("AisacControl06");
acfInfo.aisacControlNameList.Add("AisacControl07");
acfInfo.aisacControlNameList.Add("AisacControl08");
acfInfo.aisacControlNameList.Add("AisacControl09");
acfInfo.aisacControlNameList.Add("AisacControl10");
acfInfo.aisacControlNameList.Add("AisacControl11");
acfInfo.aisacControlNameList.Add("AisacControl12");
acfInfo.aisacControlNameList.Add("AisacControl13");
acfInfo.aisacControlNameList.Add("AisacControl14");
acfInfo.aisacControlNameList.Add("AisacControl15");
acfInfo.acbInfoList.Clear();
AcbInfo newAcbInfo = null;
newAcbInfo = new AcbInfo("U2DGameMusicSet", 0, "", "U2DGameMusicSet.acb", "U2DGameMusicSet.awb","0e21441e-78d3-4e27-b0c2-e04192364829");
acfInfo.acbInfoList.Add(newAcbInfo);
newAcbInfo.cueInfoList.Add(17, new CueInfo("altu", 17, ""));
newAcbInfo.cueInfoList.Add(18, new CueInfo("awhh", 18, ""));
newAcbInfo.cueInfoList.Add(19, new CueInfo("fire", 19, ""));
newAcbInfo.cueInfoList.Add(20, new CueInfo("gaugemax", 20, ""));
newAcbInfo.cueInfoList.Add(21, new CueInfo("haltu", 21, ""));
newAcbInfo.cueInfoList.Add(22, new CueInfo("hoiltu", 22, ""));
newAcbInfo.cueInfoList.Add(23, new CueInfo("iyaa", 23, ""));
newAcbInfo.cueInfoList.Add(24, new CueInfo("jump", 24, ""));
newAcbInfo.cueInfoList.Add(25, new CueInfo("kuyasigaru", 25, ""));
newAcbInfo.cueInfoList.Add(26, new CueInfo("letsgo", 26, ""));
newAcbInfo.cueInfoList.Add(27, new CueInfo("madamada", 27, ""));
newAcbInfo.cueInfoList.Add(28, new CueInfo("nice", 28, ""));
newAcbInfo.cueInfoList.Add(29, new CueInfo("pon", 29, ""));
newAcbInfo.cueInfoList.Add(30, new CueInfo("shoot", 30, ""));
newAcbInfo.cueInfoList.Add(31, new CueInfo("sonna", 31, ""));
newAcbInfo.cueInfoList.Add(32, new CueInfo("sonnnakougeki", 32, ""));
newAcbInfo.cueInfoList.Add(33, new CueInfo("sore", 33, ""));
newAcbInfo.cueInfoList.Add(34, new CueInfo("start_0", 34, ""));
newAcbInfo.cueInfoList.Add(35, new CueInfo("teei", 35, ""));
newAcbInfo.cueInfoList.Add(36, new CueInfo("teikyou", 36, ""));
newAcbInfo.cueInfoList.Add(37, new CueInfo("tooou", 37, ""));
newAcbInfo.cueInfoList.Add(38, new CueInfo("torya", 38, ""));
newAcbInfo.cueInfoList.Add(39, new CueInfo("tou", 39, ""));
newAcbInfo.cueInfoList.Add(40, new CueInfo("uwaltu", 40, ""));
newAcbInfo.cueInfoList.Add(41, new CueInfo("uwaltu_", 41, ""));
newAcbInfo.cueInfoList.Add(42, new CueInfo("waltu", 42, ""));
newAcbInfo.cueInfoList.Add(43, new CueInfo("ya", 43, ""));
newAcbInfo.cueInfoList.Add(44, new CueInfo("yada", 44, ""));
newAcbInfo.cueInfoList.Add(45, new CueInfo("yatta", 45, ""));
newAcbInfo.cueInfoList.Add(0, new CueInfo("block_break", 0, ""));
newAcbInfo.cueInfoList.Add(1, new CueInfo("block_hit", 1, ""));
newAcbInfo.cueInfoList.Add(2, new CueInfo("get", 2, ""));
newAcbInfo.cueInfoList.Add(3, new CueInfo("start", 3, ""));
newAcbInfo.cueInfoList.Add(4, new CueInfo("battle", 4, ""));
}
}
|
using Alfheim.FuzzyLogic;
using Alfheim.FuzzyLogic.FuzzyFunctionAttributes;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Alfheim.GUI.Model
{
public static class InRangePointParser
{
public static IEnumerable<InRangePoint> Parse(IFuzzyFunction function)
{
return function.GetType()
.GetProperties()
.Where(property => property.GetCustomAttributes(typeof(InRangePointAttribute)).Any())
.Select(property => new KeyValuePair<string, InRangePointAttribute>(property.Name,
property.GetCustomAttribute<InRangePointAttribute>()))
.Select(attribute => new InRangePoint(attribute.Key, attribute.Value.LeftPoint, attribute.Value.RightPoint));
}
}
}
|
namespace Tookan.NET.Core
{
public class TaskHistory
{
public int Id { get; set; }
public int JobId { get; set; }
public int FleetId { get; set; }
public string FleetName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public string CreationDateTime { get; set; }
}
} |
using System;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
namespace Umbraco.Core.Configuration.UmbracoSettings
{
public class UmbracoSettingsSection : ConfigurationSection, IUmbracoSettingsSection
{
[ConfigurationProperty("backOffice")]
internal BackOfficeElement BackOffice
{
get { return (BackOfficeElement)this["backOffice"]; }
}
[ConfigurationProperty("content")]
internal ContentElement Content
{
get { return (ContentElement)this["content"]; }
}
[ConfigurationProperty("security")]
internal SecurityElement Security
{
get { return (SecurityElement)this["security"]; }
}
[ConfigurationProperty("requestHandler")]
internal RequestHandlerElement RequestHandler
{
get { return (RequestHandlerElement)this["requestHandler"]; }
}
[ConfigurationProperty("templates")]
internal TemplatesElement Templates
{
get { return (TemplatesElement)this["templates"]; }
}
[ConfigurationProperty("logging")]
internal LoggingElement Logging
{
get { return (LoggingElement)this["logging"]; }
}
[ConfigurationProperty("scheduledTasks")]
internal ScheduledTasksElement ScheduledTasks
{
get { return (ScheduledTasksElement)this["scheduledTasks"]; }
}
[ConfigurationProperty("providers")]
internal ProvidersElement Providers
{
get { return (ProvidersElement)this["providers"]; }
}
[ConfigurationProperty("web.routing")]
internal WebRoutingElement WebRouting
{
get { return (WebRoutingElement)this["web.routing"]; }
}
IContentSection IUmbracoSettingsSection.Content
{
get { return Content; }
}
ISecuritySection IUmbracoSettingsSection.Security
{
get { return Security; }
}
IRequestHandlerSection IUmbracoSettingsSection.RequestHandler
{
get { return RequestHandler; }
}
ITemplatesSection IUmbracoSettingsSection.Templates
{
get { return Templates; }
}
IBackOfficeSection IUmbracoSettingsSection.BackOffice
{
get { return BackOffice; }
}
ILoggingSection IUmbracoSettingsSection.Logging
{
get { return Logging; }
}
IScheduledTasksSection IUmbracoSettingsSection.ScheduledTasks
{
get { return ScheduledTasks; }
}
IProvidersSection IUmbracoSettingsSection.Providers
{
get { return Providers; }
}
IWebRoutingSection IUmbracoSettingsSection.WebRouting
{
get { return WebRouting; }
}
}
}
|
using System.Runtime.InteropServices;
using WagahighChoices.Toa.Imaging;
namespace WagahighChoices
{
/// <summary>
/// <see cref="Bgra32Image"/> の <see cref="Pixel.A"/> を無視してピクセル情報を公開します。
/// </summary>
[StructLayout(LayoutKind.Auto)]
internal readonly struct Bgr2432InputImage : IInputImage
{
private readonly Bgra32Image _image;
private readonly byte[] _data;
private readonly int _offset;
public Bgr2432InputImage(Bgra32Image image)
{
this._image = image;
var data = image.Data;
this._data = data.Array;
this._offset = data.Offset;
}
public int Width => this._image.Width;
public int Height => this._image.Height;
public Pixel GetPixel(int index)
{
var baseIndex = this._offset + index * 4;
return new Pixel(this._data[baseIndex + 2], this._data[baseIndex + 1], this._data[baseIndex], 255);
}
}
}
|
namespace Whale.API.Models.Slack
{
public class ExternalCommand
{
public string Text { get; set; }
public string Email { get; set; }
}
}
|
using System;
using System.Linq;
namespace RepoDbOrm.MultiQuery
{
partial class Program
{
static void Main(string[] args)
{
Console.WriteLine("[RepoDbOrm.MultiQuery]");
Console.WriteLine(new string(char.Parse("-"), 50));
// Get all people
Console.Write("Enter Sales Person Id (274, 275, 276): ");
var id = int.Parse(Console.ReadLine());
var result = GetSales(id);
// Check the person
if (result.Item1.Any() == false)
{
Console.WriteLine($"No sales person found from the database with Id = '{id}'.");
return;
}
// Display the person
var person = result.Item1.First();
Console.WriteLine($"Found sales person: {person.FirstName} {person.LastName}");
// List all the sales order header
if (result.Item2.Any() == false)
{
Console.WriteLine($"Sales person '{person.FirstName} {person.LastName}' has no sales yet.");
}
else
{
Console.WriteLine(new string(char.Parse("-"), 50));
Console.Write("Press any key to list all the sales made by this sales person.");
Console.ReadLine();
result.Item2.ToList().ForEach(soh =>
{
Console.WriteLine($"Sales Order: {soh.Id}, Order Number: {soh.SalesOrderNumber}, Sub Total: {soh.SubTotal}, " +
$"Shipped Date: {soh.ShipDate.Value.ToShortDateString()}");
});
}
// Readline
Console.Write("Press any key to exit.");
Console.ReadLine();
}
}
}
|
using TechTalk.SpecFlow;
namespace Foo.specs
{
[Binding]
public class DemoDataTableExampleSteps
{
[Given]
public void Given_I_have_entered(Table table)
{
var secondNumberEntered = table.Rows[1][0];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.