text stringlengths 13 6.01M |
|---|
using KeHenUI.Social.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KeHenUI.Social.Common.Services
{
public class LuckyDrawListService : BaseService<LuckyDrawList, int>
{
public IList<LuckyDrawList> GetLuckyDrawList()
{
return DbBase.Query<LuckyDrawList>().ToList();
}
}
}
|
using Entidades.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
#pragma warning disable CS0661
/// <summary>
/// Clase producto que representa los objetos a vender el en petshop
/// </summary>
public class Producto
#pragma warning restore CS0661
{
public static int PrevId;
string descripcion;
int id;
double precio;
int cantidad;
float peso;
static List<Producto> listaProductos;
public static List<Producto> ListaProductos
{
get
{
return listaProductos;
}
set
{
listaProductos = value;
}
}
ETipoProducto tipoProducto;
public ETipoProducto TipoProducto
{
get
{
return this.tipoProducto;
}
set
{
this.tipoProducto = value;
}
}
public Producto this[int id]
{
get
{
foreach (Producto prod in ListaProductos)
{
if (prod.id == id)
{
return prod;
}
}
return null;
}
}
public string Descripcion
{
get
{
return this.descripcion;
}
set
{
this.descripcion = value;
}
}
public int Id
{
get
{
return this.id;
}
set
{
this.id = value;
}
}
public double Precio
{
get
{
return this.precio;
}
set
{
this.precio = value;
}
}
public int Cantidad
{
get
{
return this.cantidad;
}
set
{
this.cantidad = value;
}
}
public float Peso
{
get
{
return this.peso;
}
set
{
this.peso = value;
}
}
static Producto()
{
PrevId = 0;
ListaProductos = new List<Producto>();
}
/// <summary>
/// Carga de prueba de productos hardcodeados
/// </summary>
/// <returns>devuelve true si logro la carga, false si no la logro</returns>
public static bool CrearProductoPrueba()
{
bool altaOk = false;
Random rnd = new Random();
int testCount = 0;
for (int i = 0; i < 10; i++)
{
testCount++;
int salary = rnd.Next(10000, 100000);
Producto newProducto = new Producto($"producto{testCount}", (ETipoProducto)rnd.Next(0, 3), rnd.Next(100, 500), rnd.Next(5, 20), rnd.Next(100,500));
altaOk = ListaProductos + newProducto;
if (!altaOk)
{
break;
}
}
return altaOk;
}
//Constructor vacio para utilizarse junto cno el indexador
public Producto()
{
}
/// <summary>
/// Constructor de la clase producto, asigna sus valores de tipo, precio y cantidad, no se puede inicializar un producto sin estos datos
/// </summary>
/// <param name="tipo">ETipoProducto Enumerado, de valores predefinidos, con el valor a ser asignado</param>
/// <param name="precio">Precio del producto por unidad</param>
/// <param name="cantidad">Cantidad de productos en existencia</param>
public Producto(string descripcion, ETipoProducto tipo, double precio, int cantidad, float peso)
{
this.Id = ++PrevId;
PrevId = this.Id;
this.TipoProducto = tipo;
this.Precio = precio;
this.Cantidad = cantidad;
this.Descripcion = descripcion;
this.Peso = peso;
}
#region sobrecargas operadores
/// <summary>
/// Sobrecarga del metodo + para agregar una carga de producto al listado de productos
/// </summary>
/// <param name="listaProductos">listado de productos</param>
/// <param name="Producto">producto a ser cargado</param>
/// <returns>devuelve true si fue exitoso, false si no lo fue</returns>
public static bool operator +(List<Producto> listaProductos, Producto Producto)
{
bool altaOk = false;
foreach (Producto prd in listaProductos)
{
if (prd == Producto)
{
return false;
}
}
listaProductos.Add(Producto);
altaOk = true;
return altaOk;
}
/// <summary>
/// Sobrecarga del metodo - para eliminar una carga de producto del listado de productos
/// </summary>
/// <param name="listaProductos">listado de productos</param>
/// <param name="Producto">producto a ser eliminado</param>
/// <returns>devuelve true si fue exitoso, false si no lo fue</returns>
public static bool operator -(List<Producto> listaProductos, Producto Producto)
{
bool removeOk = false;
foreach (Producto prd in listaProductos)
{
if (prd == Producto)
{
listaProductos.Remove(prd);
return true;
}
}
return removeOk;
}
/// <summary>
/// Compara dos productos por sus ids
/// </summary>
/// <param name="Producto1">primer producto a ser evaluado</param>
/// <param name="Producto2">segundo producto a ser evaluado</param>
/// <returns>devuelve true si son iguales, false si no lo son</returns>
public static bool operator ==(Producto Producto1, Producto Producto2)
{
if (Producto1.Id == Producto2.Id)
{
return true;
}
return false;
}
/// <summary>
/// Diferencia dos productos por sus ids
/// </summary>
/// <param name="Producto1">primer producto a ser evaluado</param>
/// <param name="Producto2">segundo producto a ser evaluado</param>
/// <returns>devuelve true si son diferentes, false si no lo son</returns>
public static bool operator !=(Producto Producto1, Producto Producto2)
{
if(Producto2 == null)
{
return false;
}
return !(Producto1 == Producto2);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YzkSoftWare.Data.Sql.MsSql
{
public class DteMsSqlExpressForTable<T> : MsSqlExpressBase
where T : class
{
public DteMsSqlExpressForTable()
: base(null, DataModel.DbTypeForDataModel.Sql, SqlExpressResult.EffectCount)
{
Express = MsSqlTableCreateHelper.CreateDefineTableSql(typeof(T).GetDataModel());
}
public override object Clone()
{
return new DteMsSqlExpressForTable<T>();
}
}
}
|
using AutoMapper;
using Enrollment.Bsl.Business.Requests;
using Enrollment.Bsl.Business.Responses;
using Enrollment.Bsl.Utils;
using Enrollment.Repositories;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Enrollment.Bsl.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AnonymousTypeListController : ControllerBase
{
private readonly IMapper mapper;
private readonly IEnrollmentRepository repository;
public AnonymousTypeListController(IMapper mapper, IEnrollmentRepository repository)
{
this.mapper = mapper;
this.repository = repository;
}
[HttpPost("GetList")]
public async Task<BaseResponse> GetList([FromBody] GetObjectListRequest request)
{
return await RequestHelpers.GetAnonymousList
(
request,
repository,
mapper
);
}
}
}
|
namespace Oldest_Family_Member
{
using System;
using System.Collections.Generic;
public class Family
{
private List<Person> persons;
public Family()
{
this.persons = new List<Person>();
}
public List<Person> Persons { get; set; }
public void AddMember(Person member)
{
this.persons.Add(member);
}
public static void GetOldestMember(List<Person> persons)
{
int age = Int32.MinValue;
foreach (var p in persons)
{
if (p.age > age)
{
age = p.age;
}
}
var oldestPerson = persons.Find(p => p.age == age);
Console.WriteLine($"{oldestPerson.name} {oldestPerson.age}");
}
}
}
|
using Livet;
using Livet.EventListeners;
using LivetSample.Models;
namespace LivetSample.ViewModels
{
class MainWindowViewModel : ViewModel
{
private SampleModel SampleModel = new SampleModel();
public int Counter { get => SampleModel.ButtonCount; }
#region InputFile
private string _InputPath;
public string InputPath
{
get => _InputPath;
set
{
if (RaisePropertyChangedIfSet(ref _InputPath, value))
{
SampleModel.SetFilepath(_InputPath);
}
}
}
public long _InputFileSize;
public long InputFileSize
{
get => _InputFileSize;
private set => RaisePropertyChangedIfSet(ref _InputFileSize, value);
}
#endregion
public MainWindowViewModel()
{
CompositeDisposable.Add(SampleModel);
#region ModelEvent
// Modelの変更通知を伝搬
var listener = new PropertyChangedEventListener(SampleModel)
{
nameof(SampleModel.ButtonCount), (_, e) =>
{
if (e.PropertyName == nameof(SampleModel.ButtonCount))
{
RaisePropertyChanged(nameof(Counter));
}
},
nameof(SampleModel.FileSize), (_, e) =>
{
if (e.PropertyName == nameof(SampleModel.FileSize))
{
InputFileSize = SampleModel.FileSize;
}
},
};
#endregion
}
public void Initialize() { }
// Viewからメソッドを直接Binding
public void ButtonClickCommand()
{
SampleModel.IncrementButtonCount();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TamagotchiBL.Models;
namespace TamagotchiWebService.DataTransferObjects
{
public class AnimalDTO
{
public int AnimalId { get; set; }
public string AnimalName { get; set; }
public DateTime AnimalBirthDate { get; set; }
public double AnimalWeight { get; set; }
public double AnimalAge { get; set; }
public int AnimalHunger { get; set; }
public int AnimalCleaness { get; set; }
public int AnimalHappiness { get; set; }
public string StatusName { get; set; }
public string LifeCycleName { get; set; }
public int PlayerId { get; set; }
public AnimalDTO() { }
public AnimalDTO(Animal a)
{
this.AnimalId = a.AnimalId;
this.AnimalName = a.AnimalName;
this.AnimalBirthDate = a.AnimalBirthDate;
this.AnimalWeight = a.AnimalWeight;
this.AnimalAge = a.AnimalAge;
this.AnimalHappiness = a.AnimalHappiness;
this.AnimalHunger = a.AnimalHunger;
this.AnimalCleaness = a.AnimalCleaness;
this.StatusName = a.Status.StatusName;
this.LifeCycleName = a.LifeCycle.LifeCycleName;
this.PlayerId = a.PlayerId;
}
}
}
|
using Renting.Domain.Agreements;
using Renting.Domain.Offers;
namespace Renting.Domain.Drafts
{
public interface IDraftNumberGenerator
{
AgreementNumber GetNextAvailable(TenantId tenantId, OfferId offerId);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class PieceData : IComparable<PieceData> {
public enum Type { Normal, Hook };
public int direction, range;
public int value;
public readonly Player.PlayerColour colour;
public Type type;
private int normalDir, altDir, normalRan, altRan;
public bool flipped;
private GameObject obj;
/// <summary>
/// The sorting value.
/// </summary>
public int sortingValue;
/// <summary>
/// Accessor for normalDir.
/// </summary>
public int NormalDir { get { return normalDir; } }
/// <summary>
/// Constructor for a normal pieceData
/// </summary>
/// <param name="player">The Player who is the original owner of the piece</param>
/// <param name="normalDir">Normal direction that this peice can go</param>
/// <param name="normalRan">Normal range that this piece can go</param>
/// <param name="altDir">The alternative direction when this piece is captured</param>
/// <param name="altRan">The alternative range when this piece is captured</param>
/// <param name="obj">Game object associated with this pieceData</param>
public PieceData(Player player, int normalDir, int normalRan, int altDir, int altRan, GameObject obj) {
Debug.Assert(normalDir < 6 && normalDir >= 0, "PieceData's normal direction must be between 0 and 6");
Debug.Assert(normalRan > 0, "PieceData's normal range must be greater than 0");
Debug.Assert(altDir < 6 && altDir >= 0, "PieceData's alt direction must be between 0 and 6");
Debug.Assert(altRan > 0, "PieceData's alt range must be greater than 0");
Debug.Assert(obj != null, "PieceData's obj is null on creation");
this.normalDir = normalDir;
this.normalRan = normalRan;
this.altDir = altDir;
this.altRan = altRan;
this.obj = obj;
colour = player.colour;
value = 1;
type = Type.Normal;
direction = normalDir;
range = normalRan;
obj.transform.SetParent(GameObject.Find("Pieces").transform);
// Move to center of the board
obj.transform.position = new Vector3(975, 1000, 925);
}
/// <summary>
/// Constructor for a normal pieceData
/// </summary>
/// <param name="colour">The colour of the piece</param>
/// <param name="normalDir">Normal direction that this peice can go</param>
/// <param name="normalRan">Normal range that this piece can go</param>
/// <param name="altDir">The alternative direction when this piece is captured</param>
/// <param name="altRan">The alternative range when this piece is captured</param>
/// <param name="obj">Game object associated with this pieceData</param>
public PieceData(Player.PlayerColour colour, int normalDir, int normalRan, int altDir, int altRan, GameObject obj) {
Debug.Assert(normalDir < 6 && normalDir >= 0, "PieceData's normal direction must be between 0 and 6");
Debug.Assert(normalRan > 0, "PieceData's normal range must be greater than 0");
Debug.Assert(altDir < 6 && altDir >= 0, "PieceData's alt direction must be between 0 and 6");
Debug.Assert(altRan > 0, "PieceData's alt range must be greater than 0");
Debug.Assert(obj != null, "PieceData's obj is null on creation");
this.normalDir = normalDir;
this.normalRan = normalRan;
this.altDir = altDir;
this.altRan = altRan;
this.colour = colour;
this.obj = obj;
value = 1;
type = Type.Normal;
direction = normalDir;
range = normalRan;
obj.transform.SetParent(GameObject.Find("Pieces").transform);
// Move to center of the board
obj.transform.position = new Vector3(975, 1000, 925);
}
/// <summary>
/// applies the correct textures, should only call this once
/// </summary>
public void SetupTextures() {
string textureBase = "Images/Texture/Piece/" + colour.ToString().ToLower() + "-";
Vector2 textureScale = new Vector2(6f, 10f);
MeshRenderer meshRender = obj.GetComponent<MeshRenderer>();
// normal
Material matNormColour = meshRender.materials[0];
matNormColour.mainTexture = Resources.Load<Texture>(textureBase + HexDir.GetShortName(normalDir) + normalRan);
matNormColour.mainTextureScale = textureScale;
// alt
Material matAltColour = meshRender.materials[1];
if (type != Type.Hook) {
matAltColour.mainTexture = Resources.Load<Texture>(textureBase + HexDir.GetShortName(normalDir) + normalRan + "f");
} else {
matAltColour.mainTexture = Resources.Load<Texture>(textureBase + HexDir.GetShortName(normalDir) + normalRan);
}
matAltColour.mainTextureScale = textureScale;
// piece colour
meshRender.materials[2].color = GetMaterialColor();
}
private Color GetMaterialColor() {
return Player.ConvertToColor32(colour);
}
/// <summary>
/// Flips the piece over when captured
/// </summary>
/// <param name="flip"></param>
public void SetFlipped(bool flip) {
if (type != Type.Hook) {
flipped = flip;
if (flipped) {
obj.transform.eulerAngles = new Vector3(-270f, 90f, 0f);
direction = altDir;
range = altRan;
//obj.transform.Rotate(new Vector3(180f, 60f, 0f));
} else {
obj.transform.eulerAngles = new Vector3(-90f, 30f, 0f);
direction = normalDir;
range = normalRan;
//obj.transform.Rotate(new Vector3(-180f, -60f, 0f));
}
}
}
/// <summary>
/// Moves the gameobject to the location
/// </summary>
/// <param name="location"></param>
public void MoveTo(Vector3 location) {
if (flipped) {
location.y += 50;
}
// Smooth movement
obj.GetComponent<SmoothMovementQueue>().ClearQueue();
obj.GetComponent<SmoothMovementQueue>().ImmediateMove(location);
//obj.transform.position = location;
}
/// <summary>
/// Moves to multiple positions, one at the time.
/// </summary>
/// <param name="locations">Locations.</param>
public void MultiMoveTo(params Vector3[] locations) {
obj.GetComponent<SmoothMovementQueue>().ClearQueue();
foreach (Vector3 v in locations) {
obj.GetComponent<SmoothMovementQueue>().QueueMove(v);
}
}
public GameObject getObj()
{
return obj;
}
public int CompareTo(PieceData comp) {
return sortingValue - comp.sortingValue;
}
public bool isHook()
{
if (type.Equals(Type.Hook))
{
return true;
}
else
{
return false;
}
}
}
|
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Meziantou.Analyzer.Rules;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class UseEventArgsEmptyAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor s_rule = new(
RuleIdentifiers.UseEventArgsEmpty,
title: "Use EventArgs.Empty",
messageFormat: "Use EventArgs.Empty instead of new EventArgs()",
RuleCategories.Usage,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "",
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.UseEventArgsEmpty));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterOperationAction(Analyze, OperationKind.ObjectCreation);
}
private static void Analyze(OperationAnalysisContext context)
{
var operation = (IObjectCreationOperation)context.Operation;
if (operation == null || operation.Constructor == null)
return;
if (operation.Arguments.Length > 0)
return;
var type = context.Compilation.GetBestTypeByMetadataName("System.EventArgs");
if (operation.Constructor.ContainingType.IsEqualTo(type))
{
context.ReportDiagnostic(s_rule, operation);
}
}
}
|
using cryptoprime;
using vinkekfish;
using main_tests;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.IO;
using System.Security.AccessControl;
namespace permutationsTest
{
/*
* Тест касается разработки расширенного алгоритма на 4096 битный ключ
*
* Этот тест пытается посмотреть, что можно сделать с Tweak, чтобы дополнительно рандомозировать перестановки
* Данный тест подсчитывает количество вариантов 32-битного tweak при разных схемах его приращения
* */
unsafe class TweakTest: MultiThreadTest<TweakTest.SourceTask>
{
public TweakTest(ConcurrentQueue<TestTask> tasks): base(tasks, "TweakTest", new TweakTest.SourceTaskFabric())
{
if (!Directory.Exists("results"))
Directory.CreateDirectory("results");
}
public new class SourceTask: MultiThreadTest<SourceTask>.SourceTask
{
public readonly long Number1 = 1;
public readonly long Number2 = 1;
public readonly int Size;
public SourceTask(long Number1, long Number2, int Size)
{
this.Number1 = Number1;
this.Number2 = Number2;
this.Size = Size;
}
}
public new class SourceTaskFabric: MultiThreadTest<SourceTask>.SourceTaskFabric
{
public override IEnumerable<SourceTask> GetIterator()
{
yield return new SourceTask(0, 1253539379, 4);
yield return new SourceTask(1, 0x1_01, 2);
yield return new SourceTask(1, 0x10_01, 2);
yield return new SourceTask(0x10_01, 1, 2);
yield return new SourceTask(22079, 12241, 2);
}
}
public unsafe override void StartTests()
{
var po = new ParallelOptions();
po.MaxDegreeOfParallelism = Environment.ProcessorCount;
Parallel.ForEach
(
sources, po,
delegate (SourceTask task)
{
var fileName = $"results/r-{task.Size.ToString("D1")}-{task.Number1}-{task.Number2}.txt";
if (File.Exists(fileName))
return;
if (task.Size == 2)
{
var countOfVariants = TestAllVariants2(task.Number1, task.Number2);
File.WriteAllText(fileName, $"countOfVariants = {countOfVariants}");
}
else
if (task.Size == 4)
{
var countOfVariants = TestAllVariants4(task.Number1, task.Number2);
File.WriteAllText(fileName, $"countOfVariants = {countOfVariants}");
}
}
); // The end of Parallel.foreach sources running
}
private object TestAllVariants4(long number1, long number2)
{
ulong r = 0;
uint n1 = (uint) number1;
uint n2 = (uint) number2;
var dict = new byte[0x1_0000_0000 >> 3];
uint num = 0;
while (true)
{
num += n1;
num += n2;
if (cryptoprime.BitToBytes.getBit(dict, num))
break;
cryptoprime.BitToBytes.setBit(dict, num);
r++;
}
return r;
}
private ulong TestAllVariants2(long number1, long number2)
{
ulong r = 0;
ushort n1 = (ushort) number1;
ushort n2 = (ushort) number2;
var dict = new byte[0x1_0000_0000 >> 3];
uint num = 0;
while (true)
{
num += (uint) (n2 << 16);
num += n1;
if (cryptoprime.BitToBytes.getBit(dict, num))
break;
cryptoprime.BitToBytes.setBit(dict, num);
r++;
}
return r;
}
}
}
|
using System;
using System.Collections.Generic;
using Modelo;
using Persistencia;
using System;
using System.Collections.Generic;
using System.Text;
namespace Servico
{
public class MedicamentoConsultaServico
{
private MedicamentoConsultaDAL medicamentoConsultaDal = new MedicamentoConsultaDAL();
public IList<ConsultaMedicamento> TodasAsConsultasMedicamentosPorId(long consultaId)
{
return medicamentoConsultaDal.TodasAsConsultasMedicamentosPorId(consultaId);
}
public void GravarConsultaMedicamento(ConsultaMedicamento consultaMedicamento)
{
medicamentoConsultaDal.GravarConsultaMedicamento(consultaMedicamento);
}
public void ExcluirConsultaMedicamento(long id)
{
ConsultaMedicamento consultaMedicamento = new ConsultaMedicamento() { ConsultaMedicamentoId = id };
medicamentoConsultaDal.ExcluirConsultaMedicamento(consultaMedicamento);
}
}
}
|
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
namespace Meziantou.Analyzer.Rules;
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class DoNotUseStringGetHashCodeFixer : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(RuleIdentifiers.DoNotUseStringGetHashCode);
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root?.FindNode(context.Span, getInnermostNodeForTie: true) is not InvocationExpressionSyntax nodeToFix)
return;
if (nodeToFix.Expression is not MemberAccessExpressionSyntax)
return;
var title = "Use StringComparer.Ordinal";
var codeAction = CodeAction.Create(
title,
ct => AddStringComparison(context.Document, nodeToFix, ct),
equivalenceKey: title);
context.RegisterCodeFix(codeAction, context.Diagnostics);
}
private static async Task<Document> AddStringComparison(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var semanticModel = editor.SemanticModel;
var generator = editor.Generator;
var invocationExpression = (InvocationExpressionSyntax)nodeToFix;
if (invocationExpression == null)
return document;
var stringComparer = semanticModel.Compilation.GetBestTypeByMetadataName("System.StringComparer");
if (stringComparer is null)
return document;
var memberAccessExpression = (MemberAccessExpressionSyntax)invocationExpression.Expression;
var newExpression = generator.InvocationExpression(
generator.MemberAccessExpression(
generator.MemberAccessExpression(
generator.TypeExpression(stringComparer, addImport: true),
nameof(StringComparer.Ordinal)),
nameof(StringComparer.GetHashCode)),
memberAccessExpression.Expression);
editor.ReplaceNode(invocationExpression, newExpression);
return editor.GetChangedDocument();
}
}
|
using System;
using System.Linq;
using UnityEngine.Networking;
using BepInEx;
using RoR2;
using UnityEngine;
using RoR2.CharacterAI;
using UnityEngine.Events;
using System.Reflection;
using System.Collections.Generic;
namespace HerosNeverDie
{
[BepInPlugin("HerosNeverDie", "Respawn", "0.1")]
public class Respawn : BaseUnityPlugin
{
private Vector3 deathFootPosition;
private CharacterMaster characterMaster;
private readonly int[] itemStacks = new int[78];
private readonly List<ItemIndex> list = new List<ItemIndex>();
private readonly Dictionary<string, int> userPlayerRespawnNum = new Dictionary<string, int>();
private readonly int RemoveItemNum = 3;
private readonly int RespawnNum = 3;
//private bool preventRespawnUntilNextStageServer;
public Respawn()
{
On.RoR2.CharacterMaster.OnBodyDeath += CharacterMaster_OnBodyDeath;
}
private void CharacterMaster_OnBodyDeath(On.RoR2.CharacterMaster.orig_OnBodyDeath orig, CharacterMaster self)
{
characterMaster = self;
if (NetworkServer.active)
{
deathFootPosition = self.GetBody().footPosition;
BaseAI[] components = self.GetComponents<BaseAI>();
for (int i = 0; i < components.Length; i++)
{
components[i].OnBodyDeath();
}
PlayerCharacterMasterController component = self.GetComponent<PlayerCharacterMasterController>();
if (component)
{
component.OnBodyDeath();
}
int itemAllNum = 0;
list.Clear();
if (self.teamIndex == TeamIndex.Player)
{
for (int i = 0; i < Enum.GetValues(typeof(ItemIndex)).Length; i++)
{
ItemIndex itemIndex = (ItemIndex)i;
if (itemIndex <= ItemIndex.None || itemIndex >= ItemIndex.Count)
{
continue;
}
int num = self.inventory.GetItemCount(itemIndex);
if (num > 0)
{
list.Add(itemIndex);
}
itemAllNum += num;
itemStacks[i] = num;
}
}
string usename = Util.GetBestMasterName(self);
bool tempHerosNeverDie = itemAllNum >= RemoveItemNum;
if (tempHerosNeverDie)
{
int tempNum = 0;
if (userPlayerRespawnNum.ContainsKey(usename) == false)
userPlayerRespawnNum[usename] = 0;
else
tempNum = userPlayerRespawnNum[usename];
if (tempNum >= RespawnNum)
{
tempHerosNeverDie = false;
}
}
if (self.inventory.GetItemCount(ItemIndex.ExtraLife) > 0)
{
self.inventory.RemoveItem(ItemIndex.ExtraLife, 1);
self.Invoke("RespawnExtraLife", 2f);
self.Invoke("PlayExtraLifeSFX", 1f);
}
else if (tempHerosNeverDie)
{
for (int i = 0; i < RemoveItemNum; i++)
{
RandomRemoveItemOne();
}
userPlayerRespawnNum[usename] += 1;
this.Invoke("RespawnExtraLife", 2f);
self.Invoke("PlayExtraLifeSFX", 1f);
}
else
{
if (self.destroyOnBodyDeath)
{
UnityEngine.Object.Destroy(self.gameObject);
}
self.preventGameOver = false;
FieldInfo field = self.GetType().GetField("preventRespawnUntilNextStageServer", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(self, true);
}
MethodInfo methodInfo = self.GetType().GetMethod("ResetLifeStopwatch", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(self, null);
}
UnityEvent unityEvent = self.onBodyDeath;
if (unityEvent == null)
{
return;
}
unityEvent.Invoke();
}
public void RespawnExtraLife()
{
Chat.AddMessage("Heros Never Die");
characterMaster.Respawn(this.deathFootPosition, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f), false);
characterMaster.GetBody().AddTimedBuff(BuffIndex.Immune, 3f);
GameObject gameObject = Resources.Load<GameObject>("Prefabs/Effects/HippoRezEffect");
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
var prop_bodyInstanceObject = characterMaster.GetType().GetProperty("bodyInstanceObject", flags);
GameObject bodyInstanceObject = prop_bodyInstanceObject.GetValue(characterMaster) as GameObject;
if (bodyInstanceObject != null)
{
foreach (EntityStateMachine entityStateMachine in bodyInstanceObject.GetComponents<EntityStateMachine>())
{
entityStateMachine.initialStateType = entityStateMachine.mainStateType;
}
if (gameObject)
{
EffectManager.instance.SpawnEffect(gameObject, new EffectData
{
origin = this.deathFootPosition,
rotation = bodyInstanceObject.transform.rotation
}, true);
}
}
}
private void RandomRemoveItemOne()
{
List<ItemIndex> list = new List<ItemIndex>();
for (int i = 0; i < itemStacks.Length; i++)
{
int num = itemStacks[i];
if (num > 0)
{
list.Add((ItemIndex)i);
}
}
ItemIndex itemIndex = (list.Count == 0) ? ItemIndex.None : list[GetRandom(0, list.Count)];
characterMaster.inventory.RemoveItem(itemIndex, 1);
ItemDef itemDef = ItemCatalog.GetItemDef(itemIndex);
Chat.AddMessage("Remove One Item:" + Language.GetString(itemDef.nameToken));
itemStacks[(int)itemIndex] -= 1;
}
public int GetRandom(int varStart, int varEnd)
{
System.Random rd = new System.Random();
return rd.Next(varStart, varEnd);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Domain
{
public class DBconn
{
// For local database
String connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog = CardBinder;Integrated Security = True";
LinqToSQLDatacontext db;
private int getCount()
{
db = new LinqToSQLDatacontext(connectionString);
var count = db.cards.Count();
return count;
}
private int getLast()
{
db = new LinqToSQLDatacontext(connectionString);
cardbinder lastEntry = db.cardbinders.Last();
return lastEntry.id;
}
public void createCard(string name, string imagepath, int friendship, int bravery, int humor, int starfactor)
{
db = new LinqToSQLDatacontext(connectionString);
// Create new Card
card newcard = new card();
newcard.name = name;
newcard.serialnumber = getCount()+1;
newcard.imagepath = imagepath;
newcard.friendship = friendship;
newcard.bravery = bravery;
newcard.humor = humor;
newcard.starfactor = starfactor;
// adds new card to database
db.cards.InsertOnSubmit(newcard);
db.SubmitChanges();
}
public void removeCard(int serialNumber)
{
db = new LinqToSQLDatacontext(connectionString);
// Get Card to remove
// Lamda used!!!!!!!!!!!!!!!!!!!!!!!!!
card removeCard = db.cards.FirstOrDefault(e => e.serialnumber.Equals(serialNumber));
// Delete Card
db.cards.DeleteOnSubmit(removeCard);
db.SubmitChanges();
}
public void addCardToUser(string userName, int cardID)
{
db = new LinqToSQLDatacontext(connectionString);
// Create new card in cardbinder
cardbinder newcard = new cardbinder();
newcard.id = getLast();
newcard.userid = userName;
newcard.cardid = cardID;
//add new card til cardbinder table
db.cardbinders.InsertOnSubmit(newcard);
db.SubmitChanges();
}
public void removeCardFromUser(string userName, int serialNumber)
{
db = new LinqToSQLDatacontext(connectionString);
// Get cardbinder and remove card
cardbinder removeCard = db.cardbinders.FirstOrDefault(e => e.cardid.Equals(serialNumber) && e.userid.Equals(userName));
// Delete card
db.cardbinders.DeleteOnSubmit(removeCard);
db.SubmitChanges();
}
public User findUser(string userName)
{
db = new LinqToSQLDatacontext(connectionString);
user u = db.users.FirstOrDefault(e => e.name == userName);
User foundUser = new User(u.name, u.password);
return foundUser;
}
public void deleteUser(string userName)
{
db = new LinqToSQLDatacontext(connectionString);
// Get cardbinder to delete
db.cardbinders.DeleteAllOnSubmit(db.cardbinders.Where(e => e.userid == userName));
db.SubmitChanges();
// Get user to delete
user removeUser = db.users.FirstOrDefault(e => e.name.Equals(userName));
// Delete User
db.users.DeleteOnSubmit(removeUser);
db.SubmitChanges();
}
public void createUser(string userName, string password)
{
db = new LinqToSQLDatacontext(connectionString);
user newUser = new user();
newUser.name = userName;
newUser.password = password;
// Create User
db.users.InsertOnSubmit(newUser);
db.SubmitChanges();
}
public void editUsername(string userName, string newName)
{
db = new LinqToSQLDatacontext(connectionString);
try
{
//Get cardbinder to edit
var binderQuery =
from b in db.cardbinders
where b.userid == userName
select b;
foreach (cardbinder b in binderQuery)
{
// create new cardbinder to replace old
cardbinder binder = new cardbinder();
binder.id = b.id;
binder.cardid = b.cardid;
binder.userid = newName;
db.cardbinders.DeleteOnSubmit(b);
db.cardbinders.InsertOnSubmit(binder);
}
//Get user to edit
var query =
from u in db.users
where u.name == userName
select u;
foreach (user u in query)
{
// create new user and cardbinder to replace old
user uNew = new user();
uNew.name = newName;
uNew.password = u.password;
db.users.DeleteOnSubmit(u);
db.users.InsertOnSubmit(uNew);
}
// Save changes
db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e); ;
}
}
public Binder viewUser(string userName)
{
db = new LinqToSQLDatacontext(connectionString);
// Binder for transerfering data to gui
Binder userBinder = new Binder(userName);
// users information consists of his cardbinder, Linq statement
var query = (from t in db.cardbinders
where t.userid == userName
select t.cardid);
// Adds required cards from db to cardbinders cardlist
foreach (var id in query)
{
var cardQuery = (from c in db.cards
where c.serialnumber == id
select c);
foreach (var e in cardQuery)
{
userBinder.cardList.Add(e);
Console.WriteLine(e.name);
}
}
// returns a binder with username and cardIDs
return userBinder;
}
public List<card> getCards()
{
db = new LinqToSQLDatacontext(connectionString);
List<card> allCards = new List<card>();
var all = db.cards;
foreach (var card in all)
allCards.Add(card);
return allCards;
}
//String connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog = CardBinder;Integrated Security = True";
//LinqToDB db;
//SqlConnection connection;
//public void cardToDB(string name, int serialnumber, string imagepath)
//{
// db = new LinqToDB(connectionString);
// // Create new Card
// card newcard = new card();
// newcard.name = name;
// newcard.serialnumber = serialnumber;
// newcard.imagepath = imagepath;
// // adds new card to database
// db.cards.InsertOnSubmit(newcard);
// db.SubmitChanges();
// using (connection = new SqlConnection(connectionString))
// {
// SqlCommand cmd = new SqlCommand("INSERT INTO card (name, serialnumber, imagepath) Values(@name, @serialnumber, @imagepath)");
// cmd.CommandType = CommandType.Text;
// cmd.Connection = connection;
// cmd.Parameters.AddWithValue("@name", newcard.Name);
// cmd.Parameters.AddWithValue("@serialnumber", newcard.SerialNumber);
// cmd.Parameters.AddWithValue("@imagepath", newcard.ImagePath);
// if (connection.State != ConnectionState.Open)
// { connection.Open(); }
// cmd.ExecuteNonQuery();
// Console.WriteLine("Card Saved!");
// }
//}
//public void removeCard(Card card)
//{
// using (connection = new SqlConnection(connectionString))
// {
// SqlCommand cmd = new SqlCommand("DELETE FROM card WHERE serialnumber = @serialnumber");
// cmd.CommandType = CommandType.Text;
// cmd.Connection = connection;
// cmd.Parameters.AddWithValue("@serialnumber", card.SerialNumber);
// if (connection.State != ConnectionState.Open)
// { connection.Open(); }
// cmd.ExecuteNonQuery();
// Console.WriteLine("Card Deleted!");
// }
//}
//public void addCardToUser(Binder binder, User user, Card card)
//{
// using (connection = new SqlConnection(connectionString))
// {
// SqlCommand cmd = new SqlCommand("INSERT INTO cardbinder(id, userid, cardid) VALUES (@id, @userid, @cardid)");
// cmd.CommandType = CommandType.Text;
// cmd.Connection = connection;
// cmd.Parameters.AddWithValue("@id", binder.binderId);
// cmd.Parameters.AddWithValue("@userid", user.Username);
// cmd.Parameters.AddWithValue("@cardid", card.SerialNumber);
// if (connection.State != ConnectionState.Open)
// { connection.Open(); }
// cmd.ExecuteNonQuery();
// Console.WriteLine("Card Added!");
// }
//}
//public void removeCardFromUser(Binder binder, Card card)
//{
// using (connection = new SqlConnection(connectionString))
// {
// SqlCommand cmd = new SqlCommand("DELETE FROM cardbinder WHERE id = @id AND cardid = @cardid");
// cmd.CommandType = CommandType.Text;
// cmd.Connection = connection;
// cmd.Parameters.AddWithValue("@id", binder.binderId);
// cmd.Parameters.AddWithValue("@cardid", card.SerialNumber);
// if (connection.State != ConnectionState.Open)
// { connection.Open(); }
// cmd.ExecuteNonQuery();
// Console.WriteLine("Card Removed!");
// }
//}
//public void deleteUser(User user)
//{
// using (connection = new SqlConnection(connectionString))
// {
// SqlCommand cmd = new SqlCommand("DELETE FROM [user] WHERE name = @name");
// cmd.CommandType = CommandType.Text;
// cmd.Connection = connection;
// cmd.Parameters.AddWithValue("@name", user.Username);
// if (connection.State != ConnectionState.Open)
// { connection.Open(); }
// cmd.ExecuteNonQuery();
// Console.WriteLine("User Deleted!");
// }
//}
//public void editUsername(User user)
//{
// using (connection = new SqlConnection(connectionString))
// {
// SqlCommand cmd = new SqlCommand("UPDATE [user] SET name = @name2 WHERE name = @name");
// cmd.CommandType = CommandType.Text;
// cmd.Connection = connection;
// // Remember to connect this to a textfield
// cmd.Parameters.AddWithValue("@name2", "someName");
// cmd.Parameters.AddWithValue("@name", user.Username);
// if (connection.State != ConnectionState.Open)
// { connection.Open(); }
// cmd.ExecuteNonQuery();
// Console.WriteLine("Username Altered!");
// }
//}
//public Binder viewUser(User user)
//{
// Binder binder = new Binder(user.Username);
// using (connection = new SqlConnection(connectionString))
// {
// SqlCommand cmd = new SqlCommand("SELECT * FROM cardbinder WHERE userid = @userid");
// cmd.CommandType = CommandType.Text;
// cmd.Connection = connection;
// // Remember to connect this to a textfield
// cmd.Parameters.AddWithValue("@userid", user.Username);
// if (connection.State != ConnectionState.Open)
// { connection.Open(); }
// using (SqlDataReader reader = cmd.ExecuteReader())
// {
// while (reader.Read())
// {
// for (int i = 0; i < reader.FieldCount; i++)
// {
// Console.WriteLine(reader.GetValue(i));
// }
// }
// }
// Console.WriteLine();
// }
// return binder;
//}
//public void addUser()
//{
//}
}
}
|
using AutoMapper;
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Whale.DAL;
using Whale.DAL.Models;
using Whale.DAL.Models.Poll;
using Whale.Shared.Exceptions;
using Whale.Shared.Models.Meeting;
using Whale.Shared.Models.Poll;
using Whale.Shared.Services;
using Whale.Shared.Services.Abstract;
namespace Whale.MeetingAPI.Services
{
public class PollService : BaseService
{
private readonly SignalrService _signalrService;
private readonly RedisService _redisService;
public PollService(
WhaleDbContext context,
IMapper mapper,
SignalrService signalrService,
RedisService redisService)
: base(context, mapper)
{
_signalrService = signalrService;
this._redisService = redisService;
}
public async Task<PollDTO> CreatePollAsync(PollCreateDTO pollCreateDto)
{
_redisService.Connect();
var meetingData = await _redisService.GetAsync<MeetingRedisData>(pollCreateDto.MeetingId.ToString());
if (meetingData is null) throw new NotFoundException(nameof(Meeting));
Poll pollEntity = _mapper.Map<Poll>(pollCreateDto);
pollEntity.Id = Guid.NewGuid();
pollEntity.CreatedAt = DateTimeOffset.Now;
await _redisService.AddToSetAsync<Poll>(pollEntity.MeetingId.ToString() + nameof(Poll), pollEntity);
return _mapper.Map<PollDTO>(pollEntity);
}
public async Task SavePollAnswerAsync(VoteDTO voteDto)
{
_redisService.Connect();
var voteEntity = _mapper.Map<Vote>(voteDto);
string resultSetKey = voteDto.MeetingId + nameof(Poll);
var polls = await _redisService.GetSetMembersAsync<Poll>(resultSetKey);
var poll = polls.FirstOrDefault(poll => poll.Id == voteDto.PollId);
await _redisService.DeleteSetMemberAsync<Poll>(resultSetKey, poll);
// include user's vote in OptionResults
foreach (string choosedOption in voteDto.ChoosedOptions)
{
OptionResult optionResult = poll.OptionResults.FirstOrDefault(optResult => optResult.Option == choosedOption);
optionResult.VotedUserIds = optionResult.VotedUserIds.Append(voteDto.User.Id);
}
if (!poll.IsAnonymous && !poll.VotedUsers.Any(voter => voter.Id == voteDto.User.Id))
{
var voter = _mapper.Map<Voter>(voteDto.User);
poll.VotedUsers = poll.VotedUsers.Append(voter);
}
await _redisService.AddToSetAsync(resultSetKey, poll);
// signal
var connection = await _signalrService.ConnectHubAsync("meeting");
var pollResultDto = _mapper.Map<PollResultDTO>(poll);
await connection.InvokeAsync("OnPollResults", voteDto.MeetingId.ToString(), pollResultDto);
}
public async Task<PollsAndResultsDTO> GetPollsAndResultsAsync(Guid meetingId, Guid userId)
{
_redisService.Connect();
var polls = await _redisService.GetSetMembersAsync<Poll>(meetingId + nameof(Poll));
polls = polls.OrderByDescending(poll => poll.CreatedAt);
var resultsToSend = polls
.Where(poll => poll.OptionResults
.Any(optRes => optRes.VotedUserIds
.Any(id => id == userId)));
var pollsToSend = polls.Except(resultsToSend);
return new PollsAndResultsDTO
{
Polls = _mapper.Map<IEnumerable<PollDTO>>(pollsToSend),
Results = _mapper.Map<IEnumerable<PollResultDTO>>(resultsToSend),
};
}
public async Task DeletePollAsync(string meetingId, string pollId)
{
_redisService.Connect();
string pollsKey = meetingId + nameof(Poll);
var polls = await _redisService.GetSetMembersAsync<Poll>(pollsKey);
var pollToDelete = polls.FirstOrDefault(poll => poll.Id.ToString() == pollId);
await _redisService.DeleteSetMemberAsync(pollsKey, pollToDelete);
// signal
var connection = await _signalrService.ConnectHubAsync("meeting");
await connection.InvokeAsync("OnPollDeleted", meetingId, pollId);
}
public async Task SavePollResultsToDatabaseAndDeleteFromRedisAsync(Guid meetingId)
{
_redisService.Connect();
var polls = await _redisService.GetSetMembersAsync<Poll>(meetingId + nameof(Poll));
await _context.PollResults.AddRangeAsync(polls);
await _context.SaveChangesAsync();
await DeletePollsAndResultsFromRedisAsync(meetingId, polls);
}
public async Task DeletePollsAndResultsFromRedisAsync(Guid meetingId, IEnumerable<Poll> polls)
{
string key = meetingId + nameof(Poll);
foreach (var poll in polls)
{
await _redisService.DeleteSetMemberAsync<Poll>(key, poll);
}
await _redisService.DeleteKeyAsync(meetingId + nameof(Poll));
}
}
}
|
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 AgendaEscolar
{
public partial class Mostrar : Form
{
DataSet dsResultados = new DataSet();
Class_BaseDatos obj_Agenda = new Class_BaseDatos();
public Mostrar()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
DataSet ds;
//seleccioname todo de la tabla clientes donde en la columna nombre cliete pude ser el que yo te mande
string cmd = "Select * FROM AgendaAlumnos WHERE No_Control LIKE ('%" + textBox1.Text + "%')";
ds = obj_Agenda.CargaDatos("Select * FROM AgendaAlumnos WHERE Id_Carrera LIKE ('%" + CarreracomboBox.SelectedValue + "%')");
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception error)
{
MessageBox.Show("Informacion incorrecta" + error);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Mostrar_Load(object sender, EventArgs e)
{
dsResultados = obj_Agenda.CargaDatos("Select * From Cat_Carreras Order By NombreCarrera");
CarreracomboBox.DataSource = dsResultados.Tables["Carreras"];
CarreracomboBox.DisplayMember = dsResultados.Tables["Carreras"].Columns["NombreCarrera"].ToString();
CarreracomboBox.ValueMember = "Id_Carrera";
}
private void button3_Click(object sender, EventArgs e)
{
try
{
DataSet ds;
ds = obj_Agenda.CargaDatos("Select * FROM AgendaAlumnos WHERE No_Control LIKE ('%" + textBox1.Text + "%')");
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception error)
{
MessageBox.Show("Informacion incorrecta" + error);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
DataSet ds;
ds = obj_Agenda.CargaDatos("Select * FROM AgendaAlumnos");
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception error)
{
MessageBox.Show("Informacion incorrecta" + error);
}
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Net;
using System.Text;
namespace Microsoft.Azure.SignalR
{
internal sealed class PreviewServiceEndpointGenerator : IServiceEndpointGenerator
{
private const int ClientPort = 5001;
private const int ServerPort = 5002;
private const string ClientPath = "client";
private const string ServerPath = "server";
public string Endpoint { get; }
public string AccessKey { get; }
public PreviewServiceEndpointGenerator(string endpoint, string accessKey)
{
Endpoint = endpoint;
AccessKey = accessKey;
}
public string GetClientAudience(string hubName) =>
InternalGetEndpoint(ClientPort, ClientPath, hubName);
public string GetClientEndpoint(string hubName, string originalPath, string queryString)
{
var queryBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(originalPath))
{
queryBuilder.Append("&")
.Append(Constants.QueryParameter.OriginalPath)
.Append("=")
.Append(WebUtility.UrlEncode(originalPath));
}
if (!string.IsNullOrEmpty(queryString))
{
queryBuilder.Append("&").Append(queryString);
}
return $"{InternalGetEndpoint(ClientPort, ClientPath, hubName)}{queryBuilder}";
}
public string GetServerAudience(string hubName) =>
InternalGetEndpoint(ServerPort, ServerPath, hubName);
public string GetServerEndpoint(string hubName) =>
InternalGetEndpoint(ServerPort, ServerPath, hubName);
private string InternalGetEndpoint(int port, string path, string hubName) =>
$"{Endpoint}:{port}/{path}/?hub={hubName.ToLower()}";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static NADD.Usuario;
namespace NADD
{
class Program
{
static void Main(string[] args)
{
Area Exatas = new Area(1, "Exatas");
Curso SI = new Curso(1, "Sistemas de Informação", Exatas);
Disciplina POO = new Disciplina(1, "Programação Orientada a Objetos", SI);
Professor Rosen = new Professor(1, "Rosen", "Rosencler@gmail.com", "33201526", "167.128.067.59");
UProfessor roselia = new UProfessor(1,"roro","roro@gmail.com","123@");
UNADD carmem = new UNADD(2,"caca","carminha@gmail.com","amoMeuCachorro@123");
Reitoria japa = new Reitoria(3,"Japa", "japa@unifoa.edu.br", "Hj3$2Kj$%");
Avaliacao av1 = new Avaliacao();
av1.NovaQuestao(10, "discursiva", "péssima!");
av1.NovaQuestao(3, "objetiva", "muito boa mesmo!!!");
av1.NovaQuestao(4, "discursiva", "Topper Quest");
av1.NovaQuestao(5, "objetiva", "muito boa mesmo e reflexiva essa questão");
av1.NovaQuestao(8, "discursiva", "não entendi!");
//Polimorfismo de Sobrescrita
//roselia.cadastrarArea();
//carmem.cadastrarArea();
//japa.cadastrarArea();
//Polimorfismo de Sobrescrita
//Polimorfismo de Sobrecarga
//Console.WriteLine(av1.calculaMediaGeral(5, 75));
//Console.WriteLine(av1.calculaMediaGeral(5, 74.2));
//Polimorfismo de Sobrecarga
// Interface //
//Console.WriteLine(roselia.alertaNovaAvalicao());
//Interface //
Console.WriteLine(Rosen.IdProfessor);
Console.WriteLine("{0} {1}",Exatas.IdArea,Exatas.NomeArea);
Console.WriteLine("{0} {1} {2}",SI.IdArea.IdArea, SI.IdCurso, SI.NomeCurso);
Console.WriteLine("{0} {1} {2}", POO.IdDisciplina, POO.NomeDisciplina, POO.Curso.IdCurso);
Console.WriteLine("{0} {1} {2} {3}",Rosen.IdProfessor, Rosen.EmailProfessor, Rosen.TelProfessor, Rosen.CpfProfessor );
Console.WriteLine(av1.Media);
Console.WriteLine(av1.VetQuest[i].Observacao)
Console.Read();
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
namespace BlazorSignalR.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
using (DB baza = new DB())
{
baza.Database.EnsureCreated();
OtMA a = new OtMA();
OtMB b1 = new OtMB();
OtMB b2 = new OtMB();
a.lista.Add(b1);
a.lista.Add(b2);
baza.OtMAs.Add(a);
baza.OtMBs.Add(b1);
baza.OtMBs.Add(b2);
baza.SaveChanges();
var nesto = baza.OtMBs.First();
Console.WriteLine(nesto.A);
OtOA ooa = new OtOA();
OtOB oob = new OtOB();
ooa.B = oob;
baza.OtOAs.Add(ooa);
baza.OtOBs.Add(oob);
baza.SaveChanges();
MtMA a1mm = new MtMA();
MtMA a2mm = new MtMA();
MtMB b1mm = new MtMB();
MtMB b2mm = new MtMB();
baza.MtMA_Bs.Add(new MtMA_B(a1mm, b1mm));
baza.MtMA_Bs.Add(new MtMA_B(a1mm, b2mm));
baza.MtMA_Bs.Add(new MtMA_B(a2mm, b1mm));
baza.MtMA_Bs.Add(new MtMA_B(a2mm, b2mm));
baza.MtMAs.Add(a1mm);
baza.MtMAs.Add(a2mm);
baza.MtMBs.Add(b1mm);
baza.MtMBs.Add(b2mm);
baza.SaveChanges();
}
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<Hab>("th");
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
}
}
|
using System;
class Program {
public static void Main (string[] args) {
Console.WriteLine ("Insira o tempo em segundos:");
int s = int.Parse(Console.ReadLine());
int horas,minutos,segundos, resto;
horas = s/3600;
resto = s%3600;
minutos = resto/60;
segundos = resto%60;
Console.WriteLine("Hora(s): "+horas+", Minuto(s): "+minutos+", Segundos: "+segundos);
}
}
|
namespace Bindable.Linq.Operators
{
/// <summary>
/// Represents an instance of a case in a switch statement.
/// </summary>
/// <typeparam name="TInput">The type of the input.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
public interface ISwitchCase<TInput, TResult>
{
/// <summary>
/// Evaluates the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns></returns>
bool Evaluate(TInput input);
/// <summary>
/// Returns the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns></returns>
TResult Return(TInput input);
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CIS420Redux.Models;
namespace CIS420Redux.Controllers
{
public class ClincalComplianceController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: ClincalCompliance
public ActionResult Index()
{
var pOS = db.POS.Include(p => p.Student);
return View(db.ClincalCompliances.ToList());
}
// GET: ClincalCompliance/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ClincalCompliance clincalCompliance = db.ClincalCompliances.Find(id);
if (clincalCompliance == null)
{
return HttpNotFound();
}
return View(clincalCompliance);
}
// GET: ClincalCompliance/Create
public ActionResult Create()
{
var types = GetAllTypes();
var compliant = GetCompliantStatus();
var model = new ClincalCompliance();
model.Types = GetSelectListItems(types);
model.CompliantStatus = GetSelectListItems(compliant);
ViewBag.StudentId = new SelectList(db.Students, "Id", "LastName");
return View(model);
}
// POST: ClincalCompliance/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Type,ExpirationDate,StudentId,DocumentId")] ClincalCompliance model)
{
var types = GetAllTypes();
var compliant = GetCompliantStatus();
model.Types = GetSelectListItems(types);
model.CompliantStatus = GetSelectListItems(compliant);
if (ModelState.IsValid)
{
model.ExpirationDate = DateTime.Today;
if (model.ExpirationDate <= DateTime.Today)
{
model.IsExpired = true;
}
else
{
model.IsExpired = false;
}
db.ClincalCompliances.Add(model);
db.SaveChanges();
return RedirectToAction("CCDocuments", "Advisor");
}
ViewBag.StudentId = new SelectList(db.Students, "Id", "LastName", model.StudentId);
return View(model);
}
// GET: ClincalCompliance/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ClincalCompliance clincalcompliances = db.ClincalCompliances.Find(id);
var types = GetAllTypes();
var compliant = GetCompliantStatus();
clincalcompliances.Types = GetSelectListItems(types);
clincalcompliances.CompliantStatus = GetSelectListItems(compliant);
if (clincalcompliances == null)
{
return HttpNotFound();
}
ViewBag.StudentId = new SelectList(db.Students, "Id", "LastName", clincalcompliances.StudentId);
return View(clincalcompliances);
}
// POST: ClincalCompliance/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Type,ExpirationDate,IsCompliant,IsExpired,StudentId,DocumentId")] ClincalCompliance model)
{
var types = GetAllTypes();
var compliant = GetCompliantStatus();
model.Types = GetSelectListItems(types);
model.CompliantStatus = GetSelectListItems(compliant);
if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("CCDocuments", "Advisor");
}
ViewBag.StudentId = new SelectList(db.Students, "Id", "LastName", model.StudentId);
return View(model);
}
// GET: ClincalCompliance/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ClincalCompliance clincalCompliance = db.ClincalCompliances.Find(id);
if (clincalCompliance == null)
{
return HttpNotFound();
}
return View(clincalCompliance);
}
// POST: ClincalCompliance/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ClincalCompliance clincalCompliance = db.ClincalCompliances.Find(id);
db.ClincalCompliances.Remove(clincalCompliance);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
public IEnumerable<string> GetAllTypes()
{
return new List<string>
{
"CPR",
"HIPAA",
"Bloobourne Path.",
"Liability Insurance",
"Immunizations",
"Drug Screening",
"CNA",
};
}
public IEnumerable<string> GetCompliantStatus()
{
return new List<string>
{
"Yes",
"No"
};
}
public IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
{
var selectList = new List<SelectListItem>();
foreach (var element in elements)
{
selectList.Add(new SelectListItem
{
Value = element,
Text = element
});
}
return selectList;
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SoftwareDeveloperIO.Collections.Generic.Test
{
[TestClass]
public class FindTests
{
[TestMethod]
public void Should_ReturnTrue_When_NodeExists()
{
var list = new LinkedList<int>();
list.AddLast(2);
list.AddLast(3);
list.AddLast(5);
list.AddLast(8);
list.AddLast(13);
list.AddLast(21);
list.AddLast(34);
list.AddLast(55);
var node = list.Find(8);
Assert.AreEqual(8, node.Value);
}
[TestMethod]
public void Should_ReturnTrue_When_NodeDontExists()
{
var list = new LinkedList<int>();
list.AddLast(2);
list.AddLast(3);
list.AddLast(5);
list.AddLast(8);
list.AddLast(13);
list.AddLast(21);
list.AddLast(34);
list.AddLast(55);
var node = list.Find(100);
Assert.AreEqual(null, node);
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
#endregion
namespace DotNetNuke.Collections.Internal
{
internal class LockingStrategyFactory
{
public static ILockStrategy Create(LockingStrategy strategy)
{
switch (strategy)
{
case LockingStrategy.ReaderWriter:
return new ReaderWriterLockStrategy();
case LockingStrategy.Exclusive:
return new ExclusiveLockStrategy();
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
|
using System.Web;
namespace app.web.core.aspnet
{
public class ASPHandler : IHttpHandler
{
IProcessRequests front_controller;
ICreateRequests request_factory;
public ASPHandler(IProcessRequests front_controller, ICreateRequests request_factory)
{
this.front_controller = front_controller;
this.request_factory = request_factory;
}
public void ProcessRequest(HttpContext context)
{
front_controller.process(request_factory.create_request_from(context));
}
public bool IsReusable
{
get { return true; }
}
}
} |
using System;
using System.Collections.Generic; //ua für die Liste
using System.Linq; //ua für range
namespace Task2
{
interface IGambling
{
string Name { get; }
void get_instructions();
List<int> generate_rand();
void print_list<T>(IEnumerable<T> list, string heading);
//void check_winnings();
}
class Scratch_card : IGambling
{
private int[] sums = new int[] { 2, 4, 10, 20, 50, 100, 500, 2000, 10000, 100000 };
private int drawing = 9;
//constructor
public Scratch_card(string gname)
{
Name=gname;
}
//getter
public string Name { get; }
public void get_instructions()
{
string output="In the lottery ticket "+ Name +" you will scratch "+ drawing +
" sums. If a specific sum appears 3 time, you have won this sum once.\n";
Console.WriteLine(output);
}
public List<int> generate_rand()
{
var rand = new Random();
List<int> rand_list = new List<int>();
for (int i = 0; i < drawing; i++)
{
var index = rand.Next(0, sums.Length);
rand_list.Add(sums[index]);
}
return rand_list;
}
//ausgeben in 3er Gruppen
public void print_list<T>(IEnumerable<T> list, string heading)
{
Console.Write($"{heading}:\n");
for (var i = 0; i < list.Count(); i++)
{
Console.Write(list.ElementAt(i));
if ((i + 1) % 3 == 0)
{
Console.Write("\n");
}
else { Console.Write("\t"); }
}
Console.WriteLine("\n");
}
}
class Lottery : IGambling
{
//fields
private byte main_balls, bonus_balls;
private byte main_to_draw, bonus_to_draw;
List<string> is_gameday = new List<string>();
private enum daysofweek { Montag = 1, Dienstag, Mittwoch, Donnerstag, Freitag, Samstag, Sonntag }
//constructor
/// <summary>
/// Create a new lottery game
/// </summary>
/// <param name="name">name of lottery game</param>
/// <param name="amnt_main_balls">The total amount of main balls in-game. (It must not be 0)</param>
/// <param name="amnt_bonus_balls">The total amount of bonus balls in-game. (If there are no bonus balls, please enter 0)</param>
/// <param name="main_balls_to_draw">Number of main balls to be drawn. (It must be smaller than the total amount of balls in-game)</param>
/// <param name="bonus_balls_to_draw">Number of bonus balls to be drawn.</param>
public Lottery(string name, byte amnt_main_balls, byte amnt_bonus_balls,
byte main_balls_to_draw, byte bonus_balls_to_draw)
{
//error handling
if (name.Length < 3) throw new ArgumentException("Invalid lottery name");
if (amnt_main_balls == 0 || main_balls_to_draw == 0) throw new ArgumentException("Lottery with no main balls is not allowed");
if (amnt_main_balls <= main_balls_to_draw) throw new ArgumentException("Amount of the main balls to be drawn must not be greater or equal to the total amount of main balls");
if (amnt_bonus_balls > 0 && amnt_bonus_balls <= bonus_balls_to_draw) throw new ArgumentException("Amount of the bonus balls to be drawn must not be greater or equal to the total amount of main balls");
//assignments
Name = name;
main_balls = amnt_main_balls;
bonus_balls = amnt_bonus_balls;
main_to_draw = main_balls_to_draw;
bonus_to_draw = bonus_balls_to_draw;
}
//properties: getter
public List<string> gamedays { get { return is_gameday; } }
public string Name { get; }
//functions
Func<List<int>, byte, byte, List<int>> iter = iterate;
//methods
private string day_to_str(int day)
{
return Enum.GetName(typeof(daysofweek), day);
}
/// <summary>
/// Assign a lottery game a day/days, when the balls are drawn
/// </summary>
/// <param name="values">Montag=1, Sonntag=7</param>
public List<string> set_gamedays(params int[] values)
{
for (int i = 0; i < values.Length; i++)
{
if (!Enumerable.Range(1, 7).Contains(values[i]))
{
throw new ArgumentOutOfRangeException("The value should be between 1 (Monday) and 7 (Sunday)");
}
is_gameday.Add(day_to_str(values[i]));
}
is_gameday.Sort();
return is_gameday;
}
/// <summary>
/// Print the days to the console on which a game takes place
/// </summary>
public void print()
{
Console.WriteLine($"Spieltage {Name}:");
foreach (var gd in gamedays)
{
Console.WriteLine(gd);
}
Console.WriteLine("\n");
}
/// <summary>
/// How a game is played?
/// </summary>
/// <returns></returns>
public void get_instructions()
{
string is_bonus = "";
switch (bonus_to_draw)
{
case 0:
is_bonus = " There are no bonus numbers.";
break;
case 1:
is_bonus = " There is also a pool with bonus numbers between 1 and " + bonus_balls +
" from that only one ball will be drawn.";
break;
default:
is_bonus = " There is also a pool with bonus numbers between 1 and " + bonus_balls +
" from that exactly " + bonus_to_draw + " balls will be drawn";
break;
}
string output= Name + " is a game of chance where " + main_to_draw +
" numbers in range of 1 to " + main_balls + " will be drawn." +
is_bonus + ".\n";
Console.WriteLine(output);
}
public static List<int> iterate(List<int> number_list, byte total, byte draw)
{
Random rd = new Random();
for (uint i = 1; i <= draw; i++)
{
int rand_nr = (int)rd.Next(1, total);
while (number_list.Contains(rand_nr))
{
rand_nr = (int)rd.Next(1, total);
}
number_list.Add(rand_nr);
}
number_list.Sort(number_list.Count-draw, draw, Comparer<int>.Default);
return number_list;
}
/// <summary>
/// generate random numbers for a game (quick tip)
/// </summary>
/// <returns></returns>
public List<int> generate_rand()
{
List<int> number_list = new List<int>();
iter(number_list, main_balls, main_to_draw);
iter(number_list, bonus_balls, bonus_to_draw);
return number_list;
}
public void print_list<T>(IEnumerable<T> list, string heading)
{
foreach (var item in list)
{
Console.Write($"{item} \t"); // Replace this with your version of printing
}
Console.WriteLine("\n");
}
}
}
|
namespace SoSmartTv.TheMovieDatabaseApi.JsonConverters
{
public class NameJsonConverter : AbstractJsonConverter<string>
{
public override string PropertyPath => "name";
public override object ConvertResult(string value)
{
return value;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlServerDocumentator;
using SqlServerDocumentator.DocumentedDatabaseObjects;
namespace WebSqlServerDocumentator.Controllers.api
{
public class TableController : Controller
{
private IDocumentator _documentator;
public TableController(IDocumentator documentator)
{
this._documentator = documentator;
}
[Route("/api/servers/{serverName}/databases/{databaseName}/tables")]
public IActionResult GetAction(string serverName, string databaseName)
{
return Ok(this._documentator.GetTables(serverName, databaseName));
}
[Route("/api/servers/{serverName}/databases/{databaseName}/tables/{tableName}")]
public IActionResult GetAction(string serverName, string databaseName, string tableName)
{
return Ok(this._documentator.GetTable(serverName, databaseName, "dbo", tableName));
}
[Route("/api/servers/{serverName}/databases/{databaseName}/tables/{schema}.{tableName}")]
public IActionResult GetAction(string serverName, string databaseName, string schema, string tableName)
{
return Ok(this._documentator.GetTable(serverName, databaseName, schema, tableName));
}
[Route("/api/servers/{serverName}/databases/{databaseName}/tables/{tableName}")]
[HttpPut]
public IActionResult PutAction(string serverName, string databaseName, string tableName, [FromBody] DocumentedTable table)
{
if (!serverName.Equals(table.ServerName) ||
!databaseName.Equals(table.DatabaseName) ||
!"dbo".Equals(table.Schema) ||
!tableName.Equals(table.Name))
return BadRequest("Exist a mismatch between the url and json data.");
return Ok(this._documentator.SaveTable(table));
}
[Route("/api/servers/{serverName}/databases/{databaseName}/tables/{schema}.{tableName}")]
[HttpPut]
public IActionResult PutAction(string serverName, string databaseName, string schema, string tableName, [FromBody] DocumentedTable table)
{
if (!serverName.Equals(table.ServerName) ||
!databaseName.Equals(table.DatabaseName) ||
!schema.Equals(table.Schema) ||
!tableName.Equals(table.Name))
return BadRequest("Exist a mismatch between the url and json data.");
return Ok(this._documentator.SaveTable(table));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace FinanceApp
{
public partial class ContactView : Form
{
public ContactView()
{
InitializeComponent();
}
public Contact ContactEntry { get; set; }
private void SaveContact(object sender, EventArgs e)
{
this.ContactEntry = new Contact();
this.ContactEntry.firstName = this.txtFirstname.Text;
this.ContactEntry.lastName = this.txtLastname.Text;
this.ContactEntry.email = this.txtEmail.Text;
this.ContactEntry.telNo = this.txtTel.Text;
//Store: Temp store before pushing data cross-app-domain
String workingDir = Directory.GetCurrentDirectory();
XmlTextWriter textWriter = new XmlTextWriter("myContatc.xml", null);
textWriter.Formatting = Formatting.Indented;
textWriter.Indentation = 4;
textWriter.WriteStartDocument();
textWriter.WriteStartElement("Contact");
textWriter.WriteStartElement("Firstname");
textWriter.WriteString(this.ContactEntry.firstName);
textWriter.WriteEndElement();
textWriter.WriteStartElement("Lastname");
textWriter.WriteValue(this.ContactEntry.lastName);
textWriter.WriteEndElement();
textWriter.WriteStartElement("Email");
textWriter.WriteValue(this.ContactEntry.email);
textWriter.WriteEndElement();
textWriter.WriteStartElement("TelNo");
textWriter.WriteValue(this.ContactEntry.telNo);
textWriter.WriteEndElement();
textWriter.WriteEndElement();
textWriter.WriteEndDocument();
textWriter.Close();
Console.ReadLine();
this.Close();
}
}
}
|
using RestauranteHotel.Domain.Base;
using RestauranteHotel.Domain.Entity;
namespace RestauranteHotel.Domain.Contracts
{
public interface IProductoCompuestoRepository : IGenericRepository<ProductoCompuesto>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SecondProject.Controllers.Services.Model.Domain.DTOs
{
public class ApplicationResult
{
public ScopeName ScopeName { get; set; }
public IsCore IsCore { get; set; }
public ApplicationResult()
{
ScopeName = new ScopeName();
IsCore = new IsCore();
}
}
}
|
// Accord Machine Learning Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.MachineLearning
{
using System;
using System.Collections.Generic;
using System.Linq;
using Accord.Math;
using Accord.Statistics;
/// <summary>
/// Fitting function delegate.
/// </summary>
///
public delegate SplitSetStatistics<TModel> SplitValidationFittingFunction<TModel>(int[] trainingSamples)
where TModel : class;
/// <summary>
/// Evaluating function delegate.
/// </summary>
///
public delegate SplitSetStatistics<TModel> SplitValidationEvaluateFunction<TModel>(int[] validationSamples, TModel model)
where TModel : class;
/// <summary>
/// Split-Set Validation.
/// </summary>
///
/// <typeparam name="TModel">The type of the model being analyzed.</typeparam>
///
/// <seealso cref="Bootstrap"/>
/// <seealso cref="CrossValidation{T}"/>
/// <seealso cref="SplitSetValidation"/>
///
[Serializable]
public class SplitSetValidation<TModel> where TModel : class
{
/// <summary>
/// Gets the group labels assigned to each of the data samples.
/// </summary>
///
public int[] Indices { get; private set; }
/// <summary>
/// Gets the desired proportion of cases in
/// the training set in comparison to the
/// testing set.
/// </summary>
///
public double Proportion { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the prevalence of
/// an output label should be balanced between training and
/// testing sets.
/// </summary>
///
/// <value>
/// <c>true</c> if this instance is stratified; otherwise, <c>false</c>.
/// </value>
///
public bool IsStratified { get; private set; }
/// <summary>
/// Gets the indices of elements in the validation set.
/// </summary>
///
public int[] ValidationSet { get; private set; }
/// <summary>
/// Gets the indices of elements in the training set.
/// </summary>
///
public int[] TrainingSet { get; private set; }
[NonSerialized]
SplitValidationFittingFunction<TModel> fitting;
[NonSerialized]
SplitValidationEvaluateFunction<TModel> estimation;
/// <summary>
/// Get or sets the model fitting function.
/// </summary>
///
public SplitValidationFittingFunction<TModel> Fitting
{
get { return fitting; }
set { fitting = value; }
}
/// <summary>
/// Gets or sets the performance estimation function.
/// </summary>
///
public SplitValidationEvaluateFunction<TModel> Evaluation
{
get { return estimation; }
set { estimation = value; }
}
/// <summary>
/// Creates a new split-set validation algorithm.
/// </summary>
///
/// <param name="size">The total number of available samples.</param>
/// <param name="proportion">The desired proportion of samples in the training
/// set in comparison with the testing set.</param>
///
public SplitSetValidation(int size, double proportion)
{
this.Proportion = proportion;
this.IsStratified = false;
this.Indices = Categorical.Random(size, proportion);
this.ValidationSet = Indices.Find(x => x == 0);
this.TrainingSet = Indices.Find(x => x == 1);
}
/// <summary>
/// Creates a new split-set validation algorithm.
/// </summary>
///
/// <param name="size">The total number of available samples.</param>
/// <param name="proportion">The desired proportion of samples in the training
/// set in comparison with the testing set.</param>
/// <param name="outputs">The output labels to be balanced between the sets.</param>
///
public SplitSetValidation(int size, double proportion, int[] outputs)
{
if (outputs.Length != size)
throw new DimensionMismatchException("outputs");
this.IsStratified = true;
this.Proportion = proportion;
int negative = outputs.Min();
int positive = outputs.Max();
var negativeIndices = outputs.Find(x => x == negative).ToList();
var positiveIndices = outputs.Find(x => x == positive).ToList();
int positiveCount = positiveIndices.Count;
int negativeCount = negativeIndices.Count;
int firstGroupPositives = (int)((positiveCount / 2.0) * proportion);
int firstGroupNegatives = (int)((negativeCount / 2.0) * proportion);
List<int> training = new List<int>();
List<int> testing = new List<int>();
// Put positives and negatives into training
for (int j = 0; j < firstGroupNegatives; j++)
{
training.Add(negativeIndices[0]);
negativeIndices.RemoveAt(0);
}
for (int j = 0; j < firstGroupPositives; j++)
{
training.Add(positiveIndices[0]);
positiveIndices.RemoveAt(0);
}
testing.AddRange(negativeIndices);
testing.AddRange(positiveIndices);
this.TrainingSet = training.ToArray();
this.ValidationSet = testing.ToArray();
}
/// <summary>
/// Computes the split-set validation algorithm.
/// </summary>
///
public SplitSetResult<TModel> Compute()
{
if (Fitting == null)
throw new InvalidOperationException("Fitting function must have been previously defined.");
// Fit and evaluate the model
SplitSetStatistics<TModel> training = fitting(TrainingSet);
SplitSetStatistics<TModel> testing = estimation(ValidationSet, training.Model);
// Return validation statistics
return new SplitSetResult<TModel>(this, training, testing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IoCContainer.ValueObjects
{
//tells the container that the type has other types injected, so they need to be resolved before
[AttributeUsage(AttributeTargets.Constructor, Inherited = false)]
public class DependencyAttribute : Attribute
{
}
}
|
using System;
using System.Net;
using System.Data;
using System.Linq;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNet.OData.Query;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace CryptobotUi.Controllers.Cryptodb
{
using Models;
using Data;
using Models.Cryptodb;
[ODataRoutePrefix("odata/cryptodb/Signals")]
[Route("mvc/odata/cryptodb/Signals")]
public partial class SignalsController : ODataController
{
private Data.CryptodbContext context;
public SignalsController(Data.CryptodbContext context)
{
this.context = context;
}
// GET /odata/Cryptodb/Signals
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
[HttpGet]
public IEnumerable<Models.Cryptodb.Signal> GetSignals()
{
var items = this.context.Signals.AsQueryable<Models.Cryptodb.Signal>();
this.OnSignalsRead(ref items);
return items;
}
partial void OnSignalsRead(ref IQueryable<Models.Cryptodb.Signal> items);
partial void OnSignalGet(ref SingleResult<Models.Cryptodb.Signal> item);
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
[HttpGet("{signal_id}")]
public SingleResult<Signal> GetSignal(Int64 key)
{
var items = this.context.Signals.Where(i=>i.signal_id == key);
var result = SingleResult.Create(items);
OnSignalGet(ref result);
return result;
}
partial void OnSignalDeleted(Models.Cryptodb.Signal item);
partial void OnAfterSignalDeleted(Models.Cryptodb.Signal item);
[HttpDelete("{signal_id}")]
public IActionResult DeleteSignal(Int64 key)
{
try
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var items = this.context.Signals
.Where(i => i.signal_id == key)
.Include(i => i.SignalCommands)
.AsQueryable();
items = EntityPatch.ApplyTo<Models.Cryptodb.Signal>(Request, items);
var item = items.FirstOrDefault();
if (item == null)
{
return StatusCode((int)HttpStatusCode.PreconditionFailed);
}
this.OnSignalDeleted(item);
this.context.Signals.Remove(item);
this.context.SaveChanges();
this.OnAfterSignalDeleted(item);
return new NoContentResult();
}
catch(Exception ex)
{
ModelState.AddModelError("", ex.Message);
return BadRequest(ModelState);
}
}
partial void OnSignalUpdated(Models.Cryptodb.Signal item);
partial void OnAfterSignalUpdated(Models.Cryptodb.Signal item);
[HttpPut("{signal_id}")]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
public IActionResult PutSignal(Int64 key, [FromBody]Models.Cryptodb.Signal newItem)
{
try
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var items = this.context.Signals
.Where(i => i.signal_id == key)
.Include(i => i.SignalCommands)
.AsQueryable();
items = EntityPatch.ApplyTo<Models.Cryptodb.Signal>(Request, items);
var item = items.FirstOrDefault();
if (item == null)
{
return StatusCode((int)HttpStatusCode.PreconditionFailed);
}
this.OnSignalUpdated(newItem);
this.context.Signals.Update(newItem);
this.context.SaveChanges();
var itemToReturn = this.context.Signals.Where(i => i.signal_id == key);
Request.QueryString = Request.QueryString.Add("$expand", "Exchange,Strategy");
this.OnAfterSignalUpdated(newItem);
return new ObjectResult(SingleResult.Create(itemToReturn));
}
catch(Exception ex)
{
ModelState.AddModelError("", ex.Message);
return BadRequest(ModelState);
}
}
[HttpPatch("{signal_id}")]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
public IActionResult PatchSignal(Int64 key, [FromBody]Delta<Models.Cryptodb.Signal> patch)
{
try
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var items = this.context.Signals.Where(i => i.signal_id == key);
items = EntityPatch.ApplyTo<Models.Cryptodb.Signal>(Request, items);
var item = items.FirstOrDefault();
if (item == null)
{
return StatusCode((int)HttpStatusCode.PreconditionFailed);
}
patch.Patch(item);
this.OnSignalUpdated(item);
this.context.Signals.Update(item);
this.context.SaveChanges();
var itemToReturn = this.context.Signals.Where(i => i.signal_id == key);
Request.QueryString = Request.QueryString.Add("$expand", "Exchange,Strategy");
return new ObjectResult(SingleResult.Create(itemToReturn));
}
catch(Exception ex)
{
ModelState.AddModelError("", ex.Message);
return BadRequest(ModelState);
}
}
partial void OnSignalCreated(Models.Cryptodb.Signal item);
partial void OnAfterSignalCreated(Models.Cryptodb.Signal item);
[HttpPost]
[EnableQuery(MaxExpansionDepth=10,MaxAnyAllExpressionDepth=10,MaxNodeCount=1000)]
public IActionResult Post([FromBody] Models.Cryptodb.Signal item)
{
try
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (item == null)
{
return BadRequest();
}
this.OnSignalCreated(item);
this.context.Signals.Add(item);
this.context.SaveChanges();
var key = item.signal_id;
var itemToReturn = this.context.Signals.Where(i => i.signal_id == key);
Request.QueryString = Request.QueryString.Add("$expand", "Exchange,Strategy");
this.OnAfterSignalCreated(item);
return new ObjectResult(SingleResult.Create(itemToReturn))
{
StatusCode = 201
};
}
catch(Exception ex)
{
ModelState.AddModelError("", ex.Message);
return BadRequest(ModelState);
}
}
}
}
|
/*
* Copyright 2019 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Flora License, Version 1.1 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://floralicense.org/license
*
* 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.Runtime.CompilerServices;
using Ultraviolet.Enums;
using Xamarin.Forms;
namespace Ultraviolet.Tizen.Wearable.Behaviors
{
/// <summary>
/// Class that provides functionality for uv level indicator image.
/// </summary>
public class IndicatorBehavior : Behavior<Image>
{
/// <summary>
/// Field with animation length.
/// </summary>
private const uint AnimationLength = 800;
/// <summary>
/// Field with animation starting point value.
/// </summary>
private const int AnimationStartPoint = 0;
/// <summary>
/// Field with animation ending point value.
/// </summary>
private const int AnimationEndPoint = 10;
/// <summary>
/// Field with beginning point on animation timeline.
/// </summary>
private const double AnimationBeginning = 0;
/// <summary>
/// Field with midpoint on animation timeline.
/// </summary>
private const double AnimationMidpoint = 0.5;
/// <summary>
/// Field with finish point on animation timeline.
/// </summary>
private const double AnimationFinish = 1;
/// <summary>
/// Field with change animation length.
/// </summary>
private const uint AnimationChangeLength = 1000;
/// <summary>
/// Field with change animation starting point value.
/// </summary>
private const int AnimationShowPoint = 0;
/// <summary>
/// Field with change animation ending point value.
/// </summary>
private const int AnimationHidePoint = 300;
/// <summary>
/// Field with image to animate.
/// </summary>
private Image _image;
/// <summary>
/// Bindable property definition for uv level.
/// </summary>
public static readonly BindableProperty LevelProperty = BindableProperty.Create(
nameof(Level),
typeof(UvLevel),
typeof(IndicatorBehavior),
UvLevel.None);
/// <summary>
/// Enum representing uv level.
/// </summary>
public UvLevel Level
{
get => (UvLevel)GetValue(LevelProperty);
set => SetValue(LevelProperty, value);
}
/// <summary>
/// Bindable property definition for image source.
/// </summary>
public static readonly BindableProperty ImageSourceProperty = BindableProperty.Create(
nameof(ImageSource),
typeof(ImageSource),
typeof(IndicatorBehavior),
null);
/// <summary>
/// Source of the image indicating uv level.
/// </summary>
public ImageSource ImageSource
{
get => (ImageSource)GetValue(ImageSourceProperty);
set => SetValue(ImageSourceProperty, value);
}
/// <summary>
/// Overridden OnPropertyChanged method which refreshes properties values.
/// </summary>
/// <param name="propertyName">Name of property which changes.</param>
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (propertyName == LevelProperty.PropertyName && Level != UvLevel.None)
{
AnimateChange();
}
base.OnPropertyChanged(propertyName);
}
/// <summary>
/// Overriden OnAttachedTo method which sets BindingContext of behavior.
/// </summary>
/// <param name="bindable">Bindable object.</param>
protected override void OnAttachedTo(Image bindable)
{
BindingContext = bindable;
_image = bindable;
AnimateChange();
base.OnAttachedTo(bindable);
}
/// <summary>
/// Animates indicator, moving it up and down.
/// </summary>
private void AnimateUpDown()
{
if (_image != null)
{
var animationUp = new Animation(c => _image.TranslationY = c,
AnimationStartPoint, AnimationEndPoint, Easing.SinInOut);
var animationDown = new Animation(c => _image.TranslationY = c,
AnimationEndPoint, AnimationStartPoint, Easing.SinInOut);
var animation = new Animation();
animation.Add(AnimationBeginning, AnimationMidpoint, animationUp);
animation.Add(AnimationMidpoint, AnimationFinish, animationDown);
animation.Commit(_image, nameof(AnimateUpDown), repeat: () => true, length: AnimationLength);
}
}
/// <summary>
/// Animates change of indicator.
/// </summary>
private void AnimateChange()
{
_image?.AbortAnimation(nameof(AnimateUpDown));
if (_image != null)
{
var animationHide = new Animation(c => _image.TranslationY = c,
AnimationShowPoint, AnimationHidePoint, Easing.SinInOut,
finished: () => ImageSource = $"images/indicators/{Level.GetFilename()}");
var animationShow = new Animation(c => _image.TranslationY = c,
AnimationHidePoint, AnimationShowPoint, Easing.SinInOut,
finished: () => AnimateUpDown());
var animationChange = new Animation();
animationChange.Add(AnimationBeginning, AnimationMidpoint, animationHide);
animationChange.Add(AnimationMidpoint, AnimationFinish, animationShow);
animationChange.Commit(_image, nameof(AnimateChange), repeat: () => false,
length: AnimationChangeLength);
}
}
}
} |
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Webcorp.Model.Quotation
{
public class Fournisseur:Entity
{
[BsonId(IdGenerator = typeof(EntityIdGenerator))]
public override string Id { get; set; }
public string Nom { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Kers.Models.Repositories;
using System.Threading.Tasks;
using Kers.Models;
using Kers.Models.Data;
using Kers.Models.Contexts;
using Kers.Models.Abstract;
using Kers.Models.Entities.KERScore;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Kers.Models.Entities;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using Kers.Models.ViewModels;
using System.Text.RegularExpressions;
namespace Kers.Models.Repositories
{
public class ActivityRepository : EntityBaseRepository<Activity>, IActivityRepository
{
private KERScoreContext coreContext;
private IDistributedCache _cache;
const int workDaysPerYear = 228;
public ActivityRepository(
IDistributedCache _cache,
KERScoreContext context
) : base(context)
{
this.coreContext = context;
this._cache = _cache;
}
public async Task<List<ProgramDataViewModel>> TopProgramsPerMonth(int year = 0, int month = 0, int amount = 5, int PlanningUnitId = 0, bool refreshCache = false){
List<ProgramDataViewModel> data;
// If no month or year is provided, get the last month
if( year == 0 || month == 0){
var currentDate = DateTime.Now;
month = currentDate.Month;
if( month == 1 ){
year = currentDate.Year - 1;
month = 12;
}else{
year = currentDate.Year;
month = currentDate.Month - 1;
}
}
/*
var cacheKey = CacheKeys.StatsPerMonth + month.ToString() + year.ToString() + PlanningUnitId.ToString() + MajorProgramId.ToString();
var cachedStats = _cache.GetString(cacheKey);
StatsViewModel stats;
if (!string.IsNullOrEmpty(cachedStats) && !refreshCache){
stats = JsonConvert.DeserializeObject<StatsViewModel>(cachedStats);
}else{
*/
var firstDay = new DateTime( year, month, 1, 0, 0, 0);
var lastDay = new DateTime( year, month, DateTime.DaysInMonth(year, month), 23, 59, 59);
var activities = this.coreContext.Activity.Where( a => a.ActivityDate > firstDay && a.ActivityDate < lastDay );
if( PlanningUnitId != 0) {
activities = activities.Where( a => a.PlanningUnitId == PlanningUnitId );
}
// Exclude Administrative Functions and PSD programs
activities = activities.Where( a => a.MajorProgram.Name != "Administrative Functions" && a.MajorProgram.Name != "Staff Development");
data = await activities.GroupBy( a => a.MajorProgram )
.Select( g => new ProgramDataViewModel {
Program = g.Key,
DirectContacts = g.Sum( a => a.Audience ),
Hours = g.Sum( a => a.Hours )
})
.OrderByDescending( g => g.DirectContacts )
.Take( amount )
.ToListAsync();
return data;
}
public async Task<List<ProgramDataViewModel>> TopProgramsPerFiscalYear(FiscalYear FiscalYear, int amount = 5, int PlanningUnitId = 0, bool refreshCache = false){
List<ProgramDataViewModel> data;
var cacheKey = CacheKeys.TopProgramsPerFiscalYear + FiscalYear.Name;
var cachedStats = _cache.GetString(cacheKey);
if (!string.IsNullOrEmpty(cachedStats) && !refreshCache){
data = JsonConvert.DeserializeObject<List<ProgramDataViewModel>>(cachedStats);
}else{
var activities = this.coreContext.Activity.Where( a => a.ActivityDate > FiscalYear.Start && a.ActivityDate < FiscalYear.End );
if( PlanningUnitId != 0) {
activities = activities.Where( a => a.PlanningUnitId == PlanningUnitId );
}
// Exclude Administrative Functions and PSD programs
var activitiesList = await activities.Where( a => a.MajorProgram.Name != "Administrative Functions" && a.MajorProgram.Name != "Staff Development").Include(a => a.MajorProgram).ToListAsync();
data = activitiesList.GroupBy( a => a.MajorProgram )
.Select( g => new ProgramDataViewModel {
Program = g.Key,
DirectContacts = g.Sum( a => a.Audience ),
Hours = g.Sum( a => a.Hours )
})
.OrderByDescending( g => g.DirectContacts )
.Take( amount )
.ToList();
var serialized = JsonConvert.SerializeObject(data);
var keepCacheInDays = 3;
if( FiscalYear.End < DateTime.Now ){
keepCacheInDays = 200;
}
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(keepCacheInDays)
});
}
return data;
}
public List<int> LastActivityRevisionIds( FiscalYear fiscalYear, IDistributedCache _cache){
var cacheKey = "ActivityLastRevisionIdsPerFiscalYear" + fiscalYear.Name;
var cacheString = _cache.GetString(cacheKey);
List<int> ids;
if (!string.IsNullOrEmpty(cacheString)){
ids = JsonConvert.DeserializeObject<List<int>>(cacheString);
}else{
ids = new List<int>();
ids = coreContext.Activity.
Where(r => r.ActivityDate > fiscalYear.Start && r.ActivityDate < fiscalYear.End).
Select( r => r.LastRevisionId).ToList();
/*
var activities = coreContext.Activity.
Where(r => r.ActivityDate > fiscalYear.Start && r.ActivityDate < fiscalYear.End)
.Include( r => r.Revisions);
foreach( var actvt in activities){
var rev = actvt.Revisions.OrderBy( r => r.Created );
var last = rev.Last();
ids.Add(last.Id);
}
*/
var serialized = JsonConvert.SerializeObject(ids);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1)
});
}
return ids;
}
public List<ActivityRevision> PerMonth(KersUser user, int year, int month, string order = "desc"){
IOrderedQueryable<Activity> lastActivities;
if(order == "desc"){
lastActivities = coreContext.Activity.
Where(e=>e.KersUser == user && e.ActivityDate.Month == month && e.ActivityDate.Year == year).
Include( e => e.ActivityImages).
Include(e=>e.LastRevision).ThenInclude(r => r.MajorProgram).
Include(e=>e.LastRevision).ThenInclude(r => r.ActivityOptionSelections).ThenInclude(s => s.ActivityOption).
Include(e=>e.LastRevision).ThenInclude(r => r.ActivityOptionNumbers).ThenInclude(s => s.ActivityOptionNumber).
Include(e=>e.LastRevision).ThenInclude(r => r.RaceEthnicityValues).
AsSplitQuery().
OrderByDescending(e=>e.ActivityDate);
}else{
lastActivities = coreContext.Activity.
Where(e=>e.KersUser == user && e.ActivityDate.Month == month && e.ActivityDate.Year == year).
Include( e => e.ActivityImages).
Include(e=>e.LastRevision).ThenInclude(r => r.MajorProgram).
Include(e=>e.LastRevision).ThenInclude(r => r.ActivityOptionSelections).ThenInclude(s => s.ActivityOption).
Include(e=>e.LastRevision).ThenInclude(r => r.ActivityOptionNumbers).ThenInclude(s => s.ActivityOptionNumber).
Include(e=>e.LastRevision).ThenInclude(r => r.RaceEthnicityValues).
AsSplitQuery().
OrderBy(e=>e.ActivityDate);
}
foreach( var act in lastActivities) act.LastRevision.ActivityImages = act.ActivityImages;
var revs = lastActivities.Select( a => a.LastRevision);
/* if( lastActivities != null){
foreach(var activity in lastActivities){
if(activity.Revisions.Count != 0){
var last = activity.Revisions.OrderBy(r=>r.Created).Last();
last.ActivityImages = activity.ActivityImages;
revs.Add(last);
}
}
}*/
return revs.ToList();
}
public TableViewModel ReportsStateAll(FiscalYear fiscalYear, bool refreshCache = false){
var cacheKey = CacheKeys.StateAllContactsData + fiscalYear.Name;
var cachedTypes = _cache.GetString(cacheKey);
TableViewModel table;
if (!string.IsNullOrEmpty(cachedTypes) && !refreshCache){
table = JsonConvert.DeserializeObject<TableViewModel>(cachedTypes);
}else{
var actvtsCacheKey = CacheKeys.AllActivitiesByPlanningUnit + fiscalYear.Name;
var cachedActivities = _cache.GetString(actvtsCacheKey);
List<ActivityUnitResult> activities;
if (!string.IsNullOrEmpty(cachedActivities)){
activities = JsonConvert.DeserializeObject<List<ActivityUnitResult>>(cachedActivities);
}else{
activities = coreContext.Activity
.Where( a => a.ActivityDate < fiscalYear.End && a.ActivityDate > fiscalYear.Start)
.GroupBy(e => new {
Unit = e.PlanningUnit
})
.Select(c => new ActivityUnitResult{
Ids = c.Select(
s => s.Id
).ToList(),
Hours = c.Sum(s => s.Hours),
Audience = c.Sum(s => s.Audience),
Unit = c.Key.Unit
})
.ToList();
foreach( var activity in activities){
var males = 0;
var females = 0;
foreach( var perUserId in activity.Ids ){
var last = coreContext.ActivityRevision.Where( a => a.ActivityId == perUserId ).OrderBy( a => a.Created ).Last();
males += last.Male;
females += last.Female;
}
activity.Male = males;
activity.Female = females;
}
var serializedActivities = JsonConvert.SerializeObject(activities);
_cache.SetString(actvtsCacheKey, serializedActivities, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(2)
});
}
var result = ProcessUnitActivities( activities, _cache);
var contactsCacheKey = CacheKeys.AllContactsByPlanningUnit + fiscalYear.Name;
var cachedContacts = _cache.GetString(contactsCacheKey);
List<ContactUnitResult> contacts;
if (!string.IsNullOrEmpty(cachedContacts)){
contacts = JsonConvert.DeserializeObject<List<ContactUnitResult>>(cachedContacts);
}else{
contacts = coreContext.Contact.
Where( c =>
c.ContactDate < fiscalYear.End
&&
c.ContactDate > fiscalYear.Start
&&
c.PlanningUnit != null
)
.GroupBy(e => new {
Unit = e.PlanningUnit
})
.Select(c => new ContactUnitResult{
Ids = c.Select(
s => s.Id
).ToList(),
Unit = c.Key.Unit
})
.ToList();
var serializedContacts = JsonConvert.SerializeObject(contacts);
_cache.SetString(contactsCacheKey, serializedContacts, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(2)
});
}
result = ProcessUnitContacts( contacts, result);
result = result.OrderBy( r => r.PlanningUnit.order).ToList();
table = new TableViewModel();
table.Header = new List<string>{
"Planning Unit", "Days", "Multistate", "Total Contacts"
};
var Races = coreContext.Race.OrderBy(r => r.Order);
var Ethnicities = coreContext.Ethnicity.OrderBy( e => e.Order);
var OptionNumbers = coreContext.ActivityOptionNumber.OrderBy( n => n.Order);
foreach( var race in Races){
table.Header.Add(race.Name);
}
foreach( var ethn in Ethnicities){
table.Header.Add(ethn.Name);
}
table.Header.Add("Males");
table.Header.Add("Females");
foreach( var opnmb in OptionNumbers){
table.Header.Add(opnmb.Name);
}
var Rows = new List<List<string>>();
float TotalHours = 0;
float TotalMultistate = 0;
int TotalAudience = 0;
int ToatalMales = 0;
int TotalFemales = 0;
int[] totalPerRace = new int[Races.Count()];
int[] totalPerEthnicity = new int[Ethnicities.Count()];
int[] totalPerOptionNumber = new int[OptionNumbers.Count()];
int i = 0;
foreach(var res in result){
TotalHours += res.Hours;
TotalAudience += res.Audience;
ToatalMales += res.Male;
TotalFemales += res.Female;
TotalMultistate += res.Multistate;
var Row = new List<string>();
Row.Add(res.PlanningUnit.Name);
Row.Add((res.Hours / 8).ToString());
Row.Add((res.Multistate / 8).ToString());
Row.Add(res.Audience.ToString());
i = 0;
foreach( var race in Races){
var raceAmount = res.RaceEthnicityValues.Where( v => v.RaceId == race.Id).Sum( r => r.Amount);
Row.Add(raceAmount.ToString());
totalPerRace[i] += raceAmount;
i++;
}
i=0;
foreach( var et in Ethnicities){
var ethnAmount = res.RaceEthnicityValues.Where( v => v.EthnicityId == et.Id).Sum( r => r.Amount);
Row.Add(ethnAmount.ToString());
totalPerEthnicity[i] += ethnAmount;
i++;
}
Row.Add(res.Male.ToString());
Row.Add(res.Female.ToString());
i=0;
foreach( var opnmb in OptionNumbers){
var optNmbAmount = res.OptionNumberValues.Where( o => o.ActivityOptionNumberId == opnmb.Id).Sum( s => s.Value);
Row.Add( optNmbAmount.ToString());
totalPerOptionNumber[i] += optNmbAmount;
i++;
}
Rows.Add(Row);
}
table.Rows = Rows;
table.Foother = new List<string>{
"Total", (TotalHours / 8).ToString(), (TotalMultistate / 8).ToString(), TotalAudience.ToString()
};
i = 0;
foreach( var race in Races){
table.Foother.Add(totalPerRace[i].ToString());
i++;
}
i = 0;
foreach( var et in Ethnicities){
table.Foother.Add(totalPerEthnicity[i].ToString());
i++;
}
table.Foother.Add(ToatalMales.ToString());
table.Foother.Add(TotalFemales.ToString());
i = 0;
foreach( var opnmb in OptionNumbers){
table.Foother.Add( totalPerOptionNumber[i].ToString());
i++;
}
var serialized = JsonConvert.SerializeObject(table);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(23)
});
}
return table;
}
public async Task<TableViewModel> ContactsByCountyByMajorProgram(FiscalYear fiscalYear, bool refreshCache = false)
{
var cacheKey = CacheKeys.ActivityContactsByCountyByMajorProgram + fiscalYear.Name;
var cachedTypes = _cache.GetString(cacheKey);
TableViewModel table;
if (!string.IsNullOrEmpty(cachedTypes) && !refreshCache){
table = JsonConvert.DeserializeObject<TableViewModel>(cachedTypes);
}else{
var counties = await this.coreContext.PlanningUnit
.Where( u =>
u.District != null
&&
u.Name.Substring( u.Name.Length - 3) == "CES"
)
.OrderBy( u => u.Name)
.ToListAsync();
var majorPrograms = await this.coreContext.MajorProgram
.Where( u =>
u.StrategicInitiative.FiscalYear == fiscalYear
)
.OrderBy( u => u.Name)
.ToListAsync();
var header = new List<string>();
header.Add( "Counties" );
foreach( var program in majorPrograms){
header.Add(program.Name);
}
var rows = new List<List<string>>();
foreach( var county in counties ){
var row = new List<string>();
row.Add( county.Name );
// Add county numbers
foreach( var prgrm in majorPrograms){
var sm = coreContext.Activity.Where( a => a.MajorProgramId == prgrm.Id && a.PlanningUnitId == county.Id && a.ActivityDate.Year < 2018).Sum(s => s.Audience);
row.Add(sm.ToString());
}
rows.Add(row);
}
table = new TableViewModel();
table.Header = header;
table.Rows = rows;
table.Foother = new List<string>();
var serialized = JsonConvert.SerializeObject(table);
await _cache.SetStringAsync(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(13)
});
}
return table;
}
// type: 0 - all, 1 - UK, 2 - KSU
public async Task<TableViewModel> StateByMajorProgram(FiscalYear fiscalYear, int type = 0, bool refreshCache = false)
{
var cacheKey = CacheKeys.StateByMajorProgram + type.ToString() + fiscalYear.Name;
var cachedTypes = _cache.GetString(cacheKey);
TableViewModel table;
if (!string.IsNullOrEmpty(cachedTypes) && !refreshCache){
table = JsonConvert.DeserializeObject<TableViewModel>(cachedTypes);
}else{
var actvtsCacheKey = "AllActivitiesByMajorProgram" + type.ToString() + fiscalYear.Name;
var cachedActivities = _cache.GetString(actvtsCacheKey);
List<ActivityMajorProgramResult> activities;
if (!string.IsNullOrEmpty(cachedActivities) && !refreshCache){
activities = JsonConvert.DeserializeObject<List<ActivityMajorProgramResult>>(cachedActivities);
}else{
// Only UK
if(type == 1){
activities = await this.coreContext.Activity
.Where( a => a.ActivityDate < fiscalYear.End
&&
a.ActivityDate > fiscalYear.Start
&&
a.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.GroupBy(e => new {
Program = e.MajorProgram
})
.Select(c => new ActivityMajorProgramResult{
Ids = c.Select(
s => s.Id
).ToList(),
Hours = c.Sum(s => s.Hours),
Audience = c.Sum(s => s.Audience),
MajorProgram = c.Key.Program
})
.ToListAsync();
// Only KSU
}else if( type == 2){
activities = await this.coreContext.Activity
.Where( a => a.ActivityDate < fiscalYear.End
&&
a.ActivityDate > fiscalYear.Start
&&
a.KersUser.RprtngProfile.Institution.Code == "21000-1890")
.GroupBy(e => new {
Program = e.MajorProgram
})
.Select(c => new ActivityMajorProgramResult{
Ids = c.Select(
s => s.Id
).ToList(),
Hours = c.Sum(s => s.Hours),
Audience = c.Sum(s => s.Audience),
MajorProgram = c.Key.Program
})
.ToListAsync();
}else{
activities = await this.coreContext.Activity
.Where( a => a.ActivityDate < fiscalYear.End && a.ActivityDate > fiscalYear.Start)
.GroupBy(e => new {
Program = e.MajorProgram
})
.Select(c => new ActivityMajorProgramResult{
Ids = c.Select(
s => s.Id
).ToList(),
Hours = c.Sum(s => s.Hours),
Audience = c.Sum(s => s.Audience),
MajorProgram = c.Key.Program
})
.ToListAsync();
}
foreach( var activity in activities){
var males = 0;
var females = 0;
foreach( var perUserId in activity.Ids ){
var last = coreContext.ActivityRevision.Where( a => a.ActivityId == perUserId ).OrderBy( a => a.Created ).Last();
males += last.Male;
females += last.Female;
}
activity.Male = males;
activity.Female = females;
}
var serializedActivities = JsonConvert.SerializeObject(activities);
_cache.SetString(actvtsCacheKey, serializedActivities, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1)
});
}
var result = ProcessMajorProgramActivities( activities, _cache);
var contactsCacheKey = "AllContactsByMajorProgram" + type.ToString() + "_" + fiscalYear.Name;
var cachedContacts = _cache.GetString(contactsCacheKey);
List<ContactMajorProgramResult> contacts;
if (!string.IsNullOrEmpty(cachedContacts) && !refreshCache){
contacts = JsonConvert.DeserializeObject<List<ContactMajorProgramResult>>(cachedContacts);
}else{
if(type == 1){
contacts = await this.coreContext.Contact.
Where( c =>
c.ContactDate < fiscalYear.End
&&
c.ContactDate > fiscalYear.Start
&&
c.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.GroupBy(e => new {
Program = e.MajorProgram
})
.Select(c => new ContactMajorProgramResult{
Ids = c.Select(
s => s.Id
).ToList(),
MajorProgram = c.Key.Program
})
.ToListAsync();
}else if( type == 2){
contacts = await this.coreContext.Contact.
Where( c =>
c.ContactDate < fiscalYear.End
&&
c.ContactDate > fiscalYear.Start
&&
c.KersUser.RprtngProfile.Institution.Code == "21000-1890"
)
.GroupBy(e => new {
Program = e.MajorProgram
})
.Select(c => new ContactMajorProgramResult{
Ids = c.Select(
s => s.Id
).ToList(),
MajorProgram = c.Key.Program
})
.ToListAsync();
}else{
contacts = await this.coreContext.Contact.
Where( c =>
c.ContactDate < fiscalYear.End
&&
c.ContactDate > fiscalYear.Start
)
.GroupBy(e => new {
Program = e.MajorProgram
})
.Select(c => new ContactMajorProgramResult{
Ids = c.Select(
s => s.Id
).ToList(),
MajorProgram = c.Key.Program
})
.ToListAsync();
}
var serializedContacts = JsonConvert.SerializeObject(contacts);
_cache.SetString(contactsCacheKey, serializedContacts, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(21)
});
}
result = ProcessMajorProgramContacts( contacts, result, _cache);
result = result.OrderBy( r => r.MajorProgram.PacCode).ToList();
table = new TableViewModel();
table.Header = new List<string>{
"Major Program", "Days", "FTE", "Multistate", "Total Contacts"
};
var Races = this.coreContext.Race.OrderBy(r => r.Order);
var Ethnicities = this.coreContext.Ethnicity.OrderBy( e => e.Order);
var OptionNumbers = this.coreContext.ActivityOptionNumber.OrderBy( n => n.Order);
foreach( var race in Races){
table.Header.Add(race.Name);
}
foreach( var ethn in Ethnicities){
table.Header.Add(ethn.Name);
}
table.Header.Add("Male");
table.Header.Add("Female");
foreach( var opnmb in OptionNumbers){
table.Header.Add(opnmb.Name);
}
var Rows = new List<List<string>>();
float TotalHours = 0;
float TotalMultistate = 0;
int TotalAudience = 0;
int TotalMale = 0;
int TotalFemale = 0;
int[] totalPerRace = new int[Races.Count()];
int[] totalPerEthnicity = new int[Ethnicities.Count()];
int[] totalPerOptionNumber = new int[OptionNumbers.Count()];
int i = 0;
foreach(var res in result){
TotalHours += res.Hours;
TotalAudience += res.Audience;
TotalMale += res.Male;
TotalFemale += res.Female;
TotalMultistate += res.Multistate;
var Row = new List<string>();
Row.Add(res.MajorProgram.Name + " (" + res.MajorProgram.PacCode + ")");
Row.Add((res.Hours / 8).ToString());
Row.Add( (res.Hours / (8 * workDaysPerYear) ).ToString("0.000"));
Row.Add((res.Multistate / 8).ToString());
Row.Add(res.Audience.ToString());
i = 0;
foreach( var race in Races){
var raceAmount = res.RaceEthnicityValues.Where( v => v.RaceId == race.Id).Sum( r => r.Amount);
Row.Add(raceAmount.ToString());
totalPerRace[i] += raceAmount;
i++;
}
i=0;
foreach( var et in Ethnicities){
var ethnAmount = res.RaceEthnicityValues.Where( v => v.EthnicityId == et.Id).Sum( r => r.Amount);
Row.Add(ethnAmount.ToString());
totalPerEthnicity[i] += ethnAmount;
i++;
}
Row.Add(res.Male.ToString());
Row.Add(res.Female.ToString());
i=0;
foreach( var opnmb in OptionNumbers){
var optNmbAmount = res.OptionNumberValues.Where( o => o.ActivityOptionNumberId == opnmb.Id).Sum( s => s.Value);
Row.Add( optNmbAmount.ToString());
totalPerOptionNumber[i] += optNmbAmount;
i++;
}
Rows.Add(Row);
}
table.Rows = Rows;
table.Foother = new List<string>{
"Total", (TotalHours / 8).ToString(), (TotalHours / (8 * workDaysPerYear)).ToString("0.000"), (TotalMultistate / 8).ToString(), TotalAudience.ToString()
};
i = 0;
foreach( var race in Races){
table.Foother.Add(totalPerRace[i].ToString());
i++;
}
i = 0;
foreach( var et in Ethnicities){
table.Foother.Add(totalPerEthnicity[i].ToString());
i++;
}
table.Foother.Add(TotalMale.ToString());
table.Foother.Add(TotalFemale.ToString());
i = 0;
foreach( var opnmb in OptionNumbers){
table.Foother.Add( totalPerOptionNumber[i].ToString());
i++;
}
var serialized = JsonConvert.SerializeObject(table);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(3)
});
}
return table;
}
public List<PerUnitActivities> ProcessUnitContacts(List<ContactUnitResult> contacts, List<PerUnitActivities> result){
foreach( var contactGroup in contacts ){
var unitRevisions = new List<ContactRevision>();
var OptionNumbers = new List<IOptionNumberValue>();
var RaceEthnicities = new List<IRaceEthnicityValue>();
foreach( var rev in contactGroup.Ids){
var cacheKey = "ContactLastRevision" + rev.ToString();
var cacheString = _cache.GetString(cacheKey);
ContactRevision lstrvsn;
if (!string.IsNullOrEmpty(cacheString)){
lstrvsn = JsonConvert.DeserializeObject<ContactRevision>(cacheString);
}else{
lstrvsn = coreContext.ContactRevision.
Where(r => r.ContactId == rev).
Include(a => a.ContactOptionNumbers).ThenInclude(o => o.ActivityOptionNumber).
Include(a => a.ContactRaceEthnicityValues).
OrderBy(a => a.Created).Last();
var serialized = JsonConvert.SerializeObject(lstrvsn);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30)
});
}
unitRevisions.Add(lstrvsn);
OptionNumbers.AddRange(lstrvsn.ContactOptionNumbers);
RaceEthnicities.AddRange(lstrvsn.ContactRaceEthnicityValues);
}
var unitInResults = result.Where( r => r.PlanningUnit.Id == contactGroup.Unit.Id).FirstOrDefault();
if(unitInResults == null){
var actvts = new PerUnitActivities();
actvts.RaceEthnicityValues = RaceEthnicities;
actvts.OptionNumberValues = OptionNumbers;
actvts.Hours = unitRevisions.Sum( r => r.Days) * 8;
actvts.Male = unitRevisions.Sum( r => r.Male);
actvts.Female = unitRevisions.Sum( r => r.Female);
actvts.Audience = actvts.Male + actvts.Female;
actvts.PlanningUnit = contactGroup.Unit;
actvts.Multistate = unitRevisions.Sum(r => r.Multistate) * 8;
result.Add(actvts);
}else{
unitInResults.RaceEthnicityValues.AddRange(RaceEthnicities);
unitInResults.OptionNumberValues.AddRange(OptionNumbers);
unitInResults.Hours += unitRevisions.Sum( r => r.Days) * 8;
unitInResults.Male += unitRevisions.Sum( r => r.Male);
unitInResults.Female += unitRevisions.Sum( r => r.Female);
unitInResults.Audience += unitRevisions.Sum( r => r.Male) + unitRevisions.Sum( r => r.Female);
unitInResults.Multistate += unitRevisions.Sum(r => r.Multistate) * 8;
}
}
return result;
}
public List<PerUnitActivities> ProcessUnitActivities(List<ActivityUnitResult> activities, IDistributedCache _cache){
var result = new List<PerUnitActivities>();
foreach( var unt in activities){
var unitRevisions = new List<ActivityRevision>();
var OptionNumbers = new List<IOptionNumberValue>();
var RaceEthnicities = new List<IRaceEthnicityValue>();
foreach( var rev in unt.Ids){
var cacheKey = "ActivityLastRevision" + rev.ToString();
var cacheString = _cache.GetString(cacheKey);
ActivityRevision lstrvsn;
if (!string.IsNullOrEmpty(cacheString)){
lstrvsn = JsonConvert.DeserializeObject<ActivityRevision>(cacheString);
}else{
lstrvsn = coreContext.ActivityRevision.
Where(r => r.ActivityId == rev).
Include(a => a.ActivityOptionNumbers).ThenInclude(o => o.ActivityOptionNumber).
Include(a => a.ActivityOptionSelections).ThenInclude( s => s.ActivityOption).
Include(a => a.RaceEthnicityValues).
OrderBy(a => a.Created).Last();
var serialized = JsonConvert.SerializeObject(lstrvsn);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30)
});
}
unitRevisions.Add(lstrvsn);
OptionNumbers.AddRange(lstrvsn.ActivityOptionNumbers);
RaceEthnicities.AddRange(lstrvsn.RaceEthnicityValues);
}
var actvts = new PerUnitActivities();
actvts.RaceEthnicityValues = RaceEthnicities;
actvts.OptionNumberValues = OptionNumbers;
actvts.Hours = unt.Hours;
actvts.Audience = unt.Audience;
actvts.Male = unt.Male;
actvts.Female = unt.Female;
actvts.PlanningUnit = unt.Unit;
actvts.Multistate = unitRevisions.Where( r => r.ActivityOptionSelections.Where( s => s.ActivityOption.Name == "Multistate effort?").Count() > 0).Sum(s => s.Hours);
result.Add(actvts);
}
return result;
}
public List<PerPersonActivities> ProcessPersonActivities(List<ActivityPersonResult> activities, IDistributedCache _cache){
var result = new List<PerPersonActivities>();
foreach( var unt in activities){
var unitRevisions = new List<ActivityRevision>();
var OptionNumbers = new List<IOptionNumberValue>();
var RaceEthnicities = new List<IRaceEthnicityValue>();
foreach( var rev in unt.Ids){
var cacheKey = "ActivityLastRevision" + rev.ToString();
var cacheString = _cache.GetString(cacheKey);
ActivityRevision lstrvsn;
if (!string.IsNullOrEmpty(cacheString)){
lstrvsn = JsonConvert.DeserializeObject<ActivityRevision>(cacheString);
}else{
lstrvsn = coreContext.ActivityRevision.
Where(r => r.ActivityId == rev).
Include(a => a.ActivityOptionNumbers).ThenInclude(o => o.ActivityOptionNumber).
Include(a => a.ActivityOptionSelections).ThenInclude( s => s.ActivityOption).
Include(a => a.RaceEthnicityValues).
OrderBy(a => a.Created).Last();
var serialized = JsonConvert.SerializeObject(lstrvsn);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30)
});
}
unitRevisions.Add(lstrvsn);
OptionNumbers.AddRange(lstrvsn.ActivityOptionNumbers);
RaceEthnicities.AddRange(lstrvsn.RaceEthnicityValues);
}
var user = this.coreContext.
KersUser.Where( u => u == unt.KersUser)
.Include( u => u.PersonalProfile)
.Include(u => u.RprtngProfile).ThenInclude( r => r.PlanningUnit)
.First();
var actvts = new PerPersonActivities();
actvts.RaceEthnicityValues = RaceEthnicities;
actvts.OptionNumberValues = OptionNumbers;
actvts.Hours = unt.Hours;
actvts.Audience = unt.Audience;
actvts.Male = unt.Male;
actvts.Female = unt.Female;
actvts.KersUser = user;
actvts.Multistate = unitRevisions.Where( r => r.ActivityOptionSelections.Where( s => s.ActivityOption.Name == "Multistate effort?").Count() > 0).Sum(s => s.Hours);
result.Add(actvts);
}
return result;
}
public List<PerProgramActivities> ProcessMajorProgramActivities(List<ActivityMajorProgramResult> activities, IDistributedCache _cache){
var result = new List<PerProgramActivities>();
foreach( var unt in activities){
var unitRevisions = new List<ActivityRevision>();
var OptionNumbers = new List<IOptionNumberValue>();
var RaceEthnicities = new List<IRaceEthnicityValue>();
foreach( var rev in unt.Ids){
var cacheKey = "ActivityLastRevision" + rev.ToString();
var cacheString = _cache.GetString(cacheKey);
ActivityRevision lstrvsn;
if (!string.IsNullOrEmpty(cacheString)){
lstrvsn = JsonConvert.DeserializeObject<ActivityRevision>(cacheString);
}else{
lstrvsn = coreContext.ActivityRevision.
Where(r => r.ActivityId == rev).
Include(a => a.ActivityOptionNumbers).ThenInclude(o => o.ActivityOptionNumber).
Include(a => a.ActivityOptionSelections).ThenInclude( s => s.ActivityOption).
Include(a => a.RaceEthnicityValues).
OrderBy(a => a.Created).Last();
var serialized = JsonConvert.SerializeObject(lstrvsn);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(10)
});
}
unitRevisions.Add(lstrvsn);
OptionNumbers.AddRange(lstrvsn.ActivityOptionNumbers);
RaceEthnicities.AddRange(lstrvsn.RaceEthnicityValues);
}
var actvts = new PerProgramActivities();
actvts.RaceEthnicityValues = RaceEthnicities;
actvts.OptionNumberValues = OptionNumbers;
actvts.Hours = unt.Hours;
actvts.Audience = unt.Audience;
actvts.Male = unt.Male;
actvts.Female = unt.Female;
actvts.MajorProgram = unt.MajorProgram;
actvts.Multistate = unitRevisions.Where( r => r.ActivityOptionSelections.Where( s => s.ActivityOption.Name == "Multistate effort?").Count() > 0).Sum(s => s.Hours);
result.Add(actvts);
}
return result;
}
public List<PerProgramActivities> ProcessMajorProgramContacts(List<ContactMajorProgramResult> contacts, List<PerProgramActivities> result, IDistributedCache _cache){
foreach( var contactGroup in contacts ){
var unitRevisions = new List<ContactRevision>();
var OptionNumbers = new List<IOptionNumberValue>();
var RaceEthnicities = new List<IRaceEthnicityValue>();
foreach( var rev in contactGroup.Ids){
var cacheKey = "ContactLastRevision" + rev.ToString();
var cacheString = _cache.GetString(cacheKey);
ContactRevision lstrvsn;
if (!string.IsNullOrEmpty(cacheString)){
lstrvsn = JsonConvert.DeserializeObject<ContactRevision>(cacheString);
}else{
lstrvsn = coreContext.ContactRevision.
Where(r => r.ContactId == rev).
Include(a => a.ContactOptionNumbers).ThenInclude(o => o.ActivityOptionNumber).
Include(a => a.ContactRaceEthnicityValues).
OrderBy(a => a.Created).Last();
var serialized = JsonConvert.SerializeObject(lstrvsn);
_cache.SetString(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(10)
});
}
unitRevisions.Add(lstrvsn);
OptionNumbers.AddRange(lstrvsn.ContactOptionNumbers);
RaceEthnicities.AddRange(lstrvsn.ContactRaceEthnicityValues);
}
var unitInResults = result.Where( r => r.MajorProgram.Id == contactGroup.MajorProgram.Id).FirstOrDefault();
if(unitInResults == null){
var actvts = new PerProgramActivities();
actvts.RaceEthnicityValues = RaceEthnicities;
actvts.OptionNumberValues = OptionNumbers;
actvts.Hours = unitRevisions.Sum( r => r.Days) * 8;
actvts.Audience = unitRevisions.Sum( r => r.Male) + unitRevisions.Sum( r => r.Female);
actvts.Male = unitRevisions.Sum( r => r.Male);
actvts.Female = unitRevisions.Sum( r => r.Female );
actvts.MajorProgram = contactGroup.MajorProgram;
actvts.Multistate = unitRevisions.Sum(r => r.Multistate) * 8;
result.Add(actvts);
}else{
unitInResults.RaceEthnicityValues.AddRange(RaceEthnicities);
unitInResults.OptionNumberValues.AddRange(OptionNumbers);
unitInResults.Hours += unitRevisions.Sum( r => r.Days) * 8;
unitInResults.Male += unitRevisions.Sum( r => r.Male);
unitInResults.Female += unitRevisions.Sum( r => r.Female);
unitInResults.Audience += unitRevisions.Sum( r => r.Male) + unitRevisions.Sum( r => r.Female);
unitInResults.Multistate += unitRevisions.Sum(r => r.Multistate) * 8;
}
}
return result;
}
/*
ActivityDate
Title
Description
Employee Name
Position
Program(s)
Employed
Planning Unit
ExtensionArea
ExtensionRegion
CongressionalDistrict
MajorProgram
Hours
--- activity options ---
--- race ethnicity details --
Male
Female
--- option numbers ---
SNAP Ed eligible
Snap Admin
Snap Direct Delivery Site
Site Name
Session Type
--- snap age audience values ---
Snap Policy Purpose
Snap Policy Result
--- snap policy aimed ---
--- snap policy partners ---
--- snap indirect reached ---
--- snap indirect method ---
snap copies
*/
public List<string> ReportHeaderRow(
List<Race> races = null,
List<Ethnicity> ethnicities = null,
List<ActivityOption> options = null,
List<ActivityOptionNumber> optionNumbers = null,
List<SnapDirectAges> ages = null,
List<SnapDirectAudience> audience = null,
List<SnapIndirectMethod> method = null,
List<SnapIndirectReached> reached = null,
List<SnapPolicyAimed> aimed = null,
List<SnapPolicyPartner> partners = null)
{
var result = new List<string>();
result.Add("ActivityDate");
result.Add("Title");
result.Add("Description");
result.Add("Employee Name");
result.Add("Position");
result.Add("Program(s)");
result.Add("Employed");
result.Add("Planning Unit");
result.Add("ExtensionArea");
result.Add("ExtensionRegion");
result.Add("CongressionalDistrict");
result.Add("MajorProgram");
result.Add("Hours");
if(options == null) options = coreContext.ActivityOption.OrderBy( o => o.Order).ToList();
foreach( var option in options) result.Add( option.Name );
if( races == null) races = coreContext.Race.OrderBy( r => r.Order).ToList();
if( ethnicities == null ) ethnicities = coreContext.Ethnicity.OrderBy( e => e.Order).ToList();
foreach( var race in races){
foreach( var ethnicity in ethnicities ){
result.Add( race.Name + " " + ethnicity.Name);
}
}
result.Add("Male");
result.Add("Female");
//--- option numbers ---
if( optionNumbers == null ) optionNumbers = coreContext.ActivityOptionNumber.OrderBy( v => v.Order).ToList();
foreach( var optNum in optionNumbers) result.Add( optNum.Name );
result.Add("SNAP Ed eligible");
result.Add("Snap Admin");
result.Add("Snap Direct Delivery Site");
result.Add("Site Name");
result.Add("Session Type");
//--- snap age audience values ---
if(audience == null ) audience = coreContext.SnapDirectAudience.Where( a => a.Active).OrderBy( a => a.order).ToList();
if( ages == null ) ages = coreContext.SnapDirectAges.Where( a => a.Active).OrderBy( a => a.order).ToList();
foreach( var aud in audience)
foreach( var age in ages)
result.Add( aud.Name + " " + age.Name );
result.Add("Snap Policy Purpose");
result.Add("Snap Policy Result");
//--- snap policy aimed ---
if(aimed == null ) aimed = coreContext.SnapPolicyAimed.Where( a => a.Active ).OrderBy( a => a.order).ToList();
foreach( var am in aimed ){
result.Add( am.Name );
}
//--- snap policy partners ---
if( partners == null ) partners = coreContext.SnapPolicyPartner.Where( p => p.Active ).OrderBy( p => p.order ).ToList();
foreach( var par in partners ) result.Add( par.Name );
//--- snap indirect reached ---
if(reached == null) reached = coreContext.SnapIndirectReached.Where( r => r.Active).OrderBy( r => r.order).ToList();
foreach( var reac in reached ) result.Add( reac.Name );
if( method == null ) method = coreContext.SnapIndirectMethod.Where( a => a.Active).OrderBy( a => a.order).ToList();
foreach( var met in method) result.Add( met.Name );
//--- snap indirect method ---
result.Add("snap copies");
return result;
}
public List<string> ReportRow( int id,
Activity activity = null,
List<Race> races = null,
List<Ethnicity> ethnicities = null,
List<ActivityOption> options = null,
List<ActivityOptionNumber> optionNumbers = null,
List<SnapDirectAges> ages = null,
List<SnapDirectAudience> audience = null,
List<SnapIndirectMethod> method = null,
List<SnapIndirectReached> reached = null,
List<SnapPolicyAimed> aimed = null,
List<SnapPolicyPartner> partners = null){
var result = new List<string>();
ActivityRevision lastRevision;
KersUser user;
int? UnitId;
if( activity == null){
var revs = this.coreContext.Activity
.Where( a => a.Id == id)
.Select( a => new {
revisions = a.Revisions,
userId = a.KersUserId,
unitId = a.PlanningUnitId
}
)
.FirstOrDefault();
user = this.coreContext.KersUser
.Where( u => u.Id == revs.userId)
.Include( u => u.Specialties ).ThenInclude( s => s.Specialty)
.Include( u => u.RprtngProfile)
.Include( u => u.ExtensionPosition)
.FirstOrDefault();
UnitId = revs.unitId;
if( revs == null ) return null;
var lastOne = revs.revisions.OrderByDescending( lr => lr.Created).First();
lastRevision = this.coreContext.ActivityRevision
.Where( r => r.Id == lastOne.Id)
.Include( r => r.MajorProgram)
.Include( r => r.RaceEthnicityValues)
.Include( r => r.ActivityOptionNumbers)
.Include( r => r.ActivityOptionSelections)
.FirstOrDefault();
}else{
lastRevision = activity.Revisions.OrderByDescending(r => r.Created).FirstOrDefault();
user = activity.KersUser;
UnitId = activity.PlanningUnitId;
}
var unit = this.coreContext.PlanningUnit.Where( u => u.Id == UnitId)
.Select( u => new {
name = u.Name,
area = ( u.ExtensionArea != null ? u.ExtensionArea.Name : ""),
region = ( u.ExtensionArea != null ? u.ExtensionArea.ExtensionRegion.Name : ""),
congressional = ( u.CongressionalDistrictUnit != null ? u.CongressionalDistrictUnit.CongressionalDistrict.Name : "")
}).FirstOrDefault();
result.Add( lastRevision.ActivityDate.ToString("MM-dd-yy"));
result.Add( lastRevision.Title);
string pattern = @"<[^>]*(>|$)| |'|»|«|"|&";
result.Add(Regex.Replace(lastRevision.Description, pattern, string.Empty));
result.Add( user.RprtngProfile.Name);
result.Add( user.ExtensionPosition.Code);
var spclt = "";
foreach( var sp in user.Specialties.OrderBy( s => s.Specialty.Code)){
spclt += " " + (sp.Specialty.Code.Substring(0, 4) == "prog"?sp.Specialty.Code.Substring(4):sp.Specialty.Code);
}
result.Add( spclt);
result.Add(user.RprtngProfile.enabled.ToString());
result.Add( unit.name);
result.Add( unit.area);
result.Add( unit.region);
result.Add( unit.congressional);
result.Add( lastRevision.MajorProgram.Name);
result.Add( lastRevision.Hours.ToString());
if(options == null) options = coreContext.ActivityOption.OrderBy( o => o.Order).ToList();
foreach( var option in options){
var actvtOpt = lastRevision.ActivityOptionSelections.Where( o => o.ActivityOption == option).Any();
result.Add( actvtOpt.ToString() );
}
if( races == null) races = coreContext.Race.OrderBy( r => r.Order).ToList();
if( ethnicities == null ) ethnicities = coreContext.Ethnicity.OrderBy( e => e.Order).ToList();
foreach( var race in races){
foreach( var ethnicity in ethnicities){
var val = lastRevision.RaceEthnicityValues.Where( v => v.Race == race && v.Ethnicity == ethnicity).FirstOrDefault();
if( val == null ){
result.Add("0");
}else{
result.Add( val.Amount.ToString());
}
}
}
result.Add(lastRevision.Male.ToString());
result.Add( lastRevision.Female.ToString());
if( optionNumbers == null ) optionNumbers = coreContext.ActivityOptionNumber.OrderBy( v => v.Order).ToList();
foreach( var optNum in optionNumbers){
var opnum = lastRevision.ActivityOptionNumbers.Where( n => n.ActivityOptionNumber == optNum).FirstOrDefault();
if( opnum == null){
result.Add("0");
}else{
result.Add( opnum.Value.ToString() );
}
}
result.Add( lastRevision.isSnap.ToString() );
var directFieldsCount = 27;
var partnFieldCount = 40;
var indirectFieldCount = 17;
if( !lastRevision.isSnap ){
var numRemainingFields = indirectFieldCount + partnFieldCount + directFieldsCount + 1;
for( var i = 0; i < numRemainingFields; i++) result.Add("");
}else if( lastRevision.SnapAdmin ){
result.Add( "True");
}else{
result.Add( "False");
if(lastRevision.SnapDirectId != null && lastRevision.SnapDirectId != 0 ){
var direct = coreContext.SnapDirect
.Where( a => a.Id == lastRevision.SnapDirectId)
.Include( d => d.SnapDirectAgesAudienceValues)
.Include( d => d.SnapDirectDeliverySite)
.Include( d => d.SnapDirectSessionType)
.FirstOrDefault();
result.Add(direct.SnapDirectDeliverySite.Name);
result.Add( direct.SiteName );
result.Add( direct.SnapDirectSessionType.Name);
if(audience == null ) audience = coreContext.SnapDirectAudience.Where( a => a.Active).OrderBy( a => a.order).ToList();
if( ages == null ) ages = coreContext.SnapDirectAges.Where( a => a.Active).OrderBy( a => a.order).ToList();
foreach( var aud in audience){
foreach( var age in ages){
var aaval = direct.SnapDirectAgesAudienceValues.Where( v => v.SnapDirectAges == age && v.SnapDirectAudience == aud).FirstOrDefault();
if( aaval == null ){
result.Add("0");
}else{
result.Add( aaval.Value.ToString());
}
}
}
}else{
for( var i = 0; i < directFieldsCount; i++) result.Add("");
}
if( lastRevision.SnapPolicyId != null && lastRevision.SnapPolicyId != 0 ){
var policy = coreContext.SnapPolicy.Where( p => p.Id == lastRevision.SnapPolicyId)
.Include(p => p.SnapPolicyAimedSelections)
.Include( p => p.SnapPolicyPartnerValue )
.FirstOrDefault();
result.Add(Regex.Replace(policy.Purpose, pattern, string.Empty));
result.Add(Regex.Replace(policy.Result, pattern, string.Empty));
if(aimed == null ) aimed = coreContext.SnapPolicyAimed.Where( a => a.Active ).OrderBy( a => a.order).ToList();
foreach( var am in aimed ){
result.Add( policy.SnapPolicyAimedSelections.Where( a => a.SnapPolicyAimed == am).Any().ToString());
}
if( partners == null ) partners = coreContext.SnapPolicyPartner.Where( p => p.Active ).OrderBy( p => p.order ).ToList();
foreach( var par in partners ){
var parVal = policy.SnapPolicyPartnerValue.Where( a => a.SnapPolicyPartner == par ).FirstOrDefault();
if( parVal == null ){
result.Add("");
}else{
result.Add( parVal.Value.ToString() );
}
}
}else{
for( var i = 0; i < partnFieldCount; i++) result.Add("");
}
if( lastRevision.SnapIndirectId != null && lastRevision.SnapIndirectId != 0 ){
var indirect = coreContext.SnapIndirect
.Where( i => i.Id == lastRevision.SnapIndirectId)
.Include( i => i.SnapIndirectMethodSelections)
.Include( i => i.SnapIndirectReachedValues)
.FirstOrDefault();
if(reached == null) reached = coreContext.SnapIndirectReached.Where( r => r.Active).OrderBy( r => r.order).ToList();
foreach( var reac in reached ){
var reach = indirect.SnapIndirectReachedValues.Where( r => r.SnapIndirectReached == reac).FirstOrDefault();
if( reach == null){
result.Add("0");
}else{
result.Add( reach.Value.ToString());
}
}
if( method == null ) method = coreContext.SnapIndirectMethod.Where( a => a.Active).OrderBy( a => a.order).ToList();
foreach( var met in method)
result.Add( indirect.SnapIndirectMethodSelections.Where( s => s.SnapIndirectMethod == met).Any().ToString() );
}else{
for( var i = 0; i < indirectFieldCount; i++) result.Add("");
}
result.Add( lastRevision.SnapCopies.ToString() );
}
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Karkas.Core.DataUtil;
namespace Karkas.Ornek.Dal.Ornekler
{
public partial class StoredProcedures
{
public static int ToplaOutputParam
(
int? @SAYI1
,int? @SAYI2
,out int @SONUC
, AdoTemplate template
)
{
ParameterBuilder builder = template.getParameterBuilder();
builder.parameterEkleReturnValue( "@RETURN_VALUE",DbType.Int32);
builder.parameterEkle( "@SAYI1",DbType.Int32,@SAYI1);
builder.parameterEkle( "@SAYI2",DbType.Int32,@SAYI2);
builder.parameterEkleOutput( "@SONUC",DbType.Int32);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "ORNEKLER.TOPLA_OUTPUT_PARAM";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(builder.GetParameterArray());
template.SorguHariciKomutCalistir(cmd);
@SONUC = (int)cmd.Parameters["@SONUC"].Value;
return (int) cmd.Parameters["@RETURN_VALUE"].Value;
}
public static int ToplaOutputParam
(
int? @SAYI1
,int? @SAYI2
,out int @SONUC
)
{
AdoTemplate template = new AdoTemplate();
template.Connection = ConnectionSingleton.Instance.getConnection("KARKAS_ORNEK");
return ToplaOutputParam(
@SAYI1
,@SAYI2
,out @SONUC
,template
);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MenuButton : MonoBehaviour
{
public Sprite normal, highlight;
public MenuButton up, down, right, left;
public Image target;
public void OnClick()
{
}
public void OnSellect()
{
if (target) target.sprite = highlight;
}
public void OnDiselect()
{
if (target) target.sprite = normal;
}
public MenuButton OnRight()
{
return right;
}
public MenuButton Onleft()
{
return left;
}
public MenuButton OnUp()
{
return up;
}
public MenuButton OnDown()
{
return down;
}
//private void OnGUI()
//{
// if (Sellection.Current)
// GUI.Label(new Rect(25, 25, 200, 25), Sellection.Current.gameObject.name);
//}
}
public static class Sellection
{
static MenuButton _current;
public static MenuButton Current { get { return _current; } }
public static void SellectButton(MenuButton button)
{
if (_current) _current.OnDiselect();
_current = button;
if (_current) _current.OnSellect();
}
}
|
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace IssueLog_Api.Models
{
public class ApplicationUser:IdentityUser
{
[Required]
public string FName { get; set; }
[Required]
public string LName { get; set; }
public virtual ICollection<Project> Client { get; set; }
public virtual ICollection<Project> ProjectManager { get; set; }
public virtual ICollection<Project> ProjectLeader { get; set; }
}
} |
using System;
using UnityEngine;
using UnityEngine.Animations;
public class PowerUpController : MonoBehaviour
{
public PowerUpType powerUpType;
/// <summary>
/// For ammo means the number of bullets, for medkit means the health unit recoverd
/// </summary>
public int power;
private GameObject _player;
private PlayerController _playerController;
// TODO: think about making this variable configurable (public)!
private void Start()
{
_player = GameObject.Find("Player");
_playerController =_player.GetComponent<PlayerController>();
}
private void Update()
{
switch (powerUpType)
{
case PowerUpType.MedKit:
AnimateMedKit(Time.deltaTime);
break;
case PowerUpType.Ammo:
AnimateAmmo(Time.deltaTime);
break;
case PowerUpType.Key:
AnimateKey(Time.deltaTime);
break;
default:
throw new Exception($"Unkwon type of power-up (value: '{powerUpType}')! No animation set!");
}
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject == _player)
{
bool pickedUp = true;
switch (powerUpType)
{
case PowerUpType.MedKit:
pickedUp = HandleMedKitPickUp();
break;
case PowerUpType.Ammo:
HandleAmmoPickUp();
break;
case PowerUpType.Key:
HandleKeyPickUp();
break;
default:
throw new Exception($"Unkwon type of power-up (value: '{powerUpType}')! Collison not handled!");
}
if (pickedUp)
{
Destroy(gameObject);
}
}
}
private void AnimatePowerUp(float animateLoopIsSec, float deltaTime)
{
var rotationDegree = (deltaTime / animateLoopIsSec) * 360.0f;
switch(GetRotationAxis())
{
case Axis.X:
gameObject.transform.Rotate(rotationDegree, 0f, 0f);
break;
case Axis.Y:
gameObject.transform.Rotate(0f, rotationDegree, 0f);
break;
case Axis.Z:
gameObject.transform.Rotate(0f, 0f, rotationDegree);
break;
case Axis.None:
break;
};
}
private void AnimateMedKit(float deltaTime) => AnimatePowerUp(10f, deltaTime);
private void AnimateAmmo(float deltaTime) => AnimatePowerUp(6f, deltaTime);
private void AnimateKey(float deltaTime) => AnimatePowerUp(12f, deltaTime);
private bool HandleMedKitPickUp() => _playerController.IncreaseHealth(power);
private void HandleAmmoPickUp() => _playerController.AddAmmo(power);
private void HandleKeyPickUp() => _player.GetComponent<PlayerController>().HasKey = true;
private Axis GetRotationAxis() => powerUpType switch
{
PowerUpType.MedKit => Axis.Y,
PowerUpType.Key => Axis.Y,
PowerUpType.Ammo => Axis.Z,
_ => throw new Exception($"Unkwon type of power-up (value: '{powerUpType}')! Cannot get axis for animation!")
};
}
public enum PowerUpType
{
MedKit = 1,
Ammo = 2,
Key = 3
} |
namespace Acco.Calendar.Location
{
public interface ILocation
{
string Name { get; set; }
int? Longitude { get; set; }
int? Latitude { get; set; }
}
public class GenericLocation : ILocation
{
public string Name { get; set; }
public int? Longitude { get; set; }
public int? Latitude { get; set; }
}
} |
using UnityEngine;
using System.Collections;
public class ObjectTweener : MonoBehaviour {
// Use this for initialization
public GameObject obj;
public float time;
public int dir;
public float corridorSize = 18;
public float ySize = -1;
public ScreenData data;
public TextMesh corridorState;
void Start () {
corridorState.text = "Page " + (data.corridorState+1).ToString();
}
void OnMouseUp(){
// geser kanan
// Debug.Log (data.corridorState + " " + data.maxCorridorState);
if (GameData.readyToTween) {
GameData.readyToTween = false;
if (dir > 0 && data.corridorState < data.maxCorridorState)
data.corridorState++;
// geser kiri
else if (dir < 0 && data.corridorState > 0)
data.corridorState--;
iTween.MoveTo (obj, iTween.Hash ("position", new Vector3 (corridorSize * -data.corridorState,
ySize, obj.transform.position.z), "time", 0.1f,"onComplete", "ReadyTween", "onCompleteTarget", gameObject));
corridorState.text = "Page " + (data.corridorState + 1).ToString ();
}
}
void ReadyTween(){
GameData.readyToTween = true;
}
}
|
using System;
using DialogSystem.ScriptObject;
using UnityEngine;
namespace DialogSystem.Model
{
[Serializable]
public class BoolVarChooser
{
#pragma warning disable 649
[SerializeField] private int selectedIndex;
#pragma warning restore 649
public bool Value => DialogVarAsset.Instance.varInfos[selectedIndex].BoolValue;
}
} |
using System;
using Xamarin.Forms;
using tryfsharplib;
namespace tryfsharpforms
{
public class UnitsOfMeasurePage : BasePage
{
DataEntry rateEntryEur = new DataEntry { Placeholder = ".91" };
DataEntry valueEntryUsd = new DataEntry { Placeholder = "1000" };
GetDataButton calculateButton = new GetDataButton (Borders.Thin, 1) {
Text = "Calculate!",
TextColor = MyColors.Clouds
};
Label amountLabel = new Label { HorizontalOptions = LayoutOptions.CenterAndExpand, TextColor = MyColors.Clouds };
public UnitsOfMeasurePage ()
{
Content = new StackLayout {
Padding = new Thickness (15),
Children = {
new Label {
Text = "Strongly Typed Currency Converter",
HorizontalOptions = LayoutOptions.CenterAndExpand,
TextColor = MyColors.Clouds,
FontAttributes = FontAttributes.Bold
},
new Label {
Text = "USD to EUR",
TextColor = MyColors.Clouds
},
rateEntryEur,
valueEntryUsd,
new BoxView{ HeightRequest = 10, Opacity = 0 },
calculateButton,
amountLabel
}
};
calculateButton.Clicked += OnButtonClicked;
}
void OnButtonClicked (object sender, EventArgs e)
{
if ((rateEntryEur.Text != null) && (valueEntryUsd.Text != null)) {
decimal rate = decimal.Parse (rateEntryEur.Text);
decimal value = decimal.Parse (valueEntryUsd.Text);
var flib = new ConvertCurrency.ConvertCurrency (rate, value);
amountLabel.Text = "€" + flib.ConvertedCurrency.ToString ();
} else {
amountLabel.Text = "Be sure to enter a rate and a dollar amount!";
}
}
}
}
|
using Portal.repo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Portal
{
public partial class cityPriceAdd : System.Web.UI.Page
{
protected CitiesRepo CitiesRepo;
public cityPriceAdd()
{
CitiesRepo = new CitiesRepo();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userType"] != "admin")
{
Response.Redirect("login.aspx");
}
if (!IsPostBack)
{
cityDetail();
}
}
protected void Add_Click(object sender, EventArgs e)
{
string charges = txt_charges.Value;
if (string.IsNullOrWhiteSpace(charges))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('All fields required.');", true);
return;
}
string type = "";
if (VehicleTypeSedan.Checked)
{
type = "Sedan";
}
else if (VehicleTypeVan.Checked)
{
type = "Van";
}
else if (VehicleTypeBus.Checked)
{
type = "Bus";
}
bool VehicleTypeIsNormal = (VehicleTypeEconomy.Checked) ? true : false;
if (type.ToLower().Trim().Equals("van") && (!VehicleTypeIsNormal))
{
VehicleTypeEconomy.Checked = true;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Luxury type not set for Van.');", true);
return;
}
if (type.ToLower().Trim().Equals("bus") && (!VehicleTypeIsNormal))
{
VehicleTypeEconomy.Checked = true;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Luxury type not set for Bus.');", true);
return;
}
string result = CitiesRepo.addCityPrice(new tbl_autoCharges
{
charges = charges,
createdAt = DateTime.Now,
from_city = int.Parse(fromCity_dropDown.SelectedValue),
to_city = int.Parse(toCity_dropDown.SelectedValue),
type = type,
VehicleTypeIsNormal = VehicleTypeIsNormal
});
if (result.Equals("true"))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Added successfully.');", true);
cityDetail();
}
else if (result.Equals("already"))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('This city name is already exist.');", true);
}
else if (result.Equals("same"))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Same city names not allowed.');", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Something went wrong.');", true);
}
}
public void cityDetail()
{
try
{
var cities = CitiesRepo.getCities();
fromCity_dropDown.DataSource = cities;
fromCity_dropDown.DataTextField = "cityName";
fromCity_dropDown.DataValueField = "cityID";
fromCity_dropDown.DataBind();
toCity_dropDown.DataSource = cities;
toCity_dropDown.DataTextField = "cityName";
toCity_dropDown.DataValueField = "cityID";
toCity_dropDown.DataBind();
txt_charges.Value = "";
VehicleTypeSedan.Checked = true;
VehicleTypeEconomy.Checked = true;
}
catch (Exception)
{
Response.Redirect("CitiesPricing.aspx");
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class GenerateObfuscatedCode
{
private const string TargetCodeDir = "Assets/Script/ObfuscatedCode/Code";
private const string CodeInvokeClassName = "CodeInvoke";
private const string CodeInvokeClass = "Assets/Script/ObfuscatedCode/" + CodeInvokeClassName + ".cs";
public static void GenerateCodes()
{
DirectoryInfo dir = new DirectoryInfo(TargetCodeDir);
if (dir.Exists)
{
dir.Delete(true);
}
if (!Directory.Exists(TargetCodeDir))
{
dir = Directory.CreateDirectory(TargetCodeDir);
}
Dictionary<string, string> class2func = new Dictionary<string, string>();
int classNum = 100;
#if lunplayios2
classNum = 200;
#endif
for (int i = 0; i < classNum; i++)
{
string codeClass = GetRandomString(5, false, true, true, false, "");
string codeFunc = GetRandomString(10, false, true, true, false, "");
if(!class2func.ContainsKey(codeClass))
{
class2func[codeClass] = codeFunc;
CreateNewClassFile(codeClass, codeFunc);
}
}
string code = "public static class " + CodeInvokeClassName + "\n{\n";
code += "\tpublic static void Invoke()\n\t{\n";
foreach (KeyValuePair<string, string> pair in class2func)
{
code += System.String.Format("\t\t{0}.{1}{2}", pair.Key, pair.Value, "();\n");
}
code += "\t}\n";
code += "}\n";
using (StreamWriter writer = new StreamWriter(CodeInvokeClass, false))
{
try
{
writer.WriteLine("{0}", code);
}
catch (System.Exception ex)
{
string msg = " threw:\n" + ex.ToString();
Debug.LogError(msg);
}
}
System.Threading.Thread.Sleep(1000);
AssetDatabase.Refresh();
}
private static string CreateNewClassFile(string codeClass, string codeFunc)
{
string classFilePath = TargetCodeDir + "/" + codeClass + ".cs";
using (StreamWriter writer = new StreamWriter(classFilePath, false))
{
try
{
string code = GenerateCode(codeClass, codeFunc);
writer.WriteLine("{0}", code);
}
catch (System.Exception ex)
{
string msg = " threw:\n" + ex.ToString();
Debug.LogError(msg);
}
}
return classFilePath;
}
private static string GenerateCode(string ClassName, string funcName)
{
string code = "public static class " + ClassName + "\n{\n";
code += System.String.Format("\tpublic static void {0}{1}", funcName, "(){}");
code += "\n}\n";
return code;
}
private static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
{
byte[] b = new byte[4];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
System.Random r = new System.Random(BitConverter.ToInt32(b, 0));
string s = null, str = custom;
if (useNum == true) { str += "0123456789"; }
if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
for (int i = 0; i < length; i++)
{
s += str.Substring(r.Next(0, str.Length - 1), 1);
}
return s;
}
}
|
using Microsoft.EntityFrameworkCore;
using PlankCooking.Models;
namespace PlankCooking.Models {
public class JStanleyContext: DbContext {
public JStanleyContext(DbContextOptions<JStanleyContext> options):base(options){}
public virtual DbSet<Website> Website {get; set;}
public virtual DbSet<Category> Category {get; set;}
public virtual DbSet<Product> Product {get; set;}
public virtual DbSet<OrderCart> OrderCart {get; set;}
public virtual DbSet<OrderItem> OrderItem {get; set;}
}
} |
using Contoso.Forms.Configuration.Directives;
using Contoso.Forms.Configuration.Validation;
using System.Collections.Generic;
namespace Contoso.Forms.Configuration.DataForm
{
public class DataFormSettingsDescriptor : IFormGroupSettings
{
public string Title { get; set; }
public FormRequestDetailsDescriptor RequestDetails { get; set; }
public Dictionary<string, List<ValidationRuleDescriptor>> ValidationMessages { get; set; }
public List<FormItemSettingsDescriptor> FieldSettings { get; set; }
public FormType FormType { get; set; }
public string ModelType { get; set; }
public Dictionary<string, List<DirectiveDescriptor>> ConditionalDirectives { get; set; }
public MultiBindingDescriptor HeaderBindings { get; set; }
public MultiBindingDescriptor SubtitleBindings { get; set; }
public string GroupHeader => Title;
public bool IsHidden => false;
}
}
|
using System.Collections.Generic;
namespace Framework.Commands
{
public class CommandManager
{
private readonly Dictionary<string, Command> registeredCommands = new Dictionary<string, Command>();
public void RegisterCommand(string commandName, Command command)
{
if (registeredCommands.ContainsKey(commandName)) throw new CommandAlreadyRegisteredException();
registeredCommands.Add(commandName, command);
}
public void UnregisterCommand(string commandName)
{
if (!registeredCommands.ContainsKey(commandName)) throw new InvalidCommandException();
registeredCommands.Remove(commandName);
}
public bool Execute(string commandName, object args = null)
{
if (!registeredCommands.ContainsKey(commandName)) throw new InvalidCommandException();
return registeredCommands[commandName].Execute(args);
}
}
} |
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace City_Center.Page.SlideMenu
{
public partial class MasInformacion : ContentPage
{
public MasInformacion()
{
InitializeComponent();
NavigationPage.SetTitleIcon(this, "logo@2x.png");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Angular_NetCore_Test.Data;
using Angular_NetCore_Test.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Angular_NetCore_Test.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private readonly ApplicationDbContext _dbContext;
public ProductController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
// GET: api/Product
[HttpGet("[action]")]
// [Authorize(Policy= "RequireLoggedIn")]
public IActionResult GetProducts()
{
return Ok(_dbContext.Products.ToList());
}
[HttpPost("[action]")]
//[Authorize(Policy = "RequireAdministratorRole")]
public async Task<IActionResult> AddProduct([FromBody] ProductModel formData)
{
var product = new ProductModel
{
ProductName = formData.ProductName,
ImageUrl = formData.ImageUrl,
Description = formData.Description,
OutOfStock = formData.OutOfStock,
Price = formData.Price
};
await _dbContext.AddAsync(product);
await _dbContext.SaveChangesAsync();
return Ok(new JsonResult("The product has successfully added"));
}
//api/product/1
[HttpPut("[action]/{id}")]
//[Authorize(Policy = "RequireAdministratorRole")]
public async Task<IActionResult> UpdateProduct([FromRoute] int id, [FromBody] ProductModel formData)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var findProduct = _dbContext.Products.FirstOrDefault(x => x.ProductId == id);
if(findProduct == null)
{
return NotFound();
}
findProduct.ProductName = formData.ProductName;
findProduct.Description = formData.Description;
findProduct.ImageUrl = formData.ImageUrl;
findProduct.OutOfStock = formData.OutOfStock;
findProduct.Price = formData.Price;
_dbContext.Entry(findProduct).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
return Ok(new JsonResult(" The Product id "+id+"is updated"));
}
[HttpDelete("[action]/{id}")]
//[Authorize(Policy = "RequireAdministratorRole")]
public async Task<IActionResult> DeleteProduct([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var findProduct = _dbContext.Products.FirstOrDefault(x => x.ProductId == id);
if(findProduct == null)
{
return NotFound();
}
_dbContext.Products.Remove(findProduct);
await _dbContext.SaveChangesAsync();
return Ok(new JsonResult("The product containing id " + id + " is deltede "));
}
}
}
|
using Logica;
using Logica.Entidades;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Contactos_WindowsForm.Pantallas
{
public class menuContactos
{
#region objetos
Form form;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbContactos;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lbApellido;
private System.Windows.Forms.Label lbNombre;
private System.Windows.Forms.Label lbDireccion;
private System.Windows.Forms.Label lbTelefono;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtNombre;
private System.Windows.Forms.TextBox txtApellido;
private System.Windows.Forms.TextBox txtDireccion;
private System.Windows.Forms.TextBox txtTelelefono;
private System.Windows.Forms.Button btnEditar;
private System.Windows.Forms.Button btnGuardar;
private System.Windows.Forms.Button btnSalir;
private System.Windows.Forms.Button btnEliminar;
private System.Windows.Forms.Button btnAgregar;
String nombreGlobal;
#endregion
public void crearMenu(String nombre)
{
form = new Form();
form.SuspendLayout();
form.Size = new Size(844, 527);
form.Name = "Form1";
form.Text = "MENU CONTACTOS";
form.Visible = true;
nombreGlobal = nombre;
this.label2 = new System.Windows.Forms.Label();
this.cbContactos = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.lbApellido = new System.Windows.Forms.Label();
this.lbNombre = new System.Windows.Forms.Label();
this.lbDireccion = new System.Windows.Forms.Label();
this.lbTelefono = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.txtNombre = new System.Windows.Forms.TextBox();
this.txtApellido = new System.Windows.Forms.TextBox();
this.txtDireccion = new System.Windows.Forms.TextBox();
this.txtTelelefono = new System.Windows.Forms.TextBox();
this.btnEditar = new System.Windows.Forms.Button();
this.btnGuardar = new System.Windows.Forms.Button();
this.btnSalir = new System.Windows.Forms.Button();
this.btnEliminar = new System.Windows.Forms.Button();
this.btnAgregar = new System.Windows.Forms.Button();
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(665, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(149, 32);
this.label2.TabIndex = 6;
this.label2.Text = nombre.ToUpper();
//
// cbContactos
//
this.cbContactos.FormattingEnabled = true;
this.cbContactos.Location = new System.Drawing.Point(42, 104);
this.cbContactos.Name = "cbContactos";
this.cbContactos.Size = new System.Drawing.Size(261, 24);
this.cbContactos.TabIndex = 7;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(21, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(328, 32);
this.label1.TabIndex = 8;
this.label1.Text = "SELECCION USUARIO";
//
// lbApellido
//
this.lbApellido.AutoSize = true;
this.lbApellido.Font = new System.Drawing.Font("Microsoft Sans Serif", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbApellido.Location = new System.Drawing.Point(375, 181);
this.lbApellido.Name = "lbApellido";
this.lbApellido.Size = new System.Drawing.Size(213, 40);
this.lbApellido.TabIndex = 9;
this.lbApellido.Text = "APELLIDO:";
//
// lbNombre
//
this.lbNombre.AutoSize = true;
this.lbNombre.Font = new System.Drawing.Font("Microsoft Sans Serif", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbNombre.Location = new System.Drawing.Point(375, 104);
this.lbNombre.Name = "lbNombre";
this.lbNombre.Size = new System.Drawing.Size(191, 40);
this.lbNombre.TabIndex = 10;
this.lbNombre.Text = "NOMBRE:";
//
// lbDireccion
//
this.lbDireccion.AutoSize = true;
this.lbDireccion.Font = new System.Drawing.Font("Microsoft Sans Serif", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbDireccion.Location = new System.Drawing.Point(375, 256);
this.lbDireccion.Name = "lbDireccion";
this.lbDireccion.Size = new System.Drawing.Size(235, 40);
this.lbDireccion.TabIndex = 11;
this.lbDireccion.Text = "DIRECCION:";
//
// lbTelefono
//
this.lbTelefono.AutoSize = true;
this.lbTelefono.Font = new System.Drawing.Font("Microsoft Sans Serif", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbTelefono.Location = new System.Drawing.Point(375, 339);
this.lbTelefono.Name = "lbTelefono";
this.lbTelefono.Size = new System.Drawing.Size(230, 40);
this.lbTelefono.TabIndex = 12;
this.lbTelefono.Text = "TELEFONO:";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(389, 383);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(0, 32);
this.label7.TabIndex = 13;
//
// txtNombre
//
this.txtNombre.Location = new System.Drawing.Point(572, 114);
this.txtNombre.Name = "txtNombre";
this.txtNombre.Size = new System.Drawing.Size(208, 22);
this.txtNombre.TabIndex = 14;
//
// txtApellido
//
this.txtApellido.Location = new System.Drawing.Point(572, 191);
this.txtApellido.Name = "txtApellido";
this.txtApellido.Size = new System.Drawing.Size(208, 22);
this.txtApellido.TabIndex = 15;
//
// txtDireccion
//
this.txtDireccion.Location = new System.Drawing.Point(572, 266);
this.txtDireccion.Name = "txtDireccion";
this.txtDireccion.Size = new System.Drawing.Size(208, 22);
this.txtDireccion.TabIndex = 16;
//
// txtTelelefono
//
this.txtTelelefono.Location = new System.Drawing.Point(572, 349);
this.txtTelelefono.Name = "txtTelelefono";
this.txtTelelefono.Size = new System.Drawing.Size(208, 22);
this.txtTelelefono.TabIndex = 17;
//
// btnEditar
//
this.btnEditar.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnEditar.Location = new System.Drawing.Point(42, 402);
this.btnEditar.Name = "btnEditar";
this.btnEditar.Size = new System.Drawing.Size(169, 66);
this.btnEditar.TabIndex = 18;
this.btnEditar.Text = "VER SELECCION";
this.btnEditar.UseVisualStyleBackColor = true;
this.btnEditar.Click += new EventHandler(rellenarEditar);
//
// btnGuardar
//
this.btnGuardar.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnGuardar.Location = new System.Drawing.Point(240, 402);
this.btnGuardar.Name = "btnGuardar";
this.btnGuardar.Size = new System.Drawing.Size(188, 66);
this.btnGuardar.TabIndex = 19;
this.btnGuardar.Text = "GUARDAR";
this.btnGuardar.UseVisualStyleBackColor = true;
//
// btnSalir
//
this.btnSalir.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSalir.Location = new System.Drawing.Point(690, 435);
this.btnSalir.Name = "btnSalir";
this.btnSalir.Size = new System.Drawing.Size(124, 44);
this.btnSalir.TabIndex = 20;
this.btnSalir.Text = "EXIT";
this.btnSalir.UseVisualStyleBackColor = true;
this.btnSalir.Click += new EventHandler(exitButton);
//
// btnEliminar
//
this.btnEliminar.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnEliminar.Location = new System.Drawing.Point(423, 402);
this.btnEliminar.Name = "btnEliminar";
this.btnEliminar.Size = new System.Drawing.Size(165, 71);
this.btnEliminar.TabIndex = 21;
this.btnEliminar.Text = "CARGAR - CONTACTOS";
this.btnEliminar.Click += new EventHandler(cargarCombo);
this.btnEliminar.UseVisualStyleBackColor = true;
//
// btnAgregar
//
this.btnAgregar.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnAgregar.Location = new System.Drawing.Point(690, 383);
this.btnAgregar.Name = "btnAgregar";
this.btnAgregar.Size = new System.Drawing.Size(124, 46);
this.btnAgregar.TabIndex = 22;
this.btnAgregar.Text = "AGREGAR";
this.btnAgregar.UseVisualStyleBackColor = true;
this.btnAgregar.Click += new EventHandler(agregarButton);
//
// Form3
//
form.Controls.Add(this.btnEliminar);
form.Controls.Add(this.btnSalir);
form.Controls.Add(this.btnGuardar);
form.Controls.Add(this.btnEditar);
form.Controls.Add(this.txtTelelefono);
form.Controls.Add(this.txtDireccion);
form.Controls.Add(this.txtApellido);
form.Controls.Add(this.txtNombre);
form.Controls.Add(this.label7);
form.Controls.Add(this.lbTelefono);
form.Controls.Add(this.lbDireccion);
form.Controls.Add(this.lbNombre);
form.Controls.Add(this.lbApellido);
form.Controls.Add(this.label1);
form.Controls.Add(this.cbContactos);
form.Controls.Add(this.label2);
form.Controls.Add(this.btnAgregar);
form.Name = "Form3";
form.Text = "MENU CONTACTOS";
form.ResumeLayout(false);
form.PerformLayout();
}
public void exitButton(object sender, EventArgs e)
{
form.Close();
Form1 ff = new Form1();
ff.Visible = true;
}
public void agregarButton(object sender, EventArgs e)
{
form.Close();
AgregarContacto ag = new AgregarContacto();
ag.crearPantallaAgregarContacto(nombreGlobal);
}
public void cargarCombo(object sender, EventArgs e)
{
string[] files = Directory.GetFiles("Datos\\contacto\\");
var binfor = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream st;
for (int i = 0; i <= files.Length-1; i++)
{
st = File.OpenRead(files[i]);
contactos obj = (contactos)binfor.Deserialize(st);
if(obj.usuarioDelContacto == nombreGlobal)
{
if (cbContactos.Items.Contains(obj.nombre))
{
MessageBox.Show("La lista esta cargada");
}
else
{
cbContactos.Items.Add(obj.nombre.ToString());
}
}
}
}
public void rellenarEditar(object sender, EventArgs e)
{
string[] files = Directory.GetFiles("Datos\\contacto\\");
int dd = cbContactos.SelectedIndex;
var binfor = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream st;
if (dd == -1 || dd == 0)
{
MessageBox.Show("Debe seleccionar contacto si no existen cargue la lista o agregue un contacto");
}
else
{
st = File.OpenRead(files[dd]);
contactos obj = (contactos)binfor.Deserialize(st);
txtNombre.Text = obj.nombre.ToString();
txtApellido.Text = obj.apellido.ToString();
txtTelelefono.Text = obj.telefonoPersonal.ToString();
txtDireccion.Text = obj.direccion.ToString();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NapierBank.Database;
using NapierBank.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;
using NapierBank.Commands;
using System.Windows;
/// <summary>
/// ViewSingleEmailViewModel - Class used to setup elements for the ViewSingleView ensuring the MVVM pattern is kept.
/// </summary>
namespace NapierBank.ViewModels
{
// setup variables and relay commands
public class ViewSingleEmailViewModel : BaseViewModel
{
public ObservableCollection<Email> EmailList { get; set; }
public ICommand NextRecordButtonCommand { get; private set; }
// setup variables with getters and setters.
public Email MessageID { get; set; }
public string NewMessageID { get; set; }
public string Sender { get; set; }
public string Subject { get; set; }
public string Text { get; set; }
public string SortCode { get; set; }
public string NatureOfIncident { get; set; }
// setup constructor
public ViewSingleEmailViewModel()
{
// set to empty.
NewMessageID = "";
Sender = "";
Subject = "";
Text = "";
SortCode = "";
NatureOfIncident = "";
// Load from file.
LoadFromFile load = new LoadFromFile();
if (!load.FromJsonE())
{
// create new email collection.
EmailList = new ObservableCollection<Email>();
}
else
{
// create new email collection from load file.
EmailList = new ObservableCollection<Email>(load.EmailList);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using Ninject;
using Dao.Mercadeo;
namespace Blo.Mercadeo
{
public class MarcaBlo : GenericBlo<InvMarca>, IMarcaBlo
{
private IMarcaDao _marcaDao;
public MarcaBlo(IMarcaDao marcaDao)
: base(marcaDao)
{
_marcaDao =marcaDao;
}
}
}
|
using LRB.Lib.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LRB.Lib.Repositories
{
public class LandApplicationRepository:GenericRepository<Application>
{
public LandApplicationRepository(LandsContext context) : base(context) { }
}
}
|
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ODataQuery.Nodes
{
sealed class MathNode : Node
{
private readonly string methodName;
private readonly Node arg;
public MathNode(string methodName, Node arg)
{
this.methodName = methodName;
this.arg = arg;
}
public override Expression ToExpression(Expression instance)
{
var arg = this.arg.ToExpression(instance);
var method = typeof(Math).GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, new[] { arg.Type }, null);
return Expression.Call(null, method, arg);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BookManageSystem.Service
{
public class CodeService
{
BookManageSystem.dao.CodeDao codeDao = new BookManageSystem.dao.CodeDao();
public List<SelectListItem> GetCodeTable(string selectType)
{
return codeDao.GetCodeTable(selectType);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CCActionManager : SSActionManager, ISSActionCallback,IActionManager {
public FirstSceneController sceneController;
public List<CCMoveToAction> seq = new List<CCMoveToAction>();
public UserClickAction userClickAction;
public UFOFactory factory;
protected new void Start()
{
sceneController = (FirstSceneController)SSDirector.getInstance().current;
sceneController.actionManager = this;
factory = Singleton<UFOFactory>.Instance;
}
public void SSActionEvent(SSAction source, SSActionEventType events = SSActionEventType.Completed, int intParam = 0, string strParam = null, Object objParam = null)
{
factory.Recycleufo(source.gameObject);
seq.Remove(source as CCMoveToAction);
source.destory = true;
if (FirstSceneController.times >= 30)
sceneController.flag = 1;
}
public void CheckEvent(SSAction source, SSActionEventType events = SSActionEventType.Completed, int intParam = 0, string strParam = null, Object objParam = null)
{
}
public void Play() {
if (factory.used_ufos.Count > 0)
{
GameObject ufo = factory.used_ufos[0];
float x = Random.Range(-10, 10);
CCMoveToAction moveToAction = CCMoveToAction.GetSSAction(new Vector3(x, 12, 0), (Mathf.CeilToInt(FirstSceneController.times / 10) + 1) * Time.deltaTime);
if (ufo.transform.GetComponent<Renderer>().material.color == Color.red)
moveToAction = CCMoveToAction.GetSSAction(new Vector3(x, 12, 0), 5 * (Mathf.CeilToInt(FirstSceneController.times / 10) + 1) * Time.deltaTime);
else if(ufo.transform.GetComponent<Renderer>().material.color == Color.green)
moveToAction = CCMoveToAction.GetSSAction(new Vector3(x, 12, 0), 4 * (Mathf.CeilToInt(FirstSceneController.times / 10) + 1) * Time.deltaTime);
else if(ufo.transform.GetComponent<Renderer>().material.color == Color.blue)
moveToAction = CCMoveToAction.GetSSAction(new Vector3(x, 12, 0), 3 * (Mathf.CeilToInt(FirstSceneController.times / 10) + 1) * Time.deltaTime);
seq.Add(moveToAction);
this.RunAction(ufo, moveToAction, this);
factory.used_ufos.RemoveAt(0);
}
if (Input.GetMouseButtonDown(0) && sceneController.flag == 0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitGameObject;
if (Physics.Raycast(ray, out hitGameObject))
{
GameObject gameObject = hitGameObject.collider.gameObject;
if (gameObject.tag == "ufo")
{
foreach (var k in seq)
{
if (k.gameObject == gameObject)
k.transform.position = k.target;
}
if(gameObject.transform.GetComponent<Renderer>().material.color==Color.red)
userClickAction = UserClickAction.GetSSAction(3);
else if(gameObject.transform.GetComponent<Renderer>().material.color==Color.green)
userClickAction = UserClickAction.GetSSAction(2);
else if(gameObject.transform.GetComponent<Renderer>().material.color==Color.blue)
userClickAction = UserClickAction.GetSSAction(1);
this.RunAction(gameObject, userClickAction, this);
}
}
}
base.Update();
}
public void Pause()
{
if(sceneController.flag == 0)
{
foreach (var k in seq)
{
k.enable = false;
}
sceneController.flag = 2;
}
else if(sceneController.flag == 2)
{
foreach (var k in seq)
{
k.enable = true;
}
sceneController.flag = 0;
}
}
} |
using DebugTools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SupercapController
{
public partial class Calibrate : Form
{
List<CalibratePoint> calibValues = new List<CalibratePoint>();
int numberOfSamples = 0;
[DllImport("user32.dll")]
static extern bool GetCursorPos(ref Point lpPoint);
[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
public Calibrate()
{
InitializeComponent();
dataGridView1.Rows.Add("0", "0");
dataGridView1.Rows.Add("0", "0");
//dataGridView1.Rows.Add("0", "0");
//dataGridView1.Rows.Add("0", "0");
}
private void buttonTakeSample_Click(object sender, EventArgs e)
{
// Send command to get last ADC sample
CommandFormerClass cm = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr);
cm.GetLastADCSample(1);
var data = cm.GetFinalCommandList();
SerialDriver.Send(data, SuccessCallback, FailCallback);
}
private void button1_Click(object sender, EventArgs e) // Clear button clicked
{
calibValues = new List<CalibratePoint>();
numberOfSamples = 0;
textBoxDisplay.Text = "";
textBoxGain.Text = "Average";
}
void FailCallback()
{
FormCustomConsole.WriteLineWithConsole("Fail To Calibrate!!");
}
private void SuccessCallback(byte[] b)
{
Invoke((MethodInvoker)delegate
{
ByteArrayDecoderClass decoder = new ByteArrayDecoderClass(b);
decoder.Get2BytesAsInt(); // Ignore first 2 values (message length)
// Get raw value and convert to human readable values, with and without gain
var rawValue = decoder.Get2BytesAsInt16();
float fValue = SupercapHelperClass.ConvertToFloatInMiliVolts(rawValue);
float givenValue;
if (!float.TryParse(textBoxFixedVoltage.Text, out givenValue))
{
FormCustomConsole.WriteLineWithConsole("Wrong float value for calibration!");
return;
}
// Add to list
var calPt = new CalibratePoint(rawValue, fValue, givenValue);
calibValues.Add(calPt);
numberOfSamples++;
// Append to display
AppendToDisplay(calPt);
// Calculate average
CalculateAverage();
}
);
}
private void CalculateAverage()
{
float sum = 0;
foreach (var item in calibValues)
{
sum += item.CalculateGain();
}
// Calculate average gain
sum /= numberOfSamples;
textBoxGain.Text = "Average gain: " + sum.ToString();
}
private void AppendToDisplay(CalibratePoint cp)
{
string newLine = "Raw: " + cp.rawValue + " sampled: " + cp.sampledValue + " given: " + cp.givenValue + " gain: " + cp.CalculateGain();
textBoxDisplay.Text += "\r\n" + newLine;
}
private void buttonCopyGain_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (var item in calibValues)
{
sb.Append(item.CalculateGain() + "\r\n");
}
Clipboard.SetText(sb.ToString());
}
private void textBoxFixedVoltage_Enter(object sender, EventArgs e)
{
if (textBoxFixedVoltage.Text == "") return;
int tmp, final;
final = Convert.ToInt32(textBoxFixedVoltage.Text);
//Check if auto decrement is enabled
if (checkBox1.Checked)
{
tmp = Convert.ToInt32(textBoxAutoDecrement.Text);
tmp = final - tmp;
if (tmp >= 0) // Dont allow negative values
{
final = tmp;
}
}
textBoxFixedVoltage.Text = final.ToString();
textBoxFixedVoltage.SelectAll();
}
private void timer1_Tick(object sender, EventArgs e)
{
Point pt = new Point();
GetCursorPos(ref pt);
labelMousePosX.Text = "PosX: " + pt.X.ToString();
labelMousePosY.Text = "PosY: " + pt.Y.ToString();
}
private void Calibrate_KeyPress(object sender, KeyPressEventArgs e)
{
Point pt = new Point();
GetCursorPos(ref pt);
switch (e.KeyChar)
{
case '/':
dataGridView1.Rows[0].SetValues(pt.X.ToString(), pt.Y.ToString());
break;
case '*':
dataGridView1.Rows[1].SetValues(pt.X.ToString(), pt.Y.ToString());
break;
//case '-':
// dataGridView1.Rows[2].SetValues(pt.X.ToString(), pt.Y.ToString());
// break;
//case '+':
// dataGridView1.Rows[3].SetValues(pt.X.ToString(), pt.Y.ToString());
// break;
default:
break;
}
}
private void buttonCalib100A_Click(object sender, EventArgs e)
{
// Send commands for calibration
CommandFormerClass cm = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr);
cm.ReturnACK();
cm.AppendDischarger100AOn();
cm.AppendWaitForMs(2000);
cm.AppendDataRecorderTask(0, 2, 0, 150, DateTime.Now.AddSeconds(2)); // Take into consideration 2 sec wait above
cm.AppendWaitForMs(1000);
cm.AppendDischarger100AOffS1();
cm.AppendWaitForMs(200);
cm.AppendDischarger100AOffS2();
var data = cm.GetFinalCommandList();
SerialDriver.Send(data, SuccessCallbackCurrent100A, FailCallback);
// Now enable GW INSTEC recording
Point pt = new Point(Convert.ToInt32(dataGridView1.Rows[0].Cells[0].Value), Convert.ToInt32(dataGridView1.Rows[0].Cells[1].Value));
Cursor.Position = pt;
mouse_event(MOUSEEVENTF_LEFTDOWN, pt.X, pt.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, pt.X, pt.Y, 0, 0);
Thread.Sleep(100);
// Configrm recording
pt = new Point(Convert.ToInt32(dataGridView1.Rows[1].Cells[0].Value), Convert.ToInt32(dataGridView1.Rows[1].Cells[1].Value));
Cursor.Position = pt;
mouse_event(MOUSEEVENTF_LEFTDOWN, pt.X, pt.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, pt.X, pt.Y, 0, 0);
Thread.Sleep(2900);
// Disable measures
pt = new Point(Convert.ToInt32(dataGridView1.Rows[0].Cells[0].Value), Convert.ToInt32(dataGridView1.Rows[0].Cells[1].Value));
Cursor.Position = pt;
mouse_event(MOUSEEVENTF_LEFTDOWN, pt.X, pt.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, pt.X, pt.Y, 0, 0);
}
private void SuccessCallbackCurrent100A(byte[] obj)
{
Console.WriteLine("Finished 100A");
}
private void buttonCalib10A_Click(object sender, EventArgs e)
{
// Send commands for calibration
CommandFormerClass cm = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr);
cm.ReturnACK();
cm.AppendDischarger10AOn();
cm.AppendWaitForMs(2000);
cm.AppendDataRecorderTask(0, 2, 0, 300, DateTime.Now.AddSeconds(2)); // Take into consideration 2 sec wait above
cm.AppendWaitForMs(2000);
cm.AppendDischarger10AOffS1();
cm.AppendWaitForMs(200);
cm.AppendDischarger10AOffS2();
var data = cm.GetFinalCommandList();
SerialDriver.Send(data, SuccessCallbackCurrent100A, FailCallback);
// Now enable GW INSTEC recording
Point pt = new Point(Convert.ToInt32(dataGridView1.Rows[0].Cells[0].Value), Convert.ToInt32(dataGridView1.Rows[0].Cells[1].Value));
Cursor.Position = pt;
mouse_event(MOUSEEVENTF_LEFTDOWN, pt.X, pt.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, pt.X, pt.Y, 0, 0);
Thread.Sleep(100);
// Configrm recording
pt = new Point(Convert.ToInt32(dataGridView1.Rows[1].Cells[0].Value), Convert.ToInt32(dataGridView1.Rows[1].Cells[1].Value));
Cursor.Position = pt;
mouse_event(MOUSEEVENTF_LEFTDOWN, pt.X, pt.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, pt.X, pt.Y, 0, 0);
Thread.Sleep(3900);
// Disable measures
pt = new Point(Convert.ToInt32(dataGridView1.Rows[0].Cells[0].Value), Convert.ToInt32(dataGridView1.Rows[0].Cells[1].Value));
Cursor.Position = pt;
mouse_event(MOUSEEVENTF_LEFTDOWN, pt.X, pt.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, pt.X, pt.Y, 0, 0);
}
}
public class CalibratePoint
{
public int rawValue;
public float sampledValue;
public float givenValue;
public CalibratePoint(int raw, float sampled, float given)
{
sampledValue = sampled;
givenValue = given;
rawValue = raw;
}
public float CalculateGain()
{
return givenValue / sampledValue;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace BDinterface
{
public partial class Form1 : Form
{
public static string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\0 Cursach\\BDinterface\\BDinterface\\Db Lecturers.mdb";
private OleDbConnection myConnection;
public Form1()
{
InitializeComponent();
myConnection = new OleDbConnection(connectString);
myConnection.Open();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: данная строка кода позволяет загрузить данные в таблицу "db_LecturersDataSet.Преподаватели". При необходимости она может быть перемещена или удалена.
this.преподавателиTableAdapter.Fill(this.db_LecturersDataSet.Преподаватели);
}
private void button1_Click(object sender, EventArgs e)
{
int code = Convert.ToInt32(textBox1.Text);
string query = "DELETE FROM Преподаватели WHERE [Код] =" + code;
OleDbCommand command = new OleDbCommand(query, myConnection);
command.ExecuteNonQuery();
MessageBox.Show("Дані про викладача видалені");
this.преподавателиTableAdapter.Fill(this.db_LecturersDataSet.Преподаватели);
}
private void button2_Click(object sender, EventArgs e)
{
int code = Convert.ToInt32(textBox2.Text);
string query = "UPDATE Преподаватели SET Вчене звання викладача = '" + textBox3.Text + "' WHERE [Код] =" + code;
OleDbCommand command = new OleDbCommand(query, myConnection);
command.ExecuteNonQuery();
MessageBox.Show("Дані про викладача змінено");
this.преподавателиTableAdapter.Fill(this.db_LecturersDataSet.Преподаватели);
}
private void button3_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Owner = this;
f2.Show();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
myConnection.Close();
}
private void button2_Click_1(object sender, EventArgs e)
{
this.преподавателиTableAdapter.Fill(this.db_LecturersDataSet.Преподаватели);
}
}
}
|
using PyFarmaceutica.acceso_a_datos.interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PyFarmaceutica.acceso_a_datos.implementaciones
{
public class ReporteStockDao : IReporteStockDao
{
private SqlConnection cnn;
public ReporteStockDao()
{
cnn = new SqlConnection(HelperDao.Instancia().CadenaConeccion());
}
public DataTable ReporteStocks()
{
SqlCommand cmd = new SqlCommand("SP_CONSULTAR_STOCKS", cnn);
cmd.CommandType = CommandType.StoredProcedure;
DataTable tabla = new DataTable();
cnn.Open();
tabla.Load(cmd.ExecuteReader());
cnn.Close();
return tabla;
}
}
}
|
using System.Collections.Generic;
using Web.Models;
namespace Web.ViewModels.Meetings
{
public class PickMeetingsVm
{
public PickMeetingsVm()
{
this.PickMeetingsList = new List<PickMeeting>();
}
public List<PickMeeting> PickMeetingsList { get; set; }
}
} |
using System.Collections.Generic;
using System.Threading;
namespace Torshify.Radio.Framework
{
public interface ITrackStream
{
bool SupportsTrackSkipping
{
get;
}
string Description
{
get;
}
TrackStreamData Data
{
get;
}
IEnumerable<Track> Current { get; }
void Dispose();
bool MoveNext(CancellationToken token);
void Reset();
}
} |
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using SPDataRepository.Data.Entities;
using SPDataRepository.Domain.Dtos;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SPDataRepository.Data
{
#nullable disable
public class ProductDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Brand> Brands { get; set; }
public DbSet<ProductDto> ProductDtos { get; set; }
public ProductDbContext(DbContextOptions<ProductDbContext> options) : base(options)
{
}
/// <summary>
/// Generic Pattern to retreive data from any Stored Procedure
/// </summary>
/// <typeparam name="T">a Class Type</typeparam>
/// <param name="Schema"></param>
/// <param name="StoredProcedure">Cannot be NULL</param>
/// <param name="parameters"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<IEnumerable<T>> GetTsFromSpAsync<T>(string StoredProcedure, string Schema = "", SqlParameter[] parameters=null,
CancellationToken token=default) where T : class
{
if (parameters is null)
parameters = new SqlParameter[0];
string spName = BuildSpName(StoredProcedure, Schema,parameters);
var resultSet = await Set<T>()
.FromSqlRaw($"{spName}", parameters)
.ToListAsync(token);
return resultSet;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//This must be set in order to treat ProductDto as a non table
modelBuilder.Entity<ProductDto>().HasNoKey().ToView(null);
}
#region Helper Methods
/// <summary>
/// Build corresponding Stored Procedure Command to execute
/// </summary>
/// <param name="Schema"></param>
/// <param name="StoredProcedure">Cannot be NULL</param>
/// <param name="parameters"></param>
/// <returns></returns>
private string BuildSpName(string StoredProcedure, string Schema = "", SqlParameter[] parameters = null)
{
//Unicode for Space
var spaceChar = "\u0020";
string spName = $"EXECUTE{spaceChar}";
if (!string.IsNullOrWhiteSpace(Schema))
spName += $"{spaceChar}{Schema}.";
spName += $"{StoredProcedure}";
if (parameters.Length>0)
{
foreach (var param in parameters)
//Add spcae front and after along with Parameter name
//The only purpose of these spaces is to look cleaner
spName += $"{spaceChar}@{param.ParameterName},{spaceChar}";
//Remove the last Comma and tje White space
int lettersToRemove = 2;
spName = spName.Remove(spName.Length - lettersToRemove, lettersToRemove);
}
return spName;
}
#endregion Helper Methods
}
}
|
/*
DotNetMQ - A Complete Message Broker For .NET
Copyright (C) 2011 Halil ibrahim KALKAN
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
namespace MDS.Threading
{
/// <summary>
/// A delegate to used by QueueProcessorThread to raise processing event
/// </summary>
/// <typeparam name="T">Type of the item to process</typeparam>
/// <param name="sender">The object which raises event</param>
/// <param name="e">Event arguments</param>
public delegate void ProcessQueueItemHandler<T>(object sender, ProcessQueueItemEventArgs<T> e);
/// <summary>
/// Stores processing item and some informations about queue.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ProcessQueueItemEventArgs<T> : EventArgs
{
/// <summary>
/// The item to process.
/// </summary>
public T ProcessItem { get; set; }
/// <summary>
/// The item count waiting for processing on queue (after this one).
/// </summary>
public int QueuedItemCount { get; set; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="processItem">The item to process</param>
/// <param name="queuedItemCount">The item count waiting for processing on queue (after this one)</param>
public ProcessQueueItemEventArgs(T processItem, int queuedItemCount)
{
ProcessItem = processItem;
QueuedItemCount = queuedItemCount;
}
}
} |
//====================================================================
// 文件: c_TaskDetailsInfo.cs
// 创建时间:2017/11/8
// ===================================================================
using System;
using Dapper;
namespace SimpleCrawler
{
/// <summary>
///
/// </summary>
[Table("c_TaskDetails")]
public partial class c_TaskDetailsInfo
{
/// <summary>
///
/// </summary>
[Key]
public int Id { get; set; }
/// <summary>
///
/// </summary>
public int TaskId { get; set; }
public string Title { get; set; }
/// <summary>
///
/// </summary>
public String CrawUrl { get; set; }
public int Depth { get; set; }
/// <summary>
/// 原始html全文
/// </summary>
public String RawHtml { get; set; }
public String SelectHtml { get; set; }
/// <summary>
///
/// </summary>
public DateTime CreationTime { get; set; }
}
}
|
using System;
namespace Veeqo.Api
{
public class Class1
{
}
}
|
using System;
using AVFoundation;
using Foundation;
using System.IO;
using Xamarin.Forms;
using App1.iOS.Services;
using App1.Services;
[assembly: Dependency(typeof(CAudioPlayer))]
namespace App1.iOS.Services
{
public class CAudioPlayer : AudioPlayer
{
public AVAudioPlayer Player { get; set; }
public NSError Error;
public CAudioPlayer()
{
//AudioFilePath = Path.GetTempPath();
AudioFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
}
void AudioPlayer.PlayAudio()
{
Player = new AVAudioPlayer(NSUrl.FromFilename(Path.Combine(AudioFilePath, AudioFileName + ".wav")), ".wav", out Error);
Player.Play();
}
void AudioPlayer.StopAudio()
{
Player.Stop();
}
void AudioPlayer.PauseAudio()
{
Player.Pause();
}
private string audioFileName;
public string AudioFileName
{
get
{
return audioFileName;
}
set
{
audioFileName = value;
}
}
private string audioFilePath;
public string AudioFilePath
{
get
{
return audioFilePath;
}
set
{
audioFilePath = value;
}
}
public double Duration
{
get { return Player == null ? 0 : Player.Duration; }
}
public double CurrentPosition
{
get { return Player == null ? 0 : Player.CurrentTime; }
}
public bool IsPlaying
{
get { return Player == null ? false : Player.Playing; }
}
}
} |
using System;
public class Relatorio
{
/*Listar todos os quartos ocupados e seus devidos gastos.*/
public void Relatorio_Diario(Gerenciamento_de_reservas gr)
{
gr.Listar_Gastos_Atuais();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class gameMaster : MonoBehaviour {
public GameObject Spikes;
public GameObject Enemy;
public GameObject Space;
float Space_Width;
float Space_Height;
float Spikes_Width;
float Spikes_Height;
public GameObject Pause_Menu;
public GameObject Game_Over_Menu;
int Total_Time = 180;
Vector2 Quantity_Max;
public Vector2 Quantity;
GameObject[] All_Spikes;
float Delay;
public AudioSource Background;
void Start () {
Time.timeScale = 1;
Spikes_Width = Spikes.GetComponent<SpriteRenderer>().size.x * Spikes.GetComponent<Transform>().localScale.x;
Spikes_Height = Spikes.GetComponent<SpriteRenderer>().size.y * Spikes.GetComponent<Transform>().localScale.y;
Space_Width = Mathf.Floor((Camera.main.orthographicSize * 2f * Screen.width / Screen.height * .95f) / Spikes_Width) * Spikes_Width;
Space_Height = Mathf.Floor((Camera.main.orthographicSize * 2f * .95f) / Spikes_Width) * Spikes_Width;
Quantity_Max = new Vector2(
Mathf.RoundToInt(Space_Height / (Spikes.GetComponent<SpriteRenderer>().size.x * Spikes.GetComponent<Transform>().localScale.x)),
Mathf.RoundToInt(Space_Width / Spikes_Width)
);
Delay = Total_Time / (Quantity_Max.x + Quantity_Max.y - 8);
All_Spikes = new GameObject[Mathf.RoundToInt(Quantity_Max.x * 2 + Quantity_Max.y * 2)];
//Enemy_Wave();
StartCoroutine(Closing_Walls());
}
void Update () {
Background.pitch = 1 + (Time.timeSinceLevelLoad / Total_Time);
}
void Enemy_Wave () {
Vector2 Enemy_Size = new Vector2(
Enemy.GetComponent<SpriteRenderer>().size.x * Enemy.GetComponent<Transform>().localScale.x,
Enemy.GetComponent<SpriteRenderer>().size.y * Enemy.GetComponent<Transform>().localScale.y
);
GameObject Clone = Instantiate(Enemy);
Clone.transform.position = new Vector3(Enemy_Size.x * 10, Enemy_Size.x * Random.Range(4, 6), 0);
Clone.name = "Enemy";
Clone = Instantiate(Enemy);
Clone.transform.position = new Vector3(Enemy_Size.x * -10, Enemy_Size.x * Random.Range(4, 6), 0);
Clone.name = "Enemy";
Clone = Instantiate(Enemy);
Clone.transform.position = new Vector3(Enemy_Size.x * Random.Range(4, 6), Enemy_Size.x * 10, 0);
Clone.name = "Enemy";
Clone = Instantiate(Enemy);
Clone.transform.position = new Vector3(Enemy_Size.x * Random.Range(4, 6), Enemy_Size.x * -10, 0);
Clone.name = "Enemy";
}
public void Generate_Walls () {
Space_Width = Quantity.y * Spikes_Width;
Space_Height = Quantity.x * Spikes_Width;
float Ratio_x = Space_Width / (Camera.main.orthographicSize * 2f * Screen.width / Screen.height);
float Ratio_y = Space_Height / (Camera.main.orthographicSize * 2f);
Vector3 Screen_Pos = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width * (Ratio_x + ((1 - Ratio_x) / 2f)), Screen.height * (Ratio_y + ((1 - Ratio_y) / 2f)), 0)); // Top right
Space.transform.localScale = new Vector3(Space_Width / Space.GetComponent<SpriteRenderer>().size.x - (Spikes.GetComponent<Transform>().localScale.x), Space_Height / Space.GetComponent<SpriteRenderer>().size.x, 1);
for (int a = 0; a < All_Spikes.Length; a++) {
Destroy(All_Spikes[a]);
}
Spikes_Height = Spikes_Width;
for (int i = 0; i < Quantity.x - 1; i++) { //RIGHT
GameObject Clone = Instantiate(Spikes);
All_Spikes[i] = Clone;
Clone.name = "Spike #" + i;
Clone.GetComponent<Transform>().rotation = Quaternion.Euler(0, 0, 90);
Clone.GetComponent<Transform>().position = new Vector3(Screen_Pos.x - Spikes_Height / 2f, Screen_Pos.y - Spikes_Width / 2f - Spikes_Width * i, 0);
if (i == 0) {
Spikes_Height = Clone.GetComponent<SpriteRenderer>().size.y * Clone.GetComponent<Transform>().localScale.y;
}
}
Spikes_Height = Spikes_Width;
for (int i = 0; i < Quantity.x - 1; i++) { //LEFT
GameObject Clone = Instantiate(Spikes);
All_Spikes[Mathf.RoundToInt(i + Quantity.x)] = Clone;
Clone.name = "Spike #" + i;
Clone.GetComponent<Transform>().rotation = Quaternion.Euler(0, 0, 270);
Clone.GetComponent<Transform>().position = new Vector3(Screen_Pos.x * -1 + Spikes_Height / 2f, Screen_Pos.y * -1 + Spikes_Width / 2f + Spikes_Width * i, 0);
if (i == 0) {
Spikes_Height = Clone.GetComponent<SpriteRenderer>().size.y * Clone.GetComponent<Transform>().localScale.y;
}
}
Spikes_Height = Spikes_Width;
for (int i = 0; i < Quantity.y - 1; i++) { //TOP
GameObject Clone = Instantiate(Spikes);
All_Spikes[Mathf.RoundToInt(i + Quantity.x * 2 - 1)] = Clone;
Clone.name = "Spike #" + i;
Clone.GetComponent<Transform>().rotation = Quaternion.Euler(0, 0, 180);
Clone.GetComponent<Transform>().position = new Vector3(Screen_Pos.x * -1 + (Spikes_Width * (i + .5f)), Screen_Pos.y - Spikes_Height / 2, 0);
if (i == 0) {
Spikes_Height = Clone.GetComponent<SpriteRenderer>().size.y * Clone.GetComponent<Transform>().localScale.y;
}
}
Spikes_Height = Spikes_Width;
for (int i = 0; i < Quantity.y - 1; i++) { //BOTTOM
GameObject Clone = Instantiate(Spikes);
All_Spikes[Mathf.RoundToInt(i + Quantity.x * 2 + Quantity.y - 1)] = Clone;
Clone.name = "Spike #" + i;
Clone.GetComponent<Transform>().rotation = Quaternion.Euler(0, 0, 0);
Clone.GetComponent<Transform>().position = new Vector3(Screen_Pos.x - (Spikes_Width * (i + .5f)), Screen_Pos.y * -1 + Spikes_Height / 2, 0);
if (i == 0) {
Spikes_Height = Clone.GetComponent<SpriteRenderer>().size.y * Clone.GetComponent<Transform>().localScale.y;
}
}
}
IEnumerator Closing_Walls () {
Quantity = Quantity_Max;
Generate_Walls();
yield return new WaitForSeconds(Delay);
for (int i = 0; i < Quantity_Max.x + Quantity_Max.y - 8; i++) {
if (Quantity.y >= Quantity.x) {
Quantity = new Vector2(Quantity.x, Quantity.y - 1);
}else {
Quantity = new Vector2(Quantity.x - 1, Quantity.y);
}
Generate_Walls();
yield return new WaitForSeconds(Delay);
}
}
public void Game_Over () {
Game_Over_Menu.SetActive(true);
Freeze();
}
public void Pause () {
if (Pause_Menu.activeSelf == false) {
Pause_Menu.SetActive(true);
}else {
Pause_Menu.SetActive(false);
}
Freeze();
}
public void Freeze () {
if (Time.timeScale == 1) {
Time.timeScale = 0;
}else {
Time.timeScale = 1;
}
}
public void Restart () {
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void Exit () {
SceneManager.LoadScene("Title");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FinalliziedProject
{
public class WordProcess
{
public string kelimeAyır(string applicantext)
{
return applicantext.Replace(" ", "+");
}
public List<string> getKelimeList(string kelime)
{
try
{
return kelime.Split(' ').ToList();
}
catch (Exception ex)
{
return new List<string>();
}
}
public string cumlelereAyir(string applicantext)
{
return applicantext.Replace(".", " + ").Trim();
}
public string noktalamalariKaldir(string applicantext)
{
var sb = new StringBuilder();
foreach (char c in applicantext)
{
if (!char.IsPunctuation(c))
{
sb.Append(c);
}
else
{
sb.Append("( )");
}
}
applicantext = sb.ToString();
return applicantext;
}
public string harflereAyır(string applicantext)
{
string tempStr = "";
foreach (var item in applicantext)
{
tempStr = tempStr + " " + item;
}
return tempStr;
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using Diligent.BOL;
namespace Diligent.DAL.EntityCongfigurations
{
public class ReviewMissionConfiguration : EntityTypeConfiguration<ReviewMission>
{
public ReviewMissionConfiguration()
{
ToTable("ReviewMission");
HasRequired(rm => rm.Status)
.WithMany()
.HasForeignKey(rm => rm.StatusId)
.WillCascadeOnDelete(false);
}
}
}
|
using System;
namespace BlockBusterLab
{
class Program
{
static void Main(string[] args)
{
bool runProgram = true;
BlockBuster bb = new BlockBuster();
while (runProgram)
{
Console.Clear();
Console.WriteLine("Welcome to GC Blockbuster!");
Movie movieRental = bb.CheckOut();
movieRental.ShowMovieInfo();
Console.WriteLine();
string playYesNo = GetUserInput("Play this movie? (y/n) ");
if(playYesNo == "y")
{
movieRental.Play();
}
else if(playYesNo == "n")
{
}
else
{
Console.WriteLine("Sorry, I don't understand!");
}
Console.Clear();
string continueYesNo = GetUserInput("Would you like to continue renting? (y/n)");
runProgram = ContinueProgram(continueYesNo);
}
}
//get user input
public static string GetUserInput(string message)
{
Console.WriteLine(message);
string UserInput = Console.ReadLine().ToLower().Trim();
return UserInput;
}
public static bool ContinueProgram(string yesNo)
{
while(yesNo != "y" && yesNo != "n")
{
Console.WriteLine("Invalid input!\nWould you like to continue renting? (y/n)");
yesNo = Console.ReadLine().Trim().ToLower();
}
if(yesNo == "y")
{
return true;
}
else
{
Console.WriteLine("Thank you. Come again!");
return false;
}
}
}
}
|
namespace LocadoraVeiculoSI.Servicos
{
class ImpostoBrasilServico
{
public double Imposto(double quantia)
{
if (quantia <= 100)
{
return quantia * 0.2;
}
else
{
return quantia * 0.15;
}
}
}
}
|
using Hayalpc.Library.Common.Helpers;
using Hayalpc.Library.Common.Helpers.Interfaces;
using Hayalpc.Library.Log;
using Microsoft.Extensions.DependencyInjection;
using Hayalpc.Fatura.Vezne.External.Helpers;
namespace Hayalpc.Fatura.Vezne.External.Extensions
{
public static class ScopeExtension
{
public static void AddScopes(this IServiceCollection services)
{
services.AddScoped<IHpLogger, NlogImpl>();
services.AddScoped<IHtttpClientCreator, HtttpClientCreator>();
services.AddScoped<IHttpClientHelper, HttpClientHelper>();
services.AddScoped<ISessionHelper, SessionHelper>();
}
}
}
|
namespace Bridge.RealWorld
{
/// <summary>
/// The device interface.
/// </summary>
interface IDevice
{
/// <summary>
/// Gets a value indicating whether this instance is enabled.
/// </summary>
/// <value>
/// <c>true</c> if this instance is enabled; otherwise, <c>false</c>.
/// </value>
bool IsEnabled { get; }
/// <summary>
/// Enables this instance.
/// </summary>
void Enable();
/// <summary>
/// Disables this instance.
/// </summary>
void Disable();
/// <summary>
/// Gets the volume.
/// </summary>
/// <returns></returns>
int GetVolume();
/// <summary>
/// Sets the volume.
/// </summary>
/// <param name="percent">The percent.</param>
void SetVolume(int percent);
/// <summary>
/// Gets the channel.
/// </summary>
/// <returns></returns>
int GetChannel();
/// <summary>
/// Sets the channel.
/// </summary>
/// <param name="channel">The channel.</param>
void SetChannel(int channel);
}
} |
//using System;
//using Microsoft.VisualStudio.TestTools.UnitTesting;
//using OpenQA.Selenium;
//using OpenQA.Selenium.Firefox;
//using OpenQA.Selenium.Support.UI;
//using OpenQA.Selenium.Chrome;
//using OpenQA.Selenium.Interactions;
//using System.Threading;
//using System.Threading.Tasks;
//using System.Collections.Generic;
//namespace UnitTestProject1
//{
// class TableTest
// {
// Base baseInst;
// [TestInitialize]
// public void Start()
// {
// baseInst = new Base();
// baseInst.OpenGoogleHomePage();
// }
// [TestMethod]
// public void TestExecution()
// {
// IWebElement TempElement;
// baseInst.GoTo("http://www.machtested.com/");
// baseInst.getChromeDriver().FindElement(By.XPath("//a[contains(@href,'selenium-course')]")).Click();
// TempElement = baseInst.getChromeDriver().FindElement(By.ClassName("MsoNormalTable"));
// IList<IWebElement> ListOfElements = TempElement.FindElements(By.TagName("tr"));
// foreach (var item in ListOfElements)
// {
// Console.WriteLine(item.Text.ToString());
// }
// }
// [TestCleanup]
// public void TearDown()
// {
// baseInst.CloseBrowser();
// }
// }
//}
|
using System;
using UnityEngine;
using System.Collections.Generic;
namespace Dcl
{
[ExecuteInEditMode]
public class DclSceneMeta : MonoBehaviour
{
[SerializeField] [HideInInspector] public List<ParcelCoordinates> parcels = new List<ParcelCoordinates>
{
new ParcelCoordinates(57, -11),
};
[SerializeField] [HideInInspector] public string ethAddress;
[SerializeField] [HideInInspector] public string contactName;
[SerializeField] [HideInInspector] public string email;
public SceneToGlTFWiz sceneToGlTFWiz;
public SceneStatistics sceneStatistics = new SceneStatistics();
public SceneWarningRecorder sceneWarningRecorder = new SceneWarningRecorder();
public Material m_GroundMaterial;
private void Awake()
{
sceneToGlTFWiz = GetComponent<SceneToGlTFWiz>();
if (!sceneToGlTFWiz) sceneToGlTFWiz = gameObject.AddComponent<SceneToGlTFWiz>();
m_GroundMaterial = new Material(PrimitiveHelper.GetDefaultMaterial().shader);
m_GroundMaterial.color = Color.gray;
}
void Update()// OnDrawGizmos()
{
if (parcels.Count > 0)
{
var baseParcel = parcels[0];
// Gizmos.color = new Color(0.7, 0);
foreach (var parcel in parcels)
{
var pos = new Vector3((parcel.x - baseParcel.x) * 10, 0, (parcel.y - baseParcel.y) * 10);
//Gizmos.DrawWireCube(pos, new Vector3(10, 0f, 10));
//Gizmos.DrawCube(pos, new Vector3(10, 0f, 10));
//Gizmos.DrawMesh(PrimitiveHelper.GetPrimitiveMesh(PrimitiveType.Plane), pos);
Graphics.DrawMesh(PrimitiveHelper.GetPrimitiveMesh(PrimitiveType.Plane), pos, Quaternion.identity, m_GroundMaterial, 0);
}
}
}
void OnDrawGizmos()
{
foreach (var outOfLandWarning in sceneWarningRecorder.OutOfLandWarnings)
{
var oriColor = Gizmos.color;
Gizmos.color = Color.red;
Gizmos.DrawWireCube(outOfLandWarning.meshRenderer.bounds.center, outOfLandWarning.meshRenderer.bounds.size);
Gizmos.color = oriColor;
}
}
public void RefreshStatistics()
{
sceneStatistics = new SceneStatistics();
sceneWarningRecorder = new SceneWarningRecorder();
SceneTraverser.TraverseAllScene(null, null, sceneStatistics, sceneWarningRecorder);
}
}
[Serializable]
public struct ParcelCoordinates
{
public ParcelCoordinates(int x, int y)
{
this.x = x;
this.y = y;
}
public int x;
public int y;
public static bool operator ==(ParcelCoordinates a, ParcelCoordinates b)
{
return a.x == b.x && a.y == b.y;
}
public static bool operator !=(ParcelCoordinates a, ParcelCoordinates b)
{
return !(a == b);
}
public bool Equals(ParcelCoordinates other)
{
return x == other.x && y == other.y;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is ParcelCoordinates && Equals((ParcelCoordinates)obj);
}
public override int GetHashCode()
{
unchecked
{
return (x * 397) ^ y;
}
}
public override string ToString()
{
return string.Format("{0},{1}", x, y);
}
}
public class SceneStatistics
{
public long triangleCount;
public int entityCount;
public int bodyCount;
public float materialCount;
public float textureCount;
public float maxHeight;
}
} |
using Cinema.Data.Models;
using Cinema.Data.Models.Contracts;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace Cinema.Data.Contracts
{
public interface ICinemaDbContext : IDisposable
{
int SaveChanges();
IDbSet<User> Users { get; set; }
IDbSet<Movie> Movies { get; set; }
DbSet<TEntity> Set<TEntity>() where TEntity : class;
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DAL.Models
{
public class Author
{
public Guid AuthorId { get; set; }
public string FullName { get; set; }
}
}
|
namespace Phonebook.Repositories
{
using System;
using System.Collections.Generic;
using System.Linq;
using Phonebook.Entities;
using Wintellect.PowerCollections;
public class PhonebookRepository : IPhonebookRepository
{
private readonly OrderedSet<PhonebookEntry> sorted = new OrderedSet<PhonebookEntry>();
private readonly Dictionary<string, PhonebookEntry> dictionary = new Dictionary<string, PhonebookEntry>();
private readonly MultiDictionary<string, PhonebookEntry> multidict = new MultiDictionary<string, PhonebookEntry>(false);
public bool AddPhone(string name, IEnumerable<string> phones)
{
string nameToLower = name.ToLowerInvariant();
PhonebookEntry entry;
bool isNewEntry = !this.dictionary.TryGetValue(nameToLower, out entry);
if (isNewEntry)
{
entry = new PhonebookEntry();
entry.Name = name;
entry.Phones = new SortedSet<string>();
this.dictionary.Add(nameToLower, entry);
this.sorted.Add(entry);
}
foreach (var phone in phones)
{
this.multidict.Add(phone, entry);
}
entry.Phones.UnionWith(phones);
return isNewEntry;
}
public int ChangePhone(string oldent, string newent)
{
var found = this.multidict[oldent].ToList();
foreach (var entry in found)
{
entry.Phones.Remove(oldent);
this.multidict.Remove(oldent, entry);
entry.Phones.Add(newent);
this.multidict.Add(newent, entry);
}
return found.Count;
}
public PhonebookEntry[] ListEntries(int first, int num)
{
if (first < 0 || first + num > this.dictionary.Count)
{
throw new ArgumentOutOfRangeException("Invalid range");
}
PhonebookEntry[] list = new PhonebookEntry[num];
for (int i = first; i <= first + num - 1; i++)
{
PhonebookEntry entry = this.sorted[i];
list[i - first] = entry;
}
return list;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using OCP.AppFramework.Utility;
using Quartz;
namespace OCP.BackgroundJob
{
abstract class Job : IJob
{
/** @var int id */
protected int id;
/** @var int lastRun */
protected int lastRun;
/** @var mixed argument */
protected object argument;
/** @var ITimeFactory */
protected ITimeFactory time;
public Job(ITimeFactory time)
{
this.time = time;
}
//public Task Execute(IJobExecutionContext context)
//{
// throw new NotImplementedException();
//}
public void execute(IJobList jobList, ILogger logger = null)
{
jobList.setLastRun(this);
if (logger == null) {
//logger = \OC::server.getLogger();
}
try
{
var jobStartTime = this.time.getTime();
//logger.debug('Run '.get_class(this). ' job with ID '. this.getId(), ['app' => 'cron']);
this.run(this.argument);
var timeTaken = this.time.getTime() - jobStartTime;
//logger.debug('Finished '.get_class(this). ' job with ID '. this.getId(). ' in '. timeTaken. ' seconds', ['app' => 'cron']);
jobList.setExecutionTime(this, timeTaken);
}
catch (Exception e) {
if (logger != null) {
//logger.logException(e, [
// 'app' => 'core',
// 'message' => 'Error while running background job (class: '.get_class(this). ', arguments: '.print_r(this.argument, true). ')'
// ]);
}
}
}
public Task Execute(IJobExecutionContext context)
{
throw new NotImplementedException();
}
public object getArgument()
{
return this.argument;
}
public int getId()
{
return this.id;
}
public int getLastRun()
{
return this.lastRun;
}
public void setArgument(object argument)
{
this.argument = argument;
}
public void setId(int id)
{
this.id = id;
}
public void setLastRun(int lastRun)
{
this.lastRun = lastRun;
}
/**
* The actual function that is called to run the job
*
* @param argument
* @return mixed
*
* @since 15.0.0
*/
abstract protected object run(object argument);
}
}
|
using System;
using System.Numerics;
public class Program
{
public static void Main()
{
var centuries = int.Parse(Console.ReadLine());
var years = centuries * 100;
var days = (int)(years * 365.2422);
var hours = days * 24;
ulong minutes = (ulong)hours * 60;
ulong seconds = minutes * 60;
BigInteger milliseconds = seconds * 1000;
BigInteger microseconds = milliseconds * 1000;
BigInteger nanoseconds = microseconds * 1000;
Console.WriteLine($"{centuries} centuries = {years} years = {days} days = {hours} hours = {minutes} minutes = {seconds} seconds = {milliseconds} milliseconds = {microseconds} microseconds = {nanoseconds} nanoseconds");
}
} |
using JKMServices.BLL.Interface;
using JKMServices.DTO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Utility;
using Utility.Logger;
namespace JKMServices.BLL
{
public class DocumentDetails : ServiceBase, IDocumentDetails
{
private readonly DAL.CRM.IDocumentDetails crmDocumentDetails;
private readonly ISharepointConsumer sharepointConsumer;
private readonly IResourceManagerFactory resourceManager;
private readonly ILogger logger;
//Constructor
public DocumentDetails(DAL.CRM.IDocumentDetails crmDocumentDetails,
ISharepointConsumer sharepointConsumer,
IResourceManagerFactory resourceManager,
ILogger logger)
{
this.crmDocumentDetails = crmDocumentDetails;
this.sharepointConsumer = sharepointConsumer;
this.resourceManager = resourceManager;
this.logger = logger;
}
/// <summary>
/// Method Name : GetDocumentList
/// Author : Ranjana Singh
/// Creation Date : 22 Dec 2017
/// Purpose : Gets the list of documents to be displayed in My Documents Page. If Customerid is not provided, service will return common documents.
/// Revision :
/// </summary>
public string GetDocumentList(string moveId)
{
ServiceResponse<List<Document>> getDocumentResponse;
List<string> documentList = new List<string>();
try
{
if (!Validations.IsValid(moveId))
{
logger.Error(resourceManager.GetString("msgBadRequest"));
return General.ConvertToJson<ServiceResponse<List<Document>>>(new ServiceResponse<List<Document>> { BadRequest = resourceManager.GetString("msgBadRequest") });
}
getDocumentResponse = crmDocumentDetails.GetDocumentList(moveId);
if (getDocumentResponse.Data == null)
{
logger.Info(resourceManager.GetString("msgNoDataFoundForMove"));
return GenerateServiceResponse<Document>(INFORMATION, resourceManager.GetString("msgNoDataFoundForMove"));
}
foreach (var dtoDocument in getDocumentResponse.Data)
{
documentList.Add(dtoDocument.RelativeUrl);
}
return General.ConvertToJson<ServiceResponse<List<Document>>>(getDocumentResponse);
}
catch (Exception ex)
{
logger.Error(resourceManager.GetString("msgNoDataFoundForMove"), ex);
return GenerateServiceResponse<Document>(MESSAGE, resourceManager.GetString("msgNoDataFoundForMove"));
}
}
/// <summary>
/// Method Name : GetDocumentPDF
/// Author : Pratik Soni
/// Creation Date : 13 Feb 2018
/// Purpose : Gets the pdf file related to the document title
/// Revision :
/// </summary>
/// <remarks> Add below code instead of code written in warning. That code is mocked for testing purpose.
/// const Char relativeFilePathDelimiter = '|';
/// string[] substrings = relativeFilePath.Split(relativeFilePathDelimiter);
/// if (substrings.Count<string>() != 2)
/// {
///logger.Error(resourceManager.GetString("logInvalidRequestContent"));
/// return General.ConvertToJson<ServiceResponse<Document>>(new ServiceResponse<Document> { BadRequest = resourceManager.GetString("logInvalidRequestContent") });
///}
///
///string formattedFilePath = Path.Combine("jkmoving_move", substrings[0], substrings[1]);
///fileContentInByteArray = sharepointConsumer.HandleResult(formattedFilePath); //Sharepoint method call, which is being mocked for now.
/// </remarks>
/// <param name="relativeFilePath">It should be the combination of DTO.Document.RelativePath + "|" + DTO.Document.DocumentTitle</param>
/// <returns>Success = Service Response with base64 string in DATA node.</returns>
public string GetDocumentPDF(string relativeFilePath)
{
try
{
byte[] fileContentInByteArray;
#warning Include code from remarks from comment section in here when mocking will not be required. And remove below 4 lines
if(!Validations.IsValid(relativeFilePath.Trim()))
{
logger.Error(resourceManager.GetString("msgBadRequest"));
return General.ConvertToJson<ServiceResponse<Document>>(new ServiceResponse<Document> { BadRequest = resourceManager.GetString("msgBadRequest") });
}
string documentpath, fileFullPath, applicationPath = string.Empty;
applicationPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
documentpath = General.GetConfigValue("mockedPdfPath");
fileFullPath = Path.Combine(applicationPath, documentpath);
fileContentInByteArray = System.IO.File.ReadAllBytes(fileFullPath);
//End of mocked code
logger.Info("GetConditionalResponseForDocument method encountered to return formatted service response.");
return GetConditionalResponseForDocument(fileContentInByteArray);
}
catch (Exception ex)
{
logger.Error(resourceManager.GetString("msgServiceUnavailable"), ex);
return General.ConvertToJson<ServiceResponse<Document>>(new ServiceResponse<Document> { Message = resourceManager.GetString("msgServiceUnavailable") });
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class SaveDataPots
{
public bool s_p1, s_p2, s_p3, s_p4, s_p5, s_p6, s_p7, s_p8, s_p9, s_p10; //pot places activated
public int s_sp1, s_sp2, s_sp3, s_sp4, s_sp5, s_sp6, s_sp7, s_sp8, s_sp9, s_sp10; //skins on the active pots
public float s_pp1, s_pp2, s_pp3, s_pp4, s_pp5, s_pp6, s_pp7, s_pp8, s_pp9, s_pp10; //Plant in active pot
public string s_TT1P1, s_TT2P1, s_TT3P1;
public string s_TT1P2, s_TT2P2, s_TT3P2;
public string s_TT1P3, s_TT2P3, s_TT3P3;
public bool s_ble1,s_apple1, s_tomato1, s_eggplant1, s_pear1, s_sunflower1, s_cherry1, s_avocado1, s_kiwi1;
public bool s_ble2,s_apple2, s_tomato2, s_eggplant2, s_pear2, s_sunflower2, s_cherry2, s_avocado2, s_kiwi2;
public bool s_ble3,s_apple3, s_tomato3, s_eggplant3, s_pear3, s_sunflower3, s_cherry3, s_avocado3, s_kiwi3;
public bool s_PF1, s_PF2, s_PF3;
public int s_sell1, s_sell2, s_sell3;
public int s_lvl;
//added by axel
public bool s_got1, s_got2, s_got3;
public SaveDataPots(PotPlaces places)
{
//added by axel
s_got1 = places.got1;
s_got2 = places.got2;
s_got3 = places.got3;
//active pots? collectioin
s_p1 = places.p1;
s_p2 = places.p2;
s_p3 = places.p3;
s_p4 = places.p4;
s_p5 = places.p5;
s_p6 = places.p6;
s_p7 = places.p7;
s_p8 = places.p8;
s_p9 = places.p9;
s_p10 = places.p10;
//target times
s_TT1P1 = places.TT1P1;
s_TT2P1 = places.TT2P1;
s_TT3P1 = places.TT3P1;
s_TT1P2 = places.TT1P2;
s_TT2P2 = places.TT2P2;
s_TT3P2 = places.TT3P2;
s_TT1P3 = places.TT1P3;
s_TT2P3 = places.TT2P3;
s_TT3P3 = places.TT3P3;
//fruit planted
s_ble1 = places.ble1;
s_apple1 = places.apple1;
s_tomato1 = places.tomato1;
s_eggplant1 = places.eggplant1;
s_pear1 = places.pear1;
s_sunflower1 = places.sunflower1;
s_cherry1 = places.cherry1;
s_avocado1 = places.avocado1;
s_kiwi1 = places.kiwi1;
s_ble2 = places.ble2;
s_apple2 = places.apple2;
s_tomato2 = places.tomato2;
s_eggplant2 = places.eggplant2;
s_pear2 = places.pear2;
s_sunflower2 = places.sunflower2;
s_cherry2 = places.cherry2;
s_avocado2 = places.avocado2;
s_kiwi2 = places.kiwi2;
s_ble3 = places.ble3;
s_apple3 = places.apple3;
s_tomato3 = places.tomato3;
s_eggplant3 = places.eggplant3;
s_pear3 = places.pear3;
s_sunflower3 = places.sunflower3;
s_cherry3 = places.cherry3;
s_avocado3 = places.avocado3;
s_kiwi3 = places.kiwi3;
//selling price
s_sell1 = places.sell1;
s_sell2 = places.sell2;
s_sell3 = places.sell3;
s_lvl = places.lvl;
Debug.Log(s_lvl);
s_PF1 = places.PF1;
s_PF2 = places.PF2;
s_PF3 = places.PF3;
//if the pot has been activated, what pot skin and which plant
if (s_p1)
{
s_sp1 = places.sp1;
s_pp1 = places.pp1;
}
if (s_p2)
{
s_sp2 = places.sp2;
s_pp2 = places.pp2;
}
if (s_p3)
{
s_sp3 = places.sp3;
s_pp3 = places.pp3;
}
if (s_p4)
{
s_sp4 = places.sp4;
s_pp4 = places.pp4;
}
if (s_p5)
{
s_sp5 = places.sp5;
s_pp5 = places.pp5;
}
if (s_p6)
{
s_sp6 = places.sp6;
s_pp6 = places.pp6;
}
if (s_p7)
{
s_sp7 = places.sp7;
s_pp7 = places.pp7;
}
if (s_p8)
{
s_sp8 = places.sp8;
s_pp8 = places.pp8;
}
if (s_p9)
{
s_sp9 = places.sp9;
s_pp9 = places.pp9;
}
if (s_p10)
{
s_sp10 = places.sp10;
s_pp10 = places.pp10;
}
}
}
|
using CoreFrameWork.EventBus.Storage;
using CoreFrameWork.EventBus.Transaction;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Text;
namespace CoreFrameWork.EventBus.PostgreSql
{
/// <summary>
/// PostgreSql服务集合扩展
/// </summary>
public static class PostgreSqlServiceCollectionExtensions
{
public static EventBusBuilder AddSqlServer(this EventBusBuilder builder,
Action<EventBusPostgreSqlOptions> options = null)
{
builder.Service.TryAddSingleton<IStorage, PostgreSqlStorage>();
builder.Service.TryAddTransient<ITransaction, PostgreSqlTransaction>();
if (options != null)
builder.Service.Configure(options);
return builder;
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Plant : MonoBehaviour
{
public void Start()
{
_nutritionTimer = GameManager.Instance.GetPlantMinNutritionCooldown();
}
public enum Personality
{
Cute = 0,
Happy = 1,
Sad = 2,
Grumpy = 3,
Neutral = 4
}
[System.Serializable]
public class PlantEvent : UnityEvent<Plant> { }
[HideInInspector]
public PlantPot Pot;
private float _growth = 0f;
private bool _demandNutrition = false;
private float _nutritionTimer = 5f;
private float _demandTimer = 0f;
private float _witherTimer = 0f;
private bool _isDying;
[SerializeField]
private Personality _personality = Personality.Cute;
public Personality GetPersonality() => _personality;
[SerializeField]
private Transform _root;
[SerializeField]
private Transform _moodBubbleRoot;
[SerializeField]
private GrowthBlendshape _blendShape;
[SerializeField]
private PlantWitherVisualization _witherVisualization;
[SerializeField]
private float MaxSize = 5f;
[SerializeField]
private int _nutritionCost = 1;
public int GetNutritionCost() => _nutritionCost;
public PlantEvent OnPickEvent = new PlantEvent();
public PlantEvent OnDemandNutrition = new PlantEvent();
public PlantEvent OnNutritionGet = new PlantEvent();
public float GetPlantSize() => Mathf.Clamp01(_growth / GameManager.Instance.GetPlantMaxGrowthDuration());
public bool IsFullyGrown() => _growth >= GameManager.Instance.GetPlantMaxGrowthDuration();
public Transform GetMoodBubblePosition() => _moodBubbleRoot;
public void OnTapped()
{
if (!_demandNutrition) return;
if (NutrientsManager.Instance.Purchase(NutrientsManager.Instance.GetNutrientTypeByPersonality(_personality), GetNutritionCost()))
{
OnNutritionGiven();
}
}
public void SetPersonality(Personality type)
{
_personality = type;
}
private void Awake()
{
_nutritionTimer = GameManager.Instance.GetPlantMinNutritionCooldown();
//Avoid setting the correct growth state one frame too late.
_blendShape.SetBlendValue(GetPlantSize());
}
private void Update()
{
if (!_demandNutrition)
{
_growth += Time.deltaTime;
_blendShape.SetBlendValue(GetPlantSize());
_nutritionTimer -= Time.deltaTime;
if (_nutritionTimer <= 0)
{
TickNutritionNeed();
}
}
if (_demandNutrition)
{
_witherTimer += Time.deltaTime;
_witherVisualization.SetWitherLevel(_witherTimer / GameManager.Instance.GetPlantWitherDuration());
if (_witherTimer >= GameManager.Instance.GetPlantWitherDuration() * 0.5f && !_isDying)
{
_isDying = true;
AudioPlayer.Instance.AddDeathFlag(this);
}
if (_witherTimer >= GameManager.Instance.GetPlantWitherDuration())
{
Die();
}
}
}
private void TickNutritionNeed()
{
_demandTimer += Time.deltaTime;
if (_demandTimer >= GameManager.Instance.GetPlantNutritionDemandDelay())
{
_demandTimer = 0;
if (Random.value < GameManager.Instance.GetPlantNutritionNeedChance())
{
OnNeedNutrition();
}
}
}
private void OnNeedNutrition()
{
if (_demandNutrition) return;
OnDemandNutrition.Invoke(this);
_demandNutrition = true;
_demandTimer = 0f;
MoodBubbleManager.Instance.AllocateMoodBubble(this);
_witherTimer = 0f;
}
private void OnNutritionGiven()
{
if (!_demandNutrition) return;
OnNutritionGet.Invoke(this);
_demandNutrition = false;
_nutritionTimer = GameManager.Instance.GetPlantMinNutritionCooldown();
MoodBubbleManager.Instance.ReleaseMoodBubble(this);
AudioPlayer.Instance.ClearFlag(this);
_isDying = false;
_witherTimer = 0f;
_witherVisualization.SetWitherLevel(0f);
}
public void Reset()
{
MoodBubbleManager.Instance.ReleaseMoodBubble(this);
AudioPlayer.Instance.ClearFlag(this);
}
private void Die()
{
Reset();
if (Pot == null) return;
Pot.RemovePlant();
}
}
|
namespace JPAssets.Binary
{
/// <summary>
/// Indicates the order ("endianness") in which data may be stored.
/// </summary>
public enum Endianness
{
// Denotes little-endianness order (least significant byte comes first)
Little = 0,
// Denotes big-endianness order (most significant byte comes first)
Big = 1
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UISelectCareer : MonoBehaviour {
CLASS m_SelectClass = CLASS.None;
public GameObject[] m_CheckImage;
public UpgradesPage m_UpgradePage;
private static string[] m_ClassText = {
"Medical",
"Scientist",
"Athlete",
"Enterpreneur",
"Warrior",
"Musician"
};
private static string[] m_AbilityDes = {
"Use a free claim.",
"Undo an ability move.",
"Use a free challenge.",
"Switch puzzle sets.",
"Remove a puzzle piece.",
"Copy an ability."
};
private static string[] m_ClassUpgradeText = {
"Great choice! Medic’s have the ability to use a free claim.",
"Great choice! Scientist’s have the ability to undo an ability move.",
"Great choice! Athlete’s have the ability to use a free challenge.",
"Great choice! Entrepreneur’s have the ability to swap puzzle sets.",
"Great choice! Warrior’s have the ability to remove an opponent’s puzzle piece.",
"Great choice! Musician’s have the ability to copy your opponent’s ability."
};
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnSelectMedical()
{
m_SelectClass = CLASS.Medicial;
for (int i = 0; i < m_CheckImage.GetLength(0); i++)
{
m_CheckImage[i].SetActive(false);
}
m_CheckImage[0].SetActive(true);
}
public void OnSelectMusicial()
{
m_SelectClass = CLASS.Musician;
for (int i = 0; i < m_CheckImage.GetLength(0); i++)
{
m_CheckImage[i].SetActive(false);
}
m_CheckImage[1].SetActive(true);
}
public void OnSelectWarrior()
{
m_SelectClass = CLASS.Warrior;
for (int i = 0; i < m_CheckImage.GetLength(0); i++)
{
m_CheckImage[i].SetActive(false);
}
m_CheckImage[2].SetActive(true);
}
public void OnSelectEnterpreneur()
{
m_SelectClass = CLASS.Enterpreneur;
for (int i = 0; i < m_CheckImage.GetLength(0); i++)
{
m_CheckImage[i].SetActive(false);
}
m_CheckImage[3].SetActive(true);
}
public void OnSelecScientist()
{
m_SelectClass = CLASS.Scientist;
for (int i = 0; i < m_CheckImage.GetLength(0); i++)
{
m_CheckImage[i].SetActive(false);
}
m_CheckImage[4].SetActive(true);
}
public void OnSelecAthlete()
{
m_SelectClass = CLASS.Athlete;
for (int i = 0; i < m_CheckImage.GetLength(0); i++)
{
m_CheckImage[i].SetActive(false);
}
m_CheckImage[5].SetActive(true);
}
public void OnSelect()
{
if (m_SelectClass != CLASS.None)
{
GameManager.Instance.UpgradeTier(m_SelectClass);
GetComponent<CanvasScript>().Hide();
if (GameManager.Instance.GetPlayerProfile().m_FirstTimeExperience[3] == false)
{
GameManager.Instance.OnFirstTimeUserExperienceComplete(3);
GameManager.Instance.OnFirstTimeUserExperienceComplete(4);
SceneManager.Instance.GetCanvasByID(CanvasID.CANVAS_STORE).MoveOutToRight();
CanvasScript cs = SceneManager.Instance.GetCanvasByID(CanvasID.CANVAS_POPUP);
cs.GetComponent<UIPopup>().Show(m_ClassUpgradeText[(int)m_SelectClass - 1], 0, null, null, (int)CanvasID.CANVAS_PVP);
}
else
{
m_UpgradePage.Refresh();
}
}
}
public void Show()
{
GetComponent<CanvasScript>().Show();
}
public void ShowNextPopup()
{
CanvasScript cs = SceneManager.Instance.GetCanvasByID(CanvasID.CANVAS_POPUP);
cs.GetComponent<UIPopup>().Show("Tap your avatar to activate it’s ability. Avatar’s will glow when abilities are ready for use.", 0, null, null, (int)CanvasID.CANVAS_MAIN);
}
}
|
//-----------------------------------------------------------------------
// <copyright file="Form1.cs" company="VillageIdiot">
// Copyright (c) Village Idiot. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using ArzExplorer.Models;
using ArzExplorer.Properties;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using TQVaultAE.Domain.Contracts.Providers;
using TQVaultAE.Domain.Contracts.Services;
using TQVaultAE.Domain.Entities;
using TQVaultAE.Domain.Helpers;
using TQVaultAE.Logs;
using TQVaultAE.Services.Win32;
namespace ArzExplorer;
/// <summary>
/// Main Form for ArzExplorer
/// </summary>
public partial class MainForm : Form
{
const StringComparison noCase = StringComparison.OrdinalIgnoreCase;
private readonly ILogger Log;
private readonly IArcFileProvider arcProv;
private readonly IArzFileProvider arzProv;
private readonly IDBRecordCollectionProvider DBRecordCollectionProvider;
private readonly IBitmapService BitmapService;
private readonly IGamePathService GamePathService;
private readonly SoundServiceWin SoundService;
/// <summary>
/// Holds the initial size of the form.
/// </summary>
private Size initialSize;
#region MainForm
/// <summary>
/// Initializes a new instance of the Form1 class.
/// </summary>
public MainForm(
ILogger<MainForm> log
, IArcFileProvider arcFileProvider
, IArzFileProvider arzFileProvider
, IDBRecordCollectionProvider dBRecordCollectionProvider
, IBitmapService bitmapService
, IGamePathService gamePathService
, SoundServiceWin soundService
)
{
this.InitializeComponent();
this.Log = log;
this.arcProv = arcFileProvider;
this.arzProv = arzFileProvider;
this.DBRecordCollectionProvider = dBRecordCollectionProvider;
this.BitmapService = bitmapService;
this.GamePathService = gamePathService;
this.SoundService = soundService;
Assembly a = Assembly.GetExecutingAssembly();
this.assemblyName = a.GetName();
this.selectedFileToolStripMenuItem.Enabled = false;
this.allFilesToolStripMenuItem.Enabled = false;
this.initialSize = this.Size;
this.toolStripStatusLabel.Text = string.Empty;
// Hide Features that are not ready yet
// - Menu > Search
this.searchToolStripMenuItem.Visible = false;
// - Toolbar > Search
this.toolStripButtonSearchNext.Visible =
this.toolStripButtonSearchPrev.Visible =
this.toolStripTextBox.Visible =
this.toolStripSeparator4.Visible =
this.toolStripLabelSearch.Visible = false;
}
private void MainForm_Load(object sender, EventArgs e)
{
// Seek for all arc files
var arc = Directory.GetFiles(this.GamePathService.GamePathTQIT, "*.arc", SearchOption.AllDirectories);
ArcFileList = arc.ToDictionary(
k => k.Replace(this.GamePathService.GamePathTQIT + '\\', string.Empty).ToRecordId()
);
}
/// <summary>
/// Handler for clicking exit on the menu
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void HideAllBox()
{
StopSoundPlayer();
this.simpleSoundPlayer.Visible =
this.dataGridViewDetails.Visible =
this.textBoxDetails.Visible =
this.panelPicture.Visible = false;
this.toolStripStatusLabel.Text = string.Empty;
}
private void ShowPictureBox(Image bitmap)
{
StopSoundPlayer();
this.simpleSoundPlayer.Visible = false;
this.dataGridViewDetails.Visible = false;
this.textBoxDetails.Visible = false;
this.panelPicture.Visible = true;
this.pictureBoxItem.Image = bitmap;
this.pictureBoxItem.Size = bitmap.Size;
this.toolStripStatusLabel.Text = string.Format("PixelFormat : {0}, Size : {1}", bitmap.PixelFormat, bitmap.Size);
}
private void ShowSoundPlayer(RecordId soundId, SoundPlayer soundPlayer, byte[] soundWavData)
{
StopSoundPlayer();
this.dataGridViewDetails.Visible = false;
this.textBoxDetails.Visible = false;
this.panelPicture.Visible = false;
this.toolStripStatusLabel.Text = string.Format("Sound Name : {0}", Path.GetFileName(soundId.Raw));
this.simpleSoundPlayer.Visible = true;
this.simpleSoundPlayer.Dock = DockStyle.Fill;
this.simpleSoundPlayer.CurrentSoundId = soundId;
this.simpleSoundPlayer.CurrentSoundWavData = soundWavData;
this.simpleSoundPlayer.CurrentSoundPlayer = soundPlayer;
}
private void ShowGridView(int Count)
{
StopSoundPlayer();
this.dataGridViewDetails.Visible = true;
this.dataGridViewDetails.Dock = DockStyle.Fill;
this.simpleSoundPlayer.Visible = false;
this.textBoxDetails.Visible = false;
this.panelPicture.Visible = false;
this.toolStripStatusLabel.Text = string.Format("Record Count : {0}", Count);
}
private void StopSoundPlayer()
{
if (this.simpleSoundPlayer.Visible)
this.simpleSoundPlayer.CurrentSoundPlayer?.Stop();
}
private void ShowTextboxDetail(int Count)
{
StopSoundPlayer();
this.simpleSoundPlayer.Visible = false;
this.dataGridViewDetails.Visible = false;
this.textBoxDetails.Visible = true;
this.textBoxDetails.Dock = DockStyle.Fill;
this.panelPicture.Visible = false;
this.toolStripStatusLabel.Text = string.Format("Line Count : {0}", Count);
}
#endregion
#region Open File
internal TQFileInfo SelectedFile;
/// <summary>
/// Resolve database file
/// </summary>
string DataBasePath => Path.Combine(this.GamePathService.GamePathTQIT, @"Database\database.arz");
private readonly Dictionary<string, TQFileInfo> TQFileOpened = new();
/// <summary>
/// Found Arc Files
/// </summary>
Dictionary<RecordId, string> ArcFileList;
private void toolStripButtonLoadDataBase_Click(object sender, EventArgs e)
{
try
{
this.OpenFile(this.DataBasePath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
/// <summary>
/// Opens a file and updates the tree view.
/// </summary>
/// <param name="filename">Name of the file we want to open.</param>
private void OpenFile(string filename)
{
if (string.IsNullOrEmpty(filename))
return;
// Already loaded
if (this.TQFileOpened.Any(kv => kv.Value.SourceFile == filename))
return;
var fileInfo = new TQFileInfo();
fileInfo.SourceFile = filename;
if (string.IsNullOrEmpty(fileInfo.SourceFile))
{
MessageBox.Show("You must enter a valid source file path.");
return;
}
// See if path exists and create it if necessary
string fullSrcPath = Path.GetFullPath(fileInfo.SourceFile);
if (!File.Exists(fullSrcPath))
{
// they did not give us a file
MessageBox.Show("You must specify a file!");
return;
}
// Try to read it as an ARC file since those have a header.
fileInfo.ARCFile = new ArcFile(fileInfo.SourceFile);
if (arcProv.Read(fileInfo.ARCFile))
{
fileInfo.FileType = CompressedFileType.ArcFile;
}
else
{
fileInfo.ARCFile = null;
fileInfo.FileType = CompressedFileType.Unknown;
}
// Try reading the file as an ARZ file.
if (fileInfo.FileType == CompressedFileType.Unknown)
{
// Read our ARZ file into memory.
fileInfo.ARZFile = new ArzFile(fileInfo.SourceFile);
if (arzProv.Read(fileInfo.ARZFile))
{
fileInfo.FileType = CompressedFileType.ArzFile;
}
else
{
fileInfo.ARZFile = null;
fileInfo.FileType = CompressedFileType.Unknown;
}
}
// We failed reading the file
// so we just clear everything out.
if (fileInfo.FileType == CompressedFileType.Unknown)
{
this.Text = this.assemblyName.Name;
this.treeViewTOC.Nodes.Clear();
this.selectedFileToolStripMenuItem.Enabled = false;
this.allFilesToolStripMenuItem.Enabled = false;
this.textBoxDetails.Lines = null;
MessageBox.Show(string.Format("Error Reading {0}", fileInfo.SourceFile));
return;
}
this.selectedFileToolStripMenuItem.Enabled = true;
this.allFilesToolStripMenuItem.Enabled = true;
this.hideZeroValuesToolStripMenuItem.Enabled = fileInfo.FileType == CompressedFileType.ArzFile;
UpdateTitle(fileInfo);
this.textBoxDetails.Lines = null;
this.toolStripStatusLabel.Text = string.Empty;
this.TQFileOpened.Add(fullSrcPath, fileInfo);
this.SelectedFile = fileInfo;
this.BuildTreeView();
}
private void UpdateTitle(TQFileInfo fileInfo)
{
this.Text = string.Format("{0} - {1}", this.assemblyName.Name, fileInfo.SourceFile);
}
/// <summary>
/// Handler for clicking Open on the menu. Opens a file.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
{
using OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Filter = "Compressed TQ files (*.arz;*.arc)|*.arz;*.arc|All files (*.*)|*.*";
openDialog.FilterIndex = 1;
openDialog.RestoreDirectory = true;
// Try to read the game path
string startPath = this.GamePathService.GamePathTQIT;
// If the registry fails then default to the save folder.
if (startPath.Length < 1)
{
startPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games", "Titan Quest");
}
openDialog.InitialDirectory = startPath;
DialogResult result = openDialog.ShowDialog();
if (result == DialogResult.OK)
{
this.OpenFile(openDialog.FileName);
}
}
/// <summary>
/// Drag and drop handler
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">DragEventArgs data</param>
private void Form1_DragDrop(object sender, DragEventArgs e)
{
// Handle FileDrop data.
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
// Assign the file names to a string array, in
// case the user has selected multiple files.
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
try
{
this.OpenFile(files[0]);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
}
/// <summary>
/// Handler for entering the form with a drag item. Changes the cursor.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">DragEventArgs data</param>
private void Form1_DragEnter(object sender, DragEventArgs e)
{
// If the data is a file display the copy cursor.
e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None;
}
#endregion
#region Extract selected file
/// <summary>
/// Handler for clicking extract selected file.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void SelectedFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.SelectedFile.DestFile) || this.SelectedFile.FileType == CompressedFileType.Unknown)
return;
string filename = null;
using SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "TQ files (*.txt;*.dbr;*.tex;*.msh;*.anm;*.fnt;*.qst;*.pfx;*.ssh)|*.txt;*.dbr;*.tex;*.msh;*.anm;*.fnt;*.qst;*.pfx;*.ssh|All files (*.*)|*.*";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Save the Titan Quest File";
string startPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games", "Titan Quest");
saveFileDialog.InitialDirectory = startPath;
saveFileDialog.FileName = Path.GetFileName(this.SelectedFile.DestFile);
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
filename = saveFileDialog.FileName;
if (this.SelectedFile.FileType == CompressedFileType.ArzFile)
{
DBRecordCollectionProvider.Write(this.SelectedFile.Records, Path.GetDirectoryName(filename), Path.GetFileName(filename));
}
else if (this.SelectedFile.FileType == CompressedFileType.ArcFile)
{
arcProv.Write(
this.SelectedFile.ARCFile
, Path.GetDirectoryName(filename)
, this.SelectedFile.DestFile
, Path.GetFileName(filename)
);
}
}
}
#endregion
#region Extract all files
/// <summary>
/// Handler for clicking extract all files from the menu.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void AllFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.SelectedFile.FileType == CompressedFileType.Unknown)
return;
if ((this.SelectedFile.FileType == CompressedFileType.ArzFile && this.SelectedFile.ARZFile == null)
|| (this.SelectedFile.FileType == CompressedFileType.ArcFile && this.SelectedFile.ARCFile == null)
)
{
MessageBox.Show("Please Open a source file.");
return;
}
using (FolderBrowserDialog browseDialog = new FolderBrowserDialog())
{
browseDialog.Description = "Select the destination folder for the extracted database records";
browseDialog.ShowNewFolderButton = true;
string startPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games", "Titan Quest");
browseDialog.SelectedPath = startPath;
DialogResult result = browseDialog.ShowDialog();
if (result != DialogResult.OK)
return;
this.SelectedFile.DestDirectory = browseDialog.SelectedPath;
}
string fullDestPath = null;
if (string.IsNullOrEmpty(this.SelectedFile.DestDirectory))
{
MessageBox.Show("You must enter a valid destination folder.");
return;
}
// See if path exists and create it if necessary
if (!string.IsNullOrEmpty(this.SelectedFile.DestDirectory))
{
fullDestPath = Path.GetFullPath(this.SelectedFile.DestDirectory);
}
if (File.Exists(fullDestPath))
{
// they did not give us a file
MessageBox.Show("You must specify a folder, not a file!");
return;
}
if (!Directory.Exists(fullDestPath))
{
// see if they want to create it
string q = string.Format("{0} does not exist. Would you like to create it now?", fullDestPath);
if (MessageBox.Show(q, "Create folder?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
return;
Directory.CreateDirectory(fullDestPath);
}
var form = Program.ServiceProvider.GetService<ExtractProgress>();
form.BaseFolder = fullDestPath;
form.ShowDialog();
}
#endregion
#region About
/// <summary>
/// Handler for clicking Help->About
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox d = new AboutBox();
d.ShowDialog();
}
#endregion
#region TreeViewTOC
NodeTag SelectedTag => this.treeViewTOC.SelectedNode.Tag as NodeTag;
/// <summary>
/// Treeview node database
/// </summary>
Dictionary<RecordId, TreeNode> dicoNodes = new();
/// <summary>
/// Builds the tree view. Assumes the list is pre-sorted.
/// </summary>
private void BuildTreeView()
{
// Display a wait cursor while the TreeNodes are being created.
Cursor.Current = Cursors.WaitCursor;
try
{
this.treeViewTOC.BeginUpdate();
RecordId[] dataRecords;
if (this.SelectedFile.FileType == CompressedFileType.ArzFile)
dataRecords = arzProv.GetKeyTable(this.SelectedFile.ARZFile);
else if (this.SelectedFile.FileType == CompressedFileType.ArcFile)
dataRecords = arcProv.GetKeyTable(this.SelectedFile.ARCFile);
else
return;
// We failed so return.
if (dataRecords == null)
return;
TreeNode rootNode = new(), arcRootNode = null;
string arcPrefix = string.Empty;
if (dicoNodes.Any())
rootNode = dicoNodes[RecordId.Empty];// Get it back
else
dicoNodes.Add(RecordId.Empty, rootNode);// First time
if (this.SelectedFile.FileType == CompressedFileType.ArcFile)
{
var tokens = this.SelectedFile.SourceFileId.TokensRaw;
// Node Xpack
var arcPrefixXpack = tokens[tokens.Count - 2];
if (!arcPrefixXpack.StartsWith("XPACK", StringComparison.OrdinalIgnoreCase))
arcPrefixXpack = string.Empty;
if (arcPrefixXpack != string.Empty)
GetRootNode(arcPrefixXpack, rootNode, out arcRootNode);
// Node File
arcPrefix = Path.GetFileNameWithoutExtension(tokens[tokens.Count - 1]);
if (arcPrefixXpack == string.Empty)
GetRootNode(arcPrefix, rootNode, out arcRootNode);
else
{
arcPrefix = arcPrefixXpack + '\\' + arcPrefix;
GetRootNode(arcPrefix, arcRootNode, out arcRootNode);
}
}
for (int recIdx = 0; recIdx < dataRecords.Length; recIdx++)
{
RecordId recordID = arcPrefix == string.Empty ? dataRecords[recIdx] : Path.Combine(arcPrefix, dataRecords[recIdx].Raw);
for (int tokIdx = 0; tokIdx < recordID.TokensRaw.Count; tokIdx++)
{
var token = recordID.TokensRaw[tokIdx];
var parent = recordID.TokensRaw.Take(tokIdx).JoinString("\\").ToRecordId();
var parentnode = dicoNodes[parent];
var currnodeKey = (parent.IsEmpty ? token : parent + '\\' + token).ToRecordId();
if (parentnode.Nodes.ContainsKey(currnodeKey))
continue;
else
{
var currentNode = new TreeNode()
{
Name = currnodeKey,
Text = token,
ToolTipText = this.SelectedFile.SourceFile
};
currentNode.Tag = new NodeTag
{
thisNode = currentNode,
File = this.SelectedFile,
Thread = recordID,
Key = currnodeKey,
RecIdx = recIdx,
TokIdx = tokIdx,
Text = token,
};
parentnode.Nodes.Add(currentNode);
dicoNodes.Add(currnodeKey, currentNode);
}
}
}
// Always add the newcomers
this.treeViewTOC.Nodes.Add(rootNode.Nodes[rootNode.Nodes.Count - 1]);
this.treeViewTOC.EndUpdate();
}
finally
{
// Reset the cursor to the default for all controls.
Cursor.Current = Cursors.Default;
}
}
void GetRootNode(string arcPrefix, TreeNode rootNode, out TreeNode arcRootNode)
{
var arcPrefixId = arcPrefix.ToRecordId();
if (!dicoNodes.TryGetValue(arcPrefixId, out arcRootNode))
{
arcRootNode = new TreeNode()
{
Name = arcPrefix,
Text = arcPrefixId.TokensRaw.Last(),
ToolTipText = this.SelectedFile.SourceFile
};
arcRootNode.Tag = new NodeTag
{
thisNode = arcRootNode,
File = this.SelectedFile,
Thread = null,
Key = arcPrefix,
RecIdx = 0,
TokIdx = 0,
Text = arcRootNode.Text,
};
dicoNodes.Add(arcPrefixId, arcRootNode);
rootNode.Nodes.Add(arcRootNode);
}
}
/// <summary>
/// Handler for clicking on a treeView item
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">TreeViewEventArgs data</param>
private void TreeViewTOC_AfterSelect(object sender, TreeViewEventArgs e)
{
// Make sure we have selected the last child
// otherwise this will be a directory.
if (this.treeViewTOC.SelectedNode.GetNodeCount(false) == 0)
{
var tag = this.SelectedTag;
this.SelectedFile = tag.File;
UpdateTitle(this.SelectedFile);
this.SelectedFile.DestFile
= this.textBoxPath.Text
= this.treeViewTOC.SelectedNode.FullPath;
try
{
List<string> recordText = new List<string>();
if (this.SelectedFile.FileType == CompressedFileType.ArzFile)
{
this.SelectedFile.Records = arzProv.GetRecordNotCached(this.SelectedFile.ARZFile, this.SelectedFile.DestFile);
foreach (Variable variable in this.SelectedFile.Records)
{
if (variable.IsValueNonZero() || !hideZeroValuesToolStripMenuItem.Checked)
recordText.Add(variable.ToString());
}
PopulateGridView(recordText);
ShowGridView(recordText.Count);
StackNavigation();
}
else if (this.SelectedFile.FileType == CompressedFileType.ArcFile)
{
string extension = Path.GetExtension(tag.Key.TokensNormalized.Last());
var arcDataRecordId = tag.Key;
if (tag.Key.Normalized.Contains("XPACK"))
arcDataRecordId = tag.Key.TokensRaw.Skip(1).JoinString("\\").ToRecordId();
switch (extension)
{
case ".TXT":
if (!tag.RecordText.Any())
{
tag.RawData = arcProv.GetData(this.SelectedFile.ARCFile, arcDataRecordId);
if (tag.RawData == null)
return;
// now read it like a text file
using (StreamReader reader = new StreamReader(new MemoryStream(tag.RawData), Encoding.Default))
{
string line;
while ((line = reader.ReadLine()) != null)
{
tag.RecordText.Add(line);
}
}
}
this.textBoxDetails.Lines = tag.RecordText.ToArray();
ShowTextboxDetail(tag.RecordText.Count);
StackNavigation();
break;
case ".TEX":
if (tag.Bitmap is null)
{
tag.RawData = arcProv.GetData(this.SelectedFile.ARCFile, arcDataRecordId);
if (tag.RawData == null)
return;
tag.Bitmap = BitmapService.LoadFromTexMemory(tag.RawData, 0, tag.RawData.Length);
}
if (tag.Bitmap != null)
{
ShowPictureBox(tag.Bitmap);
StackNavigation();
}
break;
case ".MP3":
case ".WAV":
if (tag.SoundPlayer is null)
{
tag.RawData = arcProv.GetData(this.SelectedFile.ARCFile, arcDataRecordId);
if (tag.RawData == null)
return;
SoundService.SetSoundResource(arcDataRecordId, tag.RawData);
tag.SoundPlayer = SoundService.GetSoundPlayer(arcDataRecordId);
}
// Display SoundPlayer
if (tag.SoundPlayer != null)
{
ShowSoundPlayer(
arcDataRecordId
, tag.SoundPlayer
, SoundService.GetSoundResource(arcDataRecordId)
);
StackNavigation();
}
break;
default:
HideAllBox();
this.SelectedFile.DestFile = null;
this.textBoxDetails.Lines = null;
break;
}
}
}
catch (Exception ex)
{
this.Log.ErrorException(ex);
}
}
else
{
this.SelectedFile.DestFile = null;
this.textBoxDetails.Lines = null;
}
}
#endregion
#region Griv View
static char[] PopulateGridView_splitChars = new[] { ',' };
static DataGridViewCellStyle PopulateGridView_hyperLinkCellStyle = new DataGridViewCellStyle
{
Font = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Underline),
ForeColor = Color.Blue,
};
private void PopulateGridView(List<string> recordText)
{
var grd = dataGridViewDetails;
grd.Rows.Clear();
// Init data
foreach (string line in recordText)
{
string[] values = line.Split(PopulateGridView_splitChars, StringSplitOptions.RemoveEmptyEntries);
grd.Rows.Add(values);
}
// Apply link style
for (int i = 0; i < grd.RowCount; i++)
{
var cell = grd.Rows[i].Cells[1];
var val = cell.Value?.ToString() ?? string.Empty;
if (val.EndsWith(".DBR", noCase)
|| val.EndsWith(".TEX", noCase)
|| val.EndsWith(".TXT", noCase)
|| val.EndsWith(".WAV", noCase)
|| val.EndsWith(".MP3", noCase)
) cell.Style = PopulateGridView_hyperLinkCellStyle;
}
}
private void hideZeroValuesToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.SelectedFile.Records != null)
{
List<string> recordText = new List<string>();
foreach (Variable variable in this.SelectedFile.Records)
{
if (variable.IsValueNonZero() || !hideZeroValuesToolStripMenuItem.Checked)
recordText.Add(variable.ToString());
}
PopulateGridView(recordText);
}
}
#endregion
#region Clipboard
private void textBoxPath_MouseDoubleClick(object sender, MouseEventArgs e)
{
CopyPath();
}
private void CopyPath()
{
Clipboard.SetText(this.textBoxPath.Text);
}
private void textBoxDetails_MouseDoubleClick(object sender, MouseEventArgs e)
{
CopyTXT();
}
private void CopyTXT()
{
Clipboard.SetText(this.textBoxDetails.Text);
}
private void copyPathToolStripMenuItem_Click(object sender, EventArgs e)
{
CopyPath();
}
private void copyTXTToolStripMenuItem_Click(object sender, EventArgs e)
{
CopyTXT();
}
private void copyDBRToolStripMenuItem_Click(object sender, EventArgs e)
{
// DataGridView into Clipboard
DataGridViewCell currCell = null;
if (this.dataGridViewDetails.SelectedCells.Count > 0)
currCell = this.dataGridViewDetails.SelectedCells[0];
this.dataGridViewDetails.MultiSelect = true;
// Select all the cells
this.dataGridViewDetails.SelectAll();
// Copy selected cells to DataObject
DataObject dataObject = this.dataGridViewDetails.GetClipboardContent();
// Get the text of the DataObject, and serialize it to a file
Clipboard.SetDataObject(dataObject);
// Restore normal state
this.dataGridViewDetails.MultiSelect = false;
if (currCell is not null)
currCell.Selected = true;
}
private void copyBitmapToolStripMenuItem_Click(object sender, EventArgs e)
{
Clipboard.SetImage(this.pictureBoxItem.Image);
}
private void copySoundToolStripMenuItem_Click(object sender, EventArgs e)
{
Clipboard.SetAudio(this.simpleSoundPlayer.CurrentSoundWavData);
}
#endregion
#region Caps Treeview
private void toolStripButtonCaps_CheckedChanged(object sender, EventArgs e)
{
TOCCapsToggle();
}
private void capsToolStripMenuItem_Click(object sender, EventArgs e)
{
toolStripButtonCaps.Checked = !toolStripButtonCaps.Checked;
}
private void TOCCapsToggle()
{
toolStripButtonCaps.Image = toolStripButtonCaps.Checked ? Resources.CapsDown.ToBitmap() : Resources.CapsUP.ToBitmap();
this.treeViewTOC.BeginUpdate();
foreach (var node in this.dicoNodes)
{
if (node.Key != string.Empty)
{
var tag = node.Value.Tag as NodeTag;
tag.thisNode.Text = toolStripButtonCaps.Checked
? tag.TextU
: tag.Text;
}
}
this.treeViewTOC.EndUpdate();
}
#endregion
#region NavHistory
private readonly List<TreeNode> NavHistory = new();
private readonly AssemblyName assemblyName;
private int NavHistoryIndex;
bool _StackNavigationDisabled = false;
private void StackNavigation()
{
if (_StackNavigationDisabled)
return;
NavHistory.Add(this.treeViewTOC.SelectedNode);
NavHistoryIndex = NavHistory.Count - 1;
}
private void dataGridViewDetails_CellClick(object sender, DataGridViewCellEventArgs e)
{
// IsHeader
if (e.RowIndex < 0 || e.ColumnIndex < 0)
return;
var cell = dataGridViewDetails.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell.Style == PopulateGridView_hyperLinkCellStyle)
{
var value = cell.Value.ToString();
var values = value.Split(';');
NavigateTo(values.First());
}
}
private void NavigateTo(RecordId recordId)
{
// Already loaded
if (dicoNodes.TryGetValue(recordId, out var node))
{
this.treeViewTOC.SelectedNode = node;
this.treeViewTOC.Focus();
return;
}
// auto load file
// Resolve file name
string xPackVersion, fileToken, fileName, dicoKey;
if (recordId.Normalized.StartsWith("XPACK"))
{
xPackVersion = recordId.TokensNormalized[0];
fileToken = recordId.TokensNormalized[1];
fileName = $"{fileToken}.ARC";
dicoKey = @$"RESOURCES\{xPackVersion}\{fileName}";
}
else if (recordId.Normalized.EndsWith(".MP3") || recordId.Normalized.EndsWith(".WAV"))
{
xPackVersion = string.Empty;
fileToken = recordId.TokensNormalized[0];
fileName = $"{fileToken}.ARC";
dicoKey = @$"AUDIO\{fileName}";
}
else
{
xPackVersion = string.Empty;
fileToken = recordId.TokensNormalized[0];
fileName = $"{fileToken}.ARC";
dicoKey = @$"RESOURCES\{fileName}";
}
if (ArcFileList.TryGetValue(dicoKey, out var fullpath))
{
// Add TOC to treeview
this.OpenFile(fullpath);
// Navigate
if (dicoNodes.TryGetValue(recordId, out var found))
{
this.treeViewTOC.SelectedNode = found;
this.treeViewTOC.Focus();
return;
}
// Database orphan ?
this.toolStripStatusLabel.Text = @$"Unable to find ""{recordId}""";
}
}
private void previousToolStripMenuItem_Click(object sender, EventArgs e)
{
GoPrev();
}
private void nextToolStripMenuItem_Click(object sender, EventArgs e)
{
GoNext();
}
private void toolStripButtonPrev_Click(object sender, EventArgs e)
{
GoPrev();
}
private void GoPrev()
{
_StackNavigationDisabled = true;
if (NavHistory.Count > 0 && NavHistoryIndex > 0)
{
NavHistoryIndex--;
NavHistoryGoto();
}
_StackNavigationDisabled = false;
}
private void NavHistoryGoto()
{
var tag = NavHistory[NavHistoryIndex].Tag as NodeTag;
this.SelectedFile = tag.File;
this.treeViewTOC.SelectedNode = NavHistory[NavHistoryIndex];
this.treeViewTOC.Focus();
}
private void toolStripButtonNext_Click(object sender, EventArgs e)
{
GoNext();
}
private void GoNext()
{
_StackNavigationDisabled = true;
if (NavHistoryIndex < NavHistory.Count - 1)
{
NavHistoryIndex++;
NavHistoryGoto();
}
_StackNavigationDisabled = false;
}
private void toolStripButtonClearHistory_Click(object sender, EventArgs e)
{
this.NavHistory.Clear();
this.NavHistoryIndex = -1;
}
#endregion
#region Search
// TODO ARZ Explorer Search stuff!
private void toolStripButtonSearchPrev_Click(object sender, EventArgs e)
{
}
private void toolStripButtonSearchNext_Click(object sender, EventArgs e)
{
}
private void searchNextToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void findPreviousToolStripMenuItem_Click(object sender, EventArgs e)
{
}
#endregion
}
|
using System;
using System.Collections.Generic;
using BirthdayGreetings;
public interface IEmployeeRepository
{
IEnumerable<Employee> Get(Func<Employee, bool> func);
} |
using SchoolDiary.Data.Entities;
using Microsoft.EntityFrameworkCore;
namespace SchoolDiary.Data
{
public class SchoolDiaryDbContext : DbContext
{
public SchoolDiaryDbContext(DbContextOptions<SchoolDiaryDbContext> options) : base(options)
{
}
public virtual DbSet<Teacher> Teachers { get; set; }
public virtual DbSet<Student> Students { get; set; }
public virtual DbSet<Grade> Grades { get; set; }
public virtual DbSet<Subject> Subjects { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Grade>()
.HasOne(grade => grade.Student)
.WithMany()
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Grade>()
.HasOne(grade => grade.Subject)
.WithMany()
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Grade>()
.HasOne(grade => grade.Teacher)
.WithMany()
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Student>()
.HasMany(student => student.Grades)
.WithOne(grade => grade.Student)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Teacher>()
.HasMany(teacher => teacher.Subjects)
.WithOne()
.OnDelete(DeleteBehavior.SetNull);
}
}
} |
using CrawlerSelenium.CrawlerSelenium;
namespace CrawlerSelenium
{
public class RequestManager
{
public static string GetHtmlContent(string url)
{
try
{
DriverContext context = new DriverContext();
context.Start();
//context.Driver=
context.Driver.Navigate().GoToUrl(url);
var html = context.Driver.PageSource;
return html;
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
return "";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using OmniSharp.Extensions.JsonRpc.Generators.Contexts;
using OmniSharp.Extensions.JsonRpc.Generators.Strategies;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace OmniSharp.Extensions.JsonRpc.Generators
{
[Generator]
public class GenerateHandlerMethodsGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var _attributes = "GenerateHandler,GenerateRequestMethods,GenerateHandlerMethods";
var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider(
(syntaxNode, _) =>
syntaxNode is TypeDeclarationSyntax tds
and (ClassDeclarationSyntax or RecordDeclarationSyntax or InterfaceDeclarationSyntax)
&& tds.AttributeLists.ContainsAttribute(_attributes), (syntaxContext, _) => syntaxContext
)
.Combine(context.CompilationProvider)
.Select(
(tuple, _) =>
{
var (syntaxContext, compilaiton) = tuple;
var additionalUsings = new HashSet<string>
{
"System",
"System.Collections.Generic",
"System.Threading",
"System.Threading.Tasks",
"MediatR",
"Microsoft.Extensions.DependencyInjection"
};
GeneratorData? actionItem = null;
Diagnostic? diagnostic = null;
try
{
actionItem = GeneratorData.Create(
compilaiton, (TypeDeclarationSyntax)syntaxContext.Node, syntaxContext.SemanticModel, additionalUsings
);
}
catch (Exception e)
{
diagnostic = Diagnostic.Create(
GeneratorDiagnostics.Exception, syntaxContext.Node.GetLocation(), e.Message,
e.StackTrace ?? string.Empty
);
Debug.WriteLine(e);
Debug.WriteLine(e.StackTrace);
}
return ( actionItem, diagnostic, additionalUsings );
}
);
context.RegisterSourceOutput(syntaxProvider, GenerateHandlerMethods);
context.RegisterSourceOutput(
syntaxProvider.Where(z => z.actionItem is { }).SelectMany((z, _) => z.actionItem!.AssemblyJsonRpcHandlersAttributeArguments).Collect(),
GenerateAssemblyJsonRpcHandlers
);
}
private void GenerateHandlerMethods(
SourceProductionContext context, (GeneratorData? actionItem, Diagnostic? diagnostic, HashSet<string> additionalUsings) valueTuple
)
{
var (actionItem, diagnostic, additionalUsings) = valueTuple;
// context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Message, null, $"candidate: {candidateClass.Identifier.ToFullString()}"));
// can this be async???
context.CancellationToken.ThrowIfCancellationRequested();
if (actionItem is null)
{
context.ReportDiagnostic(diagnostic!);
return;
}
var candidateClass = actionItem.TypeDeclaration;
var members = CompilationUnitGeneratorStrategies.Aggregate(
new List<MemberDeclarationSyntax>(), (m, strategy) =>
{
try
{
m.AddRange(strategy.Apply(context, actionItem));
}
catch (Exception e)
{
context.ReportDiagnostic(
Diagnostic.Create(
GeneratorDiagnostics.Exception, candidateClass.GetLocation(),
$"Strategy {strategy.GetType().FullName} failed!" + " - " + e.Message, e.StackTrace ?? string.Empty
)
);
Debug.WriteLine($"Strategy {strategy.GetType().FullName} failed!");
Debug.WriteLine(e);
Debug.WriteLine(e.StackTrace);
}
return m;
}
);
if (!members.Any()) return;
var namespacesMapping = new Dictionary<string, string[]>
{
["OmniSharp.Extensions.DebugAdapter"] = new[]
{
"OmniSharp.Extensions.DebugAdapter.Protocol", "OmniSharp.Extensions.DebugAdapter.Protocol.Models",
"OmniSharp.Extensions.DebugAdapter.Protocol.Events", "OmniSharp.Extensions.DebugAdapter.Protocol.Requests"
},
["OmniSharp.Extensions.LanguageProtocol"] = new[]
{ "OmniSharp.Extensions.LanguageServer.Protocol", "OmniSharp.Extensions.LanguageServer.Protocol.Models" },
};
foreach (var assembly in actionItem.Compilation.References.Select(actionItem.Compilation.GetAssemblyOrModuleSymbol)
.OfType<IAssemblySymbol>()
.Concat(new[] { actionItem.Compilation.Assembly }))
{
if (namespacesMapping.TryGetValue(assembly.Name, out var additionalNamespaceUsings))
{
foreach (var item in additionalNamespaceUsings)
{
additionalUsings.Add(item);
}
}
}
var existingUsings = candidateClass.SyntaxTree.GetCompilationUnitRoot()
.Usings.Select(x => x.WithoutTrivia())
.Union(
additionalUsings.Except(
candidateClass.SyntaxTree.GetCompilationUnitRoot()
.Usings.Where(z => z.Alias == null)
.Select(z => z.Name.ToFullString())
)
.Except(new[] { "<global namespace>" }) // I think there is a better way... but for now..
.Distinct()
.Select(z => UsingDirective(IdentifierName(z)))
)
.OrderBy(x => x.Name.ToFullString())
.ToImmutableArray();
var cu = CompilationUnit(List<ExternAliasDirectiveSyntax>(), List(existingUsings), List<AttributeListSyntax>(), List(members));
context.AddSource(
$"{candidateClass.Identifier.Text}{( candidateClass.Arity > 0 ? candidateClass.Arity.ToString() : "" )}.cs",
cu.NormalizeWhitespace().GetText(Encoding.UTF8)
);
}
private void GenerateAssemblyJsonRpcHandlers(SourceProductionContext context, ImmutableArray<AttributeArgumentSyntax> handlers)
{
var namespaces = new HashSet<string> { "OmniSharp.Extensions.JsonRpc" };
if (handlers.Any())
{
var cu = CompilationUnit()
.WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z)))));
while (handlers.Length > 0)
{
var innerTypes = handlers.Take(10).ToArray();
handlers = handlers.Skip(10).ToImmutableArray();
cu = cu.AddAttributeLists(
AttributeList(
AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)),
SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes))))
)
);
}
context.AddSource("GeneratedAssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8));
}
}
private static readonly ImmutableArray<ICompilationUnitGeneratorStrategy> CompilationUnitGeneratorStrategies = GetCompilationUnitGeneratorStrategies();
private static ImmutableArray<ICompilationUnitGeneratorStrategy> GetCompilationUnitGeneratorStrategies()
{
var actionContextStrategies = ImmutableArray.Create<IExtensionMethodContextGeneratorStrategy>(
new WarnIfResponseRouterIsNotProvidedStrategy(),
new OnNotificationMethodGeneratorWithoutRegistrationOptionsStrategy(),
new OnNotificationMethodGeneratorWithRegistrationOptionsStrategy(),
new OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy(false),
new OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy(true),
new OnRequestTypedResolveMethodGeneratorWithoutRegistrationOptionsStrategy(),
new OnRequestMethodGeneratorWithRegistrationOptionsStrategy(false),
new OnRequestMethodGeneratorWithRegistrationOptionsStrategy(true),
new OnRequestTypedResolveMethodGeneratorWithRegistrationOptionsStrategy(),
new SendMethodNotificationStrategy(),
new SendMethodRequestStrategy()
);
var actionStrategies = ImmutableArray.Create<IExtensionMethodGeneratorStrategy>(
new EnsureNamespaceStrategy(),
new HandlerRegistryActionContextRunnerStrategy(actionContextStrategies),
new RequestProxyActionContextRunnerStrategy(actionContextStrategies),
new TypedDelegatingHandlerStrategy()
);
var compilationUnitStrategies = ImmutableArray.Create<ICompilationUnitGeneratorStrategy>(
new HandlerGeneratorStrategy(),
new ExtensionMethodGeneratorStrategy(actionStrategies)
);
return compilationUnitStrategies;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HackerrankSolutionConsole
{
class mark_and_toys : Challenge
{
public override void Main(string[] args)
{
string[] inputs = Console.ReadLine().Split(' ');
int T = Convert.ToInt32(inputs[0]);
int K = Convert.ToInt32(inputs[1]);
inputs = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(inputs, Int32.Parse);
Array.Sort(arr);
int spent = 0;
int count = 0;
for (int n = 0; n < T; n++)
{
if (spent + arr[n] <= K)
{
spent += arr[n];
count++;
}
//else
//break;
}
Console.WriteLine(count);
}
public mark_and_toys()
{
Name = "Mark and Toys";
Path = "mark-and-toys";
Difficulty = Difficulty.Easy;
Domain = Domain.Algorithms;
Subdomain = Subdomain.Greedy;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateBlade : MonoBehaviour {
public int fanSpeed = 120;
//speed of rotation
void Update() {
//rotate around the local Y axis
transform.Rotate(Vector3.up * fanSpeed * Time.deltaTime, Space.Self);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace JisalimuOnline.Models
{
public class JisalimuContext: DbContext
{
public JisalimuContext():base("JisalimuContext")
{
}
public DbSet<User> User { get; set; }
public DbSet<Doctor> Doctors { get; set; }
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
namespace NetFabric.Hyperlinq
{
[ExcludeFromCodeCoverage]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method)]
public sealed class GeneratorIgnoreAttribute : Attribute
{
public bool Value { get; }
public GeneratorIgnoreAttribute(bool value = true)
=> Value = value;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.