text stringlengths 13 6.01M |
|---|
using UnityEngine;
using System.Collections;
public class controller : MonoBehaviour {
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
// Use this for initialization
private Vector3 moveDirection = Vector3.zero;
void Start () {
}
// Update is called once per frame
void Update () {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
// We are grounded, so recalculate
// move direction directly from axes
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0,
Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
transform.Rotate (Vector3.up * Input.GetAxis ("Mouse X") * 2);
controller.Move(moveDirection * Time.deltaTime);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : Person {
public Camera firstPerson;
public Camera overhead;
GameObject result;
void showOverhead(){
firstPerson.enabled = false;
overhead.enabled = true;
}
void showFirstPerson(){
firstPerson.enabled = true;
overhead.enabled = false;
}
// Use this for initialization
//center is -0.5f,-0.5f
//x bounds are 0 and -1
//z bounds are 0 and -1
void Start () {
//StartCoroutine(towerCoroutine());
}
// Update is called once per frame
void Update () {
}
private void FixedUpdate()
{
//if enemy goes in your square, then enter first person
}
}
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Timers;
namespace ZebraUDP
{
public class ZebraPrinter : IPrinter
{
private string IP { get; set; }
private int Port { get; set; }
private PrinterState State;
private int _checkInterval;
private UdpClient _clientZP;
private IPEndPoint _siteEndPoint;
private DateTime _lastCheckDT;
private Timer _timCheckState;
private Timer _timCheckConn;
private Timer _timInit;
public ZebraPrinter(string IP, int Port)
{
_checkInterval = 5;
_siteEndPoint = new IPEndPoint(IPAddress.Any, Port);
State = new PrinterState();
this.IP = IP;
this.Port = Port;
// Init Call
CheckState();
// Start Check State
_timCheckState = new Timer(1000 * _checkInterval);
_timCheckState.Elapsed += new ElapsedEventHandler(TimCheckState);
_timCheckState.Enabled = true;
// Start Check Conn
_timCheckConn = new Timer(1000 * _checkInterval);
_timCheckConn.Elapsed += new ElapsedEventHandler(TimCheckConn);
_timCheckConn.Enabled = true;
// Only Call First Time
_timInit = new Timer(10);
_timInit.Elapsed += new ElapsedEventHandler(TimInit);
_timInit.Enabled = true;
}
/// <summary>
/// Try action of flow
/// </summary>
public void Send(string code)
{
if (string.IsNullOrEmpty(code)) throw new ArgumentNullException("Cmd code is null empty");
_clientZP = new UdpClient(IP, Port);
_clientZP.BeginReceive(Receive, null);
_clientZP.Send(Encoding.ASCII.GetBytes(code), Encoding.ASCII.GetBytes(code).Length);
}
public void Receive(IAsyncResult ar)
{
if(ar==null) throw new ArgumentNullException("Not register rcv event");
var recvBytes = _clientZP.EndReceive(ar, ref _siteEndPoint);
var recvMsg = Encoding.ASCII.GetString(recvBytes);
// Message Handling
recvMsg = recvMsg.Replace("\u0002", "").Replace("\u0003", "").Replace(" ", "").Replace("\r\nPRINTERSTATUS", "").Replace("\r\n\r\n", "");
recvMsg = Regex.Replace(recvMsg, @"(\r\n)$", "");
var pat = @"\,|\r\nERRORS:|\r\nWARNINGS:|\r\n";
var recvData = Regex.Split(recvMsg, pat);
// Set Printer State
_lastCheckDT = DateTime.Now;
if (recvData.Length == 27)
{
State.Connected = true;
State.PaperOut = recvData[1] == "1" ? true : false;
State.Pause = recvData[2] == "1" ? true : false;
State.RibbonOut = recvData[15] == "1" ? true : false;
State.Error = recvData[25].Substring(0, 1) == "1" ? true : false;
State.Warning = recvData[26].Substring(0, 1) == "1" ? true : false;
State.ErrorNum = int.TryParse(recvData[25].Substring(9, 8), out int eNum) ? eNum : 0;
State.WarningNum = int.TryParse(recvData[26].Substring(9, 8), out int wNum) ? wNum : 0;
}
}
/// <summary>
/// Check Printer State
/// </summary>
private void CheckState()
{
try
{
Send("~HS~HQES");
}
catch (Exception ex)
{
Console.WriteLine("CheckState : " + ex.Message);
}
}
/// <summary>
/// Check Printer State
/// </summary>
private void TimCheckState(object sender, ElapsedEventArgs e)
{
_timCheckState.Stop();
CheckState();
_timCheckState.Start();
}
private void TimInit(object sender, ElapsedEventArgs e)
{
_timInit.Stop();
while (State.IsStateChangeHandlerNull())
{
System.Threading.Thread.Sleep(5);
}
State.StateChange();
_timInit.Enabled = false;
}
/// <summary>
/// Connection Check
/// </summary>
private void TimCheckConn(object sender, ElapsedEventArgs e)
{
_timCheckConn.Stop();
var UpdateDuration = new TimeSpan(DateTime.Now.Ticks - _lastCheckDT.Ticks);
if (UpdateDuration.TotalSeconds > _checkInterval * 2)
{
State.Connected = false;
}
_timCheckConn.Start();
}
}
}
|
namespace CapaAplicacion
{
using CapaDominio;
using Common;
using System;
internal class CA_Update : CD_Requerimientos, ICube
{
private int x { get; set; }
private int y { get; set; }
private int z { get; set; }
private int w { get; set; }
private int dimension { get; set; }
/// <summary>
/// Método que ejecuta el query tipo update
/// </summary>
public string RealizarConsulta(int[][][] matrix)
{
string resp = "";
if (ValidarRequerimientos())
{
matrix[x - 1][y - 1][z - 1] = w;
}
else
{
resp = MensajeAlgoritmo;
}
return resp;
}
public CA_Update(string query, int dimension)
{
string[] querySplitted = query.Split(' ');
x = Convert.ToInt32(querySplitted[1]);
y = Convert.ToInt32(querySplitted[2]);
z = Convert.ToInt32(querySplitted[3]);
w = Convert.ToInt32(querySplitted[4]);
this.dimension = dimension;
}
protected bool ValidarRequerimientos()
{
return ValidarPosicionInicial(x, 'x') && ValidarPosicionInicial(y, 'y') && ValidarPosicionInicial(z, 'z') && ValidarValoresMaxMin();
}
private bool ValidarValoresMaxMin()
{
bool resp = W_MIN <= w && w <= W_MAX;
if (!resp)
{
string message = CO_MensajesSistema.ValorActualizar + W_MIN + "y " + W_MAX;
MensajeAlgoritmo += "- " + (String.IsNullOrEmpty(MensajeAlgoritmo) ? message + Environment.NewLine : message + Environment.NewLine);
}
return resp;
}
public bool ValidarPosicionInicial(int primerValor, char coordinate)
{
bool resp = 1 <= primerValor && primerValor <= dimension;
if (!resp)
{
string message = "La posición inicial de comparación en la coordenada " + coordinate + " es mayor a la final. La posición inicial del primer cubo es (1,1,1)";
MensajeAlgoritmo += "- " + (String.IsNullOrEmpty(MensajeAlgoritmo) ? message + System.Environment.NewLine : message + System.Environment.NewLine);
}
return resp;
}
public bool ValidarValoresIniciales(int first, int last, char coordinate)
{
throw new NotImplementedException();
}
}
} |
using System.Windows.Controls;
namespace Lite
{
/// <summary>
/// The Footer page
/// </summary>
public partial class LitePrintA4Template1FooterPageView : UserControl
{
/// <summary>
/// The default constructor
/// </summary>
public LitePrintA4Template1FooterPageView()
{
InitializeComponent();
}
}
}
|
using Microsoft.Xna.Framework;
using ProjectBueno.Engine;
using ProjectBueno.Game.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBueno.Game.Spells
{
class ProjectileStream : Projectile
{
public ProjectileStream(Spell spell, GameHandler game, Entity target, Entity owner) : base(spell, game, target, owner)
{
projectiles = new List<Vector2>();
this.hasUpdated = false;
}
protected const int COLLISION_COUNT = 128;
protected const float COLLISION_INTERVAL = 1f / COLLISION_COUNT;
protected List<Vector2> projectiles;
protected bool hasUpdated;
protected Entity colTarget;
protected Vector2 colPos;
public override bool toRemove
{
get
{
return hasUpdated;
}
}
public void addProjectile(Vector2 pos)
{
projectiles.Add(pos);
}
public float ProcessCollision(Vector2 origin, Vector2 dir)
{
float mult = 0.0f;
for (int i = 0; i <= COLLISION_COUNT; i++)
{
foreach (var entity in game.entities)
{
if (!entity.isAlly && entity != owner && entity.checkCollision(origin + dir * mult, size))
{
colTarget = entity;
colPos = origin + dir * (mult + COLLISION_INTERVAL);
return mult;
}
}
mult += COLLISION_INTERVAL;
}
return 2.0f;
}
public override void Draw()
{
Rectangle frameCache = projTexture.getCurFrame();
for (int i = 0; i < projectiles.Count; i++)
{
Main.spriteBatch.Draw(projTexture.texture, projectiles[i], frameCache, Color.White * 0.5f);
}
}
public override void Update()
{
hasUpdated = true;
if (colTarget != null)
{
if (colTarget.canDamage)
{
colTarget.dealDamage(spell.getDamage(colTarget), Vector2.Normalize(colTarget.pos - owner.pos) * 5f, spell.shape.dmgCooldown);
colTarget.control += spell.getControl(colTarget);
colTarget.updateState();
}
if (arcCount > 0)
{
Entity arcTarget = colTarget.GetClosest(game.entities.Where(ent => !ent.isAlly));
if (arcTarget != null)
{
Projectile proj = spell.shape.generateProjectiles(colPos, spell, game, arcTarget, colTarget);
proj.arcCount = arcCount - 1;
game.addProjectile(proj);
}
}
}
projTexture.incrementAnimation();
}
public override void DrawDebug()
{
for (int i = 0; i < projectiles.Count; i++)
{
Main.spriteBatch.Draw(Main.boxel, projectiles[i], new Rectangle(0, 0, (int)size.X, (int)size.Y), Color.Red * 0.5f);
}
}
}
}
|
using Godot;
using System;
[Serializable]
public class VehicleWheelData
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSG东莞路测客户端
{
class DiscreteScanInfo
{
//设备ID
public string DeviceID { get; set; }
public double FreqStart { get; set; }
public double FreqStop { get; set; }
//频点数
public int PointCount { get; set; }
//频点列表
public double[] FreqPoints { get; set; }
//场强列表 与频点列表一 一对应
public double[] Values { get; set; }
}
}
|
using System.Collections.Generic;
using System;
namespace HTBAntColonyTSP
{
public class UpdateEventArgs : EventArgs
{
private readonly int m_CurrentIteration;
private readonly int m_SuccessfulIterations;
private readonly int m_Failures;
private readonly double m_CurrentBestValue;
private readonly double m_LastValue;
private readonly IEnumerable<TspCity> m_BestTour;
private readonly int m_userId;
public int CurrentIteration
{
get
{
return m_CurrentIteration;
}
}
public int SuccessfulIterations
{
get
{
return m_SuccessfulIterations;
}
}
public int Failures
{
get
{
return m_Failures;
}
}
public double CurrentBestValue
{
get
{
return m_CurrentBestValue;
}
}
public double LastValue
{
get
{
return m_LastValue;
}
}
public IEnumerable<TspCity> BestTour
{
get
{
return m_BestTour;
}
}
public int UserID
{
get { return m_userId; }
}
public UpdateEventArgs(int current_iteration, int successful_iterations, int failures, double current_best_value, double last_value, IEnumerable<TspCity> best_tour, int userId = -1)
{
m_CurrentIteration = current_iteration;
m_SuccessfulIterations = successful_iterations;
m_Failures = failures;
m_CurrentBestValue = current_best_value;
m_LastValue = last_value;
m_BestTour = best_tour;
m_userId = userId;
}
public override string ToString()
{
return string.Format("Iteration: {1}{0}w/o change: {2}{0}failed: {3}{0}value: {4:f1}{0}last: {5:f1}", "\t", CurrentIteration, SuccessfulIterations, Failures, CurrentBestValue, LastValue);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Network : MonoBehaviour
{
[SerializeField] Node node;
public GameObject nodePrefab;
[SerializeField] public static int layers = 5;
[SerializeField] public static int nodesPerLayer = 3;
public static int layerCount;
public static Network instance;
[SerializeField] public static float xDist = 0.25f;
[SerializeField] public static float yDist = 0.4f;
// Start is called before the first frame update
void Awake()
{
instance = this;
node.Initialize();
}
void Initialize()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
|
using System;
namespace BlazorShared.Models.Client
{
public class DeleteClientResponse : BaseResponse
{
public DeleteClientResponse(Guid correlationId) : base(correlationId)
{
}
public DeleteClientResponse()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KeepTeamAutotests.Model
{
public class Candidate
{
public string CanVacancy { get; set; }
public string CanStatus { get; set; }
public string CanLastName { get; set; }
public string CanName { get; set; }
public string CanPatronimyc { get; set; }
public string CanDateBirhtday { get; set; }
public string CanSex { get; set; }
public string CanPayment { get; set; }
public string CanCity { get; set; }
public bool CanTrip { get; set; }
public bool CanMove { get; set; }
public int CanSkill { get; set; }
public string CanDescription { get; set; }
public string CanTypeOfContact { get; set; }
public string CanContact { get; set; }
public string CanFile { get; set; }
public string CanFileDescription { get; set; }
public override string ToString()
{
return "Фамилия = " + CanLastName + "Имя = " + CanName;
}
public void WriteToConsole(string id)
{
Console.Out.WriteLine("=============================== "+id+" ===============================");
Console.Out.WriteLine("CanStatus = " + CanStatus );
Console.Out.WriteLine("CanVacancy = " + CanVacancy );
Console.Out.WriteLine("CanLastName = " + CanLastName );
Console.Out.WriteLine("CanName = " + CanName);
Console.Out.WriteLine("CanPatronimyc = " + CanPatronimyc);
Console.Out.WriteLine("CanDateBirhtday = " + CanDateBirhtday );
Console.Out.WriteLine("CanSex = " + CanSex );
Console.Out.WriteLine("CanPayment = " + CanPayment );
Console.Out.WriteLine("CanCity = " + CanCity );
Console.Out.WriteLine("CanTrip = " + CanTrip );
Console.Out.WriteLine("CanMove = " + CanMove );
Console.Out.WriteLine("CanSkill = " + CanSkill );
Console.Out.WriteLine("CanDescription = " + CanDescription );
Console.Out.WriteLine("CanContact = " + CanContact);
Console.Out.WriteLine("CanTypeOfContact = " + CanTypeOfContact);
Console.Out.WriteLine("CanFile = " + CanFile );
Console.Out.WriteLine("CanFileDescription = " + CanFileDescription);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class responder : MonoBehaviour{
private int idTema;
public Text pergunta;
public Text respostaA;
public Text respostaB;
public Text respostaC;
public Text respostaD;
public Text infoRespostas;
public string[] perguntas; //armazena todas as perguntas
public string[] alternativaA; //armazena todas as alternativas A
public string[] alternativaB; //armazena todas as alternativas B
public string[] alternativaC; //armazena todas as alternativas C
public string[] alternativaD; //armazena todas as alternativas D
public string[] corretas; //armazena todas as alternativas corretas
private int idPergunta;
private float acertos;
private float questoes;
private float media;
private int notaFinal;
// Start is called before the first frame update
void Start()
{
idTema = PlayerPrefs.GetInt("idTema");
idPergunta = 0;
questoes = perguntas.Length;
pergunta.text = perguntas[idPergunta];
respostaA.text = alternativaA[idPergunta];
respostaB.text = alternativaB[idPergunta];
respostaC.text = alternativaC[idPergunta];
respostaD.text = alternativaD[idPergunta];
infoRespostas.text = "Respondendo "+(idPergunta + 1).ToString()+ " de "+questoes.ToString()+" perguntas.";
}
public void resposta(string alternativa)
{
if(alternativa == "A"){
if(alternativaA[idPergunta] == corretas[idPergunta]){
acertos += 1;
}
}
else if(alternativa == "B"){
if(alternativaB[idPergunta] == corretas[idPergunta]){
acertos += 1;
}
}
else if(alternativa == "C"){
if(alternativaC[idPergunta] == corretas[idPergunta]){
acertos += 1;
}
}
else if(alternativa == "D"){
if(alternativaD[idPergunta] == corretas[idPergunta]){
acertos += 1;
}
}
proximaPergunta();
}
void proximaPergunta()
{
idPergunta += 1;
if(idPergunta <= (questoes - 1))
{
pergunta.text = perguntas[idPergunta];
respostaA.text = alternativaA[idPergunta];
respostaB.text = alternativaB[idPergunta];
respostaC.text = alternativaC[idPergunta];
respostaD.text = alternativaD[idPergunta];
infoRespostas.text = "Respondendo "+(idPergunta + 1).ToString()+ " de "+questoes.ToString()+" perguntas.";
}
else
{
//O QUE FAZER SE TERMINAR AS PERGUNTAS
media = 10 * (acertos / questoes); //CALCULA A MEDIA COM BASE NO % DE ACERTO
notaFinal = Mathf.RoundToInt(media); //ARREDONDA A NOTA PARA O PROXIMO INTEIRO
if(notaFinal > PlayerPrefs.GetInt("notaFinal"+idTema.ToString()))
{
PlayerPrefs.SetInt("notaFinal"+idTema.ToString(), notaFinal);
PlayerPrefs.SetInt("acertos"+idTema.ToString(), (int) acertos);
}
PlayerPrefs.SetInt("notaFinalTemp"+idTema.ToString(), notaFinal);
PlayerPrefs.SetInt("acertosTemp"+idTema.ToString(), (int) acertos);
Application.LoadLevel("notaFinal");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterSelectionControl : MonoBehaviour
{
public Category category;
public enum Category{
PROART,
PAINTING,//3dpaint
DESIGN,//cad3d
ARTS//2dpaint
}
}
|
using System.Threading.Tasks;
namespace NETTRASH.BOT.Telegram.Core.Data
{
public class InputFile
{
#region Public properties
public string FileName { get; set; }
public byte[] FileContent { get; set; }
#endregion
#region Public static methods
public static async Task<InputFile> LoadAsync(string sFileName)
{
InputFile retVal = new InputFile();
retVal.FileName = System.IO.Path.GetFileName(sFileName);
retVal.FileContent = await Task.Run(() => System.IO.File.ReadAllBytes(sFileName));
return retVal;
}
#endregion
}
}
|
using System.Collections.Generic;
namespace CodeComb.CodeAnalysis.OmniSharp.Models
{
// [OmniSharpEndpoint(OmnisharpEndpoints.MembersFlat, typeof(MembersFlatRequest), typeof(IEnumerable<QuickFix>))]
public class MembersFlatRequest : Request
{
}
}
|
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
using TimeTableApi.Application.Shared.EventManagement.Dtos;
using TimeTableApi.Core.Entities;
namespace TimeTableApi.Application.AutoMapper
{
public class TimeTableProfile : Profile
{
public TimeTableProfile()
{
CreateMap <TimeTable, CreateOrEditTimeTableInputDto>().ReverseMap();
CreateMap<TimeTable, TimeTableDto>().ReverseMap();
}
}
}
|
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 Car_Wash
{
public partial class paymentMethodForm : Form
{
public paymentMethodForm(int washPrice, int washes)
{
InitializeComponent();
int price = washPrice;
int washNumber = washes;
priceLabel.Text = price.ToString("C2");
numberOfWashLabel.Text = washNumber.ToString();
}
private void cashButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Please insert cash.");
System.Windows.Forms.Application.Exit();
}
private void cardButton_Click(object sender, EventArgs e)
{
cardForm card = new cardForm();
this.Hide();
card.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using LorikeetMApp.ViewModels;
using Xamarin.Forms;
namespace LorikeetMApp
{
public partial class LoginPinPage : ContentPage
{
public LoginPinPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
var viewModel = new PinAuthViewModel();
viewModel.PinViewModel.Success += (object sender, EventArgs e) =>
{
Application.Current.MainPage = new MainMenu();
};
base.BindingContext = viewModel;
}
protected override bool OnBackButtonPressed() => false;
}
}
|
using System;
namespace AxiEndPoint.EndPointServer.Logging
{
public interface ILogger
{
void Trace(string message);
void Trace(string message, params object[] args);
void Debug(string message);
void Debug(string message, params object[] args);
void Warn(string message);
void Warn(string message, params object[] args);
void Error(string message);
void Error(string message, params object[] args);
void Error(Exception ex);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Example1 = DesignPatterns.Decorator.CarRentalExample;
using Example2 = DesignPatterns.Decorator.CarRentalExample2;
using Xunit;
namespace DesignPatternsTest
{
public class DecoratorTest
{
[Fact]
public void CanRentalWithNoneOfSpecialOptions()
{
Example1.Model m = new Example1.Model(10.0f, 50.0f, "Ford Taurus");
Example1.IRental r1 = new Example1.CarRental(m, 5);
Assert.True(r1.CalcPrice() == 250.0f);
}
[Fact]
public void CanRentalWithInsuranceOption()
{
Example1.Model m = new Example1.Model(10.0f, 50.0f, "Ford Taurus");
Example1.IRental r1 = new Example1.Insurance(new Example1.CarRental(m, 5), 12.5f);
Assert.True(r1.CalcPrice() == 312.5f);
}
[Fact]
public void CanRentalWithFuelAndInsuranceOptions()
{
Example1.Model m = new Example1.Model(10.0f, 50.0f, "Ford Taurus");
Example1.IRental r1 = new Example1.RefuelOnReturn(
new Example1.Insurance(new Example1.CarRental(m, 5), 12.5f), 3.75f);
Assert.True(r1.CalcPrice() == 350.0f);
}
[Fact]
public void CanRentalWithNoneOfSpecialOptions1()
{
Example2.Model m = new Example2.Model(10.0f, 50.0f, "Ford Taurus");
Example2.IRental r1 = new Example2.CarRental(m, 5);
Assert.True(r1.calcPrice() == 250.0f);
}
[Fact]
public void CanRentalWithInsuranceOption1()
{
Example2.Model m = new Example2.Model(10.0f, 50.0f, "Ford Taurus");
Example2.IRental r2 = new Example2.Insurance(
new Example2.CarRental(m, 5),
12.5f);
Assert.True(r2.calcPrice() == 312.5f);
}
[Fact]
public void CanRentalWithFuelAndInsuranceOptions1()
{
Example2.Model m = new Example2.Model(10.0f, 50.0f, "Ford Taurus");
Example2.IRental r3 = new Example2.RefuelOnReturn(
new Example2.Insurance(
new Example2.CarRental(m, 5), 12.5f), 3.75f);
Assert.True(r3.calcPrice() == 350.0f);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using alg;
/*
* tags: Euclid gcd
* Time(logn), Space(1)
*/
namespace leetcode
{
public class Lc780_Reaching_Points
{
public bool ReachingPoints(int sx, int sy, int tx, int ty)
{
while (sx < tx && sy < ty)
{
if (tx > ty) tx %= ty;
else ty %= tx;
}
return (sx == tx && (ty - sy) % sx == 0) || (sy == ty && (tx - sx) % sy == 0);
}
public bool ReachingPoints2(int sx, int sy, int tx, int ty)
{
while (sx <= tx && sy <= ty)
{
if (sx == tx && sy == ty) return true;
if (ty >= tx) ty = Math.Min(ty - tx, sy / tx * tx + (ty % tx) + tx);
else tx = Math.Min(tx - ty, sx / ty * ty + (tx % ty) + ty);
}
return false;
}
public void Test()
{
Console.WriteLine(ReachingPoints(1, 1, 3, 5) == true);
Console.WriteLine(ReachingPoints(1, 1, 2, 2) == false);
Console.WriteLine(ReachingPoints(1, 1, 1, 1) == true);
Console.WriteLine(ReachingPoints(3, 3, 12, 9) == true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace webApp.Areas.Flota.Controllers
{
public class MaestrosController : Controller
{
public ActionResult Modelo()
{
return View();
}
public ActionResult Ata()
{
return View();
}
}
} |
using System.ComponentModel.DataAnnotations;
namespace MundoMascotaRosario.Models.ViewModels
{
public class CuentaUsuarioVM
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Contraseña")]
public string Password { get; set; }
}
} |
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Implementation;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Interfaces;
using Fingo.Auth.Domain.CustomData.Factories.Implementation;
using Fingo.Auth.Domain.CustomData.Factories.Interfaces;
using Fingo.Auth.Domain.CustomData.Services.Interfaces;
using Moq;
using Xunit;
namespace Fingo.Auth.Domain.CustomData.Tests.Factories.Implementation
{
public class GetUserCustomDataListFromProjectFactoryTest
{
[Fact]
public void
GetUserCustomDataListFromProjectFactory_Should_Return_Instance_Of_GetUserCustomDataListFromProject_Given_By_IGetUserCustomDataListFromProject
()
{
//Arrange
var projectMock = new Mock<IProjectRepository>();
var userMock = new Mock<IUserRepository>();
var convertServiceMock = new Mock<ICustomDataJsonConvertService>();
//Act
IGetUserCustomDataListFromProjectFactory target =
new GetUserCustomDataListFromProjectFactory(projectMock.Object ,
userMock.Object , convertServiceMock.Object);
var result = target.Create();
//Assert
Assert.NotNull(result);
Assert.IsType<GetUserCustomDataListFromProject>(result);
Assert.IsAssignableFrom<IGetUserCustomDataListFromProject>(result);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public Graph m_Graph;
public float scale = 1;
public int x = 5, y = 5, startX = 0, startY = 0, endX = 0, endY = 0;
// Use this for initialization
void Start () {
m_Graph.CreateGraph(x, y, scale);
}
// Update is called once per frame
void Update () {
//uncolour all the nodes
foreach (Node node in m_Graph.Nodes)
{
node.UnHighlightNode();
}
//grab the start and the end nodes from the engine
Node startNode = m_Graph.FindNodeAtIndex(startX, startY);
Node endNode = m_Graph.FindNodeAtIndex(endX, endY);
//Debug.Log("x:" + startNode.Index.x + " y:" + startNode.Index.y);
//Debug.Log("x:" + endNode.Index.x + " y:" + endNode.Index.y);
//find the path!
List<Node> highlightThese = m_Graph.DjikstraSearch(startNode, endNode);
//List<Node> highlightThese = m_Graph.AStarSearch(startNode, endNode);
//colour the path!
foreach (Node node in highlightThese)
{
node.HighlightNode();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Olive.Data;
using Olive.Data.Uow;
using Olive.Web.MVC.Areas.Administration.ViewModels;
using System.Threading;
namespace Olive.Web.MVC.Areas.Administration.Controllers
{
public class SourcesController : AdministrationCRUDController
{
private IUowData db = new UowData();
//
// GET: /Administration/Sources/
public ViewResult Index()
{
//return View(db.Sources.All().ToList());
SourcesIndexViewModel indexModel = new SourcesIndexViewModel();
indexModel.AllSources = db.Sources.All();
indexModel.NewSource = new Source();
return View(indexModel);
}
//
// POST: /Administration/Sources/Create
[HttpPost]
public ActionResult Create(Source newSource)
{
var indexModel = new SourcesIndexViewModel();
var addSource = new Source();
if (ModelState.IsValid)
{
//addSource.SourceID = newSource.SourceID;
addSource.Name = newSource.Name;
db.Sources.Add(addSource);
db.SaveChanges();
}
return PartialView("_SourcePartial", addSource);
}
//
// GET: /Administration/Sources/Edit/5
public ActionResult Edit(int id)
{
Source source = db.Sources.All().Single(s => s.SourceID == id);
return PartialView(source);
}
//
// POST: /Administration/Sources/Edit/5
[HttpPost]
public ActionResult Edit(Source model,int id)
{
var indexModel = new SourcesIndexViewModel();
Source source = db.Sources.GetById(id);
if (ModelState.IsValid)
{
source.Name = model.Name;
db.Sources.Update(source);
db.SaveChanges();
}
//model.SourceID = id;
//return PartialView("_SourcePartial", model);
return Json(new { sourceID = id, sourceName = model.Name });
}
//
// GET: /Administration/Sources/Delete/5
public ActionResult Delete(int id)
{
Source source = db.Sources.All().Single(s => s.SourceID == id);
//return View(source);
return PartialView(source);
}
//
// POST: /Administration/Sources/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Source source = db.Sources.All().Single(s => s.SourceID == id);
db.Sources.Delete(source);
db.SaveChanges();
//return Json(new { id = id });
return Content(id.ToString());
}
}
} |
using Sentry.Android.Extensions;
namespace Sentry.Android.Callbacks;
internal class BeforeBreadcrumbCallback : JavaObject, JavaSdk.SentryOptions.IBeforeBreadcrumbCallback
{
private readonly Func<Breadcrumb, Hint, Breadcrumb?> _beforeBreadcrumb;
public BeforeBreadcrumbCallback(Func<Breadcrumb, Hint, Breadcrumb?> beforeBreadcrumb)
{
_beforeBreadcrumb = beforeBreadcrumb;
}
public JavaSdk.Breadcrumb? Execute(JavaSdk.Breadcrumb b, JavaSdk.Hint h)
{
// Note: Hint is unused due to:
// https://github.com/getsentry/sentry-dotnet/issues/1469
var breadcrumb = b.ToBreadcrumb();
var hint = h.ToHint();
var result = _beforeBreadcrumb.Invoke(breadcrumb, hint);
if (result == breadcrumb)
{
// The result is the same object as was input, and all properties are immutable,
// so we can return the original Java object for better performance.
return b!;
}
return result?.ToJavaBreadcrumb();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GangOfFourDesignPatterns.Behavioral.State
{
/// <summary>
/// This is an abstract/interface that is used by the Context object
/// to access the changeable functionality.
/// </summary>
public abstract class PrinterState
{
public abstract void Execute(Printer printer);
public abstract void Cancel();
}
}
|
using Ezconet.GerenciamentoProjetos.Application.Contracts;
using Ezconet.GerenciamentoProjetos.Application.Dtos;
using Ezconet.GerenciamentoProjetos.Application.Services;
using Ezconet.GerenciamentoProjetos.UI.Web.Models.Solicitacao;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ezconet.GerenciamentoProjetos.UI.Web.Controllers
{
public sealed class SolicitacaoController : Controller
{
private readonly ISolicitacaoApplicationService _solicitacaoApplicationService;
public SolicitacaoController(
ISolicitacaoApplicationService solicitacaoApplicationService)
{
_solicitacaoApplicationService = solicitacaoApplicationService;
}
private static IndexModel ToModel(SolicitacaoDto dto)
{
return new IndexModel
{
Codigo = dto.Codigo,
AreaUsuarioCriacao = dto.AreaAtualUsuarioCriacao,
CodigoObjetivo = dto.CodigoObjetivo,
CodigoUsuarioCriacao = dto.CodigoUsuarioCriacao,
Descricao = dto.Descricao,
Nome = dto.Nome
};
}
// GET: Solicitacao
public ActionResult Index()
{
var list = _solicitacaoApplicationService.Consultar();
return View(list.ToList().ConvertAll(ToModel));
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(CreateModel model)
{
if (!ModelState.IsValid)
return View(model);
Cadastrar(model);
return RedirectToAction("Index");
}
//Exemplo com IoC
public void Cadastrar(CreateModel model)
{
var solicitacaoDto = new SolicitacaoDto
{
Nome = model.Nome,
CodigoObjetivo = model.CodigoObjetivo,
Descricao = model.Descricao,
CodigoUsuarioCriacao = model.CodigoUsuarioCriacao,
AreaAtualUsuarioCriacao = model.AreaUsuarioCriacao
};
_solicitacaoApplicationService.Cadastrar(solicitacaoDto);
}
//Exemplo sem IoC
//private void Cadastrar(IndexModel model)
//{
// using (var context = new GerenciamentoProjetosDbContext())
// {
// context.Database.Log = Console.WriteLine;
// ISolicitacaoRepository solicitacaoRepository
// = new SolicitacaoRepository(context);
// IUsuarioRepository usuarioRepository
// = new UsuarioRepository(context);
// ISolicitacaoDomainService solicitacaoDomainService
// = new SolicitacaoDomainService(solicitacaoRepository, usuarioRepository);
// ISolicitacaoApplicationService solicitacaoApplicationService
// = new SolicitacaoApplicationService(solicitacaoDomainService, solicitacaoRepository, usuarioRepository);
// var solicitacaoDto = new SolicitacaoDto
// {
// Nome = model.Nome,
// CodigoObjetivo = model.CodigoObjetivo,
// Descricao = model.Descricao,
// CodigoUsuarioCriacao = model.CodigoUsuarioCriacao,
// AreaAtualUsuarioCriacao = model.AreaUsuarioCriacao
// };
// solicitacaoApplicationService.Cadastrar(solicitacaoDto);
// context.SaveChanges();
// };
//}
}
} |
using ShopDAL.Interfaces;
using ShopDAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShopDAL.Repositories
{
public class TovarRepository : ShopRepository<Tovar>, IRepository<Tovar> //IRepository<Tovar>//
{
public TovarRepository(MyDBContext ctx) : base(ctx)
{
}
//List<Tovar> list;
//public TovarRepository()
//{
// list = new List<Tovar>
// {
// new Tovar{Id=1,Name="ashdjshahkjdksjf",Price=500,CategoryId=1 },
// new Tovar{Id=2,Name="qwtyetywqewyury",Price=1000,CategoryId=2 },
// new Tovar{Id=3,Name="zxcnbzxvxcz",Price=750,CategoryId=1 }
// };
//}
//public IEnumerable<Tovar> GetAll()
//{
// return list;
//}
//public Tovar GetById(int id)
//{
// throw new NotImplementedException();
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace GesCMS.Services.BaseServices
{
public interface IBaseService<TDB, TVM>
{
Task<int> Add(TVM dto);
Task<int> AddItems(List<TVM> dtos);
Task<int> Remove(TVM dto);
Task<int> Update(TVM dto);
Task<TVM> Find(long id);
Task<IEnumerable<TVM>> GetList();
Task<IEnumerable<TVM>> GetListById();
Task<long> GetCountOfNoneDeleted();
Task<long> GetCountOfAll();
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using Pobs.Domain.Utils;
namespace Pobs.Domain.Entities
{
public class Comment : IHasWatches
{
public Comment()
{
this.ChildComments = new Collection<Comment>();
this.Reactions = new Collection<Reaction>();
this.Watches = new Collection<Watch>();
}
public Comment(string text, User postedByUser, DateTimeOffset postedAt, bool isAgree, long? parentCommentId)
: this()
{
this.Text = text.CleanText();
this.PostedByUser = postedByUser;
this.PostedAt = postedAt;
this.AgreementRating = isAgree ? AgreementRating.Agree : AgreementRating.Disagree;
if (parentCommentId.HasValue)
{
this.ParentComment = new Comment { Id = parentCommentId.Value };
}
}
public long Id { get; set; }
[Required, MaxLength(280)]
public string Text { get; set; }
[MaxLength(2000)]
public string Source { get; set; }
public AgreementRating AgreementRating { get; set; }
[Required]
public User PostedByUser { get; set; }
public int PostedByUserId { get; set; }
public DateTimeOffset PostedAt { get; set; }
public bool IsAnonymous { get; set; }
public PostStatus Status { get; set; }
[Required]
public virtual Answer Answer { get; set; }
public virtual Comment ParentComment { get; set; }
public virtual ICollection<Comment> ChildComments { get; set; }
public virtual ICollection<Reaction> Reactions { get; set; }
public virtual ICollection<Notification> Notifications { get; set; }
public virtual ICollection<Watch> Watches { get; set; }
}
}
|
using Sales.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Sales.Views
{ // Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
ChatBotViewModel vm;
InitializeComponent();
BindingContext = vm = new ChatBotViewModel();
vm.Messages.CollectionChanged += (sender, e) =>
{
var target = vm.Messages[vm.Messages.Count - 1];
MessagesList.ScrollTo(target, ScrollToPosition.End, true);
};
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace LocusNew.Core.AdminViewModels
{
public class AddAsSoldViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Ime je obavezno polje.")]
[DisplayName("Ime")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Prezime je obavezno polje.")]
[DisplayName("Prezime")]
public string LastName { get; set; }
public string Email { get; set; }
[Required(ErrorMessage = "Broj telefona je obavezno polje.")]
[DisplayName("Broj telefona")]
public string Phone { get; set; }
public string Address { get; set; }
public string IdNumber { get; set; }
public int ListingId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using CYT.Entities;
using CYT.Web.DataContext;
namespace CYT.Web.Controllers.WebApi
{
public class RecipeVotesController : ApiController
{
private CytDb db = new CytDb();
// GET: api/RecipeVotes
public IQueryable<RecipeVote> GetRecipeVotes()
{
return db.RecipeVotes;
}
// GET: api/RecipeVotes/5
[ResponseType(typeof(RecipeVote))]
public IHttpActionResult GetRecipeVote(int id)
{
RecipeVote recipeVote = db.RecipeVotes.Find(id);
if (recipeVote == null)
{
return NotFound();
}
return Ok(recipeVote);
}
// GET: api/RecipeVotes/5
[HttpGet]
[Route("api/recipe/votes/{recipeId:int}/{userId:int}")]
[ResponseType(typeof(IEnumerable<RecipeVote>))]
public IHttpActionResult GetUserVote(int recipeId,int userId)
{
IEnumerable<RecipeVote> recipeVote = db.RecipeVotes.Where(rv => rv.UserId==userId && rv.RecipeId==recipeId).ToList();
if (recipeVote == null|| recipeVote.Count()==0)
{
return NotFound();
}
return Ok(recipeVote);
}
// PUT: api/RecipeVotes/5
[ResponseType(typeof(void))]
public IHttpActionResult PutRecipeVote(int id, RecipeVote recipeVote)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != recipeVote.RecipeVoteId)
{
return BadRequest();
}
db.Entry(recipeVote).State = EntityState.Modified;
try
{
db.SaveChanges();
Recipe r = db.Recipes.SingleOrDefault(u => u.RecipeId == recipeVote.RecipeId);
IEnumerable<RecipeVote> votes = db.RecipeVotes.Where(z => z.RecipeId == z.RecipeId);
float result = 0;
foreach (RecipeVote vote in votes)
{
result += (float)vote.VoteValue;
}
result /= votes.Count();
r.Rating = result;
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!RecipeVoteExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/RecipeVotes
[ResponseType(typeof(RecipeVote))]
public IHttpActionResult PostRecipeVote(RecipeVote recipeVote)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.RecipeVotes.Add(recipeVote);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = recipeVote.RecipeVoteId }, recipeVote);
}
// DELETE: api/RecipeVotes/5
[ResponseType(typeof(RecipeVote))]
public IHttpActionResult DeleteRecipeVote(int id)
{
RecipeVote recipeVote = db.RecipeVotes.Find(id);
if (recipeVote == null)
{
return NotFound();
}
db.RecipeVotes.Remove(recipeVote);
db.SaveChanges();
return Ok(recipeVote);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool RecipeVoteExists(int id)
{
return db.RecipeVotes.Count(e => e.RecipeVoteId == id) > 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssignmentNo8
{
class AssignmentNo8
{
static void Main(string[] args)
{
GermanShepard max = new GermanShepard();
max.Origin = Origions.Germany;
max.Name = "Max";
max.BirthDate = new DateTime(2017, 10, 10);
max.Gender = Gender.Male;
max.Weight = 32.54;
max.SecurityGuard = false;
max.Size = Sizes.Large;
max.Training = TrainingAbility.Easy;
max.DisplayDogInformation();
max.Sit(max.Name);
max.Eat();
max.SayHi();
}
}
} |
using System;
using System.Linq;
using OpenQA.Selenium;
using System.Collections.Generic;
using OpenQA.Selenium.Support.UI;
using FC_TestFramework.Core.Setup;
using OpenQA.Selenium.Remote;
namespace FC_TestFramework.Core.Utils
{
public class ElementUtils : IManager
{
public ElementUtils (RemoteWebDriver Driver) : base(Driver) { }
#region Esperas
/*Aguarda um tempo específico antes de realizar alguma ação do teste*/
public void AguardarSegundos()
{
Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
public virtual void AguardarSegundos(TimeSpan tempo)
{
Driver.Manage().Timeouts().ImplicitWait = tempo;
}
/*Aguarda o carregamento da página*/
public void AguardarPaginaCarregar()
{
IJavaScriptExecutor JS = (IJavaScriptExecutor)Driver;
WebDriverWait Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(50));
Wait.Until(wd => JS.ExecuteScript("return document.readyState").ToString() == "complete");
}
public virtual void AguardarPaginaCarregar(TimeSpan tempo)
{
IJavaScriptExecutor JS = (IJavaScriptExecutor)Driver;
WebDriverWait Wait = new WebDriverWait(Driver, tempo);
Wait.Until(wd => JS.ExecuteScript("return document.readyState").ToString() == "complete");
}
/*Aguarda o carregamento de um determinado elemento na página*/
public void AguardarElemento(By seletor)
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(30))
.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(seletor));
}
catch (Exception e)
{
new Exception("O elemento não foi carregado na tela. Motivo: " + e.Message);
}
}
public virtual void AguardarElemento(By seletor, TimeSpan tempo)
{
try
{
new WebDriverWait(Driver, tempo)
.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(seletor));
}
catch (Exception e)
{
new Exception("O elemento não foi carregado na tela. Motivo: " + e.Message);
}
}
/*Aguarda a visibilidade de um determinado elemento na página*/
public void AguardarVerElemento(By seletor)
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(30))
.Until(ExpectedConditions.ElementIsVisible(seletor));
}
catch (Exception e)
{
new Exception("O elemento não foi apresentado na tela. Motivo: " + e.Message);
}
}
public virtual void AguardarVerElemento(By seletor, TimeSpan tempo)
{
try
{
new WebDriverWait(Driver, tempo)
.Until(ExpectedConditions.ElementIsVisible(seletor));
}
catch (Exception e)
{
new Exception("O elemento não foi apresentado na tela. Motivo: " + e.Message);
}
}
/*Aguarda o texto de um determinado elemento na página*/
public void AguardarVerTexto(By seletor, String texto)
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(50))
.Until(ExpectedConditions.TextToBePresentInElementLocated(seletor, texto));
}
catch (Exception e)
{
new Exception("O texto não foi apresentado na tela. Motivo: " + e.Message);
}
}
public virtual void AguardarVerTexto(By seletor, String texto, TimeSpan tempo)
{
try
{
new WebDriverWait(Driver, tempo)
.Until(ExpectedConditions.TextToBePresentInElementLocated(seletor, texto));
}
catch (Exception e)
{
new Exception("O texto não foi apresentado na tela. Motivo: " + e.Message);
}
}
/*Aguarda a invisibilidade de um determinado elemento na página*/
public void AguardarElementoDesaparecer(By seletor)
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(50))
.Until(ExpectedConditions.InvisibilityOfElementLocated(seletor));
}
catch (Exception e)
{
new Exception("O elemento ainda está sendo apresentado na tela. Motivo: " + e.Message);
}
}
public virtual void AguardarElementoDesaparecer(By seletor, TimeSpan tempo)
{
try
{
new WebDriverWait(Driver, tempo)
.Until(ExpectedConditions.InvisibilityOfElementLocated(seletor));
}
catch (Exception e)
{
new Exception("O elemento ainda está sendo apresentado na tela. Motivo: " + e.Message);
}
}
/*Aguarda o elemento ser Clicável*/
public void AguardarClicarElemento(By seletor)
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(30))
.Until(ExpectedConditions.ElementToBeClickable(seletor));
}
catch (Exception e)
{
new Exception("Ainda não é possível clicar no elemento. Motivo: " + e.Message);
}
}
public virtual void AguardarClicarElemento(By seletor, TimeSpan tempo)
{
try
{
new WebDriverWait(Driver, tempo)
.Until(ExpectedConditions.ElementToBeClickable(seletor));
}
catch (Exception e)
{
new Exception("Ainda não é possível clicar no elemento. Motivo: " + e.Message);
}
}
/*Aguarda o elemento ser Clicável*/
public void AguardarSelecionarElemento(By seletor)
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(30))
.Until(ExpectedConditions.ElementToBeSelected(seletor));
}
catch (Exception e)
{
new Exception("Ainda não é possível selecionar o elemento. Motivo: " + e.Message);
}
}
public virtual void AguardarSelecionarElemento(By seletor, TimeSpan tempo)
{
try
{
new WebDriverWait(Driver, tempo)
.Until(ExpectedConditions.ElementToBeSelected(seletor));
}
catch (Exception e)
{
new Exception("Ainda não é possível selecionar o elemento. Motivo: " + e.Message);
}
}
/*Aguarda elemento ser habilitado na tela*/
public void AguardarHabilitarElemento(IWebElement elemento)
{
try
{
int segundos = 0;
while (segundos < 60)
{
Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
if (elemento.Enabled)
break;
else
segundos++;
}
}
catch (Exception e)
{
new Exception("O elemento não foi habilitado na tela. Motivo: " + e.Message);
}
}
public virtual void AguardarHabilitarElemento(IWebElement elemento, TimeSpan tempo)
{
try
{
int segundos = 0;
while (segundos < 60)
{
Driver.Manage().Timeouts().ImplicitWait = tempo;
if (elemento.Enabled)
break;
else
segundos++;
}
}
catch (Exception e)
{
new Exception("O elemento não foi habilitado na tela. Motivo: " + e.Message);
}
}
/*Aguarda elemento ser desabilitado na tela*/
public void AguardarDesabilitarElemento(IWebElement elemento)
{
try
{
int segundos = 0;
while (segundos < 60)
{
Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
if (elemento.Enabled)
segundos++;
else
break;
}
}
catch (Exception e)
{
new Exception("O elemento não foi desabilitado na tela. Motivo: " + e.Message);
}
}
public virtual void AguardarDesabilitarElemento(IWebElement elemento, TimeSpan tempo)
{
try
{
int segundos = 0;
while (segundos < 60)
{
Driver.Manage().Timeouts().ImplicitWait = tempo;
if (elemento.Enabled)
segundos++;
else
break;
}
}
catch (Exception e)
{
new Exception("O elemento não foi desabilitado na tela. Motivo: " + e.Message);
}
}
#endregion
#region Ações
/**Encontra um elemento do tipo campo texto por um seletor[Id, Name, Link, Css ou Xpath],
* aguardando o carregamento dele antes de realizar a ação*/
public virtual IWebElement EncontrarCampo(By seletor)
{
return Driver.FindElement(seletor);
}
/**Encontra um campo do tipo lista (ComboBox, DualList)
* por um seletor[Id, Name, Link, Css ou Xpath],
* aguardando o carregamento dele antes de realizar a ação*/
public virtual SelectElement EncontrarCampoLista(By seletor)
{
return new SelectElement(EncontrarCampo(seletor));
}
/**Encontra uma lista de elementos do tipo campo texto
* por um seletor[Id, Name, Link, Css ou Xpath],
* aguardando o carregamento dele antes de realizar a ação*/
public virtual List<IWebElement> EncontrarVariosCampos(By seletor)
{
return Driver.FindElements(seletor).ToList();
}
/**Digita valores em um elemento do tipo campo,
* o encontrando por um seletor[Id, Name, Link, Css ou Xpath] e
* aguardando o carregamento dele antes de realizar a ação*/
public virtual void PreencherCampo(By seletor, String texto)
{
AguardarElemento(seletor);
RolarAteElemento(seletor);
LimparCampo(seletor);
EncontrarCampo(seletor).SendKeys(texto);
}
public virtual void PreencherCampo(IWebElement elemento, String texto)
{
AguardarSegundos();
RolarAteElemento(elemento);
LimparCampo(elemento);
if (elemento.Displayed)
elemento.SendKeys(texto);
else
PreencherCampo(elemento, texto);
}
/**Seleciona um item no campo do tipo lista (ComboBox, DualList), por seu texto,
* após o encontrar por um seletor[Id, Name, Link, Css ou Xpath],
* aguardando o carregamento dele antes de realizar a ação*/
public virtual void SelecionarItemCampoListaPorTexto(By seletor, String texto)
{
AguardarElemento(seletor);
RolarAteElemento(seletor);
new SelectElement(Driver.FindElement(seletor)).SelectByText(texto);
AguardarPaginaCarregar();
}
public virtual void SelecionarItemCampoListaPorTexto(IWebElement elemento, String texto)
{
AguardarSegundos();
RolarAteElemento(elemento);
new SelectElement(elemento).SelectByText(texto);
AguardarPaginaCarregar();
}
/**Seleciona um item no campo do tipo lista (ComboBox, DualList), por seu valor,
* após o encontrar por um seletor[Id, Name, Link, Css ou Xpath],
* aguardando o carregamento dele antes de realizar a ação*/
public virtual void SelecionarItemCampoListaPorValor(By seletor, String Valor)
{
AguardarElemento(seletor);
RolarAteElemento(seletor);
new SelectElement(EncontrarCampo(seletor)).SelectByValue(Valor);
AguardarPaginaCarregar();
}
public virtual void SelecionarItemCampoListaPorValor(IWebElement elemento, String Valor)
{
AguardarSegundos();
RolarAteElemento(elemento);
new SelectElement(elemento).SelectByValue(Valor);
AguardarPaginaCarregar();
}
/**Seleciona um item no campo do tipo lista (ComboBox, DualList), por seu valor,
* após o encontrar por um seletor[Id, Name, Link, Css ou Xpath],
* aguardando o carregamento dele antes de realizar a ação*/
public virtual void SelecionarItemCampoListaPorIndex(By seletor, int Index)
{
AguardarElemento(seletor);
RolarAteElemento(seletor);
new SelectElement(EncontrarCampo(seletor)).SelectByIndex(Index);
AguardarPaginaCarregar();
}
public virtual void SelecionarItemCampoListaPorIndex(IWebElement elemento,int Index)
{
AguardarSegundos();
RolarAteElemento(elemento);
new SelectElement(elemento).SelectByIndex(Index);
AguardarPaginaCarregar();
}
/**Retira a seleção de todos os itens no campo do tipo lista (ComboBox, DualList),
* após o encontrar por um seletor[Id, Name, Link, Css ou Xpath],
* aguardando o carregamento dele antes de realizar a ação*/
public virtual void DesselecionarItemCampoLista(By seletor)
{
AguardarElemento(seletor);
RolarAteElemento(seletor);
new SelectElement(EncontrarCampo(seletor)).DeselectAll();
AguardarPaginaCarregar();
}
public virtual void DesselecionarItemCampoLista(IWebElement elemento)
{
AguardarSegundos();
RolarAteElemento(elemento);
new SelectElement(elemento).DeselectAll();
AguardarPaginaCarregar();
}
/**Captura um valore digitado em um elemento do tipo campo texto ou label,
* o encontrando por um seletor[Id, Name, Link, Css ou Xpath] e
* aguardando o carregamento dele antes de realizar a ação*/
public virtual String PegarValorCampo(By seletor)
{
AguardarElemento(seletor);
RolarAteElemento(seletor);
return EncontrarCampo(seletor).Text;
}
public virtual String PegarValorCampo(IWebElement elemento)
{
AguardarSegundos();
RolarAteElemento(elemento);
return elemento.Text;
}
/**Captura um valor selecionado em um elemento do tipo campo texto ou combo,
* o encontrando por um seletor[Id, Name, Link, Css ou Xpath] e
* aguardando o carregamento dele antes de realizar a ação*/
public virtual String PegarValorCampoLista(By seletor)
{
AguardarSegundos();
RolarAteElemento(seletor);
return new SelectElement(this.EncontrarCampo(seletor)).SelectedOption.Text;
}
public virtual String PegarValorCampoLista(IWebElement elemento)
{
AguardarSegundos();
RolarAteElemento(elemento);
return new SelectElement(elemento).SelectedOption.Text;
}
public virtual String PegarTexto(By seletor)
{
AguardarElemento(seletor);
RolarAteElemento(seletor);
return EncontrarCampo(seletor).Text;
}
/**Captura um valore digitado em um elemento do tipo campo texto ou label,
* o encontrando por um seletor[Id, Name, Link, Css ou Xpath] e
* aguardando o carregamento dele antes de realizar a ação*/
public virtual String PegarValorSoltoCampo(By seletor)
{
FecharPopup();
AguardarElemento(seletor);
RolarAteElemento(seletor);
return EncontrarCampo(seletor).GetAttribute("innerText");
}
public virtual String PegarValorSoltoCampo(IWebElement elemento)
{
AguardarSegundos();
RolarAteElemento(elemento);
return elemento.GetAttribute("innerText");
}
/**Captura um valor apresentado em uma popup,
* o encontrando por um seletor[Id, Name, Link, Css ou Xpath] e
* aguardando o carregamento dele antes de realizar a ação*/
public virtual String PegarValorTextoPopup(By seletor)
{
Driver.SwitchTo().ParentFrame();
AguardarElemento(seletor);
return EncontrarCampo(seletor).Text;
}
public virtual String PegarValorTextoPopup(IWebElement elemento)
{
Driver.SwitchTo().ParentFrame();
AguardarSegundos();
return elemento.Text;
}
public virtual String PegarValorElemento(IWebElement elemento)
{
AguardarSegundos();
return elemento.Text;
}
/**Limpa valores Digitados em um elemento do tipo campo,
* o encontrando por um seletor[Id, Name, Link, Css ou Xpath] e
* aguardando o carregamento dele antes de realizar a ação*/
public virtual void LimparCampo(By seletor)
{
EncontrarCampo(seletor).Clear();
}
public virtual void LimparCampo(IWebElement elemento)
{
elemento.Clear();
}
/**Realiza ação de clique em um elemento do tipo Botão, Link ou Checkbox,
* o encontrando por um seletor[Id, Name, Link, Css ou Xpath] e
* aguardando o carregamento dele antes de realizar a ação*/
public virtual void Clicar(By seletor)
{
RolarAteElemento(seletor);
AguardarVerElemento(seletor, TimeSpan.FromSeconds(50));
AguardarClicarElemento(seletor, TimeSpan.FromMinutes(1));
EncontrarCampo(seletor).Click();
AguardarPaginaCarregar();
}
public virtual void Clicar(IWebElement elemento)
{
AguardarSegundos();
RolarAteElemento(elemento);
AguardarSegundos();
elemento.Click();
AguardarPaginaCarregar();
}
public virtual void SubmeterFormulario(By seletor)
{
RolarAteElemento(seletor);
AguardarVerElemento(seletor, TimeSpan.FromSeconds(50));
AguardarClicarElemento(seletor, TimeSpan.FromMinutes(1));
EncontrarCampo(seletor).Submit();
AguardarPaginaCarregar();
AguardarElementoDesaparecer(seletor, TimeSpan.FromMinutes(1));
}
#endregion
#region Alerts
/**Aguarda a condição de apresentação de um alert,
por até 30 segundos e em caso negativo, falha*/
public virtual void AguadarAlert()
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(30))
.Until(ExpectedConditions.AlertIsPresent());
}
/**Aguarda a condição de apresentação de um alert,
por tempo parametrizado e em caso negativo falha*/
public virtual void AguadarAlert(TimeSpan tempo)
{
new WebDriverWait(Driver, tempo)
.Until(ExpectedConditions.AlertIsPresent());
}
public virtual void FecharPopup()
{
if (new AssertUtils(Driver).ValidarAlert())
Driver.SwitchTo().Alert().Dismiss();
}
#endregion
#region Scroll
public virtual void RolarParaFim(IWebDriver Driver)
{
IJavaScriptExecutor JS = (IJavaScriptExecutor)Driver;
JS.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");
}
public virtual void RolarParaBaixo(IWebDriver Driver)
{
IJavaScriptExecutor JS = (IJavaScriptExecutor)Driver;
JS.ExecuteScript("scroll(0, 2500);");
}
public virtual void RolarParaCima(IWebDriver Driver)
{
IJavaScriptExecutor JS = (IJavaScriptExecutor)Driver;
JS.ExecuteScript("scroll(2500, 0);");
}
public virtual void RolarAteElemento(By seletor)
{
IWebElement elemento = Driver.FindElement(seletor);
((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", elemento);
}
public virtual void RolarAteElemento(IWebElement _Elemento)
{
((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", _Elemento);
}
#endregion
}
} |
namespace TripDestination.Web.MVC.Areas.Admin.ViewModels
{
using Common.Infrastructure.Mapping;
using System;
using System.Web.Mvc;
using TripDestination.Data.Models;
[Bind(Exclude = "CreatedOn")]
public class ContactFormAdminViewModel : IMapFrom<ContactForm>
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public string Ip { get; set; }
public DateTime CreatedOn { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using webapicrud.Models;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace webapicrud.Controllers
{
public class crudwebapiController : ApiController
{
public static string mainconn = ConfigurationManager.ConnectionStrings["serverconn"].ConnectionString;
SqlConnection con = new SqlConnection(mainconn);
SqlCommand cmd;
SqlDataReader sdr;
[HttpGet]
public IHttpActionResult getdata()
{
List<EmpClass> ec = new List<EmpClass>();
//string mainconn = ConfigurationManager.ConnectionStrings["serverconn"].ConnectionString;
//SqlConnection con = new SqlConnection(mainconn);
con.Open();
cmd = new SqlCommand("select * from tbl_emp",con);
sdr = cmd.ExecuteReader();
while(sdr.Read())
{
ec.Add(new EmpClass()
{
no = Convert.ToInt32(sdr.GetValue(0)),
firstname = sdr.GetValue(1).ToString(),
lastname = sdr.GetValue(2).ToString(),
address = sdr.GetValue(3).ToString(),
contactno = sdr.GetValue(4).ToString(),
state = sdr.GetValue(5).ToString()
});
}
con.Close();
return Ok(ec);
}
[HttpPost]
public IHttpActionResult insert(EmpClass ecobj)
{
/*cmd = new SqlCommand("insert into tbl_emp values('" + Convert.ToInt32(ecobj.no) + "'," + ecobj.firstname + "," + ecobj.lastname + "," + ecobj.address + "," + ecobj.contactno + "," + ecobj.state + ")", con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();*/
SqlCommand cmd1 = new SqlCommand();
/*cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into tbl_emp(no,firstname,lastname,address,contactno,state) values(@empno,@empfnm,@emplnm,@empadd,@contact,@empstate)";
cmd1.Connection = con;*/
//cmd1 = new SqlCommand("insert into tbl_emp(no,firstname,lastname,address,contactno,state) values(@empno,@empfnm,@emplnm,@empadd,@contact,@empstate)",con);
cmd1 = new SqlCommand("insert into tbl_emp(no,firstname,lastname,address,contactno,state) values("+Convert.ToInt32(ecobj.no)+",'"+ecobj.firstname+"','"+ecobj.lastname+"','"+ecobj.address+"','"+ecobj.contactno+"','"+ecobj.state+"')", con);
/*cmd1.Parameters.AddWithValue("@empno", Convert.ToInt32(ecobj.no));
cmd1.Parameters.AddWithValue("@empfnm", ecobj.firstname);
cmd1.Parameters.AddWithValue("@emplnm", ecobj.lastname);
cmd1.Parameters.AddWithValue("@empadd", ecobj.address);
cmd1.Parameters.AddWithValue("@contact", ecobj.contactno);
cmd1.Parameters.AddWithValue("@empstate", ecobj.state);*/
con.Open();
int rowinserted = cmd1.ExecuteNonQuery();
con.Close();
return Ok(rowinserted);
}
/*public IHttpActionResult GetEmpid(int id)
{
List<EmpClass> ec = new List<EmpClass>();
//ec = null;
con.Open();
cmd = new SqlCommand("select * from tbl_emp where no = "+Convert.ToInt32(id)+"", con);
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
ec.Add(new EmpClass()
{
no = Convert.ToInt32(sdr.GetValue(0)),
firstname = sdr.GetValue(1).ToString(),
lastname = sdr.GetValue(2).ToString(),
address = sdr.GetValue(3).ToString(),
contactno = sdr.GetValue(4).ToString(),
state = sdr.GetValue(5).ToString()
});
}
con.Close();
webapiexampleEntities db = new webapiexampleEntities();
EmpClass ec = null;
ec = db.tbl_emp.Where(x => x.no == id).Select(x => new EmpClass()
{
no = x.no,
firstname = x.firstname,
lastname = x.lastname,
address = x.address,
contactno = x.contactno,
state = x.state,
}).FirstOrDefault<EmpClass>();
if(ec==null)
{
return NotFound();
}
return Ok(ec);
}*/
[HttpPut]
public IHttpActionResult put(EmpClass ecobj)
{
cmd = new SqlCommand("update tbl_emp set firstname = '"+ecobj.firstname+"',lastname = '"+ecobj.lastname+"',address = '"+ecobj.address+"',contactno = '"+ecobj.contactno+"',state = '"+ecobj.state+"' where no = "+ecobj.no+"",con);
con.Open();
int updaterecord = cmd.ExecuteNonQuery();
con.Close();
return Ok(updaterecord);
}
[HttpDelete]
public IHttpActionResult Delete(int id)
{
cmd = new SqlCommand("delete from tbl_emp where no = " + id + "", con);
con.Open();
int delete = cmd.ExecuteNonQuery();
con.Close();
return Ok(delete);
}
[HttpGet]
public IHttpActionResult idemp(int id)
{
/*List<EmpClass> ec = new List<EmpClass>();
cmd = new SqlCommand("select * from tbl_emp where no = " + id + "", con);
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
ec.Add(new EmpClass()
{
no = Convert.ToInt32(sdr.GetValue(0)),
firstname = sdr.GetValue(1).ToString(),
lastname = sdr.GetValue(2).ToString(),
address = sdr.GetValue(3).ToString(),
contactno = sdr.GetValue(4).ToString(),
state = sdr.GetValue(5).ToString()
});
}
con.Close();
return Ok(ec);*/
EmpClass ec = new EmpClass();
DataTable dt = new DataTable();
con.Open();
cmd = new SqlCommand("select * from tbl_emp where no = '" + id + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
con.Close();
if (dt.Rows.Count == 1)
{
ec.no = Convert.ToInt32(dt.Rows[0][0].ToString());
ec.firstname = dt.Rows[0][1].ToString();
ec.lastname = dt.Rows[0][2].ToString();
ec.address = dt.Rows[0][3].ToString();
ec.contactno = dt.Rows[0][4].ToString();
ec.state = dt.Rows[0][5].ToString();
return Ok(ec);
}
else
{
return Redirect("Getdata");
}
}
/*public IHttpActionResult getempid(EmpClass empobj)
{
webapiexampleEntities db = new webapiexampleEntities();
EmpClass ec = null;
ec = db.tbl_emp.Where(x => x.no == empobj.no).Select(x => new EmpClass()
{
no = Convert.ToInt32(x.no),
firstname = x.firstname,
lastname = x.lastname,
address = x.address,
contactno = x.contactno,
state = x.state,
}).FirstOrDefault<EmpClass>();
if(ec == null)
{
return NotFound();
}
return Ok(ec);
}*/
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DBDiff.Schema.Sybase.Options
{
public class AseOptionFilter
{
private Boolean filterIndex = true;
private Boolean filterConstraint = true;
private Boolean filterTrigger = true;
private Boolean filterUserDataType = true;
private Boolean filterTableOption = true;
private Boolean filterTable = true;
private Boolean filterView = true;
private Boolean filterStoreProcedure = true;
private Boolean filterFunction = true;
private Boolean filterTableFileGroup = true;
private Boolean filterExtendedPropertys = true;
private Boolean filterColumnPosition = true;
public AseOptionFilter()
{
new AseOptionFilter(true);
}
public AseOptionFilter(Boolean defaultValue)
{
FilterConstraint = defaultValue;
FilterFunction = defaultValue;
FilterStoreProcedure = defaultValue;
FilterView = defaultValue;
FilterTable = defaultValue;
FilterTableOption = defaultValue;
FilterUserDataType = defaultValue;
FilterTrigger = defaultValue;
FilterTableFileGroup = defaultValue;
FilterExtendedPropertys = defaultValue;
FilterColumnPosition = defaultValue;
}
public Boolean FilterColumnPosition
{
get { return filterColumnPosition; }
set { filterColumnPosition = value; }
}
public Boolean FilterExtendedPropertys
{
get { return filterExtendedPropertys; }
set { filterExtendedPropertys = value; }
}
public Boolean FilterTableFileGroup
{
get { return filterTableFileGroup; }
set { filterTableFileGroup = value; }
}
public Boolean FilterFunction
{
get { return filterFunction; }
set { filterFunction = value; }
}
public Boolean FilterStoreProcedure
{
get { return filterStoreProcedure; }
set { filterStoreProcedure = value; }
}
public Boolean FilterView
{
get { return filterView; }
set { filterView = value; }
}
public Boolean FilterTable
{
get { return filterTable; }
set { filterTable = value; }
}
public Boolean FilterTableOption
{
get { return filterTableOption; }
set { filterTableOption = value; }
}
public Boolean FilterUserDataType
{
get { return filterUserDataType; }
set { filterUserDataType = value; }
}
public Boolean FilterTrigger
{
get { return filterTrigger; }
set { filterTrigger = value; }
}
public Boolean FilterConstraint
{
get { return filterConstraint; }
set { filterConstraint = value; }
}
public Boolean FilterIndex
{
get { return filterIndex; }
set { filterIndex = value; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PetController : MonoBehaviour
{
public Transform goal;
public float speed = 0.5f; //ajustar para la animacion
public float acc = 1.0f;
public float rotSpeed = 0.5f;
void LateUpdate()
{
Vector3 lookAtGoal = new Vector3(goal.position.x,
this.transform.position.y,
goal.position.z);
Vector3 direction = lookAtGoal - this.transform.position;
if (Vector3.Distance(transform.position, lookAtGoal) > acc){
//Rotate pet
this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction),
Time.deltaTime*rotSpeed);
//Move pet
this.transform.Translate(0,0,speed*Time.deltaTime);
}
}
} |
namespace ClipModels
{
public class CustomSupplierUser
{
public static char BC_TYPE_DELIMITER = ',';
public int ID { get; set; }
public string UserName { get; set; }
public string SupplierName { get; set; }
public string SupplierID { get; set; }
public string Email { get; set; }
public bool CanChangeSupplierID { get; set; }
public string AllowedBCTypes { get; set; }
public bool QuickIngest { get; set; }
public string TrafficUserName { get; set; }
public bool IsActive { get; set; }
public bool IsAdmin { get; set; }
public bool IsModerator { get; set; }
public int[] GetAllowedBCTypes()
{
string[] tmpStr = AllowedBCTypes.Split(BC_TYPE_DELIMITER);
int[] tmpInt = new int[tmpStr.Length];
for (int i = 0; i < tmpStr.Length && i < tmpInt.Length; i++)
tmpInt[i] = int.Parse(tmpStr[i].Trim());
return tmpInt;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace Senparc.Core.Models.DataBaseModel.Mapping
{
public class CompetitionProgramConfigurationMapping : IEntityTypeConfiguration<CompetitionProgram>
{
public void Configure(EntityTypeBuilder<CompetitionProgram> builder)
{
builder.HasKey(z => z.Id);
builder.Property(e => e.BdImgUrl)
.IsUnicode(false);
builder.Property(e => e.ImgUrl)
.IsUnicode(false);
builder.HasMany(z => z.ProjectMembers)
.WithOne(z => z.CompetitionProgram)
.HasForeignKey(z => z.ProjectId)
.OnDelete(DeleteBehavior.Cascade);
}
}
}
|
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace DgKMS.Cube.CubeCore
{
public class EvernoteTag : Entity<int>, IPassivable, IHasCreationTime, IHasModificationTime
{
//[Column("id")]
public int Id { get; set; }
//[Column("id")]
//[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
//public new ulong? Id { get; set; }
/// <summary>
///
/// </summary>
public string Guid { get; set; }
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public string ParentGuid { get; set; }
/// <summary>
///
/// </summary>
public int UpdateSequenceNum { get; set; }
#region Auditing
[Column("is_active")]
public bool IsActive { get; set; }
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}", ApplyFormatInEditMode = true)]
[Column("create_time")]
public DateTime CreationTime { get; set; }
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}", ApplyFormatInEditMode = true)]
[Column("modified_time")]
public DateTime? LastModificationTime { get; set; }
#endregion
}
}
|
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual
{
/// <summary>
/// Implementación del Adaptador de Requerimiento Párrafo
/// </summary>
public class RequerimientoParrafoAdapter
{
/// <summary>
/// Realiza la adaptación de campos para registrar o actualizar
/// </summary>
/// <param name="data">Datos a registrar o actualizar</param>
/// <returns>Entidad Requerimiento Párrafo con los datos a registrar</returns>
public static RequerimientoParrafoEntity RegistrarRequerimientoParrafo(RequerimientoParrafoRequest data)
{
var contratoParrafoEntity = new RequerimientoParrafoEntity();
if (data.CodigoRequerimientoParrafo != null)
{
contratoParrafoEntity.CodigoRequerimientoParrafo = new Guid(data.CodigoRequerimientoParrafo.ToString());
}
else
{
Guid code;
code = Guid.NewGuid();
contratoParrafoEntity.CodigoRequerimientoParrafo = code;
}
contratoParrafoEntity.CodigoRequerimiento = new Guid(data.CodigoRequerimiento);
contratoParrafoEntity.CodigoPlantillaParrafo = new Guid(data.CodigoPlantillaParrafo);
contratoParrafoEntity.FechaCreacion = DateTime.Now;
contratoParrafoEntity.ContenidoParrafo = data.ContenidoParrafo;
return contratoParrafoEntity;
}
}
}
|
// kcp server logic abstracted into a class.
// for use in Mirror, DOTSNET, testing, etc.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace kcp2k
{
public class KcpServer
{
// callbacks
// even for errors, to allow liraries to show popups etc.
// instead of logging directly.
// (string instead of Exception for ease of use and to avoid user panic)
//
// events are readonly, set in constructor.
// this ensures they are always initialized when used.
// fixes https://github.com/MirrorNetworking/Mirror/issues/3337 and more
readonly Action<int> OnConnected;
readonly Action<int, ArraySegment<byte>, KcpChannel> OnData;
readonly Action<int> OnDisconnected;
readonly Action<int, ErrorCode, string> OnError;
// configuration
readonly KcpConfig config;
// state
protected Socket socket;
EndPoint newClientEP;
// raw receive buffer always needs to be of 'MTU' size, even if
// MaxMessageSize is larger. kcp always sends in MTU segments and having
// a buffer smaller than MTU would silently drop excess data.
// => we need the mtu to fit channel + message!
protected readonly byte[] rawReceiveBuffer;
// connections <connectionId, connection> where connectionId is EndPoint.GetHashCode
public Dictionary<int, KcpServerConnection> connections =
new Dictionary<int, KcpServerConnection>();
public KcpServer(Action<int> OnConnected,
Action<int, ArraySegment<byte>, KcpChannel> OnData,
Action<int> OnDisconnected,
Action<int, ErrorCode, string> OnError,
KcpConfig config)
{
// initialize callbacks first to ensure they can be used safely.
this.OnConnected = OnConnected;
this.OnData = OnData;
this.OnDisconnected = OnDisconnected;
this.OnError = OnError;
this.config = config;
// create mtu sized receive buffer
rawReceiveBuffer = new byte[config.Mtu];
// create newClientEP either IPv4 or IPv6
newClientEP = config.DualMode
? new IPEndPoint(IPAddress.IPv6Any, 0)
: new IPEndPoint(IPAddress.Any, 0);
}
public virtual bool IsActive() => socket != null;
static Socket CreateServerSocket(bool DualMode, ushort port)
{
if (DualMode)
{
// IPv6 socket with DualMode @ "::" : port
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
// settings DualMode may throw:
// https://learn.microsoft.com/en-us/dotnet/api/System.Net.Sockets.Socket.DualMode?view=net-7.0
// attempt it, otherwise log but continue
// fixes: https://github.com/MirrorNetworking/Mirror/issues/3358
try
{
socket.DualMode = true;
}
catch (NotSupportedException e)
{
Log.Warning($"Failed to set Dual Mode, continuing with IPv6 without Dual Mode. Error: {e}");
}
socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
return socket;
}
else
{
// IPv4 socket @ "0.0.0.0" : port
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, port));
return socket;
}
}
public virtual void Start(ushort port)
{
// only start once
if (socket != null)
{
Log.Warning("KcpServer: already started!");
return;
}
// listen
socket = CreateServerSocket(config.DualMode, port);
// recv & send are called from main thread.
// need to ensure this never blocks.
// even a 1ms block per connection would stop us from scaling.
socket.Blocking = false;
// configure buffer sizes
Common.ConfigureSocketBuffers(socket, config.RecvBufferSize, config.SendBufferSize);
}
public void Send(int connectionId, ArraySegment<byte> segment, KcpChannel channel)
{
if (connections.TryGetValue(connectionId, out KcpServerConnection connection))
{
connection.peer.SendData(segment, channel);
}
}
public void Disconnect(int connectionId)
{
if (connections.TryGetValue(connectionId, out KcpServerConnection connection))
{
connection.peer.Disconnect();
}
}
// expose the whole IPEndPoint, not just the IP address. some need it.
public IPEndPoint GetClientEndPoint(int connectionId)
{
if (connections.TryGetValue(connectionId, out KcpServerConnection connection))
{
return connection.remoteEndPoint as IPEndPoint;
}
return null;
}
// io - input.
// virtual so it may be modified for relays, nonalloc workaround, etc.
// https://github.com/vis2k/where-allocation
// bool return because not all receives may be valid.
// for example, relay may expect a certain header.
protected virtual bool RawReceiveFrom(out ArraySegment<byte> segment, out int connectionId)
{
segment = default;
connectionId = 0;
if (socket == null) return false;
try
{
if (socket.ReceiveFromNonBlocking(rawReceiveBuffer, out segment, ref newClientEP))
{
// set connectionId to hash from endpoint
// NOTE: IPEndPoint.GetHashCode() allocates.
// it calls m_Address.GetHashCode().
// m_Address is an IPAddress.
// GetHashCode() allocates for IPv6:
// https://github.com/mono/mono/blob/bdd772531d379b4e78593587d15113c37edd4a64/mcs/class/referencesource/System/net/System/Net/IPAddress.cs#L699
//
// => using only newClientEP.Port wouldn't work, because
// different connections can have the same port.
connectionId = newClientEP.GetHashCode();
return true;
}
}
catch (SocketException e)
{
// NOTE: SocketException is not a subclass of IOException.
// the other end closing the connection is not an 'error'.
// but connections should never just end silently.
// at least log a message for easier debugging.
Log.Info($"KcpServer: ReceiveFrom failed: {e}");
}
return false;
}
// io - out.
// virtual so it may be modified for relays, nonalloc workaround, etc.
// relays may need to prefix connId (and remoteEndPoint would be same for all)
protected virtual void RawSend(int connectionId, ArraySegment<byte> data)
{
// get the connection's endpoint
if (!connections.TryGetValue(connectionId, out KcpServerConnection connection))
{
return;
}
try
{
socket.SendToNonBlocking(data, connection.remoteEndPoint);
}
catch (SocketException e)
{
Log.Error($"KcpServer: SendTo failed: {e}");
}
}
protected virtual KcpServerConnection CreateConnection(int connectionId)
{
// events need to be wrapped with connectionIds
Action<ArraySegment<byte>> RawSendWrap =
data => RawSend(connectionId, data);
// create empty connection without peer first.
// we need it to set up peer callbacks.
// afterwards we assign the peer.
KcpServerConnection connection = new KcpServerConnection(newClientEP);
// set up peer with callbacks
KcpPeer peer = new KcpPeer(RawSendWrap, OnAuthenticatedWrap, OnDataWrap, OnDisconnectedWrap, OnErrorWrap, config);
// assign peer to connection
connection.peer = peer;
return connection;
// setup authenticated event that also adds to connections
void OnAuthenticatedWrap()
{
// only send handshake to client AFTER we received his
// handshake in OnAuthenticated.
// we don't want to reply to random internet messages
// with handshakes each time.
connection.peer.SendHandshake();
// add to connections dict after being authenticated.
connections.Add(connectionId, connection);
Log.Info($"KcpServer: added connection({connectionId})");
// setup Data + Disconnected events only AFTER the
// handshake. we don't want to fire OnServerDisconnected
// every time we receive invalid random data from the
// internet.
// setup data event
// finally, call mirror OnConnected event
Log.Info($"KcpServer: OnConnected({connectionId})");
OnConnected(connectionId);
}
void OnDataWrap(ArraySegment<byte> message, KcpChannel channel)
{
// call mirror event
//Log.Info($"KCP: OnServerDataReceived({connectionId}, {BitConverter.ToString(message.Array, message.Offset, message.Count)})");
OnData(connectionId, message, channel);
}
void OnDisconnectedWrap()
{
// flag for removal
// (can't remove directly because connection is updated
// and event is called while iterating all connections)
connectionsToRemove.Add(connectionId);
// call mirror event
Log.Info($"KcpServer: OnDisconnected({connectionId})");
OnDisconnected(connectionId);
}
void OnErrorWrap(ErrorCode error, string reason)
{
OnError(connectionId, error, reason);
}
}
// receive + add + process once.
// best to call this as long as there is more data to receive.
void ProcessMessage(ArraySegment<byte> segment, int connectionId)
{
//Log.Info($"KCP: server raw recv {msgLength} bytes = {BitConverter.ToString(buffer, 0, msgLength)}");
// is this a new connection?
if (!connections.TryGetValue(connectionId, out KcpServerConnection connection))
{
// create a new KcpConnection based on last received
// EndPoint. can be overwritten for where-allocation.
connection = CreateConnection(connectionId);
// DO NOT add to connections yet. only if the first message
// is actually the kcp handshake. otherwise it's either:
// * random data from the internet
// * or from a client connection that we just disconnected
// but that hasn't realized it yet, still sending data
// from last session that we should absolutely ignore.
//
//
// TODO this allocates a new KcpConnection for each new
// internet connection. not ideal, but C# UDP Receive
// already allocated anyway.
//
// expecting a MAGIC byte[] would work, but sending the raw
// UDP message without kcp's reliability will have low
// probability of being received.
//
// for now, this is fine.
// now input the message & process received ones
// connected event was set up.
// tick will process the first message and adds the
// connection if it was the handshake.
connection.peer.RawInput(segment);
connection.peer.TickIncoming();
// again, do not add to connections.
// if the first message wasn't the kcp handshake then
// connection will simply be garbage collected.
}
// existing connection: simply input the message into kcp
else
{
connection.peer.RawInput(segment);
}
}
// process incoming messages. should be called before updating the world.
// virtual because relay may need to inject their own ping or similar.
readonly HashSet<int> connectionsToRemove = new HashSet<int>();
public virtual void TickIncoming()
{
// input all received messages into kcp
while (RawReceiveFrom(out ArraySegment<byte> segment, out int connectionId))
{
ProcessMessage(segment, connectionId);
}
// process inputs for all server connections
// (even if we didn't receive anything. need to tick ping etc.)
foreach (KcpServerConnection connection in connections.Values)
{
connection.peer.TickIncoming();
}
// remove disconnected connections
// (can't do it in connection.OnDisconnected because Tick is called
// while iterating connections)
foreach (int connectionId in connectionsToRemove)
{
connections.Remove(connectionId);
}
connectionsToRemove.Clear();
}
// process outgoing messages. should be called after updating the world.
// virtual because relay may need to inject their own ping or similar.
public virtual void TickOutgoing()
{
// flush all server connections
foreach (KcpServerConnection connection in connections.Values)
{
connection.peer.TickOutgoing();
}
}
// process incoming and outgoing for convenience.
// => ideally call ProcessIncoming() before updating the world and
// ProcessOutgoing() after updating the world for minimum latency
public virtual void Tick()
{
TickIncoming();
TickOutgoing();
}
public virtual void Stop()
{
socket?.Close();
socket = null;
}
}
}
|
namespace EPI.Strings
{
/// <summary>
/// Remove all instances of "b" and replace all instances of "a" with "dd"
/// Assume string is stored in an array with sufficient capacity to handle final result
/// and we cannot use any new string or data structure, the original array must be modified in-place
/// </summary>
public static class ReplaceAndRemove
{
private const char ToRemove = 'b';
private const char ToReplace = 'a';
private const char ReplaceWith = 'd'; // 'a' is replaced with 'dd'
public static char[] ReplaceRemove(char[] source)
{
// assume the original char array is appended with ' ' slots to fit the size of the result
int countOfAs = 0;
int lengthWithoutBs = 0;
// first pass: remove the character toRemove and also find count of character to replace
for (int i = 0; i < source.Length && source[i] != ' '; i++)
{
if (source[i] != ToRemove)
{
source[lengthWithoutBs] = source[i];
lengthWithoutBs++;
}
if (source[i] == ToReplace)
{
countOfAs++;
}
}
// replace any remaining chars with empty slot
for (int i = lengthWithoutBs; i < source.Length; i++ )
{
source[i] = new char();
}
// new length of array is length without toRemove + count of toReplace
int writeIndex = lengthWithoutBs + countOfAs -1;
// second pass: starting from end replace all instances of toReplace with 2
// instances of the replaceWith char
for (int i = lengthWithoutBs - 1; i >= 0; i--, writeIndex--)
{
if (source[i] == ToReplace)
{
source[writeIndex--] = ReplaceWith;
source[writeIndex] = ReplaceWith;
}
else
{
source[writeIndex] = source[i];
}
}
return source;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AiBridge
{
public class Dendrite
{
/// <summary>
/// Input value (Pulse)
/// </summary>
public double Value { get; set; }
/// <summary>
/// Synaptic Weight
/// </summary>
public double Weight { get; private set; }
//public bool Learnable { get; set; } = true;
public Dendrite()
{
Weight = 0;
Value = 0;
}
public Dendrite(double weight, double value = 0)
{
Weight = weight;
Value = value;
}
public void AdjustWeight(double learningRate, double delta)
{
Weight += learningRate * delta;
}
}
}
|
namespace JunimoIntelliBox
{
using System;
using JunimoIntelliBox.Animations;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
public class JunimoSlave: NPC
{
private IMonitor monitor;
private InputHelper inputHelper;
private Vector2 movementDirection;
private IJunimoAnimation currentAnimation;
public JunimoSlave(Vector2 position, IMonitor monitor) :
base(new AnimatedSprite("Characters\\Junimo", 0, 16, 16), position, 0, "JunimoSlave", (LocalizedContentManager)null)
{
this.monitor = monitor;
this.inputHelper = new InputHelper();
this.ignoreMovementAnimation = true;
this.movementDirection = Vector2.Zero;
this.currentAnimation = new JunimoAnimationIdle(this);
}
public override void update(GameTime time, GameLocation location)
{
base.update(time, location);
//this.sprite.Animate(time, 8, 4, 100f);
this.MovePosition(time, Game1.viewport, location);
//this.monitor.Log($"JunimoSlave time = {time}, location = {location.Name}", LogLevel.Info);
//this.monitor.Log($"Junimo udpate(), xVelocity {this.xVelocity} yVelocity {this.yVelocity}", LogLevel.Info);
if (this.currentAnimation != null)
{
this.currentAnimation.Play(time);
}
}
public override void draw(SpriteBatch b, float alpha = 1f)
{
if (this.isInvisible)
return;
// Draw sprite frame;
b.Draw(this.Sprite.Texture,
this.getLocalPosition(Game1.viewport) + new Vector2((float)(this.sprite.Value.spriteWidth * Game1.pixelZoom / 2), (float)((double)this.sprite.Value.spriteHeight * 3.0 / 4.0 * (double)Game1.pixelZoom / Math.Pow((double)(this.sprite.Value.spriteHeight / 16), 2.0)) + (float)this.yJumpOffset - (float)(Game1.pixelZoom * 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Rectangle?(this.Sprite.SourceRect),
this.GetColor(),
this.rotation,
new Vector2((float)(this.sprite.Value.spriteWidth * Game1.pixelZoom / 2), (float)((double)(this.sprite.Value.spriteHeight * Game1.pixelZoom) * 3.0 / 4.0)) / (float)Game1.pixelZoom,
Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom,
this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None,
//Math.Max(0.0f, this.drawOnTop ? 0.991f : (float)(((double)(this.getStandingY() + this.whichJunimoFromThisHut) + (double)this.getStandingX() / 10000.0) / 10000.0))
(float)this.getStandingY() / 10000f
);
// Draw shadow
if (this.swimming || this.hideShadow)
return;
b.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.viewport, this.position + new Vector2((float)(this.sprite.Value.spriteWidth * Game1.pixelZoom) / 2f, (float)(Game1.tileSize * 3) / 4f - (float)Game1.pixelZoom)), new Rectangle?(Game1.shadowTexture.Bounds),
this.GetColor(),
0.0f,
new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y),
((float)Game1.pixelZoom + (float)this.yJumpOffset / 40f) * this.scale,
SpriteEffects.None,
Math.Max(0.0f, (float)this.getStandingY() / 10000f) - 1E-06f);
}
public Color GetColor()
{
return Color.LightGreen;
}
public bool HandleInputEvents(object sender, EventArgsInput e)
{
this.movementDirection = this.CalculateMovementBasedOnInput(e);
this.SetMovementBasedOnDirection(this.movementDirection);
IJunimoAnimation movementAnimation = this.DecideMovementAnimation(this.movementDirection);
if (movementAnimation == null)
{
this.currentAnimation = new JunimoAnimationIdle(this);
} else
{
this.currentAnimation = movementAnimation;
}
return true;
}
private Vector2 CalculateMovementBasedOnInput(EventArgsInput e)
{
if (this.inputHelper.IsOneOfTheseKeysDown(e.Button, Game1.options.moveUpButton))
{
return new Vector2(0, -1);
}
else if (this.inputHelper.IsOneOfTheseKeysDown(e.Button, Game1.options.moveRightButton))
{
return new Vector2(1, 0);
}
else if (this.inputHelper.IsOneOfTheseKeysDown(e.Button, Game1.options.moveDownButton))
{
return new Vector2(0, 1);
}
else if (this.inputHelper.IsOneOfTheseKeysDown(e.Button, Game1.options.moveLeftButton))
{
return new Vector2(-1, 0);
}
return Vector2.Zero;
}
private void SetMovementBasedOnDirection(Vector2 movementDirection)
{
float X = movementDirection.X;
float Y = movementDirection.Y;
this.Halt();
if (X > 0)
{
this.SetMovingRight(true);
} else if (X < 0)
{
this.SetMovingLeft(true);
}
if (Y > 0)
{
this.SetMovingDown(true);
}
else if (Y < 0)
{
this.SetMovingUp(true);
}
}
private IJunimoAnimation DecideMovementAnimation(Vector2 movementDirection)
{
float X = movementDirection.X;
float Y = movementDirection.Y;
if (Math.Abs(X) > Math.Abs(Y))
{
if (X > 0)
{
return new JunimoAnimationMoveRight(this);
}
else
{
return new JunimoAnimationMoveLeft(this);
}
} else
{
if (Y > 0)
{
return new JunimoAnimationMoveDown(this);
}
else
{
return new JunimoAnimationMoveUp(this);
}
}
}
}
}
|
using System.Web.Cors;
using Microsoft.Owin;
using Owin;
using Umbraco.Web;
using TestSite;
using Umbraco.Core;
using Umbraco.RestApi;
//To use this startup class, change the appSetting value in the web.config called
// "owin:appStartup" to be "UmbracoStandardOwinStartup"
[assembly: OwinStartup("UmbracoStandardOwinStartup", typeof(UmbracoStandardOwinStartup))]
namespace TestSite
{
/// <summary>
/// The standard way to configure OWIN for Umbraco
/// </summary>
/// <remarks>
/// The startup type is specified in appSettings under owin:appStartup - change it to "StandardUmbracoStartup" to use this class
/// </remarks>
public class UmbracoStandardOwinStartup : UmbracoDefaultOwinStartup
{
public override void Configuration(IAppBuilder app)
{
// Ensure the default options are configured
base.Configuration(app);
// Configuring the Umbraco REST API options
app.ConfigureUmbracoRestApi(new UmbracoRestApiOptions()
{
// Modify the CorsPolicy as required
CorsPolicy = new CorsPolicy()
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = true
}
});
// Enabling the authentication based on Umbraco back office cookie
// Uncomment below line when testing the HAL Browser inside Umbraco webapp
app.UseUmbracoCookieAuthenticationForRestApi(ApplicationContext.Current);
// Enabling the usage of auth token retrieved by backoffice user / login
// Uncomment below line when testing the PoC website
app.UseUmbracoBackOfficeTokenAuth();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using TfsMobile.Contracts;
using TfsMobile.Repositories.v1;
namespace TfsMobile.TestClient
{
class Program
{
static void Main(string[] args)
{
if (CheckLogin())
{
Console.WriteLine("Login success!!!");
Console.WriteLine("Builds:");
var rep = new BuildsRepository(LoginDetails(), false);
var res = rep.GetBuilds(BuildDetailsDto.Default());
foreach (var buildContract in res)
{
Console.WriteLine("Name: " + buildContract.Name + " - Status: " + buildContract.Status +
" - Finished: " + buildContract.FinishTime);
}
Console.WriteLine("History last 7 days;");
var historyRep = new HistoryRepository(LoginDetails(),false);
var hist =
historyRep.GetHistoryAsync(new RequestHistoryDto() { FromDays = "20", TfsProject = "Byggtjeneste - Projects" }).Result;
foreach (var h in hist)
{
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Id: " + h.Id + " - AreaPath: " + h.AreaPath);
Console.WriteLine("- Description: " + h.Description);
Console.WriteLine("- HistoryDate:" + h.HistoryDate + "- HistoryItemType:" + h.HistoryItemType +
"- State:" + h.State);
Console.WriteLine("- IterationPath" + h.IterationPath);
Console.WriteLine("- ItemUrl" + h.TfsItemUri);
Console.WriteLine("- WorkType" + h.WorkType);
Console.WriteLine("-------------------------------------------------------");
}
}
Console.ReadKey();
}
private static bool CheckLogin()
{
//return true;
var rep = new LoginRepository(LoginDetails(), false);
return rep.TryLogin();
}
private static RequestTfsUserDto LoginDetails()
{
var userDetails = RequestTfsUserDto.Default();
userDetails.Username = "tomindre/crayon";
userDetails.Password = "pwd";
return userDetails;
}
}
}
|
using StateMachine;
namespace PJEI.Invaders {
/// <summary>
/// Reference alien state to use as a base to create the actual alien states.
/// </summary>
class SampleAlienState : State<Alien> {
#region Singleton
private static SampleAlienState instance = null;
public static SampleAlienState Instance {
get {
if (instance == null)
instance = new SampleAlienState();
return instance;
}
}
#endregion
private SampleAlienState() {
// Assign the functions to use for each case.
// OnEnter, OnUpdate and OnExit are variables which point to functions
// and can later call them, passing the proper parameters.
// If null is assigned to any of them, no function is called.
OnEnter = EnterState;
OnUpdate = UpdateState;
OnExit = ExitState;
}
private void EnterState(Alien alien) {
}
private void UpdateState(Alien alien) {
}
private void ExitState(Alien alien) {
}
}
// TODO : Add the actual states, using SampleAlienState as reference.
// Possible states: StartMoveLeft, MoveDown, MoveLeft, MoveRight
// Simplified states: Startup, MoveDown, MoveSideways
}
|
using gView.Framework.Carto;
using gView.Framework.Geometry;
namespace gView.Framework.Symbology
{
public interface ITextSymbol : ISymbol, ILabel, ISymbolTransformation, ISymbolRotation
{
GraphicsEngine.Abstraction.IFont Font { get; set; }
float MaxFontSize { get; set; }
float MinFontSize { get; set; }
void Draw(IDisplay display, IGeometry geometry, TextSymbolAlignment symbolAlignment);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PixelRobot
{
public class PixelRobotTarget
{
private TargetStatus status;
private string fileName;
private string sourceFolder;
public PixelRobotTarget(string f, string s)
{
fileName = f;
if (File.Exists(fileName))
{
Status = TargetStatus.Ready;
if (s == null)
{
FileInfo fi = new FileInfo(fileName);
sourceFolder = fi.DirectoryName;
}
else
sourceFolder = s;
}
else
Status = TargetStatus.Missing;
}
public void RunItem()
{
Status = TargetStatus.Running;
}
public void QueueItem()
{
Status = TargetStatus.Queued;
}
public void FinishItem()
{
Status = TargetStatus.Complete;
}
public void HoldItem()
{
Status = TargetStatus.Hold;
}
public void ReleaseItem()
{
Status = TargetStatus.Ready;
}
public TargetStatus Status
{
get
{
return status;
}
set
{
status = value;
}
}
public string StatusText
{
get
{
return Status.ToString();
}
}
public string Filename
{
get
{
return fileName;
}
}
public string ShortFilename
{
get
{
return System.IO.Path.GetFileName(fileName);
}
}
public string SourceFolder
{
get
{
return sourceFolder;
}
}
}
}
|
namespace Application
{
public class MemberDto
{
public int Id { get; set; }
public decimal Rating { get; set; }
}
}
|
using LookieLooks.Api.Interfaces;
using LookieLooks.Api.Model;
using Microsoft.AspNetCore.Mvc;
namespace LookieLooks.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class VoteController : ControllerBase
{
private readonly IVoteService _voteService;
public VoteController(IVoteService voteService)
{
_voteService = voteService;
}
[Route("ComputeVote")]
[HttpPost]
public void ComputeVoteAsync([FromBody] Vote vote)
{
_voteService.ComputeVoteAsync(vote);
}
}
}
|
using Discord;
using System.Collections.Immutable;
namespace JhinBot
{
public interface IBotCredentials : IService
{
ulong ClientId { get; }
string Token { get; }
ImmutableArray<ulong> OwnerIds { get; }
string TrelloToken { get; }
string TrelloApiKey { get; }
string TrelloBoardId { get; }
DBConfig Db { get; }
bool IsOwner(IUser u);
}
public class DBConfig
{
public DBConfig(string type, string connString)
{
Type = type;
ConnectionString = connString;
}
public string Type { get; }
public string ConnectionString { get; }
}
}
|
namespace P05LinkedQueue
{
using System.Collections.Generic;
public interface IQueue<T> : IEnumerable<T>
{
int Count { get; }
void Enqueue(T element);
T Dequeue();
T[] ToArray();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Serialization.Configuration
{
public interface ICorrelator
{
ICorrelationMatrixColumn GetColumns();
}
public interface ICorrelationMatrix
{
// Opcional.Name
string TitleSource { get; set; }
// Opcional.CodOpcional
string PropertyName { get; set; }
// System.Int32
string PropertyType { get; set; }
IList<ICorrelationMatrixColumn> Columns { get; set; }
}
public interface ICorrelationMatrixColumn
{
// SOS Viagem
string Title { get; set; }
// 1
string PropertyValue { get; set; }
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
namespace ReducedGrinding.Items.LockBoxes
{
public class Shadow_Lock_Box : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Shadow Lock Box");
Tooltip.SetDefault("Right click to open\nRequires a Shadow Key");
}
public override void SetDefaults()
{
item.width = 32;
item.height = 22;
item.maxStack = 99;
item.rare = 3;
item.value = Item.buyPrice(0, 1, 0, 0);
}
public override bool CanRightClick()
{
Player player = Main.player[Main.myPlayer];
if (player.HasItem(ItemID.ShadowKey))
return true;
else
return false;
}
public override void RightClick(Player player)
{
float dropChance = 0f;
int testItemID = 0;
int chosenID = 0;
if (GetInstance<GLockbBoxConfig>().LockBoxesGiveFurniture)
{
//Ruined House Banners
if (Main.rand.Next(3) == 0)
player.QuickSpawnItem(1464, 1); //Hellhound Banner
if (Main.rand.Next(3) == 0)
player.QuickSpawnItem(1465, 1); //Hell Hammer Banner
if (Main.rand.Next(3) == 0)
player.QuickSpawnItem(1466, 1); //Hell Tower Banner
if (Main.rand.Next(3) == 0)
player.QuickSpawnItem(1467, 1); //Lost Hopes Banner
if (Main.rand.Next(3) == 0)
player.QuickSpawnItem(1468, 1); //Obsidian Watcher Banner
if (Main.rand.Next(3) == 0)
player.QuickSpawnItem(1469, 1); //Lava Erupts Banner
//Ruined House Furniture
if (Main.rand.Next(5) == 0)
{
player.QuickSpawnItem(221, 1); //Hellforge
}
if (Main.rand.Next(2) == 0)
player.QuickSpawnItem(433, Main.rand.Next(5, 11)); //Demon Torch
dropChance = 0.04f; //About 4 furniture for rollng 5 times for 20 furnitures.
for (int i = 0; i <= 4; i++) //Other Furniture
{
for (testItemID = 1457; testItemID <= 1463; testItemID++)
{
if (Main.rand.NextFloat() < dropChance)
chosenID = testItemID;
}
if (Main.rand.NextFloat() < dropChance)
chosenID = 1473;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2380;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2390;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2406;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2600;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2618;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2642;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2644;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2651;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2657;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2662;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2667;
if (Main.rand.NextFloat() < dropChance)
chosenID = 2840;
player.QuickSpawnItem(chosenID);
chosenID = 0;
}
//Ruined House Paintings
dropChance = 0.0556f; //About 2 paintings when rolling 3 times for 12 paintings
for (int i = 0; i <= 2; i++)
{
if (Main.rand.NextFloat() < dropChance)
chosenID = 1475;
if (Main.rand.NextFloat() < dropChance)
chosenID = 1476;
if (Main.rand.NextFloat() < dropChance)
chosenID = 1478;
if (Main.rand.NextFloat() < dropChance)
chosenID = 1479;
if (Main.rand.NextFloat() < dropChance)
chosenID = 1497;
if (Main.rand.NextFloat() < dropChance)
chosenID = 1499;
if (Main.rand.NextFloat() < dropChance)
chosenID = 1501;
for (testItemID = 1538; testItemID <= 1542; testItemID++)
{
if (Main.rand.NextFloat() < dropChance)
chosenID = testItemID;
}
player.QuickSpawnItem(chosenID);
chosenID = 0;
}
}
if (GetInstance<GLockbBoxConfig>().LockBoxesGiveNonFurniture)
{
//Shadow Lock Box Rare Items
switch (Main.rand.Next(5))
{
case 0:
player.QuickSpawnItem(ItemID.DarkLance, 1);
break;
case 1:
player.QuickSpawnItem(ItemID.Flamelash, 1);
break;
case 2:
player.QuickSpawnItem(ItemID.FlowerofFire, 1);
break;
case 3:
player.QuickSpawnItem(ItemID.Sunfury, 1);
break;
case 4:
player.QuickSpawnItem(ItemID.HellwingBow, 1);
break;
}
if (Main.rand.Next(3) == 0)
player.QuickSpawnItem(ItemID.Dynamite, 1);
if (Main.rand.Next(2) == 0)
{
if (Main.rand.Next(1) == 0)
{
player.QuickSpawnItem(ItemID.MeteoriteBar, Main.rand.Next(15, 30)); //First number in inclusive, 2nd is exclusive
}
else
{
player.QuickSpawnItem(WorldGen.goldBar, Main.rand.Next(15, 30));
}
}
if (Main.rand.Next(2) == 0)
{
if (Main.rand.Next(1) == 0)
{
player.QuickSpawnItem(ItemID.HellfireArrow, Main.rand.Next(50, 75));
}
else
{
player.QuickSpawnItem(ItemID.SilverBullet, Main.rand.Next(50, 75));
}
}
if (Main.rand.Next(2) == 0)
{
if (Main.rand.Next(1) == 0)
{
player.QuickSpawnItem(ItemID.LesserRestorationPotion, Main.rand.Next(15, 21));
}
else
{
player.QuickSpawnItem(ItemID.RestorationPotion, Main.rand.Next(15, 21));
}
}
if (Main.rand.Next(4) <= 2)
{
switch (Main.rand.Next(8))
{
case 0:
player.QuickSpawnItem(ItemID.SpelunkerPotion, Main.rand.Next(1, 3));
break;
case 1:
player.QuickSpawnItem(ItemID.FeatherfallPotion, Main.rand.Next(1, 3));
break;
case 2:
player.QuickSpawnItem(ItemID.ManaRegenerationPotion, Main.rand.Next(1, 3));
break;
case 3:
player.QuickSpawnItem(ItemID.ObsidianSkinPotion, Main.rand.Next(1, 3));
break;
case 4:
player.QuickSpawnItem(ItemID.MagicPowerPotion, Main.rand.Next(1, 3));
break;
case 5:
player.QuickSpawnItem(ItemID.InvisibilityPotion, Main.rand.Next(1, 3));
break;
case 6:
player.QuickSpawnItem(ItemID.HunterPotion, Main.rand.Next(1, 3));
break;
case 7:
player.QuickSpawnItem(ItemID.HeartreachPotion, Main.rand.Next(1, 3));
break;
}
}
if (Main.rand.Next(3) <= 1)
{
switch (Main.rand.Next(8))
{
case 0:
player.QuickSpawnItem(ItemID.GravitationPotion, Main.rand.Next(1, 3));
break;
case 1:
player.QuickSpawnItem(ItemID.ThornsPotion, Main.rand.Next(1, 3));
break;
case 2:
player.QuickSpawnItem(ItemID.WaterWalkingPotion, Main.rand.Next(1, 3));
break;
case 3:
player.QuickSpawnItem(ItemID.ObsidianSkinPotion, Main.rand.Next(1, 3));
break;
case 4:
player.QuickSpawnItem(ItemID.BattlePotion, Main.rand.Next(1, 3));
break;
case 5:
player.QuickSpawnItem(ItemID.TeleportationPotion, Main.rand.Next(1, 3));
break;
case 6:
player.QuickSpawnItem(ItemID.InfernoPotion, Main.rand.Next(1, 3));
break;
case 7:
player.QuickSpawnItem(ItemID.LifeforcePotion, Main.rand.Next(1, 3));
break;
}
}
if (Main.rand.Next(3) == 0)
{
player.QuickSpawnItem(ItemID.RecallPotion, Main.rand.Next(1, 3));
}
if (Main.rand.Next(2) == 0)
{
if (Main.rand.Next(1) == 0)
{
player.QuickSpawnItem(ItemID.Torch, Main.rand.Next(15, 30));
}
else
{
player.QuickSpawnItem(ItemID.Glowstick, Main.rand.Next(15, 30));
}
}
if (Main.rand.Next(2) == 0)
player.QuickSpawnItem(ItemID.GoldCoin, Main.rand.Next(2, 5));
}
}
}
} |
namespace KK.AspNetCore.EasyAuthAuthentication.Models
{
using System;
using System.Security.Claims;
/// <summary>
/// All options you can set per provider.
/// </summary>
public class ProviderOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="ProviderOptions"/> class.
/// </summary>
/// <param name="providerName">The name of the provider.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0021:Use expression body for constructors", Justification = "This syntax is better for the human eyes.")]
public ProviderOptions(string providerName)
{
this.ProviderName = providerName;
}
/// <summary>
/// Initializes a new instance of the <see cref="ProviderOptions"/> class.
/// </summary>
/// <param name="providerName">The name of the provider.</param>
/// <param name="nameClaimType">The name of the field in the provider data, that contains the name of the user.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0021:Use expression body for constructors", Justification = "This syntax is better for the human eyes.")]
public ProviderOptions(string providerName, string nameClaimType)
{
this.ProviderName = providerName;
this.NameClaimType = nameClaimType;
}
/// <summary>
/// Initializes a new instance of the <see cref="ProviderOptions"/> class.
/// </summary>
/// <param name="providerName">The name of the provider.</param>
/// <param name="nameClaimType">The name of the field in the provider data, that contains the name of the user.</param>
/// <param name="roleNameClaimType">The name of the field in the provider data, that contains all roles of the user.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0021:Use expression body for constructors", Justification = "This syntax is better for the human eyes.")]
public ProviderOptions(string providerName, string nameClaimType, string roleNameClaimType)
{
this.ProviderName = providerName;
this.NameClaimType = nameClaimType;
this.RoleClaimType = roleNameClaimType;
}
/// <summary>
/// The <c>ClaimType</c> for the Idendity User.
/// </summary>
/// <value>The Claim Type to use for the User. Default is <c>ClaimType</c> of the auth provider.</value>
public string NameClaimType { get; set; } = ClaimTypes.Name;
/// <summary>
/// The <c>ClaimType</c> for the Idendity Role.
/// </summary>
/// <value>The Claim Type to use for the Roles. Default is <c>ClaimType</c> of the auth provider.</value>
public string RoleClaimType { get; set; } = ClaimTypes.Role;
/// <summary>
/// The provider name for this options object.
/// </summary>
public string ProviderName { get; private set; }
/// <summary>
/// Define if this provide is active.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// That would change the defined options of the current provider options object.
/// </summary>
/// <param name="options">The provider options model with the new options.</param>
public void ChangeModel(ProviderOptions? options)
{
if (options == null)
{
return;
}
else if (options.ProviderName != this.ProviderName)
{
throw new ArgumentException("You can only use the method ChangeModel if you use the same provider name.");
}
else
{
if (!string.IsNullOrWhiteSpace(options.NameClaimType))
{
this.NameClaimType = options.NameClaimType;
}
if (!string.IsNullOrWhiteSpace(options.RoleClaimType))
{
this.RoleClaimType = options.RoleClaimType;
}
this.Enabled = options.Enabled;
}
}
}
}
|
using System;
namespace Robot.Cli
{
class Program
{
static void Main(string[] _)
{
try {
var robot = new Robot(new World(5, 5));
var cli = new TextInterface(Console.In, Console.Out, Console.Error);
cli.Run(robot);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}
|
using System.Web.Mvc;
namespace DevExpress.Web.Demos {
public partial class ChartController : DemoController {
[HttpGet]
public ActionResult RangeViews() {
ChartViewTypeDemoOptions options = new ChartViewTypeDemoOptions();
options.View = DevExpress.XtraCharts.ViewType.RangeBar;
ViewData[ChartDemoHelper.OptionsKey] = options;
return DemoView("RangeViews", OilPricesProvider.GetOilPrices());
}
[HttpPost]
public ActionResult RangeViews([Bind] ChartViewTypeDemoOptions options) {
ViewData[ChartDemoHelper.OptionsKey] = options;
return DemoView("RangeViews", OilPricesProvider.GetOilPrices());
}
}
}
|
namespace SnowBLL.Models.Routes
{
public interface IPagingRequestModel
{
int? Page { get; set; }
int? PageSize { get; set; }
}
} |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(AspNetMvcWebApplicationIdentity.Startup))]
namespace AspNetMvcWebApplicationIdentity
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
|
using Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Application.Core.ServiceContract;
using Pe.Stracon.SGC.Cross.Core.Base;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.SGC.Presentacion.Core.Controllers.Base;
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base;
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.ReporteContratoPorVencer;
using Pe.Stracon.SGC.Presentacion.Recursos.Base;
using Pe.Stracon.SGC.Presentacion.Recursos.Contractual;
using System.Web.Mvc;
using System.Linq;
namespace Pe.Stracon.SGC.Presentacion.Core.Controllers.Contractual
{
/// <summary>
/// Controladora de Reporte de Contrato por Vencer
/// </summary>
/// <remarks>
/// Creación: GMD 20150630 </br>
/// Modificación: </br>
/// </remarks>
public class ReporteContratoPorVencerController : GenericController
{
#region Parámetros
/// <summary>
/// Servicio de manejo de parametro valor
/// </summary>
public IPoliticaService politicaService { get; set; }
/// <summary>
/// Servicio de manejo de Unidad Operativa
/// </summary>
public IUnidadOperativaService unidadOperativaService { get; set; }
/// <summary>
/// Interfaz para el manejo de auditoría
/// </summary>
public IEntornoActualAplicacion entornoActualAplicacion { get; set; }
#endregion
#region Vistas
/// <summary>
/// Muestra la vista Index
/// </summary>
/// <returns>Vista Index</returns>
public ActionResult Index(ReporteContratoPorVencerRequest filtro)
{
var alertaVencimientoContrato = politicaService.ListarAlertaVencimientoContratoDinamico().Result;
if (alertaVencimientoContrato != null)
{
if (alertaVencimientoContrato.Where(i => i.Atributo1 == DatosConstantes.AlertaVencimientoContrato.Rojo).Count() > 0)
{
filtro.NumeroDiaRojo = alertaVencimientoContrato.Where(i => i.Atributo1 == DatosConstantes.AlertaVencimientoContrato.Rojo).FirstOrDefault().Atributo3.ToString();
}
if (alertaVencimientoContrato.Where(i => i.Atributo1 == DatosConstantes.AlertaVencimientoContrato.Ambar).Count() > 0)
{
filtro.NumeroDiaAmbar = alertaVencimientoContrato.Where(i => i.Atributo1 == DatosConstantes.AlertaVencimientoContrato.Ambar).FirstOrDefault().Atributo3.ToString();
}
}
var unidadOperativa = unidadOperativaService.BuscarUnidadOperativa(new FiltroUnidadOperativa() { Nivel = DatosConstantes.Nivel.Proyecto });
var estadoContrato = politicaService.ListarEstadoContrato();
var modelo = new ReporteContratoPorVencerBusqueda(unidadOperativa.Result, estadoContrato.Result, filtro.VencimientoDesdeString, filtro.VencimientoHastaString);
if (modelo.FechaVencimientoDesdeString !=null)
{
filtro.VencimientoDesdeString = modelo.FechaVencimientoDesdeString;
}
if (modelo.FechaVencimientoHastaString != null)
{
filtro.VencimientoHastaString = modelo.FechaVencimientoHastaString;
}
if (filtro != null)
{
TempData["DataReport"] = CrearModelo(filtro);
}
return View(modelo);
}
#endregion
/// <summary>
/// Asigna los parámetros necesarios para el reporte
/// </summary>
/// <param name="filtro">Filtro de Búsqueda para el reporte</param>
/// <returns>Modelo con parámetros para el reporte</returns>
private ReporteViewModel CrearModelo(ReporteContratoPorVencerRequest filtro)
{
var reporteModel = new ReporteViewModel();
reporteModel.RutaReporte += DatosConstantes.ReporteNombreArchivo.ReporteContratoPorVencer;
reporteModel.AgregarParametro("CODIGO_LENGUAJE", DatosConstantes.Iternacionalizacion.ES_PE);
reporteModel.AgregarParametro("USUARIO", entornoActualAplicacion.UsuarioSession);
reporteModel.AgregarParametro("NOMBRE_REPORTE", ReporteContratoPorVencerResource.EtiquetaTitulo.ToUpper());
reporteModel.AgregarParametro("FORMATO_FECHA_CORTA", DatosConstantes.Formato.FormatoFecha);
reporteModel.AgregarParametro("FORMATO_HORA_CORTA", DatosConstantes.Formato.FormatoHora);
reporteModel.AgregarParametro("FORMATO_NUMERO_ENTERO", DatosConstantes.Formato.FormatoNumeroEntero);
reporteModel.AgregarParametro("FORMATO_NUMERO_DECIMAL", DatosConstantes.Formato.FormatoNumeroDecimal);
reporteModel.AgregarParametro("PIE_REPORTE", string.Format(GenericoResource.EtiquetaFinReporte, ReporteContratoPorVencerResource.EtiquetaTitulo.ToUpper()));
reporteModel.AgregarParametro("CODIGO_UNIDAD_OPERATIVA", filtro.CodigoUnidadOperativa);
var array_fecha_desde = filtro.VencimientoDesdeString.Split('/');
filtro.VencimientoDesdeString = array_fecha_desde[2] + array_fecha_desde[1] + array_fecha_desde[0];
var array_fecha_hasta = filtro.VencimientoHastaString.Split('/');
filtro.VencimientoHastaString = array_fecha_hasta[2] + array_fecha_hasta[1] + array_fecha_hasta[0];
reporteModel.AgregarParametro("FECHA_INICIO", filtro.VencimientoDesdeString);
reporteModel.AgregarParametro("FECHA_FIN", filtro.VencimientoHastaString);
reporteModel.AgregarParametro("ESTADO", DatosConstantes.EstadoContrato.Vigente);
reporteModel.AgregarParametro("NUMDIAS_ROJO", filtro.NumeroDiaRojo);
reporteModel.AgregarParametro("NUMDIAS_AMBAR", filtro.NumeroDiaAmbar);
reporteModel.AgregarParametro("NOMBRE_UNIDAD_OPERATIVA", filtro.NombreUnidadOperativa);
reporteModel.AgregarParametro("DESCRIPCION_ESTADO_CONTRATO", "Vigente");
return reporteModel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.JScript.Vsa;
using Devin;
namespace Web.EncodeAndDecode
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username1 = Request.QueryString["username1"];
string username2 = Request.QueryString["username2"];
string username3 = Request.QueryString["username3"];
string username4 = Request.QueryString["username4"];
string myusername1 = Microsoft.JScript.GlobalObject.decodeURIComponent(username2);
string myusername2 = Microsoft.JScript.GlobalObject.decodeURIComponent(username4);
string myusername3 = System.Web.HttpUtility.UrlDecode(username1);
string myusername4 = Microsoft.JScript.GlobalObject.decodeURI(username2);
string myusername5 = System.Web.HttpUtility.UrlEncode("沈金龙");
string myusername6 = Server.UrlDecode(username4);
Microsoft.JScript.GlobalObject.encodeURIComponent("");
Microsoft.JScript.GlobalObject.encodeURI("");
try {
string qq = Request.QueryString["89"];
string a = qq.Replace('a','2');
}
catch(Exception ex) {
Devin.LogUtil.WriteError(new Exception(ex.Message));
Devin.LogUtil.WriteLog(ex.Message + "呵呵哒!", Devin.LogType.Info);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using vega3.Models;
using vega3.Controllers.Resources;
namespace vega3.Controllers {
[Route ("/api/vehicles")]
public class VehiclesController : Controller {
private readonly IMapper mapper;
public VehiclesController (IMapper mapper) {
this.mapper = mapper;
}
[HttpPost]
public IActionResult CreateVehicle ([FromBody] VehicleResource vehicleResource) {
var vehicle = mapper.Map<Vehicle>(vehicleResource);
return Ok (vehicle);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Taser : Interactable {
public override void Activate()
{
base.Activate();
if (!electrified)
{
GetElectrified(null);
electricityScript.canSpread = true;
electricityScript.firstGeneration = true;
}
else Deactivate();
}
public override void Deactivate()
{
StopElectrified();
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WindowsFormsApplication2;
using ZipOneCode.ZipProvider;
public partial class adminbody : System.Web.UI.Page
{
SqlConnection mycn;
string mycns = ConfigurationSettings.AppSettings["connString"];
SqlServerDataBase sdb = new SqlServerDataBase();
protected void Page_Load(object sender, EventArgs e)
{
Session["id"] = "y";
if (!Page.IsPostBack)
{
ss_text.Visible = true;
DropDownList2.Visible = false;
btss.Visible = true;
if (Request.QueryString["admintype"] != null)
{
string str = Request.QueryString["admintype"];
Session["admintype"] = str;
if(str=="全部")
{
Session["admintype"] = "";
}
}
else
{
Session["admintype"] = "";
}
using (SqlConnection mycn = new SqlConnection(mycns))
{
using (SqlCommand sqlcmm = mycn.CreateCommand())
{
mycn.Open();
try
{
sqlcmm.CommandText = "select userID,username,password,usertype,cmpID,qyxqID,userdate,begindate,lasttime,CONVERT(nvarchar(20),DATEDIFF(DAY,GETDATE(),userdate)) as overdue,DATEDIFF(DAY,begindate,GETDATE()) as begindue,showname from User_Reg where usertype like '%" + Session["admintype"].ToString() + "%' order by usertype,begindate desc";
if (Session["admintype"].ToString() == "企业" || Session["admintype"].ToString() == "孵化企业" || Session["admintype"].ToString() == "合作企业")
{
sqlcmm.CommandText = "select userID,username,password,ryzt as usertype,cmpID,qyxqID,userdate,begindate,lasttime,CONVERT(nvarchar(20),DATEDIFF(DAY,GETDATE(),userdate)) as overdue,DATEDIFF(DAY,begindate,GETDATE()) as begindue,showname from User_Reg left join nryqyxxk on(userID=qyID) where usertype like '%" + Session["admintype"].ToString() + "%' order by usertype,begindate desc";
}
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmm);
adapter.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["username"].ToString() == "人南总经理" || dt.Rows[i]["username"].ToString() == "校本部总经理" || dt.Rows[i]["username"].ToString() == "总经理")
{
dt.Rows[i]["usertype"] += "(总公司)";
}
if (dt.Rows[i]["username"].ToString() == "菁蓉总经理")
{
dt.Rows[i]["usertype"] += "(子公司)";
}
if (int.Parse(dt.Rows[i]["overdue"].ToString()) < 1)
{
dt.Rows[i]["overdue"] = "已过有效期";
}
else
{
dt.Rows[i]["overdue"] = dt.Rows[i]["overdue"].ToString() + "天";
}
if (int.Parse(dt.Rows[i]["begindue"].ToString()) < 0)
{
dt.Rows[i]["overdue"] = "未到有效期";
}
}
if (dt.Rows.Count > 0) //当数据库有数据的时候绑定数据
{
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
//bindgrid();
}
else
{
img_nodigit.Visible = true;
}
}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message.Replace("'", "*") + "')</script>");
}
finally
{
mycn.Close();
}
}
}
}
}
void bindgrid()
{
//查询数据库
DataSet ds = new DataSet();
SqlConnection mycn = new SqlConnection(mycns);
try
{
using (SqlConnection sqlconn = new SqlConnection(mycns))
{
mycn.Open();
string str = "select userID,username,password,usertype,cmpID,qyxqID,userdate,begindate,lasttime,CONVERT(nvarchar(20),DATEDIFF(DAY,GETDATE(),userdate)) as overdue,DATEDIFF(DAY,begindate,GETDATE()) as begindue,showname from User_Reg where usertype like '%" + Session["admintype"].ToString() + "%' order by usertype,begindate desc";
if (Session["admintype"].ToString() == "企业")
{
str = "select userID,username,password,ryzt as usertype,cmpID,qyxqID,userdate,begindate,lasttime,CONVERT(nvarchar(20),DATEDIFF(DAY,GETDATE(),userdate)) as overdue,DATEDIFF(DAY,begindate,GETDATE()) as begindue,showname from User_Reg left join nryqyxxk on(userID=qyID) where usertype like '%" + Session["admintype"].ToString() + "%' order by usertype,begindate desc";
}
SqlDataAdapter sqld = new SqlDataAdapter(str, sqlconn);
sqld.Fill(ds, "tabenterprise");
}
for (int i = 0; i < ds.Tables[0].Rows.Count;i++ )
{
if (ds.Tables[0].Rows[i]["username"].ToString() == "人南总经理" || ds.Tables[0].Rows[i]["username"].ToString() == "校本部总经理" || ds.Tables[0].Rows[i]["username"].ToString() == "总经理")
{
ds.Tables[0].Rows[i]["usertype"]+="(总公司)";
}
if (ds.Tables[0].Rows[i]["username"].ToString() == "菁蓉总经理")
{
ds.Tables[0].Rows[i]["usertype"] += "(子公司)";
}
if (int.Parse(ds.Tables[0].Rows[i]["overdue"].ToString())<1) {
ds.Tables[0].Rows[i]["overdue"] = "已过有效期";
}
else{
ds.Tables[0].Rows[i]["overdue"] = ds.Tables[0].Rows[i]["overdue"].ToString() + "天";}
if (int.Parse(ds.Tables[0].Rows[i]["begindue"].ToString()) < 1)
{
ds.Tables[0].Rows[i]["overdue"] = "未到有效期";
}
}
//以起始时间倒叙排列
ds.Tables[0].DefaultView.Sort = "begindate DESC";
//为控件绑定数据
GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView;
GridView1.DataBind();
}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message.Replace("'", "*") + "')</script>");
}
finally
{
mycn.Close();
}
// countDropDownList();
}
protected void gridList_RowDataBound(object sender, GridViewRowEventArgs e)
{
string gridViewHeight = ConfigurationSettings.AppSettings["gridViewHeight"];
GridView1.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#e5ebee'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
// 控制每一行的高度
e.Row.Attributes.Add("style", gridViewHeight);
// 点击一行是复选框选中
CheckBox chk = (CheckBox)e.Row.FindControl("CheckBox1");
//e.Row.Attributes["onclick"] = "if(" + chk.ClientID + ".checked) " + chk.ClientID + ".checked = false ; else " + chk.ClientID + ".checked = true ;";
// 删除提示
//del.Attributes.Add("onclick", "if(" + chk.ClientID + ".checked==false) {javascript:alert('请选中您要删除的目标')}else {javascript:if(confirm('确定要删除吗?')){}else{return false;}}");
del.Attributes.Add("onclick", "javascript:if(confirm('确定要删除吗?')){}else{return false;}");
// 双击弹出新页面,并传递id值
//ID = e.Row.DataItemIndex.ToString();
//string ID = GridView1.Rows[e.Row.RowIndex].Cells[0].ToString();
int row_index = e.Row.RowIndex;
string ID = GridView1.DataKeys[row_index].Value.ToString();
e.Row.Attributes.Add("ondblclick", "ckxq('" + ID + "')");
var drv = (DataRowView)e.Row.DataItem;
string status = drv["overdue"].ToString().Trim();
if (status != "已过有效期" && status != "未到有效期")
{
status = status.Replace("天", "");
int num = int.Parse(status.Trim());
if (num < 30)
{
e.Row.Cells[7].ForeColor = System.Drawing.Color.Red;
}
}
}
}
// 编辑
protected void Button3_Click(object sender, EventArgs e)
{
int num = 0;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{
num++;
}
else
{
continue;
}
}
if (num == 1)
{
string ID = "";
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{
ID = GridView1.DataKeys[i].Value.ToString();
//Convert.ToInt16(ID);
Response.Write("<script>window.open('userxiugai.aspx?ID=" + ID + "','_blank')</script>");
//edi.Attributes.Add("onclick", "ckxq('" + ID + "')");
}
}
}
else
{
Response.Write("<script>alert('请选中一行!')</script>");
}
}
// 删除
protected void Button2_Click(object sender, EventArgs e)
{
mycn = new SqlConnection(mycns);
SqlCommand sqlcom1, sqlcom2, sqlcom3, sqlcom6, sqlcom7;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{
mycn.Open();
try
{
string lx;
string mysc = "select usertype from User_Reg where userID='" + GridView1.DataKeys[i].Value + "'";
SqlCommand mycmd = new SqlCommand(mysc, mycn);
SqlDataReader myrd;
myrd = mycmd.ExecuteReader();
if (myrd.Read())
{
lx = myrd[0].ToString().Trim();
myrd.Close();
string mysc4 = "select cmpID from User_Reg where userID='" + GridView1.DataKeys[i].Value + "'";
SqlCommand mycmd4 = new SqlCommand(mysc4, mycn);
SqlDataReader myrd4;
myrd4 = mycmd4.ExecuteReader();
myrd4.Read();
if (myrd4[0].ToString() != "")
{
if (lx == "孵化企业")
{
string qyID = GridView1.DataKeys[i].Value.ToString();
DataSet ds = sdb.Select("select N.qytp,N.syjhs,X.xmsb from nryqyxxk N left join xmk X on N.qyID = X.qyID where N.qyID = '" + qyID + "'", null);
if (ds.Tables[0].Rows.Count>0)
{
DataRow row = ds.Tables[0].Rows[0];
FileUtil fileUtil = new FileUtil();
if (row["qytp"] != System.DBNull.Value && row["qytp"].ToString() != "")
{
fileUtil.delFile(row["qytp"].ToString());
}
if (row["syjhs"] != System.DBNull.Value && row["syjhs"].ToString() != "")
{
fileUtil.delFile(row["syjhs"].ToString());
}
if (row["xmsb"] != System.DBNull.Value && row["xmsb"].ToString() != "")
{
fileUtil.delFile(row["xmsb"].ToString());
}
ds = sdb.Select("select fileID from zlsc where cmpID = '" + qyID + "'", null);
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
row = ds.Tables[0].Rows[j];
if (row["fileID"] != System.DBNull.Value && row["fileID"].ToString() != "")
{
fileUtil.delFile(row["fileID"].ToString());
}
}
}
myrd4.Close();
string sqlstr3 = "delete from nryqyxxk where qyID='" + GridView1.DataKeys[i].Value + "' delete from qyxxb where cmpID='" + GridView1.DataKeys[i].Value + "' delete from qyxqb where cmpID='" + GridView1.DataKeys[i].Value + "' delete from zyqyxxk where qyID='" + GridView1.DataKeys[i].Value + "' delete from tyqy where cmpID='" + GridView1.DataKeys[i].Value + "' delete from xmk where qyID='" + GridView1.DataKeys[i].Value + "' delete from zlsc where cmpID='" + GridView1.DataKeys[i].Value + "'";
sqlcom3 = new SqlCommand(sqlstr3, mycn);
sqlcom3.ExecuteNonQuery();
}
if (lx == "合作企业")
{
myrd4.Close();
string sqlstr3 = "delete from qyxxb where cmpID='" + GridView1.DataKeys[i].Value + "' delete from qyxqb where cmpID='" + GridView1.DataKeys[i].Value + "'";
sqlcom3 = new SqlCommand(sqlstr3, mycn);
sqlcom3.ExecuteNonQuery();
}
}
myrd4.Close();
string mysc5 = "select qyxqID from User_Reg where userID='" + GridView1.DataKeys[i].Value + "'";
SqlCommand mycmd5 = new SqlCommand(mysc5, mycn);
SqlDataReader myrd5;
myrd5 = mycmd5.ExecuteReader();
myrd5.Read();
if (myrd5[0].ToString() == "")
{
myrd5.Close();
}
else
{
myrd5.Close();
string sqlstr6 = "delete from qyxxb where cmpID='" + GridView1.DataKeys[i].Value + "'";
sqlcom6 = new SqlCommand(sqlstr6, mycn);
sqlcom6.ExecuteNonQuery();
string sqlstr7 = "delete from qyxqb where cmpID='" + GridView1.DataKeys[i].Value + "'";
sqlcom7 = new SqlCommand(sqlstr7, mycn);
sqlcom7.ExecuteNonQuery();
}
myrd5.Close();
if (lx == "管理员")
{ Response.Write("<script>alert('管理员账号不可删除!')</script>"); }
else if (lx == "专家")
{
SqlServerDataBase sd = new SqlServerDataBase();
DataSet dsxxk = new DataSet();
DataSet dscgk = new DataSet();
DataSet dsxmk = new DataSet();
dsxxk = sd.Select("select * from nryqyxxk where spzjID='" + GridView1.DataKeys[i].Value + "' or spzjID2='" + GridView1.DataKeys[i].Value + "' or spzjID3='" + GridView1.DataKeys[i].Value + "'", null);
dscgk = sd.Select("select * from cgk where spzjID='" + GridView1.DataKeys[i].Value + "' or spzjID2='" + GridView1.DataKeys[i].Value + "' or spzjID3='" + GridView1.DataKeys[i].Value + "'", null);
dsxmk = sd.Select("select * from xmk where spzjID='" + GridView1.DataKeys[i].Value + "' or spzjID2='" + GridView1.DataKeys[i].Value + "' or spzjID3='" + GridView1.DataKeys[i].Value + "'", null);
if (dsxxk.Tables[0].Rows.Count > 0 || dscgk.Tables[0].Rows.Count > 0 || dsxmk.Tables[0].Rows.Count > 0)
{
Response.Write("<script>alert('该专家已有企业审核、成果审核、项目审核任务,不得删除账号!')</script>");
}
else
{
myrd4.Close();
string sqlstr2 = "delete from zjk where zjID='" + GridView1.DataKeys[i].Value + "' delete from zjdbxkycg where zjID='" + GridView1.DataKeys[i].Value + "' ";
sqlcom2 = new SqlCommand(sqlstr2, mycn);
sqlcom2.ExecuteNonQuery();
string sqlstr1 = "delete from User_Reg where userID='" + GridView1.DataKeys[i].Value + "'";
sqlcom1 = new SqlCommand(sqlstr1, mycn);
sqlcom1.ExecuteNonQuery();
}
}
else
{
string sqlstr1 = "delete from User_Reg where userID='" + GridView1.DataKeys[i].Value + "'";
sqlcom1 = new SqlCommand(sqlstr1, mycn);
sqlcom1.ExecuteNonQuery();
}
}
}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message.Replace("'", "*") + "')</script>");
}
finally
{
mycn.Close();
}
}
}
bindgrid();
}
protected void sshs(object sender, EventArgs e)
{
//查询数据库
//string sqlconnstr = ConfigurationManager.ConnectionStrings["server=LAPTOP-JFN4NKUE;database=teaching;User ID=zl;pwd=123456;Trusted_Connection=no"].ConnectionString;
// Label1.Text = "查找成功";
DataSet ds = new DataSet();
SqlConnection mycn = new SqlConnection(mycns);
//mycn.Open();
string userss = ss_text.Text.ToString().Trim();
String cxtj = DropDownList1.SelectedItem.Text.Trim();
if (cxtj == "账号名称")
{
cxtj = "username";
}
else if (cxtj == "名称")
{
cxtj = "showname";
}
using (SqlConnection sqlconn = new SqlConnection(mycns))
{
mycn.Open();
try
{
SqlDataAdapter sqld = new SqlDataAdapter("select userID,username,password,usertype,cmpID,qyxqID,userdate,begindate,lasttime,CONVERT(nvarchar(20),DATEDIFF(DAY,GETDATE(),userdate)) as overdue,DATEDIFF(DAY,begindate,GETDATE()) as begindue,showname from User_Reg where " + cxtj + " like '%" + userss + "%' and usertype like '%" + Session["admintype"].ToString() + "%' order by usertype,begindate desc", sqlconn);
if (Session["admintype"].ToString() == "孵化企业" || Session["admintype"].ToString() == "合作企业" || Session["admintype"].ToString() == "企业")
{
sqld = new SqlDataAdapter("select userID,username,password,ryzt as usertype,cmpID,qyxqID,userdate,begindate,lasttime,CONVERT(nvarchar(20),DATEDIFF(DAY,GETDATE(),userdate)) as overdue,DATEDIFF(DAY,begindate,GETDATE()) as begindue,showname from User_Reg left join nryqyxxk on(userID=qyID) where " + cxtj + " like '%" + userss + "%' and usertype like '%" + Session["admintype"].ToString() + "%' order by usertype,begindate desc", sqlconn);
}
sqld.Fill(ds, "tabenterprise");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i]["username"].ToString() == "人南总经理" || ds.Tables[0].Rows[i]["username"].ToString() == "校本部总经理" || ds.Tables[0].Rows[i]["username"].ToString() == "总经理")
{
ds.Tables[0].Rows[i]["usertype"] += "(总公司)";
}
if (ds.Tables[0].Rows[i]["username"].ToString() == "菁蓉总经理")
{
ds.Tables[0].Rows[i]["usertype"] += "(子公司)";
}
if (int.Parse(ds.Tables[0].Rows[i]["overdue"].ToString()) < 1)
{
ds.Tables[0].Rows[i]["overdue"] = "已过有效期";
}
else
{
ds.Tables[0].Rows[i]["overdue"] = ds.Tables[0].Rows[i]["overdue"].ToString() + "天";
}
if (int.Parse(ds.Tables[0].Rows[i]["begindue"].ToString()) < 1)
{
ds.Tables[0].Rows[i]["overdue"] = "未到有效期";
}
}
}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message.Replace("'", "*") + "')</script>");
}
finally
{
mycn.Close();
}
}
//为控件绑定数据
GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView;
GridView1.DataBind();
}
//protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
//{
// GridView1.PageIndex = e.NewPageIndex;
// bindgrid(); //数据绑定
//}
//protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
//{
// // Retrieve the pager row.
// GridViewRow pagerRow = GridView1.BottomPagerRow;
// // Retrieve the PageDropDownList DropDownList from the bottom pager row.
// DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
// // Set the PageIndex property to display that page selected by the user.
// GridView1.PageIndex = pageList.SelectedIndex;
// bindgrid(); //数据绑定
//}
//protected void GridView1_DataBound(Object sender, EventArgs e)
//{
// GridView1.BottomPagerRow.Visible = true;//只有一页数据的时候也再下面显示pagerrow,需要top的再加Top
// // Retrieve the pager row.
// GridViewRow pagerRow = GridView1.BottomPagerRow;
// // Retrieve the DropDownList and Label controls from the row.
// DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
// Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
// if (pageList != null)
// {
// // Create the values for the DropDownList control based on
// // the total number of pages required to display the data
// // source.
// for (int i = 0; i < GridView1.PageCount; i++)
// {
// // Create a ListItem object to represent a page.
// int pageNumber = i + 1;
// ListItem item = new ListItem(pageNumber.ToString());
// // If the ListItem object matches the currently selected
// // page, flag the ListItem object as being selected. Because
// // the DropDownList control is recreated each time the pager
// // row gets created, this will persist the selected item in
// // the DropDownList control.
// if (i == GridView1.PageIndex)
// {
// item.Selected = true;
// }
// // Add the ListItem object to the Items collection of the
// // DropDownList.
// pageList.Items.Add(item);
// }
// }
// if (pageLabel != null)
// {
// // Calculate the current page number.
// int currentPage = GridView1.PageIndex + 1;
// // Update the Label control with the current page information.
// pageLabel.Text = "Page " + currentPage.ToString() +
// " of " + GridView1.PageCount.ToString();
// }
//}
//protected void countDropDownList()
//{
// GridViewRow pagerRow = GridView1.BottomPagerRow;
// DropDownList countList = (DropDownList)pagerRow.Cells[0].FindControl("CountDropDownList");
// countList.Items.Add(new ListItem("默认"));
// countList.Items.Add(new ListItem("10"));
// countList.Items.Add(new ListItem("20"));
// countList.Items.Add(new ListItem("全部"));
// switch (GridView1.PageSize)
// {
// case 7:
// countList.Text = "默认";
// break;
// case 10:
// countList.Text = "10";
// break;
// case 20:
// countList.Text = "20";
// break;
// default:
// countList.Text = "全部";
// break;
// }
//}
//protected void CountDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
//{
// GridViewRow pagerRow = GridView1.BottomPagerRow;
// DropDownList countList = (DropDownList)pagerRow.Cells[0].FindControl("CountDropDownList");
// string selectText = countList.SelectedItem.Text;
// switch (selectText)
// {
// case "默认":
// {
// GridView1.PageSize = 7;
// }
// break;
// case "10":
// {
// GridView1.PageSize = 10;
// }
// break;
// case "20":
// {
// GridView1.PageSize = 20;
// }
// break;
// case "全部":
// {
// mycn = new SqlConnection(mycns);
// SqlCommand mycmm = new SqlCommand("select count(*) from User_Reg", mycn);
// mycn.Open();
// int count = (int)mycmm.ExecuteScalar();
// mycn.Close();
// GridView1.PageSize = count;
// }
// break;
// default:
// break;
// }
// bindgrid();
//}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Text.Trim() == "账号类型")
{
ss_text.Visible = false;
DropDownList2.Visible = true;
btss.Visible = false;
}
else if (DropDownList1.SelectedItem.Text.Trim() == "账号名称")
{
ss_text.Visible = true;
DropDownList2.Visible = false;
btss.Visible = true;
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection mycn = new SqlConnection(mycns);
//mycn.Open();
string userss;
if (DropDownList2.SelectedValue == "ss")
{
userss = "";
}
else
{
userss = DropDownList2.SelectedItem.Text.Trim();
}
String cxtj = DropDownList1.SelectedValue.Trim();
using (SqlConnection sqlconn = new SqlConnection(mycns))
{
mycn.Open();
SqlDataAdapter sqld = new SqlDataAdapter("select * from User_Reg where " + cxtj + " like '%" + userss + "%' and usertype like '%" + Session["admintype"].ToString() + "%'", sqlconn);
sqld.Fill(ds, "tabenterprise");
mycn.Close();
}
//为控件绑定数据
GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView;
GridView1.DataBind();
DataSet ds1 = new DataSet();
SqlConnection mycn1 = new SqlConnection(mycns);
using (SqlConnection sqlconn = new SqlConnection(mycns))
{
mycn1.Open();
SqlDataAdapter sqld = new SqlDataAdapter("select * from User_Reg where " + cxtj + " like '%" + userss + "%' and usertype like '%" + Session["admintype"].ToString() + "%'", sqlconn);
sqld.Fill(ds1, "tabenterprise");
mycn1.Close();
}
//为控件绑定数据
GridView1.DataSource = ds1.Tables["tabenterprise"].DefaultView;
GridView1.DataBind();
}
protected void DataBaseBak_ServerClick(object sender, EventArgs e)
{
try
{
//if (txtPath.Text != "" && txtName122.Text != "")
//{
//getSqlConnection geCon = new getSqlConnection();
string mycns = ConfigurationSettings.AppSettings["connString"];
SqlConnection geCon = new SqlConnection(mycns);
geCon.Open();
DateTime dt = DateTime.Now;
string namebak = string.Format("{0:yyyyMMddHHmmss}", dt);
namebak = HttpContext.Current.Server.MapPath("~/Buffer") + "\\"+"Data" + namebak + ".bak";
string strBacl = "backup database xhkj to disk='" + namebak + "'";
SqlCommand Cmd = new SqlCommand(strBacl, geCon);
if (Cmd.ExecuteNonQuery() != 0)
{
//System.Windows.Forms.MessageBox.Show("数据备份成功!", "提示框", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
//Response.Write("<script>alert('数据备份成功!')</script>");
geCon.Close();
ZipHelper zh = new ZipHelper();
//zh.downBak(HttpContext.Current.Server.MapPath("~/Buffer")+namebak);
string sourceFilePath = HttpContext.Current.Server.MapPath("~/files");
string zipname = "File"+string.Format("{0:yyyyMMddHHmmss}", dt) + ".zip";
string destinationZipFilePath = HttpContext.Current.Server.MapPath("~/Buffer") + "\\" + zipname;
ZipHelper.CreateZip(sourceFilePath, destinationZipFilePath);
ZipHelper.addzip(namebak, destinationZipFilePath);
zh.downBak(destinationZipFilePath);
}
else
{
//System.Windows.Forms.MessageBox.Show("数据备份失败!", "提示框", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
Response.Write("<script>alert('数据备份失败!')</script>");
}
}
//else
//{
// MessageBox.Show("请填写备份的正确位置及文件名!", "提示框", MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
catch (Exception ee)
{
//System.Windows.Forms.MessageBox.Show(ee.Message.ToString());
string mass = ee.Message;
Response.Write(mass);
}
}
protected void DataBaseRestore_ServerClick(object sender, EventArgs e)
{
string sl = "<script language='javascript' type='text/javascript'> importToWord(1)</script>";
Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "importToWord", sl);
}
protected void closed_Click(object sender, EventArgs e)
{
Response.Redirect("adminbody.aspx");
}
protected void btn_restore_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(HttpContext.Current.Server.MapPath("~/buffer") + "/" + FileUpload1.FileName);
string name = HttpContext.Current.Server.MapPath("~/buffer" + "/" + FileUpload1.FileName);
int flag = 0;
ZipHelper zh = new ZipHelper();
flag = zh.restoreZip(FileUpload1.FileName);
File.Delete(name);
if (flag != 0)
{
Response.Write("<script>alert('数据还原成功!')</script>");
Response.Write("<script>alert('将返回登陆界面。')</script>");
Response.Write("<script>top.location.href = 'login.aspx';</script>");
}
else {
Response.Write("<script>alert('文件应为.zip格式!')</script>");
}
}
else
{
//System.Windows.Forms.MessageBox.Show("请选择备份文件!", "提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
Response.Write("<script>alert('请选择备份文件!')</script>");
}
}
//文件备份
protected void FilesZip_ServerClick(object sender,EventArgs e)
{
DateTime dt = DateTime.Now;
string sourceFilePath = HttpContext.Current.Server.MapPath("~/files");
string zipname = string.Format("{0:yyyyMMddHHmmss}", dt) + ".zip";
string destinationZipFilePath = HttpContext.Current.Server.MapPath("~/Buffer") + "\\" + zipname;
ZipHelper.CreateZip(sourceFilePath, destinationZipFilePath);
ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptName", "window.open('DownloadFile.aspx?path=" + "~/Buffer/" + zipname + "','_blank');", true);
}
protected void A2_ServerClick(object sender, EventArgs e)
{
int num = 0;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{
num++;
}
else
{
continue;
}
}
if (num == 1)
{
string ID = "";
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{
ID = GridView1.DataKeys[i].Value.ToString();
//Convert.ToInt16(ID);
byte[] pwd1 = System.Text.Encoding.UTF8.GetBytes("123456");
byte[] hashBytes1 = new System.Security.Cryptography.SHA256Managed().ComputeHash(pwd1);
string pass1 = Convert.ToBase64String(hashBytes1);
SqlServerDataBase ds = new SqlServerDataBase();
ds.Update("update User_Reg set password='"+pass1+"' where userID='"+ID +"'",null);
Response.Write("<script>alert('重置密码为\"123456\"')</script>");
}
}
}
else
{
Response.Write("<script>alert('请选中一行!')</script>");
}
}
} |
// Displays the Sub Menu For Resource Section
partial class ResourcesSubMenu : PortalModuleBase
{
protected void Page_Init(System.Object sender, System.EventArgs e)
{
string strTabName = "";//holds the Name of the Tab for which ever launage the user is using
string strExtraClasses = "";//holds and extra class that needs to be used for the link
int intSecLevel = 2;//holds the for secound level
DotNetNuke.Entities.Tabs.TabController ctlTab = new TabController();//holds the Tab Contorller
DataTable dtSecLevel = DAL.getSecLevelTabs(122);//holds the Secound Level Tab
TabInfo tabCurrentInfo = ctlTab.GetTab(PortalSettings.ActiveTab.TabID);//holds the Current Page Info
TabInfo tabParentInfo = null;//holds the Parent Info
TabInfo tabParentParentInfo = null;//holds the Parent Parent Info
//checks if there is a Parent
if(tabCurrentInfo.ParentId > 0)
tabParentInfo = ctlTab.GetTab(tabCurrentInfo.ParentId);
//checks if there is a Parent Parent Info
if(tabParentInfo != null && tabParentInfo.ParentId > 0)
tabParentParentInfo = ctlTab.GetTab(tabParentInfo.ParentId);
//checks if there is any items to display
if(dtSecLevel != null && dtSecLevel.Rows.Count > 0)
{
//goes around for each item and adds it to the menu then gets checks if there is a sub menu and if so then
//adds that to the menu and put a different background on it, then checks if there is a sub menu for that and if so then adds
//that to the menu and puts a different background on that too
foreach(DataRow drSecLevel in dtSecLevel.Rows)
{
TabInfo tabSecLevelInfo = ctlTab.GetTab(Convert.ToInt32(drSecLevel[""].ToString()));//holds the Current Page Info
//checks if the tab status and make sure it is not deleted, disable and that user can look
if (PortalSecurity.IsInRoles(tabSecLevelInfo.AuthorizedRoles) && (!tabSecLevelInfo.IsDeleted) && (!tabSecLevelInfo.DisableLink))
{
strTabName = Server.HtmlDecode(drSecLevel[""].ToString());
//adds the item to the menu
litSubMenu.Text += "<div class='OB-level2-rightnav-header id" + drSecLevel[""].ToString() + " Normal" + strExtraClasses + "' id='gothic10" + intSecLevel + "'><a href='" + DotNetNuke.Common.Globals.NavigateURL(Convert.ToInt32(drSecLevel["TabId"].ToString()), "", "") + "'>" +
strTabName +
" </a></div>" +
"<div class='OBLevel2RightNavBody'>" +
"<br/>" +
"</div>";
intSecLevel++;
//resets the Extra Classes
strExtraClasses = "";
}//end of if
}//end of foreach
}//end of if
}//end of Page_Init()
}//end of Class |
using Efa.Domain.Entities;
using Efa.Domain.Interfaces.Specification;
using Efa.Domain.Validation.Documentos;
namespace Efa.Domain.Specification.Alunos
{
public class AlunoPossuiEmailValido : ISpecification<Aluno>
{
public bool IsSatisfiedBy(Aluno aluno)
{
//if (!string.IsNullOrEmpty(aluno.Email))
// return EmailValidation.Validar(aluno.Email);
return true;
}
}
}
|
// basic: variable erstellen
// typedefinieren variablenameDefinieren
// bits
// 1 Bit = (0, 1) -> 2 Informationen
// 2 Bit = (00, 01, 10, 11) --> 4 Informationen
// 3 Bit = ()
// 1 2 3
// -----
// 0 0 0
// 0 0 1
// 0 1 0
// 0 1 1
// 1 0 0
// 1 0 1
// 1 1 0
// 1 1 1
// formel:
// 2^AnzahlBits
// zbsp: 3Bit = 2^3 = 8
// zbsp: 32Bit = 2^32 = 4'294'967'296
// zbsp: 64Bit = 2^64 = 1.844674407E19
// ***** Zahlen *****
// https://www.tutorialspoint.com/csharp/csharp_data_types
// ganze zahl: integer (32Bit)
// ganze zahl: long (64bit)
// dezimalzahl: float (32bit) abkürzung: f
// dezimalzahl: double (64bit), abkürzung: d
// dezimalzahl: decimal (128bit), abkürzung: m
int ganzeZahl = 132;
decimal dezimalZahl = 13.231m;
double doubleZahl64Bit = 13.1324d;
float floatZahl = 312.23f;
int jahr = 2019;
// Abkürzung: jahr += 3;
jahr = jahr + 3;
// Abkürzung: Console.WriteLine(jahr++);
// Console.WriteLine(jahr + 1);
// Console.WriteLine(jahr);
// Wahrheitswert (1 Bit)
// Werte: true oder false
bool isHeuteSonne = true;
//Console.WriteLine(isHeuteSonne);
isHeuteSonne = false;
// Buchstabe (16 Bit)
// Byte (8 Bit, 0 - 255)
byte meinByte = 85;
// **** Aritmentische Operatoren *****
// https://www.tutorialspoint.com/csharp/csharp_operators.htm
// * multiplikation
// + addition
// - subtraktion
// / division
// ++ Inkrementieren
// -- Dekrementieren
int seite_a = 13;
int seite_b = 2;
int fläche = seite_a * seite_b;
// **** Relational Operatoren *****
// == Gleich
// < Links ist kleiner als rechts
// > Links ist grösesr als rechts
// >= Links ist grösser oder gleich wie rechts
// <= Links ist kleiner oder gleich wie rechts
int jahr1 = 2019;
int jahr2 = 2021;
Console.WriteLine(jahr1 == jahr2);
int jahr3 = 2019;
int jahr4 = 2019;
Console.WriteLine(jahr3 == jahr4);
Console.WriteLine("Ist jahr1 grösser als jahr2?");
Console.WriteLine(jahr1 > jahr2);
Console.WriteLine("Ist jahr1 kleiner als jahr2?");
Console.WriteLine(jahr1 < jahr2);
// **** Logische Operatoren *****
// && Logische Und-Vergleich
// A B Resultat
// Ja Ja Ja
// Ja Nein Nein
// Nein Ja Nein
// Nein Nein Nein
bool istHeuteKeinUnterricht = true;
bool istHeuteFerien = true;
Console.WriteLine("Wenn heute kein Unterricht ist UND wir haben Ferien, dann freue ich mich sehr !");
Console.WriteLine(istHeuteKeinUnterricht && istHeuteFerien);
// || Logische Oder-Vergleich
// A B Resultat
// Ja Ja Ja
// Ja Nein Ja
// Nein Ja Ja
// Nein Nein Nein
istHeuteKeinUnterricht = true;
bool istHeuteSonne = false;
Console.WriteLine("Wenn heute kein Unterricht ist ODER es ist sonnig, dann freue ich mich sehr!");
Console.WriteLine(istHeuteKeinUnterricht || istHeuteSonne);
// ! Negation-Operator
// A Resultat
// Ja Nein
// Nein Ja
Console.WriteLine("Heute ist NICHT istHeuteSonne");
Console.WriteLine(!istHeuteSonne);
Console.WriteLine(!!istHeuteSonne);
Console.WriteLine(!!!!!!!!!!!!!!!!istHeuteSonne);
// *********** Text ***********
// Char (Buchstabe)
char a1 = 'a';
Console.WriteLine(a1);
// Array
// Speicherung: H a l l o W e l t
// Index: 0 1 2 3 4 5 6 7 8 9
string text = "Hallo Welt";
Console.WriteLine(text);
Console.WriteLine(text[0]); // Zugriff auf Index-Operator []
Console.WriteLine("Konkatination");
string wiegehts = ", Wie gehts? ";
Console.WriteLine(text + wiegehts + istHeuteSonne);
|
using System;
using System.Collections.Generic;
namespace POSServices.Models
{
public partial class LogRecord
{
public int Id { get; set; }
public DateTime? TimeStamp { get; set; }
public string Tag { get; set; }
public string Message { get; set; }
public string TransactionId { get; set; }
}
}
|
using System.Collections.Generic;
namespace ProjetctTiGr13.Domain.FicheComponent
{
public class Competence
{
public int IdComp { get; set; }
public Competence()
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
/// <summary>
/// 神经元
/// </summary>
public class Neuron : INeuron
{
#region 构造函数
/// <summary>
/// 神经元
/// </summary>
/// <param name="bias"></param>
public Neuron(double bias)
{
m_bias = new NeuralFactor(bias);
m_error = 0;
m_input = new Dictionary<INeuronSignal, NeuralFactor>();
}
#endregion
#region 成员变量
private Dictionary<INeuronSignal, NeuralFactor> m_input;
double m_output, m_error, m_lastError;
/// <summary>
/// 偏差
/// 每个神经元都会有偏见(将其视为另一个输入,但是一个是独立的,而不是来自另一个神经元)
/// </summary>
NeuralFactor m_bias;
#endregion
#region 属性
public double Output
{
get { return m_output; }
set { m_output = value; }
}
/// <summary>
/// 神经元的输入由许多其他神经元的输出组成
/// 键是信号,输出是定义该信号“权重”的类
/// </summary>
public Dictionary<INeuronSignal, NeuralFactor> Input
{
get { return m_input; }
}
/// <summary>
/// 偏差
/// 每个神经元都会有偏见(将其视为另一个输入,但是一个是独立的,而不是来自另一个神经元)
/// </summary>
public NeuralFactor Bias
{
get { return m_bias; }
set { m_bias = value; }
}
public double Error
{
get { return m_error; }
set
{
m_lastError = m_error;
m_error = value;
}
}
public double LastError
{
get { return m_lastError; }
set { m_lastError = value; }
}
#endregion
#region 方法
/// <summary>
/// 获取每个输入的值(或每个神经元的输出将信息传递给该神经元)的总和乘以字典中包含的相应权重。
/// 然后将偏差乘以偏差权重。最终输出由前面讨论的S形曲线“压扁”,
/// 结果存储在m_output变量中
/// </summary>
/// <param name="layer"></param>
public void Pulse(INeuralLayer layer)
{
lock (this)
{
m_output = 0;
foreach (KeyValuePair<INeuronSignal, NeuralFactor> item in m_input)
m_output += item.Key.Output * item.Value.Weight;
m_output += m_bias.Weight;
m_output = Sigmoid(m_output);
}
}
/// <summary>
/// 应用神经元学习的方法。
/// </summary>
/// <param name="layer"></param>
public void ApplyLearning(INeuralLayer layer, ref double learningRate)
{
foreach (KeyValuePair<INeuronSignal, NeuralFactor> m in m_input)
m.Value.ApplyWeightChange(ref learningRate);
m_bias.ApplyWeightChange(ref learningRate);
}
/// <summary>
/// 初始化学习
/// </summary>
/// <param name="layer"></param>
public void InitializeLearning(INeuralLayer layer)
{
foreach (KeyValuePair<INeuronSignal, NeuralFactor> m in m_input)
m.Value.ResetWeightChange();
m_bias.ResetWeightChange();
}
#endregion
#region 专用静态实用方法
/// <summary>
/// 使用Sigmoid曲线将神经元的输出压缩到0和1之间的值
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static double Sigmoid(double value)
{
return 1 / (1 + Math.Exp(-value));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Festival.Models
{
public class SQLFestivalRepository : IMusicFestivalRepository
{
private readonly AppDbContext context;
public SQLFestivalRepository(AppDbContext context)
{
this.context = context;
}
public IEnumerable<BandFestivalDto> GetMusicFestivals()
{
return (from e in context.MusicFestival
join Band in context.Band
on e.festivalId equals Band.festivalId into MusicFestivalBand
from mfb in MusicFestivalBand.DefaultIfEmpty()
select new BandFestivalDto
{
recordLabel = mfb.recordLabel,
bandName = mfb.name,
festivalName = e.name
}
).ToArray();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MusicManager : MonoBehaviour {
public AudioClip[] levelMusicChangeArray;
[SerializeField] private AudioClip winConditionClip;
private AudioSource source;
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
// Use this for initialization
void Start () {
source = GetComponent<AudioSource>();
source.volume = PlayerPrefsManager.GetMasterVolume();
}
private void OnLevelWasLoaded(int level)
{
if (levelMusicChangeArray[level])
{
source.clip = levelMusicChangeArray[level];
source.loop = true;
source.Play();
}
}
public void PlayWinMusic()
{
Debug.Log("Play music method start");
source.clip = winConditionClip;
source.loop = false;
source.Play();
}
internal void ChangeVolume(float value)
{
source.volume = value;
}
// Update is called once per frame
void Update () {
}
}
|
using System.Reflection;
using NLog;
using Sandbox.Game.Entities.Cube;
using Torch.Managers.PatchManager;
namespace DataValidateFix
{
//TODO this patch cause crash
//[PatchShim]
public static class MyLaserAntennaPatch
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private static FieldInfo _range;
private static float _infiniteRange;
// ReSharper disable once InconsistentNaming
private static void InitPatch(MyLaserAntenna __instance)
{
var definition = __instance.BlockDefinition;
var maxRange = definition.MaxRange >= 0 ? definition.MaxRange : _infiniteRange;
_range.GetSync<float>(__instance).ValueChangedInRange(1, maxRange);
}
public static void Patch(PatchContext patchContext)
{
Log.TryPatching(() =>
{
patchContext.PatchInit<MyLaserAntenna>(InitPatch);
_range = typeof(MyLaserAntenna).GetPrivateFieldInfo("m_range");
_infiniteRange = typeof(MyLaserAntenna).GetPrivateConstValue<float>("INFINITE_RANGE");
});
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] Collider colissionMesh;
[SerializeField] ParticleSystem deathFX;
[SerializeField] ParticleSystem shotedFX;
[SerializeField] int hitPoints = 6;
private void OnParticleCollision(GameObject other)
{
ProcessHit();
if(hitPoints < 1)
{
KillEnemy();
}
}
private void ProcessHit()
{
shotedFX.Play();
hitPoints--;
}
private void KillEnemy()
{
var dfx = Instantiate(deathFX, transform.position, Quaternion.identity);
dfx.Play();
Destroy(dfx.gameObject, dfx.main.duration);
Destroy(gameObject); // enemy
}
}
|
namespace Sentry.Tests.Protocol;
public class PackageTests
{
private readonly IDiagnosticLogger _testOutputLogger;
public PackageTests(ITestOutputHelper output)
{
_testOutputLogger = new TestOutputDiagnosticLogger(output);
}
[Fact]
public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject()
{
var sut = new Package("nuget:Sentry", "1.0.0-preview");
var actual = sut.ToJsonString(_testOutputLogger);
Assert.Equal("""{"name":"nuget:Sentry","version":"1.0.0-preview"}""", actual);
}
[Theory]
[MemberData(nameof(TestCases))]
public void SerializeObject_TestCase_SerializesAsExpected((Package msg, string serialized) @case)
{
var actual = @case.msg.ToJsonString(_testOutputLogger);
Assert.Equal(@case.serialized, actual);
}
public static IEnumerable<object[]> TestCases()
{
yield return new object[] { (new Package(null, null), "{}") };
yield return new object[] { (new Package("nuget:Sentry", null), """{"name":"nuget:Sentry"}""") };
yield return new object[] { (new Package(null, "0.0.0-alpha"), """{"version":"0.0.0-alpha"}""") };
}
}
|
using A4CoreBlog.Common;
using A4CoreBlog.Data.Services.Contracts;
using A4CoreBlog.Data.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace A4CoreBlog.Web.Areas.Api.Controllers
{
public class ImagesController : BaseApiAreaController
{
private readonly ISystemImageService _sysImgService;
public ImagesController(ISystemImageService sysImgService)
{
_sysImgService = sysImgService;
}
[HttpGet]
public IActionResult Content(int id)
{
var model = _sysImgService.Get<SystemImageContentViewModel>(id);
return File(model.Content, "image/gif");
}
}
}
|
namespace ReverseNumbers
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Startup
{
public static void Main(string[] args)
{
var input = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
Console.WriteLine(Execute(input));
}
private static string Execute(int[] input)
{
var stack = new Stack<int>(input);
return String.Join(" ", stack);
}
}
} |
using DataLayer.Repositories;
using System;
namespace DataLayer
{
public interface IUnitOfWork : IDisposable
{
IUserRepository Users { get; }
ICityRepository DefaultCities { get; }
IRequestRepository Requests { get; }
int Complete();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace damdrempe_zadaca_2.Sustav
{
/// <summary>
/// Client
/// </summary>
public class Ispisivac
{
public void IspisiTekst(Ispis ispis, string redakTeksta)
{
ispis.ObaviIspis(redakTeksta);
}
}
/// <summary>
/// Subject
/// </summary>
public abstract class Ispis
{
public abstract void ObaviIspis(string redakTeksta);
}
/// <summary>
/// Real Subject
/// </summary>
class IspisZaslon : Ispis
{
public override void ObaviIspis( string redakTeksta)
{
Console.WriteLine(redakTeksta);
}
}
/// <summary>
/// Proxy
/// </summary>
class IspisZaslonProxy : Ispis
{
IspisZaslon ispisZaslon;
string datotekaIzlaza;
public override void ObaviIspis(string redakTeksta)
{
ParametriSingleton parametri = ParametriSingleton.DohvatiInstancu(Program.DatotekaParametara);
datotekaIzlaza = Pomocno.DohvatiPutanjuDatoteke(parametri.DohvatiParametar("izlaz"));
if (this.provjeriPostojanjeDatoteke())
{
ispisZaslon = new IspisZaslon();
ispisZaslon.ObaviIspis(redakTeksta);
this.ispisUDatoteku(redakTeksta);
}
}
private bool provjeriPostojanjeDatoteke()
{
if(!File.Exists(datotekaIzlaza))
{
using (StreamWriter sw = File.CreateText(datotekaIzlaza)){} // TODO: maknuti using?
Console.WriteLine($"Stvorena datoteka izlaza {datotekaIzlaza}.");
}
return true;
}
private void ispisUDatoteku(string redakTeksta)
{
using (StreamWriter sw = File.AppendText(datotekaIzlaza))
{
sw.WriteLine(redakTeksta);
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Fingo.Auth.DbAccess.Context.Interfaces;
using Fingo.Auth.DbAccess.Models;
using Fingo.Auth.DbAccess.Repository.Implementation.GenericImplementation;
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace Fingo.Auth.DbAccess.Repository.Implementation
{
public class UserRepository : GenericRepository<User> , IUserRepository
{
private readonly IAuthServerContext _db;
public UserRepository(IAuthServerContext context) : base(context)
{
_db = context;
}
public override IEnumerable<User> GetAll()
{
return _db.Set<User>()
.Include(u => u.ProjectUsers)
.Include(m => m.UserCustomData)
.ThenInclude(m => m.ProjectCustomData);
}
public override User GetById(int id)
{
var user = _db.Set<User>()
.Include(u => u.ProjectUsers)
.Include(u => u.UserCustomData)
.ThenInclude(m => m.ProjectCustomData)
.Include(m => m.UserPolicies)
.ThenInclude(m => m.ProjectPolicies)
.FirstOrDefault(u => u.Id == id);
return user;
}
public void UpdateUserPassword(User user , string password)
{
user.Password = password;
_db.Set<User>().Update(user);
_db.SaveChanges();
}
public IEnumerable<Project> GetAllProjectsFromUser(int id)
{
var d = _db.Set<User>()
.Where(m => m.Id == id)
.Include(p => p.ProjectUsers).ThenInclude(u => u.Project)
.FirstOrDefault();
var projects = d.ProjectUsers.Select(m => m.Project);
return projects;
}
public User GetByIdWithCustomDatas(int id)
{
var user = _db.Set<User>()
.Include(u => u.UserCustomData)
.FirstOrDefault(u => u.Id == id);
return user;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual
{
/// <summary>
/// Implementacion del adaptador de Flujo Aprobacion
/// </summary>
public sealed class FlujoAprobacionAdapter
{
/// <summary>
/// Realiza la adaptación de campos para la búsqueda
/// </summary>
/// <param name="flujoAprobacionLogic">Entidad Logica de flujo aprobacion</param>
/// <param name="flujoAprobacionTipoServicioLogic">Entidad Logica de flujo aprobacion tipo de servicio</param>
/// <param name="unidadOperativa">Lista Unidad Operativa</param>
/// <param name="tipoServicio">Lista Tipo Servicio</param>
/// <returns>Clase Flujo Aprobacion con los datos de búsqueda</returns>
public static FlujoAprobacionResponse ObtenerFlujoAprobacion(
FlujoAprobacionLogic flujoAprobacionLogic,
List<FlujoAprobacionTipoContratoLogic> flujoAprobacionTipoContratoLogic,
List<UnidadOperativaResponse> unidadOperativa,
List<CodigoValorResponse> tipoContrato
)
{
string sUnidadOperativa = null;
// string sTipoServicio = null;
string sTipoContrato = null;
if (unidadOperativa != null)
{
var uoperativa = unidadOperativa.Where(n => n.CodigoUnidadOperativa.ToString() == flujoAprobacionLogic.CodigoUnidadOperativa.ToString()).FirstOrDefault();
sUnidadOperativa = (uoperativa == null ? null : uoperativa.Nombre.ToString());
}
var listaTipoContrato = new List<string>();
foreach (var item in flujoAprobacionTipoContratoLogic)
{
if (tipoContrato != null)
{
var servicio = tipoContrato.Where(n => n.Codigo.ToString() == item.CodigoTipoContrato).FirstOrDefault();
if (servicio != null)
{
listaTipoContrato.Add(servicio.Valor.ToString());
}
}
}
listaTipoContrato = listaTipoContrato.OrderBy(item => item).ToList();
foreach (var contrato in listaTipoContrato)
{
sTipoContrato = sTipoContrato + (contrato == null ? null : contrato + ", ");
}
if (!string.IsNullOrEmpty(sTipoContrato))
{
sTipoContrato = sTipoContrato.Substring(0, sTipoContrato.Length - 2);
}
var flujoAprobacionResponse = new FlujoAprobacionResponse();
flujoAprobacionResponse.CodigoFlujoAprobacion = flujoAprobacionLogic.CodigoFlujoAprobacion.ToString();
flujoAprobacionResponse.CodigoUnidadOperativa = flujoAprobacionLogic.CodigoUnidadOperativa.ToString();
flujoAprobacionResponse.DescripcionUnidadOperativa = sUnidadOperativa;
// flujoAprobacionResponse.DescripcionTipoContrato = sTipoContrato;
flujoAprobacionResponse.ListaTipoServicio = flujoAprobacionTipoContratoLogic.Select(item => item.CodigoTipoContrato).ToList();
flujoAprobacionResponse.DescripcionTipoContrato = sTipoContrato;
flujoAprobacionResponse.IndicadorAplicaMontoMinimo = flujoAprobacionLogic.IndicadorAplicaMontoMinimo;
flujoAprobacionResponse.CodigoPrimerFirmante = flujoAprobacionLogic.CodigoPrimerFirmante.ToString();
flujoAprobacionResponse.CodigoSegundoFirmante = flujoAprobacionLogic.CodigoSegundoFirmante.ToString();
flujoAprobacionResponse.IndicadorAplicaMontoMinimo = flujoAprobacionLogic.IndicadorAplicaMontoMinimo;
if (flujoAprobacionLogic.CodigoPrimerFirmanteVinculada != null)
{
flujoAprobacionResponse.CodigoPrimerFirmanteVinculada = flujoAprobacionLogic.CodigoPrimerFirmanteVinculada.ToString();
}
if (flujoAprobacionLogic.CodigoSegundoFirmanteVinculada != null)
{
flujoAprobacionResponse.CodigoSegundoFirmanteVinculada = flujoAprobacionLogic.CodigoSegundoFirmanteVinculada.ToString();
}
return flujoAprobacionResponse;
}
/// <summary>
/// Realiza la adaptación de campos para registrar o actualizar
/// </summary>
/// <param name="data">Datos a registrar o actualizar</param>
/// <returns>Entidad Datos a registrar</returns>
public static FlujoAprobacionEntity RegistrarFlujoAprobacion(FlujoAprobacionRequest data)
{
FlujoAprobacionEntity flujoAprobacionEntity = new FlujoAprobacionEntity();
if (data.CodigoFlujoAprobacion != null)
{
flujoAprobacionEntity.CodigoFlujoAprobacion = new Guid(data.CodigoFlujoAprobacion);
}
else
{
Guid code;
code = Guid.NewGuid();
flujoAprobacionEntity.CodigoFlujoAprobacion = code;
}
//flujoAprobacionEntity.CodigoFlujoAprobacion = data.CodigoFlujoAprobacion;
flujoAprobacionEntity.CodigoUnidadOperativa = new Guid(data.CodigoUnidadOperativa);
//flujoAprobacionEntity.CodigoTipoServicio = null;//data.CodigoTipoServicio;
flujoAprobacionEntity.IndicadorAplicaMontoMinimo = data.IndicadorAplicaMontoMinimo.Value;
flujoAprobacionEntity.EstadoRegistro = data.EstadoRegistro;
flujoAprobacionEntity.CodigoPrimerFirmante = new Guid(data.CodigoPrimerFirmante);
flujoAprobacionEntity.CodigoPrimerFirmanteOriginal = flujoAprobacionEntity.CodigoPrimerFirmante;
if (data.CodigoSegundoFirmante != null)
{
flujoAprobacionEntity.CodigoSegundoFirmante = new Guid(data.CodigoSegundoFirmante);
flujoAprobacionEntity.CodigoSegundoFirmanteOriginal = flujoAprobacionEntity.CodigoSegundoFirmante;
}
if (data.CodigoPrimerFirmanteVinculada != null)
{
flujoAprobacionEntity.CodigoPrimerFirmanteVinculada = new Guid(data.CodigoPrimerFirmanteVinculada);
}
if (data.CodigoSegundoFirmanteVinculada != null)
{
flujoAprobacionEntity.CodigoSegundoFirmanteVinculada = new Guid(data.CodigoSegundoFirmanteVinculada);
}
return flujoAprobacionEntity;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CC.Utilities
{
public static class CollectionExtensions
{
public static string SafeJoin(this IEnumerable<String> items, String separator = ", "){
var result = String.Empty;
if (items != null && items.Count () > 0) {
result = items.Aggregate ((a, b) => a + separator + b);
}
return result;
}
public static string DecodeByteArray(this byte[] data){
return System.Text.Encoding.UTF8.GetString (data, 0, data.Length);
}
}
}
|
using CodeCityCrew.Settings.Model;
using Microsoft.EntityFrameworkCore;
namespace CodeCityCrew.Settings
{
/// <summary>
/// Settings Context.
/// </summary>
/// <seealso cref="DbContext" />
public class SettingDbContext : DbContext
{
/// <summary>
/// Initializes a new instance of the <see cref="SettingDbContext"/> class.
/// </summary>
public SettingDbContext() { }
/// <summary>
/// Initializes a new instance of the <see cref="SettingDbContext"/> class.
/// </summary>
/// <param name="options">The options.</param>
public SettingDbContext(DbContextOptions<SettingDbContext> options) : base(options)
{
}
/// <summary>
/// Gets or sets the settings.
/// </summary>
/// <value>
/// The settings.
/// </value>
public virtual DbSet<Setting> Settings { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Setting>().HasKey(option => new { option.Id, option.EnvironmentName });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Focuswin.SP.Base.Utility;
using Microsoft.SharePoint;
using YFVIC.DMS.Model.Models.Settings;
using YFVIC.DMS.Model.Models.Common;
namespace YFVIC.DMS.Model.Models.Process
{
public class ProcessMgr
{
/// <summary>
/// 添加过程
/// </summary>
/// <param name="obj">过程实体</param>
/// <returns></returns>
public bool InsertProcess(ProcessEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = new Process();
item.Name = obj.Name;
item.ParentId = obj.ParentId;
item.Path = obj.Path;
db.Processes.InsertOnSubmit(item);
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 更新过程
/// </summary>
/// <param name="obj">过程实体</param>
/// <returns></returns>
public bool UpdataProcess(ProcessEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = db.Processes.Where(p => p.Id == obj.Id).FirstOrDefault();
item.Name = obj.Name;
item.ParentId = obj.ParentId;
item.Path = obj.Path;
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 删除过程
/// </summary>
/// <param name="obj">页面参数</param>
/// <returns></returns>
public bool DelProcess(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = db.Processes.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
db.Processes.DeleteOnSubmit(item);
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 获取过程的子过程
/// </summary>
/// <param name="obj">页面参数</param>
/// <returns></returns>
public List<ProcessEntity> GetProcess(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
List<Process> items = db.Processes.Where(p => p.ParentId == Convert.ToInt32(obj.Id)).ToList();
List<ProcessEntity> listitems = new List<ProcessEntity>();
foreach (Process item in items)
{
ProcessEntity pitem = new ProcessEntity();
pitem.ParentId =Convert.ToInt32( item.ParentId);
pitem.Id = item.Id;
pitem.Name = item.Name;
pitem.Path = item.Path;
listitems.Add(pitem);
}
return listitems;
}
}
/// <summary>
/// 获取过程的子过程数量
/// </summary>
/// <param name="obj">页面参数</param>
/// <returns></returns>
public int GetProcessCount(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
List<Process> items = db.Processes.Where(p => p.ParentId == Convert.ToInt32(obj.Id)).ToList();
return items.Count;
}
}
/// <summary>
/// 根据Id获取单个过程
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ProcessEntity GetProcessByid(string id)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = db.Processes.Where(p => p.Id == Convert.ToInt32(id)).FirstOrDefault();
ProcessEntity pitem = new ProcessEntity();
pitem.ParentId = Convert.ToInt32(item.ParentId);
pitem.Id = item.Id;
pitem.Name = item.Name;
pitem.Path = item.Path;
return pitem;
}
}
/// <summary>
/// 获取单个过程
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public ProcessEntity GetProcessByid(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = db.Processes.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
ProcessEntity pitem = new ProcessEntity();
pitem.ParentId = Convert.ToInt32(item.ParentId);
pitem.Id = item.Id;
pitem.Name = item.Name;
pitem.Path = item.Path;
return pitem;
}
}
/// <summary>
/// 检查过程
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool IsOnlyOne(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
bool flag = false;
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = db.Processes.Where(p => p.Name == obj.Name && p.ParentId == Convert.ToInt32(obj.Id)).FirstOrDefault();
if (item == null)
{
flag = true;
}
}
return flag;
}
/// <summary>
/// 获取父节点及其所有自己点
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public string GetParentProcess(string id)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
List<string> listitems = new List<string>();
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = db.Processes.Where(p => p.Id == Convert.ToInt32(id)).FirstOrDefault();
while (true)
{
if (item.ParentId == 1)
{
break;
}
item = db.Processes.Where(p => p.Id == item.ParentId).FirstOrDefault();
}
//ProcessEntity pitem = new ProcessEntity();
//if (item.ParentId != 1)
//{
// Process parentitem = db.Processes.Where(p => p.Id == Convert.ToInt32(item.ParentId)).FirstOrDefault();
// pitem.ParentId = Convert.ToInt32(parentitem.ParentId);
// pitem.Id = parentitem.Id;
// pitem.Name = parentitem.Name;
// pitem.Path = parentitem.Path;
//}
//else
//{
// pitem.ParentId = Convert.ToInt32(item.ParentId);
// pitem.Id = item.Id;
// pitem.Name = item.Name;
// pitem.Path = item.Path;
//}
//listitems.Add(pitem.Id.ToString());
//List<Process> items = db.Processes.Where(p => p.ParentId == pitem.Id).ToList();
//foreach (Process oitem in items)
//{
// listitems.Add(oitem.Id.ToString());
//}
return item.Id.ToString();
}
}
/// <summary>
/// 获取根节点
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public string GetRootProcess(string id)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
List<string> listitems = new List<string>();
using (ProcessDataContext db = new ProcessDataContext(setting.DefaultValue))
{
Process item = db.Processes.Where(p => p.Id == Convert.ToInt32(id)).FirstOrDefault();
string parentid = item.ParentId.ToString();
Process parentitem = new Process();
if (item.ParentId == 1)
{
return item.Name;
}
else
{
while (parentid != "1")
{
parentitem = db.Processes.Where(p => p.Id == Convert.ToInt32(parentid)).FirstOrDefault();
parentid = parentitem.ParentId.ToString();
}
return parentitem.Name;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TAiMStore.Model.ViewModels
{
public class ProfileViewModel
{
public string PersonFullName { get; set; }
public string Organization { get; set; }
public string PostZip { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string House { get; set; }
public string Room { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
public string EmailForTextBox { get; set; }
}
}
|
using CQRSWebAPI.Behaviors;
using CQRSWebAPI.Caching;
using CQRSWebAPI.Filter;
using CQRSWebAPI.Model;
using CQRSWebAPI.Redis;
using CQRSWebAPI.Validation;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CQRSWebAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(opt => opt.Filters.Add(typeof(ResponseMappingFilter)));
services.AddSingleton<SeedData>();
services.AddSingleton(typeof(IRedisClientsManager), new RedisManagerPool("redis://@localhost:6379?Db=0&ConnectTimeout=5000&IdleTimeOutSecs=100"));
services.AddSingleton<IRedisManager, RedisManager>();
services.AddMediatR(typeof(Startup).Assembly);
services.AddMemoryCache();
// All of our Validators
services.AddValidator();
#region IOC
services.AddTransient(typeof(IPipelineBehavior<,>),typeof(LoggingBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>),typeof(ValidationBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>),typeof(CachingBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>),typeof(PerformanceBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>),typeof(EventSourceBehaviour<,>));
#endregion
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CQRSWebAPI", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CQRSWebAPI v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Direction
{
North, East, South, West
}
public enum Orientation
{
Vertical, Horizontal
}
public enum Verticality
{
Up,
Down
}
public static class DirectionUtil
{
public static Direction Reverse(Direction direction)
{
return (Direction)(((int)direction + 2) % 4);
}
public static Orientation Reverse(Orientation orientation)
{
return orientation == global::Orientation.Vertical ? global::Orientation.Horizontal : global::Orientation.Vertical;
}
public static Orientation Orientation(Direction direction)
{
return (Orientation)((int)direction % 2);
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PiDataAdayProje.Models.Entities
{
public class Isyeri
{
public Guid Id { get; set; }
[Display(Name ="İşletme Adı")]
public string IsletmeAdi { get; set; }
public string Yetkili { get; set; }
[DataType(DataType.Text)]
public string Adres { get; set; }
[DataType(DataType.PhoneNumber)]
public string Telefon { get; set; }
[DataType(DataType.PhoneNumber)]
public string Fax { get; set; }
public virtual IEnumerable<Musteri> Musteriler { get; set; }
public virtual IEnumerable<Emlak> Emlaklar { get; set; }
}
}
|
using Nac.Common.Control;
using System.Collections.Generic;
using System.Linq;
namespace Nac.Wpf.Common.Control {
public class NacWpfSection : NacWpfObjectWithChildren {
public NacWpfSection(NacSection nacSection) : base(nacSection) { }
public new NacSection Base { get { return base.Base as NacSection; } }
public IEnumerable<NacWpfBlock> Blocks { get { return Children.Cast<NacWpfBlock>(); } }
private bool _online;
public bool Online {
get { return _online; }
set { if (value != _online) { _online = value; OnNotifyPropertyChanged("Online"); } }
}
public bool IsSubroutine {
get { return Base.IsSubroutine; }
set { if (value != Base.IsSubroutine) { Base.IsSubroutine = value; OnNotifyPropertyChanged("IsSubroutine"); } }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Domain.Base;
using System.ComponentModel.DataAnnotations;
namespace Domain.Entities
{
public class Empleado : Entity<int>
{
[Required] public string Cedula { get; set; }
[Required] public string Nombre { get; set; }
[Required] public double Salario { get; set; }
public List<Credito> Creditos { get; set; }
public Empleado()
{
Creditos = new List<Credito>();
}
public string SolicitarCredito(double valor, int plazo, double tasaDeInteres = 0.005)
{
Credito credito = new Credito(valor, plazo, tasaDeInteres);
Creditos.Add(credito);
return $"Crédito registrado. Valor a pagar: ${credito.ValorAPagar}.";
}
public override string ToString()
{
return string.Format("Cedula = {0}, Nombre = {1}, Salario = {2}", Cedula, Nombre, Salario);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace Ultranaco.Crypto.SHA256
{
public static class ObjectHash256Extend
{
public static string Hash256(this object obj)
{
var objStr = string.Empty;
if (!(obj is string))
objStr = JsonSerializer.Serialize(obj);
else
objStr = (string)obj;
string hashString;
using (var hasher = new SHA256Managed())
{
var hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(objStr));
hashString = string.Join("", hash.Select(b => b.ToString("x2")).ToArray()).ToLower();
}
return hashString;
}
public static byte[] HmacSHA256(this string data, byte[] key)
{
string algorithm = "HmacSHA256";
byte[] bytes;
using (KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(algorithm))
{
kha.Key = key;
bytes = kha.ComputeHash(Encoding.UTF8.GetBytes(data));
}
return bytes;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ideal.Ipos.RealTime.Skat.Model {
public enum Symbol {
Ass = 11,
Zehn = 10,
Koenig = 4,
Dame = 3,
Bube = 2,
Neun = 9,
Acht = 8,
Sieben = 7
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GestaoBiblioteca
{
public partial class frmPlanta : Form
{
public frmPlanta()
{
InitializeComponent();
}
private void pic1_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta1;
}
private void pic2_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta2;
}
private void pic3_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta3;
}
private void pic4_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta4;
}
private void pic5_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta5;
}
private void pic6_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta6;
}
private void pic7_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta7;
}
private void pic8_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta8;
}
private void pic9_Click(object sender, EventArgs e)
{
picZoom.Image = Properties.Resources.planta9;
}
private void Planta_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'gestaoBibliotecaDataSet.Leitor' table. You can move, or remove it, as needed.
this.leitorTableAdapter.Fill(this.gestaoBibliotecaDataSet.Leitor);
//controls.add();
picPlanta.Image = Properties.Resources.planta_Projecto;
}
private void picPerfil_Click(object sender, EventArgs e)
{
frmRegistar formRegistar = new frmRegistar(lblUsername.Text, null, 0);
formRegistar.ShowDialog();
}
private void picSuges_Click(object sender, EventArgs e)
{
frmSugestoes formSugestoes = new frmSugestoes(null);
formSugestoes.Show();
}
private void tmrUser_Tick(object sender, EventArgs e)
{
// picPerfil.Image = Image.FromFile(imagemPerfilTextBox.Text);
}
private void leitorBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.leitorBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.gestaoBibliotecaDataSet);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.